fix(entitlements): gate the AI-only invoice-inbox for non-payers (#924)
The Dokumentinkorg (invoice-inbox) leaked past the paywall: visible in the sidebar, command palette, and home "Att gora" list, its page directly reachable, and every non-AI HTTP route open. Its whole value is AI field extraction (Claude Sonnet 4.6 via Bedrock), already the paid chokepoint elsewhere, so gate the whole surface on CAPABILITY.ai. - EXTENSION_REQUIRED_CAPABILITY map + resolvers (keys.ts, sectors.ts) as the single source the nav item, the page, and the API dispatcher all read. - Hide the sidebar item, command-palette entry, and home inbox row for non-payers; subtract inbox_document from the "Att gora" total via one shared visibleWorklistTotal helper (KPI tile + header cannot drift), clamped to >= 0. - Block the /e/[sector]/[slug] page (fail-closed) with an upsell EmptyState. - Enforce the capability in the extension API dispatcher (the single chokepoint that already enforces MFA), so every company-context inbox route 403s. The skipAuth /inbound webhook stays open (freeze-and-retain). - FORCE_PAYWALL=true override so the real gate is exercisable in local dev. - Tests: gating resolver, FORCE_PAYWALL, dispatcher 403/allow/webhook-exempt, visibleWorklistTotal, and enable-banking /connect + /sync 403. Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5
parent
a566a42aec
commit
19cbb0094b
@@ -33,13 +33,33 @@ vi.mock('@/lib/auth/mfa', () => ({
|
||||
shouldEnforceMfa: vi.fn(() => false),
|
||||
}))
|
||||
|
||||
// Drive the paywall gate directly. Keep the module's real exports (the resolver
|
||||
// path reads keys.ts, not this module) and only stub requireCapability so a test
|
||||
// can force "blocked" / "allowed" without seeding capability_grants rows.
|
||||
vi.mock('@/lib/entitlements/has-capability', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@/lib/entitlements/has-capability')>()),
|
||||
requireCapability: vi.fn(),
|
||||
}))
|
||||
|
||||
// Control which capability an extension requires directly, instead of depending
|
||||
// on the generated extension registry: it is empty in the zero-extensions
|
||||
// (core-only) build, which would otherwise make the gate a no-op here.
|
||||
vi.mock('@/lib/extensions/sectors', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@/lib/extensions/sectors')>()),
|
||||
requiredCapabilityForExtensionId: vi.fn(),
|
||||
}))
|
||||
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { shouldEnforceMfa } from '@/lib/auth/mfa'
|
||||
import { requireCapability } from '@/lib/entitlements/has-capability'
|
||||
import { requiredCapabilityForExtensionId } from '@/lib/extensions/sectors'
|
||||
import { extensionRegistry } from '@/lib/extensions/registry'
|
||||
import { GET, POST } from '../route'
|
||||
|
||||
const mockCreateClient = vi.mocked(createClient)
|
||||
const mockShouldEnforceMfa = vi.mocked(shouldEnforceMfa)
|
||||
const mockRequireCapability = vi.mocked(requireCapability)
|
||||
const mockRequiredCapabilityForExtensionId = vi.mocked(requiredCapabilityForExtensionId)
|
||||
|
||||
function createPathParams(path: string[]) {
|
||||
return { params: Promise.resolve({ path }) }
|
||||
@@ -51,6 +71,11 @@ describe('Extension Catch-All Route', () => {
|
||||
// clearAllMocks doesn't reset implementations: re-assert the default so the
|
||||
// AAL2 test's mockReturnValue(true) can't leak into later cases.
|
||||
mockShouldEnforceMfa.mockReturnValue(false)
|
||||
// Default: capability present (allowed). Gated-extension tests override this.
|
||||
mockRequireCapability.mockResolvedValue(null)
|
||||
// Default: extension requires no capability, so the gate is a no-op and
|
||||
// existing dispatch tests behave as before. Paywall tests override this.
|
||||
mockRequiredCapabilityForExtensionId.mockReturnValue(undefined)
|
||||
extensionRegistry.clear()
|
||||
})
|
||||
|
||||
@@ -215,4 +240,89 @@ describe('Extension Catch-All Route', () => {
|
||||
expect(status).toBe(200)
|
||||
expect(handler).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
// Paywall: the dispatcher gates every company-context route of an extension
|
||||
// that declares a required capability (invoice-inbox → ai). The resolver is
|
||||
// mocked so the test is deterministic in any build; requireCapability is
|
||||
// mocked to force the outcome.
|
||||
it('blocks a paid extension route when the company lacks the capability, before the handler runs', async () => {
|
||||
const handler = vi.fn()
|
||||
extensionRegistry.register({
|
||||
id: 'invoice-inbox',
|
||||
name: 'Dokumentinkorg',
|
||||
version: '1.0.0',
|
||||
apiRoutes: [{ method: 'GET', path: '/items', handler }],
|
||||
})
|
||||
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
supabase.auth.getUser.mockResolvedValue({
|
||||
data: { user: { id: 'user-1' } },
|
||||
error: null,
|
||||
})
|
||||
mockCreateClient.mockResolvedValue(supabase as never)
|
||||
mockRequiredCapabilityForExtensionId.mockReturnValue('ai')
|
||||
mockRequireCapability.mockResolvedValue(
|
||||
NextResponse.json(
|
||||
{ error: 'paid', capability_blocked: true, capability: 'ai' },
|
||||
{ status: 403 },
|
||||
),
|
||||
)
|
||||
|
||||
const request = createMockRequest('/api/extensions/ext/invoice-inbox/items')
|
||||
const response = await GET(request, createPathParams(['invoice-inbox', 'items']))
|
||||
const { status } = await parseJsonResponse(response)
|
||||
|
||||
expect(status).toBe(403)
|
||||
expect(handler).not.toHaveBeenCalled()
|
||||
expect(mockRequireCapability).toHaveBeenCalledWith(expect.anything(), 'company-1', 'ai')
|
||||
})
|
||||
|
||||
it('dispatches a paid extension route when the company holds the capability', async () => {
|
||||
const handler = vi.fn().mockResolvedValue(NextResponse.json({ data: [] }))
|
||||
extensionRegistry.register({
|
||||
id: 'invoice-inbox',
|
||||
name: 'Dokumentinkorg',
|
||||
version: '1.0.0',
|
||||
apiRoutes: [{ method: 'GET', path: '/items', handler }],
|
||||
})
|
||||
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
supabase.auth.getUser.mockResolvedValue({
|
||||
data: { user: { id: 'user-1' } },
|
||||
error: null,
|
||||
})
|
||||
mockCreateClient.mockResolvedValue(supabase as never)
|
||||
mockRequiredCapabilityForExtensionId.mockReturnValue('ai')
|
||||
mockRequireCapability.mockResolvedValue(null) // capability present
|
||||
|
||||
const request = createMockRequest('/api/extensions/ext/invoice-inbox/items')
|
||||
const response = await GET(request, createPathParams(['invoice-inbox', 'items']))
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(handler).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('never gates the skipAuth ingestion webhook of a paid extension (freeze-and-retain)', async () => {
|
||||
const handler = vi.fn().mockResolvedValue(NextResponse.json({ ok: true }))
|
||||
extensionRegistry.register({
|
||||
id: 'invoice-inbox',
|
||||
name: 'Dokumentinkorg',
|
||||
version: '1.0.0',
|
||||
apiRoutes: [{ method: 'POST', path: '/inbound', handler, skipAuth: true }],
|
||||
})
|
||||
// Even if the gate would block, the skipAuth branch returns first.
|
||||
mockRequireCapability.mockResolvedValue(
|
||||
NextResponse.json({ capability_blocked: true }, { status: 403 }),
|
||||
)
|
||||
|
||||
const request = createMockRequest('/api/extensions/ext/invoice-inbox/inbound', {
|
||||
method: 'POST',
|
||||
body: {},
|
||||
})
|
||||
const response = await POST(request, createPathParams(['invoice-inbox', 'inbound']))
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(handler).toHaveBeenCalled()
|
||||
expect(mockRequireCapability).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -4,6 +4,8 @@ import { ensureInitialized } from '@/lib/init'
|
||||
import { extensionRegistry } from '@/lib/extensions/registry'
|
||||
import { createExtensionContext } from '@/lib/extensions/context-factory'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import { requireCapability } from '@/lib/entitlements/has-capability'
|
||||
import { requiredCapabilityForExtensionId } from '@/lib/extensions/sectors'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import type { ApiRouteDefinition } from '@/lib/extensions/types'
|
||||
|
||||
@@ -276,6 +278,23 @@ async function handleRequest(
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
// Paywall: this dispatcher is the single chokepoint for the whole enabled-
|
||||
// extension API surface (same reasoning as the MFA gate above), so an
|
||||
// extension whose workspace is a paid service (EXTENSION_REQUIRED_CAPABILITY,
|
||||
// e.g. the AI-only invoice-inbox) gates EVERY one of its company-context routes
|
||||
// here, not just its AI-extraction steps. Mirrors the sidebar/page gate off the
|
||||
// same map. The skipAuth ingestion webhook (/inbound) returned above is exempt
|
||||
// by construction: a lapsed company's inbound documents must still be stored
|
||||
// (freeze-and-retain), and booked documents stay reachable via the verifikat.
|
||||
const requiredCapability = requiredCapabilityForExtensionId(extensionId)
|
||||
if (requiredCapability) {
|
||||
const blocked = await requireCapability(supabase, companyId, requiredCapability)
|
||||
if (blocked) {
|
||||
log.info('extension call blocked: capability required', { capability: requiredCapability })
|
||||
return decorateResponse(blocked, requestId)
|
||||
}
|
||||
}
|
||||
|
||||
// Build context and dispatch
|
||||
const ctx = createExtensionContext(supabase, user.id, companyId, extensionId, requestId)
|
||||
const response = await matchedRoute.handler(handlerRequest, ctx)
|
||||
|
||||
Reference in New Issue
Block a user