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>
This commit is contained in:
Jakob Wennberg
2026-08-26 15:14:49 +02:00
committed by GitHub
co-authored by Jakob Wennberg Claude Fable 5
parent 1a41119682
commit 4ac7b45c8a
11 changed files with 433 additions and 109 deletions
+48
View File
@@ -0,0 +1,48 @@
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: '',
}
}
+4 -38
View File
@@ -1,49 +1,15 @@
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { shouldEnforceMfa } from './mfa'
import type { User, SupabaseClient, JwtPayload } from '@supabase/supabase-js'
import type { User, SupabaseClient } from '@supabase/supabase-js'
import { claimsPinned, userFromClaims } from './claims'
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: '',
}
}
// claimsPinned / userFromClaims live in ./claims so the dashboard request
// context (and later the auth proxy) share the exact same pinning + mapping.
/**
* Auth + MFA guard for API routes.
+54
View File
@@ -0,0 +1,54 @@
import { describe, it, expect, vi } from 'vitest'
import type { SupabaseClient } from '@supabase/supabase-js'
import { getDashboardNavFlags } from '../nav-flags'
function makeSupabase(
rpcResult: { data?: unknown; error?: { code?: string; message?: string } | null },
probes: Record<string, unknown[]> = {},
) {
const from = vi.fn((table: string) => {
const chain: Record<string, unknown> = {}
const self: unknown = new Proxy(chain, {
get: (_t, prop) => {
if (prop === 'then') {
return (resolve: (v: unknown) => void) => resolve({ data: probes[table] ?? [], error: null })
}
return () => self
},
})
return self
})
const rpc = vi.fn(async () => ({ data: rpcResult.data ?? null, error: rpcResult.error ?? null }))
return { supabase: { from, rpc } as unknown as SupabaseClient, from, rpc }
}
describe('getDashboardNavFlags', () => {
it('reads both flags from the RPC row and never touches the tables', async () => {
const { supabase, from, rpc } = makeSupabase({ data: [{ has_webshop: true, has_mileage_trips: false }] })
expect(await getDashboardNavFlags(supabase, 'c1')).toEqual({ hasWebshop: true, hasMileageTrips: false })
expect(rpc).toHaveBeenCalledWith('get_dashboard_nav_flags', { p_company_id: 'c1' })
expect(from).not.toHaveBeenCalled()
})
it('accepts a single-object payload and treats null flags as false', async () => {
const { supabase } = makeSupabase({ data: { has_webshop: null, has_mileage_trips: true } })
expect(await getDashboardNavFlags(supabase, 'c1')).toEqual({ hasWebshop: false, hasMileageTrips: true })
})
it.each(['PGRST202', '42883', '42501'])('falls back to the four probes when the RPC is unavailable (%s)', async (code) => {
const { supabase, from } = makeSupabase({ error: { code } }, { webshop_orders: [{ id: 'o1' }] })
expect(await getDashboardNavFlags(supabase, 'c1')).toEqual({ hasWebshop: true, hasMileageTrips: false })
expect(from.mock.calls.map((c) => c[0]).sort()).toEqual([
'mileage_trips',
'shopify_connections',
'webshop_orders',
'woocommerce_connections',
])
})
it('degrades to hidden rows on any other error instead of probing', async () => {
const { supabase, from } = makeSupabase({ error: { code: '57014', message: 'timeout' } })
expect(await getDashboardNavFlags(supabase, 'c1')).toEqual({ hasWebshop: false, hasMileageTrips: false })
expect(from).not.toHaveBeenCalled()
})
})
+60
View File
@@ -0,0 +1,60 @@
import type { SupabaseClient } from '@supabase/supabase-js'
export interface DashboardNavFlags {
/** An active WooCommerce/Shopify connection or already-imported webshop orders. */
hasWebshop: boolean
/** Existing mileage trips (created via UI, API or MCP). */
hasMileageTrips: boolean
}
const FALLBACK_CODES = new Set(['PGRST202', '42883', '42501'])
/**
* The two booleans that gate the Webshop and Körjournal nav rows, in one
* round trip via get_dashboard_nav_flags() (migration 20260826120000).
*
* Fallback to the four limit-1 probes the layout ran before the RPC when
* the function is not deployed yet (self-hosted instance not migrated, or
* the deploy-ordering window before the branching merge applies the
* migration) or EXECUTE is not granted: mirrors the load-bearing fallback
* in lib/company/context.ts. Any other error degrades to (false, false):
* these flags only hide nav rows, they are never load-bearing.
*/
export async function getDashboardNavFlags(
supabase: SupabaseClient,
companyId: string,
): Promise<DashboardNavFlags> {
const rpc = await supabase.rpc('get_dashboard_nav_flags', { p_company_id: companyId })
if (!rpc.error) {
const row = (Array.isArray(rpc.data) ? rpc.data[0] : rpc.data) as
| { has_webshop?: boolean | null; has_mileage_trips?: boolean | null }
| null
| undefined
return {
hasWebshop: row?.has_webshop === true,
hasMileageTrips: row?.has_mileage_trips === true,
}
}
if (!FALLBACK_CODES.has(rpc.error.code ?? '')) {
return { hasWebshop: false, hasMileageTrips: false }
}
return getDashboardNavFlagsViaProbes(supabase, companyId)
}
/** The pre-RPC implementation, kept verbatim as the fallback. */
export async function getDashboardNavFlagsViaProbes(
supabase: SupabaseClient,
companyId: string,
): Promise<DashboardNavFlags> {
const [woo, shopify, orders, trips] = await Promise.all([
supabase.from('woocommerce_connections').select('id').eq('company_id', companyId).eq('status', 'active').limit(1),
supabase.from('shopify_connections').select('id').eq('company_id', companyId).eq('status', 'active').limit(1),
supabase.from('webshop_orders').select('id').eq('company_id', companyId).limit(1),
supabase.from('mileage_trips').select('id').eq('company_id', companyId).limit(1),
])
return {
hasWebshop:
(woo.data?.length ?? 0) > 0 || (shopify.data?.length ?? 0) > 0 || (orders.data?.length ?? 0) > 0,
hasMileageTrips: (trips.data?.length ?? 0) > 0,
}
}
@@ -244,6 +244,30 @@ describe('getCompanyEntitlements', () => {
expect(result.trialExpiredAt).toBeNull()
})
it('skips the companies lookup and still scopes grants to the team when teamId is supplied', async () => {
const teamId = '22222222-2222-4222-8222-222222222222'
const base = makeSupabase({
// Deliberately wrong: if the lookup ran, the team scope would be lost.
companies: { data: { team_id: null } },
capability_grants: {
data: [{ capability_key: CAPABILITY.ai, expires_at: null, source: 'stripe' }],
},
company_capability_config: { data: [] },
})
const tables: string[] = []
const supabase = {
from: (table: string) => {
tables.push(table)
return (base.from as (t: string) => unknown)(table)
},
} as unknown as SupabaseClient
const result = await getCompanyEntitlements(supabase, companyId, { teamId })
expect(result.capabilities).toContain(CAPABILITY.ai)
expect(result.entitlementState).toBe('paid')
expect(tables).not.toContain('companies')
expect(tables).toContain('capability_grants')
})
it('hides the trial once a non-trial grant is active (converted customer)', async () => {
const supabase = makeSupabase({
companies: { data: { team_id: null } },
+36 -12
View File
@@ -321,9 +321,36 @@ const PAYING_SUBSCRIPTION_STATUSES = ['active', 'trialing', 'past_due']
* CompanyContext so the UI can hide/disable/upsell gated features.
* Self-hosted holds everything.
*/
function normalizeTeamId(raw: string | null | undefined): string | null {
return raw && isUuid(raw) ? raw : null
}
function readGrants(supabase: SupabaseClient, companyId: string, teamId: string | null) {
const scopeFilter = teamId
? `company_id.eq.${companyId},team_id.eq.${teamId}`
: `company_id.eq.${companyId}`
return supabase
.from('capability_grants')
.select('capability_key, expires_at, source')
.in('capability_key', PAID_CAPABILITIES as unknown as string[])
.or(scopeFilter)
}
export interface GetCompanyEntitlementsOptions {
/**
* The company's team_id when the caller already has it (the dashboard
* layout reads it off the membership join): skips the companies lookup and
* lets the grants read run in the same wave as the other two, one round
* trip instead of two on the layout's critical path. Pass null for a
* company without a team.
*/
teamId?: string | null
}
export async function getCompanyEntitlements(
supabase: SupabaseClient,
companyId: string,
options: GetCompanyEntitlementsOptions = {},
): Promise<CompanyEntitlements> {
if (isPaywallBypassed()) {
return {
@@ -345,8 +372,11 @@ export async function getCompanyEntitlements(
// per RLS) distinguishes a churned payer from an expired trial: cancelled
// subscriptions have their stripe grants deleted, so the grants alone
// cannot tell the two apart.
const [{ data: company }, { data: configs }, { data: subscription }] = await Promise.all([
supabase.from('companies').select('team_id').eq('id', companyId).maybeSingle(),
const knownTeam = options.teamId !== undefined
const [{ data: company }, { data: configs }, { data: subscription }, earlyGrants] = await Promise.all([
knownTeam
? Promise.resolve({ data: { team_id: options.teamId } })
: supabase.from('companies').select('team_id').eq('id', companyId).maybeSingle(),
supabase
.from('company_capability_config')
.select('capability_key, enabled')
@@ -357,18 +387,12 @@ export async function getCompanyEntitlements(
.select('status')
.eq('company_id', companyId)
.maybeSingle(),
// With the team known up front the grants read joins this wave.
knownTeam ? readGrants(supabase, companyId, normalizeTeamId(options.teamId)) : Promise.resolve(null),
])
const rawTeamId = (company as { team_id: string | null } | null)?.team_id ?? null
const teamId = rawTeamId && isUuid(rawTeamId) ? rawTeamId : null
const teamId = normalizeTeamId((company as { team_id: string | null } | null)?.team_id ?? null)
const scopeFilter = teamId
? `company_id.eq.${companyId},team_id.eq.${teamId}`
: `company_id.eq.${companyId}`
const { data: grants } = await supabase
.from('capability_grants')
.select('capability_key, expires_at, source')
.in('capability_key', PAID_CAPABILITIES as unknown as string[])
.or(scopeFilter)
const { data: grants } = earlyGrants ?? (await readGrants(supabase, companyId, teamId))
const now = Date.now()
const entitled = new Set<string>()