diff --git a/cloud/apps/billing/migrations/0005_trials.sql b/cloud/apps/billing/migrations/0005_trials.sql new file mode 100644 index 00000000000..7c2d76f481b --- /dev/null +++ b/cloud/apps/billing/migrations/0005_trials.sql @@ -0,0 +1,31 @@ +-- One-time trial (N11, O7): 2 sandbox hours per new team, no card, granted once per team and +-- once per user, verified email, GitHub user and GitHub owner. A subscription on the account ends +-- it (entitlements.ts ignores the trial once any subscription row exists). Times are epoch ms. +CREATE TABLE trials ( + account_id TEXT PRIMARY KEY, + granted_at INTEGER NOT NULL, + included_seconds INTEGER NOT NULL DEFAULT 7200, + -- Cache of SUM(usage_events.weighted_seconds) with no subscription (period_start IS NULL). + used_seconds INTEGER NOT NULL DEFAULT 0, + exhausted_at INTEGER, + granted_by_user TEXT NOT NULL, + github_owner_id TEXT, + github_user_id TEXT, + -- Set when a later check (GitHub binding) finds the same GitHub user/owner already used a trial. + revoked_at INTEGER, + revoked_reason TEXT +); + +-- Abuse keys. kind: 'user' | 'email' | 'github_user' | 'github_owner' | 'ip'. key_hash is SHA-256 +-- of the normalized value, so raw emails and IPs are never stored. granted = 1 once the key is +-- consumed by a granted trial (0 = seen on the account before a grant, e.g. a GitHub binding). +CREATE TABLE trial_claims ( + kind TEXT NOT NULL, + key_hash TEXT NOT NULL, + account_id TEXT NOT NULL, + granted INTEGER NOT NULL DEFAULT 1, + created_at INTEGER NOT NULL, + PRIMARY KEY (kind, key_hash, account_id) +); +CREATE INDEX trial_claims_account ON trial_claims(account_id); +CREATE INDEX trial_claims_recent ON trial_claims(kind, key_hash, created_at); diff --git a/cloud/apps/billing/scripts/e2e-test-mode.ts b/cloud/apps/billing/scripts/e2e-test-mode.ts index 40e06ebea7f..e39e8379868 100644 --- a/cloud/apps/billing/scripts/e2e-test-mode.ts +++ b/cloud/apps/billing/scripts/e2e-test-mode.ts @@ -17,7 +17,8 @@ // blocks starts and puts running sandboxes to sleep -> peak seats (add charged // now, removal deferred, re-add free) -> annual plan + overage (an older overage item is re-priced, not doubled) -> seat true-down + test-clock // renewal -> invoice.payment_failed -> grace -> suspend -> pay -> resume -> cancel -> 3DS Checkout -// (challenge passed; 3DS-then-decline and insufficient funds create nothing) -> cleanup. +// (challenge passed; 3DS-then-decline and insufficient funds create nothing) -> one-time trial (granted +// with no card, 1 at a time, metered until used up, once per user, a plan ends it) -> cleanup. // Prints PASS/FAIL per check and the ids. import { execFileSync } from 'node:child_process' import { readFileSync, writeFileSync } from 'node:fs' @@ -67,9 +68,9 @@ function check(name: string, ok: boolean, detail: unknown = ''): boolean { } const ids: Record = {} -async function token(org: string): Promise { +async function token(org: string, user = `user_${org}`): Promise { const now = Math.floor(Date.now() / 1000) - return new SignJWT({ sub: `user_${org}`, org, orgRole: 'owner', email: `e2e+${org}@example.com`, purpose: 'billing' }) + return new SignJWT({ sub: user, org, orgRole: 'owner', email: `e2e+${user}@example.com`, purpose: 'billing' }) .setProtectedHeader({ alg: 'ES256', kid: jwk.kid }) .setIssuer(issuer) .setAudience('orca-billing') @@ -78,9 +79,9 @@ async function token(org: string): Promise { .sign(signingKey) } -async function billing(method: string, path: string, org: string | null, body?: unknown) { +async function billing(method: string, path: string, org: string | null, body?: unknown, user?: string) { const headers: Record = { 'content-type': 'application/json' } - headers.authorization = `Bearer ${org ? await token(org) : CONTROL}` + headers.authorization = `Bearer ${org ? await token(org, user) : CONTROL}` const response = await fetch(`${BILLING_URL}${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) }) return { status: response.status, body: (await response.json().catch(() => ({}))) as Record } } @@ -476,6 +477,49 @@ for (const [name, card, threeDS] of [ await stripe('POST', `/v1/checkout/sessions/${session.id}/expire`).catch(() => undefined) } +// ---- 9b. One-time trial (N11): no card, 1 at a time, metered until used up, once per user ---- +const orgT = `e2e-${runId}-trial` +const accountT = `org:${orgT}` +const offered = await entitlement(orgT) +check('new team is offered the trial (2 sandbox hours), not yet granted', offered.reason === 'no_subscription' && + offered.offers?.trial?.includedSeconds === 2 * HOUR && offered.trial === null, { reason: offered.reason, trial: offered.offers?.trial }) +const grantedT = await billing('POST', '/v1/billing/trial', orgT) +check('trial granted with no card: status trial, can start, 1 sandbox at a time, no overage', grantedT.status === 200 && + grantedT.body.status === 'trial' && grantedT.body.canStartSandbox === true && grantedT.body.limits?.maxConcurrentSandboxes === 1 && + grantedT.body.trial?.includedSeconds === 2 * HOUR && grantedT.body.overage?.active === false, grantedT) +const trialCustomers = await stripe<{ data: Array<{ metadata: Record }> }>('GET', '/v1/customers', { email: `e2e+user_${orgT}@example.com`, limit: 10 }) +check('trial created nothing in Stripe (no customer)', trialCustomers.data.length === 0, trialCustomers.data.length) +const secondRunning = await billing('POST', '/v1/internal/entitlements/check', null, { accountId: accountT, machineSize: 'standard', runningSandboxes: 1 }).then((r) => r.body) +check('trial runs 1 sandbox at a time (concurrency_limit)', secondRunning.allow === false && secondRunning.reason === 'concurrency_limit', secondRunning) +const trialOverage = await billing('POST', '/v1/billing/overage', orgT, { enabled: true }) +check('no overage during a trial', trialOverage.status === 409, trialOverage) +const partway = await reportUsage(accountT, 1.5) +check('trial usage is metered (1.5 of 2 h used, still can start)', partway.canStartSandbox === true && partway.overageSeconds === 0, partway) +const usedUp = await reportUsage(accountT, 1) +check('trial used up -> trial_used_up, running sandboxes go to sleep', usedUp.canStartSandbox === false && + usedUp.reason === 'trial_used_up' && usedUp.suspendRunning === true, usedUp) +const sameUser = await billing('POST', '/v1/billing/trial', `${orgT}-2`, undefined, `user_${orgT}`) +check('the same user gets no second trial on another team (trial_unavailable)', sameUser.status === 403 && + sameUser.body.error === 'trial_unavailable', sameUser) +// A plan ends the trial (unused trial hours lapse). +const customerT = await stripe<{ id: string }>('POST', '/v1/customers', { email: `e2e+${orgT}@example.com`, metadata: { account_id: accountT } }) +ids.trialCustomer = customerT.id +linkAccount(accountT, customerT.id) +await stripe('POST', '/v1/payment_methods/pm_card_visa/attach', { customer: customerT.id }) + .then((pm: any) => stripe('POST', `/v1/customers/${customerT.id}`, { invoice_settings: { default_payment_method: pm.id } })) +const trialSub = await stripe<{ id: string }>('POST', '/v1/subscriptions', { + customer: customerT.id, + items: [{ price: catalog.STRIPE_PRICE_TEAM_MONTHLY, quantity: 1 }], + metadata: { account_id: accountT } +}) +ids.trialSubscription = trialSub.id +const afterPlan = await until('plan replaces trial', () => entitlement(orgT), (e) => e.status === 'active') +check('a plan ends the trial: Team active, trial gone, 60 h included', afterPlan.status === 'active' && afterPlan.trial === null && + afterPlan.includedSeconds === 60 * HOUR && afterPlan.canStartSandbox === true, { status: afterPlan.status, trial: afterPlan.trial }) +await stripe('DELETE', `/v1/subscriptions/${trialSub.id}`).catch((error) => console.log(` cleanup: ${error}`)) +// Drop this run's trial abuse keys (incl. the per-IP grant count) so reruns from this machine aren't rate limited. +d1(`DELETE FROM trial_claims WHERE account_id LIKE 'org:e2e-${runId}-%'`) + // ---- 10. Cleanup: remaining test subscriptions and the test clock (deletes its customer) ------- await stripe('DELETE', `/v1/subscriptions/${ids.annualSubscription}`).catch((error) => console.log(` cleanup: ${error}`)) await stripe('DELETE', `/v1/test_helpers/test_clocks/${ids.testClock}`).catch((error) => console.log(` cleanup: ${error}`)) diff --git a/cloud/apps/billing/src/auth.ts b/cloud/apps/billing/src/auth.ts index f34e177b006..944208b4248 100644 --- a/cloud/apps/billing/src/auth.ts +++ b/cloud/apps/billing/src/auth.ts @@ -16,6 +16,10 @@ const ClaimsSchema = z.object({ // Role in `org`. Only owners and admins may buy or manage the org's plan. orgRole: z.enum(['owner', 'admin', 'member']).optional(), email: z.string().email().max(320).optional(), + // Trial abuse limits (trial.ts): false refuses the trial; absent means auth's provider only signs + // in confirmed emails. The GitHub user id is present when the user signed in with GitHub. + emailVerified: z.boolean().optional(), + githubUserId: z.string().regex(/^\d{1,20}$/).optional(), purpose: z.literal('billing') }) @@ -24,6 +28,8 @@ export type BillingCaller = { accountId: string canManage: boolean email?: string + emailVerified?: boolean + githubUserId?: string } const keySets = new Map() @@ -136,7 +142,9 @@ export async function authenticateDesktop( userId: claims.sub, accountId: accountIdFor(claims), canManage: !claims.org || claims.orgRole === 'owner' || claims.orgRole === 'admin', - email: claims.email + email: claims.email, + ...(claims.emailVerified === undefined ? {} : { emailVerified: claims.emailVerified }), + ...(claims.githubUserId ? { githubUserId: claims.githubUserId } : {}) } } catch { return null diff --git a/cloud/apps/billing/src/entitlements.ts b/cloud/apps/billing/src/entitlements.ts index 3fc2808cb62..4d56cd2e103 100644 --- a/cloud/apps/billing/src/entitlements.ts +++ b/cloud/apps/billing/src/entitlements.ts @@ -14,6 +14,7 @@ import { } from './plans' import { accountSettings, currentSubscription, meteredSeconds, periodUsage, type SubscriptionRow } from './store' import { PAYMENT_FAILED_STATUSES } from './webhook' +import { TRIAL_MAX_CONCURRENT_SANDBOXES, trialRow, trialState, type TrialState } from './trial' export type DenyReason = | 'no_subscription' @@ -25,6 +26,9 @@ export type DenyReason = | 'machine_size_not_in_plan' | 'concurrency_limit' | 'member_concurrency_limit' + // One-time trial (trial.ts): its sandbox hours are used up, or this team can't have one. + | 'trial_used_up' + | 'trial_unavailable' export type Entitlement = { accountId: string @@ -42,6 +46,11 @@ export type Entitlement = { /** Monthly allowance window the hours below count against. */ usageWindow: { start: number; end: number } | null cancelAtPeriodEnd: boolean + /** + * The one-time trial while it is the account's plan (no subscription ever). Null otherwise: a + * subscription ends the trial for good. includedSeconds/usedSeconds below mirror it during a trial. + */ + trial: TrialState | null includedSeconds: number usedSeconds: number remainingIncludedSeconds: number @@ -92,6 +101,10 @@ export async function computeEntitlement( const spendCapCents = settings.spend_cap_cents ?? team.defaultSpendCapCents const overageBase = { optedIn: settings.overage_opt_in === 1, spendCapCents, centsPerHour: team.overageCentsPerHour } if (!subscription) { + const trialRecord = await trialRow(db, accountId) + if (trialRecord && trialRecord.revoked_at === null) { + return trialEntitlement(accountId, trialState(trialRecord), team, overageBase) + } return { accountId, plan: null, @@ -104,6 +117,7 @@ export async function computeEntitlement( period: null, usageWindow: null, cancelAtPeriodEnd: false, + trial: null, includedSeconds: 0, usedSeconds: 0, remainingIncludedSeconds: 0, @@ -117,9 +131,10 @@ export async function computeEntitlement( idleSleepMinutes: team.idleSleepMinutes }, payment: { pastDueSince: null, graceEndsAt: null, suspendRunning: false }, - suspendRunning: false, + // A revoked trial (GitHub identity reused): its running sandbox goes to sleep too. + suspendRunning: trialRecord !== null, canStartSandbox: false, - reason: 'no_subscription' + reason: trialRecord ? 'trial_unavailable' : 'no_subscription' } } const window = subscriptionWindow(subscription, now) @@ -166,6 +181,7 @@ export async function computeEntitlement( period: { start: subscription.current_period_start, end: subscription.current_period_end }, usageWindow: window, cancelAtPeriodEnd: subscription.cancel_at_period_end === 1, + trial: null, includedSeconds: included, usedSeconds: usage.usedSeconds, remainingIncludedSeconds: remaining, @@ -190,6 +206,49 @@ export async function computeEntitlement( } } +/** No card, no Stripe: the trial's hours, 1 sandbox at a time, never overage. */ +function trialEntitlement( + accountId: string, + trial: TrialState, + team: ReturnType['team'], + overageBase: { optedIn: boolean; spendCapCents: number; centsPerHour: number } +): Entitlement { + const usedPercent = trial.includedSeconds > 0 ? (trial.usedSeconds / trial.includedSeconds) * 100 : 100 + const warnings = team.warnAtPercent.filter((level) => usedPercent >= level) + const reason: DenyReason | null = trial.exhausted ? 'trial_used_up' : null + return { + accountId, + plan: null, + planLabel: null, + status: 'trial', + interval: null, + seats: 0, + members: null, + seatChange: null, + period: null, + usageWindow: null, + cancelAtPeriodEnd: false, + trial, + includedSeconds: trial.includedSeconds, + usedSeconds: trial.usedSeconds, + remainingIncludedSeconds: trial.remainingSeconds, + usageWarningPercent: warnings.length > 0 ? Math.max(...warnings) : null, + overageSeconds: 0, + overage: { ...overageBase, optedIn: false, active: false, spentCents: 0 }, + limits: { + maxConcurrentSandboxes: TRIAL_MAX_CONCURRENT_SANDBOXES, + maxConcurrentSandboxesPerMember: TRIAL_MAX_CONCURRENT_SANDBOXES, + machineSizes: team.machineSizes, + idleSleepMinutes: team.idleSleepMinutes + }, + payment: { pastDueSince: null, graceEndsAt: null, suspendRunning: false }, + // Used up: running sandboxes go to sleep (snapshot kept) until a plan starts. + suspendRunning: trial.exhausted, + canStartSandbox: reason === null, + reason + } +} + export function isMachineSize(value: unknown): value is MachineSize { return typeof value === 'string' && (MACHINE_SIZES as readonly string[]).includes(value) } diff --git a/cloud/apps/billing/src/index.ts b/cloud/apps/billing/src/index.ts index bf2f93519d1..27f5af82665 100644 --- a/cloud/apps/billing/src/index.ts +++ b/cloud/apps/billing/src/index.ts @@ -6,12 +6,14 @@ // POST /v1/billing/overage {enabled, spendCapCents?} opt in/out of overage, set the cap // POST /v1/billing/portal -> { url } Stripe Customer Portal // POST /v1/billing/team-plans {orgIds} other teams' plan state ("Switch to "), read-only +// POST /v1/billing/trial claim the team's one-time trial -> entitlement (trial.ts) // Stripe: // POST /v1/stripe/webhook signed events // Sandbox control plane (CONTROL_PLANE_TOKEN): // POST /v1/internal/entitlements/check {accountId, machineSize, runningSandboxes} // 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 // Orca Cloud auth (MEMBERSHIP_SYNC_TOKEN): // POST /v1/internal/seats {accountId, members} // POST /v1/internal/cloud-setup/redeem {sessionId, ticket} -> {userId} one-time browser ticket @@ -73,6 +75,8 @@ import { setupSessionView } from './cloud-setup' import { noTrialPort, type TrialPort } from './cloud-setup-trial' +import { grantTrial, isTeamAccount, recordTrialGithub, trialOffer, type TrialInput } from './trial' +import type { BillingCaller } from './auth' const MAX_JSON_BYTES = 16 * 1024 @@ -87,6 +91,34 @@ const StartCheckSchema = z }) .strict() +const GITHUB_ID = z.string().regex(/^\d{1,20}$/) +const TrialGithubSchema = z + .object({ accountId: z.string().min(1).max(128), githubUserId: GITHUB_ID.optional(), githubOwnerId: GITHUB_ID.optional() }) + .strict() + +function trialInput(caller: BillingCaller, request: Request): TrialInput { + return { + accountId: caller.accountId, + userId: caller.userId, + email: caller.email, + emailVerified: caller.emailVerified, + githubUserId: caller.githubUserId, + ip: request.headers.get('cf-connecting-ip') ?? undefined + } +} + +/** The desktop's entitlement body: the account's state plus what this caller is offered. */ +async function desktopEntitlement(env: Env, caller: BillingCaller, request: Request, now: number) { + const entitlement = await computeEntitlement(env, caller.accountId, now) + const offers = publicOffers(planCatalog(env)) + const neverHadPlan = entitlement.reason === 'no_subscription' + const trial = neverHadPlan ? await trialOffer(env, trialInput(caller, request), now) : null + // A team that never had a plan but can't get a trial (one already used by this user, email, + // GitHub identity, or a disposable email) is told so instead of being offered one. + const reason = neverHadPlan && !trial && isTeamAccount(caller.accountId) ? 'trial_unavailable' : entitlement.reason + return { ...entitlement, reason, canManageBilling: caller.canManage, offers: { ...offers, trial } } +} + function json(body: unknown, status = 200): Response { return Response.json(body, { status, headers: { 'cache-control': 'no-store' } }) } @@ -274,8 +306,31 @@ export async function handleRequest(request: Request, env: Env, ctx: ExecutionCo if (!caller) { return json({ error: 'unauthorized' }, 401) } - const entitlement = await computeEntitlement(env, caller.accountId, now) - return json({ ...entitlement, canManageBilling: caller.canManage, offers: publicOffers(planCatalog(env)) }) + return json(await desktopEntitlement(env, caller, request, now)) + } + + case 'POST /v1/billing/trial': { + // Any member may start the team's trial the first time they pick Orca Cloud (spec B1). + const caller = await authenticateDesktop(env, request) + if (!caller) { + return json({ error: 'unauthorized' }, 401) + } + const outcome = await grantTrial(env, trialInput(caller, request), now) + if (!outcome.ok) { + return json({ error: outcome.reason }, outcome.reason === 'team_required' ? 409 : 403) + } + return json(await desktopEntitlement(env, caller, request, now)) + } + + case 'POST /v1/internal/trial/github': { + if (!(await authenticateControlPlane(env, request))) { + return json({ error: 'unauthorized' }, 401) + } + const body = TrialGithubSchema.safeParse(await readJson(request)) + if (!body.success) { + return json({ error: 'invalid_request' }, 400) + } + return json(await recordTrialGithub(env, body.data, now)) } case 'POST /v1/billing/team-plans': { @@ -327,8 +382,7 @@ export async function handleRequest(request: Request, env: Env, ctx: ExecutionCo if (!outcome.ok) { return json({ error: outcome.error }, outcome.status) } - const entitlement = await computeEntitlement(env, caller.accountId, now) - return json({ ...entitlement, canManageBilling: caller.canManage, offers: publicOffers(planCatalog(env)) }) + return json(await desktopEntitlement(env, caller, request, now)) } case 'POST /v1/internal/seats': { diff --git a/cloud/apps/billing/src/trial.ts b/cloud/apps/billing/src/trial.ts new file mode 100644 index 00000000000..8f677d58b0f --- /dev/null +++ b/cloud/apps/billing/src/trial.ts @@ -0,0 +1,411 @@ +// One-time trial (spec N11, decision O7): 2 sandbox hours per new team, no card, no Stripe. +// - Granted explicitly (POST /v1/billing/trial, or grantTrial() from the setup session), never as a +// side effect of reading entitlements, and only to a team (org:) that has never had a +// subscription or a trial. +// - Abuse limits: once per team, per Orca user, per verified email (normalized), per GitHub user id +// and per GitHub owner id; disposable email domains are refused; grants are rate limited per IP. +// Keys are stored as SHA-256 hashes (trial_claims), never raw emails or IPs. +// - A GitHub binding learned after the grant (POST /v1/internal/trial/github) that collides with +// another team's trial revokes this one (trial_unavailable). +// - Metered through usage_events like plan usage (segments with no subscription count against the +// trial). No overage, 1 sandbox at a time. Any subscription row ends the trial for good. +import type { Env } from './env' + +export const TRIAL_INCLUDED_SECONDS = 2 * 3600 +export const TRIAL_MAX_CONCURRENT_SANDBOXES = 1 +/** Trial grants allowed from one IP address per rolling day. */ +export const TRIAL_GRANTS_PER_IP_PER_DAY = 3 +const DAY_MS = 24 * 3600 * 1000 + +// Small built-in list of the most common throwaway-mail providers. Not exhaustive by design: it +// stops casual repeat sign-ups; the per-user, per-email and per-GitHub keys do the rest. +export const DISPOSABLE_EMAIL_DOMAINS: ReadonlySet = new Set([ + '10minutemail.com', + '20minutemail.com', + 'discard.email', + 'dispostable.com', + 'emailondeck.com', + 'fakeinbox.com', + 'getairmail.com', + 'getnada.com', + 'guerrillamail.com', + 'guerrillamail.net', + 'guerrillamailblock.com', + 'maildrop.cc', + 'mailinator.com', + 'mailnesia.com', + 'mintemail.com', + 'mohmal.com', + 'moakt.com', + 'mytemp.email', + 'sharklasers.com', + 'spamgourmet.com', + 'temp-mail.org', + 'tempail.com', + 'tempmail.com', + 'tempmail.dev', + 'tempmailo.com', + 'tempr.email', + 'throwawaymail.com', + 'trashmail.com', + 'yopmail.com', + 'yopmail.net' +]) + +export type TrialRow = { + account_id: string + granted_at: number + included_seconds: number + used_seconds: number + exhausted_at: number | null + granted_by_user: string + github_owner_id: string | null + github_user_id: string | null + revoked_at: number | null + revoked_reason: string | null +} + +/** What the entitlement carries while a trial is the account's plan. */ +export type TrialState = { + includedSeconds: number + usedSeconds: number + remainingSeconds: number + exhausted: boolean + grantedAt: number +} + +export type TrialInput = { + accountId: string + userId: string + email?: string + /** From the auth token; false refuses the trial. Absent: auth only signs in confirmed emails. */ + emailVerified?: boolean + githubUserId?: string + githubOwnerId?: string + /** cf-connecting-ip of the request that asked for the grant. */ + ip?: string +} + +export type TrialRefusal = 'trial_unavailable' | 'team_required' +export type GrantOutcome = { ok: true; trial: TrialState; granted: boolean } | { ok: false; reason: TrialRefusal } + +type ClaimKind = 'user' | 'email' | 'github_user' | 'github_owner' | 'ip' + + +/** Lowercase, strip +tags, and Gmail's ignored dots, so one inbox is one key. */ +export function normalizeEmail(email: string): { address: string; domain: string } | null { + const at = email.trim().toLowerCase().lastIndexOf('@') + if (at <= 0) { + return null + } + const lower = email.trim().toLowerCase() + let local = lower.slice(0, at).split('+')[0] ?? '' + let domain = lower.slice(at + 1) + if (domain === 'googlemail.com') { + domain = 'gmail.com' + } + if (domain === 'gmail.com') { + local = local.replaceAll('.', '') + } + if (!local || !domain.includes('.')) { + return null + } + return { address: `${local}@${domain}`, domain } +} + +export function isDisposableEmailDomain(domain: string): boolean { + const parts = domain.toLowerCase().split('.') + // Also catch subdomains (x.mailinator.com). + for (let i = 0; i < parts.length - 1; i++) { + if (DISPOSABLE_EMAIL_DOMAINS.has(parts.slice(i).join('.'))) { + return true + } + } + return false +} + +async function hashKey(kind: ClaimKind, value: string): Promise { + const bytes = new Uint8Array( + await crypto.subtle.digest('SHA-256', new TextEncoder().encode(`orca-trial:${kind}:${value}`)) + ) + return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('') +} + +const GITHUB_ID = /^\d{1,20}$/ + +/** Trials belong to teams (O1): 'org:', or 'dev:org:' for dev operator accounts. */ +export function isTeamAccount(accountId: string): boolean { + return /^(dev:)?org:/.test(accountId) +} + +async function claimKeys(input: TrialInput): Promise | null> { + const keys: Array<{ kind: ClaimKind; hash: string }> = [{ kind: 'user', hash: await hashKey('user', input.userId) }] + if (input.emailVerified === false || !input.email) { + return null + } + const email = normalizeEmail(input.email) + if (!email || isDisposableEmailDomain(email.domain)) { + return null + } + keys.push({ kind: 'email', hash: await hashKey('email', email.address) }) + if (input.githubUserId && GITHUB_ID.test(input.githubUserId)) { + keys.push({ kind: 'github_user', hash: await hashKey('github_user', input.githubUserId) }) + } + if (input.githubOwnerId && GITHUB_ID.test(input.githubOwnerId)) { + keys.push({ kind: 'github_owner', hash: await hashKey('github_owner', input.githubOwnerId) }) + } + return keys +} + +export async function trialRow(db: D1Database, accountId: string): Promise { + return db.prepare('SELECT * FROM trials WHERE account_id = ?1').bind(accountId).first() +} + +export function trialState(row: TrialRow): TrialState { + const remaining = Math.max(0, row.included_seconds - row.used_seconds) + return { + includedSeconds: row.included_seconds, + usedSeconds: row.used_seconds, + remainingSeconds: remaining, + exhausted: remaining === 0 || row.exhausted_at !== null, + grantedAt: row.granted_at + } +} + +async function everSubscribed(db: D1Database, accountId: string): Promise { + const row = await db.prepare('SELECT 1 AS one FROM subscriptions WHERE account_id = ?1 LIMIT 1').bind(accountId).first() + return row !== null +} + +/** A key some other account's granted trial already used. */ +async function keyTaken(db: D1Database, keys: Array<{ kind: ClaimKind; hash: string }>, accountId: string): Promise { + for (const key of keys) { + const row = await db + .prepare('SELECT 1 AS one FROM trial_claims WHERE kind = ?1 AND key_hash = ?2 AND account_id <> ?3 AND granted = 1 LIMIT 1') + .bind(key.kind, key.hash, accountId) + .first() + if (row) { + return true + } + } + return false +} + +/** GitHub keys a binding recorded on this account before the trial was asked for. */ +async function boundGithubKeys(db: D1Database, accountId: string): Promise> { + const { results } = await db + .prepare("SELECT kind, key_hash FROM trial_claims WHERE account_id = ?1 AND kind IN ('github_user', 'github_owner')") + .bind(accountId) + .all<{ kind: ClaimKind; key_hash: string }>() + return results.map((row) => ({ kind: row.kind, hash: row.key_hash })) +} + +async function recentIpGrants(db: D1Database, ipHash: string, now: number): Promise { + const row = await db + .prepare("SELECT COUNT(*) AS n FROM trial_claims WHERE kind = 'ip' AND key_hash = ?1 AND created_at > ?2") + .bind(ipHash, now - DAY_MS) + .first<{ n: number }>() + return row?.n ?? 0 +} + +/** + * Whether this caller could get a trial for `input.accountId` right now (read only). A personal + * account (user:) is checked as the user who will get one once setup creates their team. + */ +export async function trialOffer( + env: Pick, + input: TrialInput, + _now: number +): Promise<{ includedSeconds: number } | null> { + const db = env.BILLING_DB + if ((await trialRow(db, input.accountId)) || (await everSubscribed(db, input.accountId))) { + return null + } + const keys = await claimKeys(input) + if (!keys) { + return null + } + const all = isTeamAccount(input.accountId) ? [...keys, ...(await boundGithubKeys(db, input.accountId))] : keys + if (await keyTaken(db, all, input.accountId)) { + return null + } + return { includedSeconds: TRIAL_INCLUDED_SECONDS } +} + +/** + * Grants the team its trial, atomically with every abuse key it consumes. Idempotent: a team that + * already has a trial gets it back (granted: false). Refusals never say which key matched. + */ +export async function grantTrial( + env: Pick, + input: TrialInput, + now: number +): Promise { + const db = env.BILLING_DB + if (!isTeamAccount(input.accountId)) { + // O1: trials and plans belong to a team; setup creates one first. + return { ok: false, reason: 'team_required' } + } + const existing = await trialRow(db, input.accountId) + if (existing) { + return existing.revoked_at === null && !(await everSubscribed(db, input.accountId)) + ? { ok: true, trial: trialState(existing), granted: false } + : { ok: false, reason: 'trial_unavailable' } + } + if (await everSubscribed(db, input.accountId)) { + return { ok: false, reason: 'trial_unavailable' } + } + const keys = await claimKeys(input) + if (!keys) { + return { ok: false, reason: 'trial_unavailable' } + } + const bound = await boundGithubKeys(db, input.accountId) + const consumed = [...keys, ...bound.filter((key) => !keys.some((own) => own.kind === key.kind && own.hash === key.hash))] + const ipHash = input.ip ? await hashKey('ip', input.ip) : null + if (ipHash && (await recentIpGrants(db, ipHash, now)) >= TRIAL_GRANTS_PER_IP_PER_DAY) { + return { ok: false, reason: 'trial_unavailable' } + } + const included = TRIAL_INCLUDED_SECONDS + // One transaction: the trial row is inserted only if no key is taken and the account never + // subscribed (re-checked inside the batch, so two concurrent grants can't share a key), then + // every key is marked consumed for this account. + const takenClause = consumed + .map((_, index) => `EXISTS (SELECT 1 FROM trial_claims WHERE kind = ?${7 + index * 2} AND key_hash = ?${8 + index * 2} AND account_id <> ?1 AND granted = 1)`) + .join(' OR ') + const keyParams = consumed.flatMap((key) => [key.kind, key.hash]) + const insertTrial = db + .prepare( + `INSERT OR IGNORE INTO trials (account_id, granted_at, included_seconds, used_seconds, granted_by_user, github_owner_id, github_user_id) + SELECT ?1, ?2, ?3, 0, ?4, ?5, ?6 + WHERE NOT EXISTS (SELECT 1 FROM subscriptions WHERE account_id = ?1) + AND NOT EXISTS (SELECT 1 FROM trials WHERE account_id = ?1) + AND NOT (${takenClause})` + ) + .bind( + input.accountId, + now, + included, + input.userId, + input.githubOwnerId && GITHUB_ID.test(input.githubOwnerId) ? input.githubOwnerId : null, + input.githubUserId && GITHUB_ID.test(input.githubUserId) ? input.githubUserId : null, + ...keyParams + ) + const claimRows = [...consumed, ...(ipHash ? [{ kind: 'ip' as const, hash: ipHash }] : [])].map((key) => + db + .prepare( + `INSERT INTO trial_claims (kind, key_hash, account_id, granted, created_at) + SELECT ?1, ?2, ?3, 1, ?4 WHERE EXISTS (SELECT 1 FROM trials WHERE account_id = ?3 AND granted_at = ?4 AND granted_by_user = ?5) + ON CONFLICT (kind, key_hash, account_id) DO UPDATE SET granted = 1` + ) + .bind(key.kind, key.hash, input.accountId, now, input.userId) + ) + await db.batch([insertTrial, ...claimRows]) + const row = await trialRow(db, input.accountId) + if (!row || row.granted_at !== now || row.granted_by_user !== input.userId) { + // Lost a race to a concurrent grant for the same team (fine: return it) or a key was taken. + return row && row.revoked_at === null ? { ok: true, trial: trialState(row), granted: false } : { ok: false, reason: 'trial_unavailable' } + } + return { ok: true, trial: trialState(row), granted: true } +} + +/** + * Records the GitHub identities a team bound (from the control plane's GitHub App binding). If the + * team already has a trial and another team's trial used either identity, this trial is revoked. + */ +export async function recordTrialGithub( + env: Pick, + input: { accountId: string; githubUserId?: string; githubOwnerId?: string }, + now: number +): Promise<{ revoked: boolean }> { + const db = env.BILLING_DB + if (!isTeamAccount(input.accountId)) { + // Personal accounts never get a trial, so their GitHub bindings aren't trial keys. + return { revoked: false } + } + const keys: Array<{ kind: ClaimKind; hash: string; raw: string }> = [] + if (input.githubUserId && GITHUB_ID.test(input.githubUserId)) { + keys.push({ kind: 'github_user', hash: await hashKey('github_user', input.githubUserId), raw: input.githubUserId }) + } + if (input.githubOwnerId && GITHUB_ID.test(input.githubOwnerId)) { + keys.push({ kind: 'github_owner', hash: await hashKey('github_owner', input.githubOwnerId), raw: input.githubOwnerId }) + } + if (keys.length === 0) { + return { revoked: false } + } + const trial = await trialRow(db, input.accountId) + const live = trial !== null && trial.revoked_at === null + if (live && (await keyTaken(db, keys, input.accountId))) { + await db + .prepare("UPDATE trials SET revoked_at = ?2, revoked_reason = 'github_identity_reused' WHERE account_id = ?1 AND revoked_at IS NULL") + .bind(input.accountId, now) + .run() + return { revoked: true } + } + await db.batch( + keys.map((key) => + db + .prepare( + `INSERT INTO trial_claims (kind, key_hash, account_id, granted, created_at) VALUES (?1, ?2, ?3, ?4, ?5) + ON CONFLICT (kind, key_hash, account_id) DO UPDATE SET granted = MAX(granted, excluded.granted)` + ) + .bind(key.kind, key.hash, input.accountId, live ? 1 : 0, now) + ) + ) + if (live) { + await db + .prepare( + 'UPDATE trials SET github_user_id = COALESCE(github_user_id, ?2), github_owner_id = COALESCE(github_owner_id, ?3) WHERE account_id = ?1' + ) + .bind(input.accountId, input.githubUserId ?? null, input.githubOwnerId ?? null) + .run() + } + return { revoked: false } +} + +/** Re-totals the trial's usage from usage_events (idempotent; called after each usage report). */ +export async function refreshTrialUsage(db: D1Database, accountId: string, now: number): Promise { + await db + .prepare( + `UPDATE trials SET + used_seconds = (SELECT COALESCE(SUM(weighted_seconds), 0) FROM usage_events + WHERE account_id = ?1 AND period_start IS NULL), + exhausted_at = CASE + WHEN exhausted_at IS NOT NULL THEN exhausted_at + WHEN (SELECT COALESCE(SUM(weighted_seconds), 0) FROM usage_events + WHERE account_id = ?1 AND period_start IS NULL) >= included_seconds THEN ?2 + ELSE NULL END + WHERE account_id = ?1` + ) + .bind(accountId, now) + .run() +} + +/** + * Generic fixed-window per-IP limiter for unauthenticated or pre-team endpoints (the setup session + * uses it too). Stores only a hash of the IP. Returns false when over `limit` in `windowMs`. + */ +export async function rateLimitIp( + env: Pick, + ip: string | null | undefined, + scope: string, + limit: number, + windowMs: number, + now: number +): Promise { + if (!ip) { + return true + } + const hash = await hashKey('ip', `${scope}:${ip}`) + const row = await env.BILLING_DB + .prepare("SELECT COUNT(*) AS n FROM trial_claims WHERE kind = 'ip' AND key_hash = ?1 AND created_at > ?2") + .bind(hash, now - windowMs) + .first<{ n: number }>() + if ((row?.n ?? 0) >= limit) { + return false + } + await env.BILLING_DB + .prepare("INSERT OR IGNORE INTO trial_claims (kind, key_hash, account_id, granted, created_at) VALUES ('ip', ?1, ?2, 0, ?3)") + .bind(hash, `rate:${scope}:${now}:${crypto.randomUUID()}`, now) + .run() + return true +} diff --git a/cloud/apps/billing/src/usage.ts b/cloud/apps/billing/src/usage.ts index 015e0b6fc71..ee4c02e5651 100644 --- a/cloud/apps/billing/src/usage.ts +++ b/cloud/apps/billing/src/usage.ts @@ -18,6 +18,7 @@ import { pendingMeterReports, usageOverage } from './store' +import { refreshTrialUsage } from './trial' // One segment is at most a day: the control plane settles running sandboxes periodically. const MAX_SEGMENT_MS = 24 * 3600 * 1000 @@ -91,6 +92,10 @@ export async function recordUsage( meterCustomer: customer, meterCapSeconds: capSeconds(team, settings.spend_cap_cents ?? team.defaultSpendCapCents) }) + if (!subscription) { + // No plan: the segment counts against the one-time trial, if any (never overage). + await refreshTrialUsage(db, report.accountId, now) + } return { recorded, weightedSeconds, overageSeconds: await usageOverage(db, report.usageId) } } diff --git a/cloud/apps/billing/test/billing-config.test.ts b/cloud/apps/billing/test/billing-config.test.ts index cdd2e1c85a6..7c6d6281d6f 100644 --- a/cloud/apps/billing/test/billing-config.test.ts +++ b/cloud/apps/billing/test/billing-config.test.ts @@ -46,7 +46,9 @@ describe('config: tax and plan catalog', () => { defaultSpendCapCents: 5000, maxSpendCapCents: 500_000 }, - enterprise: { label: 'Enterprise', priceLabel: 'Custom', contactUrl: 'https://example.test/sales' } + enterprise: { label: 'Enterprise', priceLabel: 'Custom', contactUrl: 'https://example.test/sales' }, + // No email on this token: no trial on offer. + trial: null }) expect(entitlement.body.overage.spendCapCents).toBe(5000) }) diff --git a/cloud/apps/billing/test/harness.ts b/cloud/apps/billing/test/harness.ts index ecae834688f..03e2aae5dc7 100644 --- a/cloud/apps/billing/test/harness.ts +++ b/cloud/apps/billing/test/harness.ts @@ -79,7 +79,7 @@ export async function createHarness(overrides: Partial = {}) { setFetch(impl: typeof fetch) { outboundFetch = impl }, - async desktopToken(claims: { sub: string; org?: string; orgRole?: string; email?: string; orgMembers?: number }, options: { audience?: string; purpose?: string; ageSeconds?: number } = {}) { + async desktopToken(claims: { sub: string; org?: string; orgRole?: string; email?: string; orgMembers?: number; emailVerified?: boolean; githubUserId?: string }, options: { audience?: string; purpose?: string; ageSeconds?: number } = {}) { const iat = Math.floor(now / 1000) - (options.ageSeconds ?? 0) return new SignJWT({ ...claims, purpose: options.purpose ?? 'billing' }) .setProtectedHeader({ alg: 'ES256', kid: jwk.kid }) diff --git a/cloud/apps/billing/test/trial.test.ts b/cloud/apps/billing/test/trial.test.ts new file mode 100644 index 00000000000..6c39d962921 --- /dev/null +++ b/cloud/apps/billing/test/trial.test.ts @@ -0,0 +1,224 @@ +import { describe, expect, it } from 'vitest' +import { checkoutCompleted } from './stripe-fake' +import { createHarness } from './harness' +import { TRIAL_GRANTS_PER_IP_PER_DAY, isDisposableEmailDomain, normalizeEmail } from '../src/trial' + +const HOUR = 3600 + +type Harness = Awaited> + +async function as(h: Harness, claims: Parameters[0], ip = '203.0.113.7') { + const token = await h.desktopToken(claims) + return { authorization: `Bearer ${token}`, 'cf-connecting-ip': ip } +} + +function segment(accountId: string, id: string, hours: number, endedAt = Date.now() - 60_000) { + return { usageId: id, accountId, sandboxId: 'sbx_t', machineSize: 'standard', startedAt: endedAt - hours * HOUR * 1000, endedAt, userId: 'u1' } +} + +function startCheck(accountId: string, runningSandboxes = 0) { + return { accountId, machineSize: 'standard', runningSandboxes, userId: 'u1', runningSandboxesForUser: runningSandboxes } +} + +describe('trial grant', () => { + it('offers a new team 2 sandbox hours, then grants them once with no card', async () => { + const h = await createHarness() + const owner = await as(h, { sub: 'u1', org: 'o1', orgRole: 'owner', email: 'neil@acme.dev' }) + const before = await h.call('GET', '/v1/billing/entitlements', { headers: owner }) + expect(before.body.reason).toBe('no_subscription') + expect(before.body.offers.trial).toEqual({ includedSeconds: 7200 }) + expect(before.body.trial).toBeNull() + + const granted = await h.call('POST', '/v1/billing/trial', { headers: owner }) + expect(granted.status).toBe(200) + expect(granted.body).toMatchObject({ + status: 'trial', + plan: null, + canStartSandbox: true, + reason: null, + includedSeconds: 7200, + remainingIncludedSeconds: 7200, + trial: { includedSeconds: 7200, usedSeconds: 0, remainingSeconds: 7200, exhausted: false }, + limits: { maxConcurrentSandboxes: 1, maxConcurrentSandboxesPerMember: 1 }, + overage: { optedIn: false, active: false } + }) + // Once granted it's no longer "on offer"; Stripe was never called. + expect(granted.body.offers.trial).toBeNull() + expect(h.stripe.calls).toHaveLength(0) + + // Idempotent: asking again (any member) returns the same trial. + const member = await as(h, { sub: 'u2', org: 'o1', orgRole: 'member', email: 'sam@acme.dev' }) + const again = await h.call('POST', '/v1/billing/trial', { headers: member }) + expect(again.status).toBe(200) + expect(again.body.trial.grantedAt).toBe(granted.body.trial.grantedAt) + }) + + it('needs a team (O1): a personal account is offered it but cannot claim it', async () => { + const h = await createHarness() + const solo = await as(h, { sub: 'u1', email: 'neil@acme.dev' }) + const view = await h.call('GET', '/v1/billing/entitlements', { headers: solo }) + expect(view.body.reason).toBe('no_subscription') + expect(view.body.offers.trial).toEqual({ includedSeconds: 7200 }) + expect(await h.call('POST', '/v1/billing/trial', { headers: solo })).toEqual({ status: 409, body: { error: 'team_required' } }) + }) +}) + +describe('trial abuse limits', () => { + it('gives each Orca user one trial: their second team is refused', async () => { + const h = await createHarness() + expect((await h.call('POST', '/v1/billing/trial', { headers: await as(h, { sub: 'u1', org: 'o1', email: 'a@acme.dev' }) })).status).toBe(200) + const second = await as(h, { sub: 'u1', org: 'o2', orgRole: 'owner', email: 'a@acme.dev' }) + expect(await h.call('POST', '/v1/billing/trial', { headers: second })).toEqual({ status: 403, body: { error: 'trial_unavailable' } }) + const view = await h.call('GET', '/v1/billing/entitlements', { headers: second }) + expect(view.body.reason).toBe('trial_unavailable') + expect(view.body.offers.trial).toBeNull() + expect(view.body.canStartSandbox).toBe(false) + }) + + it('keys verified email after normalization (+tags, Gmail dots)', async () => { + const h = await createHarness() + await h.call('POST', '/v1/billing/trial', { headers: await as(h, { sub: 'u1', org: 'o1', email: 'neil.parker@gmail.com' }) }) + const alias = await as(h, { sub: 'u9', org: 'o9', email: 'NeilParker+cloud@googlemail.com' }) + expect((await h.call('POST', '/v1/billing/trial', { headers: alias })).body).toEqual({ error: 'trial_unavailable' }) + }) + + it('refuses unverified, missing and disposable emails', async () => { + const h = await createHarness() + for (const claims of [ + { sub: 'u1', org: 'o1', email: 'a@acme.dev', emailVerified: false }, + { sub: 'u2', org: 'o2' }, + { sub: 'u3', org: 'o3', email: 'x@mailinator.com' }, + { sub: 'u4', org: 'o4', email: 'x@inbox.yopmail.com' } + ]) { + expect((await h.call('POST', '/v1/billing/trial', { headers: await as(h, claims) })).body).toEqual({ error: 'trial_unavailable' }) + } + expect(isDisposableEmailDomain('gmail.com')).toBe(false) + expect(normalizeEmail('A.B+x@Gmail.com')).toEqual({ address: 'ab@gmail.com', domain: 'gmail.com' }) + }) + + it('keys the GitHub user from the token and the GitHub owner from the binding', async () => { + const h = await createHarness() + await h.call('POST', '/v1/billing/trial', { headers: await as(h, { sub: 'u1', org: 'o1', email: 'a@acme.dev', githubUserId: '42' }) }) + const sameGithub = await as(h, { sub: 'u2', org: 'o2', email: 'b@other.dev', githubUserId: '42' }) + expect((await h.call('POST', '/v1/billing/trial', { headers: sameGithub })).body).toEqual({ error: 'trial_unavailable' }) + + // o1 binds GitHub org 777; o3 binds the same owner before asking: no trial for o3. + expect((await h.controlPlane('/v1/internal/trial/github', { accountId: 'org:o1', githubOwnerId: '777' })).body).toEqual({ revoked: false }) + expect((await h.controlPlane('/v1/internal/trial/github', { accountId: 'org:o3', githubOwnerId: '777' })).body).toEqual({ revoked: false }) + const o3 = await as(h, { sub: 'u3', org: 'o3', email: 'c@third.dev' }) + expect((await h.call('GET', '/v1/billing/entitlements', { headers: o3 })).body.reason).toBe('trial_unavailable') + expect((await h.call('POST', '/v1/billing/trial', { headers: o3 })).status).toBe(403) + + // o4 gets a trial first, then binds the already-used owner: its trial is revoked. + const o4 = await as(h, { sub: 'u4', org: 'o4', email: 'd@fourth.dev' }) + expect((await h.call('POST', '/v1/billing/trial', { headers: o4 })).status).toBe(200) + expect((await h.controlPlane('/v1/internal/trial/github', { accountId: 'org:o4', githubOwnerId: '777' })).body).toEqual({ revoked: true }) + const revoked = await h.controlPlane('/v1/internal/entitlements/check', startCheck('org:o4')) + expect(revoked.body).toMatchObject({ allow: false, reason: 'trial_unavailable', suspendRunning: true }) + expect((await h.controlPlane('/v1/internal/trial/github', { accountId: 'org:o4', githubOwnerId: 'x' })).status).toBe(400) + }) + + it('ignores GitHub bindings on personal accounts and treats dev:org: like org:', async () => { + const h = await createHarness() + for (const accountId of ['user:u1', 'dev:user:u2']) { + expect((await h.controlPlane('/v1/internal/trial/github', { accountId, githubOwnerId: '555', githubUserId: '9' })).body).toEqual({ revoked: false }) + } + expect(h.raw.prepare('SELECT COUNT(*) AS n FROM trial_claims').get()).toEqual({ n: 0 }) + // A personal account's binding doesn't block a team that later uses the same owner. + await h.call('POST', '/v1/billing/trial', { headers: await as(h, { sub: 'u3', org: 'o3', email: 'c@acme.dev' }) }) + expect((await h.controlPlane('/v1/internal/trial/github', { accountId: 'org:o3', githubOwnerId: '555' })).body).toEqual({ revoked: false }) + // dev:org: accounts are teams: a binding records the owner, and reusing it revokes. + expect((await h.controlPlane('/v1/internal/trial/github', { accountId: 'dev:org:x', githubOwnerId: '555' })).body).toEqual({ revoked: false }) + expect(h.raw.prepare("SELECT COUNT(*) AS n FROM trial_claims WHERE account_id = 'dev:org:x'").get()).toEqual({ n: 1 }) + }) + + it('rate limits grants per IP', async () => { + const h = await createHarness() + for (let i = 0; i < TRIAL_GRANTS_PER_IP_PER_DAY; i++) { + const ok = await h.call('POST', '/v1/billing/trial', { headers: await as(h, { sub: `u${i}`, org: `o${i}`, email: `p${i}@acme.dev` }) }) + expect(ok.status).toBe(200) + } + const over = await as(h, { sub: 'ux', org: 'ox', email: 'px@acme.dev' }) + expect((await h.call('POST', '/v1/billing/trial', { headers: over })).body).toEqual({ error: 'trial_unavailable' }) + const otherIp = await as(h, { sub: 'ux', org: 'ox', email: 'px@acme.dev' }, '198.51.100.1') + expect((await h.call('POST', '/v1/billing/trial', { headers: otherIp })).status).toBe(200) + }) +}) + +describe('trial metering and limits', () => { + it('meters usage against the trial, runs 1 sandbox at a time, never overage, and ends at used up', async () => { + const h = await createHarness() + const owner = await as(h, { sub: 'u1', org: 'o1', orgRole: 'owner', email: 'a@acme.dev' }) + await h.call('POST', '/v1/billing/trial', { headers: owner }) + + expect((await h.controlPlane('/v1/internal/entitlements/check', startCheck('org:o1'))).body).toMatchObject({ allow: true, maxConcurrentSandboxes: 1 }) + // Concurrency 1: a second sandbox while one runs is refused. + expect((await h.controlPlane('/v1/internal/entitlements/check', startCheck('org:o1', 1))).body).toMatchObject({ allow: false, reason: 'concurrency_limit' }) + // Overage can't be turned on during a trial. + expect((await h.call('POST', '/v1/billing/overage', { body: { enabled: true }, headers: owner })).status).toBe(409) + + const first = await h.controlPlane('/v1/internal/usage', segment('org:o1', 'use_1', 1.5)) + expect(first.body).toMatchObject({ recorded: true, overageSeconds: 0, canStartSandbox: true, suspendRunning: false }) + // A retried report doesn't count twice. + await h.controlPlane('/v1/internal/usage', segment('org:o1', 'use_1', 1.5)) + const mid = await h.call('GET', '/v1/billing/entitlements', { headers: owner }) + expect(mid.body.trial).toMatchObject({ usedSeconds: 5400, remainingSeconds: 1800, exhausted: false }) + expect(mid.body.usageWarningPercent).toBe(75) + + const last = await h.controlPlane('/v1/internal/usage', segment('org:o1', 'use_2', 1)) + expect(last.body).toMatchObject({ overageSeconds: 0, canStartSandbox: false, reason: 'trial_used_up', suspendRunning: true }) + expect((await h.controlPlane('/v1/internal/entitlements/check', startCheck('org:o1'))).body).toMatchObject({ allow: false, reason: 'trial_used_up' }) + const usedUp = await h.call('GET', '/v1/billing/entitlements', { headers: owner }) + expect(usedUp.body).toMatchObject({ status: 'trial', reason: 'trial_used_up', remainingIncludedSeconds: 0, trial: { exhausted: true } }) + expect(usedUp.body.offers.trial).toBeNull() + expect(h.stripe.calls.some((call) => call.path.includes('meter_events'))).toBe(false) + }) + + it('ends the trial when a plan starts; unused trial hours lapse', async () => { + const h = await createHarness() + const owner = await as(h, { sub: 'u1', org: 'o1', orgRole: 'owner', email: 'a@acme.dev' }) + await h.call('POST', '/v1/billing/trial', { headers: owner }) + await h.controlPlane('/v1/internal/usage', segment('org:o1', 'use_1', 0.5)) + + expect((await h.call('POST', '/v1/billing/checkout', { body: { plan: 'team', seats: 1 }, headers: owner })).status).toBe(200) + const customer = [...h.stripe.customers.keys()][0]! + const periodStart = Math.floor(Date.now() / 1000) - 60 + const subscription = h.stripe.putSubscription({ + customer, + accountId: 'org:o1', + basePrice: 'price_team_month', + quantity: 1, + periodStart, + periodEnd: periodStart + 30 * 24 * HOUR + }) + await h.webhook(checkoutCompleted({ customer, subscription: subscription.id, accountId: 'org:o1' })) + + const plan = await h.call('GET', '/v1/billing/entitlements', { headers: owner }) + expect(plan.body).toMatchObject({ plan: 'team', status: 'active', trial: null, includedSeconds: 60 * HOUR, usedSeconds: 0 }) + expect(plan.body.limits.maxConcurrentSandboxes).toBe(3) + // No second trial later, even if the plan lapses. + expect((await h.call('POST', '/v1/billing/trial', { headers: owner })).body).toEqual({ error: 'trial_unavailable' }) + }) + + it('never offers a trial to a team that already had a plan', async () => { + const h = await createHarness() + const owner = await as(h, { sub: 'u1', org: 'o1', orgRole: 'owner', email: 'a@acme.dev' }) + await h.call('POST', '/v1/billing/checkout', { body: { plan: 'team', seats: 1 }, headers: owner }) + const customer = [...h.stripe.customers.keys()][0]! + const periodStart = Math.floor(Date.now() / 1000) - 40 * 24 * HOUR + const subscription = h.stripe.putSubscription({ + customer, + accountId: 'org:o1', + basePrice: 'price_team_month', + quantity: 1, + periodStart, + periodEnd: periodStart + 30 * 24 * HOUR, + status: 'canceled' + }) + await h.webhook(checkoutCompleted({ customer, subscription: subscription.id, accountId: 'org:o1' })) + const view = await h.call('GET', '/v1/billing/entitlements', { headers: owner }) + expect(view.body.reason).toBe('subscription_inactive') + expect(view.body.offers.trial).toBeNull() + expect((await h.call('POST', '/v1/billing/trial', { headers: owner })).status).toBe(403) + }) +}) diff --git a/mobile/src/cloud/cloud-entitlement-copy.test.ts b/mobile/src/cloud/cloud-entitlement-copy.test.ts index 199ca63e10a..6695c6931a5 100644 --- a/mobile/src/cloud/cloud-entitlement-copy.test.ts +++ b/mobile/src/cloud/cloud-entitlement-copy.test.ts @@ -185,3 +185,14 @@ describe('roleForCloudError', () => { expect(await roleForCloudError(denied('included_hours_exhausted'), broken)).toBeNull() }) }) + +describe('trial denials', () => { + it('says the trial is used up (running sandboxes sleep) or was already used, then asks for a plan', () => { + expect(entitlementDeniedMessage(denied('trial_used_up'), 'owner', 'existing', t)).toBe( + 'Your trial is used up. Running sandboxes go to sleep and new ones can’t start. Nothing is deleted, and your files are safe. Choose a plan in Orca on your computer.' + ) + expect(entitlementDeniedMessage(denied('trial_unavailable'), 'member', 'create', t)).toBe( + 'This account or team already used its trial. Nothing was created, and you weren’t charged. Ask an owner or admin to choose a plan.' + ) + }) +}) diff --git a/mobile/src/cloud/cloud-entitlement-copy.ts b/mobile/src/cloud/cloud-entitlement-copy.ts index a280fc44e18..f264b94736b 100644 --- a/mobile/src/cloud/cloud-entitlement-copy.ts +++ b/mobile/src/cloud/cloud-entitlement-copy.ts @@ -15,7 +15,16 @@ import { CloudRequestError, type CloudControlPlane } from './cloud-control-plane // happened, whether anything was lost or charged, and one next step chosen by role. Owners and // admins fix billing in Orca on their computer; members are sent to them. -type Denial = 'hours' | 'cap' | 'payment' | 'plan' | 'teamLimit' | 'memberLimit' | 'other' +type Denial = + | 'hours' + | 'cap' + | 'payment' + | 'plan' + | 'trialUsedUp' + | 'trialUnavailable' + | 'teamLimit' + | 'memberLimit' + | 'other' // The shared classifier names the category; the phone keeps its own wording per category. const DENIALS: Record = { @@ -30,6 +39,13 @@ const DENIALS: Record = { } function denialOf(reason: string | undefined): Denial { + // Both trial reasons classify as 'plan' (a plan fixes them) but say what happened to the trial. + if (reason === 'trial_used_up') { + return 'trialUsedUp' + } + if (reason === 'trial_unavailable') { + return 'trialUnavailable' + } return DENIALS[classifyEntitlementDenial(reason)] } @@ -83,6 +99,13 @@ function problem( return t('cloud.denied.payment', 'Payment failed, so new sandboxes can’t start.') case 'plan': return t('cloud.denied.plan', 'Orca Cloud needs a Team plan.') + case 'trialUsedUp': + return t( + 'cloud.denied.trialUsedUp', + 'Your trial is used up. Running sandboxes go to sleep and new ones can’t start.' + ) + case 'trialUnavailable': + return t('cloud.denied.trialUnavailable', 'This account or team already used its trial.') case 'teamLimit': return t( 'cloud.denied.teamLimit', @@ -158,6 +181,8 @@ function nextStep( 'Ask an owner or admin to update the payment method.' ) case 'plan': + case 'trialUsedUp': + case 'trialUnavailable': return manager ? t('cloud.denied.next.planAdmin', 'Choose a plan in Orca on your computer.') : t('cloud.denied.next.planMember', 'Ask an owner or admin to choose a plan.') @@ -182,7 +207,7 @@ export function entitlementDeniedMessage( problem: problem(denial, when, owner, t), safety: // Out of hours or at the cap, running sandboxes go to sleep, so say what that keeps. - denial === 'hours' || denial === 'cap' + denial === 'hours' || denial === 'cap' || denial === 'trialUsedUp' ? t('cloud.denied.safety.asleep', 'Nothing is deleted, and your files are safe.') : when === 'create' ? t('cloud.denied.safety.create', 'Nothing was created, and you weren’t charged.') diff --git a/mobile/src/i18n/locales/en.json b/mobile/src/i18n/locales/en.json index 8c4656219ca..aa558075a81 100644 --- a/mobile/src/i18n/locales/en.json +++ b/mobile/src/i18n/locales/en.json @@ -5162,7 +5162,9 @@ "asleep": "Nothing is deleted, and your files are safe." }, "hours2": "Out of sandbox hours. Running sandboxes go to sleep and new ones can’t start.", - "cap2": "Spend cap reached. Running sandboxes go to sleep and new ones can’t start." + "cap2": "Spend cap reached. Running sandboxes go to sleep and new ones can’t start.", + "trialUsedUp": "Your trial is used up. Running sandboxes go to sleep and new ones can’t start.", + "trialUnavailable": "This account or team already used its trial." }, "wake": { "slowQueued": "Taking longer than usual. Your files are safe. Your prompt sends as soon as it’s awake.", diff --git a/src/cli/cloud/cloud-api-errors.ts b/src/cli/cloud/cloud-api-errors.ts index 0c1d27e95c4..84d9a3e5719 100644 --- a/src/cli/cloud/cloud-api-errors.ts +++ b/src/cli/cloud/cloud-api-errors.ts @@ -183,6 +183,20 @@ export function cloudApiError( data(['Ask an owner or admin to raise the spend cap.']) ) } + if (reason === 'trial_used_up') { + return new RuntimeClientError( + 'cloud_trial_used_up', + `Your trial is used up. ${GO_TO_SLEEP} ${safety}`, + data(['Ask an owner or admin to choose a plan in Orca → Settings → Plan & billing.']) + ) + } + if (reason === 'trial_unavailable') { + return new RuntimeClientError( + 'cloud_plan_required', + `This account or team already used its trial. ${creating ? NOTHING_CREATED : FILES_SAFE}`, + data(['Ask an owner or admin to choose a plan in Orca → Settings → Plan & billing.']) + ) + } return new RuntimeClientError( 'cloud_plan_required', `Orca Cloud needs a Team plan. ${creating ? NOTHING_CREATED : FILES_SAFE}`, diff --git a/src/main/billing/billing-client.test.ts b/src/main/billing/billing-client.test.ts index 55496241722..ba140ee484b 100644 --- a/src/main/billing/billing-client.test.ts +++ b/src/main/billing/billing-client.test.ts @@ -3,6 +3,7 @@ import { OrcaCloudRequestError } from '../orca-profiles/profile-cloud-client' import { BillingServiceError, assertStripeHostedUrl, + claimTrial, createCheckoutUrl, createPortalUrl, fetchEntitlement, @@ -204,6 +205,61 @@ describe('billing client', () => { (await fetchEntitlement(endpoints, 'bt', response({ plan: 'pro', offers: undefined }))).plan ).toBeNull() }) + + it('reads the trial and the trial offer, and claims the trial with a POST', async () => { + const trial = { + includedSeconds: 7200, + usedSeconds: 2160, + remainingSeconds: 5040, + exhausted: false, + grantedAt: 5 + } + const body = { + plan: null, + status: 'trial', + trial, + includedSeconds: 7200, + usedSeconds: 2160, + remainingIncludedSeconds: 5040, + canStartSandbox: false, + reason: 'trial_used_up', + canManageBilling: true + } + const seen: Seen[] = [] + const entitlement = await claimTrial( + endpoints, + 'bt', + fakeFetch({ 'https://billing.example.test/v1/billing/trial': Response.json(body) }, seen) + ) + expect(seen[0]?.init?.method).toBe('POST') + expect(entitlement).toMatchObject({ status: 'trial', trial, reason: 'trial_used_up' }) + // Older services: no trial fields at all. + const older = await fetchEntitlement( + endpoints, + 'bt', + fakeFetch({ + 'https://billing.example.test/v1/billing/entitlements': Response.json({ + ...body, + trial: undefined, + reason: 'trial_unavailable' + }) + }) + ) + expect(older.trial).toBeNull() + expect(older.reason).toBe('trial_unavailable') + await expect( + claimTrial( + endpoints, + 'bt', + fakeFetch({ + 'https://billing.example.test/v1/billing/trial': Response.json( + { error: 'trial_unavailable' }, + { status: 403 } + ) + }) + ) + ).rejects.toMatchObject({ statusCode: 403, errorCode: 'trial_unavailable' }) + }) }) describe('fetchTeamPlans', () => { diff --git a/src/main/billing/billing-client.ts b/src/main/billing/billing-client.ts index c6d1d46544d..31cf315a419 100644 --- a/src/main/billing/billing-client.ts +++ b/src/main/billing/billing-client.ts @@ -120,7 +120,14 @@ const OffersSchema = z priceLabel: z.string().max(40), // Opened in the browser: https only. contactUrl: z.string().url().startsWith('https://') - }) + }), + // Absent from older services: no trial on offer. + trial: z + .object({ includedSeconds: z.number().nonnegative() }) + .nullable() + .optional() + .catch(null) + .transform((value) => value ?? null) }) .nullable() .catch(null) @@ -140,6 +147,18 @@ const EntitlementSchema = z.object({ period: window, usageWindow: window, cancelAtPeriodEnd: z.boolean().catch(false), + trial: z + .object({ + includedSeconds: z.number().nonnegative(), + usedSeconds: z.number().nonnegative(), + remainingSeconds: z.number().nonnegative(), + exhausted: z.boolean(), + grantedAt: z.number() + }) + .nullable() + .optional() + .catch(null) + .transform((value) => value ?? null), includedSeconds: seconds, usedSeconds: seconds, remainingIncludedSeconds: seconds, @@ -169,7 +188,9 @@ const EntitlementSchema = z.object({ 'payment_past_due', 'payment_grace_expired', 'included_hours_exhausted', - 'overage_cap_reached' + 'overage_cap_reached', + 'trial_used_up', + 'trial_unavailable' ]) .nullable() .catch(null), @@ -289,3 +310,14 @@ export async function fetchTeamPlans( } return body.data.teams } + +/** POST /v1/billing/trial: starts the team's one-time trial (idempotent) and returns the entitlement. */ +export async function claimTrial( + endpoints: BillingEndpoints, + token: string, + fetchImpl: typeof fetch = fetch +): Promise { + return normalizeEntitlement( + await billingRequest(endpoints, token, 'POST', 'v1/billing/trial', {}, fetchImpl) + ) +} diff --git a/src/main/billing/billing-service.ts b/src/main/billing/billing-service.ts index 2a3770c75ff..89d92d3fa96 100644 --- a/src/main/billing/billing-service.ts +++ b/src/main/billing/billing-service.ts @@ -10,13 +10,15 @@ import type { OrcaBillingOverageArgs, OrcaBillingOverageResult, OrcaBillingStatusResult, - OrcaBillingTeamPlansResult + OrcaBillingTeamPlansResult, + OrcaBillingTrialClaimResult } from '../../shared/orca-billing' import { getOrcaCloudAuthConfig } from '../orca-profiles/profile-cloud-auth-config' import { runWithFreshOrcaCloudSession } from '../orca-profiles/profile-cloud-session-refresh' import { ensureActiveOrcaProfile } from '../orca-profiles/profile-index-store' import { BillingServiceError, + claimTrial, createCheckoutUrl, createPortalUrl, fetchEntitlement, @@ -253,3 +255,27 @@ export async function setOrcaBillingOverage( return { status: 'failed', error: message(error) } } } + +/** Starts the team's one-time trial (the first time someone on it picks Orca Cloud). Idempotent. */ +export async function claimOrcaBillingTrial( + userDataPath: string +): Promise { + const ready = prepare(userDataPath) + if (!ready.ok) { + return { status: ready.status } + } + try { + const entitlement = await ready.run((token, endpoints) => claimTrial(endpoints, token)) + return entitlement === 'signed-out' ? { status: 'signed-out' } : { status: 'ok', entitlement } + } catch (error) { + if (error instanceof BillingServiceError) { + if (error.errorCode === 'trial_unavailable') { + return { status: 'unavailable' } + } + if (error.errorCode === 'team_required') { + return { status: 'team-required' } + } + } + return { status: 'failed', error: message(error) } + } +} diff --git a/src/main/ipc/profiles/orca-profile-billing-handlers.ts b/src/main/ipc/profiles/orca-profile-billing-handlers.ts index 0a525ef4626..293ef6fd170 100644 --- a/src/main/ipc/profiles/orca-profile-billing-handlers.ts +++ b/src/main/ipc/profiles/orca-profile-billing-handlers.ts @@ -6,7 +6,8 @@ import type { OrcaBillingOverageArgs, OrcaBillingOverageResult, OrcaBillingStatusResult, - OrcaBillingTeamPlansResult + OrcaBillingTeamPlansResult, + OrcaBillingTrialClaimResult } from '../../../shared/orca-billing' import { ORCA_BILLING_INTERVALS, @@ -15,6 +16,7 @@ import { ORCA_BILLING_TEAM_PLANS_MAX_ORGS } from '../../../shared/orca-billing' import { + claimOrcaBillingTrial, getOrcaBillingStatus, getOrcaBillingTeamPlans, openOrcaBillingCheckout, @@ -177,6 +179,9 @@ export function registerOrcaProfileBillingHandlers(store: Store): void { : { status: 'not-found' } } ) + ipcMain.handle('orcaProfiles:billingClaimTrial', async (): Promise => + claimOrcaBillingTrial(getProfileUserDataPath()) + ) ipcMain.handle('orcaProfiles:billingOpenPortal', async (): Promise => openOrcaBillingPortal(getProfileUserDataPath()) ) diff --git a/src/preload/api/orca-profile-api.ts b/src/preload/api/orca-profile-api.ts index 13153e061ca..9517b373680 100644 --- a/src/preload/api/orca-profile-api.ts +++ b/src/preload/api/orca-profile-api.ts @@ -41,6 +41,7 @@ import type { OrcaBillingOpenResult, OrcaBillingOverageArgs, OrcaBillingOverageResult, + OrcaBillingTrialClaimResult, OrcaBillingReturn, OrcaBillingStatusResult, OrcaBillingTeamPlansResult @@ -113,4 +114,6 @@ export type OrcaProfileApi = { billingTeamPlans: (args: { orgIds: string[] }) => Promise /** Opt in/out of sandbox overage and set the monthly spend cap (org admins). */ billingSetOverage: (args: OrcaBillingOverageArgs) => Promise + /** Starts the team's one-time Orca Cloud trial (idempotent; no card). */ + billingClaimTrial: () => Promise } diff --git a/src/preload/api/orca-profiles-bridge.ts b/src/preload/api/orca-profiles-bridge.ts index 797cd845f8d..ddedd82f219 100644 --- a/src/preload/api/orca-profiles-bridge.ts +++ b/src/preload/api/orca-profiles-bridge.ts @@ -90,5 +90,6 @@ export const orcaProfilesApi = { cloudSetupStart: (args) => ipcRenderer.invoke('orcaProfiles:cloudSetupStart', args), cloudSetupGet: (args) => ipcRenderer.invoke('orcaProfiles:cloudSetupGet', args), cloudSetupLink: (args) => ipcRenderer.invoke('orcaProfiles:cloudSetupLink', args), - billingSetOverage: (args) => ipcRenderer.invoke('orcaProfiles:billingSetOverage', args) + billingSetOverage: (args) => ipcRenderer.invoke('orcaProfiles:billingSetOverage', args), + billingClaimTrial: () => ipcRenderer.invoke('orcaProfiles:billingClaimTrial') } satisfies PreloadApi['orcaProfiles'] diff --git a/src/renderer/src/components/billing/AccountMenuTrialRow.fixture.tsx b/src/renderer/src/components/billing/AccountMenuTrialRow.fixture.tsx new file mode 100644 index 00000000000..6f09eb75e6a --- /dev/null +++ b/src/renderer/src/components/billing/AccountMenuTrialRow.fixture.tsx @@ -0,0 +1,60 @@ +import { Settings, Users } from 'lucide-react' +import { defineFixture } from '../../component-fixtures/component-fixture' +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuTrigger +} from '@/components/ui/dropdown-menu' +import type { OrcaBillingEntitlement } from '../../../../shared/orca-billing' +import { AccountMenuTrialRow } from './AccountMenuTrialRow' +import { sampleTrial, sampleTrialUsedUp } from './plan-billing-fixtures' + +function Menu({ entitlement }: { entitlement: OrcaBillingEntitlement }): React.JSX.Element { + return ( +
+ + NP + + + + N + + + Neil Parker + neil@acme.dev + + + + + + + Team + + + + Settings + + + +
+ ) +} + +/** Owner or admin: the row opens the plans page. */ +export const trialOwner = defineFixture({ + width: 320, + render: () => +}) + +/** Member: the same line, nothing to pick. */ +export const trialMember = defineFixture({ + width: 320, + render: () => +}) + +export const trialUsedUpOwner = defineFixture({ + width: 320, + render: () => +}) diff --git a/src/renderer/src/components/billing/AccountMenuTrialRow.tsx b/src/renderer/src/components/billing/AccountMenuTrialRow.tsx new file mode 100644 index 00000000000..cfa4d7c4120 --- /dev/null +++ b/src/renderer/src/components/billing/AccountMenuTrialRow.tsx @@ -0,0 +1,63 @@ +// Account menu row while the team is on its one-time trial (spec T1): "Trial · 1.4 sandbox hours +// left", visible to every member; owners and admins can pick it to choose a plan. It disappears +// once a plan starts, because the entitlement no longer carries a trial. +import { Cloud } from 'lucide-react' +import { + DropdownMenuItem, + DropdownMenuLabel, + DropdownMenuSeparator +} from '@/components/ui/dropdown-menu' +import { useTranslate } from '@/i18n/use-translate' +import { cn } from '@/lib/utils' +import type { OrcaBillingStatusResult } from '../../../../shared/orca-billing' +import { accountMenuTrialRow } from './plan-billing-usage-copy' +import { openPlansPage } from './plans/plans-page-store' + +export function AccountMenuTrialRow({ + result +}: { + result: OrcaBillingStatusResult | null +}): React.JSX.Element | null { + const t = useTranslate() + const row = accountMenuTrialRow(result, t) + if (!row) { + return null + } + const label = ( + + {row.label} + + ) + return ( + <> + {row.canChoosePlan ? ( + openPlansPage('account-menu')} + aria-label={t('auto.components.billing.trialRowChoosePlan', '{{trial}}. Choose plan', { + trial: row.label + })} + > + + {/* Two lines in the 240px menu: the hours never truncate (spec T1). */} + + {label} + + {t('auto.components.billing.choosePlan', 'Choose plan')} + + + + ) : ( + + + + {label} + + + )} + + + ) +} diff --git a/src/renderer/src/components/billing/PlanBillingSection.fixture.tsx b/src/renderer/src/components/billing/PlanBillingSection.fixture.tsx index bfb259da91a..0f0ae96e997 100644 --- a/src/renderer/src/components/billing/PlanBillingSection.fixture.tsx +++ b/src/renderer/src/components/billing/PlanBillingSection.fixture.tsx @@ -1,6 +1,6 @@ import { defineFixture } from '../../component-fixtures/component-fixture' import { PlanBillingView } from './PlanBillingSection' -import { sampleTeam } from './plan-billing-fixtures' +import { sampleTeam, sampleTrial, sampleTrialUsedUp } from './plan-billing-fixtures' const HOUR = 3600 @@ -283,3 +283,61 @@ export const capTooHigh = defineFixture({ await new Promise((resolve) => setTimeout(resolve, 100)) } }) + +/** Spec T1: the team's one-time trial, owner view (Choose plan). */ +export const trial = defineFixture({ + width: 600, + render: () => ( + + ) +}) + +export const trialMember = defineFixture({ + width: 600, + render: () => ( + + ) +}) + +export const trialUsedUp = defineFixture({ + width: 600, + render: () => ( + + ) +}) + +export const trialUsedUpMember = defineFixture({ + width: 600, + render: () => ( + + ) +}) + +/** No plan and no trial on offer (this account or team already used one). */ +export const trialUnavailable = defineFixture({ + width: 600, + render: () => ( + + ) +}) diff --git a/src/renderer/src/components/billing/PlanBillingSection.tsx b/src/renderer/src/components/billing/PlanBillingSection.tsx index 9fb00b46582..0f8c0a4363c 100644 --- a/src/renderer/src/components/billing/PlanBillingSection.tsx +++ b/src/renderer/src/components/billing/PlanBillingSection.tsx @@ -7,17 +7,19 @@ import { Skeleton } from '@/components/ui/skeleton' import { useIntlLocale, useTranslate } from '@/i18n/use-translate' import { formatCents } from './plans/plans-pricing' import { cn } from '@/lib/utils' -import type { - OrcaBillingOpenResult, - OrcaBillingOverageArgs, - OrcaBillingOverageResult, - OrcaBillingStatusResult +import { + isOrcaCloudTrial, + type OrcaBillingOpenResult, + type OrcaBillingOverageArgs, + type OrcaBillingOverageResult, + type OrcaBillingStatusResult } from '../../../../shared/orca-billing' import { openPlansPage } from './plans/plans-page-store' import { PaymentIssueNotice } from './PaymentIssueNotice' import { OverageControls, UsageSummary } from './PlanBillingUsage' import { denyReasonCopy, openFailureCopy, overageFailureCopy } from './plan-billing-copy' import { PlanStatusBadge } from './PlanStatusBadge' +import { TrialPlanSummary } from './TrialPlanSummary' import { useOrcaBillingStatus } from './use-orca-billing-status' import { useAppStore } from '@/store/index' import { usageAlertLevel } from '../../../../shared/orca-billing-usage-alerts' @@ -175,6 +177,9 @@ export function PlanBillingView({ const entitlement = result.entitlement const hasPlan = entitlement.plan !== null && entitlement.status !== 'canceled' + // The one-time trial stands in for a plan until one starts (spec T1). + const onTrial = !hasPlan && isOrcaCloudTrial(entitlement) + const trialUsedUp = onTrial && entitlement.trial?.exhausted === true const monthlyCents = entitlement.offers?.team.monthlyPriceCentsPerSeat ?? null const teamPrice = monthlyCents === null ? null : formatCents(monthlyCents, locale) @@ -213,9 +218,11 @@ export function PlanBillingView({ ) : null} + {onTrial ? : null} + {/* Admins already read these above: the overage card's cap-reached hint, and the usage alert's out-of-hours sentence. */} - {hasPlan && + {(hasPlan || entitlement.reason === 'trial_unavailable') && entitlement.reason && entitlement.payment.pastDueSince === null && !( @@ -229,7 +236,7 @@ export function PlanBillingView({

) : null} - {!hasPlan ? ( + {!hasPlan && !onTrial ? (

{teamPrice ? t( @@ -245,7 +252,7 @@ export function PlanBillingView({ ) : null}

- {hasPlan ? null : ( + {hasPlan || onTrial ? null : ( @@ -270,7 +277,9 @@ export function PlanBillingView({
{/* The payment alert already says who to ask; don't ask twice. */} - {!entitlement.canManageBilling && entitlement.payment.pastDueSince === null ? ( + {!entitlement.canManageBilling && + entitlement.payment.pastDueSince === null && + !trialUsedUp ? (

{t('auto.components.billing.askAdmin2', 'Ask an owner or admin to change the plan.')}

diff --git a/src/renderer/src/components/billing/PlanStatusBadge.tsx b/src/renderer/src/components/billing/PlanStatusBadge.tsx index 1e4ef4ff3ca..0ecb5be6ff0 100644 --- a/src/renderer/src/components/billing/PlanStatusBadge.tsx +++ b/src/renderer/src/components/billing/PlanStatusBadge.tsx @@ -32,6 +32,10 @@ export function planHealth(entitlement: OrcaBillingEntitlement, t: Translate): P dot: 'warning' } } + if (entitlement.reason === 'trial_used_up') { + // Still the trial; the dot says it's used up and the line below says what to do. + return { label: t('auto.components.billing.statusTrial', 'Trial'), dot: 'warning' } + } if (entitlement.cancelAtPeriodEnd) { return { label: t('auto.components.billing.health.ending', 'Ending'), dot: 'warning' } } diff --git a/src/renderer/src/components/billing/TrialPlanSummary.tsx b/src/renderer/src/components/billing/TrialPlanSummary.tsx new file mode 100644 index 00000000000..c70346e1ed0 --- /dev/null +++ b/src/renderer/src/components/billing/TrialPlanSummary.tsx @@ -0,0 +1,67 @@ +// The team's one-time trial (spec T1) in Plan & billing and on the plans page: a "Trial" badge, +// the hours bar, and the one-time-allowance line. Never "Hours reset every month" here. +import { Cloud } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { Progress } from '@/components/ui/progress' +import { useTranslate } from '@/i18n/use-translate' +import type { OrcaBillingEntitlement } from '../../../../shared/orca-billing' +import { includedUsagePercent } from './plan-billing-format' +import { denyReasonCopy } from './plan-billing-copy' +import { + includedUsageTone, + sandboxHoursLeftLine, + trialHoursUsedLine +} from './plan-billing-usage-copy' +import { PlanStatusBadge } from './PlanStatusBadge' + +export function TrialPlanSummary({ + entitlement, + onChoosePlan +}: { + entitlement: OrcaBillingEntitlement + /** Shown to owners and admins; omitted where the plan cards are already on screen. */ + onChoosePlan?: () => void +}): React.JSX.Element { + const t = useTranslate() + const usedUp = entitlement.trial?.exhausted === true + return ( +
+
+ +

+ {t('auto.components.billing.trialProduct', 'Orca Cloud')} +

+ +
+
+ +
+ {trialHoursUsedLine(entitlement, t)} + {sandboxHoursLeftLine(entitlement, t)} +
+
+

+ {usedUp + ? denyReasonCopy('trial_used_up', t, entitlement.canManageBilling) + : t( + 'auto.components.billing.trialOneTime', + 'Trial hours are a one-time allowance and don’t reset. When they’re used up, choose a plan to keep going. No card needed until then.' + )} +

+ {onChoosePlan && entitlement.canManageBilling ? ( + + ) : null} +
+ ) +} diff --git a/src/renderer/src/components/billing/claim-trial.ts b/src/renderer/src/components/billing/claim-trial.ts new file mode 100644 index 00000000000..71bc4f2b6c7 --- /dev/null +++ b/src/renderer/src/components/billing/claim-trial.ts @@ -0,0 +1,19 @@ +// Starts the team's one-time Orca Cloud trial (spec N11/B1): the first time anyone on a team that +// never had a plan or a trial picks Orca Cloud. Billing grants it at most once per team, user, +// email and GitHub identity; the answer lands in the shared billing cache so every surface agrees. +import type { OrcaBillingTrialClaimResult } from '../../../../shared/orca-billing' +import { getBillingGeneration, recordBillingStatusIfCurrent } from './billing-summary-store' + +export async function claimOrcaCloudTrial(): Promise { + const generation = getBillingGeneration() + const result = await window.api.orcaProfiles + .billingClaimTrial() + .catch((error: unknown): OrcaBillingTrialClaimResult => ({ + status: 'failed', + error: error instanceof Error ? error.message : String(error) + })) + if (result.status === 'ok') { + recordBillingStatusIfCurrent(generation, { status: 'ok', entitlement: result.entitlement }) + } + return result +} diff --git a/src/renderer/src/components/billing/plan-billing-copy.ts b/src/renderer/src/components/billing/plan-billing-copy.ts index 8dc87f0e4f5..d72d947c013 100644 --- a/src/renderer/src/components/billing/plan-billing-copy.ts +++ b/src/renderer/src/components/billing/plan-billing-copy.ts @@ -65,6 +65,26 @@ export function denyReasonCopy( 'auto.components.billing.reasonCapMember4', 'Spend cap reached. Running sandboxes go to sleep and new ones can’t start. Nothing is deleted, and your files are safe. Ask an owner or admin to raise the spend cap.' ) + case 'trial_used_up': + return canManage + ? t( + 'auto.components.billing.reasonTrialUsedUp2', + 'Your trial is used up. Running sandboxes go to sleep and new ones can’t start. Nothing is deleted, and your files are safe. Choose a plan to keep using Orca Cloud.' + ) + : t( + 'auto.components.billing.reasonTrialUsedUpMember2', + 'Your team’s trial is used up. Running sandboxes go to sleep and new ones can’t start. Nothing is deleted, and your files are safe. Ask an owner or admin to choose a plan.' + ) + case 'trial_unavailable': + return canManage + ? t( + 'auto.components.billing.reasonTrialUnavailable', + 'This account or team already used its trial. Choose a plan to use Orca Cloud.' + ) + : t( + 'auto.components.billing.reasonTrialUnavailableMember', + 'This account or team already used its trial. Ask an owner or admin to choose a plan.' + ) } } @@ -73,6 +93,7 @@ export function statusLabel(status: string, t: Translate): string { case 'active': return t('auto.components.billing.statusActive', 'Active') case 'trialing': + case 'trial': return t('auto.components.billing.statusTrial', 'Trial') case 'past_due': return t('auto.components.billing.paymentFailed', 'Payment failed') diff --git a/src/renderer/src/components/billing/plan-billing-fixtures.ts b/src/renderer/src/components/billing/plan-billing-fixtures.ts index 696ede6ee78..ade923245df 100644 --- a/src/renderer/src/components/billing/plan-billing-fixtures.ts +++ b/src/renderer/src/components/billing/plan-billing-fixtures.ts @@ -48,3 +48,43 @@ export const sampleTeam: OrcaBillingEntitlement = { canManageBilling: true, offers: sampleOffers } + +/** A team on its one-time trial: 2 sandbox hours, 0.6 used, no plan, no card. */ +export const sampleTrial: OrcaBillingEntitlement = { + ...sampleTeam, + plan: null, + planLabel: null, + status: 'trial', + interval: null, + seats: 0, + period: null, + usageWindow: null, + trial: { + includedSeconds: 2 * HOUR, + usedSeconds: 0.6 * HOUR, + remainingSeconds: 1.4 * HOUR, + exhausted: false, + grantedAt: Date.UTC(2026, 10, 10) + }, + includedSeconds: 2 * HOUR, + usedSeconds: 0.6 * HOUR, + remainingIncludedSeconds: 1.4 * HOUR, + offers: { ...sampleOffers, trial: null } +} + +/** The same team once its trial hours are used up. */ +export const sampleTrialUsedUp: OrcaBillingEntitlement = { + ...sampleTrial, + trial: { + includedSeconds: 2 * HOUR, + usedSeconds: 2 * HOUR, + remainingSeconds: 0, + exhausted: true, + grantedAt: Date.UTC(2026, 10, 10) + }, + usedSeconds: 2 * HOUR, + remainingIncludedSeconds: 0, + usageWarningPercent: 100, + canStartSandbox: false, + reason: 'trial_used_up' +} diff --git a/src/renderer/src/components/billing/plan-billing-usage-copy.test.ts b/src/renderer/src/components/billing/plan-billing-usage-copy.test.ts index 47749e67ede..b3201d77bca 100644 --- a/src/renderer/src/components/billing/plan-billing-usage-copy.test.ts +++ b/src/renderer/src/components/billing/plan-billing-usage-copy.test.ts @@ -1,9 +1,14 @@ import { describe, expect, it } from 'vitest' import { translate } from '@/i18n/i18n' import type { OrcaBillingEntitlement } from '../../../../shared/orca-billing' -import { sampleTeam } from './plan-billing-fixtures' +import { sampleTeam, sampleTrial, sampleTrialUsedUp } from './plan-billing-fixtures' +import { denyReasonCopy, statusLabel } from './plan-billing-copy' +import { planHealth } from './PlanStatusBadge' import { + accountMenuTrialRow, accountMenuUsageLines, + trialHoursLeftHint, + trialHoursUsedLine, includedUsageTone, sandboxHoursCount, sandboxHoursLeftLine, @@ -132,3 +137,54 @@ describe('sandbox hours copy', () => { expect(accountMenuUsageLines({ status: 'failed', error: 'offline' }, t, 'en')).toBeNull() }) }) + +describe('trial copy (spec T1, glossary "Trial")', () => { + it('counts the one-time trial hours without "this month"', () => { + expect(trialHoursUsedLine(sampleTrial, t)).toBe('0.6 of 2 sandbox hours used') + expect(trialHoursLeftHint(sampleTrial, t)).toBe('Trial · 1.4 sandbox hours left') + expect(trialHoursLeftHint({ ...sampleTrial, remainingIncludedSeconds: HOUR }, t)).toBe( + 'Trial · 1 sandbox hour left' + ) + }) + + it('shows the account menu row to every member, Choose plan to owners and admins only', () => { + expect(accountMenuTrialRow({ status: 'ok', entitlement: sampleTrial }, t)).toEqual({ + label: 'Trial · 1.4 sandbox hours left', + usedUp: false, + canChoosePlan: true + }) + expect( + accountMenuTrialRow( + { status: 'ok', entitlement: { ...sampleTrial, canManageBilling: false } }, + t + ) + ).toMatchObject({ canChoosePlan: false }) + expect(accountMenuTrialRow({ status: 'ok', entitlement: sampleTrialUsedUp }, t)).toMatchObject({ + label: 'Your trial is used up', + usedUp: true + }) + // Gone once a plan starts, and never for a team without a trial. + expect(accountMenuTrialRow({ status: 'ok', entitlement: sampleTeam }, t)).toBeNull() + expect(accountMenuTrialRow({ status: 'failed', error: 'x' }, t)).toBeNull() + // The plan's hours line stays off during a trial. + expect(accountMenuUsageLines({ status: 'ok', entitlement: sampleTrial }, t, 'en-US')).toBeNull() + }) + + it('labels the trial "Trial" and says what to do when it is used up or unavailable', () => { + expect(statusLabel('trial', t)).toBe('Trial') + expect(planHealth(sampleTrial, t)).toEqual({ label: 'Trial', dot: null }) + expect(planHealth(sampleTrialUsedUp, t)).toEqual({ label: 'Trial', dot: 'warning' }) + expect(denyReasonCopy('trial_used_up', t, true)).toBe( + 'Your trial is used up. Running sandboxes go to sleep and new ones can’t start. Nothing is deleted, and your files are safe. Choose a plan to keep using Orca Cloud.' + ) + expect(denyReasonCopy('trial_used_up', t, false)).toBe( + 'Your team’s trial is used up. Running sandboxes go to sleep and new ones can’t start. Nothing is deleted, and your files are safe. Ask an owner or admin to choose a plan.' + ) + expect(denyReasonCopy('trial_unavailable', t, true)).toBe( + 'This account or team already used its trial. Choose a plan to use Orca Cloud.' + ) + expect(denyReasonCopy('trial_unavailable', t, false)).toBe( + 'This account or team already used its trial. Ask an owner or admin to choose a plan.' + ) + }) +}) diff --git a/src/renderer/src/components/billing/plan-billing-usage-copy.ts b/src/renderer/src/components/billing/plan-billing-usage-copy.ts index c19c5b7ee7f..54b3ca26c95 100644 --- a/src/renderer/src/components/billing/plan-billing-usage-copy.ts +++ b/src/renderer/src/components/billing/plan-billing-usage-copy.ts @@ -1,9 +1,10 @@ // Sandbox-hours lines shared by Plan & billing, the plans page and the account menu, so every // surface counts, pluralizes and warns the same way. import type { Translate } from '@/i18n/use-translate' -import type { - OrcaBillingEntitlement, - OrcaBillingStatusResult +import { + isOrcaCloudTrial, + type OrcaBillingEntitlement, + type OrcaBillingStatusResult } from '../../../../shared/orca-billing' import { usageAlertSentence } from '../../../../shared/orca-billing-usage-alerts' import { includedUsagePercent } from './plan-billing-format' @@ -82,3 +83,42 @@ export function accountMenuUsageLines( warning: usageWarningLine(result.entitlement, t, locale) } } + +/** "0.6 of 2 sandbox hours used": the trial's hours never reset, so no "this month". */ +export function trialHoursUsedLine(entitlement: OrcaBillingEntitlement, t: Translate): string { + return t('auto.components.billing.trialHoursUsed', '{{used}} of {{count}} sandbox hours used', { + used: String(sandboxHoursCount(Math.min(entitlement.usedSeconds, entitlement.includedSeconds))), + count: sandboxHoursCount(entitlement.includedSeconds), + defaultValue_one: '{{used}} of {{count}} sandbox hour used' + }) +} + +/** "Trial · 1.4 sandbox hours left" (glossary hint), for the account menu and the composer. */ +export function trialHoursLeftHint(entitlement: OrcaBillingEntitlement, t: Translate): string { + return t('auto.components.billing.trialHoursLeft', 'Trial · {{count}} sandbox hours left', { + count: sandboxHoursCount(entitlement.remainingIncludedSeconds), + defaultValue_one: 'Trial · {{count}} sandbox hour left' + }) +} + +/** + * The account menu's trial row (spec T1): every member sees it while the team is on its trial; + * owners and admins also get Choose plan. Gone once a plan starts (the entitlement has no trial). + */ +export function accountMenuTrialRow( + result: OrcaBillingStatusResult | null, + t: Translate +): { label: string; usedUp: boolean; canChoosePlan: boolean } | null { + if (result?.status !== 'ok' || !isOrcaCloudTrial(result.entitlement)) { + return null + } + const entitlement = result.entitlement + const usedUp = entitlement.trial?.exhausted === true + return { + label: usedUp + ? t('auto.components.billing.trialUsedUpTitle', 'Your trial is used up') + : trialHoursLeftHint(entitlement, t), + usedUp, + canChoosePlan: entitlement.canManageBilling + } +} diff --git a/src/renderer/src/components/billing/plans/PlansView.fixture.tsx b/src/renderer/src/components/billing/plans/PlansView.fixture.tsx index c496a5b2947..d6b234599d4 100644 --- a/src/renderer/src/components/billing/plans/PlansView.fixture.tsx +++ b/src/renderer/src/components/billing/plans/PlansView.fixture.tsx @@ -1,6 +1,6 @@ import { defineFixture } from '../../../component-fixtures/component-fixture' import type { OrcaBillingEntitlement } from '../../../../../shared/orca-billing' -import { sampleTeam } from '../plan-billing-fixtures' +import { sampleTeam, sampleTrial, sampleTrialUsedUp } from '../plan-billing-fixtures' import { Dialog } from '@/components/ui/dialog' import { PlansDialogContent } from './PlansDialogContent' import type { PlansViewProps } from './PlansView' @@ -125,3 +125,14 @@ export const currentPlanUsageWarning = defineFixture({ /> ) }) + +/** Spec T1: the plans page during the trial; the strip replaces the value props. */ +export const trialStrip = defineFixture({ + width, + render: () => +}) + +export const trialUsedUpStrip = defineFixture({ + width, + render: () => +}) diff --git a/src/renderer/src/components/billing/plans/PlansView.tsx b/src/renderer/src/components/billing/plans/PlansView.tsx index 13b5b709022..4a013f4efc8 100644 --- a/src/renderer/src/components/billing/plans/PlansView.tsx +++ b/src/renderer/src/components/billing/plans/PlansView.tsx @@ -5,6 +5,7 @@ import { Skeleton } from '@/components/ui/skeleton' import { Progress } from '@/components/ui/progress' import { useIntlLocale, useTranslate } from '@/i18n/use-translate' import { + isOrcaCloudTrial, ORCA_BILLING_MAX_SEATS, type OrcaBillingEntitlement, type OrcaBillingInterval, @@ -21,6 +22,7 @@ import { sandboxHoursLeftLine, usageWarningLine } from '../plan-billing-usage-copy' +import { TrialPlanSummary } from '../TrialPlanSummary' import { EnterprisePlanCard } from './EnterprisePlanCard' import { PlansIntervalToggle } from './PlansIntervalToggle' import { TeamPlanCard, type TeamPlanCardMode } from './TeamPlanCard' @@ -285,6 +287,11 @@ export function PlansView(props: PlansViewProps): React.JSX.Element { /> + ) : isOrcaCloudTrial(entitlement) ? ( + // The trial's strip: the plan cards right below are the way out of it (spec T1). +
+ +
) : ( )} diff --git a/src/renderer/src/components/sidebar/account-menu/SidebarAccountMenu.tsx b/src/renderer/src/components/sidebar/account-menu/SidebarAccountMenu.tsx index b7e1597a75f..0be718f3e6f 100644 --- a/src/renderer/src/components/sidebar/account-menu/SidebarAccountMenu.tsx +++ b/src/renderer/src/components/sidebar/account-menu/SidebarAccountMenu.tsx @@ -18,6 +18,7 @@ import { useIntlLocale, useTranslate } from '@/i18n/use-translate' import { cn } from '@/lib/utils' import { useBillingState } from '../../billing/billing-summary-store' import { accountMenuUsageLines } from '../../billing/plan-billing-usage-copy' +import { AccountMenuTrialRow } from '../../billing/AccountMenuTrialRow' import { SidebarTeamSubmenu } from './SidebarTeamSubmenu' import { useSetupGuideProgress } from '../../setup-guide/use-setup-guide-progress' import { getAccountMenuIdentity, type AccountMenuIdentity } from './account-menu-identity' @@ -71,7 +72,8 @@ export function SidebarAccountMenu(): React.JSX.Element { const identity = getAccountMenuIdentity(authStatus) // The team is named once, on the switcher below; the header carries the plan's hours instead. - const usage = accountMenuUsageLines(useBillingState().result, t, locale) + const billingResult = useBillingState().result + const usage = accountMenuUsageLines(billingResult, t, locale) const visibleItems = selectVisibleAccountMenuItems(registeredItems, authStatus) // Freeze the item list while the menu is open: a billing answer arriving mid-read must not // swap rows under the pointer (e.g. Upgrade replacing Plan & billing). @@ -211,6 +213,7 @@ export function SidebarAccountMenu(): React.JSX.Element { + {identity.signedIn ? : null} ) : null} diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index 022b4961979..5ea645e29d3 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -247,7 +247,11 @@ }, "teamUsedAllOverageOff": "Your team has used all of this month’s sandbox hours. Running sandboxes go to sleep and new ones can’t start. Turn on overage to keep going.", "teamUsedAllOverageOn": "Your team has used all of this month’s sandbox hours. Overage is on, up to your {{cap}} spend cap.", - "teamUsedPercent": "Your team has used {{percent}}% of this month’s sandbox hours." + "teamUsedPercent": "Your team has used {{percent}}% of this month’s sandbox hours.", + "trialHoursLeft_one": "Trial · {{count}} sandbox hour left", + "trialHoursLeft_other": "Trial · {{count}} sandbox hours left", + "trialHoursUsed_one": "{{used}} of {{count}} sandbox hour used", + "trialHoursUsed_other": "{{used}} of {{count}} sandbox hours used" }, "browser-pane": { "markup": { diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 4bbdb126632..fb9af10ad44 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -20738,7 +20738,21 @@ "teamUsedAllOverageOff": "Your team has used all of this month’s sandbox hours. Running sandboxes go to sleep and new ones can’t start. Turn on overage to keep going.", "teamUsedAllOverageOn": "Your team has used all of this month’s sandbox hours. Overage is on, up to your {{cap}} spend cap.", "teamUsedPercent": "Your team has used {{percent}}% of this month’s sandbox hours.", - "usageAlertsNote": "Owners and admins are alerted in Orca at 75%, 90% and 100% of your team’s sandbox hours." + "usageAlertsNote": "Owners and admins are alerted in Orca at 75%, 90% and 100% of your team’s sandbox hours.", + "choosePlan": "Choose plan", + "reasonTrialUnavailable": "This account or team already used its trial. Choose a plan to use Orca Cloud.", + "reasonTrialUnavailableMember": "This account or team already used its trial. Ask an owner or admin to choose a plan.", + "reasonTrialUsedUp2": "Your trial is used up. Running sandboxes go to sleep and new ones can’t start. Nothing is deleted, and your files are safe. Choose a plan to keep using Orca Cloud.", + "reasonTrialUsedUpMember2": "Your team’s trial is used up. Running sandboxes go to sleep and new ones can’t start. Nothing is deleted, and your files are safe. Ask an owner or admin to choose a plan.", + "trialHoursLeft_one": "Trial · {{count}} sandbox hour left", + "trialHoursLeft_other": "Trial · {{count}} sandbox hours left", + "trialHoursUsed_one": "{{used}} of {{count}} sandbox hour used", + "trialHoursUsed_other": "{{used}} of {{count}} sandbox hours used", + "trialHoursUsedLabel": "Trial sandbox hours used", + "trialOneTime": "Trial hours are a one-time allowance and don’t reset. When they’re used up, choose a plan to keep going. No card needed until then.", + "trialProduct": "Orca Cloud", + "trialRowChoosePlan": "{{trial}}. Choose plan", + "trialUsedUpTitle": "Your trial is used up" }, "ports": { "RuntimePortAutoForwarder": { diff --git a/src/renderer/src/web/preload-api/web-orca-profiles-api.ts b/src/renderer/src/web/preload-api/web-orca-profiles-api.ts index 94e8cb2fe87..33e3bdf3c72 100644 --- a/src/renderer/src/web/preload-api/web-orca-profiles-api.ts +++ b/src/renderer/src/web/preload-api/web-orca-profiles-api.ts @@ -82,7 +82,8 @@ export function createWebOrcaProfilesApi(): Partial { cloudSetupLink: async () => ({ status: 'unconfigured' }), billingOpenPortal: async () => ({ status: 'unconfigured' }), billingTeamPlans: async () => ({ status: 'unconfigured' }), - billingSetOverage: async () => ({ status: 'unconfigured' }) + billingSetOverage: async () => ({ status: 'unconfigured' }), + billingClaimTrial: async () => ({ status: 'unconfigured' }) } } } diff --git a/src/shared/orca-billing-denial.test.ts b/src/shared/orca-billing-denial.test.ts index 3202b13ede2..c6295fea0b0 100644 --- a/src/shared/orca-billing-denial.test.ts +++ b/src/shared/orca-billing-denial.test.ts @@ -15,6 +15,11 @@ describe('classifyEntitlementDenial', () => { expect(classifyEntitlementDenial('machine_size_not_in_plan')).toBe('machineSize') }) + it('treats both trial reasons as needing a plan', () => { + expect(classifyEntitlementDenial('trial_used_up')).toBe('plan') + expect(classifyEntitlementDenial('trial_unavailable')).toBe('plan') + }) + it('falls back to other for unknown or missing reasons', () => { expect(classifyEntitlementDenial('something_new')).toBe('other') expect(classifyEntitlementDenial(undefined)).toBe('other') diff --git a/src/shared/orca-billing.ts b/src/shared/orca-billing.ts index 41c4ebc21cc..5085876a7ce 100644 --- a/src/shared/orca-billing.ts +++ b/src/shared/orca-billing.ts @@ -15,6 +15,10 @@ export type OrcaBillingDenyReason = | 'payment_grace_expired' | 'included_hours_exhausted' | 'overage_cap_reached' + /** The team's one-time trial hours are used up (no plan yet). */ + | 'trial_used_up' + /** The team never had a plan and can't get a trial (one was already used by this account or team). */ + | 'trial_unavailable' /** * What a plan refusal means, whatever surface shows it. Billing's account reasons plus the control @@ -34,11 +38,14 @@ export type OrcaEntitlementDenialKind = export function classifyEntitlementDenial( reason: string | null | undefined ): OrcaEntitlementDenialKind { - // 'no plan' is the hosted provider's older log line for a missing plan. + // 'no plan' is the hosted provider's older log line for a missing plan. Both trial reasons are + // fixed by choosing a plan, so they read as "needs a plan" everywhere. switch (reason) { case 'no_subscription': case 'subscription_inactive': case 'no plan': + case 'trial_used_up': + case 'trial_unavailable': return 'plan' case 'included_hours_exhausted': return 'hours' @@ -81,6 +88,17 @@ export type OrcaBillingOffers = { maxSpendCapCents: number | null } enterprise: { label: string; priceLabel: string; contactUrl: string } + /** The one-time trial this caller could still start for the team; null when none is on offer. */ + trial?: { includedSeconds: number } | null +} + +/** The team's one-time trial (no card, no Stripe). Hours don't reset; a plan ends it. */ +export type OrcaBillingTrial = { + includedSeconds: number + usedSeconds: number + remainingSeconds: number + exhausted: boolean + grantedAt: number } export type OrcaBillingEntitlement = { @@ -96,6 +114,11 @@ export type OrcaBillingEntitlement = { /** Monthly window the hours count against (a slice of the year on annual plans). */ usageWindow: { start: number; end: number } | null cancelAtPeriodEnd: boolean + /** + * The trial while it is the team's plan (status 'trial'); null otherwise. During a trial, + * includedSeconds/usedSeconds/remainingIncludedSeconds mirror it and concurrency is 1. + */ + trial?: OrcaBillingTrial | null includedSeconds: number usedSeconds: number remainingIncludedSeconds: number @@ -175,6 +198,23 @@ export type OrcaBillingTeamPlansResult = /** At most this many teams per lookup (the billing Worker's bound). */ export const ORCA_BILLING_TEAM_PLANS_MAX_ORGS = 10 +/** The team is on its one-time trial (used up or not), with no plan. */ +export function isOrcaCloudTrial( + entitlement: Pick | null | undefined +): boolean { + return entitlement?.trial != null && entitlement.status === 'trial' +} + +export type OrcaBillingTrialClaimResult = + | { status: 'ok'; entitlement: OrcaBillingEntitlement } + | { status: 'unconfigured' } + | { status: 'signed-out' } + /** The trial can't be granted (abuse limits, already used, or the team had a plan). */ + | { status: 'unavailable' } + /** A personal account: setup creates a team first (O1). */ + | { status: 'team-required' } + | { status: 'failed'; error: string } + export function isOrcaBillingPlanId(value: unknown): value is OrcaBillingPlanId { return ORCA_BILLING_PLAN_IDS.some((plan) => plan === value) }