Fix/attributes config (#926)
* fix(git): pin LF on generated extension registry and vitest snapshots setup:extensions and vitest write these files with LF; with core.autocrlf=true git expects CRLF and flags them as phantom modifications on every dev/build run. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(security): enforce MFA on mcp-oauth consent and gate viewer storno route mcp-oauth/authorize renders an HTML consent page and issues 303 redirects that withRouteContext cannot express, so it kept raw getUser() and thereby skipped the AAL2 gate: a password-only (AAL1) session could approve consent that mints a long-lived, MFA-bypassing API key. Add a route-local requireAal2() step-up on GET and POST; AAL1 sessions redirect to /mfa/verify, BankID users are exempt. Separately, POST /api/reports/vat-declaration/rc-basis-gaps/fix calls correctEntry() (storno of a posted entry) but lacked requireWrite, so viewer-role members could trigger it. Add { requireWrite: true }. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(api): route transactions endpoints through withRouteContext Migrate the transactions routes off hand-rolled supabase.auth.getUser() onto the MFA-enforcing withRouteContext wrapper; add requireWrite on mutating handlers (book, uncategorize, attach-document, ignore, batch-match, create-from-document). Behavior and response shapes preserved; tests updated to the wrapper mock pattern. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(api): route SIE import and bank reconciliation through withRouteContext Migrate import/sie and reconciliation/bank routes onto the MFA-enforcing wrapper; requireWrite on mutations (import execute, create-accounts, mappings write verbs, link/unlink/run/mark-opening-balance). Reads (status, unmatched-entries) stay ungated. Response shapes preserved; tests added/updated to the wrapper mock pattern. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(api): route salary endpoints through withRouteContext Migrate salary employees and runs routes (plus ku, payroll-config, tax-tables) onto the MFA-enforcing wrapper; requireWrite on mutations. Personnummer masking/encryption untouched; file downloads (AGI XML, payslip PDF, payment files) keep their headers. Two payment-file GETs retain requireWrite because they stamp *_file_generated_at and previously gated viewers. Tests added/updated to the wrapper mock pattern. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(api): route report endpoints through withRouteContext Migrate the read-only report routes (trial balance, balansrapport, resultatrapport, income statement, ledgers, KPI, VAT declaration, salary journal, monthly breakdown, journal register, continuity check, full archive, etc.) onto the MFA-enforcing wrapper. All read-only, no requireWrite. JSON/XLSX/PDF/ZIP response bodies and headers preserved byte-for-byte; tests updated to the wrapper mock pattern. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(api): route invoices, skatteverket, agent and extension endpoints through withRouteContext Migrate invoices, supplier-invoices, skatteverket tax-payments, and dynamic extension routes onto the MFA-enforcing wrapper with requireWrite on mutations. The two NDJSON streaming agent routes (invoke, onboarding/stream) use requireAuth() directly (the wrapper can't wrap a streaming response) so MFA is still enforced. skatteverket payment-file GET keeps requireWrite (stamps a generated-at field). Response shapes and file headers preserved; tests added/updated. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(api): route documents, events, team and account endpoints through withRouteContext Migrate documents, events, kpi/preferences, vat/validate, support/contact onto the MFA-enforcing wrapper with requireWrite on mutations. account/password, team/accept and team/members use requireAuth() directly (user-level or pre-membership flows with no active company context) so MFA is still enforced. events keeps its dual API-key-or-session auth. Document retention guard untouched; tests added/updated. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(api): route settings and pending-operations endpoints through withRouteContext Migrate settings (api-keys, oauth-clients, booking-templates, counterparty-templates, logo, company settings) and pending-operations (commit, bulk-commit, reject, edit-before-approve) onto the MFA-enforcing wrapper with requireWrite on mutations. Credential-guarding routes keep their per-user ownership filters. Response shapes preserved; tests added/updated to the wrapper mock pattern. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * chore(guards): ratchet raw-route-auth baseline 119->1 after A1 migration Lock in the withRouteContext migration so the count cannot regress. The single remaining entry, mcp-oauth/authorize, is a documented exception (HTML consent + redirects, MFA enforced via route-local step-up). Record the campaign and requireWrite decisions in DECISIONS.md. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(vat): add eSKD momsdeklaration file export for "Deklarera via fil" Generate the Skatteverket eSKDUpload v6.0 XML file so users can file VAT by upload instead of typing every ruta into the form. Extract buildFiledAmounts() as the shared whole-krona source of truth (öre truncated per SFL 22 kap 1 §) so the XML file and the manual-filing PDF can never disagree. Adds the /eskd API route, an XML option in the report export menu, and the upload button on the manual-filing card. Strings in sv + en. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(vat): add 'vat_settlement' source type and update related components * fix(booking): adjust search input layout and enable autofocus * fix(vat): support 12-digit org numbers and adjust emission order for eSKD file * fix(migration): add 'vat_settlement' to journal_entries.source_type CHECK --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
63e05c4eec
commit
abe9ac9d8c
@@ -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: 'test@test.se' }
|
||||
|
||||
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)
|
||||
})
|
||||
})
|
||||
@@ -1,21 +1,10 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import { requireWritePermission } from '@/lib/auth/require-write'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
|
||||
export async function GET(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ sector: string; slug: string }> }
|
||||
) {
|
||||
export const GET = withRouteContext<{ params: Promise<{ sector: string; slug: string }> }>(
|
||||
'extension.data.get',
|
||||
async (request, { supabase, companyId }, { params }) => {
|
||||
const { sector, slug } = await params
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const extensionId = `${sector}/${slug}`
|
||||
|
||||
@@ -43,24 +32,13 @@ export async function GET(
|
||||
}
|
||||
|
||||
return NextResponse.json({ data })
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
export async function POST(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ sector: string; slug: string }> }
|
||||
) {
|
||||
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 supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const writeCheck = await requireWritePermission(supabase, user.id)
|
||||
if (!writeCheck.ok) return writeCheck.response
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const body = await request.json()
|
||||
const { key, value } = body
|
||||
@@ -91,24 +69,14 @@ export async function POST(
|
||||
}
|
||||
|
||||
return NextResponse.json({ data })
|
||||
}
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
|
||||
export async function DELETE(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ sector: string; slug: string }> }
|
||||
) {
|
||||
export const DELETE = withRouteContext<{ params: Promise<{ sector: string; slug: string }> }>(
|
||||
'extension.data.delete',
|
||||
async (request, { supabase, companyId }, { params }) => {
|
||||
const { sector, slug } = await params
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const writeCheck = await requireWritePermission(supabase, user.id)
|
||||
if (!writeCheck.ok) return writeCheck.response
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const key = searchParams.get('key')
|
||||
@@ -131,4 +99,6 @@ export async function DELETE(
|
||||
}
|
||||
|
||||
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: 'test@test.se' }
|
||||
|
||||
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 })
|
||||
})
|
||||
})
|
||||
@@ -1,21 +1,10 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import { requireWritePermission } from '@/lib/auth/require-write'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
|
||||
export async function GET(
|
||||
_request: Request,
|
||||
{ params }: { params: Promise<{ sector: string; slug: string }> }
|
||||
) {
|
||||
export const GET = withRouteContext<{ params: Promise<{ sector: string; slug: string }> }>(
|
||||
'extension.settings.get',
|
||||
async (_request, { supabase, companyId }, { params }) => {
|
||||
const { sector, slug } = await params
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const extensionId = `${sector}/${slug}`
|
||||
|
||||
@@ -28,24 +17,13 @@ export async function GET(
|
||||
.single()
|
||||
|
||||
return NextResponse.json({ data: data?.value ?? {} })
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
export async function PATCH(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ sector: string; slug: string }> }
|
||||
) {
|
||||
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 supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const writeCheck = await requireWritePermission(supabase, user.id)
|
||||
if (!writeCheck.ok) return writeCheck.response
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const body = await request.json()
|
||||
const extensionId = `${sector}/${slug}`
|
||||
@@ -81,4 +59,6 @@ export async function PATCH(
|
||||
}
|
||||
|
||||
return NextResponse.json({ data: data.value })
|
||||
}
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
|
||||
@@ -1,15 +1,11 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { createExtensionContext } from '@/lib/extensions/context-factory'
|
||||
import { computeSkattekontoDrift } from '@/extensions/general/skatteverket/lib/skattekonto-drift'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
const log = createLogger('skattekonto-drift-route')
|
||||
|
||||
/**
|
||||
* GET /api/extensions/skatteverket/skattekonto/drift
|
||||
*
|
||||
@@ -23,22 +19,15 @@ const log = createLogger('skattekonto-drift-route')
|
||||
* log line gives an auditable record without overrunning the 30-day event
|
||||
* log retention (SOC 2 CC8.1, ISO 27001 A.8.15).
|
||||
*/
|
||||
export async function GET(_request: Request) {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
export const GET = withRouteContext(
|
||||
'skatteverket.skattekonto.drift',
|
||||
async (_request, { supabase, user, companyId, log, requestId }) => {
|
||||
const ctx = createExtensionContext(supabase, user.id, companyId, 'skatteverket', requestId)
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
const ctx = createExtensionContext(supabase, user.id, companyId, 'skatteverket')
|
||||
|
||||
const drift = await computeSkattekontoDrift(ctx)
|
||||
log.info('skattekonto drift snapshot accessed', {
|
||||
userId: user.id,
|
||||
companyId,
|
||||
hasDrift: drift !== null,
|
||||
})
|
||||
return NextResponse.json({ data: drift })
|
||||
}
|
||||
const drift = await computeSkattekontoDrift(ctx)
|
||||
log.info('skattekonto drift snapshot accessed', {
|
||||
hasDrift: drift !== null,
|
||||
})
|
||||
return NextResponse.json({ data: drift })
|
||||
},
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user