diff --git a/cloud/apps/billing/migrations/0007_cloud_setup_sessions.sql b/cloud/apps/billing/migrations/0007_cloud_setup_sessions.sql new file mode 100644 index 00000000000..d67dcd8f1fb --- /dev/null +++ b/cloud/apps/billing/migrations/0007_cloud_setup_sessions.sql @@ -0,0 +1,39 @@ +-- Cloud setup sessions (NP-4 N1): one browser trip that chains sign-in, team, plan and GitHub. +-- The desktop creates a session after sign-in and polls it; the setup pages on Orca Cloud auth +-- (auth.onorca.dev/cloud/setup/...) read and advance it; the control plane flips the GitHub step. +-- Times are epoch milliseconds. Additive only. +CREATE TABLE cloud_setup_sessions ( + id TEXT PRIMARY KEY, + -- Orca user who created it (billing token `sub`); every page and poll must be that user. + user_id TEXT NOT NULL, + -- 'org:' once a team is chosen or created; null until then (setup never bills a user:). + account_id TEXT, + team_name TEXT, + -- 1 when setup created the team (shown as "Rename team" on the done page). + team_created INTEGER NOT NULL DEFAULT 0, + -- https://github.com//, lower-cased, no .git; null when no repository is involved. + repo TEXT, + -- JSON array of the steps the desktop asked for: subset of ["team","plan","github"]. + needs TEXT NOT NULL, + -- Label of the device waiting for this session ("MacBook Pro"), shown on the account page. + device TEXT, + -- 'month' | 'year', chosen on the plan page. + billing_interval TEXT, + -- null | 'open' | 'canceled' | 'paid' + checkout_state TEXT, + -- null | 'pending' (owner approval requested on GitHub) | 'done' + github_state TEXT, + -- Latest error for the tracker (X1): timed_out | checkout_canceled | bank_step | trial_unavailable + -- | team_create_failed | wrong_account; cleared when the step moves on. + error_kind TEXT, + error_detail TEXT, + -- One-time browser ticket (SHA-256 hex) that lets the setup pages adopt this session's user. + ticket_hash TEXT, + ticket_expires_at INTEGER, + finished_at INTEGER, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL +); +CREATE INDEX cloud_setup_sessions_user ON cloud_setup_sessions(user_id, created_at); +CREATE INDEX cloud_setup_sessions_account_repo ON cloud_setup_sessions(account_id, repo); diff --git a/cloud/apps/billing/src/checkout.ts b/cloud/apps/billing/src/checkout.ts index e0e22fec7f6..5fddb7396f5 100644 --- a/cloud/apps/billing/src/checkout.ts +++ b/cloud/apps/billing/src/checkout.ts @@ -6,6 +6,7 @@ import { BILLING_INTERVALS, PLAN_IDS, priceForPlan, type BillingInterval, type P import { StripeError, type StripeClient } from './stripe' import { currentSubscription, customerFor, ensureAccount, linkCustomer } from './store' import { orgIdOf, type MembershipSource } from './membership' +import { setupCheckoutReturnUrls } from './cloud-setup-urls' export const MAX_TEAM_SEATS = 500 @@ -13,7 +14,9 @@ export const CheckoutRequestSchema = z .object({ plan: z.enum(PLAN_IDS), interval: z.enum(BILLING_INTERVALS).default('month'), - seats: z.number().int().min(1).max(MAX_TEAM_SEATS).default(1) + seats: z.number().int().min(1).max(MAX_TEAM_SEATS).default(1), + // The in-app plans dialog joins an open setup session: Checkout returns to its next step. + setupSessionId: z.string().regex(/^cs_[A-Za-z0-9_-]{22}$/).optional() }) .strict() @@ -46,11 +49,17 @@ export async function createCheckout( caller: BillingCaller, request: { plan: PlanId; interval: BillingInterval; seats: number }, now: number, - membership: MembershipSource + membership: MembershipSource, + options: { setupSessionId?: string } = {} ): Promise { if (!caller.canManage) { return { ok: false, status: 403, error: 'billing_admin_required' } } + // O1/N4: every Checkout lands on a team. A personal account's subscription could never move to + // a team later (the account id is the billing key), so the desktop creates the team first. + if (!caller.accountId.startsWith('org:')) { + return { ok: false, status: 409, error: 'team_required' } + } const existing = await currentSubscription(env.BILLING_DB, caller.accountId) if (existing && OPEN_STATUSES.has(existing.status)) { // Seat and interval changes go through the portal, which prorates; a second subscription @@ -78,7 +87,13 @@ export async function createCheckout( throw error } } - const metadata = { account_id: caller.accountId, plan: request.plan, interval: request.interval } + const metadata = { + account_id: caller.accountId, + plan: request.plan, + interval: request.interval, + ...(options.setupSessionId ? { setup_session_id: options.setupSessionId } : {}) + } + const setupReturn = options.setupSessionId ? setupCheckoutReturnUrls(env, options.setupSessionId) : null const session = await stripe.createCheckoutSession( { mode: 'subscription', @@ -92,8 +107,9 @@ export async function createCheckout( payment_method_collection: 'always', allow_promotion_codes: true, customer_update: { address: 'auto', name: 'auto' }, - success_url: returnUrl(env, { checkout: 'success', session_id: 'CHECKOUT_SESSION_ID_PLACEHOLDER' }), - cancel_url: returnUrl(env, { checkout: 'cancel' }), + success_url: + setupReturn?.success ?? returnUrl(env, { checkout: 'success', session_id: 'CHECKOUT_SESSION_ID_PLACEHOLDER' }), + cancel_url: setupReturn?.cancel ?? returnUrl(env, { checkout: 'cancel' }), metadata, ...(env.STRIPE_AUTOMATIC_TAX === 'true' ? { automatic_tax: { enabled: true }, tax_id_collection: { enabled: true } } diff --git a/cloud/apps/billing/src/cloud-setup-trial.ts b/cloud/apps/billing/src/cloud-setup-trial.ts new file mode 100644 index 00000000000..b9f2925dd00 --- /dev/null +++ b/cloud/apps/billing/src/cloud-setup-trial.ts @@ -0,0 +1,31 @@ +// The setup session's view of the one-time trial (N11, owned by src/trial.ts). Kept behind this +// port so the setup flow reads one shape whatever the trial module returns. +import type { Env } from './env' + +export type SetupTrial = { includedSeconds: number; usedSeconds: number; exhausted: boolean } + +export type TrialGrantInput = { + accountId: string + userId: string + email?: string + emailVerified?: boolean + githubUserId?: number + githubOwnerId?: number + ip?: string +} + +export type TrialPort = { + /** Sandbox seconds a new team's trial includes, or null when no trial is offered at all. */ + offeredSeconds(env: Env): number | null + /** The account's trial, or null when it has none (or a plan ended it). */ + current(env: Env, accountId: string, now: number): Promise + /** Grants the trial if this account and user may still get one. Idempotent. */ + grant(env: Env, input: TrialGrantInput, now: number): Promise<{ ok: true; trial: SetupTrial } | { ok: false; reason: string }> +} + +/** No trial backend: every team goes through a plan. Replaced by the trial module's port. */ +export const noTrialPort: TrialPort = { + offeredSeconds: () => null, + current: async () => null, + grant: async () => ({ ok: false, reason: 'trial_unavailable' }) +} diff --git a/cloud/apps/billing/src/cloud-setup-urls.ts b/cloud/apps/billing/src/cloud-setup-urls.ts new file mode 100644 index 00000000000..4ccc17b8461 --- /dev/null +++ b/cloud/apps/billing/src/cloud-setup-urls.ts @@ -0,0 +1,22 @@ +// URLs of the cloud setup pages on Orca Cloud auth (auth.onorca.dev/cloud/setup/...). +import type { Env } from './env' + +function pagesOrigin(env: Env): string { + return (env.CLOUD_SETUP_PAGES_URL ?? 'https://auth.onorca.dev').replace(/\/$/, '') +} + +export function setupPageUrl(env: Env, path: string, params: Record): string { + const url = new URL(`${pagesOrigin(env)}/cloud/setup${path}`) + for (const [key, value] of Object.entries(params)) { + url.searchParams.set(key, value) + } + return url.toString() +} + +/** Checkout return URLs for a setup session: success continues the chain, cancel goes back to T3. */ +export function setupCheckoutReturnUrls(env: Env, id: string): { success: string; cancel: string } { + return { + success: setupPageUrl(env, '/next', { session: id, from: 'checkout', checkout: 'success' }), + cancel: setupPageUrl(env, '/plan', { session: id, checkout: 'canceled' }) + } +} diff --git a/cloud/apps/billing/src/cloud-setup.ts b/cloud/apps/billing/src/cloud-setup.ts new file mode 100644 index 00000000000..b84bd4cd62c --- /dev/null +++ b/cloud/apps/billing/src/cloud-setup.ts @@ -0,0 +1,661 @@ +// Cloud setup sessions (NP-4 N1): one browser tab that chains sign-in -> team -> plan/trial -> +// (Checkout only when needed) -> GitHub App install, skipping steps that are already done. +// +// Who talks to it: +// - Desktop (billing JWT): creates a session after sign-in and polls it. The session belongs to +// that Orca user; nobody else can read it. +// - Setup pages on Orca Cloud auth (MEMBERSHIP_SYNC_TOKEN): redeem the one-time browser ticket, +// read the session, bind the team, open Checkout, ask for the GitHub install URL, record errors. +// Auth asserts the browser's user; every call re-checks it against the session's user. +// - Control plane (CONTROL_PLANE_TOKEN): flips the GitHub step when an installation binds. +// +// Steps are derived on every read (entitlement, trial, GitHub state), so the session never caches +// a plan state that billing could contradict. +import { z } from 'zod' +import type { BillingCaller } from './auth' +import { createCheckout, OPEN_STATUSES } from './checkout' +import type { TrialPort } from './cloud-setup-trial' +import { computeEntitlement } from './entitlements' +import type { Env } from './env' +import type { MembershipSource } from './membership' +import { BILLING_INTERVALS, type BillingInterval } from './plans' +import type { StripeClient } from './stripe' +import { currentSubscription } from './store' +import { setupPageUrl } from './cloud-setup-urls' + +export const SETUP_SESSION_ID = /^cs_[A-Za-z0-9_-]{22}$/ +const ORCA_ID = /^[A-Za-z0-9_.:-]{1,128}$/ + +export const SETUP_STEPS = ['team', 'plan', 'github'] as const +export type SetupNeed = (typeof SETUP_STEPS)[number] + +/** Sessions live two hours; no progress for 15 minutes reads as "Setup didn't finish". */ +export const SESSION_TTL_MS = 2 * 3600_000 +export const IDLE_TIMEOUT_MS = 15 * 60_000 +const TICKET_TTL_MS = 10 * 60_000 +/** Per user: enough for retries and several projects, too few to farm sessions. */ +const MAX_SESSIONS_PER_HOUR = 20 + +export const SETUP_ERROR_KINDS = [ + 'timed_out', + 'checkout_canceled', + 'bank_step', + 'trial_unavailable', + 'team_create_failed', + 'wrong_account' +] as const +export type SetupErrorKind = (typeof SETUP_ERROR_KINDS)[number] + +export type SetupStepState = 'done' | 'needed' | 'active' | 'pending' | 'failed' | 'optional' +export type SetupStep = { id: 'account' | 'team' | 'plan' | 'github'; state: SetupStepState; detail?: string } + +export type SetupSessionRow = { + id: string + user_id: string + account_id: string | null + team_name: string | null + team_created: number + repo: string | null + needs: string + device: string | null + billing_interval: string | null + checkout_state: string | null + github_state: string | null + error_kind: string | null + error_detail: string | null + ticket_hash: string | null + ticket_expires_at: number | null + finished_at: number | null + created_at: number + updated_at: number + expires_at: number +} + +export type SetupSessionView = { + id: string + steps: SetupStep[] + team: { orgId: string; name: string | null; created: boolean } | null + trial: { includedSeconds: number; usedSeconds: number; exhausted: boolean } | null + /** What the plan step rests on once done. */ + plan: 'subscription' | 'trial' | null + repo: string | null + finished: boolean + error: { kind: SetupErrorKind; detail?: string } | null + expiresAt: number +} + +/** Normalizes a GitHub repository URL to https://github.com// (lower case). */ +export function normalizeRepo(value: string | null | undefined): string | null { + if (!value) { + return null + } + const trimmed = value.trim().replace(/\/+$/, '').replace(/\.git$/i, '') + const match = + /^https:\/\/github\.com\/([A-Za-z0-9-]{1,39})\/([A-Za-z0-9._-]{1,100})$/i.exec(trimmed) ?? + /^git@github\.com:([A-Za-z0-9-]{1,39})\/([A-Za-z0-9._-]{1,100})$/i.exec(trimmed) + return match ? `https://github.com/${match[1]}/${match[2]}`.toLowerCase() : null +} + +export function repoOwner(repo: string | null): string | null { + return repo ? (/^https:\/\/github\.com\/([^/]+)\//.exec(repo)?.[1] ?? null) : null +} + +function base64url(bytes: Uint8Array): string { + let binary = '' + for (const byte of bytes) { + binary += String.fromCharCode(byte) + } + return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') +} + +function randomToken(bytes: number): string { + return base64url(crypto.getRandomValues(new Uint8Array(bytes))) +} + +async function sha256Hex(value: string): Promise { + const bytes = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value))) + return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('') +} + +export function newSetupSessionId(): string { + // 16 random bytes -> 22 base64url characters. + return `cs_${randomToken(16)}` +} + +function parseNeeds(row: SetupSessionRow): Set { + try { + const parsed = z.array(z.enum(SETUP_STEPS)).safeParse(JSON.parse(row.needs)) + return new Set(parsed.success ? parsed.data : []) + } catch { + return new Set() + } +} + +export const CreateSetupSessionSchema = z + .object({ + repo: z.string().max(300).optional(), + needs: z.array(z.enum(SETUP_STEPS)).max(3).default(['team', 'plan']), + device: z.string().trim().min(1).max(80).optional(), + // The desktop's active team is the session's team unless it asks to choose ('team' in needs). + useActiveTeam: z.boolean().default(true) + }) + .strict() + +export type CreateSetupSessionResult = + | { ok: true; id: string; url: string; expiresAt: number } + | { ok: false; status: number; error: string } + +export async function createSetupSession( + env: Env, + caller: BillingCaller, + body: z.infer, + now: number +): Promise { + const recent = await env.BILLING_DB.prepare( + 'SELECT COUNT(*) AS n FROM cloud_setup_sessions WHERE user_id = ?1 AND created_at > ?2' + ) + .bind(caller.userId, now - 3600_000) + .first<{ n: number }>() + if ((recent?.n ?? 0) >= MAX_SESSIONS_PER_HOUR) { + return { ok: false, status: 429, error: 'rate_limited' } + } + const repo = normalizeRepo(body.repo) + if (body.repo && !repo) { + return { ok: false, status: 400, error: 'invalid_repo' } + } + const needs = new Set(body.needs) + if (needs.has('github') && !repo) { + needs.delete('github') + } + // O1: setup never puts a plan or a trial on a personal account, so a user: caller always gets a + // team step; an org caller keeps its active team unless it asked to choose. + const orgAccount = caller.accountId.startsWith('org:') ? caller.accountId : null + const keepTeam = orgAccount !== null && body.useActiveTeam && !needs.has('team') + if (!keepTeam) { + needs.add('team') + } + const id = newSetupSessionId() + const ticket = randomToken(32) + const expiresAt = now + SESSION_TTL_MS + await env.BILLING_DB.prepare( + `INSERT INTO cloud_setup_sessions (id, user_id, account_id, repo, needs, device, ticket_hash, + ticket_expires_at, created_at, updated_at, expires_at) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?9, ?10)` + ) + .bind( + id, + caller.userId, + keepTeam ? orgAccount : null, + repo, + JSON.stringify([...needs]), + body.device ?? null, + await sha256Hex(ticket), + now + TICKET_TTL_MS, + now, + expiresAt + ) + .run() + return { ok: true, id, url: setupPageUrl(env, '/start', { session: id, ticket }), expiresAt } +} + +/** "Copy setup link": a fresh one-time ticket for another browser (the old one is replaced). */ +export async function reissueSetupTicket( + env: Env, + caller: BillingCaller, + id: string, + now: number +): Promise<{ url: string } | null> { + const row = await loadSetupSession(env, id, now) + if (!row || row.user_id !== caller.userId || row.finished_at !== null) { + return null + } + const ticket = randomToken(32) + await touch(env, id, { ticket_hash: await sha256Hex(ticket), ticket_expires_at: now + TICKET_TTL_MS }, now) + return { url: setupPageUrl(env, '/start', { session: id, ticket }) } +} + +export async function loadSetupSession(env: Env, id: string, now: number): Promise { + if (!SETUP_SESSION_ID.test(id)) { + return null + } + const row = await env.BILLING_DB.prepare('SELECT * FROM cloud_setup_sessions WHERE id = ?1') + .bind(id) + .first() + return row && row.expires_at > now ? row : null +} + +async function touch(env: Env, id: string, fields: Record, now: number): Promise { + const keys = Object.keys(fields) + const sets = keys.map((key, index) => `${key} = ?${index + 2}`) + await env.BILLING_DB.prepare( + `UPDATE cloud_setup_sessions SET ${[...sets, `updated_at = ?${keys.length + 2}`].join(', ')} WHERE id = ?1` + ) + .bind(id, ...keys.map((key) => fields[key] ?? null), now) + .run() +} + +/** The account's plan state as setup sees it: a live subscription, a usable trial, or neither. */ +async function planState( + env: Env, + trial: TrialPort, + accountId: string, + now: number +): Promise<{ plan: 'subscription' | 'trial' | null; trial: SetupSessionView['trial'] }> { + const subscription = await currentSubscription(env.BILLING_DB, accountId) + if (subscription && OPEN_STATUSES.has(subscription.status)) { + const entitlement = await computeEntitlement(env, accountId, now) + // past_due etc. still count as "has a plan": the composer shows the payment state, not setup. + return { plan: entitlement.plan ? 'subscription' : null, trial: null } + } + const current = await trial.current(env, accountId, now) + return { plan: current && !current.exhausted ? 'trial' : null, trial: current } +} + +export async function setupSessionView( + env: Env, + trial: TrialPort, + row: SetupSessionRow, + now: number +): Promise { + const needs = parseNeeds(row) + const plan = row.account_id ? await planState(env, trial, row.account_id, now) : { plan: null, trial: null } + const done = { + team: row.account_id !== null, + plan: plan.plan !== null || !needs.has('plan'), + github: row.github_state === 'done' || !needs.has('github') + } + const steps: SetupStep[] = [{ id: 'account', state: 'done' }] + let activeTaken = false + const push = (id: 'team' | 'plan' | 'github', isDone: boolean, detail?: string) => { + if (id !== 'team' && !needs.has(id) && !isDone) { + return + } + if (isDone) { + steps.push({ id, state: 'done', ...(detail ? { detail } : {}) }) + return + } + const state: SetupStepState = activeTaken ? 'pending' : 'active' + activeTaken = true + steps.push({ id, state, ...(detail ? { detail } : {}) }) + } + push('team', done.team, row.team_name ?? undefined) + if (needs.has('plan') || plan.plan) { + push('plan', done.plan, plan.plan ?? (row.checkout_state === 'open' ? 'checkout' : undefined)) + } + if (needs.has('github')) { + push('github', done.github, row.github_state === 'pending' ? 'requested' : undefined) + } + const finished = steps.every((step) => step.state === 'done') + if (finished && row.finished_at === null) { + await touch(env, row.id, { finished_at: now, error_kind: null, error_detail: null }, now) + } + let error: SetupSessionView['error'] = null + if (!finished) { + if (row.error_kind && (SETUP_ERROR_KINDS as readonly string[]).includes(row.error_kind)) { + error = { kind: row.error_kind as SetupErrorKind, ...(row.error_detail ? { detail: row.error_detail } : {}) } + } else if (now - row.updated_at > IDLE_TIMEOUT_MS && row.github_state !== 'pending') { + // An owner approval on GitHub can take longer; everything else has stalled. + error = { kind: 'timed_out' } + } + } + // A failed step reads as failed in the tracker; the rest keep their state. + if (error && error.kind !== 'timed_out') { + const failing = error.kind === 'team_create_failed' || error.kind === 'wrong_account' ? 'team' : 'plan' + const step = steps.find((candidate) => candidate.id === failing) + if (step && step.state !== 'done') { + step.state = 'failed' + } + } + return { + id: row.id, + steps, + team: row.account_id + ? { orgId: row.account_id.slice('org:'.length), name: row.team_name, created: row.team_created === 1 } + : null, + trial: plan.trial, + plan: plan.plan, + repo: row.repo, + finished, + error, + expiresAt: row.expires_at + } +} + +// ---- Internal: setup pages on Orca Cloud auth ------------------------------------------------- + +const UserSchema = z.string().regex(ORCA_ID) + +export const RedeemSchema = z.object({ sessionId: z.string().regex(SETUP_SESSION_ID), ticket: z.string().min(20).max(100) }).strict() + +/** One-time: the ticket from the desktop's URL becomes the browser's proof of this session's user. */ +export async function redeemSetupTicket( + env: Env, + body: z.infer, + now: number +): Promise<{ userId: string } | null> { + const row = await loadSetupSession(env, body.sessionId, now) + if (!row || !row.ticket_hash || (row.ticket_expires_at ?? 0) <= now) { + return null + } + if (row.ticket_hash !== (await sha256Hex(body.ticket))) { + return null + } + // Clear it in the same statement that checks it, so two tabs can't both redeem. + const result = await env.BILLING_DB.prepare( + 'UPDATE cloud_setup_sessions SET ticket_hash = NULL, ticket_expires_at = NULL, updated_at = ?3 WHERE id = ?1 AND ticket_hash = ?2' + ) + .bind(row.id, row.ticket_hash, now) + .run() + if ((result.meta as { changes?: number }).changes === 0) { + return null + } + return { userId: row.user_id } +} + +export const InternalReadSchema = z.object({ userId: UserSchema }).strict() + +export type InternalSetupSession = SetupSessionView & { + needs: SetupNeed[] + device: string | null + interval: BillingInterval | null + checkoutState: string | null + githubState: string | null + /** For the plan page: whether this team can still get its trial (granted when the team binds). */ + ownerHint: string | null +} + +export async function readSetupSessionForPages( + env: Env, + trial: TrialPort, + id: string, + userId: string, + now: number +): Promise { + const row = await loadSetupSession(env, id, now) + if (!row || row.user_id !== userId) { + return null + } + const view = await setupSessionView(env, trial, row, now) + return { + ...view, + needs: [...parseNeeds(row)], + device: row.device, + interval: (BILLING_INTERVALS as readonly string[]).includes(row.billing_interval ?? '') + ? (row.billing_interval as BillingInterval) + : null, + checkoutState: row.checkout_state, + githubState: row.github_state, + ownerHint: repoOwner(row.repo) + } +} + +export const TeamPlansSchema = z + .object({ userId: UserSchema, orgIds: z.array(z.string().regex(ORCA_ID)).max(50) }) + .strict() + +/** A3: which of the user's teams already have a plan or a usable trial (that team is preselected). */ +export async function setupTeamPlans( + env: Env, + trial: TrialPort, + id: string, + body: z.infer, + now: number +): Promise | null> { + const row = await loadSetupSession(env, id, now) + if (!row || row.user_id !== body.userId) { + return null + } + const entries = await Promise.all( + body.orgIds.map(async (orgId) => { + const state = await planState(env, trial, `org:${orgId}`, now) + return [orgId, state.plan ?? (state.trial?.exhausted ? 'trial_used_up' : null)] as const + }) + ) + return Object.fromEntries(entries) +} + +export const BindTeamSchema = z + .object({ + userId: UserSchema, + orgId: z.string().regex(ORCA_ID), + name: z.string().trim().min(1).max(120), + created: z.boolean().default(false), + // Trial abuse keys (N11), forwarded from the page's request and the user's identity. + email: z.string().email().max(320).optional(), + emailVerified: z.boolean().optional(), + githubUserId: z.number().int().positive().optional(), + githubOwnerId: z.number().int().positive().optional(), + ip: z.string().max(64).optional() + }) + .strict() + +/** + * Binds the session to a team (chosen, created, or renamed). A team that has no plan gets the + * trial now if it can; otherwise the plan step stays and the pages offer T3 + Checkout. + */ +export async function bindSetupTeam( + env: Env, + trial: TrialPort, + id: string, + body: z.infer, + now: number +): Promise<{ ok: true; trial: 'granted' | 'unavailable' | 'not_needed' } | { ok: false; status: number; error: string }> { + const row = await loadSetupSession(env, id, now) + if (!row || row.user_id !== body.userId) { + return { ok: false, status: 404, error: 'not_found' } + } + const accountId = `org:${body.orgId}` + // Once bound, only a rename of the same team is accepted; a different team needs a new session. + if (row.account_id && row.account_id !== accountId) { + return { ok: false, status: 409, error: 'team_already_chosen' } + } + await touch( + env, + id, + { + account_id: accountId, + team_name: body.name, + team_created: body.created || row.team_created === 1 ? 1 : 0, + error_kind: null, + error_detail: null + }, + now + ) + const state = await planState(env, trial, accountId, now) + if (state.plan !== null || !parseNeeds(row).has('plan')) { + return { ok: true, trial: 'not_needed' } + } + if (state.trial) { + // Had a trial and used it up: Checkout. + return { ok: true, trial: 'unavailable' } + } + const granted = await trial.grant( + env, + { + accountId, + userId: body.userId, + ...(body.email ? { email: body.email } : {}), + ...(body.emailVerified !== undefined ? { emailVerified: body.emailVerified } : {}), + ...(body.githubUserId ? { githubUserId: body.githubUserId } : {}), + ...(body.githubOwnerId ? { githubOwnerId: body.githubOwnerId } : {}), + ...(body.ip ? { ip: body.ip } : {}) + }, + now + ) + return { ok: true, trial: granted.ok ? 'granted' : 'unavailable' } +} + +export const SetupErrorSchema = z + .object({ + userId: UserSchema, + kind: z.enum(SETUP_ERROR_KINDS).nullable(), + detail: z.string().max(320).optional() + }) + .strict() + +export async function recordSetupError( + env: Env, + id: string, + body: z.infer, + now: number +): Promise { + const row = await loadSetupSession(env, id, now) + if (!row || row.user_id !== body.userId) { + return false + } + await touch( + env, + id, + { + error_kind: body.kind, + error_detail: body.kind ? (body.detail ?? null) : null, + ...(body.kind === 'checkout_canceled' ? { checkout_state: 'canceled' } : {}) + }, + now + ) + return true +} + +export const SetupCheckoutSchema = z + .object({ + userId: UserSchema, + orgRole: z.enum(['owner', 'admin', 'member']), + email: z.string().email().max(320).optional(), + interval: z.enum(BILLING_INTERVALS) + }) + .strict() + +/** T3 -> Stripe: Checkout for the session's team, returning to the setup pages (never a user:). */ +export async function createSetupCheckout( + env: Env, + stripe: StripeClient, + id: string, + body: z.infer, + now: number, + membership: MembershipSource +): Promise<{ ok: true; url: string } | { ok: false; status: number; error: string }> { + const row = await loadSetupSession(env, id, now) + if (!row || row.user_id !== body.userId) { + return { ok: false, status: 404, error: 'not_found' } + } + if (!row.account_id) { + return { ok: false, status: 409, error: 'team_required' } + } + const caller: BillingCaller = { + userId: body.userId, + accountId: row.account_id, + canManage: body.orgRole === 'owner' || body.orgRole === 'admin', + ...(body.email ? { email: body.email } : {}) + } + const outcome = await createCheckout( + env, + stripe, + caller, + { plan: 'team', interval: body.interval, seats: 1 }, + now, + membership, + { setupSessionId: id } + ) + if (outcome.ok) { + await touch(env, id, { billing_interval: body.interval, checkout_state: 'open', error_kind: null, error_detail: null }, now) + } + return outcome +} + +export const GithubInstallSchema = z + .object({ + userId: UserSchema, + // Set only after auth verified a live GitHub sign-in token for this user (N5). + githubUserId: z.number().int().positive().optional(), + githubLogin: z.string().regex(/^[A-Za-z0-9-]{1,39}$/).optional() + }) + .strict() + +const InstallUrlResponse = z.looseObject({ + access: z.enum(['public', 'granted', 'missing', 'requested']), + url: z.string().url().nullable().optional() +}) + +/** Asks the control plane how this session's repository is reachable and, if not, for the install URL. */ +export async function setupGithubInstall( + env: Env, + id: string, + body: z.infer, + now: number, + fetchImpl: typeof fetch = fetch +): Promise<{ ok: true; access: string; url: string | null } | { ok: false; status: number; error: string }> { + const row = await loadSetupSession(env, id, now) + if (!row || row.user_id !== body.userId) { + return { ok: false, status: 404, error: 'not_found' } + } + if (!row.repo || !row.account_id) { + return { ok: false, status: 409, error: row.repo ? 'team_required' : 'no_repo' } + } + if (!env.SANDBOX_CONTROL_URL) { + return { ok: false, status: 503, error: 'github_unavailable' } + } + const url = new URL('/v1/internal/github/install-url', env.SANDBOX_CONTROL_URL) + url.searchParams.set('accountId', row.account_id) + url.searchParams.set('userId', row.user_id) + url.searchParams.set('repo', row.repo) + url.searchParams.set('session', row.id) + if (body.githubUserId && body.githubLogin) { + url.searchParams.set('githubUserId', String(body.githubUserId)) + url.searchParams.set('githubLogin', body.githubLogin) + } + const token = (env.CONTROL_PLANE_TOKEN ?? '').split(',')[0]?.trim() ?? '' + const response = await fetchImpl(url, { + headers: { authorization: `Bearer ${token}`, accept: 'application/json' }, + signal: AbortSignal.timeout(8000) + }) + const parsed = InstallUrlResponse.safeParse(await response.json().catch(() => null)) + if (!response.ok || !parsed.success) { + return { ok: false, status: 502, error: 'github_unavailable' } + } + const access = parsed.data.access + if (access === 'public' || access === 'granted') { + await touch(env, id, { github_state: 'done' }, now) + } else if (access === 'requested') { + await touch(env, id, { github_state: 'pending' }, now) + } + return { ok: true, access, url: access === 'missing' ? (parsed.data.url ?? null) : null } +} + +// ---- Internal: control plane ------------------------------------------------------------------ + +export const GithubEventSchema = z + .object({ + sessionId: z.string().regex(SETUP_SESSION_ID).optional(), + accountId: z.string().regex(ORCA_ID), + repo: z.string().max(300), + state: z.enum(['done', 'pending']) + }) + .strict() + +/** An installation bound (or an owner approval was requested): flip matching open sessions. */ +export async function recordGithubEvent( + env: Env, + body: z.infer, + now: number +): Promise<{ matched: number }> { + const repo = normalizeRepo(body.repo) + if (!repo) { + return { matched: 0 } + } + // 'pending' never overwrites 'done' (a late request echo after the bind). + const guard = body.state === 'pending' ? "AND (github_state IS NULL OR github_state <> 'done')" : '' + const result = body.sessionId + ? await env.BILLING_DB.prepare( + `UPDATE cloud_setup_sessions SET github_state = ?1, updated_at = ?2 + WHERE id = ?3 AND account_id = ?4 AND repo = ?5 AND expires_at > ?2 ${guard}` + ) + .bind(body.state, now, body.sessionId, body.accountId, repo) + .run() + : await env.BILLING_DB.prepare( + `UPDATE cloud_setup_sessions SET github_state = ?1, updated_at = ?2 + WHERE account_id = ?3 AND repo = ?4 AND expires_at > ?2 AND finished_at IS NULL ${guard}` + ) + .bind(body.state, now, body.accountId, repo) + .run() + return { matched: (result.meta as { changes?: number }).changes ?? 0 } +} diff --git a/cloud/apps/billing/src/env.ts b/cloud/apps/billing/src/env.ts index d7692f9c752..60af142b11f 100644 --- a/cloud/apps/billing/src/env.ts +++ b/cloud/apps/billing/src/env.ts @@ -61,4 +61,10 @@ export type Env = { // Auth origin serving POST /v1/internal/billing/org-members. Unset: seats come from pushes and the // Checkout request only (local dev). AUTH_INTERNAL_URL?: string + + // Cloud setup sessions (cloud-setup.ts). Origin of the setup pages on Orca Cloud auth + // (https://auth.onorca.dev, staging https://auth-staging.onorca.dev); Checkout returns there. + CLOUD_SETUP_PAGES_URL?: string + // Control plane origin billing asks for a repository's GitHub install URL (CONTROL_PLANE_TOKEN). + SANDBOX_CONTROL_URL?: string } diff --git a/cloud/apps/billing/src/index.ts b/cloud/apps/billing/src/index.ts index c6f028510cb..bf2f93519d1 100644 --- a/cloud/apps/billing/src/index.ts +++ b/cloud/apps/billing/src/index.ts @@ -14,6 +14,20 @@ // GET /v1/internal/suspensions accounts whose payment grace expired (suspend running) // 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 +// GET /v1/internal/cloud-setup/sessions/:id?userId= session for the pages +// POST /v1/internal/cloud-setup/sessions/:id/team {userId, orgId, name, created, ...abuse keys} +// POST /v1/internal/cloud-setup/sessions/:id/team-plans {userId, orgIds[]} -> {plans} +// POST /v1/internal/cloud-setup/sessions/:id/checkout {userId, orgRole, email?, interval} -> {url} +// POST /v1/internal/cloud-setup/sessions/:id/github {userId, githubUserId?, githubLogin?} +// POST /v1/internal/cloud-setup/sessions/:id/error {userId, kind|null, detail?} +// Cloud setup (desktop billing JWT): +// POST /v1/cloud-setup/sessions {repo?, needs[], device?, useActiveTeam?} -> {id, url, expiresAt} +// GET /v1/cloud-setup/sessions/:id steps, team, trial, finished, error +// POST /v1/cloud-setup/sessions/:id/link -> {url} fresh one-time link ("Copy setup link") +// GET /v1/cloud-setup/offers public: trial hours and Team prices for the setup pages +// Control plane (CONTROL_PLANE_TOKEN): +// POST /v1/internal/cloud-setup/github {sessionId?, accountId, repo, state} import { z } from 'zod' import { ADMIN_ACTION_MAX_TOKEN_AGE, @@ -35,6 +49,30 @@ import { LiveModeRefusedError, StripeError, createStripeClient, type StripeClien import { UsageReportSchema, flushMeterReports, recordUsage, validateSegment } from './usage' import { handleStripeWebhook } from './webhook' import { renderReturnPage, returnOutcome } from './return-page' +import { + BindTeamSchema, + CreateSetupSessionSchema, + GithubEventSchema, + GithubInstallSchema, + InternalReadSchema, + RedeemSchema, + SetupCheckoutSchema, + SetupErrorSchema, + TeamPlansSchema, + bindSetupTeam, + setupTeamPlans, + createSetupCheckout, + createSetupSession, + loadSetupSession, + readSetupSessionForPages, + recordGithubEvent, + recordSetupError, + redeemSetupTicket, + reissueSetupTicket, + setupGithubInstall, + setupSessionView +} from './cloud-setup' +import { noTrialPort, type TrialPort } from './cloud-setup-trial' const MAX_JSON_BYTES = 16 * 1024 @@ -61,7 +99,149 @@ async function readJson(request: Request): Promise { return text ? JSON.parse(text) : {} } -export type Deps = { stripe?: StripeClient; now?: () => number; membership?: MembershipSource; orgMember?: OrgMemberCheck } +export type Deps = { + stripe?: StripeClient + now?: () => number + membership?: MembershipSource + orgMember?: OrgMemberCheck + trial?: TrialPort + fetch?: typeof fetch +} + +const SETUP_SESSION_PATH = /^\/v1\/cloud-setup\/sessions\/(cs_[A-Za-z0-9_-]{22})(\/link)?$/ +const INTERNAL_SETUP_PATH = /^\/v1\/internal\/cloud-setup\/sessions\/(cs_[A-Za-z0-9_-]{22})(?:\/(team|team-plans|checkout|github|error))?$/ + +async function handleCloudSetup( + request: Request, + env: Env, + url: URL, + now: number, + deps: { stripe: StripeClient; membership: MembershipSource; trial: TrialPort; fetch: typeof fetch } +): Promise { + const route = `${request.method} ${url.pathname}` + if (route === 'GET /v1/cloud-setup/offers') { + // Public: the setup pages show the trial and prices before anyone has signed in. + const offered = deps.trial.offeredSeconds(env) + return json({ ...publicOffers(planCatalog(env)), trial: offered ? { includedSeconds: offered } : null }) + } + if (route === 'POST /v1/cloud-setup/sessions') { + const caller = await authenticateDesktop(env, request) + if (!caller) { + return json({ error: 'unauthorized' }, 401) + } + const body = CreateSetupSessionSchema.safeParse(await readJson(request)) + if (!body.success) { + return json({ error: 'invalid_request' }, 400) + } + const created = await createSetupSession(env, caller, body.data, now) + return created.ok + ? json({ id: created.id, url: created.url, expiresAt: created.expiresAt }, 201) + : json({ error: created.error }, created.status) + } + const desktopMatch = SETUP_SESSION_PATH.exec(url.pathname) + if (desktopMatch?.[2] && request.method === 'POST') { + const caller = await authenticateDesktop(env, request) + if (!caller) { + return json({ error: 'unauthorized' }, 401) + } + const link = await reissueSetupTicket(env, caller, desktopMatch[1]!, now) + return link ? json(link) : json({ error: 'not_found' }, 404) + } + if (desktopMatch && !desktopMatch[2] && request.method === 'GET') { + const caller = await authenticateDesktop(env, request) + if (!caller) { + return json({ error: 'unauthorized' }, 401) + } + const row = await loadSetupSession(env, desktopMatch[1]!, now) + if (!row || row.user_id !== caller.userId) { + return json({ error: 'not_found' }, 404) + } + return json(await setupSessionView(env, deps.trial, row, now)) + } + if (route === 'POST /v1/internal/cloud-setup/github') { + if (!(await authenticateControlPlane(env, request))) { + return json({ error: 'unauthorized' }, 401) + } + const body = GithubEventSchema.safeParse(await readJson(request)) + if (!body.success) { + return json({ error: 'invalid_request' }, 400) + } + return json({ ok: true, ...(await recordGithubEvent(env, body.data, now)) }) + } + if (route === 'POST /v1/internal/cloud-setup/redeem') { + if (!(await authenticateMembershipSync(env, request))) { + return json({ error: 'unauthorized' }, 401) + } + const body = RedeemSchema.safeParse(await readJson(request)) + if (!body.success) { + return json({ error: 'invalid_request' }, 400) + } + const redeemed = await redeemSetupTicket(env, body.data, now) + return redeemed ? json(redeemed) : json({ error: 'invalid_ticket' }, 404) + } + const internalMatch = INTERNAL_SETUP_PATH.exec(url.pathname) + if (!internalMatch) { + return null + } + if (!(await authenticateMembershipSync(env, request))) { + return json({ error: 'unauthorized' }, 401) + } + const id = internalMatch[1]! + const action = internalMatch[2] + if (!action && request.method === 'GET') { + const query = InternalReadSchema.safeParse({ userId: url.searchParams.get('userId') ?? '' }) + if (!query.success) { + return json({ error: 'invalid_request' }, 400) + } + const session = await readSetupSessionForPages(env, deps.trial, id, query.data.userId, now) + return session ? json({ ...session, offers: publicOffers(planCatalog(env)) }) : json({ error: 'not_found' }, 404) + } + if (request.method !== 'POST' || !action) { + return json({ error: 'not_found' }, 404) + } + const raw = await readJson(request) + switch (action) { + case 'team': { + const body = BindTeamSchema.safeParse(raw) + if (!body.success) { + return json({ error: 'invalid_request' }, 400) + } + const bound = await bindSetupTeam(env, deps.trial, id, body.data, now) + return bound.ok ? json(bound) : json({ error: bound.error }, bound.status) + } + case 'team-plans': { + const body = TeamPlansSchema.safeParse(raw) + if (!body.success) { + return json({ error: 'invalid_request' }, 400) + } + const plans = await setupTeamPlans(env, deps.trial, id, body.data, now) + return plans ? json({ plans }) : json({ error: 'not_found' }, 404) + } + case 'checkout': { + const body = SetupCheckoutSchema.safeParse(raw) + if (!body.success) { + return json({ error: 'invalid_request' }, 400) + } + const outcome = await createSetupCheckout(env, deps.stripe, id, body.data, now, deps.membership) + return outcome.ok ? json({ url: outcome.url }) : json({ error: outcome.error }, outcome.status) + } + case 'github': { + const body = GithubInstallSchema.safeParse(raw) + if (!body.success) { + return json({ error: 'invalid_request' }, 400) + } + const outcome = await setupGithubInstall(env, id, body.data, now, deps.fetch) + return outcome.ok ? json({ access: outcome.access, url: outcome.url }) : json({ error: outcome.error }, outcome.status) + } + default: { + const body = SetupErrorSchema.safeParse(raw) + if (!body.success) { + return json({ error: 'invalid_request' }, 400) + } + return (await recordSetupError(env, id, body.data, now)) ? json({ ok: true }) : json({ error: 'not_found' }, 404) + } + } +} export async function handleRequest(request: Request, env: Env, ctx: ExecutionContext, deps: Deps = {}): Promise { const url = new URL(request.url) @@ -70,6 +250,17 @@ export async function handleRequest(request: Request, env: Env, ctx: ExecutionCo const membership = deps.membership ?? authMembershipSource(env) const route = `${request.method} ${url.pathname}` try { + if (url.pathname.startsWith('/v1/cloud-setup/') || url.pathname.startsWith('/v1/internal/cloud-setup/')) { + const handled = await handleCloudSetup(request, env, url, now, { + stripe, + membership, + trial: deps.trial ?? noTrialPort, + fetch: deps.fetch ?? fetch + }) + if (handled) { + return handled + } + } switch (route) { case 'GET /return': // Where Checkout and the Portal send the browser back; hands off to the desktop app. @@ -111,7 +302,15 @@ export async function handleRequest(request: Request, env: Env, ctx: ExecutionCo if (!body.success) { return json({ error: 'invalid_request' }, 400) } - const outcome = await createCheckout(env, stripe, caller, body.data, now, membership) + const { setupSessionId, ...checkout } = body.data + if (setupSessionId) { + // The plans dialog joins the open setup session only for its own user and team. + const session = await loadSetupSession(env, setupSessionId, now) + if (!session || session.user_id !== caller.userId || (session.account_id && session.account_id !== caller.accountId)) { + return json({ error: 'setup_session_mismatch' }, 409) + } + } + const outcome = await createCheckout(env, stripe, caller, checkout, now, membership, setupSessionId ? { setupSessionId } : {}) return outcome.ok ? json({ url: outcome.url }) : json({ error: outcome.error }, outcome.status) } diff --git a/cloud/apps/billing/test/billing-config.test.ts b/cloud/apps/billing/test/billing-config.test.ts index 1b5f3835a5e..cdd2e1c85a6 100644 --- a/cloud/apps/billing/test/billing-config.test.ts +++ b/cloud/apps/billing/test/billing-config.test.ts @@ -12,7 +12,7 @@ describe('config: tax and plan catalog', () => { ['true', 'true'] ] as const) { const h = await createHarness(flag ? { STRIPE_AUTOMATIC_TAX: flag } : {}) - const token = await h.desktopToken({ sub: 'u1' }) + const token = await h.desktopToken({ sub: 'u1', org: 'o1', orgRole: 'owner' }) await h.call('POST', '/v1/billing/checkout', { body: { plan: 'team' }, headers: { authorization: `Bearer ${token}` } }) const session = h.stripe.calls.find((call) => call.method === 'POST' && call.path === '/v1/checkout/sessions')! expect(session.form.get('automatic_tax[enabled]')).toBe(expected) diff --git a/cloud/apps/billing/test/billing-flow.test.ts b/cloud/apps/billing/test/billing-flow.test.ts index 7638d4f5d6c..196e588dcae 100644 --- a/cloud/apps/billing/test/billing-flow.test.ts +++ b/cloud/apps/billing/test/billing-flow.test.ts @@ -67,7 +67,7 @@ describe('checkout and portal', () => { expect(annual!.headers.get('idempotency-key')).toMatch(/^checkout:org:o1:/) }) - it('lets only org owners and admins buy or manage the plan; personal accounts manage themselves', async () => { + it('lets only org owners and admins buy or manage the plan; personal accounts must make a team first', async () => { const h = await createHarness() const member = await h.desktopToken({ sub: 'u2', org: 'o1', orgRole: 'member' }) const auth = { authorization: `Bearer ${member}` } @@ -79,8 +79,10 @@ describe('checkout and portal', () => { expect((await h.call('POST', '/v1/billing/overage', { body: { enabled: true }, headers: auth })).status).toBe(403) const solo = await h.desktopToken({ sub: 'u3' }) - expect((await h.call('POST', '/v1/billing/checkout', { body: { plan: 'team' }, headers: { authorization: `Bearer ${solo}` } })).status).toBe(200) - expect(h.stripe.customers.values().next().value?.metadata.account_id).toBe('user:u3') + expect((await h.call('POST', '/v1/billing/checkout', { body: { plan: 'team' }, headers: { authorization: `Bearer ${solo}` } })).body).toEqual({ + error: 'team_required' + }) + expect(h.stripe.customers.size).toBe(0) }) it('rejects bad tokens, unknown plans and a second subscription', async () => { @@ -470,7 +472,7 @@ describe('entitlements, overage and usage', () => { it('refuses to run with a live Stripe key', async () => { const h = await createHarness({ STRIPE_SECRET_KEY: 'sk_live_nope' }) - const token = await h.desktopToken({ sub: 'u1' }) + const token = await h.desktopToken({ sub: 'u1', org: 'o1', orgRole: 'owner' }) expect(await h.call('POST', '/v1/billing/checkout', { body: { plan: 'team' }, headers: { authorization: `Bearer ${token}` } })).toEqual({ status: 503, body: { error: 'billing_misconfigured' } diff --git a/cloud/apps/billing/test/cloud-setup.test.ts b/cloud/apps/billing/test/cloud-setup.test.ts new file mode 100644 index 00000000000..90ade3bd9e6 --- /dev/null +++ b/cloud/apps/billing/test/cloud-setup.test.ts @@ -0,0 +1,251 @@ +import { describe, expect, it } from 'vitest' +import type { TrialPort, SetupTrial } from '../src/cloud-setup-trial' +import { normalizeRepo } from '../src/cloud-setup' +import { checkoutCompleted } from './stripe-fake' +import { CONTROL_TOKEN, createHarness } from './harness' + +const SYNC = 'sync_test_0123456789abcdef0123456789abcdef' +const REPO = 'https://github.com/Acme/Web.git' + +/** In-memory trial backend: one 2-hour trial per account, exhausted on demand. */ +function fakeTrials(options: { refuse?: boolean } = {}) { + const trials = new Map() + const grants: string[] = [] + const port: TrialPort = { + offeredSeconds: () => 7200, + current: async (_env, accountId) => trials.get(accountId) ?? null, + grant: async (_env, input) => { + grants.push(input.accountId) + if (options.refuse) { + return { ok: false, reason: 'trial_unavailable' } + } + const trial = trials.get(input.accountId) ?? { includedSeconds: 7200, usedSeconds: 0, exhausted: false } + trials.set(input.accountId, trial) + return { ok: true, trial } + } + } + return { port, trials, grants } +} + +async function setup(options: { refuseTrial?: boolean } = {}) { + const h = await createHarness({ MEMBERSHIP_SYNC_TOKEN: SYNC, CLOUD_SETUP_PAGES_URL: 'https://auth.test', SANDBOX_CONTROL_URL: 'https://cp.test' }) + const trials = fakeTrials({ refuse: options.refuseTrial }) + h.setTrial(trials.port) + const sync = { authorization: `Bearer ${SYNC}` } + const personal = { authorization: `Bearer ${await h.desktopToken({ sub: 'u1', email: 'neil@acme.dev' })}` } + const create = async (body: Record = { repo: REPO, needs: ['plan', 'github'], device: 'MacBook Pro' }, auth = personal) => + h.call('POST', '/v1/cloud-setup/sessions', { body, headers: auth }) + const poll = (id: string, auth = personal) => h.call('GET', `/v1/cloud-setup/sessions/${id}`, { headers: auth }) + const pages = { + redeem: (sessionId: string, ticket: string) => h.call('POST', '/v1/internal/cloud-setup/redeem', { body: { sessionId, ticket }, headers: sync }), + read: (id: string, userId = 'u1') => h.call('GET', `/v1/internal/cloud-setup/sessions/${id}?userId=${userId}`, { headers: sync }), + post: (id: string, action: string, body: unknown) => h.call('POST', `/v1/internal/cloud-setup/sessions/${id}/${action}`, { body, headers: sync }) + } + return { h, trials, create, poll, pages, personal } +} + +function ticketOf(url: string): { session: string; ticket: string } { + const parsed = new URL(url) + return { session: parsed.searchParams.get('session')!, ticket: parsed.searchParams.get('ticket')! } +} + +describe('cloud setup sessions', () => { + it('publishes the trial and prices for the pages without auth', async () => { + const { h } = await setup() + const offers = await h.call('GET', '/v1/cloud-setup/offers') + expect(offers.body.trial).toEqual({ includedSeconds: 7200 }) + expect(offers.body.team.monthlyPriceLabel).toMatch(/per seat per month/) + }) + + it('normalizes GitHub repositories', () => { + expect(normalizeRepo('https://github.com/Acme/Web.git/')).toBe('https://github.com/acme/web') + expect(normalizeRepo('git@github.com:acme/web.git')).toBe('https://github.com/acme/web') + expect(normalizeRepo('https://gitlab.com/acme/web')).toBeNull() + }) + + it('chains a new user through team (trial granted), then GitHub, then finishes', async () => { + const { h, trials, create, poll, pages, personal } = await setup() + const created = await create() + expect(created.status).toBe(201) + expect(created.body.id).toMatch(/^cs_[A-Za-z0-9_-]{22}$/) + const { session, ticket } = ticketOf(created.body.url) + expect(created.body.url).toMatch(/^https:\/\/auth\.test\/cloud\/setup\/start\?/) + expect(session).toBe(created.body.id) + + // Personal account: the team step is added (O1) and is the active one. + expect((await poll(session)).body.steps).toEqual([ + { id: 'account', state: 'done' }, + { id: 'team', state: 'active' }, + { id: 'plan', state: 'pending' }, + { id: 'github', state: 'pending' } + ]) + + // The ticket redeems exactly once, and only with the right value. + expect((await pages.redeem(session, 'x'.repeat(43))).status).toBe(404) + expect((await pages.redeem(session, ticket)).body).toEqual({ userId: 'u1' }) + expect((await pages.redeem(session, ticket)).status).toBe(404) + // "Copy setup link" mints a fresh one-time link for another browser. + const link = await h.call('POST', `/v1/cloud-setup/sessions/${session}/link`, { headers: personal }) + expect((await pages.redeem(session, ticketOf(link.body.url).ticket)).body).toEqual({ userId: 'u1' }) + + // Pages read it as the session's user only. + expect((await pages.read(session, 'u2')).status).toBe(404) + const read = await pages.read(session) + expect(read.body).toMatchObject({ ownerHint: 'acme', device: 'MacBook Pro', needs: ['plan', 'github', 'team'] }) + + const bound = await pages.post(session, 'team', { userId: 'u1', orgId: 'o_acme', name: 'acme', created: true, githubOwnerId: 42 }) + expect(bound.body).toEqual({ ok: true, trial: 'granted' }) + expect(trials.grants).toEqual(['org:o_acme']) + const afterTeam = (await poll(session)).body + expect(afterTeam.team).toEqual({ orgId: 'o_acme', name: 'acme', created: true }) + expect(afterTeam.plan).toBe('trial') + expect(afterTeam.trial).toEqual({ includedSeconds: 7200, usedSeconds: 0, exhausted: false }) + expect(afterTeam.steps.map((s: { state: string }) => s.state)).toEqual(['done', 'done', 'done', 'active']) + + // GitHub: the control plane hands out the install URL, then reports the bind. + const seen: string[] = [] + h.setFetch(async (input) => { + seen.push(String(input)) + return Response.json({ access: 'missing', url: 'https://github.com/apps/orca-cloud/installations/new?state=s' }) + }) + const install = await pages.post(session, 'github', { userId: 'u1', githubUserId: 7, githubLogin: 'neil-acme' }) + expect(install.body).toEqual({ access: 'missing', url: 'https://github.com/apps/orca-cloud/installations/new?state=s' }) + const asked = new URL(seen[0]!) + expect(asked.origin + asked.pathname).toBe('https://cp.test/v1/internal/github/install-url') + expect(Object.fromEntries(asked.searchParams)).toEqual({ + accountId: 'org:o_acme', + userId: 'u1', + repo: 'https://github.com/acme/web', + session, + githubUserId: '7', + githubLogin: 'neil-acme' + }) + + const event = await h.controlPlane('/v1/internal/cloud-setup/github', { + sessionId: session, + accountId: 'org:o_acme', + repo: 'https://github.com/Acme/web', + state: 'done' + }) + expect(event.body).toEqual({ ok: true, matched: 1 }) + const finished = (await poll(session)).body + expect(finished.finished).toBe(true) + expect(finished.error).toBeNull() + }) + + it('sends a team whose trial is used up through T3 Checkout that returns to the setup pages', async () => { + const { h, trials, create, poll, pages } = await setup() + trials.trials.set('org:o1', { includedSeconds: 7200, usedSeconds: 7200, exhausted: true }) + const owner = { authorization: `Bearer ${await h.desktopToken({ sub: 'u1', org: 'o1', orgRole: 'owner' })}` } + const created = await create({ needs: ['plan'] }, owner) + const id = created.body.id + // The active team is kept: team done, plan active. + expect((await poll(id, owner)).body.steps).toEqual([ + { id: 'account', state: 'done' }, + { id: 'team', state: 'done' }, + { id: 'plan', state: 'active' } + ]) + expect((await pages.post(id, 'checkout', { userId: 'u1', orgRole: 'member', interval: 'year' })).status).toBe(403) + const checkout = await pages.post(id, 'checkout', { userId: 'u1', orgRole: 'owner', interval: 'year', email: 'a@acme.dev' }) + expect(checkout.status).toBe(200) + const call = h.stripe.calls.find((c) => c.method === 'POST' && c.path === '/v1/checkout/sessions')! + expect(call.form.get('line_items[0][price]')).toBe('price_team_year') + expect(call.form.get('success_url')).toBe(`https://auth.test/cloud/setup/next?session=${id}&from=checkout&checkout=success`) + expect(call.form.get('cancel_url')).toBe(`https://auth.test/cloud/setup/plan?session=${id}&checkout=canceled`) + expect(call.form.get('metadata[setup_session_id]')).toBe(id) + expect((await poll(id, owner)).body.steps[2]).toEqual({ id: 'plan', state: 'active', detail: 'checkout' }) + + // Canceled: the tracker gets checkout_canceled and the plan row fails. + await pages.post(id, 'error', { userId: 'u1', kind: 'checkout_canceled' }) + const canceled = (await poll(id, owner)).body + expect(canceled.error).toEqual({ kind: 'checkout_canceled' }) + expect(canceled.steps[2].state).toBe('failed') + + // Paid: the subscription ends the plan step. + const customer = [...h.stripe.customers.keys()][0]! + const subscription = h.stripe.putSubscription({ + customer, + accountId: 'org:o1', + basePrice: 'price_team_year', + quantity: 1, + periodStart: Math.floor(Date.now() / 1000), + periodEnd: Math.floor(Date.now() / 1000) + 365 * 86400 + }) + await h.webhook(checkoutCompleted({ customer, subscription: subscription.id, accountId: 'org:o1' })) + const paid = (await poll(id, owner)).body + expect(paid.plan).toBe('subscription') + expect(paid.finished).toBe(true) + }) + + it('keeps the plan step when the trial is refused, and never lets another user or team in', async () => { + const { h, create, poll, pages } = await setup({ refuseTrial: true }) + const id = (await create({ needs: ['plan'] })).body.id + expect((await pages.post(id, 'team', { userId: 'u2', orgId: 'o9', name: 'x' })).status).toBe(404) + expect((await pages.post(id, 'team', { userId: 'u1', orgId: 'o1', name: 'acme' })).body).toEqual({ ok: true, trial: 'unavailable' }) + expect((await pages.post(id, 'team', { userId: 'u1', orgId: 'o2', name: 'other' })).status).toBe(409) + // A rename of the same team is fine. + expect((await pages.post(id, 'team', { userId: 'u1', orgId: 'o1', name: 'acme-web' })).status).toBe(200) + expect((await poll(id)).body.team).toEqual({ orgId: 'o1', name: 'acme-web', created: false }) + const stranger = { authorization: `Bearer ${await h.desktopToken({ sub: 'u2' })}` } + expect((await poll(id, stranger)).status).toBe(404) + expect((await h.call('GET', `/v1/cloud-setup/sessions/${id}`)).status).toBe(401) + expect((await h.call('GET', `/v1/internal/cloud-setup/sessions/${id}?userId=u1`, { headers: { authorization: `Bearer ${CONTROL_TOKEN}` } })).status).toBe(401) + }) + + it('reports a stalled session as timed out and expires it after two hours', async () => { + const { h, create, poll } = await setup() + const start = Date.now() + h.setNow(start) + const id = (await create({ needs: ['plan'] })).body.id + h.setNow(start + 16 * 60_000) + expect((await poll(id)).body.error).toEqual({ kind: 'timed_out' }) + h.setNow(start + 2 * 3600_000 + 1) + expect((await poll(id)).status).toBe(404) + }) + + it('rate limits session creation per user', async () => { + const { create } = await setup() + for (let i = 0; i < 20; i++) { + expect((await create({ needs: ['plan'] })).status).toBe(201) + } + expect((await create({ needs: ['plan'] })).status).toBe(429) + }) + + it('matches control-plane GitHub events without a session id on account and repo', async () => { + const { h, create, poll, pages } = await setup() + const id = (await create()).body.id + await pages.post(id, 'team', { userId: 'u1', orgId: 'o1', name: 'acme' }) + expect((await h.controlPlane('/v1/internal/cloud-setup/github', { accountId: 'org:o1', repo: 'https://github.com/acme/web', state: 'pending' })).body).toEqual({ ok: true, matched: 1 }) + expect((await poll(id)).body.steps.at(-1)).toEqual({ id: 'github', state: 'active', detail: 'requested' }) + expect((await h.controlPlane('/v1/internal/cloud-setup/github', { accountId: 'org:o1', repo: 'https://github.com/acme/web', state: 'done' })).body.matched).toBe(1) + // A late 'pending' never undoes 'done'. + expect((await h.controlPlane('/v1/internal/cloud-setup/github', { accountId: 'org:o1', repo: 'https://github.com/acme/web', state: 'pending' })).body.matched).toBe(0) + expect((await h.controlPlane('/v1/internal/cloud-setup/github', { accountId: 'org:o1', repo: 'x', state: 'done' }, 'wrong-token-0123456789abcdef0123456789')).status).toBe(401) + }) +}) + +describe('team-first checkout (O1/N4)', () => { + it('refuses a personal-account Checkout with team_required', async () => { + const h = await createHarness() + const solo = await h.desktopToken({ sub: 'u3' }) + expect(await h.call('POST', '/v1/billing/checkout', { body: { plan: 'team' }, headers: { authorization: `Bearer ${solo}` } })).toEqual({ + status: 409, + body: { error: 'team_required' } + }) + expect(h.stripe.customers.size).toBe(0) + }) + + it('lets the plans dialog join its own setup session only', async () => { + const h = await createHarness({ MEMBERSHIP_SYNC_TOKEN: SYNC, CLOUD_SETUP_PAGES_URL: 'https://auth.test' }) + const owner = { authorization: `Bearer ${await h.desktopToken({ sub: 'u1', org: 'o1', orgRole: 'owner' })}` } + const other = { authorization: `Bearer ${await h.desktopToken({ sub: 'u2', org: 'o1', orgRole: 'owner' })}` } + const id = (await h.call('POST', '/v1/cloud-setup/sessions', { body: { needs: ['plan'] }, headers: owner })).body.id + expect((await h.call('POST', '/v1/billing/checkout', { body: { plan: 'team', setupSessionId: id }, headers: other })).body).toEqual({ + error: 'setup_session_mismatch' + }) + const joined = await h.call('POST', '/v1/billing/checkout', { body: { plan: 'team', setupSessionId: id }, headers: owner }) + expect(joined.status).toBe(200) + const call = h.stripe.calls.find((c) => c.method === 'POST' && c.path === '/v1/checkout/sessions')! + expect(call.form.get('success_url')).toContain(`/cloud/setup/next?session=${id}`) + }) +}) diff --git a/cloud/apps/billing/test/harness.ts b/cloud/apps/billing/test/harness.ts index 1f8b101e799..ecae834688f 100644 --- a/cloud/apps/billing/test/harness.ts +++ b/cloud/apps/billing/test/harness.ts @@ -5,6 +5,7 @@ import { createStripeClient } from '../src/stripe' import type { OrgMemberCheck } from '../src/team-plans' import { createFakeD1 } from './d1-fake' import { createFakeStripe, signStripePayload } from './stripe-fake' +import type { TrialPort } from '../src/cloud-setup-trial' export const WEBHOOK_SECRET = 'whsec_test_local_fixture_secret' export const CONTROL_TOKEN = 'cp_test_0123456789abcdef0123456789abcdef' @@ -35,6 +36,8 @@ export async function createHarness(overrides: Partial = {}) { let membership: (orgId: string) => Promise = async () => null // Auth's live org-member check (cloud start B2); null = auth unavailable (the default). let orgMember: OrgMemberCheck = async () => null + let trial: TrialPort | undefined + let outboundFetch: typeof fetch | undefined const waits: Promise[] = [] const ctx = { waitUntil: (promise: Promise) => waits.push(promise), passThroughOnException() {} } as unknown as ExecutionContext @@ -48,7 +51,9 @@ export async function createHarness(overrides: Partial = {}) { stripe: createStripeClient(env, stripe.fetchImpl), now: () => now, membership: (orgId) => membership(orgId), - orgMember: (orgId, billingToken) => orgMember(orgId, billingToken) + orgMember: (orgId, billingToken) => orgMember(orgId, billingToken), + ...(trial ? { trial } : {}), + ...(outboundFetch ? { fetch: outboundFetch } : {}) }) await Promise.all(waits.splice(0)) return { status: response.status, body: (await response.json()) as Record } @@ -68,6 +73,12 @@ export async function createHarness(overrides: Partial = {}) { setOrgMember(check: OrgMemberCheck) { orgMember = check }, + setTrial(port: TrialPort) { + trial = port + }, + 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 } = {}) { const iat = Math.floor(now / 1000) - (options.ageSeconds ?? 0) return new SignJWT({ ...claims, purpose: options.purpose ?? 'billing' }) diff --git a/cloud/apps/billing/wrangler.dev.jsonc b/cloud/apps/billing/wrangler.dev.jsonc index 9eab816db28..cf472671fa6 100644 --- a/cloud/apps/billing/wrangler.dev.jsonc +++ b/cloud/apps/billing/wrangler.dev.jsonc @@ -38,6 +38,9 @@ // (secret MEMBERSHIP_SYNC_TOKEN must equal staging's ORCA_CLOUD_BILLING_MEMBERSHIP_TOKEN). "BILLING_STAGING_JWKS_URL": "https://auth-staging.onorca.dev/.well-known/jwks.json", "BILLING_STAGING_AUTH_ISSUER": "https://auth-staging.onorca.dev", - "AUTH_INTERNAL_URL": "https://auth-staging.onorca.dev" + "AUTH_INTERNAL_URL": "https://auth-staging.onorca.dev", + // Cloud setup sessions: pages on staging auth, GitHub install URLs from the dev control plane. + "CLOUD_SETUP_PAGES_URL": "https://auth-staging.onorca.dev", + "SANDBOX_CONTROL_URL": "https://orca-sandbox-control-dev.lovecast.workers.dev" } } diff --git a/src/main/billing/billing-client.ts b/src/main/billing/billing-client.ts index 923eccc453c..c6d1d46544d 100644 --- a/src/main/billing/billing-client.ts +++ b/src/main/billing/billing-client.ts @@ -68,7 +68,7 @@ export async function mintBillingToken( return body.data.billingToken } -async function billingRequest( +export async function billingRequest( endpoints: BillingEndpoints, token: string, method: 'GET' | 'POST', @@ -221,7 +221,12 @@ export async function createCheckoutUrl( token, 'POST', 'v1/billing/checkout', - { plan: args.plan, interval: args.interval, seats: args.seats }, + { + plan: args.plan, + interval: args.interval, + seats: args.seats, + ...(args.setupSessionId ? { setupSessionId: args.setupSessionId } : {}) + }, fetchImpl ) return assertStripeHostedUrl(UrlBody.safeParse(body).data?.url) diff --git a/src/main/billing/billing-service.ts b/src/main/billing/billing-service.ts index fea3e4c225a..2a3770c75ff 100644 --- a/src/main/billing/billing-service.ts +++ b/src/main/billing/billing-service.ts @@ -106,6 +106,22 @@ function prepare(userDataPath: string): Ready { } } +/** + * Runs one billing-service call with a fresh billing token for the active profile (cloud setup + * uses it for its session calls). 'signed-out' when there is no usable Orca session. + */ +export async function withBillingToken( + userDataPath: string, + call: (token: string, endpoints: BillingEndpoints) => Promise +): Promise<{ status: 'ok'; value: T } | { status: 'unconfigured' | 'signed-out' }> { + const ready = prepare(userDataPath) + if (!ready.ok) { + return { status: ready.status } + } + const value = await ready.run(call) + return value === 'signed-out' ? { status: 'signed-out' } : { status: 'ok', value } +} + const message = (error: unknown): string => (error instanceof Error ? error.message : String(error)) export async function getOrcaBillingStatus(userDataPath: string): Promise { @@ -152,6 +168,9 @@ function openResultForError(error: unknown): OrcaBillingOpenResult { if (error.errorCode === 'no_billing_account') { return { status: 'no-billing-account' } } + if (error.errorCode === 'team_required') { + return { status: 'team-required' } + } } return { status: 'failed', error: message(error) } } @@ -183,11 +202,25 @@ async function openHosted( } } -export function openOrcaBillingCheckout( +export async function openOrcaBillingCheckout( userDataPath: string, args: OrcaBillingCheckoutArgs ): Promise { - return openHosted(userDataPath, (token, endpoints) => createCheckoutUrl(endpoints, token, args)) + const result = await openHosted(userDataPath, (token, endpoints) => + createCheckoutUrl(endpoints, token, args) + ) + // A setup session for another team or user (or an expired one) must not block buying. + if ( + args.setupSessionId && + result.status === 'failed' && + /setup_session_mismatch/.test(result.error) + ) { + const { setupSessionId: _dropped, ...plain } = args + return openHosted(userDataPath, (token, endpoints) => + createCheckoutUrl(endpoints, token, plain) + ) + } + return result } export function openOrcaBillingPortal(userDataPath: string): Promise { diff --git a/src/main/billing/cloud-setup-service.test.ts b/src/main/billing/cloud-setup-service.test.ts new file mode 100644 index 00000000000..cd0cec0b9aa --- /dev/null +++ b/src/main/billing/cloud-setup-service.test.ts @@ -0,0 +1,104 @@ +import { describe, expect, it, vi } from 'vitest' + +vi.mock('electron', () => ({ app: { isPackaged: false }, shell: { openExternal: vi.fn() } })) + +import { + createSetupSessionRequest, + getSetupSessionRequest, + setupDeviceLabel +} from './cloud-setup-service' +import { cloudSetupStartArgsFromUnknown } from '../ipc/profiles/orca-profile-billing-handlers' + +const endpoints = { + billingApiUrl: 'https://billing.test', + billingTokenEndpoint: 'https://auth.test/t' +} +const ID = 'cs_AAAAAAAAAAAAAAAAAAAAAA' + +function fakeFetch(body: unknown, status = 200) { + const calls: { url: string; init: RequestInit }[] = [] + const impl: typeof fetch = async (url, init) => { + calls.push({ url: String(url), init: init ?? {} }) + return new Response(JSON.stringify(body), { status }) + } + return { impl, calls } +} + +describe('cloud setup service', () => { + it('creates a session with the billing token and returns its one-tab URL', async () => { + const { impl, calls } = fakeFetch({ + id: ID, + url: `https://auth-staging.onorca.dev/cloud/setup/start?session=${ID}&ticket=t`, + expiresAt: 1 + }) + const created = await createSetupSessionRequest( + endpoints, + 'tok', + { + repo: 'https://github.com/acme/web', + needs: ['plan', 'github'], + device: 'MacBook Pro', + useActiveTeam: true + }, + impl + ) + expect(created.id).toBe(ID) + expect(calls[0]!.url).toBe('https://billing.test/v1/cloud-setup/sessions') + expect(JSON.parse(String(calls[0]!.init.body))).toEqual({ + repo: 'https://github.com/acme/web', + needs: ['plan', 'github'], + device: 'MacBook Pro', + useActiveTeam: true + }) + expect(new Headers(calls[0]!.init.headers).get('authorization')).toBe('Bearer tok') + }) + + it('refuses a session URL that is not https', async () => { + const { impl } = fakeFetch({ id: ID, url: 'http://evil.test/x', expiresAt: 1 }) + await expect( + createSetupSessionRequest( + endpoints, + 'tok', + { needs: ['plan'], device: 'x', useActiveTeam: true }, + impl + ) + ).rejects.toThrow('invalid_setup_session') + }) + + it('reads steps, team, trial and errors, dropping unknown error kinds', async () => { + const { impl } = fakeFetch({ + id: ID, + steps: [ + { id: 'account', state: 'done' }, + { id: 'team', state: 'done', detail: 'acme' }, + { id: 'plan', state: 'failed' } + ], + team: { orgId: 'org_1', name: 'acme', created: true }, + trial: null, + plan: null, + finished: false, + error: { kind: 'something_new' }, + expiresAt: 5 + }) + const session = await getSetupSessionRequest(endpoints, 'tok', ID, impl) + expect(session.steps).toHaveLength(3) + expect(session.team).toEqual({ orgId: 'org_1', name: 'acme', created: true }) + expect(session.error).toBeNull() + }) + + it('labels the device from the host name', () => { + expect(setupDeviceLabel('Neils-MacBook-Pro.local')).toBe('Neils MacBook Pro') + expect(setupDeviceLabel('')).toBe('this computer') + }) + + it('validates start args from the renderer', () => { + expect(cloudSetupStartArgsFromUnknown({ needs: ['team', 'plan'], chooseTeam: true })).toEqual({ + needs: ['team', 'plan'], + chooseTeam: true + }) + expect(() => + cloudSetupStartArgsFromUnknown({ needs: ['team'], repo: 'https://gitlab.com/a/b' }) + ).toThrow() + expect(() => cloudSetupStartArgsFromUnknown({ needs: ['bogus'] })).toThrow() + }) +}) diff --git a/src/main/billing/cloud-setup-service.ts b/src/main/billing/cloud-setup-service.ts new file mode 100644 index 00000000000..c0119923a66 --- /dev/null +++ b/src/main/billing/cloud-setup-service.ts @@ -0,0 +1,240 @@ +// Orca Cloud setup session (NP-4 N1), desktop side. "Set up and start" opens ONE browser tab: +// - signed out: the sign-in tab shows the setup account page (A2); once the code is exchanged, +// the session is created and the same tab continues to the setup pages; +// - signed in: the session is created and its start URL is opened. +// The composer then polls getCloudSetupSession until every step is done. +import { appendFile } from 'node:fs/promises' +import { hostname } from 'node:os' +import { app, shell } from 'electron' +import { z } from 'zod' +import { + CLOUD_SETUP_ERROR_KINDS, + CLOUD_SETUP_SESSION_ID, + type CloudSetupGetResult, + type CloudSetupLinkResult, + type CloudSetupNeed, + type CloudSetupSession, + type CloudSetupStartArgs, + type CloudSetupStartResult +} from '../../shared/orca-cloud-setup' +import { connectCurrentOrcaProfile } from '../orca-profiles/profile-cloud-service' +import { billingRequest, BillingServiceError, type BillingEndpoints } from './billing-client' +import { withBillingToken } from './billing-service' + +const CreatedBody = z.object({ + id: z.string().regex(CLOUD_SETUP_SESSION_ID), + url: z.string().url().startsWith('https://'), + expiresAt: z.number() +}) + +const StepBody = z.object({ + id: z.enum(['account', 'team', 'plan', 'github']), + state: z.enum(['done', 'needed', 'active', 'pending', 'failed', 'optional']), + detail: z.string().max(200).optional() +}) + +const SessionBody = z.object({ + id: z.string().regex(CLOUD_SETUP_SESSION_ID), + steps: z.array(StepBody).max(8), + team: z + .object({ + orgId: z.string().max(128), + name: z.string().max(200).nullable(), + created: z.boolean() + }) + .nullable() + .catch(null), + trial: z + .object({ includedSeconds: z.number(), usedSeconds: z.number(), exhausted: z.boolean() }) + .nullable() + .catch(null), + plan: z.enum(['subscription', 'trial']).nullable().catch(null), + finished: z.boolean(), + error: z + .object({ kind: z.enum(CLOUD_SETUP_ERROR_KINDS), detail: z.string().max(320).optional() }) + .nullable() + .catch(null), + expiresAt: z.number() +}) + +/** What this Mac is called on the setup page ("Orca on MacBook Pro is waiting for you"). */ +export function setupDeviceLabel(name = hostname()): string { + return ( + name + .replace(/\.local$/i, '') + .replace(/[-_]+/g, ' ') + .trim() + .slice(0, 80) || 'this computer' + ) +} + +export async function createSetupSessionRequest( + endpoints: BillingEndpoints, + token: string, + body: { repo?: string; needs: CloudSetupNeed[]; device: string; useActiveTeam: boolean }, + fetchImpl: typeof fetch = fetch +): Promise> { + const created = CreatedBody.safeParse( + await billingRequest(endpoints, token, 'POST', 'v1/cloud-setup/sessions', body, fetchImpl) + ) + if (!created.success) { + throw new Error('invalid_setup_session') + } + return created.data +} + +export async function getSetupSessionRequest( + endpoints: BillingEndpoints, + token: string, + sessionId: string, + fetchImpl: typeof fetch = fetch +): Promise { + const session = SessionBody.safeParse( + await billingRequest( + endpoints, + token, + 'GET', + `v1/cloud-setup/sessions/${sessionId}`, + undefined, + fetchImpl + ) + ) + if (!session.success) { + throw new Error('invalid_setup_session') + } + return session.data +} + +async function openInBrowser(url: string): Promise { + // Dev automation only: hand the URL to a test driver instead of the user's browser. + const devUrlFile = app.isPackaged + ? '' + : (process.env.ORCA_BILLING_DEV_OPEN_URL_FILE?.trim() ?? '') + await (devUrlFile ? appendFile(devUrlFile, `${url}\n`, { mode: 0o600 }) : shell.openExternal(url)) +} + +const message = (error: unknown): string => (error instanceof Error ? error.message : String(error)) + +export async function startCloudSetup( + userDataPath: string, + args: CloudSetupStartArgs +): Promise { + const device = setupDeviceLabel() + const body = { + ...(args.repo ? { repo: args.repo } : {}), + needs: args.needs, + device, + useActiveTeam: !args.chooseTeam + } + const create = (): ReturnType>> => + withBillingToken(userDataPath, (token, endpoints) => + createSetupSessionRequest(endpoints, token, body) + ) + try { + const signedIn = await create() + if (signedIn.status === 'ok') { + await openInBrowser(signedIn.value.url) + return { status: 'opened', sessionId: signedIn.value.id, expiresAt: signedIn.value.expiresAt } + } + if (signedIn.status === 'unconfigured') { + return { status: 'unconfigured' } + } + // Signed out: one tab signs in and then carries on into setup. + // Filled in by afterSignIn, inside the sign-in flow. + const outcome: { created: z.infer | null; error: unknown } = { + created: null, + error: null + } + const connected = await connectCurrentOrcaProfile(userDataPath, { + authorizeParams: { + setup: '1', + device, + // New users skip the team page (made for them), so only plan/GitHub are announced. + setup_steps: args.needs.filter((need) => need !== 'team').join(',') + }, + afterSignIn: async () => { + try { + const result = await create() + outcome.created = result.status === 'ok' ? result.value : null + } catch (error) { + outcome.error = error + } + return outcome.created?.url ?? null + } + }) + if (connected.status === 'cancelled' || connected.status === 'timed-out') { + return { status: 'cancelled' } + } + if (connected.status !== 'connected') { + return connected.status === 'unconfigured' + ? { status: 'unconfigured' } + : { status: 'failed', error: connected.error } + } + const session = outcome.created + if (!session) { + return { + status: 'failed', + error: outcome.error ? message(outcome.error) : 'setup_session_unavailable' + } + } + return { status: 'opened', sessionId: session.id, expiresAt: session.expiresAt } + } catch (error) { + return { status: 'failed', error: message(error) } + } +} + +export async function getCloudSetupSession( + userDataPath: string, + sessionId: string +): Promise { + if (!CLOUD_SETUP_SESSION_ID.test(sessionId)) { + return { status: 'not-found' } + } + try { + const result = await withBillingToken(userDataPath, (token, endpoints) => + getSetupSessionRequest(endpoints, token, sessionId) + ) + return result.status === 'ok' ? { status: 'ok', session: result.value } : result + } catch (error) { + if (error instanceof BillingServiceError && error.statusCode === 404) { + return { status: 'not-found' } + } + return { status: 'failed', error: message(error) } + } +} + +const LinkBody = z.object({ url: z.string().url().startsWith('https://') }) + +/** "Copy setup link": a fresh one-time link to the same session, for a different browser. */ +export async function getCloudSetupLink( + userDataPath: string, + sessionId: string +): Promise { + if (!CLOUD_SETUP_SESSION_ID.test(sessionId)) { + return { status: 'not-found' } + } + try { + const result = await withBillingToken(userDataPath, async (token, endpoints) => { + const body = LinkBody.safeParse( + await billingRequest( + endpoints, + token, + 'POST', + `v1/cloud-setup/sessions/${sessionId}/link`, + {}, + fetch + ) + ) + if (!body.success) { + throw new Error('invalid_setup_link') + } + return body.data.url + }) + return result.status === 'ok' ? { status: 'ok', url: result.value } : result + } catch (error) { + if (error instanceof BillingServiceError && error.statusCode === 404) { + return { status: 'not-found' } + } + 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 cce8468ceb6..0a525ef4626 100644 --- a/src/main/ipc/profiles/orca-profile-billing-handlers.ts +++ b/src/main/ipc/profiles/orca-profile-billing-handlers.ts @@ -26,12 +26,26 @@ import { ensureActiveOrcaProfile } from '../../orca-profiles/profile-index-store import { notifyUsageAlertIfDue } from '../../billing/usage-alert-notifier' import { showUsageAlertNotification, usageAlertBody } from '../../billing/usage-alert-desktop' import type { Store } from '../../persistence/loading-store/store' +import { + CLOUD_SETUP_NEEDS, + CLOUD_SETUP_SESSION_ID, + type CloudSetupGetResult, + type CloudSetupLinkResult, + type CloudSetupStartArgs, + type CloudSetupStartResult +} from '../../../shared/orca-cloud-setup' +import { + getCloudSetupLink, + getCloudSetupSession, + startCloudSetup +} from '../../billing/cloud-setup-service' const CheckoutArgs = z .object({ plan: z.enum(ORCA_BILLING_PLAN_IDS), interval: z.enum(ORCA_BILLING_INTERVALS), - seats: z.number().int().min(1).max(ORCA_BILLING_MAX_SEATS) + seats: z.number().int().min(1).max(ORCA_BILLING_MAX_SEATS), + setupSessionId: z.string().regex(CLOUD_SETUP_SESSION_ID).optional() }) .strict() @@ -65,6 +79,24 @@ export function billingTeamPlansArgsFromUnknown(args: unknown): { orgIds: string return { orgIds: [...new Set(parsed.data.orgIds)] } } +const CloudSetupStart = z + .object({ + repo: z.string().url().startsWith('https://github.com/').max(300).optional(), + needs: z.array(z.enum(CLOUD_SETUP_NEEDS)).max(3), + chooseTeam: z.boolean().optional() + }) + .strict() + +const CloudSetupGet = z.object({ sessionId: z.string().regex(CLOUD_SETUP_SESSION_ID) }).strict() + +export function cloudSetupStartArgsFromUnknown(args: unknown): CloudSetupStartArgs { + const parsed = CloudSetupStart.safeParse(args) + if (!parsed.success) { + throw new Error('invalid_cloud_setup_start') + } + return parsed.data +} + export function billingCheckoutArgsFromUnknown(args: unknown): OrcaBillingCheckoutArgs { const parsed = CheckoutArgs.safeParse(args) if (!parsed.success) { @@ -122,6 +154,29 @@ export function registerOrcaProfileBillingHandlers(store: Store): void { billingTeamPlansArgsFromUnknown(rawArgs).orgIds ) ) + ipcMain.handle( + 'orcaProfiles:cloudSetupStart', + async (_event, rawArgs: unknown): Promise => + startCloudSetup(getProfileUserDataPath(), cloudSetupStartArgsFromUnknown(rawArgs)) + ) + ipcMain.handle( + 'orcaProfiles:cloudSetupGet', + async (_event, rawArgs: unknown): Promise => { + const parsed = CloudSetupGet.safeParse(rawArgs) + return parsed.success + ? getCloudSetupSession(getProfileUserDataPath(), parsed.data.sessionId) + : { status: 'not-found' } + } + ) + ipcMain.handle( + 'orcaProfiles:cloudSetupLink', + async (_event, rawArgs: unknown): Promise => { + const parsed = CloudSetupGet.safeParse(rawArgs) + return parsed.success + ? getCloudSetupLink(getProfileUserDataPath(), parsed.data.sessionId) + : { status: 'not-found' } + } + ) ipcMain.handle('orcaProfiles:billingOpenPortal', async (): Promise => openOrcaBillingPortal(getProfileUserDataPath()) ) diff --git a/src/main/orca-profiles/profile-cloud-pkce.test.ts b/src/main/orca-profiles/profile-cloud-pkce.test.ts new file mode 100644 index 00000000000..ca13f97a480 --- /dev/null +++ b/src/main/orca-profiles/profile-cloud-pkce.test.ts @@ -0,0 +1,78 @@ +import { mkdtempSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' + +vi.mock('electron', () => ({ app: { isPackaged: false }, shell: { openExternal: vi.fn() } })) + +import type { OrcaCloudAuthConfig } from './profile-cloud-auth-config' +import { beginOrcaCloudPkceFlow } from './profile-cloud-pkce' + +const base = 'https://auth.test' +const config: OrcaCloudAuthConfig = { + apiBaseUrl: base, + authorizeEndpoint: `${base}/v1/desktop/auth/authorize`, + sessionEndpoint: `${base}/s`, + refreshEndpoint: `${base}/r`, + capabilitiesEndpoint: `${base}/c`, + profileEndpoint: `${base}/p`, + orgEndpoint: `${base}/o`, + logoutEndpoint: `${base}/l`, + relayTokenEndpoint: `${base}/rt`, + connectorTokenEndpoint: `${base}/ct`, + relayDirectorUrl: base, + clientId: 'orca-desktop', + scope: 'openid' +} + +afterEach(() => { + delete process.env.ORCA_CLOUD_DEV_OPEN_URL_FILE +}) + +describe('PKCE loopback for cloud setup', () => { + it('adds the setup parameters and holds the tab until setup says where it goes next', async () => { + process.env.ORCA_CLOUD_DEV_OPEN_URL_FILE = join(mkdtempSync(join(tmpdir(), 'pkce-')), 'urls') + let authorize = '' + const flow = beginOrcaCloudPkceFlow(config, 'profile-1', { + onAuthorizeUrl: (url) => (authorize = url), + authorizeParams: { setup: '1', device: 'MacBook Pro', setup_steps: 'github' }, + holdBrowser: true + }) + await vi.waitFor(() => expect(authorize).not.toBe('')) + const url = new URL(authorize) + expect(url.searchParams.get('setup')).toBe('1') + expect(url.searchParams.get('device')).toBe('MacBook Pro') + expect(url.searchParams.get('setup_steps')).toBe('github') + + const callback = new URL(url.searchParams.get('redirect_uri')!) + callback.searchParams.set('code', 'the-code') + callback.searchParams.set('state', url.searchParams.get('state')!) + const browser = fetch(callback, { redirect: 'manual' }) + const code = await flow + expect(code.code).toBe('the-code') + expect(code.finishBrowser).toBeTypeOf('function') + code.finishBrowser!('https://auth.test/cloud/setup/start?session=cs_x&ticket=t') + const response = await browser + expect(response.status).toBe(302) + expect(response.headers.get('location')).toBe( + 'https://auth.test/cloud/setup/start?session=cs_x&ticket=t' + ) + }) + + it('shows the signed-in page when setup has nowhere to go (or an unsafe URL)', async () => { + process.env.ORCA_CLOUD_DEV_OPEN_URL_FILE = join(mkdtempSync(join(tmpdir(), 'pkce-')), 'urls') + let authorize = '' + const flow = beginOrcaCloudPkceFlow(config, 'profile-1', { + onAuthorizeUrl: (url) => (authorize = url), + holdBrowser: true + }) + await vi.waitFor(() => expect(authorize).not.toBe('')) + const url = new URL(authorize) + const callback = new URL(url.searchParams.get('redirect_uri')!) + callback.searchParams.set('code', 'c') + callback.searchParams.set('state', url.searchParams.get('state')!) + const browser = fetch(callback, { redirect: 'manual' }) + ;(await flow).finishBrowser!('javascript:alert(1)') + expect((await browser).status).toBe(200) + }) +}) diff --git a/src/main/orca-profiles/profile-cloud-pkce.ts b/src/main/orca-profiles/profile-cloud-pkce.ts index 3bd183a06ce..be85d68036f 100644 --- a/src/main/orca-profiles/profile-cloud-pkce.ts +++ b/src/main/orca-profiles/profile-cloud-pkce.ts @@ -14,8 +14,16 @@ export type OrcaCloudAuthorizationCode = { nonce: string redirectUri: string state: string + /** + * Only with `holdBrowser`: finishes the browser tab, either sending it on to `location` (cloud + * setup continues in the same tab) or showing the usual "signed in" page when null. + */ + finishBrowser?: (location: string | null) => void } +/** How long a held browser tab waits for the caller before it gets the "signed in" page. */ +const HOLD_BROWSER_MS = 30_000 + const AUTH_TIMEOUT_MS = 5 * 60 * 1000 function base64Url(buffer: Buffer): string { @@ -43,7 +51,14 @@ function closeServer(server: Server): void { export function beginOrcaCloudPkceFlow( config: OrcaCloudAuthConfig, localProfileId: string, - options: { onAuthorizeUrl?: (url: string) => void; signal?: AbortSignal } = {} + options: { + onAuthorizeUrl?: (url: string) => void + signal?: AbortSignal + /** Extra authorize parameters (cloud setup: setup=1, device, setup_steps). */ + authorizeParams?: Record + /** Keep the browser's callback request open until the caller calls finishBrowser. */ + holdBrowser?: boolean + } = {} ): Promise { const codeVerifier = createCodeVerifier() const nonce = base64Url(randomBytes(32)) @@ -62,19 +77,35 @@ export function beginOrcaCloudPkceFlow( closeServer(server) } - function resolveFlow(code: string): void { + function resolveFlow(code: string, held?: ServerResponse): void { if (settled) { return } settled = true - resolve({ - code, - codeVerifier, - nonce, - redirectUri, - state - }) - closeServer(server) + if (!held) { + resolve({ code, codeVerifier, nonce, redirectUri, state }) + closeServer(server) + return + } + let finished = false + const finishBrowser = (location: string | null): void => { + if (finished) { + return + } + finished = true + clearTimeout(holdTimer) + // Only an https page may follow a sign-in in the same tab. + if (location && location.startsWith('https://')) { + held.writeHead(302, { location, 'cache-control': 'no-store' }) + held.end() + } else { + held.writeHead(200, ORCA_CLOUD_CALLBACK_RESPONSE_HEADERS) + held.end(ORCA_CLOUD_CALLBACK_SUCCESS_PAGE) + } + closeServer(server) + } + const holdTimer = setTimeout(() => finishBrowser(null), HOLD_BROWSER_MS) + resolve({ code, codeVerifier, nonce, redirectUri, state, finishBrowser }) } function writeInvalidCallback(response: ServerResponse): void { @@ -114,6 +145,10 @@ export function beginOrcaCloudPkceFlow( writeInvalidCallback(response) return } + if (options.holdBrowser) { + resolveFlow(code, response) + return + } response.writeHead(200, ORCA_CLOUD_CALLBACK_RESPONSE_HEADERS) response.end(ORCA_CLOUD_CALLBACK_SUCCESS_PAGE) resolveFlow(code) @@ -149,6 +184,9 @@ export function beginOrcaCloudPkceFlow( authorizeUrl.searchParams.set('code_challenge', createCodeChallenge(codeVerifier)) authorizeUrl.searchParams.set('code_challenge_method', 'S256') authorizeUrl.searchParams.set('local_profile_id', localProfileId) + for (const [key, value] of Object.entries(options.authorizeParams ?? {})) { + authorizeUrl.searchParams.set(key, value) + } options.onAuthorizeUrl?.(authorizeUrl.toString()) // Dev automation only (unpackaged): hand the sign-in URL to a test driver instead of // opening the developer's own browser. Same pattern as ORCA_BILLING_DEV_OPEN_URL_FILE. diff --git a/src/main/orca-profiles/profile-cloud-service.ts b/src/main/orca-profiles/profile-cloud-service.ts index b5b6b097f65..4bd70e0412f 100644 --- a/src/main/orca-profiles/profile-cloud-service.ts +++ b/src/main/orca-profiles/profile-cloud-service.ts @@ -67,8 +67,18 @@ export function getCurrentOrcaProfileAuthStatus(userDataPath: string): OrcaProfi return getOrcaProfileAuthStatusFromProfile(ensureActiveOrcaProfile(userDataPath), userDataPath) } +/** + * Cloud setup sign-in: the authorize page shows the setup account step (A2), and once signed in + * the same browser tab continues to whatever `afterSignIn` returns (the setup session's URL). + */ +export type OrcaCloudSetupSignIn = { + authorizeParams: Record + afterSignIn: () => Promise +} + export async function connectCurrentOrcaProfile( - userDataPath: string + userDataPath: string, + setup?: OrcaCloudSetupSignIn ): Promise { const active = ensureActiveOrcaProfile(userDataPath) if (isOrcaCloudDevAuthEnabled()) { @@ -92,11 +102,14 @@ export async function connectCurrentOrcaProfile( const attempt = ++nextCloudConnectAttempt const browserWait = new AbortController() startOrcaCloudSignInProgress(attempt, () => browserWait.abort()) + let finishBrowser: ((location: string | null) => void) | undefined try { const code = await beginOrcaCloudPkceFlow(configState.config, active.profile.id, { signal: browserWait.signal, - onAuthorizeUrl: (link) => setOrcaCloudSignInLink(attempt, link) + onAuthorizeUrl: (link) => setOrcaCloudSignInLink(attempt, link), + ...(setup ? { authorizeParams: setup.authorizeParams, holdBrowser: true } : {}) }) + finishBrowser = code.finishBrowser // The callback listener has closed, so its browser link is dead. setOrcaCloudSignInLink(attempt, null) if (attempt < linkedCloudConnectAttempt) { @@ -106,7 +119,11 @@ export async function connectCurrentOrcaProfile( } } const exchange = await exchangeOrcaCloudAuthCode(configState.config, { - ...code, + code: code.code, + codeVerifier: code.codeVerifier, + nonce: code.nonce, + redirectUri: code.redirectUri, + state: code.state, localProfileId: active.profile.id }) if (attempt < linkedCloudConnectAttempt) { @@ -118,6 +135,11 @@ export async function connectCurrentOrcaProfile( signInCloudSession(active.profile.id, userDataPath, exchange) const list = linkOrcaProfileToCloud(active.profile.id, exchange.cloud, userDataPath) linkedCloudConnectAttempt = attempt + if (setup && finishBrowser) { + const next = await setup.afterSignIn().catch(() => null) + finishBrowser(next) + finishBrowser = undefined + } return { status: 'connected', auth: getCurrentOrcaProfileAuthStatus(userDataPath), @@ -148,6 +170,7 @@ export async function connectCurrentOrcaProfile( error: message } } finally { + finishBrowser?.(null) endOrcaCloudSignInProgress(attempt) } } diff --git a/src/preload/api/orca-profile-api.ts b/src/preload/api/orca-profile-api.ts index 3b1ef33ae6b..13153e061ca 100644 --- a/src/preload/api/orca-profile-api.ts +++ b/src/preload/api/orca-profile-api.ts @@ -1,3 +1,9 @@ +import type { + CloudSetupGetResult, + CloudSetupLinkResult, + CloudSetupStartArgs, + CloudSetupStartResult +} from '../../shared/orca-cloud-setup' import type { OrcaProfileOrgCreateArgs, OrcaProfileOrgCreateResult, @@ -95,6 +101,12 @@ export type OrcaProfileApi = { billingStatus: () => Promise /** Opens hosted Stripe Checkout in the browser. */ billingOpenCheckout: (args: OrcaBillingCheckoutArgs) => Promise + /** Starts Orca Cloud setup: one browser tab for sign-in, team, plan and GitHub. */ + cloudSetupStart: (args: CloudSetupStartArgs) => Promise + /** The setup session's steps, for the composer's setup panel. */ + cloudSetupGet: (args: { sessionId: string }) => Promise + /** "Copy setup link": a fresh one-time link to the same setup session. */ + cloudSetupLink: (args: { sessionId: string }) => Promise /** Opens the Stripe Customer Portal in the browser. */ billingOpenPortal: () => Promise /** Plan state for other teams the user is on ("Switch to "); never switches teams. */ diff --git a/src/preload/api/orca-profiles-bridge.ts b/src/preload/api/orca-profiles-bridge.ts index ca59a6514d5..797cd845f8d 100644 --- a/src/preload/api/orca-profiles-bridge.ts +++ b/src/preload/api/orca-profiles-bridge.ts @@ -87,5 +87,8 @@ export const orcaProfilesApi = { billingOpenCheckout: (args) => ipcRenderer.invoke('orcaProfiles:billingOpenCheckout', args), billingOpenPortal: () => ipcRenderer.invoke('orcaProfiles:billingOpenPortal'), billingTeamPlans: (args) => ipcRenderer.invoke('orcaProfiles:billingTeamPlans', args), + 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) } satisfies PreloadApi['orcaProfiles'] diff --git a/src/renderer/src/components/billing/checkout/use-checkout-flow.ts b/src/renderer/src/components/billing/checkout/use-checkout-flow.ts index ef6d1900244..753c6b2afff 100644 --- a/src/renderer/src/components/billing/checkout/use-checkout-flow.ts +++ b/src/renderer/src/components/billing/checkout/use-checkout-flow.ts @@ -2,6 +2,10 @@ import { useCallback, useEffect, useRef, useState } from 'react' import type { OrcaBillingOpenResult } from '../../../../../shared/orca-billing' import { getBillingGeneration, recordBillingStatusIfCurrent } from '../billing-summary-store' import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval' +import { + activeCloudSetupSessionId, + startCloudSetupSession +} from '@/lib/orca-cloud/cloud-setup-session' import { CHECKOUT_POLL_MS, CHECKOUT_SLOW_POLL_MS, @@ -42,12 +46,28 @@ export function useCheckoutFlow({ onPaid }: { onPaid: (seats: number) => void }) const start = useCallback((order: CheckoutOrder) => { const id = ++runId.current setPhase({ kind: 'opening', order }) + // Joins an open setup session, so Checkout returns to its next step (T2 Compare plans). + const setupSessionId = activeCloudSetupSessionId() void window.api.orcaProfiles - .billingOpenCheckout({ plan: 'team', interval: order.interval, seats: order.seats }) + .billingOpenCheckout({ + plan: 'team', + interval: order.interval, + seats: order.seats, + ...(setupSessionId ? { setupSessionId } : {}) + }) .catch((error: unknown): OrcaBillingOpenResult => ({ status: 'failed', error: String(error) })) + .then(async (result): Promise => { + if (result.status !== 'team-required') { + return result + } + // O1: a plan always lands on a team. The browser makes or picks the team, then Checkout; + // the setup session switches this profile to that team when it's there. + const started = await startCloudSetupSession({ needs: ['team', 'plan'], chooseTeam: true }) + return started ? { status: 'opened' } : result + }) .then((result) => { if (id === runId.current) { setPhase(nextPhaseAfterOpen(order, result, Date.now())) diff --git a/src/renderer/src/components/billing/plan-billing-copy.ts b/src/renderer/src/components/billing/plan-billing-copy.ts index df35f015606..8dc87f0e4f5 100644 --- a/src/renderer/src/components/billing/plan-billing-copy.ts +++ b/src/renderer/src/components/billing/plan-billing-copy.ts @@ -97,6 +97,11 @@ export function openFailureCopy(result: OrcaBillingOpenResult, t: Translate): st 'auto.components.billing.openAlreadySubscribed', 'This account already has a plan. Use Manage billing to change it.' ) + case 'team-required': + return t( + 'auto.components.billing.openTeamRequired', + 'Plans belong to a team. Create a team, then choose a plan.' + ) case 'no-billing-account': return t( 'auto.components.billing.openNoAccount', diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index c480d52a29a..4bbdb126632 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -20700,6 +20700,7 @@ "capUsedLabel": "Overage spend cap used", "enterpriseContactSales": "Contact sales", "openForbidden2": "Only an owner or admin can manage billing.", + "openTeamRequired": "Plans belong to a team. Create a team, then choose a plan.", "openSignedOut2": "Sign in to Orca again to manage your team.", "overageDescription7": "Optional overage at {{rate}} per sandbox hour, billed by the minute, up to a monthly spend cap you set ({{cap}} by default).", "overageMemberHint": "Owners and admins can change overage.", diff --git a/src/renderer/src/lib/orca-cloud/cloud-setup-session.test.ts b/src/renderer/src/lib/orca-cloud/cloud-setup-session.test.ts new file mode 100644 index 00000000000..0a0c7c08411 --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/cloud-setup-session.test.ts @@ -0,0 +1,136 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const selectOrcaProfileOrg = vi.hoisted(() => vi.fn(async () => undefined)) +const storeState = vi.hoisted(() => ({ + orcaProfileAuthStatus: { cloud: { activeOrgId: undefined as string | undefined } }, + selectOrcaProfileOrg +})) +vi.mock('@/store', () => ({ useAppStore: { getState: () => storeState } })) + +import type { CloudSetupSession } from '../../../../shared/orca-cloud-setup' +import { + SETUP_FAST_POLL_MS, + activeCloudSetupSessionId, + getCloudSetupSnapshot, + refreshCloudSetupSession, + resetCloudSetupSessionsForTests, + snapshotFromSession, + startCloudSetupSession, + subscribeCloudSetupSessions +} from './cloud-setup-session' + +const ID = 'cs_AAAAAAAAAAAAAAAAAAAAAA' + +function session(overrides: Partial = {}): CloudSetupSession { + return { + id: ID, + steps: [ + { id: 'account', state: 'done' }, + { id: 'team', state: 'active' }, + { id: 'github', state: 'pending' } + ], + team: null, + trial: null, + plan: null, + finished: false, + error: null, + expiresAt: Date.now() + 3600_000, + ...overrides + } +} + +const cloudSetupStart = vi.fn() +const cloudSetupGet = vi.fn() + +beforeEach(() => { + vi.useFakeTimers() + cloudSetupStart.mockReset() + cloudSetupGet.mockReset() + selectOrcaProfileOrg.mockClear() + storeState.orcaProfileAuthStatus.cloud.activeOrgId = undefined + vi.stubGlobal( + 'window', + Object.assign(globalThis, { api: { orcaProfiles: { cloudSetupStart, cloudSetupGet } } }) + ) +}) + +afterEach(() => { + resetCloudSetupSessionsForTests() + vi.useRealTimers() +}) + +describe('cloud setup session (renderer)', () => { + it('maps a session to panel rows with the team name as detail', () => { + const snapshot = snapshotFromSession( + session({ + steps: [ + { id: 'account', state: 'done' }, + { id: 'team', state: 'done' }, + { id: 'plan', state: 'done', detail: 'trial' } + ], + team: { orgId: 'org_1', name: 'acme', created: true }, + finished: true + }) + ) + expect(snapshot.steps).toEqual([ + { id: 'account', state: 'done' }, + { id: 'team', state: 'done', detail: 'acme' }, + { id: 'plan', state: 'done', detail: 'trial' } + ]) + expect(snapshot.finished).toBe(true) + expect(snapshot.error).toBeUndefined() + }) + + it('starts, polls every 2 s, follows the new team, and stops when finished', async () => { + cloudSetupStart.mockResolvedValue({ status: 'opened', sessionId: ID, expiresAt: 0 }) + cloudSetupGet.mockResolvedValueOnce({ status: 'ok', session: session() }) + const seen: string[] = [] + subscribeCloudSetupSessions((id) => seen.push(id)) + + expect( + await startCloudSetupSession({ repo: 'https://github.com/acme/web', needs: ['github'] }) + ).toEqual({ + sessionId: ID + }) + expect(cloudSetupStart).toHaveBeenCalledWith({ + repo: 'https://github.com/acme/web', + needs: ['github'] + }) + await vi.advanceTimersByTimeAsync(0) + expect(getCloudSetupSnapshot(ID)?.steps[1]).toEqual({ id: 'team', state: 'active' }) + expect(activeCloudSetupSessionId()).toBe(ID) + + cloudSetupGet.mockResolvedValueOnce({ + status: 'ok', + session: session({ + steps: [ + { id: 'account', state: 'done' }, + { id: 'team', state: 'done' }, + { id: 'github', state: 'done' } + ], + team: { orgId: 'org_new', name: 'acme', created: true }, + finished: true + }) + }) + await vi.advanceTimersByTimeAsync(SETUP_FAST_POLL_MS) + expect(selectOrcaProfileOrg).toHaveBeenCalledWith('org_new') + expect(getCloudSetupSnapshot(ID)?.finished).toBe(true) + expect(seen).toEqual([ID, ID]) + expect(activeCloudSetupSessionId()).toBeNull() + + // Finished: no more polls. + await vi.advanceTimersByTimeAsync(SETUP_FAST_POLL_MS * 3) + expect(cloudSetupGet).toHaveBeenCalledTimes(2) + }) + + it('stops on an expired session and returns null when setup cannot open', async () => { + cloudSetupStart.mockResolvedValueOnce({ status: 'signed-out' }) + expect(await startCloudSetupSession({ needs: ['plan'] })).toBeNull() + + cloudSetupGet.mockResolvedValue({ status: 'not-found' }) + await refreshCloudSetupSession(ID) + expect(getCloudSetupSnapshot(ID)).toBeNull() + await vi.advanceTimersByTimeAsync(SETUP_FAST_POLL_MS * 2) + expect(cloudSetupGet).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/renderer/src/lib/orca-cloud/cloud-setup-session.ts b/src/renderer/src/lib/orca-cloud/cloud-setup-session.ts new file mode 100644 index 00000000000..d4bd4812bee --- /dev/null +++ b/src/renderer/src/lib/orca-cloud/cloud-setup-session.ts @@ -0,0 +1,216 @@ +// Orca Cloud setup session (NP-4 N1), renderer side: starts the one-tab browser setup, polls the +// session while it is open, and keeps the latest snapshot for the composer's setup panel +// (w2-lifecycle's seam reads it synchronously) and the setup tracker (np4-shell). +import { useAppStore } from '@/store' +import { onCloudSetupReturn } from './cloud-setup-return' +import type { + CloudSetupNeed, + CloudSetupSession, + CloudSetupStartResult +} from '../../../../shared/orca-cloud-setup' + +/** Poll every 2 s for the first 3 minutes, then every 10 s (spec A6). */ +export const SETUP_FAST_POLL_MS = 2_000 +export const SETUP_FAST_WINDOW_MS = 3 * 60_000 +export const SETUP_SLOW_POLL_MS = 10_000 + +export type CloudSetupRowId = 'account' | 'team' | 'plan' | 'github' + +/** One row of the setup panel; the same shape as the composer's CloudSetupStep for these ids. */ +export type CloudSetupSnapshotStep = { + id: CloudSetupRowId + state: 'done' | 'needed' | 'active' | 'pending' | 'failed' | 'optional' + detail?: string +} + +export type CloudSetupSnapshot = { + steps: CloudSetupSnapshotStep[] + finished: boolean + error?: { kind: string; detail?: string } + team: CloudSetupSession['team'] + trial: CloudSetupSession['trial'] + plan: CloudSetupSession['plan'] +} + +/** + * Session -> panel rows. Every required row is present (account, team, plan, github when asked), + * because a snapshot replaces the composer's own rows. `detail` carries the team name, how the + * plan is covered ('trial' | 'subscription' | 'checkout') and 'requested' for a pending GitHub + * approval. + */ +export function snapshotFromSession(session: CloudSetupSession): CloudSetupSnapshot { + const steps = session.steps.map((step): CloudSetupSnapshotStep => { + const detail = step.id === 'team' ? (session.team?.name ?? step.detail) : step.detail + return { id: step.id, state: step.state, ...(detail ? { detail } : {}) } + }) + return { + steps, + finished: session.finished, + ...(session.error ? { error: session.error } : {}), + team: session.team, + trial: session.trial, + plan: session.plan + } +} + +type Entry = { + snapshot: CloudSetupSnapshot | null + startedAt: number + timer: number | null + inFlight: boolean + gone: boolean + /** The team the profile was switched to for this session (once). */ + switchedTo: string | null +} + +const entries = new Map() +const listeners = new Set<(sessionId: string) => void>() + +function emit(sessionId: string): void { + for (const listener of listeners) { + listener(sessionId) + } +} + +/** Latest known state of a session, or null before the first poll answers. */ +export function getCloudSetupSnapshot(sessionId: string): CloudSetupSnapshot | null { + return entries.get(sessionId)?.snapshot ?? null +} + +export function subscribeCloudSetupSessions(listener: (sessionId: string) => void): () => void { + listeners.add(listener) + return () => listeners.delete(listener) +} + +function schedule(sessionId: string, entry: Entry): void { + if (entry.timer !== null) { + window.clearTimeout(entry.timer) + } + if (entry.gone || entry.snapshot?.finished) { + entry.timer = null + return + } + const delay = + Date.now() - entry.startedAt < SETUP_FAST_WINDOW_MS ? SETUP_FAST_POLL_MS : SETUP_SLOW_POLL_MS + entry.timer = window.setTimeout(() => void refreshCloudSetupSession(sessionId), delay) +} + +/** + * Setup chose or created a team in the browser: make it this profile's active team, so billing, + * sandboxes and the composer's checks all read that team (O1: cloud work belongs to a team). + */ +async function followSetupTeam(entry: Entry, session: CloudSetupSession): Promise { + const orgId = session.team?.orgId + if (!orgId || entry.switchedTo === orgId) { + return + } + entry.switchedTo = orgId + const state = useAppStore.getState() + if (state.orcaProfileAuthStatus?.cloud?.activeOrgId !== orgId) { + await state.selectOrcaProfileOrg(orgId) + } +} + +/** Polls now (the orca://cloud/setup/return link and window focus call this). */ +export async function refreshCloudSetupSession(sessionId: string): Promise { + const entry = entries.get(sessionId) ?? watchCloudSetupSession(sessionId) + if (entry.inFlight || entry.gone) { + return + } + entry.inFlight = true + try { + const result = await window.api.orcaProfiles.cloudSetupGet({ sessionId }) + if (result.status === 'ok') { + entry.snapshot = snapshotFromSession(result.session) + await followSetupTeam(entry, result.session) + emit(sessionId) + } else if (result.status === 'not-found') { + // Expired or another account's: stop polling; the composer falls back to its own rows. + entry.gone = true + entry.snapshot = null + emit(sessionId) + } + } catch { + // Offline or main busy: keep the last snapshot and try again on the next tick. + } finally { + entry.inFlight = false + schedule(sessionId, entry) + } +} + +let disposeReturnLink: (() => void) | null = null + +/** Starts polling a session (e.g. one restored from the on-disk draft after a restart). */ +export function watchCloudSetupSession(sessionId: string): Entry { + // The done page's orca://cloud/setup/return link polls at once instead of on the next tick. + disposeReturnLink ??= onCloudSetupReturn((returned) => { + if (entries.has(returned)) { + void refreshCloudSetupSession(returned) + } + }) + let entry = entries.get(sessionId) + if (!entry) { + entry = { + snapshot: null, + startedAt: Date.now(), + timer: null, + inFlight: false, + gone: false, + switchedTo: null + } + entries.set(sessionId, entry) + window.setTimeout(() => void refreshCloudSetupSession(sessionId), 0) + } + return entry +} + +export function stopWatchingCloudSetupSession(sessionId: string): void { + const entry = entries.get(sessionId) + if (entry?.timer != null) { + window.clearTimeout(entry.timer) + } + entries.delete(sessionId) +} + +/** "Set up and start": opens the one browser tab and starts polling. Null when it couldn't. */ +export async function startCloudSetupSession(request: { + repo?: string + needs: CloudSetupNeed[] + chooseTeam?: boolean +}): Promise<{ sessionId: string } | null> { + let result: CloudSetupStartResult + try { + result = await window.api.orcaProfiles.cloudSetupStart({ + ...(request.repo ? { repo: request.repo } : {}), + needs: request.needs, + ...(request.chooseTeam ? { chooseTeam: true } : {}) + }) + } catch { + return null + } + if (result.status !== 'opened') { + return null + } + watchCloudSetupSession(result.sessionId) + return { sessionId: result.sessionId } +} + +/** The setup session still open in this window, for the plans dialog to join (T2 Compare plans). */ +export function activeCloudSetupSessionId(): string | null { + for (const [sessionId, entry] of entries) { + if (!entry.gone && !entry.snapshot?.finished) { + return sessionId + } + } + return null +} + +/** Test-only. */ +export function resetCloudSetupSessionsForTests(): void { + for (const sessionId of entries.keys()) { + stopWatchingCloudSetupSession(sessionId) + } + listeners.clear() + disposeReturnLink?.() + disposeReturnLink = null +} 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 84d26b9621e..94e8cb2fe87 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 @@ -77,6 +77,9 @@ export function createWebOrcaProfilesApi(): Partial { onCloudSetupReturn: () => () => {}, billingStatus: async () => ({ status: 'unconfigured' }), billingOpenCheckout: async () => ({ status: 'unconfigured' }), + cloudSetupStart: async () => ({ status: 'unconfigured' }), + cloudSetupGet: async () => ({ status: 'unconfigured' }), + cloudSetupLink: async () => ({ status: 'unconfigured' }), billingOpenPortal: async () => ({ status: 'unconfigured' }), billingTeamPlans: async () => ({ status: 'unconfigured' }), billingSetOverage: async () => ({ status: 'unconfigured' }) diff --git a/src/shared/orca-billing.ts b/src/shared/orca-billing.ts index 8cee347aa50..41c4ebc21cc 100644 --- a/src/shared/orca-billing.ts +++ b/src/shared/orca-billing.ts @@ -128,6 +128,8 @@ export type OrcaBillingCheckoutArgs = { plan: OrcaBillingPlanId interval: OrcaBillingInterval seats: number + /** The plans dialog joins an open cloud setup session: Checkout then returns to its next step. */ + setupSessionId?: string } export type OrcaBillingOverageArgs = { @@ -143,6 +145,8 @@ export type OrcaBillingOpenResult = | { status: 'forbidden' } | { status: 'already-subscribed' } | { status: 'no-billing-account' } + /** Personal account: every plan lands on a team, so the caller starts cloud setup instead. */ + | { status: 'team-required' } | { status: 'failed'; error: string } export type OrcaBillingOverageResult = diff --git a/src/shared/orca-cloud-setup.ts b/src/shared/orca-cloud-setup.ts new file mode 100644 index 00000000000..a1477682041 --- /dev/null +++ b/src/shared/orca-cloud-setup.ts @@ -0,0 +1,69 @@ +// Orca Cloud setup session (NP-4 N1): one browser tab that chains sign-in, team, plan or trial, +// Checkout (only when needed) and the GitHub App install. The billing service owns the session; +// the desktop starts it and polls it while the composer's setup panel shows each step. + +export const CLOUD_SETUP_NEEDS = ['team', 'plan', 'github'] as const +export type CloudSetupNeed = (typeof CLOUD_SETUP_NEEDS)[number] + +export const CLOUD_SETUP_SESSION_ID = /^cs_[A-Za-z0-9_-]{22}$/ + +export type CloudSetupStartArgs = { + /** https://github.com// of the project, when the workspace needs GitHub access. */ + repo?: string + needs: CloudSetupNeed[] + /** Ask which team even when the profile already has an active one. */ + chooseTeam?: boolean +} + +export type CloudSetupStartResult = + | { status: 'opened'; sessionId: string; expiresAt: number } + | { status: 'unconfigured' } + | { status: 'signed-out' } + | { status: 'cancelled' } + | { status: 'failed'; error: string } + +export type CloudSetupStepState = 'done' | 'needed' | 'active' | 'pending' | 'failed' | 'optional' + +export type CloudSetupSessionStep = { + id: 'account' | 'team' | 'plan' | 'github' + state: CloudSetupStepState + /** team: its name · plan: 'trial' | 'subscription' | 'checkout' · github: 'requested'. */ + detail?: string +} + +/** Error kinds the setup tracker shows (spec X1); `detail` carries e.g. the other account's email. */ +export const CLOUD_SETUP_ERROR_KINDS = [ + 'timed_out', + 'checkout_canceled', + 'bank_step', + 'trial_unavailable', + 'team_create_failed', + 'wrong_account' +] as const +export type CloudSetupErrorKind = (typeof CLOUD_SETUP_ERROR_KINDS)[number] + +export type CloudSetupSession = { + id: string + steps: CloudSetupSessionStep[] + team: { orgId: string; name: string | null; created: boolean } | null + trial: { includedSeconds: number; usedSeconds: number; exhausted: boolean } | null + plan: 'subscription' | 'trial' | null + finished: boolean + error: { kind: CloudSetupErrorKind; detail?: string } | null + expiresAt: number +} + +export type CloudSetupGetResult = + | { status: 'ok'; session: CloudSetupSession } + /** Expired, or it belongs to another account. */ + | { status: 'not-found' } + | { status: 'unconfigured' } + | { status: 'signed-out' } + | { status: 'failed'; error: string } + +export type CloudSetupLinkResult = + | { status: 'ok'; url: string } + | { status: 'not-found' } + | { status: 'unconfigured' } + | { status: 'signed-out' } + | { status: 'failed'; error: string }