Files
accounted/lib/auth/require-auth.ts
T
Mattsson 288915c152 Fix/fdb fr usrs (#1125)
* fix(invoices): return attachment filename in delivery history summaries

The 20260723003000 hardening dropped attachment_filename from
list_invoice_delivery_summaries, so the delivery history UI always fell
back to the generic "faktura.pdf" label. Recreate the RPC with the
filename included: it is derived from company name, customer name,
invoice number, and date, all already visible to every company member,
so the minimization boundary is unchanged. Addresses stay masked and
message content, BCC, and checksums stay server-side.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(reconciliation): surface own-account transfer legs in match-to-voucher by default

The second (incoming) leg of a transfer between two of the company's own
bank accounts was hidden in the 'Matcha mot befintlig verifikation' dialog
because the voucher counted as 'already matched' once its outgoing leg was
linked, even though the incoming account's line had no settling transaction.
Users read the empty default list as 'the app won't let me link this'.

get_account_gl_lines_for_matching now counts links per settlement account:
a transaction provably on another cash account no longer marks the voucher
as matched for the requested account, so the unsettled transfer leg surfaces
by default (and auto-selects on an exact match). Same-account N:1 stays
behind the 'Visa aven matchade verifikationer' opt-in, and transactions
without a resolvable cash account conservatively keep counting everywhere.
get_unlinked_gl_lines is deliberately untouched (feeds auto-reconcile).

Companion guard: mark_entry_as_opening_balance now refuses entries with
linked bank transactions, since half-settled transfer vouchers became
reachable in the reconciliation view's unmatched table where 'Mark som IB'
renders; re-tagging one would strand its transaction against a movement-
excluded entry. getReconciliationStatus counts unmatched GL lines with the
account-scoped RPC so the status card agrees with the table.

Fixes #1026

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* perf(api): cut prod p95 latency via local JWT auth, single-RT company resolution, and report aggregate RPCs

Baseline 2026-07-23 (487 prod samples): p50 160ms, p95 480ms, 13% of
requests over 300ms. Target: p95 under 300ms.

- requireAuth: verify JWTs locally via getClaims (ES256/JWKS) instead of
  a second network getUser per request; getUser fallback keeps HS256
  self-hosted and existing test mocks working; middleware still
  revocation-checks every /api request
- resolve_active_company RPC (20260723161000): one round trip replaces
  2-3 queries in getActiveCompanyId and middleware; PGRST202/42501 fall
  back to the legacy query path
- arsredovisning build-data: ~33 sequential round trips down to ~7,
  output byte-identical (snapshot-proven)
- currency rate route: stop bypassing the exchange_rates cache (missing
  supabase arg caused an external Riksbanken call on every request)
- document.get: parallelize row fetch, signed URL and audit event
- list_company_accounts RPC (20260723170000): accounts list in one round
  trip instead of paging past PostgREST's 1000-row cap
- vat-declaration route: drop a dead sequential company_settings query
- get_kpi_report_aggregates RPC (20260723180000): KPI report's three
  full-period line scans collapsed into one aggregate call; dimension-
  filtered path unchanged
- lint: fix 9 baseline errors, downgrade 4 react-hooks compiler rules to
  warn, zero the eslint baseline ratchet

All four gates green: lint 0 errors, 9163 tests, check:guards, build.
Migrations applied idempotently to staging only; prod receives them via
Supabase branching on merge.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(review): resolve PR review findings across auth, VAT declaration, and IB retag

- requireAuth getClaims fast path: pin iss (project URL) and aud
  ('authenticated'), log every fallback to getUser (ASVS V9.1 finding)
- remove the ignored accountingMethod parameter from calculateVatDeclaration
  and the dead company_settings.accounting_method reads in xlsx/pdf/eskd
  routes; v1 API keeps accepting the query param but documents it as a no-op
- close the mark_entry_as_opening_balance TOCTOU race with a transactions
  trigger (20260723190000, FOR KEY SHARE on journal_entries) + pg tests;
  applied to staging and smoke-verified both directions
- re-add the 42501 tenant guard to branch-local migration 20260723160000
  (function body had silently reverted to the pre-20260619130100 definition)
- document the buildK3Noter tbFullRows full-TB contract (uppskjuten skatt
  opening balance per BFNAR 2012:1 ch.29)
- add KPI VAT-liability test covering reduced-rate output accounts 2621/2631

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(db): use NULL-safe caller_is_company_member in opening-balance retag guard

The re-added tenant guard carried the pre-20260703180000 raw
NOT IN (SELECT user_company_ids()) pattern, which the
null-safe-tenant-guards ratchet blocks. Staging re-synced.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-23 16:16:55 +02:00

118 lines
4.4 KiB
TypeScript

import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { shouldEnforceMfa } from './mfa'
import type { User, SupabaseClient, JwtPayload } from '@supabase/supabase-js'
type AuthResult =
| { user: User; supabase: SupabaseClient; error: null }
| { user: null; supabase: SupabaseClient; error: NextResponse }
/**
* Maps verified JWT claims onto the User subset routes actually consume
* (id, email, is_anonymous, app_metadata, user_metadata, role, phone).
*
* Server-only fields (identities, factors, created_at timestamps) are absent
* from the token and verified unused by any route (2026-07-23 audit);
* created_at is set to '' only to satisfy the type.
*/
/**
* Defense-in-depth pinning on top of getClaims' signature/expiry verification:
* the token must come from THIS project's auth server (iss) and be an
* end-user access token (aud 'authenticated'; anonymous sign-ins share it).
* A mismatch is not treated as unauthenticated: we fall back to the
* server-side getUser() check, which is authoritative.
*/
function claimsPinned(claims: JwtPayload): boolean {
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL?.replace(/\/+$/, '')
// Without a configured URL (unit tests) there is nothing to pin against.
const issOk = !supabaseUrl || claims.iss === `${supabaseUrl}/auth/v1`
const aud = claims.aud
const audOk = Array.isArray(aud) ? aud.includes('authenticated') : aud === 'authenticated'
return issOk && audOk
}
function userFromClaims(claims: JwtPayload): User {
return {
id: claims.sub,
aud: Array.isArray(claims.aud) ? (claims.aud[0] ?? 'authenticated') : (claims.aud ?? 'authenticated'),
role: claims.role,
email: claims.email,
phone: claims.phone,
app_metadata: claims.app_metadata ?? {},
user_metadata: claims.user_metadata ?? {},
is_anonymous: claims.is_anonymous ?? false,
created_at: '',
}
}
/**
* Auth + MFA guard for API routes.
*
* Returns the authenticated user and Supabase client, or a JSON error response.
* When MFA is required (hosted deployment), verifies AAL2 assurance level.
*
* Fast path: getClaims() performs local WebCrypto verification against the
* shared 10-minute JWKS cache instead of a per-request network getUser()
* round trip. HS256/self-hosted projects fall back to a server call inside
* getClaims itself (identical semantics; NEXT_PUBLIC_SELF_HOSTED needs no
* special-casing). Revocation is still checked on every request by proxy.ts
* middleware getUser() before any route runs. Claims-sourced metadata
* (email, app_metadata, is_anonymous) can be up to one access-token TTL
* stale, which is acceptable for all current consumers: bankid_linked
* staleness is covered because the middleware MFA gate
* (lib/supabase/middleware.ts) uses the FRESH getUser result.
*/
export async function requireAuth(): Promise<AuthResult> {
const supabase = await createClient()
let user: User | null = null
try {
// The typeof guard keeps legacy test mocks (auth object with only
// getUser) on the old path.
if (typeof supabase.auth.getClaims === 'function') {
const { data } = await supabase.auth.getClaims()
const claims = data?.claims
if (claims?.sub) {
if (claimsPinned(claims)) {
user = userFromClaims(claims)
} else {
console.error('requireAuth: getClaims iss/aud pinning failed; falling back to getUser', {
iss: claims.iss,
aud: claims.aud,
})
}
}
}
} catch (err) {
// JWKS outage or malformed token: fall through to the server-side check.
// Logged because every hit here degrades the request to the slower
// getUser round trip; a spike must be visible in production.
console.error('requireAuth: getClaims failed; falling back to getUser', err)
}
if (!user) {
const { data } = await supabase.auth.getUser()
user = data?.user ?? null
}
if (!user) {
return {
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
}
}
if (shouldEnforceMfa(user)) {
const { data: aal } = await supabase.auth.mfa.getAuthenticatorAssuranceLevel()
if (aal?.nextLevel === 'aal2' && aal?.currentLevel !== 'aal2') {
return {
user: null,
supabase,
error: NextResponse.json({ error: 'MFA verification required' }, { status: 403 }),
}
}
}
return { user, supabase, error: null }
}