From a0ef341878cf86d0275e4c4e40ee7d397812aaed Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 12 Nov 2026 19:51:55 -0800 Subject: [PATCH] feat(cloud): audit_log entitlement on Enterprise (catalog v2), feature flags route, contact-sales grant --- cloud/apps/billing/catalog/catalog.json | 17 ++++++++- cloud/apps/billing/src/entitlement-keys.ts | 20 +++++++--- cloud/apps/billing/src/features.ts | 35 ++++++++++++++++++ cloud/apps/billing/src/grants.ts | 43 ++++++++++++++++++++++ cloud/apps/billing/src/index.ts | 14 +++++++ cloud/apps/billing/src/plans-api.ts | 5 ++- 6 files changed, 127 insertions(+), 7 deletions(-) create mode 100644 cloud/apps/billing/src/features.ts diff --git a/cloud/apps/billing/catalog/catalog.json b/cloud/apps/billing/catalog/catalog.json index 29c52b6af11..f9b10e8212b 100644 --- a/cloud/apps/billing/catalog/catalog.json +++ b/cloud/apps/billing/catalog/catalog.json @@ -73,7 +73,7 @@ "name": "Enterprise", "sort": 20, "public": true, - "currentVersion": 1, + "currentVersion": 2, "contactUrl": "https://orca.dev/enterprise", "priceLabel": "Custom", "versions": [ @@ -87,6 +87,21 @@ { "id": "egress_controls", "params": {}, "text": "Network egress controls" }, { "id": "custom_limits", "params": {}, "text": "Custom limits and pricing" } ] + }, + { + "version": 2, + "note": "Adds the team audit log (audit_log). Sandbox hours and limits still come from the team's subscription.", + "entitlements": { + "audit_log": { "value": true } + }, + "policy": {}, + "features": [ + { "id": "byoc", "params": {}, "text": "Run sandboxes in your own cloud" }, + { "id": "sso_scim", "params": {}, "text": "SSO and SCIM" }, + { "id": "audit_log", "params": {}, "text": "Team audit log" }, + { "id": "egress_controls", "params": {}, "text": "Network egress controls" }, + { "id": "custom_limits", "params": {}, "text": "Custom limits and pricing" } + ] } ] }, diff --git a/cloud/apps/billing/src/entitlement-keys.ts b/cloud/apps/billing/src/entitlement-keys.ts index f2d946bce10..1d783939974 100644 --- a/cloud/apps/billing/src/entitlement-keys.ts +++ b/cloud/apps/billing/src/entitlement-keys.ts @@ -12,7 +12,9 @@ export const ENTITLEMENT_KEYS = [ 'max_concurrent_sandboxes', 'max_concurrent_sandboxes_per_member', 'machine_sizes', - 'overage_allowed' + 'overage_allowed', + // Feature flags (Enterprise): viewing the team audit log. Recording never depends on it. + 'audit_log' ] as const export type EntitlementKey = (typeof ENTITLEMENT_KEYS)[number] @@ -27,9 +29,15 @@ export const ENTITLEMENT_REGISTRY: Record + export function isEntitlementKey(value: string): value is EntitlementKey { return (ENTITLEMENT_KEYS as readonly string[]).includes(value) } @@ -62,6 +70,7 @@ export type EffectiveValues = { maxConcurrentSandboxesPerMember: number machineSizes: MachineSize[] overageAllowed: boolean + auditLog: boolean } /** Combines grant values by each key's rule. Per-seat values multiply by max(1, seats). */ @@ -69,7 +78,7 @@ export function aggregateGrants(grants: readonly GrantValue[]): EffectiveValues const sums: Record = {} const maxes: Record = {} const sizes = new Set() - let overage = false + const flags: Record = {} for (const grant of grants) { const multiplier = grant.perSeat ? Math.max(1, grant.seats ?? 1) : 1 const definition = ENTITLEMENT_REGISTRY[grant.key] @@ -86,7 +95,7 @@ export function aggregateGrants(grants: readonly GrantValue[]): EffectiveValues } break case 'or': - overage = overage || grant.value === true + flags[grant.key] = flags[grant.key] === true || grant.value === true break } } @@ -98,6 +107,7 @@ export function aggregateGrants(grants: readonly GrantValue[]): EffectiveValues maxConcurrentSandboxesPerMember: maxes.max_concurrent_sandboxes_per_member ?? 0, // Registry order, so the list is stable whatever order grants came in. machineSizes: MACHINE_SIZES.filter((size) => sizes.has(size)), - overageAllowed: overage + overageAllowed: flags.overage_allowed === true, + auditLog: flags.audit_log === true } } diff --git a/cloud/apps/billing/src/features.ts b/cloud/apps/billing/src/features.ts new file mode 100644 index 00000000000..78739e882a9 --- /dev/null +++ b/cloud/apps/billing/src/features.ts @@ -0,0 +1,35 @@ +// Feature entitlements: boolean switches a plan turns on (the team audit log on Enterprise). +// They gate a surface and nothing else, so they stay out of the Entitlement object: the start +// check, usage metering and the shadow comparison never see them. Resolved from the account's +// live grants in every mode but 'off' (where nothing projects grants, so nothing is on). The +// legacy computation has no features, so there is nothing for shadow mode to compare. +// +// POST /v1/internal/entitlements/features {accountId} -> { features: { audit_log: boolean } } +import { z } from 'zod' +import { FEATURE_KEYS, type FeatureFlags } from './entitlement-keys' +import { entitlementsMode } from './entitlements-mode' +import type { Env } from './env' +import { grantsForSubject, liveAt } from './grants' + +export const FeaturesRequestSchema = z.object({ accountId: z.string().min(1).max(160).regex(/^[A-Za-z0-9_.:-]+$/) }).strict() + +const NONE = Object.fromEntries(FEATURE_KEYS.map((key) => [key, false])) as FeatureFlags + +/** A feature is on while any active, in-window grant holds it as true. Held (unpaid) grants do not count. */ +export async function featuresFor(env: Pick, accountId: string, now: number): Promise { + if (entitlementsMode(env) === 'off') { + return { ...NONE } + } + const flags = { ...NONE } + for (const row of await grantsForSubject(env.BILLING_DB, accountId)) { + if (row.state !== 'active' || !liveAt(row, now)) { + continue + } + for (const key of FEATURE_KEYS) { + if (row.entitlement_key === key && row.value_json === 'true') { + flags[key] = true + } + } + } + return flags +} diff --git a/cloud/apps/billing/src/grants.ts b/cloud/apps/billing/src/grants.ts index ea56cbb8a28..4f9b55b2637 100644 --- a/cloud/apps/billing/src/grants.ts +++ b/cloud/apps/billing/src/grants.ts @@ -395,6 +395,49 @@ export async function putManualGrant( }) } +/** + * Ops: put a team on a contact-sales plan (Enterprise). The plan's current version is projected + * as a manual grant that names the real plan and version, so the audit row and /v1/entitlements + * show e.g. enterprise@2. `sourceId` is `plan::`. Sandbox hours and limits still + * come from the team's subscription: manual grants add to one, they do not replace it. + */ +export async function grantContactSalesPlan( + db: D1Database, + catalog: Catalog, + args: { subjectId: string; planId: string; sourceId: string; startsAt: number; endsAt: number | null; actor: string; now: number } +): Promise<{ changed: boolean; planVersion: number }> { + const plan = catalog.plans.get(args.planId) + if (!plan || plan.kind !== 'contact_sales') { + throw new Error(`not_a_contact_sales_plan:${args.planId}`) + } + const entitlements: Partial> = {} + for (const [key, entry] of Object.entries(planVersion(plan, plan.currentVersion).entitlements)) { + if (entry) { + entitlements[key as EntitlementKey] = parseEntitlementValue(key, entry) + } + } + const { changed } = await applyProjection(db, { + subjectId: args.subjectId, + source: 'manual', + sourceId: args.sourceId, + projection: { + state: 'active', + holdReason: null, + heldSince: null, + planId: plan.id, + planVersion: plan.currentVersion, + entitlements, + seatQuantity: null, + startsAt: args.startsAt, + endsAt: args.endsAt + }, + syncedAt: args.now, + now: args.now, + actor: args.actor + }) + return { changed, planVersion: plan.currentVersion } +} + export async function revokeManualGrant( db: D1Database, args: { subjectId: string; source: 'manual' | 'promo'; sourceId: string; reason: string; actor: string; now: number } diff --git a/cloud/apps/billing/src/index.ts b/cloud/apps/billing/src/index.ts index d674ea84316..7ef8e937c96 100644 --- a/cloud/apps/billing/src/index.ts +++ b/cloud/apps/billing/src/index.ts @@ -15,6 +15,7 @@ // POST /v1/stripe/webhook signed events // Sandbox control plane (CONTROL_PLANE_TOKEN): // POST /v1/internal/entitlements/check {accountId, machineSize, runningSandboxes} +// POST /v1/internal/entitlements/features {accountId} -> {features: {audit_log}} plan feature flags // POST /v1/internal/usage {usageId, accountId, sandboxId, machineSize, startedAt, endedAt} // GET /v1/internal/suspensions accounts whose payment grace expired (suspend running) // POST /v1/internal/trial/github {accountId, githubUserId?, githubOwnerId?} GitHub binding -> trial abuse keys @@ -57,6 +58,7 @@ import { MACHINE_SIZES, PlanConfigError, planCatalog, publicOffers } from './pla import { OverageRequestSchema, updateOverage } from './overage' import { LiveModeRefusedError, StripeError, createStripeClient, type StripeClient } from './stripe' import { UsageReportSchema, flushMeterReports, recordUsage, validateSegment } from './usage' +import { FeaturesRequestSchema, featuresFor } from './features' import { handleStripeWebhook } from './webhook' import { UsageHistoryQuerySchema, usageHistory } from './usage-history' import { renderReturnPage, returnOutcome } from './return-page' @@ -515,6 +517,18 @@ export async function handleRequest(request: Request, env: Env, ctx: ExecutionCo }) } + case 'POST /v1/internal/entitlements/features': { + // Plan features the control plane gates a surface on (the team audit log). + if (!(await authenticateControlPlane(env, request))) { + return json({ error: 'unauthorized' }, 401) + } + const body = FeaturesRequestSchema.safeParse(await readJson(request)) + if (!body.success) { + return json({ error: 'invalid_request' }, 400) + } + return json({ features: await featuresFor(env, body.data.accountId, now) }) + } + case 'POST /v1/internal/usage': { if (!(await authenticateControlPlane(env, request))) { return json({ error: 'unauthorized' }, 401) diff --git a/cloud/apps/billing/src/plans-api.ts b/cloud/apps/billing/src/plans-api.ts index ac0e6e160a5..554ea7a21ad 100644 --- a/cloud/apps/billing/src/plans-api.ts +++ b/cloud/apps/billing/src/plans-api.ts @@ -7,6 +7,7 @@ import { checkoutPrice } from './catalog-sync' import { defaultSelfServePlan, loadCatalog, planVersion, policyFor, type Catalog, type CatalogPlan } from './catalog' import { catalogOverageCentsPerHour, computeEntitlement, entitlementsMode, type Entitlement } from './entitlements' import type { Env } from './env' +import { featuresFor } from './features' import { grantsForSubject, liveAt } from './grants' import { MACHINE_SIZE_WEIGHT, planCatalog, publicOffers, type BillingInterval } from './plans' @@ -152,7 +153,9 @@ export async function entitlementsView(env: Env, accountId: string, canManageBil machineSizes: entitlement.limits.machineSizes, overage: entitlement.overage, overageSeconds: entitlement.overageSeconds, - usageWarningPercent: entitlement.usageWarningPercent + usageWarningPercent: entitlement.usageWarningPercent, + // Additive: plan features (Enterprise). Who may use each one is the owning service's call. + features: await featuresFor(env, accountId, now) }, access: { canStartSandbox: entitlement.canStartSandbox, reason: entitlement.reason, suspendRunning: entitlement.suspendRunning }, payment: { pastDueSince: entitlement.payment.pastDueSince, graceEndsAt: entitlement.payment.graceEndsAt },