Files
accounted/lib/auth/claims.ts
T
Jakob Wennberg 4ac7b45c8a perf(layout): dashboard layout in two waves, nav flags as one RPC, local JWT verification (#1946)
The dashboard layout runs on every hard load, hard refresh, company switch
and the 16 router.refresh() sites, and loading.tsx cannot paint until it
resolves. It cost ~20 network calls in 4 sequential waves: a third
getUser() round trip to Supabase Auth (after the proxy's and the route
guard's), the company resolution, then 16 reads including four limit-1
probes whose only job is to decide whether to render the Webshop and
Körjournal nav rows, and an entitlements read that itself ran two waves.

- lib/auth/claims.ts: claimsPinned/userFromClaims extracted from
  require-auth.ts (unchanged) so the dashboard request context shares the
  exact pinning + mapping. getDashboardAuthContext verifies the JWT locally
  and falls back to getUser() only when claims are missing, unpinned or
  unverifiable: the proxy already performed the per-request revocation
  check before the layout runs (same semantics approved for routes on
  2026-07-23).
- Wave 1 (user-keyed, parallel with the company resolution): team
  membership, profile, user preferences and the memberships join, which
  now also supplies the active company's row and role, so the separate
  companies and company_members reads are gone.
- Wave 2 (company-keyed): settings, agent profile, the switcher's settings
  names, entitlements in ONE wave (getCompanyEntitlements takes the
  team_id the join already carries and runs the grants read alongside
  config + subscription), and get_dashboard_nav_flags().
- supabase/migrations/20260826120000_get_dashboard_nav_flags.sql:
  SECURITY INVOKER, STABLE, EXECUTE for authenticated only; RLS applies
  inside. lib/dashboard/nav-flags.ts wraps it with the pre-RPC four-probe
  fallback on PGRST202/42883/42501 (self-hosted not yet migrated, deploy
  ordering) and degrades to hidden rows on any other error.
- tests/pg/dashboard-nav-flags-rpc.pg.test.ts (6): fresh company, active vs
  pending WooCommerce, active Shopify, mileage trips, RLS for a member of
  another company, EXECUTE grants. Unit tests for the wrapper (RPC row,
  single-object payload, each fallback code, other errors) and for the
  entitlements teamId option.

~20 calls / 4 waves -> ~12 calls / 2 waves, 0 auth network calls.

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-26 15:14:49 +02:00

49 lines
2.0 KiB
TypeScript

import type { JwtPayload, User } from '@supabase/supabase-js'
/**
* Local JWT claims to a User: shared by the API route guard (require-auth),
* the dashboard request context and, once adopted, the auth proxy.
*
* getClaims() verifies signature and expiry locally against the cached JWKS
* (asymmetric signing keys; HS256 projects fall back to a server call inside
* getClaims itself). These helpers add the pinning and the User mapping.
*/
/**
* 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: callers fall back to the
* server-side getUser() check, which is authoritative.
*/
export 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
}
/**
* Maps verified JWT claims onto the User subset server code actually consumes
* (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.
*/
export 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: '',
}
}