Files
accounted/app/api/account/password/__tests__/route.test.ts
T
MattssonandClaude Opus 4.8 abe9ac9d8c 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>
2026-07-08 09:54:46 +02:00

305 lines
9.7 KiB
TypeScript

import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
vi.mock('@/lib/supabase/server', () => ({
createServiceClient: vi.fn(),
}))
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
import { createServiceClient } from '@/lib/supabase/server'
import { POST } from '../route'
const mockCreateServiceClient = vi.mocked(createServiceClient)
type AuthMetadata = Record<string, unknown>
function mockUserClient(opts: {
user: { id: string; app_metadata?: AuthMetadata } | null
updateUserError?: { message: string; status?: number; code?: string } | null
}) {
const updateUser = vi.fn().mockResolvedValue({
data: {},
error: opts.updateUserError ?? null,
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const supabase = { auth: { updateUser } } as any
if (opts.user) {
requireAuthMock.mockResolvedValue({ user: opts.user, supabase, error: null })
} else {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
}
return { updateUser }
}
function mockService(opts: {
priorAppMetadata?: AuthMetadata
// Returned-error from admin.updateUserById when called with { password }
passwordSetError?: { message: string; status?: number; code?: string } | null
// Thrown error from admin.updateUserById when called with { app_metadata }
flagFlipError?: Error | null
}) {
const updateUserById = vi
.fn()
.mockImplementation((_id: string, args: Record<string, unknown>) => {
if ('password' in args) {
return Promise.resolve({
data: {},
error: opts.passwordSetError ?? null,
})
}
if (opts.flagFlipError) return Promise.reject(opts.flagFlipError)
return Promise.resolve({ data: {}, error: null })
})
const getUserById = vi.fn().mockResolvedValue({
data: { user: { app_metadata: opts.priorAppMetadata ?? {} } },
})
mockCreateServiceClient.mockReturnValue({
auth: { admin: { getUserById, updateUserById } },
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)
return { getUserById, updateUserById }
}
const STRONG_PASSWORD = 'StrongP@ssword1'
function flagFlipCall(updateUserById: ReturnType<typeof vi.fn>) {
return updateUserById.mock.calls.find(
([, args]) => args && typeof args === 'object' && 'app_metadata' in args,
)
}
function passwordSetCall(updateUserById: ReturnType<typeof vi.fn>) {
return updateUserById.mock.calls.find(
([, args]) => args && typeof args === 'object' && 'password' in args,
)
}
beforeEach(() => {
vi.clearAllMocks()
})
describe('POST /api/account/password', () => {
it('returns 401 when unauthenticated', async () => {
mockUserClient({ user: null })
mockService({})
const req = createMockRequest('/api/account/password', {
method: 'POST',
body: { password: STRONG_PASSWORD },
})
const { status } = await parseJsonResponse(await POST(req))
expect(status).toBe(401)
})
it('returns 400 when password is too weak', async () => {
mockUserClient({ user: { id: 'user-1', app_metadata: { has_password: true } } })
mockService({ priorAppMetadata: { has_password: true } })
const req = createMockRequest('/api/account/password', {
method: 'POST',
body: { password: 'weak' },
})
const { status } = await parseJsonResponse(await POST(req))
expect(status).toBe(400)
})
describe('first-time set (has_password !== true)', () => {
it('writes the password via admin API and flips the flag', async () => {
const { updateUser } = mockUserClient({
user: {
id: 'user-1',
app_metadata: { has_password: false, bankid_linked: true },
},
})
const { updateUserById } = mockService({
priorAppMetadata: { has_password: false, bankid_linked: true },
})
const req = createMockRequest('/api/account/password', {
method: 'POST',
body: { password: STRONG_PASSWORD },
})
const { status, body } = await parseJsonResponse<{
data?: { ok: boolean }
}>(await POST(req))
expect(status).toBe(200)
expect(body.data?.ok).toBe(true)
// Did NOT go through the user session: that path would fail with AAL2.
expect(updateUser).not.toHaveBeenCalled()
// Password set via admin
expect(passwordSetCall(updateUserById)).toEqual([
'user-1',
{ password: STRONG_PASSWORD },
])
// Flag flipped, siblings preserved
expect(flagFlipCall(updateUserById)).toEqual([
'user-1',
{
app_metadata: {
has_password: true,
bankid_linked: true,
},
},
])
})
it('treats unset has_password as first-time set', async () => {
const { updateUser } = mockUserClient({
user: { id: 'user-1' /* no app_metadata */ },
})
const { updateUserById } = mockService({})
const req = createMockRequest('/api/account/password', {
method: 'POST',
body: { password: STRONG_PASSWORD },
})
const { status } = await parseJsonResponse(await POST(req))
expect(status).toBe(200)
expect(updateUser).not.toHaveBeenCalled()
expect(passwordSetCall(updateUserById)).toBeDefined()
})
it('returns 400 and skips flag flip when the admin password set fails', async () => {
const { updateUser } = mockUserClient({
user: { id: 'user-1', app_metadata: { has_password: false } },
})
const { updateUserById } = mockService({
priorAppMetadata: { has_password: false },
passwordSetError: { message: 'Password too weak', status: 400 },
})
const req = createMockRequest('/api/account/password', {
method: 'POST',
body: { password: STRONG_PASSWORD },
})
const { status, body } = await parseJsonResponse<{ error?: string }>(
await POST(req),
)
expect(status).toBe(400)
expect(body.error).toContain('Password too weak')
expect(updateUser).not.toHaveBeenCalled()
expect(flagFlipCall(updateUserById)).toBeUndefined()
})
it('still returns success when the flag flip fails after admin password set', async () => {
mockUserClient({
user: { id: 'user-1', app_metadata: { has_password: false } },
})
mockService({
priorAppMetadata: { has_password: false },
flagFlipError: new Error('admin down'),
})
const req = createMockRequest('/api/account/password', {
method: 'POST',
body: { password: STRONG_PASSWORD },
})
const { status, body } = await parseJsonResponse<{
data?: { ok: boolean }
}>(await POST(req))
expect(status).toBe(200)
expect(body.data?.ok).toBe(true)
})
})
describe('change-password (has_password === true)', () => {
it('writes via the user session so Supabase enforces AAL2', async () => {
const { updateUser } = mockUserClient({
user: { id: 'user-1', app_metadata: { has_password: true } },
})
const { updateUserById } = mockService({
priorAppMetadata: { has_password: true, provider: 'email' },
})
const req = createMockRequest('/api/account/password', {
method: 'POST',
body: { password: STRONG_PASSWORD },
})
const { status, body } = await parseJsonResponse<{
data?: { ok: boolean }
}>(await POST(req))
expect(status).toBe(200)
expect(body.data?.ok).toBe(true)
// Used user session, NOT admin API for the password itself
expect(updateUser).toHaveBeenCalledWith({ password: STRONG_PASSWORD })
expect(passwordSetCall(updateUserById)).toBeUndefined()
// Flag is still flipped (idempotent) with siblings preserved
expect(flagFlipCall(updateUserById)).toEqual([
'user-1',
{
app_metadata: {
has_password: true,
provider: 'email',
},
},
])
})
it('returns 400 and skips flag flip when Supabase rejects the password update', async () => {
const { updateUser } = mockUserClient({
user: { id: 'user-1', app_metadata: { has_password: true } },
updateUserError: { message: 'Password too similar to old', status: 400 },
})
const { updateUserById } = mockService({
priorAppMetadata: { has_password: true },
})
const req = createMockRequest('/api/account/password', {
method: 'POST',
body: { password: STRONG_PASSWORD },
})
const { status, body } = await parseJsonResponse<{ error?: string }>(
await POST(req),
)
expect(status).toBe(400)
expect(body.error).toContain('Password too similar')
expect(updateUser).toHaveBeenCalledWith({ password: STRONG_PASSWORD })
expect(flagFlipCall(updateUserById)).toBeUndefined()
})
it('surfaces the AAL2 error verbatim so the client can step up via /mfa/verify', async () => {
mockUserClient({
user: { id: 'user-1', app_metadata: { has_password: true } },
updateUserError: {
message:
'AAL2 session is required to update email or password when MFA is enabled',
status: 422,
},
})
mockService({ priorAppMetadata: { has_password: true } })
const req = createMockRequest('/api/account/password', {
method: 'POST',
body: { password: STRONG_PASSWORD },
})
const { status, body } = await parseJsonResponse<{ error?: string }>(
await POST(req),
)
expect(status).toBe(400)
expect(body.error).toContain('AAL2')
})
})
})