fix(security): audit remediation 2026-09-01: api_keys identity, viewer gates, OAuth binding, XSS, MFA gate (#2155)

* fix(security): bind api_keys to the caller, lock hash-as-bearer RPCs and provider token tables

Security audit 2026-09-01, critical items.

- api_keys INSERT requires user_id = auth.uid() again (an admin could
  forge a key for any co-member and act as them in every company they
  belong to); SELECT is own-keys-or-admin; a BEFORE trigger freezes the
  identity and credential columns against user-session UPDATEs.
- rotate_mcp_refresh_token and validate_and_increment_api_key become
  service_role only: they match rows by a presented SHA-256, so a hash
  readable by co-members was a bearer credential.
- validate_and_increment_api_key fails closed when the key's user is no
  longer a member of the key's company.
- provider_consent_tokens and provider_otc: the DELETE policies collapsed
  to "caller has any team row" (correlated subquery on a non-existent
  team_members.company_id). All member policies dropped; service_role
  only, matching every existing code path.

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

* fix(security): role gates, ownership guards and posting integrity in the database

Security audit 2026-09-01, high items at the database layer.

- One table-level guard, enforce_company_writer_role(), blocks the
  read-only viewer role on 55 company-scoped tables including through
  the 15 membership-only SECURITY DEFINER writers. Keyed on the JWT role
  claim so it fires inside definer bodies; no-op for service_role and
  trigger cascades.
- company_members user_id/company_id immutable from user sessions;
  invitations can never grant owner; team_members gains a transition
  guard (admins keep non-owner role moves); companies team_id and
  archiving are owner-only and team attachment needs team membership.
- Direct statements (current_user = authenticated) can no longer insert
  posted headers, add lines under posted verifikat, or post a draft with
  a voucher number the sequence never issued. Sanctioned RPCs run as the
  definer and are untouched; the engine's own draft-then-post shapes
  still pass.
- create_document_version refuses viewers and foreign storage paths;
  validate_version_chain needs membership and loses anon EXECUTE;
  match_documents / match_booking_templates lose anon; cron maintenance
  RPCs become service_role only; the production-only
  seed_asset_categories is dropped.

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

* build: pin tsx as an exact devDependency instead of fetching it with npx at build time

prebuild ran "npx tsx" with no lockfile entry, so every Vercel, Docker
and CI build downloaded tsx@latest and its transitive tree from the
registry with no integrity check, inside the build environment.

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

* fix(security): refuse the viewer role on API-key and MCP write paths

The v1 wrapper and the MCP company routing checked company membership
but never role, and both run as service role, so a read-only viewer
holding an API key could post vouchers and change settings through the
API. Mutating methods and non-read scopes now return 403 ROLE_READ_ONLY
for viewers on v1; MCP write tools refuse viewers the same way.

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

* fix(security): stop serving uploaded SVG, XML and HTML as executable content on the app origin

Uploads persisted the browser-declared mime type and the inline proxy
served it verbatim, sandboxing only text/html; the storage proxy
forwarded the uploader's Content-Type. Any writer, or any Peppol sender,
could plant a scripted SVG or XHTML that executed on app.gnubok.se.

- inline route: allow-list of natively safe types (PDF, raster images)
  served as before; everything else gets the opaque sandbox CSP.
- storage proxy: octet-stream + attachment + sandbox unless the DB
  mime for the key is on the allow-list.
- document-service: the stored mime is the magic-byte validated type.
- logo upload: magic-byte validation, SVG refused.

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

* fix(security): byrå brand logo upload decides the type by magic bytes and drops SVG

Same pattern as the company logo route: the logos bucket is public, so a
scripted SVG (or anything declared as an image) must never land there.
The upload pickers stop advertising SVG.

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

* fix(security): bind Enable Banking, Stripe and WooCommerce callbacks to the initiating user

The callbacks resolved the pending row by oauth_state alone, so a
victim who completed an attacker-initiated consent had their bank
account, merchant account or store attached to the attacker's company.
requireFlowInitiator() now requires the cookie session of the user who
started the flow: no session redirects to login with the callback URL
preserved, a different user is refused and nothing is exchanged.

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

* fix(security): guard tenant-controlled outbound fetches and surface the disabled rate limiter

WooCommerce and Shopify syncs fetched a member-editable store URL with
plain fetch() and redirect following under the service role, and the
invoice PDF renderer fetched company_settings.logo_url unguarded. All
three go through a new safeFetch() (public-IP validation via url-guard,
https only, redirect: 'manual', body size cap) and re-normalise the
stored host at use time. checkRateLimit() keeps failing open on hosted
but logs one error per process when Upstash is not configured and
exports isRateLimiterConfigured().

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

* fix(security): decide the API MFA gate from server-authenticated factors, not the session cookie

getAuthenticatorAssuranceLevel() without arguments derives nextLevel
from session.user.factors, which comes from the unsigned sb-*-auth-token
cookie. Deleting factors from the cookie made an enrolled account look
like it had nothing to step up to, on every /api route and in
requireAuth. Both gates now read factors from the getUser() result or
listFactors() and the level from the verified JWT claim, and fail closed
on errors. Page-branch gate hardened the same way.

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

* fix(security): bind Fortnox/Visma, Gmail and Skatteverket callbacks to the initiating user

The arcim-migration callback exchanged the provider code onto whatever
consent the one-time state named, with no check of who completed the
flow and no org-number comparison, so a phished Fortnox admin handed
their ledger to the attacker's company. provider_otc now records the
initiating user (migration 20260902100000); the callback requires that
session and, after the exchange, refuses a provider company whose org
number differs from the consent's company. The Gmail and Skatteverket
callbacks enforce the same initiator check.

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

* fix(security): BankID signup confirms the email before linking the identity

Signup created an email-confirmed, MFA-exempt account for any address
the caller typed and returned a magic link, so an attacker could
pre-register a victim's email and keep a permanent BankID login into the
account the victim later adopted. The user is now created unconfirmed,
the identity carries email_verified_at NULL (migration 20260902101000),
bankid_linked is not set until the mailed confirmation is clicked, and
BankID login of a pending identity is refused with the confirmation
re-sent.

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

* fix(security): bind MCP OAuth redirect URIs to the consenting user and cap scopes

A user-registered redirect URI was allowlisted globally, the consent page
named no client, and all scopes were pre-checked, so one phishing link
handed an attacker a full-scope key for the victim's company. Registered
URIs now resolve only for the registrant or a colleague sharing a
company; the consent page shows the client identity and redirect host;
non-built-in clients default to read-only pre-checks; scopes are capped
by the user's role (viewer: read only) at consent and at /token.

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

* fix(auth): client follow-ups for BankID confirmation, callback mismatch copy and decision log

- register client handles the new confirmation_sent response from BankID
  signup with the existing inbox screen instead of calling verifyOtp.
- BankID login surfaces the email_unconfirmed explanation.
- WooCommerce settings map woocommerce_error=wrong_user to its own copy.
- Logo help text no longer advertises SVG.
- DECISIONS.md records the audit remediation choices.

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

* fix(mcp-oauth): literal SoD columns in the api_keys insert so the phantom-column scanner resolves them

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

* test(logo): type the upload fixtures as Uint8Array<ArrayBuffer> so they are valid BlobParts

Fixes the typecheck ratchet on PR #2155 and ratchets the baseline down
by the one legacy error the change removed.

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

---------

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-09-02 11:38:30 +02:00
committed by GitHub
co-authored by Claude Fable 5.1 Jakob Wennberg
parent 6e8d76a9cb
commit 18cbc4c30a
92 changed files with 10355 additions and 657 deletions
+221 -33
View File
@@ -6,7 +6,9 @@ import { NextRequest } from 'next/server'
*
* Focus: every auth bounce must (a) remember where the user was heading,
* (b) reject an off-origin destination, and (c) not leak the original query
* string onto the auth page. MFA enforcement conditions must be unchanged.
* string onto the auth page. MFA enforcement decides on server-authenticated
* data only (the getUser() factor list and the signature-verified `aal`
* claim), never on the editable cookie session.
*/
const state = vi.hoisted(() => ({
@@ -14,12 +16,26 @@ const state = vi.hoisted(() => ({
id: string
email?: string
app_metadata?: Record<string, unknown>
// What GoTrue returns on /user: the server-side factor list.
factors?: Array<{ id: string; status: string; factor_type: string }>
},
sessionId: 'session-1' as string | null,
authError: null as unknown,
aal: null as null | { currentLevel: string; nextLevel: string },
factors: null as null | { totp: Array<{ id: string; status: string }> },
listFactors: vi.fn(async () => ({ data: state.factors })),
// `aal` claim of the (mock) signature-verified access token, i.e. what
// getClaims() reports. null = the token carries no aal claim.
jwtAal: null as string | null,
// Make getClaims() fail: an error result or a throw.
claimsFailure: null as null | 'error' | 'throw',
// The cookie-derived assurance lookup and the listFactors round trip. The
// proxy must call NEITHER any more: the first computes nextLevel from the
// editable cookie session, the second is a getUser() the proxy has already
// paid for. Spies so tests can prove it. getAal answers the way a cookie
// with `user.factors` stripped would: "nothing to step up to".
getAal: vi.fn(async () => ({
data: { currentLevel: 'aal1', nextLevel: 'aal1' },
error: null,
})),
listFactors: vi.fn(async () => ({ data: { totp: [] }, error: null })),
company: {
data: [{ company_id: 'company-1', locale: 'sv', used_fallback: false }],
error: null as unknown,
@@ -86,13 +102,32 @@ vi.mock('@supabase/ssr', () => ({
error: state.authError,
}
}),
getClaims: vi.fn(async () => ({
data: { claims: state.sessionId ? { session_id: state.sessionId } : {} },
})),
getClaims: vi.fn(async () => {
if (state.claimsFailure === 'throw') throw new Error('jwks fetch failed')
if (state.claimsFailure === 'error') {
return {
data: null,
error: { name: 'AuthInvalidJwtError', message: 'Invalid JWT signature' },
}
}
return {
data: {
claims: {
...(state.sessionId ? { session_id: state.sessionId } : {}),
...(state.jwtAal ? { aal: state.jwtAal } : {}),
// Satisfy the iss/aud pinning the MFA gates apply (lib/auth/claims.ts).
iss: `${(process.env.NEXT_PUBLIC_SUPABASE_URL ?? '').replace(/\/+$/, '')}/auth/v1`,
aud: 'authenticated',
sub: state.user?.id,
},
},
error: null,
}
}),
signOut: state.signOut,
mfa: {
getAuthenticatorAssuranceLevel: vi.fn(async () => ({ data: state.aal })),
listFactors: (...args: unknown[]) => state.listFactors(...args),
getAuthenticatorAssuranceLevel: () => state.getAal(),
listFactors: () => state.listFactors(),
},
},
rpc: vi.fn(async () => state.company),
@@ -172,6 +207,9 @@ import { SESSION_TIMEOUT_COOKIE } from '@/lib/auth/session-timeout-shared'
const ORIGIN = 'http://localhost:3000'
const SIGNED_IN = { id: 'user-1', app_metadata: {} }
const VERIFIED_TOTP = { id: 'f1', status: 'verified', factor_type: 'totp' }
/** A user whose server-side record carries a verified TOTP factor. */
const MFA_USER = { ...SIGNED_IN, factors: [VERIFIED_TOTP] }
function locationOf(response: Response) {
return response.headers.get('location')
@@ -199,12 +237,13 @@ describe('updateSession redirect destinations', () => {
vi.clearAllMocks()
logState.info.mockClear()
state.listFactors.mockClear()
state.getAal.mockClear()
state.user = null
state.sessionId = 'session-1'
state.authError = null
state.cookieWrites = []
state.aal = null
state.factors = null
state.jwtAal = null
state.claimsFailure = null
state.company = {
data: [{ company_id: 'company-1', locale: 'sv', used_fallback: false }],
error: null,
@@ -619,8 +658,9 @@ describe('updateSession redirect destinations', () => {
describe('MFA step-up bounce to /mfa/verify', () => {
beforeEach(() => {
process.env.NEXT_PUBLIC_REQUIRE_MFA = 'true'
state.user = SIGNED_IN
state.aal = { currentLevel: 'aal1', nextLevel: 'aal2' }
// Verified factor on the server-side user, single-factor token.
state.user = MFA_USER
state.jwtAal = 'aal1'
})
it('preserves the destination as ?returnTo=', async () => {
@@ -657,14 +697,48 @@ describe('updateSession redirect destinations', () => {
expect(new URL(locationOf(response)!).pathname).toBe('/mfa/verify')
expect(response.cookies.get('sb-test-auth-token')?.value).toBe('rotated')
})
it('decides on the server-side factor list, never on the cookie session', async () => {
// The attack: the sb-*-auth-token cookie is unsigned JSON, so the
// password holder strips `user.factors` and the local assurance lookup
// reports nextLevel aal1 ("nothing to step up to"). state.getAal is
// that view; the proxy must not even ask for it.
const response = await run('/invoices')
expect(new URL(locationOf(response)!).pathname).toBe('/mfa/verify')
expect(state.getAal).not.toHaveBeenCalled()
expect(state.listFactors).not.toHaveBeenCalled()
})
it.each(['error', 'throw'] as const)(
'fails closed when getClaims reports %s',
async (failure) => {
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
state.claimsFailure = failure
const response = await run('/invoices')
expect(new URL(locationOf(response)!).pathname).toBe('/mfa/verify')
expect(errorSpy).toHaveBeenCalled()
errorSpy.mockRestore()
},
)
it('fails closed when the verified claims carry no aal', async () => {
state.jwtAal = null
const response = await run('/invoices')
expect(new URL(locationOf(response)!).pathname).toBe('/mfa/verify')
})
})
describe('forced enrollment bounce to /mfa/enroll', () => {
beforeEach(() => {
process.env.NEXT_PUBLIC_REQUIRE_MFA = 'true'
// No factor on the server-side user, single-factor token.
state.user = SIGNED_IN
state.aal = { currentLevel: 'aal1', nextLevel: 'aal1' }
state.factors = { totp: [] }
state.jwtAal = 'aal1'
})
it('preserves the destination as ?returnTo=', async () => {
@@ -675,12 +749,15 @@ describe('updateSession redirect destinations', () => {
expect(url.searchParams.get('returnTo')).toBe('/invoices/new')
})
it('still forces enrollment (the gate itself is unchanged)', async () => {
state.factors = { totp: [{ id: 'f1', status: 'verified' }] }
it('steps up instead of enrolling when the server-side user already has a verified factor', async () => {
// Previously this scenario (cookie says no factor, server says one
// exists, token at aal1) rendered the page at AAL1: the verify bounce
// trusted the cookie and the enrolment check then found the factor.
state.user = MFA_USER
const response = await run('/invoices/new')
expect(response.status).toBe(200)
expect(new URL(locationOf(response)!).pathname).toBe('/mfa/verify')
})
it('skips enrollment for a user with no company, as before', async () => {
@@ -691,18 +768,19 @@ describe('updateSession redirect destinations', () => {
expect(response.status).toBe(200)
})
it('still asks for the factor list at aal1/aal1 before bouncing', async () => {
it('reads the factor list off the getUser() round trip, not a second auth call', async () => {
const response = await run('/invoices/new')
expect(new URL(locationOf(response)!).pathname).toBe('/mfa/enroll')
expect(state.listFactors).toHaveBeenCalledTimes(1)
expect(state.listFactors).not.toHaveBeenCalled()
expect(state.getAal).not.toHaveBeenCalled()
})
it('never calls listFactors once the session is at aal2 (a verified factor is implied)', async () => {
state.aal = { currentLevel: 'aal2', nextLevel: 'aal2' }
// Even a factor list that would read as "none" must not matter here:
// the call is skipped, not just its result ignored.
state.factors = { totp: [] }
it('lets an aal2 token through even when the server-side user has no factor left', async () => {
// A user who unenrols their last factor mid-session keeps aal2 until
// the next token refresh; the enrolment bounce lands on the refresh,
// not on the next click (unchanged deferral, PR #1922).
state.jwtAal = 'aal2'
const response = await run('/invoices/new')
@@ -711,12 +789,123 @@ describe('updateSession redirect destinations', () => {
})
it('does not spend an MFA lookup on RSC and prefetch requests at aal2 either', async () => {
state.aal = { currentLevel: 'aal2', nextLevel: 'aal2' }
state.jwtAal = 'aal2'
await run('/invoices', { headers: { rsc: '1' } })
await run('/invoices', { headers: { 'next-router-prefetch': '1', rsc: '1' } })
expect(state.listFactors).not.toHaveBeenCalled()
expect(state.getAal).not.toHaveBeenCalled()
})
})
// ── API branch: the MFA gate for cookie sessions ──────────────────────
describe('API MFA gate for cookie sessions', () => {
const FORBIDDEN = { error: 'MFA-verifiering krävs.' }
beforeEach(() => {
process.env.NEXT_PUBLIC_REQUIRE_MFA = 'true'
state.user = MFA_USER
state.jwtAal = 'aal1'
})
it('returns 403 for an AAL1 session whose server-side user has a verified factor', async () => {
const response = await run('/api/invoices')
expect(response.status).toBe(403)
await expect(response.json()).resolves.toEqual(FORBIDDEN)
})
it('never consults the cookie-derived assurance level or a second factor lookup', async () => {
// state.getAal reports nextLevel aal1: the answer a cookie with
// `user.factors` stripped produces. It must not be asked at all.
const response = await run('/api/invoices')
expect(response.status).toBe(403)
expect(state.getAal).not.toHaveBeenCalled()
expect(state.listFactors).not.toHaveBeenCalled()
})
it('lets an AAL2 session through', async () => {
state.jwtAal = 'aal2'
const response = await run('/api/invoices')
expect(response.status).toBe(200)
})
it.each(['error', 'throw'] as const)(
'fails closed when getClaims reports %s',
async (failure) => {
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
state.claimsFailure = failure
const response = await run('/api/invoices')
expect(response.status).toBe(403)
expect(errorSpy).toHaveBeenCalled()
errorSpy.mockRestore()
},
)
it('fails closed when the verified claims carry no aal', async () => {
state.jwtAal = null
const response = await run('/api/invoices')
expect(response.status).toBe(403)
})
it("passes a user with nothing to step up to (enrolment stays the page gate's job)", async () => {
state.user = SIGNED_IN
expect((await run('/api/invoices')).status).toBe(200)
state.user = {
...SIGNED_IN,
factors: [{ id: 'f2', status: 'unverified', factor_type: 'totp' }],
}
expect((await run('/api/invoices')).status).toBe(200)
expect(state.getAal).not.toHaveBeenCalled()
})
it('keeps the AAL1 escape hatches and the OAuth endpoints open', async () => {
for (const path of ['/api/account/delete', '/api/company/current', '/api/mcp-oauth/token']) {
expect((await run(path)).status).toBe(200)
}
})
it('skips Bearer-auth surfaces by path, and only with the header present', async () => {
const headers = { authorization: 'Bearer key' }
expect((await run('/api/v1/companies/c1/invoices', { headers })).status).toBe(200)
expect((await run('/api/extensions/ext/mcp-server/mcp', { headers })).status).toBe(200)
// A cookie session on a v1 path without the header is still a cookie session.
expect((await run('/api/v1/companies/c1/invoices')).status).toBe(403)
// A forged header on a cookie-authenticated route never disables the gate.
expect((await run('/api/invoices', { headers })).status).toBe(403)
})
it('does not gate BankID-linked users, nor anyone when MFA is off', async () => {
state.user = { ...MFA_USER, app_metadata: { bankid_linked: true } }
expect((await run('/api/invoices')).status).toBe(200)
state.user = MFA_USER
delete process.env.NEXT_PUBLIC_REQUIRE_MFA
expect((await run('/api/invoices')).status).toBe(200)
})
it('carries the rotated auth cookie on the 403', async () => {
state.cookieWrites = [
{ name: 'sb-test-auth-token', value: 'rotated', options: { path: '/' } },
]
const response = await run('/api/invoices')
expect(response.status).toBe(403)
expect(response.cookies.get('sb-test-auth-token')?.value).toBe('rotated')
})
})
@@ -1080,8 +1269,8 @@ describe('updateSession redirect destinations', () => {
describe('MFA-disabled and self-hosted paths are unchanged', () => {
it('does not redirect when NEXT_PUBLIC_REQUIRE_MFA is unset', async () => {
state.user = SIGNED_IN
state.aal = { currentLevel: 'aal1', nextLevel: 'aal2' }
state.user = MFA_USER
state.jwtAal = 'aal1'
const response = await run('/settings/tax')
@@ -1091,9 +1280,8 @@ describe('updateSession redirect destinations', () => {
it('does not redirect on self-hosted even with MFA required', async () => {
process.env.NEXT_PUBLIC_REQUIRE_MFA = 'true'
process.env.NEXT_PUBLIC_SELF_HOSTED = 'true'
state.user = SIGNED_IN
state.aal = { currentLevel: 'aal1', nextLevel: 'aal2' }
state.factors = { totp: [] }
state.user = MFA_USER
state.jwtAal = 'aal1'
const response = await run('/settings/tax')
@@ -1102,8 +1290,8 @@ describe('updateSession redirect destinations', () => {
it('does not redirect BankID-linked users, who are already 2FA', async () => {
process.env.NEXT_PUBLIC_REQUIRE_MFA = 'true'
state.user = { id: 'user-1', app_metadata: { bankid_linked: true } }
state.aal = { currentLevel: 'aal1', nextLevel: 'aal2' }
state.user = { ...MFA_USER, app_metadata: { bankid_linked: true } }
state.jwtAal = 'aal1'
const response = await run('/settings/tax')
+2
View File
@@ -8,6 +8,8 @@ const url = process.env.NEXT_PUBLIC_SUPABASE_URL ?? ''
const key = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ?? ''
const isBuildPlaceholder = !url || url.startsWith('__')
// Cookie encoding must match lib/supabase/server.ts (default
// `user-and-tokens`); see the note there before switching to `tokens-only`.
export function createClient() {
return createBrowserClient(
isBuildPlaceholder ? 'https://placeholder.supabase.co' : url,
+100 -32
View File
@@ -1,4 +1,5 @@
import { createServerClient } from '@supabase/ssr'
import type { User } from '@supabase/supabase-js'
import { NextResponse, type NextRequest } from 'next/server'
import { createLogger } from '@/lib/logger'
import {
@@ -11,6 +12,7 @@ import {
type ProxyTimings,
} from '@/lib/supabase/proxy-timing'
import { shouldEnforceMfa } from '@/lib/auth/mfa'
import { claimsPinned } from '@/lib/auth/claims'
import { isMultiUserEnforced } from '@/lib/entitlements/multi-user'
import { MULTI_USER_GRACE_DAYS } from '@/lib/entitlements/multi-user-state'
import { apiPathSkipsMfaGate } from '@/lib/auth/api-mfa-gate'
@@ -262,11 +264,22 @@ async function updateSessionInner(
pathname,
hasAuthorizationHeader,
)
if (!skipMfaGate && user && shouldEnforceMfa(user)) {
const { data: aal } = await timed(timing, 'mfaMs', () =>
supabase.auth.mfa.getAuthenticatorAssuranceLevel(),
// `user` is the getUser() result above: server-authenticated, so its
// factor list is trustworthy. Only a session with something to step up
// TO is gated here; forcing enrolment stays the page branch's job, as
// before. The assurance level itself comes from the signature-verified
// claims and fails CLOSED (see resolveVerifiedAal), never from the
// cookie's session object.
if (
!skipMfaGate &&
user &&
shouldEnforceMfa(user) &&
userHasVerifiedFactor(user)
) {
const aal = await timed(timing, 'mfaMs', () =>
resolveVerifiedAal(supabase),
)
if (aal?.nextLevel === 'aal2' && aal?.currentLevel === 'aal1') {
if (aal !== 'aal2') {
const response = NextResponse.json(
{ error: 'MFA-verifiering krävs.' },
{ status: 403 },
@@ -455,38 +468,31 @@ async function updateSessionInner(
// MFA enforcement (application-side only, not RLS)
if (shouldEnforceMfa(user)) {
const { data: aal } = await timed(timing, 'mfaMs', () =>
supabase.auth.mfa.getAuthenticatorAssuranceLevel(),
)
const aal = await timed(timing, 'mfaMs', () => resolveVerifiedAal(supabase))
// User has MFA enrolled but hasn't verified this session → redirect to verify
if (aal?.nextLevel === 'aal2' && aal?.currentLevel === 'aal1') {
return bounceToAuth(request, supabaseResponse, '/mfa/verify')
}
// Nothing below applies at AAL2: reaching it requires having verified a
// challenge on a verified factor. Deliberately also skipped for a user
// who unenrols their last factor mid-session: the JWT keeps aal2 until
// the next token refresh, so the enrolment bounce lands on the refresh
// instead of the next click (unchanged from the listFactors-era gate,
// PR #1922).
if (aal !== 'aal2') {
// The factor list is read off the server-authenticated getUser()
// result above, never off the cookie session. A cookie edited to hide
// the factor used to sail past this bounce, and because the enrolment
// check below then found the factor server-side, straight onto the
// page at AAL1. Reading it here also drops the listFactors() round
// trip that check used to pay: auth-js implements listFactors() as
// that very getUser() call.
if (userHasVerifiedFactor(user)) {
return bounceToAuth(request, supabaseResponse, '/mfa/verify')
}
// MFA required but user has no factor enrolled yet → force enrollment
// Skip for users with no companies (still setting up).
//
// Only worth asking when the session is NOT at AAL2: reaching AAL2
// requires having verified a challenge on a verified factor, so the
// factor list cannot be empty there. auth-js implements listFactors()
// as a getUser() network round trip, and running it here on every
// page, RSC and prefetch request for every MFA-verified user was the
// second Supabase Auth call per request (measured via mw-mfa, PR #1922).
// The narrow case this defers is a user who unenrols their last factor
// mid-session: the JWT keeps aal2 until the next token refresh, so the
// enrolment bounce lands on the refresh instead of the next click.
if (aal?.currentLevel !== 'aal2') {
// MFA required but no factor enrolled yet: force enrolment. Skipped
// for users with no companies (still setting up).
const { companyId: companyIdForMfa } = await resolveCompanyOnce()
if (companyIdForMfa) {
const { data: factors } = await timed(timing, 'mfaMs', () =>
supabase.auth.mfa.listFactors(),
)
const hasVerifiedFactor = factors?.totp?.some(f => f.status === 'verified')
if (!hasVerifiedFactor) {
return bounceToAuth(request, supabaseResponse, '/mfa/enroll')
}
return bounceToAuth(request, supabaseResponse, '/mfa/enroll')
}
}
}
@@ -641,6 +647,68 @@ async function getSupabaseSessionId(
}
}
/**
* Whether the SERVER-authenticated user carries a verified MFA factor.
*
* Only ever call this with the getUser() result: GoTrue returns `factors` on
* /user (auth-js's listFactors() is that same call, filtered), so reading it
* off the round trip the proxy has already paid costs nothing extra. The
* server omits an empty list, so a missing array means "no factor", exactly
* the reading listFactors() would give.
*
* Never call it with a user deserialised from the session cookie: the
* sb-*-auth-token cookie is unsigned base64 JSON, so whoever holds the
* password can strip `factors` from it and make an enrolled account look
* like one with nothing to step up to.
*/
function userHasVerifiedFactor(user: Pick<User, 'factors'>): boolean {
return user.factors?.some((factor) => factor.status === 'verified') ?? false
}
/**
* Assurance level of the current session, read from the signature-verified
* JWT claims: getClaims() checks the token locally against the cached JWKS
* (server-side for HS256 projects) and the iss/aud pinning is the same one
* require-auth applies. Returns null on ANY failure so both MFA gates fail
* closed; each failure is logged because a spike means MFA users are being
* refused, which must be visible in production.
*
* Deliberately not `mfa.getAuthenticatorAssuranceLevel()`: called without a
* JWT it computes `nextLevel` from `session.user.factors`, and that session
* is the editable cookie described on userHasVerifiedFactor. Its
* `currentLevel` happens to be sound (the JWT the preceding getUser() was
* accepted with), but the two halves come as one answer, so neither gate
* consumes it any more (security audit 2026-09).
*/
async function resolveVerifiedAal(
supabase: ReturnType<typeof createServerClient>,
): Promise<string | null> {
if (typeof supabase.auth.getClaims !== 'function') {
console.error('[middleware] getClaims unavailable; treating session as not MFA-assured')
return null
}
try {
const { data, error } = await supabase.auth.getClaims()
const claims = data?.claims
if (error || !claims) {
console.error('[middleware] getClaims failed; treating session as not MFA-assured', error)
return null
}
if (!claimsPinned(claims)) {
console.error('[middleware] getClaims iss/aud pinning failed; treating session as not MFA-assured', {
iss: claims.iss,
aud: claims.aud,
})
return null
}
return typeof claims.aal === 'string' ? claims.aal : null
} catch (error) {
console.error('[middleware] getClaims threw; treating session as not MFA-assured', error)
return null
}
}
async function signOutTimedOutSession(
supabase: ReturnType<typeof createServerClient>,
): Promise<void> {
+19
View File
@@ -9,6 +9,25 @@ const isBuildPlaceholder = url?.startsWith('__')
const safeUrl = isBuildPlaceholder ? 'https://placeholder.supabase.co' : url
const safeKey = isBuildPlaceholder ? 'placeholder' : key
/**
* Cookie-session client for server components, server actions and routes.
*
* Cookie encoding stays the default `user-and-tokens` on purpose.
* @supabase/ssr 0.12 offers an experimental `cookies.encode: 'tokens-only'`
* that keeps the user object out of the cookie, but auth-js then substitutes a
* THROWING proxy for `session.user` wherever no user store holds it: every
* fresh server request (app/api/mcp-oauth/authorize/route.ts calls
* `mfa.getAuthenticatorAssuranceLevel()`, which reads `session.user.factors`)
* and, in the browser, every `getSession().user` read after a session minted
* by the server-side PKCE callback (reset-password, SendInvoiceDialog) until
* the next token refresh. The trust problem is solved at the consumers
* instead: lib/supabase/middleware.ts and lib/auth/require-auth.ts never read
* MFA state off the cookie's user object (factors come from getUser() or
* listFactors(), the level from signature-verified claims). Switch the
* encoding only together with those call sites, and identically here, in
* client.ts and in middleware.ts: @supabase/ssr requires the two sides to
* match.
*/
export async function createClient() {
const cookieStore = await cookies()