docs(production): standardiserad produktionsberedskap och gap-analys
Lägger docs/production-readiness.md och siax/production-gaps.json enligt SIAX Master Definition of Done. Underlag: git-, kod- och live-evidens 2026-11-11. Nivån är evidensbaserad, inte ett leveransgodkännande.
This commit is contained in:
@@ -1,328 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import {
|
||||
createQueuedMockSupabase,
|
||||
createMockRequest,
|
||||
parseJsonResponse,
|
||||
} from '@/tests/helpers'
|
||||
import { NextResponse } from 'next/server'
|
||||
|
||||
// Mock dependencies
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({
|
||||
ensureInitialized: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/extensions/context-factory', () => ({
|
||||
createExtensionContext: vi.fn().mockReturnValue({
|
||||
userId: 'user-1',
|
||||
extensionId: 'test-ext',
|
||||
}),
|
||||
}))
|
||||
|
||||
// Default to "MFA not enforced" so existing tests authenticate normally;
|
||||
// the AAL2-gate regression test below flips this on.
|
||||
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 }) }
|
||||
}
|
||||
|
||||
describe('Extension Catch-All Route', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
// 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()
|
||||
})
|
||||
|
||||
it('returns 400 for empty path', async () => {
|
||||
const request = createMockRequest('/api/extensions/ext/')
|
||||
const response = await GET(request, createPathParams([]))
|
||||
const { status } = await parseJsonResponse(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 404 for unknown extension', async () => {
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
supabase.auth.getUser.mockResolvedValue({
|
||||
data: { user: { id: 'user-1' } },
|
||||
error: null,
|
||||
})
|
||||
mockCreateClient.mockResolvedValue(supabase as never)
|
||||
|
||||
const request = createMockRequest('/api/extensions/ext/nonexistent/foo')
|
||||
const response = await GET(request, createPathParams(['nonexistent', 'foo']))
|
||||
const { status } = await parseJsonResponse(response)
|
||||
|
||||
expect(status).toBe(404)
|
||||
})
|
||||
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
extensionRegistry.register({
|
||||
id: 'test-ext',
|
||||
name: 'Test',
|
||||
version: '1.0.0',
|
||||
apiRoutes: [{ method: 'GET', path: '/data', handler: vi.fn() }],
|
||||
})
|
||||
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
supabase.auth.getUser.mockResolvedValue({
|
||||
data: { user: null },
|
||||
error: { message: 'Not authenticated' },
|
||||
})
|
||||
mockCreateClient.mockResolvedValue(supabase as never)
|
||||
|
||||
const request = createMockRequest('/api/extensions/ext/test-ext/data')
|
||||
const response = await GET(request, createPathParams(['test-ext', 'data']))
|
||||
const { status } = await parseJsonResponse(response)
|
||||
|
||||
expect(status).toBe(401)
|
||||
})
|
||||
|
||||
it('blocks a session that has not completed MFA (AAL2) and never dispatches the handler', async () => {
|
||||
// Regression for the audit fix: the dispatcher is the single chokepoint for
|
||||
// the whole extension surface, so an AAL1 (single-factor) session on hosted
|
||||
// must be rejected before any extension handler runs.
|
||||
const handler = vi.fn()
|
||||
extensionRegistry.register({
|
||||
id: 'test-ext',
|
||||
name: 'Test',
|
||||
version: '1.0.0',
|
||||
apiRoutes: [{ method: 'GET', path: '/data', handler }],
|
||||
})
|
||||
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
supabase.auth.getUser.mockResolvedValue({
|
||||
data: { user: { id: 'user-1', app_metadata: {} } },
|
||||
error: null,
|
||||
})
|
||||
// MFA is required for this user, but only AAL1 has been reached.
|
||||
mockShouldEnforceMfa.mockReturnValue(true)
|
||||
;(supabase.auth as unknown as { mfa: unknown }).mfa = {
|
||||
getAuthenticatorAssuranceLevel: vi
|
||||
.fn()
|
||||
.mockResolvedValue({ data: { currentLevel: 'aal1', nextLevel: 'aal2' } }),
|
||||
}
|
||||
mockCreateClient.mockResolvedValue(supabase as never)
|
||||
|
||||
const request = createMockRequest('/api/extensions/ext/test-ext/data')
|
||||
const response = await GET(request, createPathParams(['test-ext', 'data']))
|
||||
const { status } = await parseJsonResponse(response)
|
||||
|
||||
expect(status).toBe(403)
|
||||
expect(handler).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 404 for unmatched method/path', async () => {
|
||||
extensionRegistry.register({
|
||||
id: 'test-ext',
|
||||
name: 'Test',
|
||||
version: '1.0.0',
|
||||
apiRoutes: [{ method: 'POST', path: '/data', handler: vi.fn() }],
|
||||
})
|
||||
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
supabase.auth.getUser.mockResolvedValue({
|
||||
data: { user: { id: 'user-1' } },
|
||||
error: null,
|
||||
})
|
||||
mockCreateClient.mockResolvedValue(supabase as never)
|
||||
|
||||
// GET doesn't match POST /data
|
||||
const request = createMockRequest('/api/extensions/ext/test-ext/data')
|
||||
const response = await GET(request, createPathParams(['test-ext', 'data']))
|
||||
const { status } = await parseJsonResponse(response)
|
||||
|
||||
expect(status).toBe(404)
|
||||
})
|
||||
|
||||
it('dispatches to matching handler with context', async () => {
|
||||
const handler = vi.fn().mockResolvedValue(
|
||||
NextResponse.json({ banks: [] })
|
||||
)
|
||||
|
||||
extensionRegistry.register({
|
||||
id: 'enable-banking',
|
||||
name: 'Enable Banking',
|
||||
version: '1.0.0',
|
||||
apiRoutes: [{ method: 'GET', path: '/banks', handler }],
|
||||
})
|
||||
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
supabase.auth.getUser.mockResolvedValue({
|
||||
data: { user: { id: 'user-1' } },
|
||||
error: null,
|
||||
})
|
||||
mockCreateClient.mockResolvedValue(supabase as never)
|
||||
|
||||
const request = createMockRequest('/api/extensions/ext/enable-banking/banks')
|
||||
const response = await GET(request, createPathParams(['enable-banking', 'banks']))
|
||||
const { status, body } = await parseJsonResponse<{ banks: unknown[] }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.banks).toEqual([])
|
||||
expect(handler).toHaveBeenCalledWith(request, expect.objectContaining({
|
||||
extensionId: 'test-ext',
|
||||
}))
|
||||
})
|
||||
|
||||
it('dispatches POST requests correctly', async () => {
|
||||
const handler = vi.fn().mockResolvedValue(
|
||||
NextResponse.json({ ok: true })
|
||||
)
|
||||
|
||||
extensionRegistry.register({
|
||||
id: 'test-ext',
|
||||
name: 'Test',
|
||||
version: '1.0.0',
|
||||
apiRoutes: [{ method: 'POST', path: '/connect', handler }],
|
||||
})
|
||||
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
supabase.auth.getUser.mockResolvedValue({
|
||||
data: { user: { id: 'user-1' } },
|
||||
error: null,
|
||||
})
|
||||
mockCreateClient.mockResolvedValue(supabase as never)
|
||||
|
||||
const request = createMockRequest('/api/extensions/ext/test-ext/connect', {
|
||||
method: 'POST',
|
||||
body: { foo: 'bar' },
|
||||
})
|
||||
const response = await POST(request, createPathParams(['test-ext', 'connect']))
|
||||
const { status } = await parseJsonResponse(response)
|
||||
|
||||
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()
|
||||
})
|
||||
})
|
||||
@@ -1,314 +0,0 @@
|
||||
import { requireAuth } from '@/lib/auth/require-auth'
|
||||
import { NextResponse } from 'next/server'
|
||||
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'
|
||||
|
||||
const dispatcherLog = createLogger('extension-dispatcher')
|
||||
|
||||
function generateRequestId(): string {
|
||||
return `req_${crypto.randomUUID()}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap a Response so support staff can find the inbound request in stdout
|
||||
* logs by id:
|
||||
*
|
||||
* 1. set the `X-Request-Id` header if missing
|
||||
* 2. for JSON error envelopes (`{ error: { code, ... } }`) that came back
|
||||
* without a requestId, inject one into the body so the toast can show
|
||||
* `Felreferens: req_…`
|
||||
*
|
||||
* Non-JSON responses (HTML for OAuth callbacks, file downloads) only get the
|
||||
* header: body rewriting is reserved for the canonical envelope shape.
|
||||
*/
|
||||
async function decorateResponse(response: Response, requestId: string): Promise<Response> {
|
||||
if (!response.headers.get('X-Request-Id')) {
|
||||
response.headers.set('X-Request-Id', requestId)
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const contentType = response.headers.get('content-type') || ''
|
||||
if (contentType.includes('application/json')) {
|
||||
try {
|
||||
const cloned = response.clone()
|
||||
const body = await cloned.json()
|
||||
if (
|
||||
body &&
|
||||
typeof body === 'object' &&
|
||||
body.error &&
|
||||
typeof body.error === 'object' &&
|
||||
typeof body.error.code === 'string' &&
|
||||
!body.error.requestId
|
||||
) {
|
||||
const augmented = {
|
||||
...body,
|
||||
error: { ...body.error, requestId },
|
||||
}
|
||||
return new NextResponse(JSON.stringify(augmented), {
|
||||
status: response.status,
|
||||
headers: response.headers,
|
||||
})
|
||||
}
|
||||
} catch {
|
||||
// Body wasn't valid JSON: leave it alone.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
// Heavy extension routes (SIE import, migration) need up to 5 minutes
|
||||
export const maxDuration = 300
|
||||
|
||||
/**
|
||||
* Per-extension runtime feature flags. Lets ops toggle an integration off
|
||||
* without redeploying or removing it from extensions.config.json: useful
|
||||
* for phased rollouts (dev tenants → design partners → general).
|
||||
*
|
||||
* The flag is checked on every request. If the env var is not exactly the
|
||||
* string "true", the dispatcher returns 503 with `code: 'EXTENSION_DISABLED'`.
|
||||
*
|
||||
* Server-side env vars only: no NEXT_PUBLIC_ prefix. Next.js inlines
|
||||
* NEXT_PUBLIC_* into the client bundle at build time, so a flip on Vercel
|
||||
* without a redeploy would create split-brain (server returns 503,
|
||||
* client still renders the enabled flow). UI panels detect the 503 by
|
||||
* response code, not by reading the flag directly.
|
||||
*/
|
||||
const EXTENSION_FEATURE_FLAGS: Record<string, { envVar: string; disabledMessage: string }> = {
|
||||
skatteverket: {
|
||||
envVar: 'SKATTEVERKET_ENABLED',
|
||||
disabledMessage: 'Skatteverket-integrationen är inte aktiverad i denna miljö.',
|
||||
},
|
||||
}
|
||||
|
||||
/**
|
||||
* Match a request path against a route pattern.
|
||||
* Supports :param wildcards (e.g., /:id/confirm).
|
||||
* Returns extracted params on match, null on mismatch.
|
||||
*/
|
||||
function matchPath(
|
||||
pattern: string,
|
||||
requestPath: string
|
||||
): Record<string, string> | null {
|
||||
const patternParts = pattern.split('/').filter(Boolean)
|
||||
const requestParts = requestPath.split('/').filter(Boolean)
|
||||
|
||||
if (patternParts.length !== requestParts.length) return null
|
||||
|
||||
const params: Record<string, string> = {}
|
||||
|
||||
for (let i = 0; i < patternParts.length; i++) {
|
||||
if (patternParts[i].startsWith(':')) {
|
||||
params[patternParts[i].slice(1)] = requestParts[i]
|
||||
} else if (patternParts[i] !== requestParts[i]) {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
return params
|
||||
}
|
||||
|
||||
/**
|
||||
* Catch-all route for extension-declared API routes.
|
||||
*
|
||||
* URL scheme: /api/extensions/ext/{extensionId}/{...routePath}
|
||||
* Example: /api/extensions/ext/mcp-server/mcp → POST /mcp
|
||||
*
|
||||
* - Looks up the extension in the registry
|
||||
* - Checks the extension toggle (disabled → 403)
|
||||
* - Matches method + path pattern to registered apiRoutes
|
||||
* - Extracts path params and appends them as URL search params
|
||||
* - Builds an ExtensionContext and passes it to the handler
|
||||
*/
|
||||
async function handleRequest(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ path: string[] }> }
|
||||
): Promise<Response> {
|
||||
const requestId = generateRequestId()
|
||||
const start = Date.now()
|
||||
const segments = await params
|
||||
|
||||
if (!segments.path || segments.path.length < 1) {
|
||||
return decorateResponse(
|
||||
NextResponse.json({ error: 'Invalid extension route' }, { status: 400 }),
|
||||
requestId,
|
||||
)
|
||||
}
|
||||
|
||||
const [extensionId, ...rest] = segments.path
|
||||
const routePath = '/' + rest.join('/')
|
||||
const method = request.method as 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'
|
||||
|
||||
const log = dispatcherLog.child({ requestId, extensionId, routePath, method })
|
||||
|
||||
// Look up extension
|
||||
const extension = extensionRegistry.get(extensionId)
|
||||
if (!extension || !extension.apiRoutes || extension.apiRoutes.length === 0) {
|
||||
log.warn('extension not found')
|
||||
return decorateResponse(
|
||||
NextResponse.json({ error: 'Extension not found' }, { status: 404 }),
|
||||
requestId,
|
||||
)
|
||||
}
|
||||
|
||||
// Per-extension feature flags. Lets us toggle a single integration off
|
||||
// mid-rollout without redeploying or removing it from extensions.config.json.
|
||||
// The frontend (SkatteverketPanel, AGIPanel) inspects the 503 + code to
|
||||
// render an "extension disabled" empty state.
|
||||
const flag = EXTENSION_FEATURE_FLAGS[extensionId]
|
||||
if (flag && process.env[flag.envVar] !== 'true') {
|
||||
return decorateResponse(
|
||||
NextResponse.json(
|
||||
{ error: flag.disabledMessage, code: 'EXTENSION_DISABLED' },
|
||||
{ status: 503 },
|
||||
),
|
||||
requestId,
|
||||
)
|
||||
}
|
||||
|
||||
// Match route BEFORE auth so we can check skipAuth (e.g. OAuth callbacks)
|
||||
let matchedRoute: ApiRouteDefinition | null = null
|
||||
let extractedParams: Record<string, string> = {}
|
||||
|
||||
for (const route of extension.apiRoutes) {
|
||||
if (route.method !== method) continue
|
||||
|
||||
const routeParams = matchPath(route.path, routePath)
|
||||
if (routeParams !== null) {
|
||||
matchedRoute = route
|
||||
extractedParams = routeParams
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if (!matchedRoute) {
|
||||
return decorateResponse(
|
||||
NextResponse.json({ error: 'Route not found' }, { status: 404 }),
|
||||
requestId,
|
||||
)
|
||||
}
|
||||
|
||||
// Config sanity check: these flags are orthogonal and the combination is
|
||||
// nonsensical. `skipAuth` already implies no company resolution, so adding
|
||||
// `skipCompanyContext: true` is at best redundant, and if a maintainer
|
||||
// intended "auth required, no company" but also wrote `skipAuth: true`,
|
||||
// the auth requirement would be silently dropped (skipAuth fires first
|
||||
// below). Fail loudly instead of masking the mistake.
|
||||
if (matchedRoute.skipAuth && matchedRoute.skipCompanyContext) {
|
||||
log.error('route misconfigured: skipAuth + skipCompanyContext are mutually exclusive', undefined)
|
||||
return decorateResponse(
|
||||
NextResponse.json({ error: 'Route misconfigured' }, { status: 500 }),
|
||||
requestId,
|
||||
)
|
||||
}
|
||||
|
||||
// For skipAuth routes (e.g. OAuth callbacks from external providers),
|
||||
// skip user auth, toggle check, and AI consent: dispatch immediately
|
||||
if (matchedRoute.skipAuth) {
|
||||
let handlerRequest = request
|
||||
if (Object.keys(extractedParams).length > 0) {
|
||||
const url = new URL(request.url)
|
||||
for (const [key, value] of Object.entries(extractedParams)) {
|
||||
url.searchParams.set(`_${key}`, value)
|
||||
}
|
||||
const cloned = request.clone()
|
||||
handlerRequest = new Request(url.toString(), {
|
||||
method: cloned.method,
|
||||
headers: cloned.headers,
|
||||
body: cloned.body,
|
||||
// @ts-expect-error -- duplex needed for streaming body
|
||||
duplex: 'half',
|
||||
})
|
||||
}
|
||||
const response = await matchedRoute.handler(handlerRequest)
|
||||
log.info('extension call completed', { durationMs: Date.now() - start, status: response.status })
|
||||
return decorateResponse(response, requestId)
|
||||
}
|
||||
|
||||
// Auth check: requireAuth() enforces MFA (AAL2) on hosted, which the previous
|
||||
// inline supabase.auth.getUser() did not. This dispatcher is the single
|
||||
// chokepoint for the entire enabled-extension surface (banking sync, document
|
||||
// upload/booking, supplier-invoice flows, migration), so enforcing MFA here
|
||||
// closes the gap across all of them at once.
|
||||
const auth = await requireAuth()
|
||||
if (auth.error) {
|
||||
return decorateResponse(auth.error, requestId)
|
||||
}
|
||||
const { user, supabase } = auth
|
||||
|
||||
// If path params were extracted, create a new Request with them as search params
|
||||
let handlerRequest = request
|
||||
if (Object.keys(extractedParams).length > 0) {
|
||||
const url = new URL(request.url)
|
||||
for (const [key, value] of Object.entries(extractedParams)) {
|
||||
url.searchParams.set(`_${key}`, value)
|
||||
}
|
||||
// Clone first to avoid body stream locking issues when transferring to new Request
|
||||
const cloned = request.clone()
|
||||
handlerRequest = new Request(url.toString(), {
|
||||
method: cloned.method,
|
||||
headers: cloned.headers,
|
||||
body: cloned.body,
|
||||
// @ts-expect-error -- duplex needed for streaming body
|
||||
duplex: 'half',
|
||||
})
|
||||
}
|
||||
|
||||
// Routes that are authenticated but run before a company exists (TIC
|
||||
// /lookup during onboarding, for example) opt out of company resolution.
|
||||
// Dispatch without a context: handlers that opt in must not rely on ctx.
|
||||
if (matchedRoute.skipCompanyContext) {
|
||||
const response = await matchedRoute.handler(handlerRequest)
|
||||
log.info('extension call completed', {
|
||||
durationMs: Date.now() - start,
|
||||
status: response.status,
|
||||
userId: user.id,
|
||||
})
|
||||
return decorateResponse(response, requestId)
|
||||
}
|
||||
|
||||
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)
|
||||
log.info('extension call completed', {
|
||||
durationMs: Date.now() - start,
|
||||
status: response.status,
|
||||
userId: user.id,
|
||||
companyId,
|
||||
})
|
||||
return decorateResponse(response, requestId)
|
||||
}
|
||||
|
||||
export const GET = handleRequest
|
||||
export const POST = handleRequest
|
||||
export const PUT = handleRequest
|
||||
export const DELETE = handleRequest
|
||||
export const PATCH = handleRequest
|
||||
Reference in New Issue
Block a user