fix(entitlements): gate paid MCP tools (send_invoice/agi_submit/vat_declaration_submit) server-side (#846)
The HTTP routes call requireCapability at every paid chokepoint, but the MCP/agent path bypassed the paywall entirely: the three external-service tools stage operations whose commit calls the email / Skatteverket services directly, with no capability check. After the 2026-07-07 trial cutover a trial-connected non-payer using the gnubok MCP connector could still send invoice emails and file AGI/VAT. Close the gap with two layers, mirroring the existing TOOL_SCOPE_MAP gate: - Dispatch gate (mcp-server/server.ts): MCP_TOOL_CAPABILITY_MAP, checked right after the scope check, blocks a non-entitled company before any pending op is staged. Emits errorKind='capability_denied' telemetry. - Commit-time gate (commitPendingOperation): PAID_OPERATION_CAPABILITY_MAP, checked before the atomic claim. The real external-service chokepoint — applies to the MCP approve tool AND the UI approval path, and closes the trial-connected-token window (the grant has expired by commit time). A blocked op stays 'pending', so it is re-approvable once the company subscribes. Adds a transport-free capabilityBlockedError() helper (shared bilingual copy) and locks both maps with tests (maps, dispatch gate, commit gate). Only the three write/submit tools are gated; SKV read/local tools stay free per the statutory carve-out. No DB/migration change; self-hosted stays all-on. Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
5df6199bd1
commit
db843a7a5b
@@ -0,0 +1,51 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
MCP_TOOL_CAPABILITY_MAP,
|
||||
PAID_OPERATION_CAPABILITY_MAP,
|
||||
PAID_CAPABILITIES,
|
||||
CAPABILITY,
|
||||
} from '../keys'
|
||||
|
||||
/**
|
||||
* These maps are the contract that gates the paid MCP/agent path (dispatch +
|
||||
* commit). Locking the exact entries is the guard against a future paid
|
||||
* external-service tool silently bypassing the paywall — mirrors the
|
||||
* TOOL_SCOPE_MAP assertions in the mcp-server tests.
|
||||
*/
|
||||
describe('MCP_TOOL_CAPABILITY_MAP', () => {
|
||||
it('gates exactly the three paid external-service MCP tools', () => {
|
||||
expect(MCP_TOOL_CAPABILITY_MAP).toEqual({
|
||||
gnubok_send_invoice: CAPABILITY.email_send,
|
||||
gnubok_vat_declaration_submit: CAPABILITY.skatteverket,
|
||||
gnubok_agi_submit: CAPABILITY.skatteverket,
|
||||
})
|
||||
})
|
||||
|
||||
it('only maps tools to PAID capabilities', () => {
|
||||
for (const key of Object.values(MCP_TOOL_CAPABILITY_MAP)) {
|
||||
expect(PAID_CAPABILITIES).toContain(key)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('PAID_OPERATION_CAPABILITY_MAP', () => {
|
||||
it('gates exactly the three paid pending-operation types', () => {
|
||||
expect(PAID_OPERATION_CAPABILITY_MAP).toEqual({
|
||||
send_invoice: CAPABILITY.email_send,
|
||||
submit_vat_declaration: CAPABILITY.skatteverket,
|
||||
submit_agi: CAPABILITY.skatteverket,
|
||||
})
|
||||
})
|
||||
|
||||
it('only maps operations to PAID capabilities', () => {
|
||||
for (const key of Object.values(PAID_OPERATION_CAPABILITY_MAP)) {
|
||||
expect(PAID_CAPABILITIES).toContain(key)
|
||||
}
|
||||
})
|
||||
|
||||
it('covers the same set of capabilities as the MCP tool map (dispatch ↔ commit parity)', () => {
|
||||
expect(new Set(Object.values(PAID_OPERATION_CAPABILITY_MAP))).toEqual(
|
||||
new Set(Object.values(MCP_TOOL_CAPABILITY_MAP)),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -80,6 +80,12 @@ export async function hasCapability(
|
||||
return true
|
||||
}
|
||||
|
||||
/** Bilingual paywall copy, shared by every transport (HTTP route, MCP tool, commit executor). */
|
||||
export const CAPABILITY_BLOCKED_MESSAGE_SV =
|
||||
'Den här funktionen kräver en betald prenumeration. Uppgradera för att fortsätta använda externa tjänster.'
|
||||
export const CAPABILITY_BLOCKED_MESSAGE_EN =
|
||||
'This feature requires a paid subscription. Upgrade to keep using external services.'
|
||||
|
||||
/**
|
||||
* Standard bilingual 403 for a capability-blocked endpoint. Matches the
|
||||
* sandbox/guard envelope so the UI surfaces the upsell consistently.
|
||||
@@ -87,10 +93,8 @@ export async function hasCapability(
|
||||
export function capabilityBlockedResponse(key: CapabilityKey): NextResponse {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
'Den här funktionen kräver en betald prenumeration. Uppgradera för att fortsätta använda externa tjänster.',
|
||||
error_en:
|
||||
'This feature requires a paid subscription. Upgrade to keep using external services.',
|
||||
error: CAPABILITY_BLOCKED_MESSAGE_SV,
|
||||
error_en: CAPABILITY_BLOCKED_MESSAGE_EN,
|
||||
capability_blocked: true,
|
||||
capability: key,
|
||||
},
|
||||
@@ -98,6 +102,30 @@ export function capabilityBlockedResponse(key: CapabilityKey): NextResponse {
|
||||
)
|
||||
}
|
||||
|
||||
export interface CapabilityBlockedError {
|
||||
code: 'capability_blocked'
|
||||
capability_blocked: true
|
||||
capability: CapabilityKey
|
||||
message_sv: string
|
||||
message_en: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Transport-free counterpart to capabilityBlockedResponse, for call sites that
|
||||
* don't return a NextResponse — the MCP dispatcher (folded into the JSON-RPC
|
||||
* `isError` envelope) and the pending-operation commit executor. Same copy and
|
||||
* the same `capability_blocked: true` marker so every surface upsells alike.
|
||||
*/
|
||||
export function capabilityBlockedError(key: CapabilityKey): CapabilityBlockedError {
|
||||
return {
|
||||
code: 'capability_blocked',
|
||||
capability_blocked: true,
|
||||
capability: key,
|
||||
message_sv: CAPABILITY_BLOCKED_MESSAGE_SV,
|
||||
message_en: CAPABILITY_BLOCKED_MESSAGE_EN,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience wrapper: check + return the 403 in one call. Returns the
|
||||
* NextResponse to return from the route, or null when the company has the
|
||||
|
||||
@@ -53,3 +53,34 @@ export const PAID_CAPABILITIES: readonly CapabilityKey[] = [
|
||||
CAPABILITY.skatteverket,
|
||||
CAPABILITY.email_send,
|
||||
] as const
|
||||
|
||||
/**
|
||||
* Paid MCP tools → required capability. The MCP/agent path is a paid chokepoint
|
||||
* just like the HTTP routes, so the dispatcher gates these the same way it gates
|
||||
* API-key scope (see mcp-server `tools/call`). Only external-service WRITE tools
|
||||
* appear here: send_invoice (email) and the two Skatteverket submissions. The
|
||||
* read/local SKV tools (generate_agi, vat_declaration_validate/status, agi_status)
|
||||
* stay free — the §4 carve-out forbids blocking a statutory filing obligation.
|
||||
*
|
||||
* No MCP tool invokes AI or triggers bank sync, so those PAID capabilities have
|
||||
* no entry here — they are reachable only via already-gated HTTP routes/handlers.
|
||||
*/
|
||||
export const MCP_TOOL_CAPABILITY_MAP: Readonly<Partial<Record<string, CapabilityKey>>> = {
|
||||
gnubok_send_invoice: CAPABILITY.email_send,
|
||||
gnubok_vat_declaration_submit: CAPABILITY.skatteverket,
|
||||
gnubok_agi_submit: CAPABILITY.skatteverket,
|
||||
} as const
|
||||
|
||||
/**
|
||||
* Paid pending-operation types → required capability. Keyed by
|
||||
* `pending_operations.operation_type`. This is the commit-time twin of
|
||||
* MCP_TOOL_CAPABILITY_MAP: it gates the actual external-service call inside
|
||||
* commitPendingOperation, so an operation staged during the trial cannot be
|
||||
* committed once the grant has expired — regardless of caller (MCP approve tool
|
||||
* or the UI approval path). Keep the values in sync with MCP_TOOL_CAPABILITY_MAP.
|
||||
*/
|
||||
export const PAID_OPERATION_CAPABILITY_MAP: Readonly<Partial<Record<string, CapabilityKey>>> = {
|
||||
send_invoice: CAPABILITY.email_send,
|
||||
submit_vat_declaration: CAPABILITY.skatteverket,
|
||||
submit_agi: CAPABILITY.skatteverket,
|
||||
} as const
|
||||
|
||||
+1
-1
@@ -168,7 +168,7 @@ export type CoreEvent =
|
||||
success: boolean // true iff the tool returned without throwing AND was invoked (not denied)
|
||||
isError: boolean // matches the JSON-RPC tool-result isError flag returned to the client
|
||||
errorCode: string | null // structured error code from tool-result.toToolError when applicable
|
||||
errorKind: 'execution' | 'scope_denied' | 'unknown_tool' | null
|
||||
errorKind: 'execution' | 'scope_denied' | 'capability_denied' | 'unknown_tool' | null
|
||||
errorMessage: string | null // human-readable error message (truncated to 500 chars), null on success.
|
||||
// Raw material for clustering real agent failures into curated gotchas —
|
||||
// errorCode alone can't distinguish "period locked" from "unbalanced".
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
/**
|
||||
* Tests for the commit-time capability gate in commitPendingOperation.
|
||||
*
|
||||
* This is the twin of the MCP dispatch gate and the true external-service
|
||||
* chokepoint: it runs BEFORE the atomic claim, so a blocked op stays 'pending'
|
||||
* (re-approvable once the company subscribes) and an op staged DURING the trial
|
||||
* cannot be committed once the grant expires — regardless of caller (MCP approve
|
||||
* tool or the UI approval path).
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { eventBus } from '@/lib/events/bus'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import type { PendingOperation } from '@/types'
|
||||
|
||||
vi.mock('@/lib/entitlements/has-capability', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/lib/entitlements/has-capability')>()
|
||||
return { ...actual, hasCapability: vi.fn() }
|
||||
})
|
||||
|
||||
import { commitPendingOperation } from '../commit'
|
||||
import { hasCapability } from '@/lib/entitlements/has-capability'
|
||||
|
||||
const mockHasCapability = vi.mocked(hasCapability)
|
||||
|
||||
function makePendingOp(overrides: Partial<PendingOperation>): PendingOperation {
|
||||
return {
|
||||
id: 'op-1',
|
||||
user_id: 'user-1',
|
||||
company_id: 'company-1',
|
||||
operation_type: 'send_invoice',
|
||||
status: 'pending',
|
||||
title: 'test',
|
||||
params: {},
|
||||
preview_data: {},
|
||||
result_data: null,
|
||||
actor_type: 'user',
|
||||
actor_id: null,
|
||||
actor_label: null,
|
||||
risk_level: 'high',
|
||||
created_at: '2026-06-01T00:00:00Z',
|
||||
resolved_at: null,
|
||||
updated_at: '2026-06-01T00:00:00Z',
|
||||
...overrides,
|
||||
} as PendingOperation
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
eventBus.clear()
|
||||
})
|
||||
|
||||
describe('commitPendingOperation: capability gate', () => {
|
||||
it('blocks send_invoice when email_send is not entitled — 403, op left pending', async () => {
|
||||
mockHasCapability.mockResolvedValue(false)
|
||||
const { supabase } = createQueuedMockSupabase() // no responses enqueued: the claim must never run
|
||||
|
||||
const op = makePendingOp({ operation_type: 'send_invoice', params: { invoice_id: 'inv-1' } })
|
||||
const result = await commitPendingOperation(supabase as never, 'user-1', 'company-1', op)
|
||||
|
||||
expect(result.status).toBe('failed')
|
||||
expect(result.http_status).toBe(403)
|
||||
expect(result.code).toBe('capability_blocked')
|
||||
expect(mockHasCapability).toHaveBeenCalledWith(supabase, 'company-1', 'email_send')
|
||||
})
|
||||
|
||||
it('blocks submit_vat_declaration when skatteverket is not entitled', async () => {
|
||||
mockHasCapability.mockResolvedValue(false)
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
|
||||
const op = makePendingOp({ operation_type: 'submit_vat_declaration', params: { period_type: 'monthly', year: 2025, period: 3 } })
|
||||
const result = await commitPendingOperation(supabase as never, 'user-1', 'company-1', op)
|
||||
|
||||
expect(result.status).toBe('failed')
|
||||
expect(result.http_status).toBe(403)
|
||||
expect(result.code).toBe('capability_blocked')
|
||||
expect(mockHasCapability).toHaveBeenCalledWith(supabase, 'company-1', 'skatteverket')
|
||||
})
|
||||
|
||||
it('does NOT consult the gate for a free operation type', async () => {
|
||||
mockHasCapability.mockResolvedValue(false)
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: null, error: null }) // claim resolves to "already claimed" → early 409, before any executor
|
||||
|
||||
const op = makePendingOp({ operation_type: 'create_customer', params: { name: 'x' } })
|
||||
const result = await commitPendingOperation(supabase as never, 'user-1', 'company-1', op)
|
||||
|
||||
// create_customer is not in PAID_OPERATION_CAPABILITY_MAP — the gate is skipped.
|
||||
expect(mockHasCapability).not.toHaveBeenCalled()
|
||||
expect(result.status).toBe('failed') // claim returned no row (409); proves we got past the gate
|
||||
})
|
||||
})
|
||||
@@ -21,6 +21,15 @@ import type { SkvSubmitResult } from '@/lib/pending-operations/skatteverket-comm
|
||||
import type { PendingOperation } from '@/types'
|
||||
import { commitPendingOperation } from '../commit'
|
||||
|
||||
// The commit-time capability gate (PR: gate paid MCP tools) runs hasCapability
|
||||
// before the atomic claim for submit_vat_declaration/submit_agi. These tests
|
||||
// isolate the registry/lifecycle wiring, so make the gate transparent here;
|
||||
// its enforcement is covered by commit-capability-gate.test.ts.
|
||||
vi.mock('@/lib/entitlements/has-capability', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/lib/entitlements/has-capability')>()
|
||||
return { ...actual, hasCapability: vi.fn().mockResolvedValue(true) }
|
||||
})
|
||||
|
||||
function makePendingOp(overrides: Partial<PendingOperation>): PendingOperation {
|
||||
return {
|
||||
id: 'op-1',
|
||||
|
||||
@@ -60,6 +60,8 @@ import {
|
||||
type SkvSubmitResult,
|
||||
} from '@/lib/pending-operations/skatteverket-commit'
|
||||
import { getEmailService } from '@/lib/email/service'
|
||||
import { hasCapability, CAPABILITY_BLOCKED_MESSAGE_SV } from '@/lib/entitlements/has-capability'
|
||||
import { PAID_OPERATION_CAPABILITY_MAP } from '@/lib/entitlements/keys'
|
||||
import {
|
||||
generateInvoiceEmailHtml,
|
||||
generateInvoiceEmailText,
|
||||
@@ -3665,6 +3667,23 @@ async function commitPendingOperationInner(
|
||||
pendingOp: PendingOperation,
|
||||
opts: CommitOptions = {}
|
||||
): Promise<CommitResult> {
|
||||
// ── Capability gate (commit-time twin of the MCP dispatch gate). The actual
|
||||
// external-service call (email / Skatteverket submit) happens below, so
|
||||
// this is the true paid chokepoint — it also catches an op STAGED during
|
||||
// the trial then approved AFTER the grant expired, regardless of caller
|
||||
// (MCP approve tool or the UI approval path). Checked BEFORE the atomic
|
||||
// claim so a blocked op stays 'pending' and is re-approvable once the
|
||||
// company subscribes. Self-hosted short-circuits to all-on in hasCapability.
|
||||
const requiredCapability = PAID_OPERATION_CAPABILITY_MAP[pendingOp.operation_type]
|
||||
if (requiredCapability && !(await hasCapability(supabase, companyId, requiredCapability))) {
|
||||
return {
|
||||
status: 'failed',
|
||||
error: CAPABILITY_BLOCKED_MESSAGE_SV,
|
||||
http_status: 403,
|
||||
code: 'capability_blocked',
|
||||
}
|
||||
}
|
||||
|
||||
// ── Atomic claim: flip status pending → committing in a single conditional
|
||||
// update. If 0 rows are affected, another caller (auto-commit ↔ human
|
||||
// approval, or two parallel approvals) already claimed this op and we
|
||||
|
||||
Reference in New Issue
Block a user