'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 { Badge } from '@/components/ui/badge' import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from '@/components/ui/dialog' import { Checkbox } from '@/components/ui/checkbox' import { DestructiveConfirmDialog, useDestructiveConfirm } from '@/components/ui/destructive-confirm-dialog' import { useToast } from '@/components/ui/use-toast' import { Loader2, Plus, Copy, Check, Trash2, Key, ChevronDown } from 'lucide-react' const SCOPE_GROUPS = [ { domain: 'transactions', label: 'Transaktioner', read: 'transactions:read' as const, readLabel: 'Läs — lista transaktioner, mallförslag, kategoriförslag', readTools: 3, write: 'transactions:write' as const, writeLabel: 'Skriv — kategorisera, kvittomatchning, koppling mot faktura', writeTools: 3, }, { domain: 'customers', label: 'Kunder', read: 'customers:read' as const, readLabel: 'Läs — lista kunder', readTools: 1, write: 'customers:write' as const, writeLabel: 'Skriv — skapa kunder', writeTools: 1, }, { domain: 'invoices', label: 'Fakturor', read: 'invoices:read' as const, readLabel: 'Läs — lista fakturor', readTools: 1, write: 'invoices:write' as const, writeLabel: 'Skriv — skapa, skicka, markera betald/skickad', writeTools: 4, }, { domain: 'suppliers', label: 'Leverantörer', read: 'suppliers:read' as const, readLabel: 'Läs — lista leverantörer och leverantörsfakturor', readTools: 2, write: null, writeLabel: null, writeTools: 0, }, { domain: 'reports', label: 'Rapporter', read: 'reports:read' as const, readLabel: 'Läs — kontoplan, huvudbok, balansräkning, resultaträkning, moms, KPI, kundreskontra, leverantörsreskontra, räkenskapsperioder, bankavstämning', readTools: 11, write: null, writeLabel: null, writeTools: 0, }, ] as const type Scope = | 'transactions:read' | 'transactions:write' | 'customers:read' | 'customers:write' | 'invoices:read' | 'invoices:write' | 'suppliers:read' | 'reports:read' const ALL_SCOPES: Scope[] = SCOPE_GROUPS.flatMap((g) => g.write ? [g.read, g.write] : [g.read] ) /** Map scope key → display label for badges */ const SCOPE_LABELS: Record = { 'transactions:read': 'Transaktioner (läs)', 'transactions:write': 'Transaktioner (skriv)', 'customers:read': 'Kunder (läs)', 'customers:write': 'Kunder (skriv)', 'invoices:read': 'Fakturor (läs)', 'invoices:write': 'Fakturor (skriv)', 'suppliers:read': 'Leverantörer (läs)', 'reports:read': 'Rapporter (läs)', } 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 } function CopyBlock({ text }: { text: string }) { const [copied, setCopied] = useState(false) async function handleCopy() { try { await navigator.clipboard.writeText(text) setCopied(true) setTimeout(() => setCopied(false), 2000) } catch { // clipboard unavailable (insecure context) — silently ignore } } return (
        {text}
      
) } export function ApiKeysPanel() { const { toast } = useToast() const { dialogProps: revokeDialogProps, confirm: confirmRevoke } = useDestructiveConfirm() const [keys, setKeys] = useState([]) const [isLoading, setIsLoading] = useState(true) const [isCreating, setIsCreating] = useState(false) const [showCreateDialog, setShowCreateDialog] = useState(false) const [showKeyDialog, setShowKeyDialog] = useState(false) const [showApiKeyMethods, setShowApiKeyMethods] = useState(false) const [newKeyName, setNewKeyName] = useState('') const [newKeyScopes, setNewKeyScopes] = useState>(new Set(ALL_SCOPES)) const [newKeyValue, setNewKeyValue] = useState('') const [copied, setCopied] = useState(false) 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', scopes: Array.from(newKeyScopes) }), }) 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('') setNewKeyScopes(new Set(ALL_SCOPES)) fetchKeys() } catch { toast({ title: 'Fel', description: 'Kunde inte skapa nyckel', variant: 'destructive' }) } finally { setIsCreating(false) } } async function handleRevoke(id: string, name: string) { const ok = await confirmRevoke({ title: 'Återkalla API-nyckel', description: `"${name}" återkallas permanent. Alla klienter som använder nyckeln slutar fungera omedelbart.`, confirmLabel: 'Återkalla', }) if (!ok) return 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' }) } } 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 (
API-nycklar Hantera nycklar för MCP-klienter (Claude, Cursor) och andra integrationer.
{isLoading ? (
) : keys.length === 0 ? (

Inga API-nycklar ännu.

Skapa en nyckel för att koppla din MCP-klient.

) : (
{keys.map((key) => { const scopeCount = key.scopes?.length ?? 0 return (

{key.name}

{scopeCount === ALL_SCOPES.length ? 'Alla behörigheter' : scopeCount === 0 ? 'Inga behörigheter' : `${scopeCount} behörigheter`}
{key.key_prefix}... Skapad {formatDate(key.created_at)} {key.last_used_at ? `Använd ${formatDate(key.last_used_at)}` : 'Aldrig använd'}
) })}
)}
Anslut MCP-klient

Claude.ai

Rekommenderat

Gå till Settings → Integrations → Add Integration och klistra in MCP-serverns URL. Du loggas in via ditt gnubok-konto — ingen API-nyckel behövs.

Claude Code / Cursor

Kör i terminalen — loggar in via webbläsaren:

{showApiKeyMethods && (

Claude Desktop

Lägg till i claude_desktop_config.json (Inställningar → Developer):

Claude Code / Cursor

Kör i terminalen med en API-nyckel:

)}
{/* Create key dialog */} Skapa API-nyckel Ge nyckeln ett namn så du vet vad den används till.
setNewKeyName(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && handleCreate()} />

Välj vad nyckeln ska ha åtkomst till.

{SCOPE_GROUPS.map((group) => (

{group.label}

{group.write && ( )}
))}
{/* Show key once dialog */} { if (!open) { setNewKeyValue('') setCopied(false) } setShowKeyDialog(open) }}> Din nya API-nyckel Kopiera nyckeln nu. Den visas bara en gång.
{newKeyValue}
) }