* 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>
99 lines
3.8 KiB
TypeScript
99 lines
3.8 KiB
TypeScript
import { NextResponse } from 'next/server'
|
|
import { z } from 'zod'
|
|
import { withRouteContext } from '@/lib/api/with-route-context'
|
|
|
|
const RejectBodySchema = z.object({
|
|
rejection_category: z
|
|
.enum(['wrong_category', 'wrong_amount', 'duplicate', 'wrong_period', 'other'])
|
|
.optional(),
|
|
rejection_reason: z.string().max(2000).optional(),
|
|
})
|
|
|
|
/**
|
|
* POST /api/pending-operations/:id/reject
|
|
*
|
|
* Reject a pending operation. Optionally accepts a JSON body with
|
|
* `rejection_category` (fixed enum) and `rejection_reason` (free text). Both
|
|
* are stored on the row so agents can fetch them via gnubok_get_recent_rejections
|
|
* and learn from "no". The body is optional: bodyless POSTs from older
|
|
* clients still mark the op rejected with NULL category/reason.
|
|
*/
|
|
export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
|
|
'pending_operation.reject',
|
|
async (request, { supabase, companyId }, { params }) => {
|
|
const { id } = await params
|
|
|
|
// Body is optional: accept empty/missing body without rejecting the request.
|
|
// Old clients posted no body; the UI dialog will now post a body, but we
|
|
// keep accepting both shapes to avoid coupling the API to the UI version.
|
|
let rejectionCategory: string | undefined
|
|
let rejectionReason: string | undefined
|
|
const contentLength = request.headers.get('content-length')
|
|
if (contentLength && contentLength !== '0') {
|
|
try {
|
|
const raw = await request.json()
|
|
const parsed = RejectBodySchema.safeParse(raw)
|
|
if (!parsed.success) {
|
|
return NextResponse.json(
|
|
{ error: parsed.error.issues.map((i) => i.message).join('; ') },
|
|
{ status: 400 },
|
|
)
|
|
}
|
|
rejectionCategory = parsed.data.rejection_category
|
|
rejectionReason = parsed.data.rejection_reason?.trim() || undefined
|
|
} catch {
|
|
// Body present but unparseable: fail closed.
|
|
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 })
|
|
}
|
|
}
|
|
|
|
const { data: op, error: fetchError } = await supabase
|
|
.from('pending_operations')
|
|
.select('id, status')
|
|
.eq('id', id)
|
|
.eq('company_id', companyId)
|
|
.single()
|
|
|
|
if (fetchError || !op) {
|
|
return NextResponse.json({ error: 'Pending operation not found' }, { status: 404 })
|
|
}
|
|
|
|
if (op.status !== 'pending') {
|
|
// There is no auto-commit path (removed in 20260505190027), so a non-pending
|
|
// status here means the op was resolved explicitly: almost always the user
|
|
// pressed Godkänn in the /pending (Att göra) UI in parallel, or another
|
|
// client already rejected it. Spell that out so an agent doesn't read the
|
|
// generic 409 as "the system committed it behind my back".
|
|
const explained =
|
|
op.status === 'rejected'
|
|
? 'Operation already rejected.'
|
|
: op.status === 'expired'
|
|
? 'Operation already expired and can no longer be rejected.'
|
|
: `Operation already ${op.status}: it was approved explicitly (most likely via the ` +
|
|
'Att göra / pending UI in parallel), not auto-committed. It can no longer be rejected; ' +
|
|
'reverse or correct the resulting verifikat instead.'
|
|
return NextResponse.json(
|
|
{ error: explained, status: op.status },
|
|
{ status: 409 }
|
|
)
|
|
}
|
|
|
|
const { error: updateError } = await supabase
|
|
.from('pending_operations')
|
|
.update({
|
|
status: 'rejected',
|
|
resolved_at: new Date().toISOString(),
|
|
...(rejectionCategory ? { rejection_category: rejectionCategory } : {}),
|
|
...(rejectionReason ? { rejection_reason: rejectionReason } : {}),
|
|
})
|
|
.eq('id', id)
|
|
|
|
if (updateError) {
|
|
return NextResponse.json({ error: updateError.message }, { status: 500 })
|
|
}
|
|
|
|
return NextResponse.json({ data: { id, status: 'rejected' } })
|
|
},
|
|
{ requireWrite: true },
|
|
)
|