Files
accounted/lib/notifications/multi-user-grace.ts
T
Mattsson aabddb592f 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>
2026-09-01 11:29:12 +02:00

259 lines
9.9 KiB
TypeScript

import type { SupabaseClient } from '@supabase/supabase-js'
import { CAPABILITY } from '@/lib/entitlements/keys'
import {
computeMultiUserState,
MULTI_USER_GRACE_DAYS,
type MultiUserGrantRow,
} from '@/lib/entitlements/multi-user-state'
import { isMultiUserEnforced } from '@/lib/entitlements/multi-user'
import { getEmailService } from '@/lib/email/service'
import { getSenderForCompany, getBaseUrlForBrand } from '@/lib/email/brand-sender'
import { getBranding } from '@/lib/branding/service'
import { formatDate } from '@/lib/utils'
import { createLogger } from '@/lib/logger'
const logger = createLogger('notifications/multi-user-grace')
/**
* Multi-user grace reminders: mails company OWNERS when the 20-day grace
* window opens (their extra members will pause) and again on its last day.
*
* Windowing keeps the daily cron idempotent without a sent-log: with the
* newest multi_user expiry E and grace end G = E + 20d,
* "start" mail : E in (now - 24h, now] (the lapse happened since the
* previous daily run)
* "final" mail : G in (now, now + 24h] (the freeze lands before the
* next daily run)
* The two windows can only both hit for a sub-24h grace, which the 20-day
* constant rules out. Companies with no non-owner members are skipped:
* single-person companies must never hear about the seat gate.
*
* The launch cohort's mail is sent by hand (founder decision 2026-09-01);
* this cron owns every FUTURE lapse: trial ends, subscription cancellations.
*/
const DAY_MS = 86_400_000
export interface MultiUserGraceSummary {
companiesInGrace: number
startMails: number
finalMails: number
errors: number
skipped?: 'not_enforced' | 'email_not_configured'
}
interface GrantRow {
company_id: string | null
team_id: string | null
expires_at: string | null
metadata: Record<string, unknown> | null
}
interface TrackedGrant extends MultiUserGrantRow {
metadata: Record<string, unknown> | null
}
export async function runMultiUserGraceReminders(
supabase: SupabaseClient,
now: Date,
): Promise<MultiUserGraceSummary> {
const summary: MultiUserGraceSummary = {
companiesInGrace: 0,
startMails: 0,
finalMails: 0,
errors: 0,
}
if (!isMultiUserEnforced()) {
summary.skipped = 'not_enforced'
return summary
}
const emailService = getEmailService()
if (!emailService.isConfigured()) {
summary.skipped = 'email_not_configured'
return summary
}
// All multi_user grants in one read: the key has at most a handful of rows
// per company, and the whole-table scan on one capability_key is what the
// idx_capability_grants_key index exists for.
const { data: grantRows, error: grantsError } = await supabase
.from('capability_grants')
.select('company_id, team_id, expires_at, metadata')
.eq('capability_key', CAPABILITY.multi_user)
if (grantsError) {
throw new Error(`multi-user grace: grants read failed: ${grantsError.message}`)
}
const grants = (grantRows ?? []) as GrantRow[]
const companyGrants = new Map<string, TrackedGrant[]>()
const teamGrants = new Map<string, TrackedGrant[]>()
for (const g of grants) {
if (g.company_id) {
const list = companyGrants.get(g.company_id) ?? []
list.push({ expires_at: g.expires_at, metadata: g.metadata })
companyGrants.set(g.company_id, list)
}
if (g.team_id) {
const list = teamGrants.get(g.team_id) ?? []
list.push({ expires_at: g.expires_at, metadata: g.metadata })
teamGrants.set(g.team_id, list)
}
}
if (companyGrants.size === 0 && teamGrants.size === 0) return summary
// Candidate companies: company-scoped grant holders PLUS every company of
// a team that holds grants (a byrå whose team agreement lapses has client
// companies with zero company-scoped rows, and their owners must be mailed
// like anyone else's).
const companies = new Map<string, { id: string; name: string; team_id: string | null }>()
const companyIds = [...companyGrants.keys()]
for (let i = 0; i < companyIds.length; i += 200) {
const chunk = companyIds.slice(i, i + 200)
const { data, error } = await supabase
.from('companies')
.select('id, name, team_id, archived_at')
.in('id', chunk)
.is('archived_at', null)
if (error) throw new Error(`multi-user grace: companies read failed: ${error.message}`)
for (const c of (data ?? []) as { id: string; name: string; team_id: string | null }[]) {
companies.set(c.id, c)
}
}
const teamIds = [...teamGrants.keys()]
for (let i = 0; i < teamIds.length; i += 200) {
const chunk = teamIds.slice(i, i + 200)
const { data, error } = await supabase
.from('companies')
.select('id, name, team_id, archived_at')
.in('team_id', chunk)
.is('archived_at', null)
if (error) throw new Error(`multi-user grace: team companies read failed: ${error.message}`)
for (const c of (data ?? []) as { id: string; name: string; team_id: string | null }[]) {
companies.set(c.id, c)
}
}
const nowMs = now.getTime()
for (const company of companies.values()) {
const rows = [
...(companyGrants.get(company.id) ?? []),
...(company.team_id ? (teamGrants.get(company.team_id) ?? []) : []),
]
const access = computeMultiUserState(rows, nowMs)
if (access.state !== 'grace' || !access.graceEndsAt) continue
summary.companiesInGrace += 1
const graceEndMs = new Date(access.graceEndsAt).getTime()
const lapseMs = graceEndMs - MULTI_USER_GRACE_DAYS * DAY_MS
// The launch cohort's start mail is sent by hand (founder decision
// 2026-09-01): the grandfather backfill row expires at deploy time, so
// without this check the first cron run after deploy would re-mail the
// whole cohort. The day-19 final reminder still goes out.
const anchorIsGrandfather = rows.some(
(r) =>
r.expires_at !== null &&
new Date(r.expires_at).getTime() === lapseMs &&
(r.metadata as { reason?: string } | null)?.reason === 'multi_user_grandfather',
)
const isStart = !anchorIsGrandfather && lapseMs > nowMs - DAY_MS && lapseMs <= nowMs
const isFinal = graceEndMs > nowMs && graceEndMs <= nowMs + DAY_MS
if (!isStart && !isFinal) continue
try {
const sent = await sendGraceMail(supabase, {
companyId: company.id,
companyName: company.name,
kind: isFinal ? 'final' : 'start',
graceEndsAt: access.graceEndsAt,
})
if (sent === 0) continue
if (isFinal) summary.finalMails += sent
else summary.startMails += sent
} catch (err) {
summary.errors += 1
logger.error('multi-user grace mail failed', err as Error, { companyId: company.id })
}
}
return summary
}
async function sendGraceMail(
supabase: SupabaseClient,
args: { companyId: string; companyName: string; kind: 'start' | 'final'; graceEndsAt: string },
): Promise<number> {
// Sandbox/demo companies have no billing: never mail them.
const { data: settings } = await supabase
.from('company_settings')
.select('is_sandbox, company_name')
.eq('company_id', args.companyId)
.maybeSingle()
if ((settings as { is_sandbox?: boolean } | null)?.is_sandbox === true) return 0
const companyName =
(settings as { company_name?: string | null } | null)?.company_name || args.companyName
const { data: members } = await supabase
.from('company_members')
.select('user_id, role')
.eq('company_id', args.companyId)
const memberRows = (members ?? []) as { user_id: string; role: string }[]
const affected = memberRows.filter((m) => m.role !== 'owner')
// Single-person companies never hear about the seat gate.
if (affected.length === 0) return 0
const owners = memberRows.filter((m) => m.role === 'owner')
if (owners.length === 0) return 0
const { data: profiles } = await supabase
.from('profiles')
.select('id, email')
.in('id', memberRows.map((m) => m.user_id))
const emailById = new Map(
((profiles ?? []) as { id: string; email: string | null }[]).map((p) => [p.id, p.email]),
)
const ownerEmails = owners.map((o) => emailById.get(o.user_id)).filter((e): e is string => !!e)
const affectedEmails = affected
.map((a) => emailById.get(a.user_id))
.filter((e): e is string => !!e)
if (ownerEmails.length === 0) return 0
const sender = await getSenderForCompany(args.companyId)
const appUrl = sender.brand ? getBaseUrlForBrand(sender.brand) : getBranding().appUrl
const billingUrl = `${appUrl}/settings/billing`
const freezeDate = formatDate(args.graceEndsAt)
const affectedList = affectedEmails.join(', ')
const subject =
args.kind === 'final'
? `Imorgon pausas fler användare i ${companyName}`
: `Fler användare i ${companyName} kräver betald plan`
const intro =
args.kind === 'final'
? `Imorgon (${freezeDate}) pausas följande konton från ${companyName}: ${affectedList}.`
: `Från och med den ${freezeDate} ingår flera användare endast i den betalda planen. Då pausas följande konton från ${companyName}: ${affectedList}.`
const outro =
'Ingen data försvinner och inga användare tas bort. Uppgraderar ni, nu eller senare, ' +
'får alla tillbaka sin åtkomst direkt.'
const body = `Hej!\n\n${intro}\n\n${outro}\n\nUppgradera här: ${billingUrl}\n`
const html =
`<p>Hej!</p><p>${intro}</p><p>${outro}</p>` +
`<p><a href="${billingUrl}">Uppgradera till betald plan</a></p>`
const emailService = getEmailService()
let sent = 0
for (const to of ownerEmails) {
const result = await emailService.sendEmail({
to,
subject,
html,
text: body,
fromName: sender.fromName ?? undefined,
fromAddress: sender.fromAddress ?? undefined,
replyTo: sender.replyTo ?? undefined,
})
if (result.success) sent += 1
else logger.warn('multi-user grace mail send failed', { companyId: args.companyId })
}
return sent
}