Files
accounted/lib/entitlements/has-capability.ts
T
Jakob Wennberg 4f0a7b1db0 feat(entitlements): per-company capability paywall — gate, trial seeding, UI upsells, Stripe checkout (#815)
* feat(entitlements): capability-grant gate substrate (paywall + modularity)

Two-axis capability primitive behind the SaaS paywall and the per-tenant
modularity/marketplace vision:
- migration: capability_grants (entitlement axis, polymorphic company/firm
  scope), company_capability_config (enablement axis), metered_events
  (append-only), company_has_capability() RPC reusing the 20260619130100
  tenant guard; SELECT-only RLS (writes service-role only, no self-grant).
- lib/entitlements: hasCapability/requireCapability gate (mirrors guardSandbox,
  fail-closed, NEXT_PUBLIC_SELF_HOSTED bypass), capability key namespace,
  metering helper.
- unit (11) + pg-real tests (RPC/RLS/tenant-guard incl. no-self-grant).

Gate not yet wired into call sites (follow-up commit). Paid keys:
ai, bank_sync, skatteverket, email_send.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(entitlements): enforce capability gate at paid external-service chokepoints

Wire the gate into the paid surfaces (keys: ai, email_send, bank_sync, skatteverket):
- AI routes (agent invoke/composer/onboarding stream): requireCapability(ai)
- Invoice send (web + v1): requireCapability(email_send)
- document-extraction event handler: skip Bedrock extract if ai not entitled
- enable-banking + skatteverket crons: per-company hasCapability skip in loop
- colocated send-route test mocks updated (requireCapability -> null)

Free per founder decision: TIC org lookup, VIES VAT validation, FX auto-fetch,
cloud backup, BankID login, all internal bookkeeping.

DEPLOY ORDER: fail-closed by design — do NOT deploy before trial/comp grant
seeding lands, or companies without grants lose these features. Seeding +
Stripe checkout/webhook are the next steps.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(entitlements): seed trial + comp capability grants

Makes the fail-closed gate safely deployable — nobody is locked out at cutover:
- AFTER INSERT trigger on companies grants every NEW company a 30-day trial on
  the PAID keys (ai, bank_sync, skatteverket, email_send), on ALL creation paths
  (RPC/MCP/direct) — so a new signup can use onboarding AI immediately.
- one-time backfill for EXISTING companies: created <=2026-06-07 -> trial ends
  2026-07-07; created later -> created_at + 30 days.
- permanent comp grants for Arcim/Mattsson (matched by name, no hardcoded UUIDs).
- pg tests: clearGrants() for controlled resolver tests + trigger coverage.

Trigger fn is SECURITY DEFINER so it writes grants regardless of caller RLS
(table has no INSERT policy for authenticated — no self-grant).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(entitlements): client capability visibility + billing page

Non-payers get a clean upsell instead of broken/empty features:
- CompanyContext gains capabilities[] + useCapability(key); resolved once
  server-side in the dashboard layout via getCompanyCapabilities (batched, 2
  queries), all three provider branches wired.
- /settings/billing upgrade page — the destination upsells point to (Stripe
  Payment Link via NEXT_PUBLIC_STRIPE_PAYMENT_LINK; degrades to 'coming soon'
  until automated checkout lands).
- ChatEmptyState: non-payer sees an Uppgradera CTA (mirrors the sandbox state).
- SendInvoiceDialog: email send disabled + upsell note when email_send missing
  (extends the existing sandbox-disable pattern).

Fast-follow: chat input/FAB + document-inbox empty state + bank/skatteverket/
AI-suggest buttons + a shared capability_blocked->toast backstop.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(entitlements): gate remaining paid UI surfaces with upsell (fast-follow)

disable-with-upsell across the rest of the paid surfaces (keys: bank_sync, skatteverket, ai):
- BankSyncNowButton: sync/reconnect disabled + note when !bank_sync (CSV/SIE stays free)
- AGIPanel: AGI submit-to-Skatteverket disabled + note when !skatteverket
- SkatteverketConnectPanel: BankID connect/reconnect disabled + upsell
- ApprovalCard: AI re-propose (correction) gated; manual approve/reject stay free
- InvoiceInboxWorkspace: upsell when extraction empty AND !ai (deterministic parse + manual entry unaffected)
- AgentTrigger FAB: routes to /settings/billing when !ai (no dead chat)
- settings nav: 'Abonnemang'/'Subscription' link to /settings/billing (sv/en)

TaxPaymentPanel + TransactionInboxCard intentionally untouched — only local/
deterministic actions there, nothing paid+external to gate.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(entitlements): automated Stripe subscription checkout + webhook

Self-serve revenue wired to the same capability-grant primitive:
- migration: company_subscriptions (company<->Stripe link/status) + stripe_webhook_events (idempotency)
- lib/stripe: getStripe singleton, plan->price mapping, subscription-sync (statusGrantsAccess / subscriptionToState / applySubscriptionState / handleStripeEvent). Active sub -> upsert source='stripe' grants for PAID keys (expiry = period_end + 3d grace); canceled/unpaid -> remove ONLY stripe grants (freeze-and-retain).
- routes: POST /api/billing/checkout (hosted subscription Checkout, company_id metadata), POST /api/billing/portal (Customer Portal), POST /api/stripe/webhook (raw-body signature verify, event-id dedup; handles checkout.session.completed + customer.subscription.*)
- billing page: real plan-toggle Checkout CTA / manage-subscription portal, gated on isStripeConfigured()
- adds stripe@22; unit tests for sync logic

Provisioning is webhook-driven (never trusts the success redirect). Needs env: STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET, STRIPE_PRICE_MONTHLY, STRIPE_PRICE_YEARLY.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(entitlements): validate UUIDs in capability filter + log webhook errors

Addresses PR review (Superagent Security / PR Agent):
- has-capability.ts: validate companyId/teamId as UUIDs before interpolating into the PostgREST .or() filter (fail-closed) — removes the latent injection vector flagged in the entitlement gate. Unit tests updated to use UUIDs.
- stripe/webhook: log processing failures with event id + type before the generic 500, so a failing webhook is visible to operators.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(salary): always-free AGI XML download for manual filing; only direct API submit is paid

Per founder decision on the swedish-compliance-review finding: AGI is a mandatory statutory filing, so producing/downloading the AGI XML must never be paywalled. Adds a free 'Ladda ner AGI-fil' button (generates + downloads the XML for manual upload to Skatteverket's e-service) on all tiers; the gated 'Skicka in underlag' stays the paid convenience (direct API submission — which also requires the paid BankID connection). Upsell reworded to point to the manual path.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(entitlements): harden comp-grant match after prod verification

Verified Arcim/Mattsson in prod (pwxtzglxptnnvjrpixpg): the name match was case-sensitive (missed the active 'Arcim technology AB' lowercase variant) and would have granted 3 archived dupes. Now match by org_number (5595386219 / 5595719864) OR case-insensitive name, active companies only — hits exactly the 3 active comp companies, excludes archived dupes and the unrelated 'Amnäs Mattsson, Emil' enskild firma.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-29 15:56:19 +02:00

169 lines
6.1 KiB
TypeScript

import type { SupabaseClient } from '@supabase/supabase-js'
import { NextResponse } from 'next/server'
import { PAID_CAPABILITIES, type CapabilityKey } from './keys'
/**
* Entitlement gate — the single primitive behind the paywall ("non-payer loses
* functionality") AND the vision's modularity-out ("hide a module this company
* doesn't need"). Both are the same question: does this company hold the
* capability, fail-closed, resolved server-side?
*
* Two orthogonal axes, AND-ed together (see migration
* 20260628140000_capability_grants_and_metered_events):
* ENTITLEMENT — an unexpired capability_grant on the company OR its firm/team.
* ENABLEMENT — not explicitly disabled in company_capability_config (absent == enabled).
*
* Mirrors the shape of lib/sandbox/guard.ts so it drops in at the same call
* sites. The company is resolved by the CALLER (requireCompanyId for web, the
* validated API key for MCP) — never taken from untrusted input here.
*/
/** Self-hosted deployments are all-on — the gate never withholds anything. */
function isSelfHosted(): boolean {
return process.env.NEXT_PUBLIC_SELF_HOSTED === 'true'
}
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
/**
* Only server-resolved UUIDs may be interpolated into the PostgREST `.or()`
* filter below — commas/dots/parens are filter syntax. companyId/teamId always
* come from the DB, but we validate at this boundary as defense in depth.
*/
function isUuid(v: string): boolean {
return UUID_RE.test(v)
}
export async function hasCapability(
supabase: SupabaseClient,
companyId: string,
key: CapabilityKey,
): Promise<boolean> {
if (isSelfHosted()) return true
if (!isUuid(companyId)) return false // fail-closed: never interpolate a non-UUID
// Resolve the company's firm/team (firm-scoped grants cascade to clients).
const { data: company } = await supabase
.from('companies')
.select('team_id')
.eq('id', companyId)
.maybeSingle()
const rawTeamId = (company as { team_id: string | null } | null)?.team_id ?? null
const teamId = rawTeamId && isUuid(rawTeamId) ? rawTeamId : null
// ENTITLEMENT axis: any unexpired grant on the company or its team.
const scopeFilter = teamId
? `company_id.eq.${companyId},team_id.eq.${teamId}`
: `company_id.eq.${companyId}`
const { data: grants, error: grantsError } = await supabase
.from('capability_grants')
.select('expires_at')
.eq('capability_key', key)
.or(scopeFilter)
if (grantsError) return false // fail-closed on any read error
const now = Date.now()
const entitled = (grants ?? []).some((g) => {
const exp = (g as { expires_at: string | null }).expires_at
return exp === null || new Date(exp).getTime() > now
})
if (!entitled) return false
// ENABLEMENT axis: explicitly turned off for this company? (absence == enabled)
const { data: config } = await supabase
.from('company_capability_config')
.select('enabled')
.eq('company_id', companyId)
.eq('capability_key', key)
.maybeSingle()
if ((config as { enabled: boolean } | null)?.enabled === false) return false
return true
}
/**
* Standard bilingual 403 for a capability-blocked endpoint. Matches the
* sandbox/guard envelope so the UI surfaces the upsell consistently.
*/
export function capabilityBlockedResponse(key: CapabilityKey): NextResponse {
return NextResponse.json(
{
error:
'Den här funktionen kräver en betald prenumeration. Uppgradera för att fortsätta använda externa tjänster.',
error_en:
'This feature requires a paid subscription. Upgrade to keep using external services.',
capability_blocked: true,
capability: key,
},
{ status: 403 },
)
}
/**
* Convenience wrapper: check + return the 403 in one call. Returns the
* NextResponse to return from the route, or null when the company has the
* capability and the route should proceed.
*
* const blocked = await requireCapability(supabase, companyId, CAPABILITY.ai)
* if (blocked) return blocked
*/
export async function requireCapability(
supabase: SupabaseClient,
companyId: string,
key: CapabilityKey,
): Promise<NextResponse | null> {
if (await hasCapability(supabase, companyId, key)) return null
return capabilityBlockedResponse(key)
}
/**
* Resolve which PAID capabilities a company currently holds (entitled AND
* enabled), in two queries. Used to seed the client CompanyContext so the UI
* can hide/disable/upsell gated features. Self-hosted holds everything.
*/
export async function getCompanyCapabilities(
supabase: SupabaseClient,
companyId: string,
): Promise<CapabilityKey[]> {
if (isSelfHosted()) return [...PAID_CAPABILITIES]
if (!isUuid(companyId)) return [] // fail-closed: never interpolate a non-UUID
const { data: company } = await supabase
.from('companies')
.select('team_id')
.eq('id', companyId)
.maybeSingle()
const rawTeamId = (company as { team_id: string | null } | null)?.team_id ?? null
const teamId = rawTeamId && isUuid(rawTeamId) ? rawTeamId : 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')
.in('capability_key', PAID_CAPABILITIES as unknown as string[])
.or(scopeFilter)
const now = Date.now()
const entitled = new Set<string>()
for (const g of grants ?? []) {
const row = g as { capability_key: string; expires_at: string | null }
if (row.expires_at === null || new Date(row.expires_at).getTime() > now) {
entitled.add(row.capability_key)
}
}
if (entitled.size === 0) return []
// Subtract any explicitly-disabled (enablement axis).
const { data: configs } = await supabase
.from('company_capability_config')
.select('capability_key, enabled')
.eq('company_id', companyId)
.eq('enabled', false)
for (const c of configs ?? []) {
entitled.delete((c as { capability_key: string }).capability_key)
}
return PAID_CAPABILITIES.filter((k) => entitled.has(k))
}