Fix/mcp fixes and bugs (#518)

* feat(voucher): add create voucher and correct entry previews; update commit methods

* feat: add support for pending operations in API key scopes and OAuth client management

- Introduced new API key scopes for reading and approving pending operations.
- Updated the scope groups to include pending operations.
- Added new tools for listing and managing pending operations.
- Implemented OAuth client registration and revocation endpoints.
- Created a UI panel for managing OAuth clients, including registration and revocation.
- Added tests for pending operations tools and OAuth allowlist functionality.
- Implemented a database migration for OAuth client registrations with appropriate policies and constraints.

* feat: Implement OAuth client registration rate limiting and enhance security measures

- Added IP-based rate limiting to the OAuth client registration endpoint to prevent enumeration attacks.
- Introduced a service-role client for allowlist lookups, ensuring trust boundaries are maintained.
- Updated error responses to be uniform across different types of redirect URI validation failures.
- Enhanced tests to reflect changes in OAuth scope handling, ensuring fallback to read-only scopes when no scopes are provided.
- Improved handling of high-risk pending operations, requiring explicit confirmation for approvals.
- Added audit logging for OAuth client revocations and pending operation approvals/rejections to maintain a security audit trail.
- Refactored API key scope management to include default read-only scopes for OAuth-issued keys and added segregation-of-duties checks.
This commit is contained in:
Mattsson
2026-05-18 19:02:42 +02:00
committed by GitHub
parent d27c3dd3dc
commit 16164ea14c
26 changed files with 2363 additions and 154 deletions
+142 -23
View File
@@ -1,8 +1,11 @@
import crypto from 'crypto'
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { createAuthCode } from '@/lib/auth/oauth-codes'
import { requireCompanyId } from '@/lib/company/context'
import { getBranding } from '@/lib/branding/service'
import { isAllowedRedirectUri } from '@/lib/auth/oauth-allowlist'
import { API_KEY_SCOPES, type ApiKeyScope } from '@/lib/auth/api-keys'
/**
* OAuth 2.0 Authorization Endpoint.
@@ -14,16 +17,76 @@ import { getBranding } from '@/lib/branding/service'
* after PKCE verification, preventing orphaned keys on abandoned flows.
*/
// Allowed redirect URI patterns — prevent open redirect attacks
const ALLOWED_REDIRECT_PATTERNS = [
/^https:\/\/claude\.ai\/api\//, // Claude.ai API callbacks (connector IDs vary in path)
/^https:\/\/claude\.com\/api\//, // Claude.com API callbacks
/^http:\/\/localhost(:\d+)?\//, // Local development
/^http:\/\/127\.0\.0\.1(:\d+)?\//, // Local development
]
type ScopeParseResult =
| { kind: 'ok'; scopes: ApiKeyScope[] | undefined }
| { kind: 'invalid_scope'; description: string }
function isAllowedRedirectUri(uri: string): boolean {
return ALLOWED_REDIRECT_PATTERNS.some((pattern) => pattern.test(uri))
/**
* Parse the OAuth `scope` query param (RFC 6749 §3.3 — space-delimited list)
* into the subset of API_KEY_SCOPES that the user actually granted.
*
* Returns:
* - { ok, scopes: undefined } when no scope param was supplied — the token
* endpoint will fall back to DEFAULT_OAUTH_SCOPES (read-only, GDPR
* Art.25(2) data-protection-by-default).
* - { ok, scopes: [...] } when at least one valid scope was requested.
* - { invalid_scope } when a scope param was supplied but every value was
* unknown — refusing the request is safer than silently widening the
* grant to ALL_SCOPES (V10.2.6).
*
* The bare `mcp` marker is treated as "no granular scopes" and accepted for
* backwards compatibility with Claude's connector — it falls through to
* `undefined` so the default-OAuth fallback applies.
*/
function parseRequestedScopes(scopeParam: string | null): ScopeParseResult {
if (!scopeParam) return { kind: 'ok', scopes: undefined }
const requested = scopeParam.split(/\s+/).filter(Boolean)
if (requested.length === 0) return { kind: 'ok', scopes: undefined }
// The coarse-grained `mcp` marker is treated as "no granular request" so
// we can keep Claude's existing flow working unchanged.
const onlyMcp = requested.length === 1 && requested[0] === 'mcp'
if (onlyMcp) return { kind: 'ok', scopes: undefined }
const valid = requested.filter((s): s is ApiKeyScope => s in API_KEY_SCOPES)
if (valid.length === 0) {
return {
kind: 'invalid_scope',
description: 'none of the requested scopes are recognised',
}
}
return { kind: 'ok', scopes: valid }
}
/**
* Sign the scope payload so a tampered POST cannot widen the grant
* displayed at GET. The HMAC binds the originally requested scope param to
* the consent page that the user actually saw (V10.3.1).
*
* Derived from SUPABASE_SERVICE_ROLE_KEY — same root secret the auth-code
* AEAD uses, so deploying the OAuth surface doesn't require a separate
* signing key. Missing env vars cause /authorize to fail closed.
*/
function getScopeSigningKey(): Buffer {
const secret = process.env.SUPABASE_SERVICE_ROLE_KEY
if (!secret) throw new Error('SUPABASE_SERVICE_ROLE_KEY is required for OAuth scope binding')
return crypto.createHash('sha256').update(`oauth-scope:${secret}`).digest()
}
function signScopeBinding(scopeParam: string): string {
return crypto.createHmac('sha256', getScopeSigningKey()).update(scopeParam).digest('base64url')
}
function verifyScopeBinding(scopeParam: string, signature: string): boolean {
if (typeof signature !== 'string' || signature.length === 0) return false
const expected = signScopeBinding(scopeParam)
const expectedBuf = Buffer.from(expected, 'base64url')
let presentedBuf: Buffer
try {
presentedBuf = Buffer.from(signature, 'base64url')
} catch {
return false
}
if (expectedBuf.length !== presentedBuf.length) return false
return crypto.timingSafeEqual(expectedBuf, presentedBuf)
}
function buildLoginRedirect(request: Request): Response {
@@ -48,10 +111,12 @@ function errorRedirect(redirectUri: string, state: string | null, error: string,
export async function GET(request: Request) {
const url = new URL(request.url)
const redirectUri = url.searchParams.get('redirect_uri')
const state = url.searchParams.get('state')
const codeChallenge = url.searchParams.get('code_challenge')
// state and code_challenge are carried through to the POST handler via
// the form action's url.search, so we don't read them here — they're only
// validated on POST.
const codeChallengeMethod = url.searchParams.get('code_challenge_method') || 'S256'
const responseType = url.searchParams.get('response_type')
const scopeParam = url.searchParams.get('scope')
if (responseType !== 'code') {
return NextResponse.json(
@@ -67,17 +132,19 @@ export async function GET(request: Request) {
)
}
// Validate redirect_uri against allowlist (prevents open redirect)
if (!isAllowedRedirectUri(redirectUri)) {
if (codeChallengeMethod !== 'S256') {
return NextResponse.json(
{ error: 'invalid_request', error_description: 'redirect_uri is not allowed' },
{ error: 'invalid_request', error_description: 'Only S256 code_challenge_method is supported' },
{ status: 400 }
)
}
if (codeChallengeMethod !== 'S256') {
// Parse the requested scopes up front so the consent display reflects the
// exact grant. Reject early if the client sent only unknown scopes (V10.2.6).
const parsed = parseRequestedScopes(scopeParam)
if (parsed.kind === 'invalid_scope') {
return NextResponse.json(
{ error: 'invalid_request', error_description: 'Only S256 code_challenge_method is supported' },
{ error: 'invalid_scope', error_description: parsed.description },
{ status: 400 }
)
}
@@ -90,6 +157,15 @@ export async function GET(request: Request) {
return buildLoginRedirect(request)
}
// Validate redirect_uri against allowlist (prevents open redirect). Passing
// the authenticated client makes the trust boundary explicit (SOC 2 CC6.1).
if (!(await isAllowedRedirectUri(redirectUri, supabase))) {
return NextResponse.json(
{ error: 'invalid_request', error_description: 'redirect_uri is not allowed' },
{ status: 400 }
)
}
const companyId = await requireCompanyId(supabase, user.id)
// Get company name for the consent page
@@ -103,6 +179,12 @@ export async function GET(request: Request) {
const appNameLower = escapeHtml(getBranding().appName.toLowerCase())
// Bind the requested scope to the consent display. The HMAC signature is
// verified on POST so a tampered form submission cannot widen the grant
// beyond what the user actually saw (V10.3.1).
const scopeBindingValue = scopeParam ?? ''
const scopeBindingSignature = signScopeBinding(scopeBindingValue)
// Render consent page
const html = `<!DOCTYPE html>
<html lang="sv">
@@ -142,10 +224,14 @@ export async function GET(request: Request) {
<div class="actions">
<form method="POST" action="${url.pathname}${url.search}" style="flex:1;display:flex;">
<input type="hidden" name="consent" value="deny">
<input type="hidden" name="scope_binding" value="${escapeHtml(scopeBindingValue)}">
<input type="hidden" name="scope_binding_sig" value="${escapeHtml(scopeBindingSignature)}">
<button type="submit" class="deny" style="width:100%;">Neka</button>
</form>
<form method="POST" action="${url.pathname}${url.search}" style="flex:1;display:flex;">
<input type="hidden" name="consent" value="allow">
<input type="hidden" name="scope_binding" value="${escapeHtml(scopeBindingValue)}">
<input type="hidden" name="scope_binding_sig" value="${escapeHtml(scopeBindingSignature)}">
<button type="submit" class="allow" style="width:100%;">Tillåt</button>
</form>
</div>
@@ -166,18 +252,12 @@ export async function POST(request: Request) {
const redirectUri = url.searchParams.get('redirect_uri')
const state = url.searchParams.get('state')
const codeChallenge = url.searchParams.get('code_challenge') || ''
const querystringScopeParam = url.searchParams.get('scope')
if (!redirectUri) {
return NextResponse.json({ error: 'invalid_request' }, { status: 400 })
}
if (!isAllowedRedirectUri(redirectUri)) {
return NextResponse.json(
{ error: 'invalid_request', error_description: 'redirect_uri is not allowed' },
{ status: 400 }
)
}
// Check auth
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
@@ -186,6 +266,15 @@ export async function POST(request: Request) {
return buildLoginRedirect(request)
}
// Pass the authenticated client so the lookup is bound to the same session
// that the consent display ran under (SOC 2 CC6.1).
if (!(await isAllowedRedirectUri(redirectUri, supabase))) {
return NextResponse.json(
{ error: 'invalid_request', error_description: 'redirect_uri is not allowed' },
{ status: 400 }
)
}
await requireCompanyId(supabase, user.id)
// Parse form body
@@ -196,11 +285,41 @@ export async function POST(request: Request) {
return errorRedirect(redirectUri, state, 'access_denied', 'User denied the request')
}
// Verify the scope binding signed at consent display matches what was
// submitted with the form. This prevents a tampered POST from widening the
// grant beyond what the user actually saw (V10.3.1).
const presentedScopeBinding = formData.get('scope_binding')
const presentedScopeBindingSig = formData.get('scope_binding_sig')
const presentedScopeStr = typeof presentedScopeBinding === 'string' ? presentedScopeBinding : ''
const presentedSigStr = typeof presentedScopeBindingSig === 'string' ? presentedScopeBindingSig : ''
const expectedScopeStr = querystringScopeParam ?? ''
if (
presentedScopeStr !== expectedScopeStr ||
!verifyScopeBinding(presentedScopeStr, presentedSigStr)
) {
return errorRedirect(
redirectUri,
state,
'invalid_request',
'Scope binding mismatch — consent token is invalid or has been tampered with'
)
}
// Parse the bound scope rather than re-reading the querystring at POST time
// so the auth code always reflects the consent the user gave. parseRequestedScopes
// already rejects requests where every scope is unknown (V10.2.6).
const parsed = parseRequestedScopes(querystringScopeParam)
if (parsed.kind === 'invalid_scope') {
return errorRedirect(redirectUri, state, 'invalid_scope', parsed.description)
}
const requestedScopes = parsed.scopes
// Create auth code with userId (NO API key — that's created at /token after PKCE)
const code = createAuthCode({
userId: user.id,
codeChallenge,
redirectUri,
...(requestedScopes ? { scopes: requestedScopes } : {}),
})
// Redirect to callback with the code
+57 -17
View File
@@ -1,24 +1,50 @@
import { NextResponse } from 'next/server'
import crypto from 'crypto'
// Allowed redirect URI patterns (must match CLAUDE.md allowlist)
const ALLOWED_REDIRECT_PATTERNS = [
/^https:\/\/claude\.ai\/api\//,
/^https:\/\/claude\.com\/api\//,
/^http:\/\/localhost(:\d+)?(\/|$)/,
/^http:\/\/127\.0\.0\.1(:\d+)?(\/|$)/,
]
function isRedirectUriAllowed(uri: string): boolean {
return ALLOWED_REDIRECT_PATTERNS.some(pattern => pattern.test(uri))
}
import { isAllowedRedirectUri } from '@/lib/auth/oauth-allowlist'
import { createServiceClientNoCookies } from '@/lib/auth/api-keys'
import { checkRateLimit } from '@/lib/auth/rate-limit-http'
import { truncateIp } from '@/lib/api/v1/with-api-v1'
/**
* RFC 7591 — Dynamic Client Registration.
* Claude Desktop registers itself as an OAuth client before starting the auth flow.
* Validates redirect_uris against the allowlist before accepting registration.
*
* Claude Desktop and self-hosted MCP clients register themselves before
* starting the auth flow. The redirect URIs they declare are validated
* against built-in patterns (Claude/localhost) and the user-managed
* oauth_client_registrations table (self-hosted custom apps).
*
* Security model:
* - Anonymous by design (RFC 7591 §3 allows it); the endpoint does NOT
* write to oauth_client_registrations — only owner/admin users can
* insert via /api/settings/oauth-clients. This endpoint just echoes
* a client_id back to callers whose redirect_uris are already on the
* allowlist.
* - Per-/24 sliding-window rate-limit prevents the endpoint being used
* as a high-rate oracle for enumerating registered URIs.
* - Error responses are uniform across "built-in", "DB-registered", and
* "disallowed" so an attacker cannot distinguish between them.
*/
const REGISTER_RATE_LIMIT = {
// 10 attempts per minute per /24 — enough headroom for a developer
// iterating on a custom MCP client, low enough to make enumeration
// attacks impractical.
maxRequests: 10,
windowMs: 60 * 1000,
}
export async function POST(request: Request) {
// ── IP-based rate limit ─────────────────────────────────────
const fwd = request.headers.get('x-forwarded-for')
const rawIp = fwd ? fwd.split(',')[0]?.trim() : request.headers.get('x-real-ip') ?? undefined
const ipIdentifier = truncateIp(rawIp || undefined) ?? 'unknown'
const rl = await checkRateLimit({
prefix: 'mcp-oauth:register',
identifier: ipIdentifier,
...REGISTER_RATE_LIMIT,
})
if (!rl.ok) return rl.response!
let body: Record<string, unknown>
try {
body = await request.json()
@@ -26,12 +52,26 @@ export async function POST(request: Request) {
return NextResponse.json({ error: 'invalid_request' }, { status: 400 })
}
// Validate redirect_uris against allowlist
// Service-role client used for the allowlist lookup. Building it once
// keeps the per-URI loop from re-instantiating the client and surfaces
// the trust boundary at the callsite (SOC 2 CC6.1).
let allowlistClient: ReturnType<typeof createServiceClientNoCookies> | undefined
try {
allowlistClient = createServiceClientNoCookies()
} catch {
// Env vars missing — built-in patterns still resolve, DB-backed
// registrations will all return false (fail closed).
allowlistClient = undefined
}
const redirectUris = Array.isArray(body.redirect_uris) ? body.redirect_uris : []
for (const uri of redirectUris) {
if (typeof uri !== 'string' || !isRedirectUriAllowed(uri)) {
if (typeof uri !== 'string' || !(await isAllowedRedirectUri(uri, allowlistClient))) {
// Single error shape regardless of whether the URI is malformed,
// unknown, or revoked — prevents the endpoint being used as an
// enumeration oracle for the user-managed allowlist (CC6.6).
return NextResponse.json(
{ error: 'invalid_redirect_uri', error_description: `Redirect URI not allowed: ${uri}` },
{ error: 'invalid_redirect_uri', error_description: 'Redirect URI not allowed' },
{ status: 400 }
)
}
@@ -267,4 +267,162 @@ describe('POST /api/mcp-oauth/token', () => {
expect(body.error_description).toContain('already used')
})
})
describe('scope plumbing', () => {
it('falls back to read-only DEFAULT_OAUTH_SCOPES when the auth code carries no scopes', async () => {
vi.mocked(decryptAuthCode).mockReturnValue({
userId: 'user-1',
codeChallenge: 'challenge',
redirectUri: 'https://claude.ai/api/cb',
exp: Date.now() + 60_000,
})
vi.mocked(verifyPkce).mockReturnValue(true)
const { supabase, enqueueMany } = createQueuedMockSupabase()
mocks.supabaseFactory.mockReturnValue(supabase)
enqueueMany([
{ data: null, error: null },
{ data: null, error: null },
{ data: null, error: null },
])
const res = await POST(
formRequest({
grant_type: 'authorization_code',
code: 'ciphertext',
code_verifier: 'verifier',
redirect_uri: 'https://claude.ai/api/cb',
})
)
expect(res.status).toBe(200)
const body = await res.json()
// DEFAULT_OAUTH_SCOPES is read-only by design (GDPR Art. 25(2) —
// destructive scopes must be requested explicitly).
const granted = body.scope.split(' ')
expect(granted).toContain('transactions:read')
expect(granted).toContain('reports:read')
expect(granted).not.toContain('bookkeeping:write')
expect(granted).not.toContain('pending_operations:approve')
expect(granted).not.toContain('transactions:write')
})
it('honours scopes from the auth code when present', async () => {
vi.mocked(decryptAuthCode).mockReturnValue({
userId: 'user-1',
codeChallenge: 'challenge',
redirectUri: 'https://claude.ai/api/cb',
scopes: ['transactions:read', 'invoices:read'],
exp: Date.now() + 60_000,
})
vi.mocked(verifyPkce).mockReturnValue(true)
const { supabase, enqueueMany } = createQueuedMockSupabase()
mocks.supabaseFactory.mockReturnValue(supabase)
enqueueMany([
{ data: null, error: null },
{ data: null, error: null },
{ data: null, error: null },
])
const res = await POST(
formRequest({
grant_type: 'authorization_code',
code: 'ciphertext',
code_verifier: 'verifier',
redirect_uri: 'https://claude.ai/api/cb',
})
)
expect(res.status).toBe(200)
const body = await res.json()
expect(body.scope).toBe('transactions:read invoices:read')
})
it('rejects a code whose embedded scopes are all unknown', async () => {
// V9.2.1 defense-in-depth: even though /authorize already filters
// unknown scopes, the token endpoint must not silently mint a
// key with empty scopes — the auth code payload boundary is
// treated as hostile.
vi.mocked(decryptAuthCode).mockReturnValue({
userId: 'user-1',
codeChallenge: 'challenge',
redirectUri: 'https://claude.ai/api/cb',
scopes: ['unknown:scope', 'definitely:not:real'] as unknown as string[],
exp: Date.now() + 60_000,
})
vi.mocked(verifyPkce).mockReturnValue(true)
const { supabase, enqueueMany } = createQueuedMockSupabase()
mocks.supabaseFactory.mockReturnValue(supabase)
enqueueMany([
{ data: null, error: null }, // insert into oauth_used_codes
{ data: null, error: null }, // delete expired codes
])
const res = await POST(
formRequest({
grant_type: 'authorization_code',
code: 'ciphertext',
code_verifier: 'verifier',
redirect_uri: 'https://claude.ai/api/cb',
})
)
expect(res.status).toBe(400)
const body = await res.json()
expect(body.error).toBe('invalid_grant')
})
})
describe('refresh_token scope response', () => {
it('returns the granular scopes the api_key was minted with', async () => {
// Greptile P1 — refresh response previously hardcoded scope:'mcp',
// causing OAuth 2.1 clients to think they had lost their grant.
const { supabase, enqueueMany } = createQueuedMockSupabase()
mocks.supabaseFactory.mockReturnValue(supabase)
enqueueMany([
{
data: {
id: 'key-1',
revoked_at: null,
scopes: ['transactions:read', 'invoices:read', 'invoices:write'],
},
error: null,
}, // SELECT
{ data: [{ id: 'key-1' }], error: null }, // UPDATE
])
const res = await POST(
formRequest({
grant_type: 'refresh_token',
refresh_token: 'gnubok_rt_anything',
})
)
expect(res.status).toBe(200)
const body = await res.json()
expect(body.scope.split(' ').sort()).toEqual(
['transactions:read', 'invoices:read', 'invoices:write'].sort()
)
})
it('falls back to DEFAULT_OAUTH_SCOPES for legacy keys with null scopes', async () => {
const { supabase, enqueueMany } = createQueuedMockSupabase()
mocks.supabaseFactory.mockReturnValue(supabase)
enqueueMany([
{ data: { id: 'key-1', revoked_at: null, scopes: null }, error: null },
{ data: [{ id: 'key-1' }], error: null },
])
const res = await POST(
formRequest({
grant_type: 'refresh_token',
refresh_token: 'gnubok_rt_anything',
})
)
expect(res.status).toBe(200)
const body = await res.json()
const granted = body.scope.split(' ')
expect(granted).toContain('transactions:read')
expect(granted).not.toContain('bookkeeping:write')
expect(granted).not.toContain('pending_operations:approve')
})
})
})
+37 -6
View File
@@ -5,7 +5,9 @@ import {
generateRefreshToken,
hashRefreshToken,
createServiceClientNoCookies,
ALL_SCOPES,
validateScopes,
DEFAULT_OAUTH_SCOPES,
type ApiKeyScope,
} from '@/lib/auth/api-keys'
import { requireCompanyId } from '@/lib/company/context'
@@ -121,6 +123,27 @@ async function handleAuthorizationCodeGrant(params: URLSearchParams) {
const { key, hash, prefix } = generateApiKey()
const refresh = generateRefreshToken()
// Use the scopes the user consented to during /authorize. Re-validate
// every value against API_KEY_SCOPES even though /authorize already did
// — the auth code is AEAD-encrypted but we treat the boundary as
// hostile by default (V9.2.1, defense-in-depth).
let grantedScopes: ApiKeyScope[]
if (payload.scopes && Array.isArray(payload.scopes) && payload.scopes.length > 0) {
const revalidated = validateScopes(payload.scopes)
if (!revalidated) {
return NextResponse.json(
{ error: 'invalid_grant', error_description: 'Authorization code carried no valid scopes' },
{ status: 400 }
)
}
grantedScopes = revalidated
} else {
// Code minted with no scope (Claude's existing flow). Fall back to the
// read-only OAuth defaults — destructive scopes must be requested
// explicitly (GDPR Art. 25(2)).
grantedScopes = DEFAULT_OAUTH_SCOPES
}
const { error: insertError } = await supabase
.from('api_keys')
.insert({
@@ -129,7 +152,7 @@ async function handleAuthorizationCodeGrant(params: URLSearchParams) {
key_hash: hash,
key_prefix: prefix,
name: 'MCP-klient (OAuth)',
scopes: ALL_SCOPES,
scopes: grantedScopes,
refresh_token_hash: refresh.hash,
})
@@ -145,7 +168,7 @@ async function handleAuthorizationCodeGrant(params: URLSearchParams) {
token_type: 'Bearer',
expires_in: ACCESS_TOKEN_TTL_SECONDS,
refresh_token: refresh.token,
scope: 'mcp',
scope: grantedScopes.join(' '),
})
}
@@ -162,10 +185,13 @@ async function handleRefreshTokenGrant(params: URLSearchParams) {
const presentedHash = hashRefreshToken(refreshToken)
// Look up the api_key row by refresh_token_hash. The hash is unique among
// non-null values, so there's at most one match.
// non-null values, so there's at most one match. We pull `scopes` so the
// rotated token response advertises the same granular grant the key
// already carries (otherwise OAuth 2.1 clients would re-authorize on
// every refresh).
const { data: row, error: lookupError } = await supabase
.from('api_keys')
.select('id, revoked_at')
.select('id, revoked_at, scopes')
.eq('refresh_token_hash', presentedHash)
.maybeSingle()
@@ -223,11 +249,16 @@ async function handleRefreshTokenGrant(params: URLSearchParams) {
)
}
// Return the granular scopes the key was originally minted with. Falling
// back to the read-only OAuth defaults preserves the pre-scope-plumbing
// behaviour for legacy keys whose scopes column is null.
const persistedScopes = validateScopes(row.scopes) ?? DEFAULT_OAUTH_SCOPES
return NextResponse.json({
access_token: newKey,
token_type: 'Bearer',
expires_in: ACCESS_TOKEN_TTL_SECONDS,
refresh_token: rotated.token,
scope: 'mcp',
scope: persistedScopes.join(' '),
})
}
@@ -43,7 +43,7 @@ export async function POST(
user.id,
companyId,
op as PendingOperation,
{ userEmail: user.email }
{ userEmail: user.email, commitMethod: 'user_accept' }
)
if (result.status === 'committed') {
@@ -235,7 +235,10 @@ describe('POST /api/pending-operations/bulk-commit', () => {
'user-1',
'company-1',
expect.objectContaining({ id: VALID_ID_1 }),
{ userEmail: 'test@test.se' }
// commit_method must be 'bulk_accept' so any journal_entries created
// during bulk approval are tagged distinctly from single-approval ones
// (BFNAR 2013:2 behandlingshistorik).
{ userEmail: 'test@test.se', commitMethod: 'bulk_accept' }
)
})
@@ -67,6 +67,7 @@ export async function POST(request: Request) {
const result = await commitPendingOperation(supabase, user.id, companyId, op, {
userEmail: user.email,
commitMethod: 'bulk_accept',
})
if (result.status === 'committed') {
results.push({ id, status: 'committed' })
@@ -0,0 +1,81 @@
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { requireWritePermission } from '@/lib/auth/require-write'
import { requireCompanyId } from '@/lib/company/context'
import { appendProcessingHistory } from '@/lib/processing-history/append'
import { createLogger } from '@/lib/logger'
const log = createLogger('oauth-clients:delete')
/**
* DELETE /api/settings/oauth-clients/[id] — revoke a redirect URI
* registration. Soft-delete via revoked_at so the audit trail survives
* and the same URI can be re-registered later.
*
* Emits an audit event so revocations are visible in processing_history —
* revoking an OAuth client is a security-relevant access-control change
* (SOC 2 CC7.2). Returns 404 when the row is unknown or already revoked
* so callers can surface failures rather than treating "no-op" as success.
*/
export async function DELETE(
_request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const supabase = await createClient()
const { id } = await params
const { data: { user } } = await supabase.auth.getUser()
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const writeCheck = await requireWritePermission(supabase, user.id)
if (!writeCheck.ok) return writeCheck.response
const { data: rows, error } = await supabase
.from('oauth_client_registrations')
.update({ revoked_at: new Date().toISOString() })
.eq('id', id)
.eq('user_id', user.id)
.is('revoked_at', null)
.select('id, redirect_uri, client_name')
if (error) {
return NextResponse.json({ error: error.message }, { status: 500 })
}
if (!rows || rows.length === 0) {
return NextResponse.json(
{ error: 'OAuth-klient hittades inte eller är redan återkallad.' },
{ status: 404 }
)
}
// Audit the revocation. Failure to append must not break the user flow —
// the revocation has already happened in the DB. We log the appendError
// so a systematic outage is visible in operations rather than silently
// degraded.
try {
const companyId = await requireCompanyId(supabase, user.id)
await appendProcessingHistory({
companyId,
correlationId: id,
aggregateType: 'System',
aggregateId: id,
eventType: 'OAuthClientRevoked',
payload: {
client_id: id,
// Note: redirect_uri may contain a host the user identifies with their
// own infrastructure but is not PII per Art. 4(1). Stored to satisfy
// SOC 2 CC7.2 "what was revoked" evidence trail.
redirect_uri: rows[0].redirect_uri,
},
actor: { type: 'user', id: user.id },
occurredAt: new Date(),
})
} catch (auditErr) {
log.warn('Failed to append OAuthClientRevoked audit event', auditErr)
}
return NextResponse.json({ success: true })
}
+91
View File
@@ -0,0 +1,91 @@
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { requireWritePermission } from '@/lib/auth/require-write'
import { z } from 'zod'
/**
* GET /api/settings/oauth-clients — list the current user's registered
* redirect URIs.
* POST /api/settings/oauth-clients — register a new redirect URI for use
* with the MCP OAuth flow.
*
* Built-in patterns (claude.ai, claude.com, localhost) bypass this table
* entirely — registrations here are only for self-hosted custom apps.
*/
const RegistrationSchema = z.object({
client_name: z.string().trim().min(1).max(100),
// Require https for non-loopback URIs. We reject loopback here because
// localhost is already on the built-in allowlist — there's no reason to
// register it explicitly.
redirect_uri: z
.string()
.url('redirect_uri must be a valid URL')
.refine((u) => u.startsWith('https://'), 'redirect_uri must use https://')
.refine(
(u) => !/^https:\/\/(localhost|127\.0\.0\.1|::1)(:|\/|$)/i.test(u),
'localhost is already allowed without registration'
)
.max(500),
})
export async function GET() {
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const { data, error } = await supabase
.from('oauth_client_registrations')
.select('id, client_name, redirect_uri, created_at, revoked_at')
.eq('user_id', user.id)
.order('created_at', { ascending: false })
if (error) {
return NextResponse.json({ error: error.message }, { status: 500 })
}
return NextResponse.json({ data })
}
export async function POST(request: Request) {
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
const writeCheck = await requireWritePermission(supabase, user.id)
if (!writeCheck.ok) return writeCheck.response
let body: z.infer<typeof RegistrationSchema>
try {
const json = await request.json()
body = RegistrationSchema.parse(json)
} catch (err) {
return NextResponse.json(
{ error: err instanceof Error ? err.message : 'Invalid request body' },
{ status: 400 }
)
}
const { data, error } = await supabase
.from('oauth_client_registrations')
.insert({
user_id: user.id,
client_name: body.client_name,
redirect_uri: body.redirect_uri,
})
.select('id, client_name, redirect_uri, created_at')
.single()
if (error) {
// Unique-index violation on redirect_uri → 409
if (error.code === '23505') {
return NextResponse.json(
{ error: 'Den här redirect URI:n är redan registrerad.' },
{ status: 409 }
)
}
return NextResponse.json({ error: error.message }, { status: 500 })
}
return NextResponse.json({ data })
}