fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
masterplan-lock / check (push) Successful in 19s
ci / sonar (push) Failing after 21s
security / scan (push) Failing after 1m37s

Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i
server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma
strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
2026-11-10 09:37:22 +01:00
parent 077251ac94
commit e7f0070e84
6135 changed files with 1718997 additions and 4 deletions
@@ -0,0 +1,122 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import {
createMockRequest,
createMockRouteParams,
parseJsonResponse,
createQueuedMockSupabase,
} from '@/tests/helpers'
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const requireWriteMock = vi.fn()
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
}))
import { GET, POST, DELETE } from '../route'
const params = () => createMockRouteParams({ sector: 'general', slug: 'demo' })
describe('/api/extensions/[sector]/[slug]/data', () => {
const mockUser = { id: 'user-1', email: '[email protected]' }
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: mockUser, supabase: mockSupabase, error: null })
requireWriteMock.mockResolvedValue({ ok: true })
})
it('GET lists extension data', async () => {
enqueue({ data: [{ key: 'a', value: 1 }] })
const response = await GET(createMockRequest('/api/extensions/general/demo/data'), params())
const { status, body } = await parseJsonResponse<{ data: unknown[] }>(response)
expect(status).toBe(200)
expect(body.data).toHaveLength(1)
})
it('POST returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: mockSupabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const response = await POST(
createMockRequest('/api/extensions/general/demo/data', { method: 'POST', body: { key: 'k', value: 1 } }),
params(),
)
expect(response.status).toBe(401)
})
it('POST returns 403 for a viewer', async () => {
requireWriteMock.mockResolvedValue({
ok: false,
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
})
const response = await POST(
createMockRequest('/api/extensions/general/demo/data', { method: 'POST', body: { key: 'k', value: 1 } }),
params(),
)
expect(response.status).toBe(403)
})
it('POST returns 400 when key is missing', async () => {
const response = await POST(
createMockRequest('/api/extensions/general/demo/data', { method: 'POST', body: { value: 1 } }),
params(),
)
expect(response.status).toBe(400)
})
it('POST upserts a key/value (happy path)', async () => {
enqueue({ data: { key: 'k', value: 42 }, error: null })
const response = await POST(
createMockRequest('/api/extensions/general/demo/data', { method: 'POST', body: { key: 'k', value: 42 } }),
params(),
)
const { status, body } = await parseJsonResponse<{ data: { value: number } }>(response)
expect(status).toBe(200)
expect(body.data.value).toBe(42)
})
it('DELETE returns 400 without a key query param', async () => {
const response = await DELETE(
createMockRequest('/api/extensions/general/demo/data', { method: 'DELETE' }),
params(),
)
expect(response.status).toBe(400)
})
it('DELETE removes a key (happy path)', async () => {
enqueue({ data: null, error: null })
const response = await DELETE(
createMockRequest('/api/extensions/general/demo/data', {
method: 'DELETE',
searchParams: { key: 'k' },
}),
params(),
)
const { status, body } = await parseJsonResponse<{ success: boolean }>(response)
expect(status).toBe(200)
expect(body.success).toBe(true)
})
})
@@ -0,0 +1,105 @@
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
export const GET = withRouteContext<{ params: Promise<{ sector: string; slug: string }> }>(
'extension.data.get',
async (request, { supabase, companyId }, { params }) => {
const { sector, slug } = await params
const extensionId = `${sector}/${slug}`
const { searchParams } = new URL(request.url)
const key = searchParams.get('key')
let query = supabase
.from('extension_data')
.select('*')
.eq('company_id', companyId)
.eq('extension_id', extensionId)
const prefix = searchParams.get('prefix')
if (key) {
query = query.eq('key', key)
} else if (prefix) {
query = query.ilike('key', `${prefix}%`)
}
const { data, error } = await query
if (error) {
return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
}
return NextResponse.json({ data })
},
)
export const POST = withRouteContext<{ params: Promise<{ sector: string; slug: string }> }>(
'extension.data.set',
async (request, { supabase, user, companyId }, { params }) => {
const { sector, slug } = await params
const body = await request.json()
const { key, value } = body
if (!key) {
return NextResponse.json({ error: 'key is required' }, { status: 400 })
}
const extensionId = `${sector}/${slug}`
const { data, error } = await supabase
.from('extension_data')
.upsert(
{
user_id: user.id,
company_id: companyId,
extension_id: extensionId,
key,
value,
},
{ onConflict: 'user_id,extension_id,key' }
)
.select()
.single()
if (error) {
return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
}
return NextResponse.json({ data })
},
{ requireWrite: true },
)
export const DELETE = withRouteContext<{ params: Promise<{ sector: string; slug: string }> }>(
'extension.data.delete',
async (request, { supabase, companyId }, { params }) => {
const { sector, slug } = await params
const { searchParams } = new URL(request.url)
const key = searchParams.get('key')
if (!key) {
return NextResponse.json({ error: 'key query parameter is required' }, { status: 400 })
}
const extensionId = `${sector}/${slug}`
const { error } = await supabase
.from('extension_data')
.delete()
.eq('company_id', companyId)
.eq('extension_id', extensionId)
.eq('key', key)
if (error) {
return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
}
return NextResponse.json({ success: true })
},
{ requireWrite: true },
)
@@ -0,0 +1,91 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import {
createMockRequest,
createMockRouteParams,
parseJsonResponse,
createQueuedMockSupabase,
} from '@/tests/helpers'
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const requireWriteMock = vi.fn()
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
}))
import { GET, PATCH } from '../route'
const params = () => createMockRouteParams({ sector: 'general', slug: 'demo' })
describe('/api/extensions/[sector]/[slug]/settings', () => {
const mockUser = { id: 'user-1', email: '[email protected]' }
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: mockUser, supabase: mockSupabase, error: null })
requireWriteMock.mockResolvedValue({ ok: true })
})
it('GET returns the stored settings value', async () => {
enqueue({ data: { value: { theme: 'dark' } } })
const response = await GET(createMockRequest('/api/extensions/general/demo/settings'), params())
const { status, body } = await parseJsonResponse<{ data: { theme: string } }>(response)
expect(status).toBe(200)
expect(body.data.theme).toBe('dark')
})
it('PATCH returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: mockSupabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const response = await PATCH(
createMockRequest('/api/extensions/general/demo/settings', { method: 'PATCH', body: { b: 2 } }),
params(),
)
expect(response.status).toBe(401)
})
it('PATCH returns 403 for a viewer', async () => {
requireWriteMock.mockResolvedValue({
ok: false,
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
})
const response = await PATCH(
createMockRequest('/api/extensions/general/demo/settings', { method: 'PATCH', body: { b: 2 } }),
params(),
)
expect(response.status).toBe(403)
})
it('PATCH merges and upserts settings (happy path)', async () => {
enqueue({ data: { value: { a: 1 } } }) // existing settings
enqueue({ data: { value: { a: 1, b: 2 } }, error: null }) // upsert
const response = await PATCH(
createMockRequest('/api/extensions/general/demo/settings', { method: 'PATCH', body: { b: 2 } }),
params(),
)
const { status, body } = await parseJsonResponse<{ data: { a: number; b: number } }>(response)
expect(status).toBe(200)
expect(body.data).toEqual({ a: 1, b: 2 })
})
})
@@ -0,0 +1,65 @@
import { NextResponse } from 'next/server'
import { withRouteContext } from '@/lib/api/with-route-context'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
export const GET = withRouteContext<{ params: Promise<{ sector: string; slug: string }> }>(
'extension.settings.get',
async (_request, { supabase, companyId }, { params }) => {
const { sector, slug } = await params
const extensionId = `${sector}/${slug}`
const { data } = await supabase
.from('extension_data')
.select('value')
.eq('company_id', companyId)
.eq('extension_id', extensionId)
.eq('key', 'settings')
.single()
return NextResponse.json({ data: data?.value ?? {} })
},
)
export const PATCH = withRouteContext<{ params: Promise<{ sector: string; slug: string }> }>(
'extension.settings.update',
async (request, { supabase, user, companyId }, { params }) => {
const { sector, slug } = await params
const body = await request.json()
const extensionId = `${sector}/${slug}`
// Get existing settings and merge
const { data: existing } = await supabase
.from('extension_data')
.select('value')
.eq('company_id', companyId)
.eq('extension_id', extensionId)
.eq('key', 'settings')
.single()
const mergedSettings = { ...(existing?.value ?? {}), ...body }
const { data, error } = await supabase
.from('extension_data')
.upsert(
{
user_id: user.id,
company_id: companyId,
extension_id: extensionId,
key: 'settings',
value: mergedSettings,
},
{ onConflict: 'user_id,extension_id,key' }
)
.select()
.single()
if (error) {
return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
}
return NextResponse.json({ data: data.value })
},
{ requireWrite: true },
)
@@ -0,0 +1,72 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const mocks = vi.hoisted(() => ({
from: vi.fn(),
delete: vi.fn(),
lte: vi.fn(),
createServiceClient: vi.fn(),
}))
vi.mock('@/lib/supabase/server', () => ({ createServiceClient: mocks.createServiceClient }))
vi.mock('@/lib/observability', () => ({ captureException: vi.fn(), captureMessage: vi.fn() }))
import { GET } from '../route'
describe('provider OAuth expiry cleanup', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.stubEnv('CRON_SECRET', 'test-cron-secret')
vi.useFakeTimers()
vi.setSystemTime(new Date('2026-09-05T12:00:00Z'))
mocks.createServiceClient.mockReturnValue({ from: mocks.from })
mocks.from.mockReturnValue({ delete: mocks.delete })
mocks.delete.mockReturnValue({ lte: mocks.lte })
mocks.lte.mockResolvedValue({ count: 3, error: null })
})
afterEach(() => {
vi.unstubAllEnvs()
vi.useRealTimers()
})
function request(authorization = 'Bearer test-cron-secret') {
return new Request('https://app.accounted.se/api/extensions/arcim-migration/cleanup/cron', {
headers: authorization ? { authorization } : {},
})
}
it.each(['', 'Bearer wrong-secret'])('rejects unauthorized requests before database access (%s)', async (authorization) => {
const response = await GET(request(authorization))
expect(response.status).toBe(401)
expect(mocks.createServiceClient).not.toHaveBeenCalled()
})
it('fails closed when the cron secret is not configured', async () => {
vi.stubEnv('CRON_SECRET', '')
expect((await GET(request())).status).toBe(401)
expect(mocks.createServiceClient).not.toHaveBeenCalled()
})
it('deletes only rows that have reached expiry and reports the count', async () => {
const response = await GET(request())
expect(response.status).toBe(200)
expect(await response.json()).toEqual({ data: { deleted: 3 } })
expect(mocks.from).toHaveBeenCalledWith('provider_otc')
expect(mocks.delete).toHaveBeenCalledWith({ count: 'exact' })
expect(mocks.lte).toHaveBeenCalledWith('expires_at', '2026-09-05T12:00:00.000Z')
})
it('succeeds when no rows have expired', async () => {
mocks.lte.mockResolvedValue({ count: 0, error: null })
const response = await GET(request())
expect(response.status).toBe(200)
expect(await response.json()).toEqual({ data: { deleted: 0 } })
})
it('reports database failures without exposing their details', async () => {
mocks.lte.mockResolvedValue({ count: null, error: new Error('private database detail') })
const response = await GET(request())
expect(response.status).toBe(500)
expect(await response.text()).not.toContain('private database detail')
})
})
@@ -0,0 +1,18 @@
import { NextResponse } from 'next/server'
import { withCronContext } from '@/lib/api/with-cron-context'
import { createServiceClient } from '@/lib/supabase/server'
// Purge abandoned OAuth states and handoffs even when their consent is retained.
export const GET = withCronContext('cron.provider_oauth_cleanup', async (_request, ctx) => {
const supabase = createServiceClient()
const { count, error } = await supabase
.from('provider_otc')
.delete({ count: 'exact' })
.lte('expires_at', new Date().toISOString())
if (error) throw error
const deleted = count ?? 0
ctx.log.info('provider OAuth cleanup summary', { deleted })
return NextResponse.json({ data: { deleted } })
})
@@ -0,0 +1,405 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { NextResponse } from 'next/server'
/**
* The hourly pass that fills in the rows the migration's bounded hydration
* did not reach. The route is thin: refuse without the cron secret, refuse
* when the extension is off, size every usable consent's register on our
* side, then hand the registers with anything left to the pass smallest
* first, each with its share of the run, and add the counts up.
*/
vi.mock('@/lib/extensions/loader', () => ({ loadExtensions: vi.fn() }))
vi.mock('@/lib/extensions/registry', () => ({ extensionRegistry: { get: vi.fn() } }))
vi.mock('@/lib/auth/cron', () => ({ verifyCronSecret: vi.fn().mockReturnValue(null) }))
const h = vi.hoisted(() => ({
consents: { data: [] as unknown[] | null, error: null as { message: string } | null },
}))
vi.mock('@/lib/auth/api-keys', () => ({
createServiceClientNoCookies: vi.fn(() => ({
from: vi.fn(() => {
const builder: Record<string, unknown> = {}
for (const method of ['select', 'eq', 'not', 'order']) {
builder[method] = vi.fn(() => builder)
}
builder.limit = vi.fn(() => Promise.resolve(h.consents))
return builder
}),
})),
}))
vi.mock('@/extensions/general/arcim-migration/lib/complete-invoice-lines', () => ({
completeMigratedInvoiceLines: vi.fn(),
countRowlessInvoices: vi.fn(),
}))
import { GET, maxDuration, consentIsUsable } from '../route'
import { extensionRegistry } from '@/lib/extensions/registry'
import { verifyCronSecret } from '@/lib/auth/cron'
import {
completeMigratedInvoiceLines,
countRowlessInvoices,
} from '@/extensions/general/arcim-migration/lib/complete-invoice-lines'
const mockRegistryGet = vi.mocked(extensionRegistry.get)
const mockVerifyCronSecret = vi.mocked(verifyCronSecret)
const mockComplete = vi.mocked(completeMigratedInvoiceLines)
const mockCount = vi.mocked(countRowlessInvoices)
const EMPTY = {
candidates: 0, providerInvoices: 0, matched: 0, unmatched: 0, completed: 0, headersUpdated: 0,
totalMismatch: 0, noLinesAtProvider: 0, rowsMismatch: 0, notHydrated: 0, vatUnresolved: 0, failed: 0,
historyAppended: 0, remaining: 0,
hydration: { needed: 0, hydrated: 0, failed: 0, skippedForBudget: 0 }, dryRun: false,
}
const DAY_MS = 24 * 60 * 60 * 1000
const RUN_BUDGET_MS = 240_000
const PER_COMPANY_BUDGET_MS = 120_000
/** A consent whose access token expired `daysAgo` days ago (null: never expires). */
function consent(id: string, companyId: string, daysAgo: number | null, provider = 'fortnox') {
return {
id,
company_id: companyId,
provider,
created_at: '2026-08-13T22:58:24Z',
provider_consent_tokens: {
token_expires_at: daysAgo === null ? null : new Date(Date.now() - daysAgo * DAY_MS).toISOString(),
},
}
}
/** Row-less invoices per company, as the sizing phase finds them. */
function sizes(byCompany: Record<string, number>) {
mockCount.mockImplementation(async (_supabase, companyId) => byCompany[companyId] ?? 0)
}
/** A pass that completes everything it is given and reports the size it found. */
function completesAll(byCompany: Record<string, number>) {
mockComplete.mockImplementation(async ({ companyId }) => {
const n = byCompany[companyId] ?? 0
return { ...EMPTY, candidates: n, matched: n, completed: n, headersUpdated: n }
})
}
function makeRequest() {
return new Request('http://localhost/api/extensions/arcim-migration/complete-invoice-lines/cron', {
headers: { authorization: 'Bearer synthetic-cron-secret' },
})
}
/** Freeze the clock so a share is exactly its constant and the run's spend is what the pass says it spent. */
function freezeClock() {
vi.useFakeTimers({ toFake: ['Date'] })
vi.setSystemTime(new Date('2026-09-06T10:20:00Z'))
}
beforeEach(() => {
vi.clearAllMocks()
mockCount.mockReset()
mockComplete.mockReset()
mockVerifyCronSecret.mockReturnValue(null)
mockRegistryGet.mockReturnValue({ id: 'arcim-migration' } as never)
mockCount.mockResolvedValue(0)
h.consents = { data: [], error: null }
})
afterEach(() => {
vi.useRealTimers()
})
describe('GET /api/extensions/arcim-migration/complete-invoice-lines/cron', () => {
it('reserves the full function window: hydration is rate-limited at the provider', () => {
expect(maxDuration).toBe(300)
})
it('returns 401 when the cron secret is rejected', async () => {
mockVerifyCronSecret.mockReturnValue(NextResponse.json({ error: 'Unauthorized' }, { status: 401 }))
const response = await GET(makeRequest())
expect(response.status).toBe(401)
expect(mockCount).not.toHaveBeenCalled()
expect(mockComplete).not.toHaveBeenCalled()
})
it('returns 503 EXTENSION_DISABLED when the extension is not in the registry', async () => {
mockRegistryGet.mockReturnValue(undefined)
const response = await GET(makeRequest())
const body = await response.json()
expect(response.status).toBe(503)
expect(body.code).toBe('EXTENSION_DISABLED')
expect(mockCount).not.toHaveBeenCalled()
expect(mockComplete).not.toHaveBeenCalled()
})
it('sizes every usable register before the first provider call, then completes them smallest first', async () => {
// 2026-09-05 on prod: the 1 125-invoice register sat on the newest
// consent and used two runs in a row; the 384-invoice one three consents
// older waited both times. Consent age says nothing about work size.
h.consents = {
data: [
consent('c-newest', 'co-big', 0),
consent('c-mid', 'co-small', 1),
consent('c-oldest', 'co-medium', 3),
],
error: null,
}
const work = { 'co-big': 1125, 'co-small': 155, 'co-medium': 384 }
sizes(work)
completesAll(work)
const response = await GET(makeRequest())
const body = await response.json()
expect(response.status).toBe(200)
expect(mockCount.mock.calls.map((c) => c[1])).toEqual(['co-big', 'co-small', 'co-medium'])
expect(mockComplete.mock.calls.map((c) => c[0].companyId)).toEqual(['co-small', 'co-medium', 'co-big'])
expect(mockComplete.mock.calls.map((c) => c[0].consentId)).toEqual(['c-mid', 'c-oldest', 'c-newest'])
// Sizing is a separate phase: the last count lands before the first pass.
expect(Math.max(...mockCount.mock.invocationCallOrder)).toBeLessThan(Math.min(...mockComplete.mock.invocationCallOrder))
expect(body.data).toMatchObject({
consents: 3,
consentsStale: 0,
consentsFailed: 0,
companies: 3,
candidates: 1664,
completed: 1664,
skippedForBudget: 0,
deferred: [],
})
})
it('adds the counts up across the registers it completed', async () => {
h.consents = {
data: [
consent('c-new', 'co-1', 0),
consent('c-old', 'co-2', 22),
consent('c-done', 'co-3', 4, 'visma'),
],
error: null,
}
sizes({ 'co-1': 311, 'co-2': 384, 'co-3': 0 })
mockComplete
.mockResolvedValueOnce({ ...EMPTY, candidates: 311, matched: 311, completed: 300, headersUpdated: 300, notHydrated: 11, remaining: 11 })
.mockResolvedValueOnce({ ...EMPTY, candidates: 384, matched: 384, completed: 384, headersUpdated: 358 })
const response = await GET(makeRequest())
const body = await response.json()
expect(response.status).toBe(200)
expect(mockComplete).toHaveBeenCalledTimes(2)
expect(mockComplete.mock.calls[0][0]).toMatchObject({ companyId: 'co-1', consentId: 'c-new' })
expect(mockComplete.mock.calls[0][0].budgetMs).toBeGreaterThan(0)
expect(mockComplete.mock.calls[0][0].budgetMs).toBeLessThanOrEqual(PER_COMPANY_BUDGET_MS)
// The company with nothing to complete is sized, never passed, not counted.
expect(body.data).toMatchObject({
consents: 3,
consentsStale: 0,
consentsFailed: 0,
companies: 2,
candidates: 695,
completed: 684,
headersUpdated: 658,
remaining: 11,
notHydrated: 11,
skippedForBudget: 0,
})
})
it('skips a register with nothing left: no pass, no provider contact, no budget spent', async () => {
freezeClock()
h.consents = {
data: [consent('c-done', 'co-done', 0), consent('c-todo', 'co-todo', 1)],
error: null,
}
sizes({ 'co-done': 0, 'co-todo': 12 })
completesAll({ 'co-todo': 12 })
const response = await GET(makeRequest())
const body = await response.json()
expect(response.status).toBe(200)
expect(mockCount).toHaveBeenCalledTimes(2)
expect(mockComplete).toHaveBeenCalledTimes(1)
// The register behind it still gets a whole share: sizing cost it nothing.
expect(mockComplete.mock.calls[0][0]).toMatchObject({
companyId: 'co-todo', consentId: 'c-todo', budgetMs: PER_COMPANY_BUDGET_MS,
})
expect(body.data).toMatchObject({ consents: 2, companies: 1, candidates: 12, completed: 12, skippedForBudget: 0 })
})
it('stops at the run deadline and defers what it did not reach, which is the largest registers', async () => {
freezeClock()
h.consents = {
data: [
consent('c-1', 'co-big', 0),
consent('c-2', 'co-small', 1),
consent('c-3', 'co-medium', 2),
],
error: null,
}
const work = { 'co-big': 1125, 'co-small': 155, 'co-medium': 384 }
sizes(work)
// Each register uses the whole share it is given: two shares fill the run.
mockComplete.mockImplementation(async ({ companyId, budgetMs }) => {
vi.setSystemTime(Date.now() + (budgetMs ?? 0))
const n = work[companyId as keyof typeof work]
return { ...EMPTY, candidates: n, matched: n, completed: n, headersUpdated: n }
})
const response = await GET(makeRequest())
const body = await response.json()
expect(response.status).toBe(200)
expect(mockComplete.mock.calls.map((c) => c[0].companyId)).toEqual(['co-small', 'co-medium'])
expect(mockComplete.mock.calls.map((c) => c[0].budgetMs)).toEqual([PER_COMPANY_BUDGET_MS, RUN_BUDGET_MS - PER_COMPANY_BUDGET_MS])
expect(body.data).toMatchObject({
consents: 3,
companies: 2,
candidates: 539,
skippedForBudget: 1,
deferred: [{ companyId: 'co-big', candidates: 1125 }],
})
})
it('gives a register reached late the remainder of the run, not a whole share', async () => {
freezeClock()
h.consents = {
data: [consent('c-1', 'co-a', 0), consent('c-2', 'co-b', 1), consent('c-3', 'co-c', 2)],
error: null,
}
const work = { 'co-a': 10, 'co-b': 20, 'co-c': 30 }
sizes(work)
// 120 s + 100 s spent: 20 s remain, exactly the minimum worth starting on.
const spend: Record<string, number> = { 'co-a': 120_000, 'co-b': 100_000, 'co-c': 5_000 }
mockComplete.mockImplementation(async ({ companyId }) => {
vi.setSystemTime(Date.now() + spend[companyId])
const n = work[companyId as keyof typeof work]
return { ...EMPTY, candidates: n, matched: n, completed: n }
})
const response = await GET(makeRequest())
const body = await response.json()
expect(response.status).toBe(200)
expect(mockComplete.mock.calls.map((c) => [c[0].companyId, c[0].budgetMs])).toEqual([
['co-a', PER_COMPANY_BUDGET_MS],
['co-b', PER_COMPANY_BUDGET_MS],
['co-c', 20_000],
])
expect(body.data).toMatchObject({ companies: 3, skippedForBudget: 0 })
})
it('isolates a failing count: that consent is reported failed and the others still run', async () => {
h.consents = {
data: [consent('c-broken', 'co-broken', 0), consent('c-live', 'co-live', 1)],
error: null,
}
mockCount.mockImplementation(async (_supabase, companyId) => {
if (companyId === 'co-broken') throw new Error('canceling statement due to statement timeout')
return 7
})
completesAll({ 'co-live': 7 })
const response = await GET(makeRequest())
const body = await response.json()
expect(response.status).toBe(200)
expect(mockComplete.mock.calls.map((c) => c[0].companyId)).toEqual(['co-live'])
expect(body.data).toMatchObject({ consents: 2, consentsFailed: 1, companies: 1, completed: 7 })
})
it('isolates a failing pass: the others still run and the failure is counted', async () => {
h.consents = {
data: [consent('c-revoked', 'co-1', 1), consent('c-live', 'co-2', 2)],
error: null,
}
sizes({ 'co-1': 5, 'co-2': 5 })
mockComplete
.mockRejectedValueOnce(new Error('Token refresh failed for fortnox; the connection must be re-authorized'))
.mockResolvedValueOnce({ ...EMPTY, candidates: 5, matched: 5, completed: 5, headersUpdated: 5 })
const response = await GET(makeRequest())
const body = await response.json()
expect(response.status).toBe(200)
expect(mockComplete).toHaveBeenCalledTimes(2)
// Equal sizes keep the scan order: the newer consent first.
expect(mockComplete.mock.calls.map((c) => c[0].consentId)).toEqual(['c-revoked', 'c-live'])
expect(body.data).toMatchObject({ consents: 2, consentsFailed: 1, companies: 1, completed: 5 })
})
it('skips consents whose credentials can no longer be refreshed, by token state not consent age', async () => {
// Fortnox refresh tokens live 45 days and rotate on every refresh: a pair
// whose access token expired 46 days ago is dead however young the consent
// row is. A pair refreshed yesterday on a consent from months ago is live.
// A token without an expiry (Bokio) never goes stale.
h.consents = {
data: [
{ ...consent('c-dead', 'co-1', 46), created_at: '2026-09-01T00:00:00Z' },
{ ...consent('c-live', 'co-2', 1), created_at: '2026-04-01T00:00:00Z' },
consent('c-bokio', 'co-3', null, 'bokio'),
{ ...consent('c-no-token', 'co-4', 1), provider_consent_tokens: null },
],
error: null,
}
sizes({ 'co-1': 1, 'co-2': 1, 'co-3': 1, 'co-4': 1 })
completesAll({ 'co-2': 1, 'co-3': 1 })
const response = await GET(makeRequest())
const body = await response.json()
expect(response.status).toBe(200)
// A dead consent is not even sized: nothing about it can be acted on.
expect(mockCount.mock.calls.map((c) => c[1])).toEqual(['co-2', 'co-3'])
expect(mockComplete.mock.calls.map((c) => c[0].consentId)).toEqual(['c-live', 'c-bokio'])
expect(body.data).toMatchObject({ consents: 2, consentsStale: 2 })
})
it('does not page: every usable consent is sized, not only the newest few', async () => {
// 57 consents were accepted in the last 60 days on prod (2026-09-05); a
// fixed page of the newest ones would leave older companies with row-less
// invoices waiting forever behind companies that are already done.
h.consents = {
data: Array.from({ length: 80 }, (_, i) => consent(`c-${i}`, `co-${i}`, 1)),
error: null,
}
mockCount.mockResolvedValue(1)
mockComplete.mockResolvedValue({ ...EMPTY, candidates: 1, matched: 1, completed: 1 })
const response = await GET(makeRequest())
const body = await response.json()
expect(response.status).toBe(200)
expect(mockCount).toHaveBeenCalledTimes(80)
expect(mockComplete).toHaveBeenCalledTimes(80)
expect(body.data).toMatchObject({ consents: 80, companies: 80, skippedForBudget: 0 })
})
it('consentIsUsable reads the token row, tolerating either embed cardinality', () => {
const now = Date.now()
const array = { ...consent('c', 'co', 1), provider_consent_tokens: [{ token_expires_at: new Date(now - DAY_MS).toISOString() }] }
const stale = { ...consent('c', 'co', 1), provider_consent_tokens: [{ token_expires_at: new Date(now - 50 * DAY_MS).toISOString() }] }
const garbage = { ...consent('c', 'co', 1), provider_consent_tokens: { token_expires_at: 'not a date' } }
expect(consentIsUsable(array, now)).toBe(true)
expect(consentIsUsable(stale, now)).toBe(false)
expect(consentIsUsable(garbage, now)).toBe(false)
expect(consentIsUsable({ ...consent('c', 'co', 1), provider_consent_tokens: [] }, now)).toBe(false)
})
it('surfaces a failed consent lookup instead of reporting an empty run', async () => {
h.consents = { data: null, error: { message: 'relation does not exist' } }
const response = await GET(makeRequest())
expect(response.status).toBeGreaterThanOrEqual(500)
expect(mockCount).not.toHaveBeenCalled()
expect(mockComplete).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,224 @@
import { NextResponse } from 'next/server'
import { loadExtensions } from '@/lib/extensions/loader'
import { extensionRegistry } from '@/lib/extensions/registry'
import { withCronContext } from '@/lib/api/with-cron-context'
import { createServiceClientNoCookies } from '@/lib/auth/api-keys'
import {
completeMigratedInvoiceLines,
countRowlessInvoices,
type CompleteInvoiceLinesResult,
} from '@/extensions/general/arcim-migration/lib/complete-invoice-lines'
/**
* GET /api/extensions/arcim-migration/complete-invoice-lines/cron: fetch the
* rows (and the VAT split) for migrated sales invoices that were imported
* without them.
*
* The migration hydrates the provider's detail form inside a fixed budget
* and reports the shortfall; this is what picks the shortfall up. Every run
* walks the accepted consents whose credentials can still be used, in two
* phases. First it sizes each register on our side: one indexed count of the
* invoices still without rows per consent, no provider call. Then it hands
* the registers with anything left to the pass smallest first, each within
* its share of the run. Shortest job first: a register that fits its share
* is finished this run whatever was accepted after it, and a register that
* needs several runs takes what is left of each instead of pushing every
* older company back by an hour per run (on 2026-09-05 a 1 125-invoice
* register on the newest consent used two runs in a row while a 384-invoice
* register three consents older, about 100 s of work, was skipped for budget
* both times). Nothing is stored between runs: the counts are taken fresh
* every hour, so a register the wizard or an earlier run finished simply
* stops appearing.
*
* What a run does not reach is, by construction, its largest registers. They
* are reported as deferred with their counts in the run summary and in the
* response, so a register that is deferred hour after hour (possible only
* while smaller registers keep arriving faster than the run clears them) is
* visible rather than silent. Scheduled hourly in vercel.json (and the
* Docker crontabs); a company the size of Clearstoq (1 125 invoices) is done
* after two or three runs.
*
* "Can still be used" is read off the token row, not the consent's age:
* Fortnox issues a new refresh token on every refresh and each one lives 45
* days, so a pair whose access token expired more than 45 days ago has not
* been refreshed since and its refresh token is dead. Trying such a consent
* every hour would only log the same PROVIDER_AUTH_EXPIRED; when the company
* reconnects through the wizard, the token row is renewed and the next run
* finds it here. A token without an expiry (Bokio's private tokens) is
* always eligible.
*/
export const maxDuration = 300
/** Leave the function a margin for the DB writes after the last fetch. */
const RUN_BUDGET_MS = 240_000
/** One company's share of provider detail fetches per run. */
const PER_COMPANY_BUDGET_MS = 120_000
/** Below this the registers still in line (the largest ones) wait for the next run. */
const MIN_COMPANY_BUDGET_MS = 20_000
/**
* A token pair not refreshed for this long cannot be refreshed any more
* (Fortnox: refresh tokens live 45 days and rotate on every refresh).
*/
const TOKEN_STALE_DAYS = 45
/** Hard safety on the consent scan; prod holds ~120 accepted consents in total. */
const MAX_CONSENTS_SCANNED = 500
interface ConsentRow {
id: string
company_id: string
provider: string | null
created_at: string
provider_consent_tokens: { token_expires_at: string | null } | { token_expires_at: string | null }[] | null
}
/** A usable consent whose company still has invoices without rows, sized by that count. */
interface Register {
consent: ConsentRow
candidates: number
}
/** The consent's token row, whichever cardinality PostgREST rendered it with. */
function tokenOf(consent: ConsentRow): { token_expires_at: string | null } | null {
const tokens = consent.provider_consent_tokens
if (!tokens) return null
return Array.isArray(tokens) ? (tokens[0] ?? null) : tokens
}
/** Does this consent still hold credentials a run can use? */
export function consentIsUsable(consent: ConsentRow, now: number): boolean {
const token = tokenOf(consent)
if (!token) return false
if (token.token_expires_at === null) return true
const expiredAt = Date.parse(token.token_expires_at)
if (Number.isNaN(expiredAt)) return false
return now - expiredAt <= TOKEN_STALE_DAYS * 24 * 60 * 60 * 1000
}
export const GET = withCronContext('cron.arcim_migration_complete_invoice_lines', async (_request, ctx) => {
loadExtensions()
// Physical routes under app/api/extensions/<id>/ compile into every build;
// the registry (generated from extensions.config.json) is what switches an
// extension on. A scheduled-but-disabled cron must fail visibly.
if (!extensionRegistry.get('arcim-migration')) {
ctx.log.warn('arcim-migration extension is not enabled; cron refused')
return NextResponse.json(
{ error: 'Migration extension is not enabled', code: 'EXTENSION_DISABLED' },
{ status: 503 },
)
}
const supabase = createServiceClientNoCookies()
const { data, error } = await supabase
.from('provider_consents')
.select('id, company_id, provider, created_at, provider_consent_tokens(token_expires_at)')
.eq('status', 1)
.not('provider', 'is', null)
// A stable scan order under the cap, and the tiebreak between registers
// of equal size (the sort below is stable): the newer consent goes first.
.order('created_at', { ascending: false })
.limit(MAX_CONSENTS_SCANNED)
if (error) {
throw new Error(`provider_consents lookup failed: ${error.message}`)
}
const now = Date.now()
const scanned = (data ?? []) as ConsentRow[]
const usable = scanned.filter((consent) => consentIsUsable(consent, now))
const deadline = now + RUN_BUDGET_MS
// Phase 1: size every register on our side. No consent is touched here, so
// a company with nothing left costs one count and no token refresh.
const registers: Register[] = []
const sizing = await ctx.forEach('consent', usable, async (consent) => {
const candidates = await countRowlessInvoices(supabase, consent.company_id)
if (candidates > 0) registers.push({ consent, candidates })
})
registers.sort((a, b) => a.candidates - b.candidates)
if (registers.length > 0) {
ctx.log.info('registers with row-less invoices, smallest first', {
registers: registers.map((r) => ({
companyId: r.consent.company_id, provider: r.consent.provider, candidates: r.candidates,
})),
})
}
// Phase 2: complete them smallest first, each within its share of the run.
const deferred: { companyId: string; candidates: number }[] = []
const totals = {
companies: 0,
candidates: 0,
completed: 0,
headersUpdated: 0,
remaining: 0,
notHydrated: 0,
totalMismatch: 0,
rowsMismatch: 0,
failed: 0,
historyAppended: 0,
}
const completing = await ctx.forEach('register', registers, async ({ consent, candidates }, itemCtx) => {
const budgetMs = Math.min(PER_COMPANY_BUDGET_MS, deadline - Date.now())
if (budgetMs < MIN_COMPANY_BUDGET_MS) {
deferred.push({ companyId: consent.company_id, candidates })
return
}
const result: CompleteInvoiceLinesResult = await completeMigratedInvoiceLines({
supabase,
companyId: consent.company_id,
consentId: consent.id,
budgetMs,
})
// The pass re-reads our side before it touches the consent; a register
// the wizard finished between the count and now is neither worked on nor
// counted as a company.
if (result.candidates === 0) return
totals.companies++
totals.candidates += result.candidates
totals.completed += result.completed
totals.headersUpdated += result.headersUpdated
totals.remaining += result.remaining
totals.notHydrated += result.notHydrated
totals.totalMismatch += result.totalMismatch
totals.rowsMismatch += result.rowsMismatch
totals.failed += result.failed
totals.historyAppended += result.historyAppended
itemCtx.log.info('migrated invoice rows completed for company', {
companyId: consent.company_id,
provider: consent.provider,
candidates: result.candidates,
matched: result.matched,
completed: result.completed,
remaining: result.remaining,
notHydrated: result.notHydrated,
totalMismatch: result.totalMismatch,
rowsMismatch: result.rowsMismatch,
failed: result.failed,
historyAppended: result.historyAppended,
hydration: result.hydration,
})
})
if (deferred.length > 0) {
ctx.log.warn('run deadline reached; the largest registers wait for the next run', { deferred })
}
const summary = {
consents: usable.length,
consentsStale: scanned.length - usable.length,
consentsFailed: sizing.failed + completing.failed,
skippedForBudget: deferred.length,
deferred,
...totals,
}
ctx.log.info('complete-invoice-lines run finished', summary)
return NextResponse.json({ data: summary })
})
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,366 @@
import { createServiceRoleClient } from '@/lib/supabase/service-client'
import { NextResponse } from 'next/server'
import { withCronContext } from '@/lib/api/with-cron-context'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { performSync, saveExtensionData } from '@/extensions/general/cloud-backup/lib/sync'
import { isScheduleDue } from '@/extensions/general/cloud-backup/lib/schedule'
import { CLOUD_PROVIDERS } from '@/extensions/general/cloud-backup/lib/provider-registry'
import {
sendBackupFailureAlert,
shouldSendBackupAlert,
type BackupAlertKind,
} from '@/extensions/general/cloud-backup/lib/backup-alert'
import type { CloudStorageProvider } from '@/extensions/general/cloud-backup/lib/cloud-provider'
import type {
CloudConnection,
CloudSchedule,
} from '@/extensions/general/cloud-backup/types'
/**
* GET /api/extensions/cloud-backup/auto-sync/cron
*
* Runs hourly. Finds every (company, provider) pair whose auto-sync is due
* (daily slot has passed and no attempt has run since it: see `isScheduleDue`)
* and triggers a full backup for each via the shared `performSync()` helper.
* Pairs left over when a run hits its time budget stay due and are picked up
* by the next hourly run instead of losing the day.
*
* Providers are scheduled independently: a company can back up to Google Drive
* nightly and to Dropbox weekly, and a Dropbox failure never marks the Drive
* backup unhealthy. Each provider keeps its own schedule record, failure
* counter and alert throttle.
*
* Failures increment `consecutive_failures` on that provider's schedule; alert
* emails go out on dead tokens (once per incident) and repeated failures
* (threshold in `backup-alert.ts`), throttled per company and provider.
*
* Uses the service role client: no user session, no RLS. Each row in
* `extension_data` carries its own `user_id` (the user who configured the
* schedule), which we use as the "actor" when writing back the sync result.
*/
export const GET = withCronContext('cron.cloud_backup_auto_sync', async (_request, ctx) => {
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY
if (!supabaseUrl || !supabaseServiceKey) {
return errorResponseFromCode('INTERNAL_ERROR', ctx.log, {
requestId: ctx.requestId,
details: { reason: 'Missing Supabase configuration' },
})
}
const supabase = createServiceRoleClient(supabaseUrl, supabaseServiceKey)
const now = new Date()
const origin = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'
// Every provider's schedules are fetched, but only providers this deployment
// has credentials for are run: without them every sync would fail on the
// token refresh and burn the failure counter. Schedules belonging to an
// unconfigured provider are counted and logged rather than dropped silently,
// because that is a deployment mistake someone needs to see.
const providerByScheduleKey = new Map<string, CloudStorageProvider>(
CLOUD_PROVIDERS.map((p) => [p.keys.schedule, p])
)
const { data: rows, error } = await supabase
.from('extension_data')
.select('company_id, user_id, key, value')
.eq('extension_id', 'cloud-backup')
.in('key', [...providerByScheduleKey.keys()])
if (error) {
ctx.log.error('failed to fetch schedules', error, {
message: error.message,
code: error.code,
})
return errorResponse(error, ctx.log, { requestId: ctx.requestId })
}
if (!rows || rows.length === 0) {
return NextResponse.json({ message: 'No schedules configured', processed: 0 })
}
interface Candidate {
companyId: string
userId: string
provider: CloudStorageProvider
schedule: CloudSchedule
}
const candidates: Candidate[] = []
const unconfigured = new Map<string, number>()
for (const row of rows) {
const provider = providerByScheduleKey.get(row.key as string)
if (!provider) continue
const schedule = row.value as CloudSchedule | null
if (!isScheduleDue(schedule, now)) continue
if (!provider.isConfigured()) {
unconfigured.set(provider.id, (unconfigured.get(provider.id) ?? 0) + 1)
continue
}
candidates.push({
companyId: row.company_id as string,
userId: row.user_id as string,
provider,
schedule: schedule as CloudSchedule,
})
}
if (unconfigured.size > 0) {
// Companies are expecting a backup that this deployment cannot perform.
ctx.log.error(
'due backups skipped: provider has no OAuth credentials in this environment',
undefined,
{ skipped: Object.fromEntries(unconfigured) }
)
}
if (candidates.length === 0) {
return NextResponse.json({
message: 'No companies due this hour',
checked: rows.length,
processed: 0,
})
}
// Connections flagged needs_reauth carry a permanently dead refresh token
// (the provider returned 400 invalid_grant): skip them instead of retrying
// every night. They stay visible in the UI until the user reconnects.
const connectionKeys = [
...new Set(candidates.map((c) => c.provider.keys.connection)),
]
const { data: connectionRows, error: connectionError } = await supabase
.from('extension_data')
.select('company_id, key, value')
.eq('extension_id', 'cloud-backup')
.in('key', connectionKeys)
.in('company_id', [...new Set(candidates.map((c) => c.companyId))])
if (connectionError) {
// Fail open: without connection data we cannot tell who needs reauth,
// so fall back to attempting everyone (performSync re-flags dead tokens).
ctx.log.warn('failed to fetch connections for reauth check', {
message: connectionError.message,
})
}
// Keyed by company + connection key: one company can hold a healthy Drive
// connection and a dead Dropbox one at the same time.
const connectionByCompanyAndKey = new Map<string, CloudConnection>()
for (const r of connectionRows ?? []) {
const value = r.value as CloudConnection | null
if (value) connectionByCompanyAndKey.set(`${r.company_id}:${r.key}`, value)
}
const startTime = Date.now()
const TIME_BUDGET_MS = 250_000 // 4m10s: leaves 50s margin below Vercel's 300s Pro limit
const results: {
companyId: string
provider: string
status: 'success' | 'error' | 'skipped'
error?: string
}[] = []
/**
* Send a failure alert if warranted and return the new last_alert_at.
* Best-effort: alert failures are logged inside sendBackupFailureAlert.
*/
const maybeAlert = async (params: {
companyId: string
userId: string
providerLabel: string
kind: BackupAlertKind
consecutiveFailures: number
errorMessage: string | null
lastAlertAt: string | null | undefined
}): Promise<string | null> => {
const prior = params.lastAlertAt ?? null
if (
!shouldSendBackupAlert({
kind: params.kind,
consecutiveFailures: params.consecutiveFailures,
lastAlertAt: prior,
now: new Date(),
})
) {
return prior
}
const sent = await sendBackupFailureAlert(supabase, {
companyId: params.companyId,
userId: params.userId,
providerLabel: params.providerLabel,
kind: params.kind,
consecutiveFailures: params.consecutiveFailures,
errorMessage: params.errorMessage,
origin,
})
return sent.sent ? new Date().toISOString() : prior
}
for (const candidate of candidates) {
if (Date.now() - startTime > TIME_BUDGET_MS) {
ctx.log.info('time budget reached', {
processedSoFar: results.length,
skipped: candidates.length - results.length,
})
break
}
const { companyId, userId, provider, schedule } = candidate
const scheduleKey = provider.keys.schedule
const connection = connectionByCompanyAndKey.get(
`${companyId}:${provider.keys.connection}`
)
if (connection?.status === 'needs_reauth') {
// Do not touch last_auto_sync_* here: the schedule keeps showing the
// failure from the night the dead token was detected. But make sure the
// incident has been alerted once: a token can go dead via a manual sync
// (which never emails) and would otherwise stay silent forever.
const alertedSinceIncident =
schedule.last_alert_at &&
connection.needs_reauth_at &&
new Date(schedule.last_alert_at).getTime() >=
new Date(connection.needs_reauth_at).getTime()
if (!alertedSinceIncident) {
const lastAlertAt = await maybeAlert({
companyId,
userId,
providerLabel: provider.label,
kind: 'needs_reauth',
consecutiveFailures: schedule.consecutive_failures ?? 0,
errorMessage: null,
lastAlertAt: schedule.last_alert_at,
})
if (lastAlertAt !== (schedule.last_alert_at ?? null)) {
await saveExtensionData(supabase, companyId, userId, scheduleKey, {
...schedule,
last_alert_at: lastAlertAt,
}).catch((persistErr) => {
ctx.log.error('failed to persist alert state', persistErr as Error, {
companyId,
provider: provider.id,
})
})
}
}
results.push({
companyId,
provider: provider.id,
status: 'skipped',
error: 'needs_reauth',
})
continue
}
try {
const syncResult = await performSync({
supabase,
companyId,
userId,
origin,
includeDocuments: true,
allowDocumentFallback: true,
provider,
})
const consecutiveFailures = syncResult.ok
? 0
: (schedule.consecutive_failures ?? 0) + 1
const safeSyncError = syncResult.ok ? null : getErrorMessage(syncResult.message)
let lastAlertAt = schedule.last_alert_at ?? null
if (!syncResult.ok) {
lastAlertAt = await maybeAlert({
companyId,
userId,
providerLabel: provider.label,
kind: syncResult.reason === 'needs_reauth' ? 'needs_reauth' : 'repeated_failures',
consecutiveFailures,
errorMessage: safeSyncError,
lastAlertAt,
})
}
const updated: CloudSchedule = {
...schedule,
last_auto_sync_at: new Date().toISOString(),
last_auto_sync_status: syncResult.ok ? 'success' : 'error',
last_auto_sync_error: safeSyncError,
consecutive_failures: consecutiveFailures,
last_alert_at: lastAlertAt,
}
await saveExtensionData(supabase, companyId, userId, scheduleKey, updated)
results.push({
companyId,
provider: provider.id,
status: syncResult.ok ? 'success' : 'error',
error: safeSyncError ?? undefined,
})
} catch (err) {
const safeMessage = getErrorMessage(err)
ctx.log.error('cloud backup sync failed for company', err as Error, {
companyId,
provider: provider.id,
})
const consecutiveFailures = (schedule.consecutive_failures ?? 0) + 1
const lastAlertAt = await maybeAlert({
companyId,
userId,
providerLabel: provider.label,
kind: 'repeated_failures',
consecutiveFailures,
errorMessage: safeMessage.slice(0, 200),
lastAlertAt: schedule.last_alert_at,
})
const updated: CloudSchedule = {
...schedule,
last_auto_sync_at: new Date().toISOString(),
last_auto_sync_status: 'error',
last_auto_sync_error: safeMessage.slice(0, 200),
consecutive_failures: consecutiveFailures,
last_alert_at: lastAlertAt,
}
await saveExtensionData(supabase, companyId, userId, scheduleKey, updated).catch(
(persistErr) => {
ctx.log.error('failed to persist failure state', persistErr as Error, {
companyId,
provider: provider.id,
})
},
)
results.push({
companyId,
provider: provider.id,
status: 'error',
error: safeMessage,
})
}
}
const successCount = results.filter((r) => r.status === 'success').length
const errorCount = results.filter((r) => r.status === 'error').length
const skippedCount = results.filter((r) => r.status === 'skipped').length
ctx.log.info('cloud backup cron summary', {
processed: results.length,
succeeded: successCount,
failed: errorCount,
skipped: skippedCount,
})
return NextResponse.json({
checked: rows.length,
candidates: candidates.length,
processed: results.length,
successes: successCount,
errors: errorCount,
skipped: skippedCount,
results,
})
})
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,178 @@
/**
* Interim "finalizing" page for the Enable Banking OAuth callback.
*
* The callback has seconds of unavoidable server work between the bank's
* redirect and our own (session exchange with Enable Banking, account
* mirroring, audit events). A classic 307 would leave the user staring at a
* blank browser tab for that whole window, which reads as "the connection
* failed" and provokes retries (and, historically, duplicate connections).
*
* Instead the route streams this page in two chunks:
* 1. renderFinalizeShell() - flushed immediately, before any slow work:
* branded spinner + "Slutför anslutningen".
* 2. renderFinalizeRedirect() - flushed when the work is done: script +
* meta-refresh + visible fallback link that
* navigates to the settings page.
*
* The page is standalone HTML (no app bundle), styled to match the editorial
* monochrome design system; see app/api/mcp-oauth/authorize for the sibling
* standalone page this mirrors. Swedish-only, like the rest of the
* enable-banking extension surfaces.
*
* Inline scripts are nonce-bound (ASVS V3.3): the route generates a
* per-request nonce, stamps it on every <script> tag here, and sets a
* response-level CSP with script-src 'nonce-...'. The global next.config CSP
* (which still carries 'unsafe-inline' for the app bundle) also applies;
* browsers enforce the intersection, so an injected inline script without
* the nonce is blocked on this response.
*/
import { escapeHtml } from '@/lib/email/user-text'
/**
* Opening chunk: full document head, styles, spinner and heading, plus a
* watchdog that reveals an escape hatch if the server work takes abnormally
* long (dead function, hung upstream). Deliberately does NOT close <body>:
* the redirect chunk does. `cspNonce` must match the script-src nonce the
* route puts in the response's Content-Security-Policy header.
*/
export function renderFinalizeShell(bankName: string | null, cspNonce: string): string {
const heading = bankName
? `Slutf&ouml;r anslutningen till ${escapeHtml(bankName)}&hellip;`
: 'Slutf&ouml;r bankanslutningen&hellip;'
return `<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex, nofollow">
<meta name="color-scheme" content="light">
<title>Slutf&ouml;r bankanslutningen</title>
<style>
:root {
--bg: hsl(0 0% 100%);
--border: hsl(45 5% 85%);
--fg: hsl(0 0% 9%);
--fg-muted: hsl(0 0% 40%);
--fg-faint: hsl(0 0% 55%);
--warm-accent: hsl(38 45% 52%);
}
* { margin: 0; padding: 0; box-sizing: border-box; }
html { -webkit-text-size-adjust: 100%; }
body {
font-family: 'Geist', -apple-system, system-ui, 'Segoe UI', sans-serif;
background: var(--bg);
color: var(--fg);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 100vh;
padding: 2rem 1.5rem;
font-size: 14px;
line-height: 1.5;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
main {
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
max-width: 26rem;
}
.spinner {
width: 28px;
height: 28px;
border: 2px solid var(--border);
border-top-color: var(--fg);
border-radius: 50%;
animation: spin 0.8s linear infinite;
margin-bottom: 1.5rem;
}
@keyframes spin { to { transform: rotate(360deg); } }
@media (prefers-reduced-motion: reduce) {
/* Keep a slow spin: a frozen spinner reads as a hung page. */
.spinner { animation-duration: 2.5s; }
}
.eyebrow {
display: inline-flex;
align-items: center;
gap: 0.375rem;
font-size: 0.6875rem;
font-weight: 500;
text-transform: uppercase;
letter-spacing: 0.08em;
color: var(--fg-faint);
margin-bottom: 0.875rem;
}
.eyebrow::before {
content: "";
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--warm-accent);
}
h1 {
font-family: 'Hedvig Letters Serif', Georgia, 'Times New Roman', serif;
font-size: 1.625rem;
font-weight: 400;
letter-spacing: -0.018em;
line-height: 1.15;
margin-bottom: 0.625rem;
}
.lede {
font-size: 0.875rem;
color: var(--fg-muted);
line-height: 1.55;
}
.slow {
margin-top: 1.5rem;
font-size: 0.8125rem;
color: var(--fg-muted);
line-height: 1.55;
}
.slow[hidden] { display: none; }
a { color: var(--fg); text-decoration: underline; text-underline-offset: 2px; }
.fallback { margin-top: 1.25rem; font-size: 0.8125rem; }
</style>
</head>
<body>
<main role="main" aria-busy="true">
<div class="spinner" aria-hidden="true"></div>
<div class="eyebrow">Bankanslutning</div>
<h1>${heading}</h1>
<p class="lede">Vi bekr&auml;ftar anslutningen och h&auml;mtar dina konton fr&aring;n banken. Du skickas vidare automatiskt.</p>
<p class="slow" id="slow-notice" hidden>
Det tar l&auml;ngre tid &auml;n vanligt. V&auml;nta g&auml;rna kvar en stund till,
eller <a href="/settings/banking">g&aring; till bankinst&auml;llningarna</a>.
</p>
</main>
<script nonce="${escapeHtml(cspNonce)}">
setTimeout(function () {
var el = document.getElementById('slow-notice');
if (el) el.hidden = false;
}, 30000);
</script>
`
}
/**
* Closing chunk: navigates to `url` the instant it arrives. Three mechanisms,
* most graceful first: location.replace (keeps the callback URL out of
* history so Back cannot re-trigger it), a meta refresh for no-JS, and a
* visible link as the last resort.
*/
export function renderFinalizeRedirect(url: string, cspNonce: string): string {
// <-escape so a "</script>" sequence can never terminate the block
// early, even though our URLs are app-relative and query-encoded.
const jsUrl = JSON.stringify(url).replace(/</g, '\\u003c')
return ` <script nonce="${escapeHtml(cspNonce)}">window.location.replace(${jsUrl});</script>
<noscript><meta http-equiv="refresh" content="0;url=${escapeHtml(url)}"></noscript>
<div class="fallback"><a href="${escapeHtml(url)}">Klicka h&auml;r om du inte skickas vidare automatiskt</a></div>
</body>
</html>
`
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,328 @@
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()
})
})
+314
View File
@@ -0,0 +1,314 @@
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
@@ -0,0 +1,85 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
vi.mock('@/lib/extensions/loader', () => ({
loadExtensions: vi.fn(),
}))
vi.mock('@/lib/extensions/registry', () => ({
extensionRegistry: {
get: vi.fn(),
},
}))
vi.mock('@/lib/auth/api-keys', () => ({
createServiceClientNoCookies: vi.fn().mockReturnValue({}),
}))
vi.mock('@/extensions/general/invoice-inbox/lib/sweep', () => ({
runInboxSweep: vi.fn(),
}))
vi.mock('@/lib/auth/cron', () => ({
verifyCronSecret: vi.fn().mockReturnValue(null),
}))
import { GET } from '../route'
import { extensionRegistry } from '@/lib/extensions/registry'
import { loadExtensions } from '@/lib/extensions/loader'
import { runInboxSweep } from '@/extensions/general/invoice-inbox/lib/sweep'
import { verifyCronSecret } from '@/lib/auth/cron'
const mockRegistryGet = vi.mocked(extensionRegistry.get)
const mockVerifyCronSecret = vi.mocked(verifyCronSecret)
const mockRunInboxSweep = vi.mocked(runInboxSweep)
function makeRequest() {
return new Request('http://localhost/api/extensions/invoice-inbox/sweep/cron', {
headers: { authorization: 'Bearer synthetic-cron-secret' },
})
}
beforeEach(() => {
vi.clearAllMocks()
mockVerifyCronSecret.mockReturnValue(null)
})
describe('GET /api/extensions/invoice-inbox/sweep/cron', () => {
it('returns 401 when the cron secret is rejected', async () => {
mockVerifyCronSecret.mockReturnValue(
NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
)
const response = await GET(makeRequest())
expect(response.status).toBe(401)
expect(mockRunInboxSweep).not.toHaveBeenCalled()
})
it('returns 503 EXTENSION_DISABLED when the extension is not in the registry', async () => {
// Physical extension routes deploy in every build; the registry, generated
// from extensions.config.json, is what turns them on. Disabled must mean
// no sweeping AND a visible failure if the cron is scheduled anyway.
mockRegistryGet.mockReturnValue(undefined)
const response = await GET(makeRequest())
const body = await response.json()
expect(response.status).toBe(503)
expect(body.code).toBe('EXTENSION_DISABLED')
expect(mockRunInboxSweep).not.toHaveBeenCalled()
})
it('runs the sweep and returns its summary when enabled', async () => {
mockRegistryGet.mockReturnValue({ id: 'invoice-inbox' } as never)
mockRunInboxSweep.mockResolvedValue({ flipped: 3 })
const response = await GET(makeRequest())
const body = await response.json()
expect(loadExtensions).toHaveBeenCalled()
expect(mockRegistryGet).toHaveBeenCalledWith('invoice-inbox')
expect(response.status).toBe(200)
expect(body.data).toEqual({ flipped: 3 })
})
})
@@ -0,0 +1,48 @@
import { NextResponse } from 'next/server'
import { loadExtensions } from '@/lib/extensions/loader'
import { extensionRegistry } from '@/lib/extensions/registry'
import { withCronContext } from '@/lib/api/with-cron-context'
import { createServiceClientNoCookies } from '@/lib/auth/api-keys'
import { runInboxSweep } from '@/extensions/general/invoice-inbox/lib/sweep'
/**
* GET /api/extensions/invoice-inbox/sweep/cron: crash recovery for the
* staged upload. Flips invoice_inbox_items rows stuck in 'processing' (a
* deferred extraction worker that died with its instance) to 'received'
* with the empty extraction skeleton. No re-extraction here: the UI retry
* button covers that. Scheduled every 2 minutes in vercel.json (and the
* Docker crontabs).
*
* Overlap with a slow previous run is safe: the flip is a guarded claim on
* status='processing' with extracted_data still NULL.
*/
// The work is one indexed select plus one guarded update: seconds, not
// minutes. Kept well under the WhatsApp sweep's 300s Bedrock budget.
export const maxDuration = 60
export const GET = withCronContext('cron.invoice_inbox_sweep', async (_request, ctx) => {
// Load the registry so it reflects extensions.config.json.
loadExtensions()
// Physical routes under app/api/extensions/<id>/ compile into EVERY build,
// including the core-with-zero-extensions one: the registry (generated from
// extensions.config.json) is what actually switches an extension on. Mirror
// the ext/[...path] dispatcher: a disabled extension must not expose a live
// surface, and a scheduled-but-disabled cron must fail visibly (503)
// instead of quietly doing the work anyway.
if (!extensionRegistry.get('invoice-inbox')) {
ctx.log.warn('invoice-inbox extension is not enabled; cron refused')
return NextResponse.json(
{ error: 'Invoice inbox extension is not enabled', code: 'EXTENSION_DISABLED' },
{ status: 503 },
)
}
const supabase = createServiceClientNoCookies()
const summary = await runInboxSweep(supabase)
ctx.log.info('invoice inbox sweep complete', { ...summary })
return NextResponse.json({ data: summary })
})
@@ -0,0 +1,105 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
vi.mock('@/lib/extensions/loader', () => ({
loadExtensions: vi.fn(),
}))
vi.mock('@/lib/extensions/registry', () => ({
extensionRegistry: {
get: vi.fn(),
},
}))
vi.mock('@/lib/auth/api-keys', () => ({
createServiceClientNoCookies: vi.fn().mockReturnValue({}),
}))
vi.mock('@/lib/transactions/inbox-underlag-reconcile', () => ({
reconcileStrandedInboxUnderlag: vi.fn(),
}))
vi.mock('@/lib/auth/cron', () => ({
verifyCronSecret: vi.fn().mockReturnValue(null),
}))
import { GET } from '../route'
import { extensionRegistry } from '@/lib/extensions/registry'
import { loadExtensions } from '@/lib/extensions/loader'
import { reconcileStrandedInboxUnderlag } from '@/lib/transactions/inbox-underlag-reconcile'
import { verifyCronSecret } from '@/lib/auth/cron'
const mockRegistryGet = vi.mocked(extensionRegistry.get)
const mockVerifyCronSecret = vi.mocked(verifyCronSecret)
const mockReconcile = vi.mocked(reconcileStrandedInboxUnderlag)
function makeRequest() {
return new Request('http://localhost/api/extensions/invoice-inbox/underlag-reconcile/cron', {
headers: { authorization: 'Bearer synthetic-cron-secret' },
})
}
const SUMMARY = {
execute: true,
scanned: 4,
truncated: false,
strandedOnBooked: 3,
repaired: 2,
alreadyAnchored: 0,
stillUnlinked: 0,
unlinkedLocked: 0,
deferred: 0,
anchoredElsewhere: 1,
companiesTouched: 1,
historyAppended: 2,
failures: 0,
}
beforeEach(() => {
vi.clearAllMocks()
mockVerifyCronSecret.mockReturnValue(null)
})
describe('GET /api/extensions/invoice-inbox/underlag-reconcile/cron', () => {
it('returns 401 when the cron secret is rejected', async () => {
mockVerifyCronSecret.mockReturnValue(
NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
)
const response = await GET(makeRequest())
expect(response.status).toBe(401)
expect(mockReconcile).not.toHaveBeenCalled()
})
it('returns 503 EXTENSION_DISABLED when the extension is not in the registry', async () => {
// Physical extension routes deploy in every build; the registry, generated
// from extensions.config.json, is what turns them on. Disabled must mean
// no reconciling AND a visible failure if the cron is scheduled anyway.
mockRegistryGet.mockReturnValue(undefined)
const response = await GET(makeRequest())
const body = await response.json()
expect(response.status).toBe(503)
expect(body.code).toBe('EXTENSION_DISABLED')
expect(mockReconcile).not.toHaveBeenCalled()
})
it('runs the reconciliation in execute mode and returns its summary when enabled', async () => {
mockRegistryGet.mockReturnValue({ id: 'invoice-inbox' } as never)
mockReconcile.mockResolvedValue(SUMMARY)
const response = await GET(makeRequest())
const body = await response.json()
expect(loadExtensions).toHaveBeenCalled()
expect(mockRegistryGet).toHaveBeenCalledWith('invoice-inbox')
expect(mockReconcile).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({ execute: true, actorId: 'cron.invoice_inbox_underlag_reconcile' }),
)
expect(response.status).toBe(200)
expect(body.data).toEqual(SUMMARY)
})
})
@@ -0,0 +1,55 @@
import { NextResponse } from 'next/server'
import { loadExtensions } from '@/lib/extensions/loader'
import { extensionRegistry } from '@/lib/extensions/registry'
import { withCronContext } from '@/lib/api/with-cron-context'
import { createServiceClientNoCookies } from '@/lib/auth/api-keys'
import { reconcileStrandedInboxUnderlag } from '@/lib/transactions/inbox-underlag-reconcile'
/**
* GET /api/extensions/invoice-inbox/underlag-reconcile/cron: daily
* reconciliation of inbox items stranded on already-booked transactions
* (#1548). Re-runs the underlag propagation for matched items whose
* transaction is booked but whose stamp never landed, so a transient link
* failure heals without an ad-hoc script run, and counts the permanent
* conflicts (document anchored to another verifikat) so they are visible
* in one summary instead of scattered warn lines. Scheduled daily in
* vercel.json (and the generated Docker crontabs).
*
* Idempotent and safe to overlap with a slow previous run: the propagation
* skips documents that already reference the verifikat and CASes the stamp
* on its null predicate.
*/
// One bounded scan (1000 items) plus a handful of batched lookups per
// company, and a document link per stranded item. Same budget as the
// WhatsApp sweep so a large backlog on first run cannot time out midway.
export const maxDuration = 300
export const GET = withCronContext('cron.invoice_inbox_underlag_reconcile', async (_request, ctx) => {
// Load the registry so it reflects extensions.config.json.
loadExtensions()
// Physical routes under app/api/extensions/<id>/ compile into EVERY build,
// including the core-with-zero-extensions one: the registry (generated from
// extensions.config.json) is what actually switches an extension on. A
// scheduled-but-disabled cron must fail visibly (503) instead of quietly
// doing the work anyway.
if (!extensionRegistry.get('invoice-inbox')) {
ctx.log.warn('invoice-inbox extension is not enabled; cron refused')
return NextResponse.json(
{ error: 'Invoice inbox extension is not enabled', code: 'EXTENSION_DISABLED' },
{ status: 503 },
)
}
const supabase = createServiceClientNoCookies()
const summary = await reconcileStrandedInboxUnderlag(supabase, {
execute: true,
log: ctx.log,
actorId: 'cron.invoice_inbox_underlag_reconcile',
})
ctx.log.info('invoice inbox underlag reconcile complete', { ...summary })
return NextResponse.json({ data: summary })
})
@@ -0,0 +1,114 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
vi.mock('@supabase/supabase-js', () => ({
createClient: vi.fn().mockReturnValue({}),
}))
vi.mock('@/lib/extensions/loader', () => ({
loadExtensions: vi.fn(),
}))
vi.mock('@/lib/extensions/registry', () => ({
extensionRegistry: {
get: vi.fn(),
},
}))
vi.mock('@/extensions/general/push-notifications/notification-scheduler', () => ({
sendTaxDeadlineNotifications: vi.fn(),
sendInvoiceNotifications: vi.fn(),
sendMissingUnderlagNotifications: vi.fn(),
}))
vi.mock('@/lib/auth/cron', () => ({
verifyCronSecret: vi.fn().mockReturnValue(null),
}))
import { GET } from '../route'
import { extensionRegistry } from '@/lib/extensions/registry'
import { loadExtensions } from '@/lib/extensions/loader'
import {
sendTaxDeadlineNotifications,
sendInvoiceNotifications,
sendMissingUnderlagNotifications,
} from '@/extensions/general/push-notifications/notification-scheduler'
import { verifyCronSecret } from '@/lib/auth/cron'
const mockRegistryGet = vi.mocked(extensionRegistry.get)
const mockVerifyCronSecret = vi.mocked(verifyCronSecret)
const mockTax = vi.mocked(sendTaxDeadlineNotifications)
const mockInvoice = vi.mocked(sendInvoiceNotifications)
const mockUnderlag = vi.mocked(sendMissingUnderlagNotifications)
function makeRequest() {
return new Request('http://localhost/api/extensions/push-notifications/cron', {
headers: { authorization: 'Bearer synthetic-cron-secret' },
})
}
beforeEach(() => {
vi.clearAllMocks()
mockVerifyCronSecret.mockReturnValue(null)
process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://synthetic.supabase.co'
process.env.SUPABASE_SERVICE_ROLE_KEY = 'synthetic-service-role-key'
})
describe('GET /api/extensions/push-notifications/cron', () => {
it('returns 401 when the cron secret is rejected', async () => {
mockVerifyCronSecret.mockReturnValue(
NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
)
const response = await GET(makeRequest())
expect(response.status).toBe(401)
expect(mockTax).not.toHaveBeenCalled()
})
it('returns 503 EXTENSION_DISABLED when the extension is not in the registry', async () => {
// Physical extension routes deploy in every build; the registry, generated
// from extensions.config.json, is what turns them on. Disabled must mean
// no sends AND a visible failure if the cron is ever scheduled anyway.
mockRegistryGet.mockReturnValue(undefined)
const response = await GET(makeRequest())
const body = await response.json()
expect(response.status).toBe(503)
expect(body.code).toBe('EXTENSION_DISABLED')
expect(mockTax).not.toHaveBeenCalled()
expect(mockInvoice).not.toHaveBeenCalled()
expect(mockUnderlag).not.toHaveBeenCalled()
})
it('runs all three schedulers and sums the totals when enabled', async () => {
mockRegistryGet.mockReturnValue({ id: 'push-notifications' } as never)
mockTax.mockResolvedValue({ sent: 2, skipped: 1 })
mockInvoice.mockResolvedValue({ sent: 3, skipped: 0 })
mockUnderlag.mockResolvedValue({ sent: 1, skipped: 4 })
const response = await GET(makeRequest())
const body = await response.json()
expect(loadExtensions).toHaveBeenCalled()
expect(mockRegistryGet).toHaveBeenCalledWith('push-notifications')
expect(response.status).toBe(200)
expect(body.success).toBe(true)
expect(body.totalSent).toBe(6)
expect(body.totalSkipped).toBe(5)
expect(body.details.taxDeadlines).toEqual({ sent: 2, skipped: 1 })
})
it('returns the error envelope when Supabase configuration is missing', async () => {
mockRegistryGet.mockReturnValue({ id: 'push-notifications' } as never)
delete process.env.NEXT_PUBLIC_SUPABASE_URL
const response = await GET(makeRequest())
const body = await response.json()
expect(response.status).toBe(500)
expect(body.error.code).toBe('INTERNAL_ERROR')
expect(mockTax).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,83 @@
import { createServiceRoleClient } from '@/lib/supabase/service-client'
import { NextResponse } from 'next/server'
import { loadExtensions } from '@/lib/extensions/loader'
import { extensionRegistry } from '@/lib/extensions/registry'
import {
sendTaxDeadlineNotifications,
sendInvoiceNotifications,
sendMissingUnderlagNotifications,
} from '@/extensions/general/push-notifications/notification-scheduler'
import { withCronContext } from '@/lib/api/with-cron-context'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
/**
* GET /api/extensions/push-notifications/cron: daily 09:00 UTC.
* Sends due tax, invoice and missing-underlag push notifications.
*
* NOT scheduled: this path is absent from vercel.json's crons (and therefore
* from the Docker crontabs generated from it). Adding it there is a product
* decision, not a code change.
*/
export const GET = withCronContext('cron.push_notifications', async (_request, ctx) => {
// Load the registry so it reflects extensions.config.json.
loadExtensions()
// Physical routes under app/api/extensions/<id>/ compile into EVERY build,
// including the core-with-zero-extensions one: the registry (generated from
// extensions.config.json) is what actually switches an extension on. Mirror
// the ext/[...path] dispatcher: a disabled extension must not expose a live
// send/query surface, and a scheduled-but-disabled cron must fail visibly
// (503) instead of quietly doing the work anyway.
if (!extensionRegistry.get('push-notifications')) {
ctx.log.warn('push-notifications extension is not enabled; cron refused')
return NextResponse.json(
{ error: 'Push notifications extension is not enabled', code: 'EXTENSION_DISABLED' },
{ status: 503 }
)
}
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY
if (!supabaseUrl || !supabaseServiceKey) {
return errorResponseFromCode('INTERNAL_ERROR', ctx.log, {
requestId: ctx.requestId,
details: { reason: 'Missing Supabase configuration' },
})
}
const supabase = createServiceRoleClient(supabaseUrl, supabaseServiceKey)
try {
const [taxResult, invoiceResult, underlagResult] = await Promise.all([
sendTaxDeadlineNotifications(supabase),
sendInvoiceNotifications(supabase),
sendMissingUnderlagNotifications(supabase),
])
const totalSent = taxResult.sent + invoiceResult.sent + underlagResult.sent
const totalSkipped = taxResult.skipped + invoiceResult.skipped + underlagResult.skipped
ctx.log.info('push notification cron summary', {
totalSent,
totalSkipped,
taxSent: taxResult.sent,
invoiceSent: invoiceResult.sent,
underlagSent: underlagResult.sent,
})
return NextResponse.json({
success: true,
totalSent,
totalSkipped,
details: {
taxDeadlines: taxResult,
invoices: invoiceResult,
missingUnderlag: underlagResult,
},
})
} catch (err) {
ctx.log.error('push notification cron failed', err as Error)
return errorResponse(err, ctx.log, { requestId: ctx.requestId })
}
})
@@ -0,0 +1,168 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
const verifyCronSecret = vi.fn(() => null as unknown)
vi.mock('@/lib/auth/cron', () => ({
verifyCronSecret: (...args: unknown[]) => verifyCronSecret(...args),
}))
const registryGet = vi.fn()
vi.mock('@/lib/extensions/loader', () => ({ loadExtensions: vi.fn() }))
vi.mock('@/lib/extensions/registry', () => ({
extensionRegistry: { get: (...args: unknown[]) => registryGet(...args) },
}))
// The connection query chain ends in .limit(); resolve it there.
const limitResult = vi.fn()
vi.mock('@supabase/supabase-js', () => ({
createClient: vi.fn(() => ({
from: () => ({
select: () => ({
eq: () => ({
eq: () => ({
order: () => ({
limit: (...args: unknown[]) => limitResult(...args),
}),
}),
}),
}),
}),
})),
}))
const isShopifyConfigured = vi.fn(() => true)
vi.mock('@/extensions/general/shopify/lib/credentials', () => ({
isShopifyConfigured: (...args: unknown[]) => isShopifyConfigured(...args),
}))
const syncShopifyOrders = vi.fn()
vi.mock('@/extensions/general/shopify/lib/order-sync', () => ({
syncShopifyOrders: (...args: unknown[]) => syncShopifyOrders(...args),
}))
const hasCapability = vi.fn()
vi.mock('@/lib/entitlements/has-capability', () => ({
hasCapability: (...args: unknown[]) => hasCapability(...args),
}))
const CONNECTION = { id: 'conn-1', company_id: 'company-1' }
async function callRoute() {
const { GET } = await import('../route')
return GET(new Request('https://example.test/api/extensions/shopify/orders/cron'))
}
beforeEach(() => {
vi.clearAllMocks()
verifyCronSecret.mockReturnValue(null)
registryGet.mockReturnValue({ id: 'shopify' })
isShopifyConfigured.mockReturnValue(true)
hasCapability.mockResolvedValue(true)
limitResult.mockResolvedValue({ data: [CONNECTION], error: null })
syncShopifyOrders.mockResolvedValue({
fetched: 2,
refundsFetched: 0,
inserted: 2,
updated: 0,
unchanged: 0,
frozenFlagged: 0,
crossMarked: 0,
errors: 0,
})
process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://project.supabase.co'
process.env.SUPABASE_SERVICE_ROLE_KEY = 'service-key'
})
describe('GET /api/extensions/shopify/orders/cron', () => {
it('returns 401 when the cron secret is wrong', async () => {
verifyCronSecret.mockReturnValue({ error: 'unauthorized' })
const res = await callRoute()
expect(res.status).toBe(401)
expect(syncShopifyOrders).not.toHaveBeenCalled()
})
it('refuses with 503 when the extension is not enabled', async () => {
registryGet.mockReturnValue(undefined)
const res = await callRoute()
expect(res.status).toBe(503)
const body = await res.json()
expect(body.code).toBe('EXTENSION_DISABLED')
})
it('no-ops when the encryption key is not configured', async () => {
isShopifyConfigured.mockReturnValue(false)
const res = await callRoute()
expect(res.status).toBe(200)
expect((await res.json()).processed).toBe(0)
expect(syncShopifyOrders).not.toHaveBeenCalled()
})
it('fails loudly when the connection query errors', async () => {
limitResult.mockResolvedValue({ data: null, error: { message: 'boom', code: '500' } })
const res = await callRoute()
expect(res.status).toBeGreaterThanOrEqual(500)
})
it('syncs each eligible connection and reports the totals', async () => {
limitResult.mockResolvedValue({
data: [CONNECTION, { id: 'conn-2', company_id: 'company-2' }],
error: null,
})
const res = await callRoute()
expect(res.status).toBe(200)
const body = await res.json()
expect(body.processed).toBe(2)
expect(body.inserted).toBe(4)
expect(syncShopifyOrders).toHaveBeenCalledTimes(2)
// Runs on the service client with a shared deadline.
expect(syncShopifyOrders.mock.calls[0][0]).toBeTruthy()
expect(typeof syncShopifyOrders.mock.calls[0][3]).toBe('number')
})
it('skips connections whose company is not entitled', async () => {
hasCapability.mockResolvedValue(false)
const res = await callRoute()
expect(res.status).toBe(200)
expect((await res.json()).processed).toBe(0)
expect(syncShopifyOrders).not.toHaveBeenCalled()
})
it('records a failed connection without aborting the run', async () => {
limitResult.mockResolvedValue({
data: [CONNECTION, { id: 'conn-2', company_id: 'company-2' }],
error: null,
})
syncShopifyOrders
.mockRejectedValueOnce(new Error('store on fire'))
.mockResolvedValueOnce({
fetched: 1,
refundsFetched: 0,
inserted: 1,
updated: 0,
unchanged: 0,
frozenFlagged: 0,
crossMarked: 0,
errors: 0,
})
const res = await callRoute()
expect(res.status).toBe(200)
const body = await res.json()
expect(body.processed).toBe(2)
expect(body.results.map((r: { status: string }) => r.status)).toEqual(['error', 'synced'])
})
it('marks a revoked connection in the results', async () => {
syncShopifyOrders.mockResolvedValue({
fetched: 0,
refundsFetched: 0,
inserted: 0,
updated: 0,
unchanged: 0,
frozenFlagged: 0,
crossMarked: 0,
errors: 0,
revoked: true,
})
const body = await (await callRoute()).json()
expect(body.results[0].status).toBe('revoked')
})
})
@@ -0,0 +1,138 @@
import { createServiceRoleClient } from '@/lib/supabase/service-client'
import { NextResponse } from 'next/server'
import { withCronContext } from '@/lib/api/with-cron-context'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { hasCapability } from '@/lib/entitlements/has-capability'
import { CAPABILITY } from '@/lib/entitlements/keys'
import { loadExtensions } from '@/lib/extensions/loader'
import { extensionRegistry } from '@/lib/extensions/registry'
import { isShopifyConfigured } from '@/extensions/general/shopify/lib/credentials'
import { syncShopifyOrders } from '@/extensions/general/shopify/lib/order-sync'
import type { ShopifyConnection } from '@/extensions/general/shopify/types'
export const maxDuration = 300
/**
* GET /api/extensions/shopify/orders/cron
* Nightly order sync for connections that opted in (transaction_sync_enabled):
* upserts each connected store's paid orders and refunds into webshop_orders
* (the Orders page), replacing the earlier transactions-inbox feed.
*
* Read-only against the stores, and it never posts to the journal: rows land
* unbooked; booking stays a human decision on the Orders page. Idempotent via
* the (company_id, external_id) unique index; overlap re-polls become status
* updates. Emits no events, so no ensureInitialized() is needed.
*/
export const GET = withCronContext('cron.shopify_order_sync', async (_request, ctx) => {
// Physical routes under app/api/extensions/<id>/ compile into EVERY build,
// including the core-with-zero-extensions one: the registry (generated from
// extensions.config.json) is what actually switches an extension on. A
// scheduled-but-disabled cron must fail visibly (503) instead of quietly
// doing the work anyway.
loadExtensions()
if (!extensionRegistry.get('shopify')) {
ctx.log.warn('shopify extension is not enabled; cron refused')
return NextResponse.json(
{ error: 'Shopify extension is not enabled', code: 'EXTENSION_DISABLED' },
{ status: 503 },
)
}
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY
if (!supabaseUrl || !supabaseServiceKey) {
return errorResponseFromCode('INTERNAL_ERROR', ctx.log, {
requestId: ctx.requestId,
details: { reason: 'Missing Supabase configuration' },
})
}
if (!isShopifyConfigured()) {
return NextResponse.json({ message: 'Shopify not configured', processed: 0 })
}
const supabase = createServiceRoleClient(supabaseUrl, supabaseServiceKey)
const { data: connections, error: connError } = await supabase
.from('shopify_connections')
.select('*')
.eq('status', 'active')
.eq('transaction_sync_enabled', true)
.order('last_order_synced_at', { ascending: true, nullsFirst: true })
.limit(50)
if (connError) {
ctx.log.error('failed to fetch shopify connections', connError, {
message: connError.message,
code: connError.code,
})
return errorResponse(connError, ctx.log, { requestId: ctx.requestId })
}
if (!connections || connections.length === 0) {
return NextResponse.json({
message: 'No connections with transaction sync enabled',
processed: 0,
})
}
const startTime = Date.now()
const TIME_BUDGET_MS = 240_000 // leave a minute of margin inside maxDuration
// Shared with syncShopifyOrders: it stops between pages and persists its
// cursor, so a truncated connection resumes next night.
const deadlineMs = startTime + TIME_BUDGET_MS
const results: Array<{
connectionId: string
inserted: number
updated: number
status: 'synced' | 'revoked' | 'error'
}> = []
for (const connection of connections as ShopifyConnection[]) {
if (Date.now() >= deadlineMs) {
ctx.log.info('time budget reached', { processedSoFar: results.length })
break
}
if (!(await hasCapability(supabase, connection.company_id, CAPABILITY.shopify_sync))) {
ctx.log.info('skip: capability not entitled', { companyId: connection.company_id })
continue
}
try {
const summary = await syncShopifyOrders(supabase, connection, ctx.log, deadlineMs)
if (summary.deadlineReached) {
ctx.log.info('connection stopped early on time budget; remaining rows resume next run', {
connectionId: connection.id,
})
}
results.push({
connectionId: connection.id,
inserted: summary.inserted,
updated: summary.updated,
status: summary.revoked ? 'revoked' : 'synced',
})
} catch (error) {
ctx.log.error('shopify order sync failed for connection', error as Error, {
connectionId: connection.id,
companyId: connection.company_id,
})
results.push({
connectionId: connection.id,
inserted: 0,
updated: 0,
status: 'error',
})
}
}
const totalInserted = results.reduce((acc, r) => acc + r.inserted, 0)
ctx.log.info('shopify order sync summary', {
processed: results.length,
totalInserted,
failed: results.filter((r) => r.status === 'error').length,
})
return NextResponse.json({ processed: results.length, inserted: totalInserted, results })
})
@@ -0,0 +1,421 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
vi.mock('@supabase/supabase-js', () => ({
createClient: vi.fn(),
}))
vi.mock('@/lib/init', () => ({
ensureInitialized: vi.fn(),
}))
vi.mock('@/lib/auth/cron', () => ({
verifyCronSecret: vi.fn().mockReturnValue(null),
}))
// The route and the reconcile helper log through '@/lib/logger'. The real
// logger suppresses info/warn under NODE_ENV=test, so warn/error output is
// observed via these recorders instead of console spies. Console spies stay
// for the route's remaining console.* lines (summary, skip).
const { warnRecorder, errorRecorder } = vi.hoisted(() => ({
warnRecorder: vi.fn(),
errorRecorder: vi.fn(),
}))
vi.mock('@/lib/logger', () => {
const logger = {
info: vi.fn(),
warn: warnRecorder,
error: errorRecorder,
child: (): unknown => logger,
}
return { createLogger: () => logger }
})
vi.mock('@/extensions/general/skatteverket/lib/agi-client', () => ({
agiGetKvittenser: vi.fn(),
}))
// Provide the class in the mock factory so both the route's instanceof
// checks and the errors constructed in tests use the same identity,
// without loading the real api-client module (oauth, rate limiter, ...).
vi.mock('@/extensions/general/skatteverket/lib/api-client', () => {
class SkatteverketAuthError extends Error {
constructor(
message: string,
public readonly code: string,
) {
super(message)
this.name = 'SkatteverketAuthError'
}
}
return {
SkatteverketAuthError,
// resolve-auth's currentSkvEnvironment (grant-revoked path) reads this.
getSkatteverketEnvironment: vi.fn().mockReturnValue('test'),
}
})
vi.mock('@/extensions/general/skatteverket/lib/token-store', () => ({
// Mirrors the real RECONSENT_ERROR_CODES: terminal codes that only a
// fresh BankID consent can fix.
RECONSENT_ERROR_CODES: [
'SESSION_EXPIRED',
'REFRESH_EXHAUSTED',
'MISSING_SCOPE',
'TOKEN_CORRUPTED',
] as const,
markNeedsReconsent: vi.fn().mockResolvedValue(undefined),
}))
vi.mock('@/lib/entitlements/has-capability', () => ({
hasCapability: vi.fn().mockResolvedValue(true),
}))
// The route's real connection-store hits the DB via its own service client;
// mocking keeps the grant-revoked path deterministic. resolve-auth also
// imports getConnection from here (only used when system auth mode is on,
// which is off in tests), so export it too.
vi.mock('@/extensions/general/skatteverket/lib/connection-store', () => ({
getConnection: vi.fn().mockResolvedValue(null),
markGrantRevoked: vi.fn().mockResolvedValue(undefined),
}))
vi.mock('@/lib/deadlines/complete-tax-deadline', () => ({
completeTaxDeadline: vi.fn().mockResolvedValue(undefined),
}))
vi.mock('@/extensions/general/skatteverket/lib/kvittens-notification', () => ({
sendKvittensNotification: vi.fn().mockResolvedValue(undefined),
}))
import { GET } from '../route'
import { createClient } from '@supabase/supabase-js'
import { verifyCronSecret } from '@/lib/auth/cron'
import { agiGetKvittenser } from '@/extensions/general/skatteverket/lib/agi-client'
import { SkatteverketAuthError } from '@/extensions/general/skatteverket/lib/api-client'
import { markNeedsReconsent } from '@/extensions/general/skatteverket/lib/token-store'
import { markGrantRevoked } from '@/extensions/general/skatteverket/lib/connection-store'
import { completeTaxDeadline } from '@/lib/deadlines/complete-tax-deadline'
import { sendKvittensNotification } from '@/extensions/general/skatteverket/lib/kvittens-notification'
const mockCreateClient = vi.mocked(createClient)
const mockVerifyCronSecret = vi.mocked(verifyCronSecret)
const mockAgiGetKvittenser = vi.mocked(agiGetKvittenser)
const mockMarkNeedsReconsent = vi.mocked(markNeedsReconsent)
const mockMarkGrantRevoked = vi.mocked(markGrantRevoked)
const mockCompleteTaxDeadline = vi.mocked(completeTaxDeadline)
const mockSendKvittensNotification = vi.mocked(sendKvittensNotification)
function makeRequest() {
return new Request('http://localhost/api/extensions/skatteverket/agi/kvittenser/cron', {
headers: { authorization: 'Bearer test-secret' },
})
}
const PENDING_DECLARATION = {
id: 'decl-1',
company_id: 'comp-1',
salary_run_id: null,
period_year: 2026,
period_month: 5,
}
/**
* Generic chainable Supabase stub: from(table) returns a chain whose
* terminal calls (maybeSingle/single/await) resolve to the per-table
* result. Good enough for this route: it never branches on update or
* delete results.
*/
function makeSupabaseStub(tables: Record<string, { data: unknown; error?: unknown }>) {
return {
from: vi.fn((table: string) => {
const result = tables[table] ?? { data: null, error: null }
const resolved = { data: result.data, error: result.error ?? null }
const chain: any = {}
for (const method of ['select', 'eq', 'in', 'order', 'limit', 'update', 'delete', 'insert']) {
chain[method] = vi.fn(() => chain)
}
chain.maybeSingle = vi.fn().mockResolvedValue(resolved)
chain.single = vi.fn().mockResolvedValue(resolved)
chain.then = (resolve: (v: unknown) => void) => resolve(resolved)
return chain
}),
} as any
}
function stubHappyTables() {
return makeSupabaseStub({
agi_declarations: { data: [PENDING_DECLARATION] },
skatteverket_tokens: { data: [{ user_id: 'user-1', status: 'active' }] },
company_settings: { data: { org_number: '556123-4567', entity_type: 'aktiebolag' } },
})
}
describe('AGI kvittenser cron', () => {
let warnSpy: ReturnType<typeof vi.spyOn>
let errorSpy: ReturnType<typeof vi.spyOn>
let logSpy: ReturnType<typeof vi.spyOn>
let infoSpy: ReturnType<typeof vi.spyOn>
beforeEach(() => {
vi.clearAllMocks()
process.env.SKATTEVERKET_ENABLED = 'true'
process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://test.supabase.co'
process.env.SUPABASE_SERVICE_ROLE_KEY = 'service-key'
mockVerifyCronSecret.mockReturnValue(null)
warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
infoSpy = vi.spyOn(console, 'info').mockImplementation(() => {})
})
afterEach(() => {
warnSpy.mockRestore()
errorSpy.mockRestore()
logSpy.mockRestore()
infoSpy.mockRestore()
})
it('returns 401 when cron auth fails', async () => {
mockVerifyCronSecret.mockReturnValueOnce(
new Response(JSON.stringify({ error: 'Unauthorized' }), { status: 401 }) as any,
)
const res = await GET(makeRequest())
expect(res.status).toBe(401)
expect(mockCreateClient).not.toHaveBeenCalled()
})
it('marks the declaration signed when a kvittens exists', async () => {
mockCreateClient.mockReturnValueOnce(stubHappyTables())
mockAgiGetKvittenser.mockResolvedValueOnce({
ok: true,
status: 200,
data: {
kvittenser: [
{
uuidKvittens: 'uuid-1',
signeradAv: '191212121212',
signeradTid: '2026-06-01T10:00:00Z',
},
],
},
} as any)
const res = await GET(makeRequest())
const body = await res.json()
expect(body.signed).toBe(1)
expect(body.errors).toBe(0)
expect(body.grantRevoked).toBe(0)
expect(body.results[0].status).toBe('signed')
// Tenant identifiers stay in internal log context only.
expect(body.results[0]).not.toHaveProperty('companyId')
expect(mockCompleteTaxDeadline).toHaveBeenCalledTimes(1)
expect(mockSendKvittensNotification).toHaveBeenCalledTimes(1)
expect(errorSpy).not.toHaveBeenCalled()
expect(errorRecorder).not.toHaveBeenCalled()
})
it('still reports signed and sends the notification when completeTaxDeadline throws', async () => {
mockCreateClient.mockReturnValueOnce(stubHappyTables())
mockAgiGetKvittenser.mockResolvedValueOnce({
ok: true,
status: 200,
data: {
kvittenser: [
{
uuidKvittens: 'uuid-1',
signeradAv: '191212121212',
signeradTid: '2026-06-01T10:00:00Z',
},
],
},
} as any)
mockCompleteTaxDeadline.mockRejectedValueOnce(new Error('deadline table unavailable'))
const res = await GET(makeRequest())
const body = await res.json()
// The filing succeeded before the best-effort step failed: the row must
// still land as signed, never as error (the next run only revisits
// pending_signature rows, so an error here would be lost permanently).
expect(body.signed).toBe(1)
expect(body.errors).toBe(0)
expect(body.results[0].status).toBe('signed')
// The notification still goes out even though deadline completion threw.
expect(mockSendKvittensNotification).toHaveBeenCalledTimes(1)
expect(mockSendKvittensNotification).toHaveBeenCalledWith(expect.anything(), {
companyId: 'comp-1',
userId: 'user-1',
kind: 'agi',
period: expect.any(String),
kvittensnummer: 'uuid-1',
referenceId: 'decl-1',
})
// The failure is a warning (via the structured logger), not an error.
expect(errorSpy).not.toHaveBeenCalled()
expect(errorRecorder).not.toHaveBeenCalled()
const warnMessages = warnRecorder.mock.calls.map(c => String(c[0]))
expect(warnMessages.some(m => m.includes('completeTaxDeadline failed'))).toBe(true)
})
it('still reports signed when sendKvittensNotification throws', async () => {
mockCreateClient.mockReturnValueOnce(stubHappyTables())
mockAgiGetKvittenser.mockResolvedValueOnce({
ok: true,
status: 200,
data: {
kvittenser: [
{
uuidKvittens: 'uuid-1',
signeradAv: '191212121212',
signeradTid: '2026-06-01T10:00:00Z',
},
],
},
} as any)
mockSendKvittensNotification.mockRejectedValueOnce(new Error('smtp down'))
const res = await GET(makeRequest())
const body = await res.json()
expect(body.signed).toBe(1)
expect(body.errors).toBe(0)
expect(body.results[0].status).toBe('signed')
expect(errorSpy).not.toHaveBeenCalled()
expect(errorRecorder).not.toHaveBeenCalled()
const warnMessages = warnRecorder.mock.calls.map(c => String(c[0]))
expect(warnMessages.some(m => m.includes('sendKvittensNotification failed'))).toBe(true)
})
it('counts grant_revoked in the run summary', async () => {
mockCreateClient.mockReturnValueOnce(stubHappyTables())
mockAgiGetKvittenser.mockRejectedValueOnce(
new SkatteverketAuthError('Ombud grant missing.', 'OMBUD_GRANT_MISSING'),
)
const res = await GET(makeRequest())
const body = await res.json()
expect(body.processed).toBe(1)
expect(body.grantRevoked).toBe(1)
expect(body.errors).toBe(0)
expect(body.results[0]).toMatchObject({ status: 'grant_revoked', error: 'OMBUD_GRANT_MISSING' })
expect(mockMarkGrantRevoked).toHaveBeenCalledWith('comp-1', expect.any(String), 'lasombud', 'OMBUD_GRANT_MISSING')
const summaryLine = logSpy.mock.calls.map(c => String(c[0])).find(m => m.includes('Processed'))
expect(summaryLine).toContain('1 grants revoked')
})
it('treats ACCESS_DENIED as a real error now that the APIGW subscription is expected (#2226)', async () => {
mockCreateClient.mockReturnValueOnce(stubHappyTables())
mockAgiGetKvittenser.mockRejectedValueOnce(
new SkatteverketAuthError('Skatteverkets API-gateway nekade anropet.', 'ACCESS_DENIED'),
)
const res = await GET(makeRequest())
const body = await res.json()
expect(body.processed).toBe(1)
expect(body.errors).toBe(1)
// The old known-gap bucket is gone from the response contract.
expect(body).not.toHaveProperty('apigwConfig')
expect(body.results[0]).toMatchObject({
declarationId: 'decl-1',
status: 'error',
// Machine-readable code, never the generic "Något gick fel" fallback.
error: 'ACCESS_DENIED',
})
// companyId is internal log context, never response payload.
expect(body.results[0]).not.toHaveProperty('companyId')
// A gateway refusal is a regression, not a known gap: error level with
// the gateway's message in context, no warn-once suppression, no
// reconsent flagging.
expect(errorRecorder).toHaveBeenCalledTimes(1)
expect(String(errorRecorder.mock.calls[0][0])).toContain('Reconciliation failed')
expect(errorRecorder.mock.calls[0][1]).toMatchObject({
declarationId: 'decl-1',
companyId: 'comp-1',
message: 'Skatteverkets API-gateway nekade anropet.',
})
expect(warnSpy).not.toHaveBeenCalled()
expect(warnRecorder).not.toHaveBeenCalled()
expect(mockMarkNeedsReconsent).not.toHaveBeenCalled()
const summaryLine = logSpy.mock.calls.map(c => String(c[0])).find(m => m.includes('Processed'))
expect(summaryLine).toContain('1 errors')
expect(summaryLine).not.toContain('apigw')
})
it('still flags reconsent codes as expired_token and marks the connection', async () => {
mockCreateClient.mockReturnValueOnce(stubHappyTables())
mockAgiGetKvittenser.mockRejectedValueOnce(
new SkatteverketAuthError('Sessionen har gått ut.', 'SESSION_EXPIRED'),
)
const res = await GET(makeRequest())
const body = await res.json()
expect(body.expired).toBe(1)
expect(body.results[0]).toMatchObject({ status: 'expired_token', error: 'SESSION_EXPIRED' })
expect(mockMarkNeedsReconsent).toHaveBeenCalledWith(expect.anything(), 'user-1', 'comp-1', 'SESSION_EXPIRED')
expect(errorSpy).not.toHaveBeenCalled()
expect(errorRecorder).not.toHaveBeenCalled()
expect(warnSpy).not.toHaveBeenCalled()
expect(warnRecorder).not.toHaveBeenCalled()
})
it('still records expired_token for TOKEN_REVOKED without reconsent flagging', async () => {
mockCreateClient.mockReturnValueOnce(stubHappyTables())
mockAgiGetKvittenser.mockRejectedValueOnce(
new SkatteverketAuthError('Token has been revoked.', 'TOKEN_REVOKED'),
)
const res = await GET(makeRequest())
const body = await res.json()
expect(body.expired).toBe(1)
expect(body.results[0]).toMatchObject({ status: 'expired_token', error: 'TOKEN_REVOKED' })
expect(mockMarkNeedsReconsent).not.toHaveBeenCalled()
expect(errorSpy).not.toHaveBeenCalled()
expect(errorRecorder).not.toHaveBeenCalled()
})
it('still logs at error level for other SkatteverketAuthError codes', async () => {
mockCreateClient.mockReturnValueOnce(stubHappyTables())
mockAgiGetKvittenser.mockRejectedValueOnce(
new SkatteverketAuthError('Du har inte behörighet.', 'BEHORIGHET_SAKNAS'),
)
const res = await GET(makeRequest())
const body = await res.json()
expect(body.errors).toBe(1)
expect(body.results[0]).toMatchObject({ status: 'error', error: 'Du har inte behörighet.' })
expect(errorRecorder).toHaveBeenCalledTimes(1)
expect(String(errorRecorder.mock.calls[0][0])).toContain('Reconciliation failed')
expect(warnSpy).not.toHaveBeenCalled()
expect(warnRecorder).not.toHaveBeenCalled()
})
it('still logs at error level for generic errors', async () => {
mockCreateClient.mockReturnValueOnce(stubHappyTables())
mockAgiGetKvittenser.mockRejectedValueOnce(new Error('fetch failed'))
const res = await GET(makeRequest())
const body = await res.json()
expect(body.errors).toBe(1)
expect(body.results[0]).toMatchObject({
status: 'error',
error: 'Något gick fel. Försök igen.',
})
expect(errorRecorder).toHaveBeenCalledTimes(1)
expect(String(errorRecorder.mock.calls[0][0])).toContain('Reconciliation failed')
})
})
@@ -0,0 +1,224 @@
import { createServiceRoleClient } from '@/lib/supabase/service-client'
import { NextResponse } from 'next/server'
import { ensureInitialized } from '@/lib/init'
import { createLogger } from '@/lib/logger'
import { verifyCronSecret } from '@/lib/auth/cron'
import { SkatteverketAuthError } from '@/extensions/general/skatteverket/lib/api-client'
import { markNeedsReconsent, RECONSENT_ERROR_CODES } from '@/extensions/general/skatteverket/lib/token-store'
import { currentSkvEnvironment, findCompanyTokenUser } from '@/extensions/general/skatteverket/lib/resolve-auth'
import { markGrantRevoked } from '@/extensions/general/skatteverket/lib/connection-store'
import { reconcileAgiDeclaration } from '@/extensions/general/skatteverket/lib/agi-kvittens-reconcile'
import { formatRedovisningsperiod } from '@/lib/skatteverket/format'
import { hasCapability } from '@/lib/entitlements/has-capability'
import { CAPABILITY } from '@/lib/entitlements/keys'
import { getErrorMessage } from '@/lib/errors/get-error-message'
ensureInitialized()
export const maxDuration = 60
// Failure logs route through the structured logger so third-party error
// strings pass its redaction. The budget + summary logs / capability skip
// stay on console.*: their content is fixed internal strings.
const log = createLogger('agi-kvittenser-cron')
// Cron responses must never be cached: they report a point-in-time run.
const NO_STORE_HEADERS = { 'Cache-Control': 'no-store' } as const
/**
* GET /api/extensions/skatteverket/agi/kvittenser/cron
*
* Daily kvittens reconciliation. The user-side flow signs the AGI in
* Skatteverket's Mina Sidor; the resulting kvittens (uuidKvittens +
* signeradTid) is the canonical filing receipt. Without this cron,
* `salary_runs.agi_submitted_at` only gets stamped when the user returns
* to the panel and clicks "Hämta kvittens" or stays on the page long
* enough for the in-browser timers to fire, which is unreliable, and
* leaves the audit trail out of step with reality (BFNAR 2013:2 kap 8 +
* BFL 5 kap 5§ require the behandlingshistorik to faithfully record
* filing events).
*
* Strategy: walk every `agi_declarations` row in `pending_signature`
* status, look up its arbetsgivare/period, fetch /kvittenser via the
* extension's per-user token, and on a hit promote the row to
* `submitted` + stamp salary_runs.agi_submitted_at.
*
* Per-row errors are logged and skipped: one expired token shouldn't
* block other companies' reconciliation.
*
* Time budget: 50s (Vercel default 60s function timeout with 10s margin).
*/
export async function GET(request: Request) {
const authError = verifyCronSecret(request)
if (authError) return authError
if (process.env.SKATTEVERKET_ENABLED !== 'true') {
return NextResponse.json(
{ message: 'Skatteverket extension disabled', processed: 0 },
{ headers: NO_STORE_HEADERS },
)
}
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY
if (!supabaseUrl || !supabaseServiceKey) {
return NextResponse.json(
{ error: 'Missing Supabase configuration' },
{ status: 500, headers: NO_STORE_HEADERS },
)
}
const supabase = createServiceRoleClient(supabaseUrl, supabaseServiceKey)
const { data: pending, error: pendingError } = await supabase
.from('agi_declarations')
.select('id, company_id, salary_run_id, period_year, period_month')
.eq('status', 'pending_signature')
.order('created_at', { ascending: true })
.limit(100)
if (pendingError) {
log.error('Failed to fetch pending declarations', {
message: pendingError.message,
code: pendingError.code,
})
return NextResponse.json(
{ error: 'Failed to fetch pending declarations' },
{ status: 500, headers: NO_STORE_HEADERS },
)
}
if (!pending || pending.length === 0) {
return NextResponse.json(
{ message: 'No pending signatures', processed: 0 },
{ headers: NO_STORE_HEADERS },
)
}
const startTime = Date.now()
const TIME_BUDGET_MS = 50_000
// No companyId here: results echo back in the HTTP response body, so
// tenant identifiers stay in internal log context only (declarationId
// is enough to find the row).
type Result = {
declarationId: string
period: string
status: 'signed' | 'still_pending' | 'already_claimed' | 'no_token' | 'no_company_settings' | 'expired_token' | 'grant_revoked' | 'error'
error?: string
}
const results: Result[] = []
for (const decl of pending) {
if (Date.now() - startTime > TIME_BUDGET_MS) {
console.log(`[agi-kvittenser-cron] Time budget reached after ${results.length} declarations`)
break
}
const companyId = decl.company_id as string
const declarationId = decl.id as string
const period = formatRedovisningsperiod('monthly', decl.period_year as number, decl.period_month as number)
if (!(await hasCapability(supabase, companyId, CAPABILITY.skatteverket))) {
console.info('[agi-kvittenser-cron] skip: capability not entitled', { companyId })
continue
}
try {
// The shared reconciler resolves auth (system grant → user token),
// fetches the kvittens, and on a hit promotes the declaration +
// stamps salary_runs / deadline / notification. Auth errors propagate
// to the catch below, which owns the cron-specific side effects.
const outcome = await reconcileAgiDeclaration(
supabase,
{
id: declarationId,
company_id: companyId,
salary_run_id: (decl.salary_run_id as string | null) ?? null,
period_year: decl.period_year as number,
period_month: decl.period_month as number,
},
{ reconciledBy: 'cron' },
)
const result: Result = { declarationId, period, status: outcome.status }
if ('error' in outcome) result.error = outcome.error
results.push(result)
} catch (err) {
const message = err instanceof Error ? err.message : 'Unknown error'
if (err instanceof SkatteverketAuthError && err.code === 'OMBUD_GRANT_MISSING') {
// System-mode read rejected: the company withdrew the behorighet.
// Downgrade the connection row so the next run falls back to the
// user token (if any). Never touches skatteverket_tokens.
await markGrantRevoked(companyId, currentSkvEnvironment(), 'lasombud', err.code)
results.push({ declarationId, period, status: 'grant_revoked', error: err.code })
continue
}
if (
err instanceof SkatteverketAuthError &&
(RECONSENT_ERROR_CODES as readonly string[]).includes(err.code)
) {
// Persist the health flag so both crons stop retrying this
// connection and the UI can prompt for re-consent proactively.
// Same pick as the reconciler's resolveReadAuth (a company can hold
// one row per connected member), so the flag lands on the row that
// just failed.
const tokenRow = await findCompanyTokenUser(supabase, companyId)
if (tokenRow) {
await markNeedsReconsent(supabase, tokenRow.userId, companyId, err.code)
}
results.push({ declarationId, period, status: 'expired_token', error: err.code })
continue
}
if (err instanceof SkatteverketAuthError && err.code === 'TOKEN_REVOKED') {
// skvRequest already deleted the token row.
results.push({ declarationId, period, status: 'expired_token', error: err.code })
continue
}
// ACCESS_DENIED (Skatteverket's gateway refusing the APIGW client) is
// no longer bucketed as a known configuration gap: the AGI hantera
// subscription is expected to be in place (#2226), so a gateway refusal
// is a real regression and lands in the error path below like any
// other failure.
log.error('Reconciliation failed', { declarationId, companyId, period, message })
// A gateway refusal keeps its machine-readable code in the body (as the
// expired_token / grant_revoked rows do): the keyword heuristic in
// getErrorMessage misses the gateway wording and would collapse it
// into "Något gick fel". The full guidance is in the error log above.
const isGatewayRefusal = err instanceof SkatteverketAuthError && err.code === 'ACCESS_DENIED'
results.push({
declarationId,
period,
status: 'error',
error: isGatewayRefusal ? err.code : getErrorMessage(err),
})
}
}
const signed = results.filter(r => r.status === 'signed').length
const stillPending = results.filter(r => r.status === 'still_pending').length
const alreadyClaimed = results.filter(r => r.status === 'already_claimed').length
const expired = results.filter(r => r.status === 'expired_token').length
const grantRevoked = results.filter(r => r.status === 'grant_revoked').length
const errors = results.filter(r => r.status === 'error').length
console.log(
`[agi-kvittenser-cron] Processed ${results.length}: ${signed} signed, ${stillPending} still pending, ${alreadyClaimed} already claimed, ${expired} expired, ${grantRevoked} grants revoked, ${errors} errors`,
)
return NextResponse.json(
{
processed: results.length,
signed,
stillPending,
alreadyClaimed,
expired,
grantRevoked,
errors,
results,
},
{ headers: NO_STORE_HEADERS },
)
}
@@ -0,0 +1,304 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
vi.mock('@/lib/extensions/loader', () => ({ loadExtensions: vi.fn() }))
const mockRegistryGet = vi.fn((_id: string): unknown => ({ id: 'skatteverket' }))
vi.mock('@/lib/extensions/registry', () => ({
extensionRegistry: { get: (id: string) => mockRegistryGet(id) },
}))
const mockVerifyCronSecret = vi.fn()
vi.mock('@/lib/auth/cron', () => ({
verifyCronSecret: (...a: unknown[]) => mockVerifyCronSecret(...a),
}))
const mockMode = vi.fn()
const mockConfigured = vi.fn()
vi.mock('@/extensions/general/skatteverket/lib/system-auth/config', () => ({
getSystemAuthMode: () => mockMode(),
isSystemAuthConfigured: () => mockConfigured(),
}))
vi.mock('@/extensions/general/skatteverket/lib/resolve-auth', () => ({
currentSkvEnvironment: () => 'test',
}))
const mockListConnections = vi.fn()
const mockRecordProbeResult = vi.fn()
const mockContested = vi.fn(async (): Promise<Set<string>> => new Set())
vi.mock('@/extensions/general/skatteverket/lib/connection-store', () => ({
listConnections: (...a: unknown[]) => mockListConnections(...a),
recordProbeResult: (...a: unknown[]) => mockRecordProbeResult(...a),
findContestedOrgNumbers: () => mockContested(),
}))
const mockListOmbudGrants = vi.fn()
vi.mock('@/extensions/general/skatteverket/lib/ombud-client', async (importOriginal) => {
const actual = (await importOriginal()) as Record<string, unknown>
return {
...actual,
listOmbudGrants: (...a: unknown[]) => mockListOmbudGrants(...a),
}
})
import { GET } from '../route'
const ENV_KEYS = ['SKATTEVERKET_ENABLED']
let savedEnv: Record<string, string | undefined>
type Status = 'unknown' | 'granted' | 'denied' | 'error'
function connection(
companyId: string,
orgNumber: string,
lasombud: Status = 'granted',
moms: Status = 'granted',
status = 'verified'
) {
return {
id: `conn-${companyId}`,
company_id: companyId,
environment: 'test',
org_number: orgNumber,
status,
lasombud_status: lasombud,
moms_ombud_status: moms,
}
}
const JLO = (huvudman: string) => ({
huvudman,
roll: 'JLO',
rollbeskrivning: 'Juridiskt läsombud',
giltigFrom: '2026-07-19',
})
const MOMS = (huvudman: string) => ({
huvudman,
roll: 'MOMS',
rollbeskrivning: 'Momsdeklaration, ombud',
giltigFrom: '2026-07-19',
})
beforeEach(() => {
vi.clearAllMocks()
savedEnv = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]]))
process.env.SKATTEVERKET_ENABLED = 'true'
mockVerifyCronSecret.mockReturnValue(null)
mockMode.mockReturnValue('shadow')
mockConfigured.mockReturnValue(true)
mockListConnections.mockResolvedValue([])
mockRecordProbeResult.mockResolvedValue({ id: 'conn' })
mockContested.mockResolvedValue(new Set())
mockListOmbudGrants.mockResolvedValue([])
vi.spyOn(console, 'warn').mockImplementation(() => {})
vi.spyOn(console, 'error').mockImplementation(() => {})
})
afterEach(() => {
for (const k of ENV_KEYS) {
if (savedEnv[k] === undefined) delete process.env[k]
else process.env[k] = savedEnv[k]
}
})
const request = () => new Request('http://localhost/api/extensions/skatteverket/ombud/sync/cron')
const recordedFor = (companyId: string) =>
mockRecordProbeResult.mock.calls.map((c) => c[0]).filter((input) => input.companyId === companyId)
describe('GET /api/extensions/skatteverket/ombud/sync/cron', () => {
it('401 without the cron secret', async () => {
mockVerifyCronSecret.mockReturnValue(new Response('nope', { status: 401 }))
const res = await GET(request())
expect(res.status).toBe(401)
expect(mockListOmbudGrants).not.toHaveBeenCalled()
})
it('503 EXTENSION_DISABLED when the skatteverket extension is not in the registry', async () => {
mockRegistryGet.mockReturnValueOnce(undefined)
const res = await GET(request())
expect(res.status).toBe(503)
expect(await res.json()).toMatchObject({ code: 'EXTENSION_DISABLED' })
expect(mockListOmbudGrants).not.toHaveBeenCalled()
})
it('no-ops when the extension is disabled or system auth is off/unconfigured', async () => {
process.env.SKATTEVERKET_ENABLED = 'false'
expect(await (await GET(request())).json()).toMatchObject({ processed: 0 })
process.env.SKATTEVERKET_ENABLED = 'true'
mockMode.mockReturnValue('off')
expect(await (await GET(request())).json()).toMatchObject({ message: 'System auth not active' })
mockMode.mockReturnValue('on')
mockConfigured.mockReturnValue(false)
expect(await (await GET(request())).json()).toMatchObject({ message: 'System auth not active' })
expect(mockListOmbudGrants).not.toHaveBeenCalled()
})
it('502 when the register cannot be read, without touching any row', async () => {
mockListOmbudGrants.mockRejectedValue(new Error('down'))
const res = await GET(request())
expect(res.status).toBe(502)
expect(mockRecordProbeResult).not.toHaveBeenCalled()
})
it('asks the register with the cron-only empty-on-404 option', async () => {
await GET(request())
expect(mockListOmbudGrants).toHaveBeenCalledWith({}, { emptyOn404: true })
})
it('records grants only on rows that already exist (tenant opt-in); a listed huvudman without a row is ignored', async () => {
mockListConnections.mockResolvedValue([
connection('c-pending', '165560000000', 'unknown', 'unknown', 'pending'),
connection('c-partial', '195001011234', 'denied', 'denied', 'pending'),
])
mockListOmbudGrants.mockResolvedValue([
JLO('165560000000'),
MOMS('165560000000'),
{ ...JLO('195001011234'), roll: 'DEKL', rollbeskrivning: 'Deklarationsombud' },
MOMS('195001011234'),
JLO('165550000000'), // no row for this org number: the twin/unmatched case
])
const body = await (await GET(request())).json()
expect(body).toMatchObject({ registryHuvudman: 3, rows: 2, granted: 2, denied: 0, revoked: 0, guardTripped: false })
expect(mockRecordProbeResult).toHaveBeenCalledTimes(2)
expect(recordedFor('c-pending')[0]).toMatchObject({
environment: 'test',
orgNumber: '165560000000',
lasombud: expect.objectContaining({ status: 'granted' }),
momsOmbud: expect.objectContaining({ status: 'granted' }),
})
expect(recordedFor('c-partial')[0]).toMatchObject({
lasombud: expect.objectContaining({ status: 'denied' }),
momsOmbud: expect.objectContaining({ status: 'granted' }),
})
// Never creates a row for the unmatched huvudman.
expect(mockRecordProbeResult.mock.calls.some((c) => c[0].orgNumber === '165550000000')).toBe(false)
})
it('skips rows the tenant revoked locally even though the grant still stands at Skatteverket', async () => {
mockListConnections.mockResolvedValue([connection('c-off', '165560000000', 'unknown', 'unknown', 'revoked')])
mockListOmbudGrants.mockResolvedValue([JLO('165560000000'), MOMS('165560000000')])
const body = await (await GET(request())).json()
expect(body).toMatchObject({ rows: 0 })
expect(mockRecordProbeResult).not.toHaveBeenCalled()
})
it('leaves unchanged rows alone, records denial once for a never-listed pending row, downgrades one revoked-at-SKV row', async () => {
mockListConnections.mockResolvedValue([
connection('c-keep', '165560000000'),
connection('c-keep2', '165570000000'),
connection('c-keep3', '165580000000'),
connection('c-gone', '165590000000'),
connection('c-never', '165500000000', 'denied', 'denied', 'pending'),
connection('c-fresh', '165510000000', 'unknown', 'unknown', 'pending'),
])
mockListOmbudGrants.mockResolvedValue([
JLO('165560000000'), MOMS('165560000000'),
JLO('165570000000'), MOMS('165570000000'),
JLO('165580000000'), MOMS('165580000000'),
])
const body = await (await GET(request())).json()
expect(body).toMatchObject({ unchanged: 4, revoked: 1, denied: 1, granted: 0, guardTripped: false })
expect(mockRecordProbeResult).toHaveBeenCalledTimes(2)
expect(recordedFor('c-gone')[0]).toMatchObject({
orgNumber: '165590000000',
lasombud: { status: 'denied', detail: expect.stringContaining('huvudman saknas') },
momsOmbud: { status: 'denied' },
})
// The deep-link row nobody signed yet: written once as "Saknas", not left "Inte verifierad".
expect(recordedFor('c-fresh')[0]).toMatchObject({ lasombud: { status: 'denied' }, momsOmbud: { status: 'denied' } })
expect(recordedFor('c-never')).toHaveLength(0)
})
it('a failed upsert is counted once and never turns into a downgrade', async () => {
mockListConnections.mockResolvedValue([connection('c-1', '165560000000', 'unknown', 'unknown', 'pending')])
mockListOmbudGrants.mockResolvedValue([JLO('165560000000')])
mockRecordProbeResult.mockResolvedValue(null)
const body = await (await GET(request())).json()
expect(body).toMatchObject({ failed: 1, revoked: 0, granted: 0 })
expect(mockRecordProbeResult).toHaveBeenCalledTimes(1)
})
it('empty-register guard: no grants while rows exist downgrades nothing', async () => {
mockListOmbudGrants.mockResolvedValue([])
mockListConnections.mockResolvedValue([connection('c-1', '165560000000')])
const body = await (await GET(request())).json()
expect(body).toMatchObject({ registryHuvudman: 0, revoked: 0, skipped: 1, guardTripped: true, guardReason: 'empty_register' })
expect(mockRecordProbeResult).not.toHaveBeenCalled()
})
it('mass-downgrade guard: a run that would deny most granted rows applies no downgrade, but still records upgrades', async () => {
// Four granted rows; the register (say, with a mistyped pinned code) lists
// only one of them, plus a pending row that did get its grant.
mockListConnections.mockResolvedValue([
connection('c-1', '165510000000'),
connection('c-2', '165520000000'),
connection('c-3', '165530000000'),
connection('c-4', '165540000000'),
connection('c-new', '165550000000', 'unknown', 'unknown', 'pending'),
])
mockListOmbudGrants.mockResolvedValue([JLO('165510000000'), MOMS('165510000000'), JLO('165550000000'), MOMS('165550000000')])
const body = await (await GET(request())).json()
expect(body).toMatchObject({ guardTripped: true, guardReason: 'mass_downgrade', revoked: 0, skipped: 3, granted: 1, unchanged: 1 })
expect(mockRecordProbeResult).toHaveBeenCalledTimes(1)
expect(recordedFor('c-new')[0]).toMatchObject({ lasombud: { status: 'granted' } })
})
it('a contested org number (two live companies claim it) is never granted, and an existing grant on it is withdrawn', async () => {
mockListConnections.mockResolvedValue([
connection('c-victim', '165560000000'), // verified before the twin appeared
connection('c-twin', '165560000000', 'unknown', 'unknown', 'pending'),
connection('c-clear', '165570000000', 'unknown', 'unknown', 'pending'),
])
mockContested.mockResolvedValue(new Set(['165560000000']))
mockListOmbudGrants.mockResolvedValue([JLO('165560000000'), MOMS('165560000000'), JLO('165570000000')])
const body = await (await GET(request())).json()
expect(body).toMatchObject({ contested: 2, revoked: 1, granted: 1, guardTripped: false })
expect(mockRecordProbeResult).toHaveBeenCalledTimes(2)
expect(recordedFor('c-clear')[0]).toMatchObject({ lasombud: { status: 'granted' } })
expect(recordedFor('c-victim')[0]).toMatchObject({
lasombud: { status: 'denied', detail: expect.stringContaining('fler än ett företag') },
momsOmbud: { status: 'denied' },
})
expect(recordedFor('c-twin')).toHaveLength(0)
})
it('a huvudman listed with only unrecognised role codes is neither granted nor denied (pinning problem)', async () => {
mockListConnections.mockResolvedValue([connection('c-1', '165560000000')])
mockListOmbudGrants.mockResolvedValue([
{ huvudman: '165560000000', roll: 'ZZ9', rollbeskrivning: 'Läsombud, juridisk person', giltigFrom: '2026-07-19' },
])
const body = await (await GET(request())).json()
expect(body).toMatchObject({ unrecognized: 1, revoked: 0, denied: 0, guardTripped: false })
expect(mockRecordProbeResult).not.toHaveBeenCalled()
})
it('mass-downgrade guard needs at least three planned downgrades', async () => {
mockListConnections.mockResolvedValue([
connection('c-1', '165510000000'),
connection('c-2', '165520000000'),
])
mockListOmbudGrants.mockResolvedValue([JLO('165510000000'), MOMS('165510000000')])
const body = await (await GET(request())).json()
expect(body).toMatchObject({ guardTripped: false, revoked: 1 })
})
})
@@ -0,0 +1,273 @@
import { NextResponse } from 'next/server'
import { ensureInitialized } from '@/lib/init'
import { verifyCronSecret } from '@/lib/auth/cron'
import { loadExtensions } from '@/lib/extensions/loader'
import { extensionRegistry } from '@/lib/extensions/registry'
import { getSystemAuthMode, isSystemAuthConfigured } from '@/extensions/general/skatteverket/lib/system-auth/config'
import { currentSkvEnvironment } from '@/extensions/general/skatteverket/lib/resolve-auth'
import {
findContestedOrgNumbers,
listConnections,
recordProbeResult,
type GrantStatus,
type SkvCompanyConnection,
} from '@/extensions/general/skatteverket/lib/connection-store'
import {
isoDate,
listOmbudGrants,
summarizeGrants,
type HuvudmanGrantSummary,
} from '@/extensions/general/skatteverket/lib/ombud-client'
ensureInitialized()
export const maxDuration = 60
const TIME_BUDGET_MS = 50_000
/**
* Downgrade guard: a single run may not turn more than this share of the
* currently granted rows into fully denied ones. A mistyped pinned role code,
* a renamed rollbeskrivning, or a partial register response would otherwise
* deny every company in one night and silently push their background reads
* back onto 65-minute personal tokens. Below MIN_ROWS the share test is
* meaningless (one of two rows is 50%), so small fleets are guarded by the
* absolute floor instead.
*/
export const MASS_DOWNGRADE_MIN_ROWS = 3
export const MASS_DOWNGRADE_MAX_SHARE = 0.5
/**
* GET /api/extensions/skatteverket/ombud/sync/cron
*
* Daily ombudsregister sync (cron 30 3 * * *, half an hour before the
* skattekonto sync so a grant signed yesterday is used this morning).
*
* Companies appoint Accounted as ombud in Skatteverket's e-service, and
* nothing calls us back. One call to Ombudshantering v2
* (GET /ombud/autentisieratOmbud on the system identity) lists every huvudman
* that granted Accounted anything, and this route reconciles that list
* against the company's OWN connection row:
*
* - only rows that already exist are touched. A row exists because a
* member of that company pressed Verifiera or minted the deep link: the
* tenant's explicit opt-in. Rows are never created here,
* - an org number claimed by more than one live company is contested:
* no row on it is granted or changed (org-number reuse is allowed and
* org numbers are public, so a tenant that typed a victim's number must
* not inherit the victim's grant; see findContestedOrgNumbers),
* - rows marked 'revoked' by the tenant's own "Koppla från" stay revoked
* until a member re-verifies; a still-standing grant at Skatteverket is
* not permission to switch the row back on,
* - a listed huvudman: granted/denied per behörighet from its active roles,
* - an unlisted huvudman: both behörigheter denied (withdrawn or expired),
* subject to the downgrade guards below.
*
* Runs in shadow mode as well as on: it only records grant state, never
* changes which credentials a read uses (that policy lives in
* resolveReadAuth). Off mode, or an unconfigured system flow, is a no-op.
*
* Downgrade guards: (1) an empty register while rows exist downgrades
* nothing (a wrong base URL or a "wrong URI" 404 must not mass-revoke);
* (2) a run that would fully deny more than MASS_DOWNGRADE_MAX_SHARE of the
* currently granted rows (and at least MASS_DOWNGRADE_MIN_ROWS of them)
* applies no downgrades at all and reports guardTripped, so a classification
* or partial-response problem surfaces in the logs instead of in every
* company's settings.
*/
export async function GET(request: Request) {
const authError = verifyCronSecret(request)
if (authError) return authError
// Physical routes under app/api/extensions/<id>/ compile into every build,
// including core-with-zero-extensions: the registry is what switches the
// extension on, so a disabled extension must refuse visibly (503).
loadExtensions()
if (!extensionRegistry.get('skatteverket')) {
return NextResponse.json(
{ error: 'Skatteverket extension is not enabled', code: 'EXTENSION_DISABLED' },
{ status: 503 }
)
}
if (process.env.SKATTEVERKET_ENABLED !== 'true') {
return NextResponse.json({ message: 'Skatteverket extension disabled', processed: 0 })
}
if (getSystemAuthMode() === 'off' || !isSystemAuthConfigured()) {
return NextResponse.json({ message: 'System auth not active', processed: 0 })
}
const startedAt = Date.now()
const environment = currentSkvEnvironment()
const today = isoDate(new Date())
let grants: Map<string, HuvudmanGrantSummary>
try {
grants = summarizeGrants(await listOmbudGrants({}, { emptyOn404: true }), today)
} catch (error) {
console.error('[ombud-sync-cron] ombudsregister lookup failed', {
message: error instanceof Error ? error.message : String(error),
})
return NextResponse.json({ error: 'Ombudsregister lookup failed' }, { status: 502 })
}
const rows = (await listConnections(environment)).filter((row) => row.status !== 'revoked')
const contested = await findContestedOrgNumbers()
const decisions = planDecisions(rows, grants, today, contested)
const grantedNow = rows.filter(isAnyGranted).length
const fullDowngrades = decisions.filter((d) => d.kind === 'downgrade').length
const emptyRegisterGuard = grants.size === 0 && rows.length > 0
const massDowngradeGuard =
fullDowngrades >= MASS_DOWNGRADE_MIN_ROWS && fullDowngrades > grantedNow * MASS_DOWNGRADE_MAX_SHARE
const guardTripped = emptyRegisterGuard || massDowngradeGuard
if (guardTripped) {
console.warn('[ombud-sync-cron] downgrade guard tripped; no row is downgraded this run', {
environment,
registryHuvudman: grants.size,
rows: rows.length,
grantedNow,
plannedDowngrades: fullDowngrades,
reason: emptyRegisterGuard ? 'empty_register' : 'mass_downgrade',
})
}
const counts = { granted: 0, denied: 0, revoked: 0, unchanged: 0, contested: 0, unrecognized: 0, failed: 0, skipped: 0 }
for (const decision of decisions) {
if (Date.now() - startedAt > TIME_BUDGET_MS) {
counts.skipped += 1
continue
}
if (decision.kind === 'downgrade' && guardTripped) {
counts.skipped += 1
continue
}
if (decision.kind === 'contested') {
counts.contested += 1
if (!decision.lasombud || !decision.momsOmbud) continue
const withdrawn = await recordProbeResult({
companyId: decision.row.company_id,
environment,
orgNumber: decision.row.org_number,
lasombud: { status: decision.lasombud, detail: decision.detail },
momsOmbud: { status: decision.momsOmbud, detail: decision.detail },
error: null,
})
if (withdrawn) counts.revoked += 1
else counts.failed += 1
continue
}
if (decision.kind === 'unrecognized') {
counts.unrecognized += 1
continue
}
if (decision.kind === 'unchanged') {
counts.unchanged += 1
continue
}
const recorded = await recordProbeResult({
companyId: decision.row.company_id,
environment,
orgNumber: decision.row.org_number,
lasombud: { status: decision.lasombud, detail: decision.detail },
momsOmbud: { status: decision.momsOmbud, detail: decision.detail },
error: null,
})
if (!recorded) {
counts.failed += 1
continue
}
if (decision.kind === 'downgrade') counts.revoked += 1
else if (decision.lasombud === 'granted' || decision.momsOmbud === 'granted') counts.granted += 1
else counts.denied += 1
}
return NextResponse.json({
environment,
registryHuvudman: grants.size,
rows: rows.length,
...counts,
guardTripped,
guardReason: emptyRegisterGuard ? 'empty_register' : massDowngradeGuard ? 'mass_downgrade' : null,
durationMs: Date.now() - startedAt,
})
}
function isAnyGranted(row: SkvCompanyConnection): boolean {
return row.lasombud_status === 'granted' || row.moms_ombud_status === 'granted'
}
type Decision =
| { kind: 'unchanged'; row: SkvCompanyConnection }
/**
* More than one live company claims this org number: nobody gets granted
* on it, and a row that already holds a grant has it withdrawn (the
* denied statuses are present exactly then).
*/
| {
kind: 'contested'
row: SkvCompanyConnection
lasombud?: GrantStatus
momsOmbud?: GrantStatus
detail?: string
}
/** The register lists roles we cannot name (codes unpinned/renamed): never a denial. */
| { kind: 'unrecognized'; row: SkvCompanyConnection }
| {
/** 'record' updates from the register; 'downgrade' is a granted row that would lose every grant. */
kind: 'record' | 'downgrade'
row: SkvCompanyConnection
lasombud: GrantStatus
momsOmbud: GrantStatus
detail: string
}
/**
* What the register says about each opted-in row, without writing anything:
* the guards need the whole picture before the first upsert.
*/
export function planDecisions(
rows: SkvCompanyConnection[],
grants: Map<string, HuvudmanGrantSummary>,
today: string,
contested: Set<string> = new Set()
): Decision[] {
const decisions: Decision[] = []
for (const row of rows) {
if (contested.has(row.org_number)) {
// A contested number is frozen in both directions: never granted, and
// any grant already recorded on it is withdrawn until support settles
// which tenant the org number belongs to. Withdrawn outside the
// downgrade guards on purpose: this is the guard.
if (isAnyGranted(row)) {
const detail = `ombudsregister ${today}: organisationsnumret används av fler än ett företag`
decisions.push({ kind: 'contested', row, lasombud: 'denied', momsOmbud: 'denied', detail })
} else {
decisions.push({ kind: 'contested', row })
}
continue
}
const summary = grants.get(row.org_number)
if (summary && summary.roles.length > 0 && !summary.recognized) {
// Same rule as probeViaOmbudsregister: unknown role codes are a
// pinning problem on our side, not a company withdrawing anything.
decisions.push({ kind: 'unrecognized', row })
continue
}
const lasombud: GrantStatus = summary?.lasombud ? 'granted' : 'denied'
const momsOmbud: GrantStatus = summary?.moms_ombud ? 'granted' : 'denied'
const detail = summary
? `ombudsregister ${today}: roller ${summary.roles.join(', ') || 'inga'}`
: `ombudsregister ${today}: huvudman saknas`
// A row already showing exactly this state is left alone, so a never-listed
// company is written once (unknown -> denied, "Saknas" in settings) and
// then skipped every following night.
if (row.lasombud_status === lasombud && row.moms_ombud_status === momsOmbud) {
decisions.push({ kind: 'unchanged', row })
continue
}
const losesEverything = isAnyGranted(row) && lasombud === 'denied' && momsOmbud === 'denied'
decisions.push({ kind: losesEverything ? 'downgrade' : 'record', row, lasombud, momsOmbud, detail })
}
return decisions
}
@@ -0,0 +1,166 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const mocks = vi.hoisted(() => ({
createClient: vi.fn(),
verifyCronSecret: vi.fn(),
getCompanyIdsWithCapability: vi.fn(),
createExtensionContext: vi.fn(),
syncSkattekonto: vi.fn(),
}))
vi.mock('@supabase/supabase-js', () => ({
createClient: (...args: unknown[]) => mocks.createClient(...args),
}))
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
vi.mock('@/lib/auth/cron', () => ({
verifyCronSecret: (...args: unknown[]) => mocks.verifyCronSecret(...args),
}))
vi.mock('@/lib/entitlements/has-capability', () => ({
getCompanyIdsWithCapability: (...args: unknown[]) => mocks.getCompanyIdsWithCapability(...args),
}))
vi.mock('@/lib/extensions/context-factory', () => ({
createExtensionContext: (...args: unknown[]) => mocks.createExtensionContext(...args),
}))
vi.mock('@/extensions/general/skatteverket/lib/skattekonto-sync', () => ({
SKATTEKONTO_LAST_SYNCED_AT_KEY: 'skattekonto_last_synced_at',
syncSkattekonto: (...args: unknown[]) => mocks.syncSkattekonto(...args),
}))
vi.mock('@/extensions/general/skatteverket/lib/api-client', () => {
class SkatteverketAuthError extends Error {
constructor(
message: string,
public readonly code: string,
) {
super(message)
}
}
return { SkatteverketAuthError }
})
vi.mock('@/extensions/general/skatteverket/lib/skattekonto-client', () => {
class SkatteverketSkattekontoError extends Error {
felkod = 'TEST'
}
return { SkatteverketSkattekontoError }
})
vi.mock('@/extensions/general/skatteverket/lib/token-store', () => ({
RECONSENT_ERROR_CODES: [] as const,
markNeedsReconsent: vi.fn(),
}))
vi.mock('@/extensions/general/skatteverket/lib/system-auth/config', () => ({
getSystemAuthMode: vi.fn(() => 'off'),
isSystemAuthConfigured: vi.fn(() => false),
}))
vi.mock('@/extensions/general/skatteverket/lib/connection-store', () => ({
listVerifiedCompanies: vi.fn().mockResolvedValue([]),
markGrantRevoked: vi.fn(),
}))
vi.mock('@/extensions/general/skatteverket/lib/resolve-auth', () => ({
currentSkvEnvironment: vi.fn(() => 'test'),
hasVerifiedGrant: vi.fn().mockResolvedValue(false),
}))
vi.mock('@/lib/errors/get-error-message', () => ({
getErrorMessage: vi.fn(() => 'Något gick fel. Försök igen.'),
}))
import { GET } from '../route'
function makeRequest(): Request {
return new Request('http://localhost/api/extensions/skatteverket/skattekonto/sync/cron')
}
function makeSupabaseStub(tokens: Record<string, unknown>[]) {
return {
from: vi.fn((table: string) => {
const resolved = table === 'skatteverket_tokens'
? { data: tokens, error: null }
: { data: null, error: null }
const chain: any = {}
for (const method of ['select', 'eq', 'order', 'range']) {
chain[method] = vi.fn(() => chain)
}
chain.maybeSingle = vi.fn().mockResolvedValue(resolved)
chain.then = (resolve: (value: unknown) => void) => resolve(resolved)
return chain
}),
}
}
describe('GET /api/extensions/skatteverket/skattekonto/sync/cron', () => {
let errorSpy: ReturnType<typeof vi.spyOn>
let infoSpy: ReturnType<typeof vi.spyOn>
let logSpy: ReturnType<typeof vi.spyOn>
beforeEach(() => {
vi.clearAllMocks()
process.env.SKATTEVERKET_ENABLED = 'true'
process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://test.supabase.co'
process.env.SUPABASE_SERVICE_ROLE_KEY = 'service-key'
mocks.verifyCronSecret.mockReturnValue(null)
mocks.createExtensionContext.mockImplementation(
(supabase: unknown, userId: string, companyId: string) => ({ supabase, userId, companyId }),
)
mocks.syncSkattekonto.mockResolvedValue({ booked: 0, upcoming: 0 })
errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
infoSpy = vi.spyOn(console, 'info').mockImplementation(() => {})
logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
})
afterEach(() => {
errorSpy.mockRestore()
infoSpy.mockRestore()
logSpy.mockRestore()
vi.unstubAllEnvs()
})
it('returns 401 before creating a database client when cron auth fails', async () => {
mocks.verifyCronSecret.mockReturnValueOnce(
new Response(JSON.stringify({ error: 'Unauthorized' }), { status: 401 }),
)
const response = await GET(makeRequest())
expect(response.status).toBe(401)
expect(mocks.createClient).not.toHaveBeenCalled()
})
it('syncs an entitled company after fifty ineligible token rows', async () => {
const entitledCompanyId = '11111111-1111-4111-8111-111111111111'
const tokens = [
...Array.from({ length: 50 }, (_, index) => ({
user_id: `00000000-0000-4000-8000-${String(index).padStart(12, '0')}`,
company_id: `22222222-2222-4222-8222-${String(index).padStart(12, '0')}`,
expires_at: `2026-01-${String((index % 28) + 1).padStart(2, '0')}T00:00:00Z`,
refresh_count: 0,
})),
{
user_id: '33333333-3333-4333-8333-333333333333',
company_id: entitledCompanyId,
expires_at: '2099-01-01T00:00:00Z',
refresh_count: 0,
},
]
mocks.createClient.mockReturnValue(makeSupabaseStub(tokens))
mocks.getCompanyIdsWithCapability.mockResolvedValue(new Set([entitledCompanyId]))
const response = await GET(makeRequest())
const body = await response.json()
expect(response.status).toBe(200)
expect(body).toMatchObject({ processed: 1, synced: 1, errors: 0 })
expect(mocks.syncSkattekonto).toHaveBeenCalledTimes(1)
expect(mocks.syncSkattekonto.mock.calls[0][0]).toMatchObject({ companyId: entitledCompanyId })
})
})

Some files were not shown because too many files have changed in this diff Show More