feat(billing): multi-user paywall: multi_user capability, 20-day grace, owner-only dormancy (#2099)
* feat(billing): multi-user seat gate: multi_user capability, 20-day grace, owner-only dormancy Multiple people in one company becomes a paid capability (multi_user, the eighth PAID key). Derived at access time from capability_grants, no status column, no enforcement cron: - entitled: active grant (trial/stripe/team/manual/comp), everyone works - grace: newest grant expired < 20 days ago; countdown banner for everyone in companies with > 1 user; invites still allowed - frozen: only role=owner resolves; other memberships go dormant (rows untouched, paying reactivates instantly); invites 403 with paid-plan upsell Enforcement: new resolve_active_company_gated RPC (zero-arg RPC and RLS twin untouched: they also run on self-hosts, where the gate never bites), gated query fallback for service-role/API-key paths, setActiveCompany guard, MCP company-access check, invite route. Middleware routes all-frozen users to a new /paused page; the switcher greys locked companies. Migration 20260901081417 (applied to staging): trial trigger seeds multi_user, backfills for mid-trial companies, active Stripe subs, team agreements, and a grandfather grant (expires now, i.e. grace = deploy + 20 days) for existing unpaid multi-member companies. Daily cron mails owners at grace start and last day. Strings in sv+en; pg-real + unit tests included. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L4tNt8wRG3a5iuU1JE2pnP * fix(billing): multi-user seat gate hardening from skeptic review - Stripe cancel now EXPIRES the multi_user stripe grant instead of deleting it: the 20-day grace window hangs on an expired row, so a deleted one froze churned payers' staff instantly with no banner and no mail. Other stripe grants keep the freeze-and-retain delete. - New SECURITY DEFINER company_multi_user_state() RPC (migration 20260901083726, applied to staging) and RPC-first getMultiUserState: capability_grants RLS hides team-scoped rows from non-team users, so user-client reads misread byra-covered companies as frozen (switch refusal, wrong switcher locks). - Byra-kind teams get a standing team-scoped multi_user grant (backfill + teams trigger): byra client companies have no company-scoped trial by design, so a grantless byra team would freeze every consultant and client user. - Comped/manual companies with active PAID-key grants extend to multi_user (a comped company must not read as paying while locking out user two). - /api/v1 gets the same dormancy gate as MCP (frozen non-owner -> 403). - PGRST202 on resolution fails OPEN (pre-migration DB has zero multi_user rows; the gated fallback would have frozen every non-owner mid-deploy). - Grace cron: covers team-scoped lapses (byra agreement ending) and skips the start mail for the hand-mailed grandfather cohort. - Tests updated/added across all touched surfaces; pg tests for the new RPC and byra trigger; trial-suppression pg test extended to 8 keys. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L4tNt8wRG3a5iuU1JE2pnP * fix(billing): decouple seat-gate env check and fail open on gate read throws CI round 1 on #2099: - isMultiUserEnforced no longer imports has-capability: several route test suites partially mock that module and the vitest mock guard threw from inside the v1 seat gate, turning expected 4xx responses into 500s. multi_user is never a connector capability, so the bypass reduces to the same env reads, now inlined. - getMultiUserState wraps its resolution in a fail-open try/catch: a client without .rpc or a thrown network error must never lock users out. - no-phantom-columns ceiling 391 -> 393 with reasons: the seat gate's .or() scope filter (server-resolved UUIDs) and the Stripe cancel expiry update's timestamp .or(); all columns in both strings are literals. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L4tNt8wRG3a5iuU1JE2pnP * fix(billing): membership-guard the multi-user entitlement RPCs (Superagent P3) company_multi_user_ok and company_multi_user_state are SECURITY DEFINER and were granted to authenticated with a caller-supplied company UUID: any logged-in user could probe an arbitrary company's billing state and grace deadline across tenants. Migration 20260901091752 (applied to staging) requires an auth.uid() membership in the target company when a JWT is present, keeps service-role/definer contexts unrestricted, and clamps the grace window to [0, 20] days. pg tests: stranger gets false/NULL, member reads normally, oversized p_grace_days cannot widen the probe. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L4tNt8wRG3a5iuU1JE2pnP --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5
parent
ca12b1855e
commit
aabddb592f
+48
-14
@@ -11,6 +11,8 @@ import {
|
||||
type ProxyTimings,
|
||||
} from '@/lib/supabase/proxy-timing'
|
||||
import { shouldEnforceMfa } from '@/lib/auth/mfa'
|
||||
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'
|
||||
import { DEFAULT_LOCALE, LOCALE_COOKIE, isLocale } from '@/i18n/config'
|
||||
import { userHasPassword } from '@/lib/auth/has-password'
|
||||
@@ -435,6 +437,7 @@ async function updateSessionInner(
|
||||
companyId: string | null
|
||||
locale: string | null
|
||||
degraded: boolean
|
||||
allLocked: boolean
|
||||
} | null = null
|
||||
const resolveCompanyOnce = async () =>
|
||||
(resolvedCompany ??= await timed(timing, 'companyMs', () =>
|
||||
@@ -485,7 +488,7 @@ async function updateSessionInner(
|
||||
|
||||
// Company context resolution
|
||||
const cookieCompanyId = request.cookies.get('gnubok-company-id')?.value
|
||||
const { companyId, locale: dbLocale, degraded } = await resolveCompanyOnce()
|
||||
const { companyId, locale: dbLocale, degraded, allLocked } = await resolveCompanyOnce()
|
||||
|
||||
// If the cookie pointed at a company we can no longer resolve (e.g.
|
||||
// archived), clear it so the browser stops sending it. Never on degraded
|
||||
@@ -516,7 +519,10 @@ async function updateSessionInner(
|
||||
pathname.startsWith('/select-company') ||
|
||||
pathname.startsWith('/settings/account') ||
|
||||
pathname.startsWith('/api/account/') ||
|
||||
pathname.startsWith('/api/company')
|
||||
pathname.startsWith('/api/company') ||
|
||||
// Multi-user seat gate: the paused page IS the destination for a user
|
||||
// whose every membership is frozen, so it must render in that state.
|
||||
pathname.startsWith('/paused')
|
||||
|
||||
// No companies: redirect to the picker if we have BankID enrichment for
|
||||
// this user, otherwise the manual wizard. Either way, allow the escape-hatch
|
||||
@@ -565,6 +571,18 @@ async function updateSessionInner(
|
||||
return NextResponse.redirect(new URL('/byra', request.url))
|
||||
}
|
||||
|
||||
// Multi-user seat gate: memberships exist but every one is frozen for
|
||||
// this (non-owner) user. This is NOT the no-company state: sending them
|
||||
// to onboarding would walk a locked-out colleague into creating a
|
||||
// pointless company. The paused page explains and names the companies.
|
||||
// API requests pass through so routes answer JSON, not an HTML redirect.
|
||||
if (allLocked) {
|
||||
if (pathname.startsWith('/api/')) {
|
||||
return supabaseResponse
|
||||
}
|
||||
return NextResponse.redirect(new URL('/paused', request.url))
|
||||
}
|
||||
|
||||
// Enrichment lives in the user-keyed `bankid_enrichment` table (migration
|
||||
// 20260506160000), it cannot live in extension_data, which is
|
||||
// company-scoped, and the user has no company yet on this path.
|
||||
@@ -965,19 +983,32 @@ async function resolveCompanyForMiddleware(
|
||||
supabase: ReturnType<typeof createServerClient>,
|
||||
userId: string,
|
||||
_request: NextRequest
|
||||
): Promise<{ companyId: string | null; locale: string | null; degraded: boolean }> {
|
||||
const { data, error } = await supabase.rpc('resolve_active_company')
|
||||
): Promise<{ companyId: string | null; locale: string | null; degraded: boolean; allLocked: boolean }> {
|
||||
// Multi-user seat gate: the gated RPC skips memberships frozen for this
|
||||
// user (non-owner, multi_user lapsed past its 20-day grace) and reports
|
||||
// has_locked_membership when NOTHING resolved because of that, which is
|
||||
// what routes the user to /paused instead of onboarding. Self-hosted and
|
||||
// dev call the ungated function: the gate never bites there.
|
||||
const enforced = isMultiUserEnforced()
|
||||
const { data, error } = enforced
|
||||
? await supabase.rpc('resolve_active_company_gated', {
|
||||
p_grace_days: MULTI_USER_GRACE_DAYS,
|
||||
})
|
||||
: await supabase.rpc('resolve_active_company')
|
||||
|
||||
if (error) {
|
||||
if (error.code === 'PGRST202') {
|
||||
// Function not deployed here: use the query path.
|
||||
// Function not deployed here (self-host not migrated yet, or a deploy
|
||||
// racing the branch merge): use the ungated query path. The race
|
||||
// window fails OPEN for the seat gate on purpose: never lock people
|
||||
// out because a deploy is mid-flight.
|
||||
return resolveCompanyForMiddlewareViaQueries(supabase, userId, _request)
|
||||
}
|
||||
// Issue #1053: a FAILED call degrades (fail open), never reads as "no
|
||||
// companies". locale null is fine because the degraded flag already
|
||||
// suppresses the locale-cookie sync at the call site.
|
||||
console.error('[middleware] resolve_active_company rpc failed', error)
|
||||
return { companyId: null, locale: null, degraded: true }
|
||||
return { companyId: null, locale: null, degraded: true, allLocked: false }
|
||||
}
|
||||
|
||||
const row = Array.isArray(data) ? data[0] : data
|
||||
@@ -985,7 +1016,7 @@ async function resolveCompanyForMiddleware(
|
||||
// Zero rows = NULL auth.uid(); impossible for the cookie-auth middleware
|
||||
// client, so treat as degraded rather than redirecting to onboarding.
|
||||
console.error('[middleware] resolve_active_company returned no row for authenticated user')
|
||||
return { companyId: null, locale: null, degraded: true }
|
||||
return { companyId: null, locale: null, degraded: true, allLocked: false }
|
||||
}
|
||||
|
||||
if (row.company_id && row.used_fallback) {
|
||||
@@ -1008,6 +1039,9 @@ async function resolveCompanyForMiddleware(
|
||||
companyId: row.company_id ?? null,
|
||||
locale: row.locale ?? null,
|
||||
degraded: false,
|
||||
// Only the gated RPC carries the column; the ungated one leaves it
|
||||
// undefined, which correctly reads as false.
|
||||
allLocked: row.has_locked_membership === true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1020,7 +1054,7 @@ async function resolveCompanyForMiddlewareViaQueries(
|
||||
supabase: ReturnType<typeof createServerClient>,
|
||||
userId: string,
|
||||
_request: NextRequest
|
||||
): Promise<{ companyId: string | null; locale: string | null; degraded: boolean }> {
|
||||
): Promise<{ companyId: string | null; locale: string | null; degraded: boolean; allLocked: boolean }> {
|
||||
// 1. user_preferences (authoritative) + first membership, fetched in
|
||||
// parallel: the fallback query result doubles as validation when the
|
||||
// preferred company happens to be the first membership, which is the
|
||||
@@ -1055,12 +1089,12 @@ async function resolveCompanyForMiddlewareViaQueries(
|
||||
'[middleware] company resolution query failed',
|
||||
prefsRes.error ?? firstRes.error
|
||||
)
|
||||
return { companyId: null, locale, degraded: true }
|
||||
return { companyId: null, locale, degraded: true, allLocked: false }
|
||||
}
|
||||
|
||||
if (prefs?.active_company_id) {
|
||||
if (prefs.active_company_id === firstCompany?.company_id) {
|
||||
return { companyId: firstCompany.company_id, locale, degraded: false }
|
||||
return { companyId: firstCompany.company_id, locale, degraded: false, allLocked: false }
|
||||
}
|
||||
|
||||
const { data: membership, error: membershipError } = await supabase
|
||||
@@ -1075,14 +1109,14 @@ async function resolveCompanyForMiddlewareViaQueries(
|
||||
// first membership (wrong company for consultants): degrade instead.
|
||||
if (membershipError) {
|
||||
console.error('[middleware] company preference validation failed', membershipError)
|
||||
return { companyId: null, locale, degraded: true }
|
||||
return { companyId: null, locale, degraded: true, allLocked: false }
|
||||
}
|
||||
|
||||
if (membership) return { companyId: membership.company_id, locale, degraded: false }
|
||||
if (membership) return { companyId: membership.company_id, locale, degraded: false, allLocked: false }
|
||||
}
|
||||
|
||||
// 2. Fallback: first non-archived membership (already fetched above)
|
||||
if (!firstCompany) return { companyId: null, locale, degraded: false }
|
||||
if (!firstCompany) return { companyId: null, locale, degraded: false, allLocked: false }
|
||||
|
||||
// Write the fallback back to user_preferences so future RLS lookups
|
||||
// see the same active company without needing this fallback scan.
|
||||
@@ -1100,5 +1134,5 @@ async function resolveCompanyForMiddlewareViaQueries(
|
||||
console.error('[middleware] active company write-back failed', writeBackError)
|
||||
}
|
||||
|
||||
return { companyId: firstCompany.company_id, locale, degraded: false }
|
||||
return { companyId: firstCompany.company_id, locale, degraded: false, allLocked: false }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user