Files
accounted/lib/extensions/__tests__/sectors.test.ts
T
Jakob Wennberg 5d66dd6bfc 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>
2026-03-21 12:57:14 +01:00

113 lines
3.3 KiB
TypeScript

import { resolve, join } from 'path'
import { readdirSync, readFileSync } from 'fs'
/**
* Build EXTENSION_DEFINITIONS from manifest.json files so the test
* is independent of extensions.config.json.
*/
function buildDefinitionsFromManifests(): Record<string, unknown[]> {
const extensionsDir = resolve(__dirname, '../../../extensions')
const result: Record<string, unknown[]> = {}
function walk(dir: string) {
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const fullPath = join(dir, entry.name)
if (entry.isDirectory()) {
walk(fullPath)
} else if (entry.name === 'manifest.json') {
const manifest = JSON.parse(readFileSync(fullPath, 'utf-8'))
const sector: string = manifest.sector
if (!result[sector]) result[sector] = []
result[sector].push({
slug: manifest.id,
sector: manifest.sector,
...manifest.definition,
})
}
}
}
walk(extensionsDir)
return result
}
vi.mock('@/lib/extensions/_generated/sector-definitions', () => ({
EXTENSION_DEFINITIONS: buildDefinitionsFromManifests(),
}))
import {
SECTORS,
getSector,
getExtensionDefinition,
getAllExtensions,
getExtensionsBySector,
} from '../sectors'
describe('sectors registry', () => {
it('should have 1 sector', () => {
expect(SECTORS.length).toBe(1)
})
it('should have 8 total extensions', () => {
expect(getAllExtensions().length).toBe(11)
})
it('should have unique slugs within each sector', () => {
for (const sector of SECTORS) {
const slugs = sector.extensions.map(e => e.slug)
const uniqueSlugs = new Set(slugs)
expect(uniqueSlugs.size).toBe(slugs.length)
}
})
it('should have at least one extension per sector', () => {
for (const sector of SECTORS) {
expect(sector.extensions.length).toBeGreaterThan(0)
}
})
it('getSector returns correct sector', () => {
const sector = getSector('general')
expect(sector).toBeDefined()
expect(sector!.slug).toBe('general')
expect(sector!.name).toBe('Generella verktyg')
})
it('getSector returns undefined for unknown slug', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const sector = getSector('invalid' as any)
expect(sector).toBeUndefined()
})
it('getExtensionDefinition returns correct extension', () => {
const ext = getExtensionDefinition('general', 'ai-chat')
expect(ext).toBeDefined()
expect(ext!.slug).toBe('ai-chat')
expect(ext!.name).toBe('AI-assistent')
expect(ext!.sector).toBe('general')
})
it('getExtensionDefinition returns undefined for unknown extension', () => {
const ext = getExtensionDefinition('general', 'nonexistent')
expect(ext).toBeUndefined()
})
it('getExtensionsBySector returns extensions for a sector', () => {
const extensions = getExtensionsBySector('general')
expect(extensions.length).toBe(11)
})
it('all extensions have required fields', () => {
for (const ext of getAllExtensions()) {
expect(ext.slug).toBeTruthy()
expect(ext.name).toBeTruthy()
expect(ext.sector).toBeTruthy()
expect(ext.category).toBeTruthy()
expect(ext.description).toBeTruthy()
expect(ext.longDescription).toBeTruthy()
expect(ext.icon).toBeTruthy()
expect(ext.dataPattern).toBeTruthy()
}
})
})