* 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>
129 lines
3.8 KiB
TypeScript
129 lines
3.8 KiB
TypeScript
import { NextResponse } from 'next/server'
|
|
import { decryptAuthCode, verifyPkce, hashAuthCode } from '@/lib/auth/oauth-codes'
|
|
import { generateApiKey } from '@/lib/auth/api-keys'
|
|
import { createServiceClientNoCookies } from '@/lib/auth/api-keys'
|
|
|
|
/**
|
|
* OAuth 2.0 Token Endpoint.
|
|
*
|
|
* Exchanges an authorization code for an API key (access token).
|
|
* 1. Decrypts the stateless auth code
|
|
* 2. Checks for replay (single-use enforcement per OAuth 2.1 §4.1.2)
|
|
* 3. Verifies PKCE (S256 only)
|
|
* 4. Creates the API key (deferred from /authorize to prevent orphaned keys)
|
|
* 5. Returns the key as a bearer token
|
|
*/
|
|
export async function POST(request: Request) {
|
|
let params: URLSearchParams
|
|
|
|
const contentType = request.headers.get('content-type') || ''
|
|
if (contentType.includes('application/x-www-form-urlencoded')) {
|
|
const text = await request.text()
|
|
params = new URLSearchParams(text)
|
|
} else if (contentType.includes('application/json')) {
|
|
const json = await request.json()
|
|
params = new URLSearchParams(json as Record<string, string>)
|
|
} else {
|
|
return NextResponse.json({ error: 'unsupported_content_type' }, { status: 400 })
|
|
}
|
|
|
|
const grantType = params.get('grant_type')
|
|
const code = params.get('code')
|
|
const codeVerifier = params.get('code_verifier')
|
|
const redirectUri = params.get('redirect_uri')
|
|
|
|
if (grantType !== 'authorization_code') {
|
|
return NextResponse.json(
|
|
{ error: 'unsupported_grant_type', error_description: 'Only authorization_code is supported' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
if (!code) {
|
|
return NextResponse.json(
|
|
{ error: 'invalid_request', error_description: 'Missing code parameter' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
// Decrypt the auth code
|
|
const payload = decryptAuthCode(code)
|
|
if (!payload) {
|
|
return NextResponse.json(
|
|
{ error: 'invalid_grant', error_description: 'Invalid or expired authorization code' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
// Verify redirect_uri matches
|
|
if (redirectUri && redirectUri !== payload.redirectUri) {
|
|
return NextResponse.json(
|
|
{ error: 'invalid_grant', error_description: 'redirect_uri mismatch' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
// Verify PKCE (S256 only)
|
|
if (!codeVerifier) {
|
|
return NextResponse.json(
|
|
{ error: 'invalid_request', error_description: 'code_verifier is required' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
if (!verifyPkce(codeVerifier, payload.codeChallenge)) {
|
|
return NextResponse.json(
|
|
{ error: 'invalid_grant', error_description: 'PKCE verification failed' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
// Single-use enforcement: check and mark code as used (atomically via unique constraint)
|
|
const codeHash = hashAuthCode(code)
|
|
const supabase = createServiceClientNoCookies()
|
|
|
|
const { error: replayError } = await supabase
|
|
.from('oauth_used_codes')
|
|
.insert({ code_hash: codeHash })
|
|
|
|
if (replayError) {
|
|
// Unique constraint violation = code already used
|
|
return NextResponse.json(
|
|
{ error: 'invalid_grant', error_description: 'Authorization code already used' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
// Clean up expired codes (non-blocking, best-effort)
|
|
supabase
|
|
.from('oauth_used_codes')
|
|
.delete()
|
|
.lt('created_at', new Date(Date.now() - 10 * 60 * 1000).toISOString())
|
|
.then(() => {})
|
|
|
|
// Create the API key now (after PKCE verification — prevents orphaned keys)
|
|
const { key, hash, prefix } = generateApiKey()
|
|
|
|
const { error: insertError } = await supabase
|
|
.from('api_keys')
|
|
.insert({
|
|
user_id: payload.userId,
|
|
key_hash: hash,
|
|
key_prefix: prefix,
|
|
name: 'MCP-klient (OAuth)',
|
|
})
|
|
|
|
if (insertError) {
|
|
return NextResponse.json(
|
|
{ error: 'server_error', error_description: 'Failed to create API key' },
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
|
|
return NextResponse.json({
|
|
access_token: key,
|
|
token_type: 'Bearer',
|
|
scope: 'mcp',
|
|
})
|
|
}
|