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:
co-authored by
Claude Opus 4.6
parent
2b75ef6538
commit
5d66dd6bfc
@@ -0,0 +1,65 @@
|
||||
import crypto from 'crypto'
|
||||
import { createClient } from '@supabase/supabase-js'
|
||||
|
||||
const KEY_PREFIX = 'gnubok_sk_'
|
||||
|
||||
/**
|
||||
* Create a Supabase service client that doesn't require cookies.
|
||||
* Used for API key validation (MCP, webhooks) where there's no browser session.
|
||||
*/
|
||||
export function createServiceClientNoCookies() {
|
||||
return createClient(
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL!,
|
||||
process.env.SUPABASE_SERVICE_ROLE_KEY!
|
||||
)
|
||||
}
|
||||
|
||||
export function generateApiKey(): { key: string; hash: string; prefix: string } {
|
||||
const random = crypto.randomBytes(32).toString('base64url')
|
||||
const key = `${KEY_PREFIX}${random}`
|
||||
const hash = hashApiKey(key)
|
||||
const prefix = key.slice(0, KEY_PREFIX.length + 8)
|
||||
return { key, hash, prefix }
|
||||
}
|
||||
|
||||
export function hashApiKey(key: string): string {
|
||||
return crypto.createHash('sha256').update(key).digest('hex')
|
||||
}
|
||||
|
||||
export function extractBearerToken(request: Request): string | null {
|
||||
const authHeader = request.headers.get('authorization')
|
||||
if (!authHeader?.startsWith('Bearer ')) return null
|
||||
return authHeader.slice(7)
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an API key and enforce rate limiting.
|
||||
* Uses the DB RPC for atomic check + increment.
|
||||
* Returns the user_id on success, or an error with HTTP status.
|
||||
*/
|
||||
export async function validateApiKey(
|
||||
key: string
|
||||
): Promise<{ userId: string } | { error: string; status: number }> {
|
||||
if (!key.startsWith(KEY_PREFIX)) {
|
||||
return { error: 'Invalid API key format', status: 401 }
|
||||
}
|
||||
|
||||
const hash = hashApiKey(key)
|
||||
const supabase = createServiceClientNoCookies()
|
||||
|
||||
const { data, error } = await supabase.rpc('validate_and_increment_api_key', {
|
||||
p_key_hash: hash,
|
||||
})
|
||||
|
||||
if (error || !data || data.length === 0) {
|
||||
return { error: 'Invalid API key', status: 401 }
|
||||
}
|
||||
|
||||
const row = data[0]
|
||||
|
||||
if (row.rate_limited) {
|
||||
return { error: 'Rate limit exceeded', status: 429 }
|
||||
}
|
||||
|
||||
return { userId: row.user_id }
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import crypto from 'crypto'
|
||||
|
||||
/**
|
||||
* Stateless OAuth auth codes.
|
||||
* The auth code is an AES-256-GCM encrypted JSON payload containing
|
||||
* the user ID, PKCE code_challenge, and expiry.
|
||||
*
|
||||
* The API key is NOT embedded — it gets created at token exchange
|
||||
* after PKCE verification, preventing orphaned keys.
|
||||
*/
|
||||
|
||||
const ALGORITHM = 'aes-256-gcm'
|
||||
const CODE_TTL_MS = 5 * 60 * 1000 // 5 minutes
|
||||
|
||||
function getEncryptionKey(): Buffer {
|
||||
const secret = process.env.SUPABASE_SERVICE_ROLE_KEY
|
||||
if (!secret) throw new Error('SUPABASE_SERVICE_ROLE_KEY is required')
|
||||
return crypto.createHash('sha256').update(secret).digest()
|
||||
}
|
||||
|
||||
export interface AuthCodePayload {
|
||||
userId: string
|
||||
codeChallenge: string
|
||||
codeChallengeMethod: string
|
||||
redirectUri: string
|
||||
exp: number
|
||||
}
|
||||
|
||||
export function createAuthCode(payload: Omit<AuthCodePayload, 'exp'>): string {
|
||||
const data: AuthCodePayload = {
|
||||
...payload,
|
||||
exp: Date.now() + CODE_TTL_MS,
|
||||
}
|
||||
|
||||
const key = getEncryptionKey()
|
||||
const iv = crypto.randomBytes(12)
|
||||
const cipher = crypto.createCipheriv(ALGORITHM, key, iv)
|
||||
|
||||
const json = JSON.stringify(data)
|
||||
const encrypted = Buffer.concat([cipher.update(json, 'utf8'), cipher.final()])
|
||||
const tag = cipher.getAuthTag()
|
||||
|
||||
const combined = Buffer.concat([iv, tag, encrypted])
|
||||
return combined.toString('base64url')
|
||||
}
|
||||
|
||||
export function decryptAuthCode(code: string): AuthCodePayload | null {
|
||||
try {
|
||||
const key = getEncryptionKey()
|
||||
const combined = Buffer.from(code, 'base64url')
|
||||
|
||||
const iv = combined.subarray(0, 12)
|
||||
const tag = combined.subarray(12, 28)
|
||||
const encrypted = combined.subarray(28)
|
||||
|
||||
const decipher = crypto.createDecipheriv(ALGORITHM, key, iv)
|
||||
decipher.setAuthTag(tag)
|
||||
|
||||
const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()])
|
||||
const payload: AuthCodePayload = JSON.parse(decrypted.toString('utf8'))
|
||||
|
||||
if (Date.now() > payload.exp) return null
|
||||
|
||||
return payload
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify PKCE: SHA256(code_verifier) must equal the stored code_challenge.
|
||||
* Only S256 is supported (plain is insecure and not advertised).
|
||||
*/
|
||||
export function verifyPkce(
|
||||
codeVerifier: string,
|
||||
codeChallenge: string
|
||||
): boolean {
|
||||
const hash = crypto
|
||||
.createHash('sha256')
|
||||
.update(codeVerifier)
|
||||
.digest('base64url')
|
||||
return hash === codeChallenge
|
||||
}
|
||||
|
||||
/**
|
||||
* Hash an auth code for replay tracking.
|
||||
*/
|
||||
export function hashAuthCode(code: string): string {
|
||||
return crypto.createHash('sha256').update(code).digest('hex')
|
||||
}
|
||||
@@ -49,7 +49,7 @@ describe('sectors registry', () => {
|
||||
})
|
||||
|
||||
it('should have 8 total extensions', () => {
|
||||
expect(getAllExtensions().length).toBe(10)
|
||||
expect(getAllExtensions().length).toBe(11)
|
||||
})
|
||||
|
||||
it('should have unique slugs within each sector', () => {
|
||||
@@ -94,7 +94,7 @@ describe('sectors registry', () => {
|
||||
|
||||
it('getExtensionsBySector returns extensions for a sector', () => {
|
||||
const extensions = getExtensionsBySector('general')
|
||||
expect(extensions.length).toBe(10)
|
||||
expect(extensions.length).toBe(11)
|
||||
})
|
||||
|
||||
it('all extensions have required fields', () => {
|
||||
|
||||
@@ -5,4 +5,5 @@ export const ENABLED_EXTENSION_IDS: ReadonlySet<string> = new Set([
|
||||
'email',
|
||||
'arcim-migration',
|
||||
'tic',
|
||||
'mcp-server',
|
||||
])
|
||||
|
||||
@@ -4,10 +4,12 @@ import { enableBankingExtension } from '@/extensions/general/enable-banking'
|
||||
import { emailExtension } from '@/extensions/general/email'
|
||||
import { arcimMigrationExtension } from '@/extensions/general/arcim-migration'
|
||||
import { ticExtension } from '@/extensions/general/tic'
|
||||
import { mcpServerExtension } from '@/extensions/general/mcp-server'
|
||||
|
||||
export const FIRST_PARTY_EXTENSIONS: Extension[] = [
|
||||
enableBankingExtension,
|
||||
emailExtension,
|
||||
arcimMigrationExtension,
|
||||
ticExtension,
|
||||
mcpServerExtension,
|
||||
]
|
||||
|
||||
@@ -58,5 +58,15 @@ export const EXTENSION_DEFINITIONS: Record<string, ExtensionDefinition[]> = {
|
||||
"order": 10
|
||||
}
|
||||
},
|
||||
{
|
||||
"slug": "mcp-server",
|
||||
"name": "MCP-server (API)",
|
||||
"sector": "general",
|
||||
"category": "operations",
|
||||
"icon": "Terminal",
|
||||
"dataPattern": "manual",
|
||||
"description": "Gör bokföring via Claude, Cursor eller annan MCP-klient",
|
||||
"longDescription": "Exponerar gnuboks bokföringsmotor som MCP-verktyg (Model Context Protocol). Koppla din MCP-klient med en API-nyckel och gör bokföring genom konversation: visa okategoriserade transaktioner, bokför dem, skapa fakturor."
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
calculateGrossMargin,
|
||||
calculateCashPosition,
|
||||
calculateRevenueGrowth,
|
||||
calculateExpenseRatio,
|
||||
calculateAvgPaymentDays,
|
||||
} from '../kpi'
|
||||
import type { IncomeStatementReport, TrialBalanceRow } from '@/types'
|
||||
|
||||
function makeIncomeStatement(
|
||||
overrides: Partial<IncomeStatementReport> = {}
|
||||
): IncomeStatementReport {
|
||||
return {
|
||||
revenue_sections: [],
|
||||
total_revenue: 100000,
|
||||
expense_sections: [],
|
||||
total_expenses: 60000,
|
||||
financial_sections: [],
|
||||
total_financial: 0,
|
||||
net_result: 40000,
|
||||
period: { start: '2025-01-01', end: '2025-12-31' },
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function makeTrialBalanceRow(
|
||||
overrides: Partial<TrialBalanceRow> = {}
|
||||
): TrialBalanceRow {
|
||||
return {
|
||||
account_number: '1930',
|
||||
account_name: 'Företagskonto',
|
||||
account_class: 1,
|
||||
opening_debit: 0,
|
||||
opening_credit: 0,
|
||||
period_debit: 0,
|
||||
period_credit: 0,
|
||||
closing_debit: 0,
|
||||
closing_credit: 0,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('calculateGrossMargin', () => {
|
||||
it('returns margin when revenue and COGS exist', () => {
|
||||
const stmt = makeIncomeStatement({
|
||||
total_revenue: 200000,
|
||||
expense_sections: [
|
||||
{
|
||||
title: 'Varor och material',
|
||||
rows: [{ account_number: '4010', account_name: 'Inköp', amount: 80000 }],
|
||||
subtotal: 80000,
|
||||
},
|
||||
{
|
||||
title: 'Lokalkostnader',
|
||||
rows: [{ account_number: '5010', account_name: 'Hyra', amount: 20000 }],
|
||||
subtotal: 20000,
|
||||
},
|
||||
],
|
||||
})
|
||||
// (200000 - 80000) / 200000 * 100 = 60%
|
||||
expect(calculateGrossMargin(stmt)).toBe(60)
|
||||
})
|
||||
|
||||
it('returns null when total_revenue is 0', () => {
|
||||
const stmt = makeIncomeStatement({ total_revenue: 0 })
|
||||
expect(calculateGrossMargin(stmt)).toBeNull()
|
||||
})
|
||||
|
||||
it('returns 100% when no class 4 expenses', () => {
|
||||
const stmt = makeIncomeStatement({
|
||||
total_revenue: 50000,
|
||||
expense_sections: [
|
||||
{
|
||||
title: 'Lokalkostnader',
|
||||
rows: [{ account_number: '5010', account_name: 'Hyra', amount: 10000 }],
|
||||
subtotal: 10000,
|
||||
},
|
||||
],
|
||||
})
|
||||
expect(calculateGrossMargin(stmt)).toBe(100)
|
||||
})
|
||||
})
|
||||
|
||||
describe('calculateCashPosition', () => {
|
||||
it('sums closing balances for 19xx accounts', () => {
|
||||
const rows = [
|
||||
makeTrialBalanceRow({ account_number: '1930', closing_debit: 50000, closing_credit: 0 }),
|
||||
makeTrialBalanceRow({ account_number: '1931', closing_debit: 10000, closing_credit: 0 }),
|
||||
makeTrialBalanceRow({ account_number: '1510', closing_debit: 25000, closing_credit: 0 }),
|
||||
]
|
||||
// Only 1930 + 1931 = 60000
|
||||
expect(calculateCashPosition(rows)).toBe(60000)
|
||||
})
|
||||
|
||||
it('returns 0 for empty rows', () => {
|
||||
expect(calculateCashPosition([])).toBe(0)
|
||||
})
|
||||
|
||||
it('handles credit balances on 19xx accounts', () => {
|
||||
const rows = [
|
||||
makeTrialBalanceRow({ account_number: '1930', closing_debit: 0, closing_credit: 5000 }),
|
||||
]
|
||||
expect(calculateCashPosition(rows)).toBe(-5000)
|
||||
})
|
||||
})
|
||||
|
||||
describe('calculateRevenueGrowth', () => {
|
||||
it('returns positive growth', () => {
|
||||
// (120000 - 100000) / 100000 * 100 = 20%
|
||||
expect(calculateRevenueGrowth(120000, 100000)).toBe(20)
|
||||
})
|
||||
|
||||
it('returns negative growth (decline)', () => {
|
||||
// (80000 - 100000) / 100000 * 100 = -20%
|
||||
expect(calculateRevenueGrowth(80000, 100000)).toBe(-20)
|
||||
})
|
||||
|
||||
it('returns null when previous revenue is null', () => {
|
||||
expect(calculateRevenueGrowth(100000, null)).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null when previous revenue is 0', () => {
|
||||
expect(calculateRevenueGrowth(100000, 0)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('calculateExpenseRatio', () => {
|
||||
it('returns ratio for normal data', () => {
|
||||
const stmt = makeIncomeStatement({ total_revenue: 200000, total_expenses: 120000 })
|
||||
// 120000 / 200000 * 100 = 60%
|
||||
expect(calculateExpenseRatio(stmt)).toBe(60)
|
||||
})
|
||||
|
||||
it('returns null when total_revenue is 0', () => {
|
||||
const stmt = makeIncomeStatement({ total_revenue: 0, total_expenses: 5000 })
|
||||
expect(calculateExpenseRatio(stmt)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('calculateAvgPaymentDays', () => {
|
||||
it('returns average for >= 5 invoices', () => {
|
||||
const invoices = [
|
||||
{ invoice_date: '2025-01-01', paid_at: '2025-01-11' }, // 10 days
|
||||
{ invoice_date: '2025-02-01', paid_at: '2025-02-21' }, // 20 days
|
||||
{ invoice_date: '2025-03-01', paid_at: '2025-03-16' }, // 15 days
|
||||
{ invoice_date: '2025-04-01', paid_at: '2025-04-26' }, // 25 days
|
||||
{ invoice_date: '2025-05-01', paid_at: '2025-05-31' }, // 30 days
|
||||
]
|
||||
// avg = (10+20+15+25+30) / 5 = 20
|
||||
expect(calculateAvgPaymentDays(invoices)).toBe(20)
|
||||
})
|
||||
|
||||
it('returns null for fewer than 5 invoices', () => {
|
||||
const invoices = [
|
||||
{ invoice_date: '2025-01-01', paid_at: '2025-01-11' },
|
||||
{ invoice_date: '2025-02-01', paid_at: '2025-02-21' },
|
||||
]
|
||||
expect(calculateAvgPaymentDays(invoices)).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null for empty array', () => {
|
||||
expect(calculateAvgPaymentDays([])).toBeNull()
|
||||
})
|
||||
|
||||
it('clamps negative days to 0', () => {
|
||||
const invoices = [
|
||||
{ invoice_date: '2025-01-10', paid_at: '2025-01-05' }, // would be -5, clamped to 0
|
||||
{ invoice_date: '2025-02-01', paid_at: '2025-02-11' }, // 10
|
||||
{ invoice_date: '2025-03-01', paid_at: '2025-03-11' }, // 10
|
||||
{ invoice_date: '2025-04-01', paid_at: '2025-04-11' }, // 10
|
||||
{ invoice_date: '2025-05-01', paid_at: '2025-05-11' }, // 10
|
||||
]
|
||||
// avg = (0+10+10+10+10) / 5 = 8
|
||||
expect(calculateAvgPaymentDays(invoices)).toBe(8)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,74 @@
|
||||
import type { IncomeStatementReport, TrialBalanceRow } from '@/types'
|
||||
|
||||
/**
|
||||
* Calculate gross margin from income statement.
|
||||
* Gross margin = (revenue - COGS) / revenue × 100
|
||||
* COGS = class 4 expense sections (Varor och material, etc.)
|
||||
*/
|
||||
export function calculateGrossMargin(incomeStatement: IncomeStatementReport): number | null {
|
||||
const { total_revenue, expense_sections } = incomeStatement
|
||||
if (total_revenue === 0) return null
|
||||
|
||||
// Class 4 expenses = cost of goods sold (account prefixes 40-49)
|
||||
const cogs = expense_sections
|
||||
.filter((s) => s.rows.some((r) => r.account_number.startsWith('4')))
|
||||
.reduce((sum, s) => sum + s.subtotal, 0)
|
||||
|
||||
return Math.round(((total_revenue - cogs) / total_revenue) * 10000) / 100
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate cash position from trial balance rows.
|
||||
* Sums closing balances for accounts matching 19xx (bank + cash accounts).
|
||||
*/
|
||||
export function calculateCashPosition(rows: TrialBalanceRow[]): number {
|
||||
const cashRows = rows.filter((r) => r.account_number.startsWith('19'))
|
||||
const total = cashRows.reduce(
|
||||
(sum, r) => sum + (r.closing_debit - r.closing_credit),
|
||||
0
|
||||
)
|
||||
return Math.round(total * 100) / 100
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate revenue growth between two periods.
|
||||
* Returns percentage or null if no previous period data.
|
||||
*/
|
||||
export function calculateRevenueGrowth(
|
||||
currentRevenue: number,
|
||||
previousRevenue: number | null
|
||||
): number | null {
|
||||
if (previousRevenue === null || previousRevenue === 0) return null
|
||||
return Math.round(((currentRevenue - previousRevenue) / previousRevenue) * 10000) / 100
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate expense ratio from income statement.
|
||||
* Expense ratio = total_expenses / total_revenue × 100
|
||||
*/
|
||||
export function calculateExpenseRatio(incomeStatement: IncomeStatementReport): number | null {
|
||||
const { total_revenue, total_expenses } = incomeStatement
|
||||
if (total_revenue === 0) return null
|
||||
return Math.round((total_expenses / total_revenue) * 10000) / 100
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate average payment days from paid invoices.
|
||||
* Returns null if fewer than 5 invoices with paid_at data.
|
||||
*/
|
||||
export function calculateAvgPaymentDays(
|
||||
paidInvoices: { invoice_date: string; paid_at: string }[]
|
||||
): number | null {
|
||||
if (paidInvoices.length < 5) return null
|
||||
|
||||
const totalDays = paidInvoices.reduce((sum, inv) => {
|
||||
const invoiceDate = new Date(inv.invoice_date)
|
||||
const paidDate = new Date(inv.paid_at)
|
||||
const days = Math.floor(
|
||||
(paidDate.getTime() - invoiceDate.getTime()) / (1000 * 60 * 60 * 24)
|
||||
)
|
||||
return sum + Math.max(0, days)
|
||||
}, 0)
|
||||
|
||||
return Math.round(totalDays / paidInvoices.length)
|
||||
}
|
||||
Reference in New Issue
Block a user