abe9ac9d8c
* 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>
137 lines
4.3 KiB
TypeScript
137 lines
4.3 KiB
TypeScript
import { createServiceClient } from '@/lib/supabase/server'
|
|
import { NextResponse, type NextRequest } from 'next/server'
|
|
import { requireAuth } from '@/lib/auth/require-auth'
|
|
import { hashInviteToken } from '@/lib/auth/invite-tokens'
|
|
|
|
/**
|
|
* GET /api/team/accept?token=xxx
|
|
* Validates an invite token and returns invite info (for the invite page).
|
|
* Only company invitations are supported: team invitations are disabled.
|
|
* No auth required: this is a public endpoint.
|
|
*/
|
|
export async function GET(request: NextRequest) {
|
|
const token = request.nextUrl.searchParams.get('token')
|
|
if (!token) {
|
|
return NextResponse.json({ error: 'Token saknas.' }, { status: 400 })
|
|
}
|
|
|
|
const tokenHash = hashInviteToken(token)
|
|
const serviceClient = createServiceClient()
|
|
|
|
const { data: companyInvite } = await serviceClient
|
|
.from('company_invitations')
|
|
.select('id, email, status, expires_at, company_id, companies:company_id(name)')
|
|
.eq('token_hash', tokenHash)
|
|
.single()
|
|
|
|
if (!companyInvite) {
|
|
return NextResponse.json({ error: 'Inbjudan hittades inte eller är ogiltig.' }, { status: 404 })
|
|
}
|
|
|
|
if (companyInvite.status !== 'pending') {
|
|
return NextResponse.json({ error: 'Inbjudan har redan använts.' }, { status: 410 })
|
|
}
|
|
|
|
const expired = new Date(companyInvite.expires_at) < new Date()
|
|
|
|
const { data: alreadyHasAccount } = await serviceClient.rpc('check_email_exists', {
|
|
email_to_check: companyInvite.email,
|
|
})
|
|
|
|
return NextResponse.json({
|
|
data: {
|
|
type: 'company',
|
|
companyName: (companyInvite.companies as unknown as { name: string })?.name || 'Företag',
|
|
email: companyInvite.email,
|
|
expired,
|
|
alreadyHasAccount,
|
|
},
|
|
})
|
|
}
|
|
|
|
/**
|
|
* POST /api/team/accept
|
|
* Accepts a company invite after the user has signed up.
|
|
* Team invitations are disabled: teams are single-user.
|
|
*/
|
|
export async function POST(request: NextRequest) {
|
|
const { user, error } = await requireAuth()
|
|
if (error) return error
|
|
|
|
const body = await request.json()
|
|
const token = body.token as string
|
|
if (!token) {
|
|
return NextResponse.json({ error: 'Token saknas.' }, { status: 400 })
|
|
}
|
|
|
|
const tokenHash = hashInviteToken(token)
|
|
const serviceClient = createServiceClient()
|
|
|
|
const { data: companyInvite, error: companyLookupError } = await serviceClient
|
|
.from('company_invitations')
|
|
.select('id, company_id, email, role, status, expires_at')
|
|
.eq('token_hash', tokenHash)
|
|
.single()
|
|
|
|
if (companyLookupError) {
|
|
console.error('[team/accept] company lookup error:', companyLookupError.message)
|
|
}
|
|
|
|
if (!companyInvite || companyInvite.status !== 'pending') {
|
|
return NextResponse.json({ error: 'Inbjudan är ogiltig.' }, { status: 400 })
|
|
}
|
|
|
|
if (new Date(companyInvite.expires_at) < new Date()) {
|
|
await serviceClient
|
|
.from('company_invitations')
|
|
.update({ status: 'expired' })
|
|
.eq('id', companyInvite.id)
|
|
return NextResponse.json({ error: 'Inbjudan har gått ut.' }, { status: 410 })
|
|
}
|
|
|
|
if (user.email?.toLowerCase() !== companyInvite.email.toLowerCase()) {
|
|
return NextResponse.json({ error: 'E-postadressen matchar inte inbjudan.' }, { status: 403 })
|
|
}
|
|
|
|
// Add user to company
|
|
const { error: memberError } = await serviceClient
|
|
.from('company_members')
|
|
.insert({
|
|
company_id: companyInvite.company_id,
|
|
user_id: user.id,
|
|
role: companyInvite.role,
|
|
source: 'direct',
|
|
})
|
|
|
|
if (memberError) {
|
|
if (memberError.code === '23505') {
|
|
return NextResponse.json({ error: 'Du är redan medlem.' }, { status: 409 })
|
|
}
|
|
return NextResponse.json({ error: 'Kunde inte lägga till medlem.' }, { status: 500 })
|
|
}
|
|
|
|
// Set active company. Non-fatal on failure: the membership insert already
|
|
// succeeded and middleware falls back to it, but log so silent
|
|
// persistence failures (#701) are observable.
|
|
const { error: prefError } = await serviceClient
|
|
.from('user_preferences')
|
|
.upsert({
|
|
user_id: user.id,
|
|
active_company_id: companyInvite.company_id,
|
|
}, { onConflict: 'user_id' })
|
|
|
|
if (prefError) {
|
|
console.error('[team/accept] failed to set active company', prefError)
|
|
}
|
|
|
|
// Mark invite as accepted
|
|
await serviceClient
|
|
.from('company_invitations')
|
|
.update({ status: 'accepted' })
|
|
.eq('id', companyInvite.id)
|
|
|
|
return NextResponse.json({
|
|
data: { type: 'company', companyId: companyInvite.company_id },
|
|
})
|
|
}
|