Merge remote-tracking branch 'private/cloud/integration' into cloud/w6-repo-can-install-local

This commit is contained in:
Neil
2026-11-13 00:43:49 -08:00
106 changed files with 3759 additions and 775 deletions
+17 -5
View File
@@ -188,12 +188,18 @@ function repoOwner(accountId: string, repo: string): string {
return `${accountId}#${repo}`
}
/** The owners whose secrets a sandbox session receives. */
export function ownersForSandbox(row: Pick<SandboxRow, 'account_id' | 'user_id' | 'repo_url'>) {
/**
* The owners whose secrets a sandbox session receives.
* SEC-5: a workspace shared with teammates runs their shells too, so anything in its env is theirs to
* read (and a placeholder is theirs to spend). It gets the team's and the repository's secrets only,
* never its owner's personal ones, the same rule as personal accounts (D13). Fails closed: only a row
* known to be private counts as unshared.
*/
export function ownersForSandbox(row: Pick<SandboxRow, 'account_id' | 'user_id' | 'repo_url' | 'visibility'>) {
const repo = normalizeRepo(row.repo_url)
return {
org: ORG_ACCOUNT.test(row.account_id) ? row.account_id : null,
personal: personalOwner(row.user_id, row.account_id.startsWith('dev:')),
personal: row.visibility === 'private' ? personalOwner(row.user_id, row.account_id.startsWith('dev:')) : null,
repo: repo ? repoOwner(row.account_id, repo) : null
}
}
@@ -352,16 +358,22 @@ export type ResolvedSecrets = { env: Record<string, string>; scopes: Record<stri
export async function resolveSandboxSecrets(
db: D1Database,
keyring: Keyring,
row: Pick<SandboxRow, 'id' | 'account_id' | 'user_id' | 'repo_url'>
row: Pick<SandboxRow, 'id' | 'account_id' | 'user_id' | 'repo_url' | 'visibility'>
): Promise<ResolvedSecrets> {
const owners = ownersForSandbox(row)
const pairs: [SecretScope, string][] = [['personal', owners.personal]]
const pairs: [SecretScope, string][] = []
if (owners.personal) {
pairs.push(['personal', owners.personal])
}
if (owners.org) {
pairs.push(['org', owners.org])
}
if (owners.repo) {
pairs.push(['repo', owners.repo])
}
if (pairs.length === 0) {
return { env: {}, scopes: {}, skipped: 0 }
}
const where = pairs.map(() => '(scope = ? AND owner_id = ?)').join(' OR ')
const { results } = await db
.prepare(`SELECT * FROM secrets WHERE ${where}`)
@@ -29,7 +29,7 @@ export type ProviderEnv = { env: Record<string, string>; scopes: Record<string,
export async function resolvedProviderEnv(
db: D1Database,
keyring: Keyring,
row: Pick<SandboxRow, 'id' | 'account_id' | 'user_id' | 'repo_url'>
row: Pick<SandboxRow, 'id' | 'account_id' | 'user_id' | 'repo_url' | 'visibility'>
): Promise<ProviderEnv> {
const { env: stored, scopes } = await resolveSandboxSecrets(db, keyring, row)
// The proxy only needs the keys; dropping those of agents not on 'keep' happens at request time
@@ -45,7 +45,8 @@ const PROVIDER_ENV_CACHE_MS = 60_000
const providerEnvCache = new Map<string, { at: number; value: Promise<ProviderEnv> }>()
export function cachedProviderEnv(db: D1Database, keyring: Keyring, row: SandboxRow, now: number): Promise<ProviderEnv> {
const key = `${row.id}:${row.session_id ?? ''}`
// Visibility is part of the key: sharing a workspace stops its owner's personal keys at once (SEC-5).
const key = `${row.id}:${row.session_id ?? ''}:${row.visibility}`
const hit = providerEnvCache.get(key)
if (hit && now - hit.at < PROVIDER_ENV_CACHE_MS) {
return hit.value
@@ -0,0 +1,216 @@
// SEC-5: a workspace shared with teammates runs their shells too, so nothing personal to its owner may
// be in its env: not a variable's value, and not a placeholder that would spend the owner's model key.
import { SignJWT, createLocalJWKSet, exportJWK, generateKeyPair } from 'jose'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ENV_COMMAND, START_COMMAND } from '../src/sandbox-vm-commands'
import { ownersForSandbox } from '../src/secrets'
import { createHarness } from './harness'
const KEK = Buffer.alloc(32, 7).toString('base64')
const PROXY_URL = 'https://sandbox.test/v1/egress/proxy'
// Fake values only.
const TEAM_KEY = 'sk-ant-api03-TEAM-fake-0000-aaaa'
const PERSONAL_OPENAI = 'sk-proj-fake-personal-openai-2222'
const PERSONAL_VALUES = [PERSONAL_OPENAI, 'personal-db-password', 'personal-foo-value', 'personal-aws-secret-value']
type Harness = Awaited<ReturnType<typeof createHarness>>
const logs: string[] = []
beforeEach(() => {
logs.length = 0
for (const method of ['log', 'info', 'warn', 'error', 'debug'] as const) {
vi.spyOn(console, method).mockImplementation((...args: unknown[]) => {
logs.push(args.map((arg) => (typeof arg === 'string' ? arg : JSON.stringify(arg))).join(' '))
})
}
})
afterEach(() => {
for (const value of [...PERSONAL_VALUES, TEAM_KEY]) {
expect(logs.join('\n')).not.toContain(value)
}
vi.restoreAllMocks()
})
function decodeEnv(encoded: string | undefined): Record<string, string> {
return Object.fromEntries(
(encoded ?? '')
.split('\n')
.filter(Boolean)
.map((line) => {
const at = line.indexOf('=')
return [line.slice(0, at), Buffer.from(line.slice(at + 1), 'base64').toString('utf8')]
})
)
}
/** The env the VM got at its last boot, or from its last live refresh. */
function vmEnv(h: Harness, command: string = START_COMMAND): Record<string, string> {
return decodeEnv(h.vercel.commands.filter((c) => c.command === command).at(-1)!.env.ORCA_SECRET_ENV)
}
/** Everything the control plane ever sent the VM, as one string: no personal value may be in it. */
function everythingSent(h: Harness, from = 0): string {
return JSON.stringify(
h.vercel.commands.slice(from).map((c) => ({ ...c, env: { ...c.env, ORCA_SECRET_ENV: decodeEnv(c.env.ORCA_SECRET_ENV) } }))
)
}
async function seeded(overrides: Record<string, string> = {}, deps: Parameters<typeof createHarness>[1] = {}) {
const h = await createHarness({ SECRETS_KEK: KEK, ...overrides }, deps)
const admin = await h.token('ada', 'acme', 'sandbox', { orgRole: 'admin' })
const mia = await h.token('mia', 'acme', 'sandbox', { orgRole: 'member' })
const put = (scope: string, name: string, value: string, bearer: string, repo?: string) =>
h.call('PUT', `/v1/secrets/${scope}/${name}${repo ? `?repo=${encodeURIComponent(repo)}` : ''}`, { body: { value }, bearer })
await put('org', 'ANTHROPIC_API_KEY', TEAM_KEY, admin)
await put('org', 'FOO', 'team-foo-value', admin)
await put('repo', 'BAR', 'repo-bar-value', admin, 'acme/app')
await put('personal', 'OPENAI_API_KEY', PERSONAL_OPENAI, mia)
await put('personal', 'DB_PASSWORD', 'personal-db-password', mia)
await put('personal', 'FOO', 'personal-foo-value', mia)
await put('personal', 'AWS_SECRET_ACCESS_KEY', 'personal-aws-secret-value', mia)
const create = (visibility?: 'team' | 'private') =>
h.call('POST', '/v1/sandboxes', {
body: { workspaceId: 'ws-1', machineSize: 'standard', repo: { url: 'https://github.com/acme/app' }, ...(visibility ? { visibility } : {}) },
bearer: mia
})
const share = (id: string, visibility: 'team' | 'private') =>
h.call('PATCH', `/v1/team/workspaces/${id}`, { body: { visibility }, bearer: mia })
return { h, mia, admin, put, create, share }
}
const TEAM_AND_REPO = { ANTHROPIC_API_KEY: TEAM_KEY, BAR: 'repo-bar-value', FOO: 'team-foo-value' }
describe('personal secrets in shared workspaces (SEC-5)', () => {
it('resolves no personal owner for a shared row, and fails closed on an unknown visibility', () => {
const row = { account_id: 'org:acme', user_id: 'mia', repo_url: 'https://github.com/acme/app' }
expect(ownersForSandbox({ ...row, visibility: 'private' }).personal).toBe('user:mia')
expect(ownersForSandbox({ ...row, visibility: 'team' })).toEqual({ org: 'org:acme', personal: null, repo: 'org:acme#github.com/acme/app' })
expect(ownersForSandbox({ ...row, visibility: undefined as never }).personal).toBeNull()
})
it('keeps the owner’s personal secrets in their own private workspace', async () => {
const { h, create } = await seeded()
expect((await create()).status).toBe(200)
expect(vmEnv(h)).toEqual({
...TEAM_AND_REPO,
AWS_SECRET_ACCESS_KEY: 'personal-aws-secret-value',
DB_PASSWORD: 'personal-db-password',
FOO: 'personal-foo-value',
OPENAI_API_KEY: PERSONAL_OPENAI
})
})
it('starts a shared workspace with team and repository secrets only; the team value replaces a personal override', async () => {
const { h, create } = await seeded()
expect((await create('team')).status).toBe(200)
expect(vmEnv(h)).toEqual(TEAM_AND_REPO)
for (const value of PERSONAL_VALUES) {
expect(everythingSent(h)).not.toContain(value)
}
})
it('drops them from a running workspace the moment it is shared, and brings them back when it is private again', async () => {
const { h, create, share, mia } = await seeded()
const id: string = (await create()).body.sandbox.id
expect(vmEnv(h).DB_PASSWORD).toBe('personal-db-password')
const before = h.vercel.commands.length
expect((await share(id, 'team')).status).toBe(200)
expect(vmEnv(h, ENV_COMMAND)).toEqual(TEAM_AND_REPO)
for (const value of PERSONAL_VALUES) {
expect(everythingSent(h, before)).not.toContain(value)
}
// A wake while shared resolves the same way.
await h.call('POST', `/v1/sandboxes/${id}/suspend`, { bearer: mia })
await h.call('POST', `/v1/sandboxes/${id}/resume`, { bearer: mia })
expect(vmEnv(h)).toEqual(TEAM_AND_REPO)
expect((await share(id, 'private')).status).toBe(200)
expect(vmEnv(h, ENV_COMMAND)).toMatchObject({ DB_PASSWORD: 'personal-db-password', FOO: 'personal-foo-value' })
})
it('does not pick up a personal secret the owner saves while the workspace is shared', async () => {
const { h, create, put, mia } = await seeded()
await create('team')
await put('personal', 'LATER', 'personal-db-password', mia)
const refreshes = h.vercel.commands.filter((c) => c.command === ENV_COMMAND)
for (const refresh of refreshes) {
expect(decodeEnv(refresh.env.ORCA_SECRET_ENV)).toEqual(TEAM_AND_REPO)
}
})
})
describe('personal model keys in shared workspaces with egress placeholders (SEC-5)', () => {
async function placeholderSetup() {
const { privateKey, publicKey } = await generateKeyPair('RS256')
const jwks = { keys: [{ ...(await exportJWK(publicKey)), kid: 'v1', alg: 'RS256' }] }
const upstream: { url: string; headers: Headers }[] = []
const ctx = await seeded(
{ SECRETS_EGRESS_PLACEHOLDERS: 'on', EGRESS_PROXY_URL: PROXY_URL },
{
egressKeysForIssuer: () => createLocalJWKSet(jwks),
credentials: { authorizationFor: async () => 'Bearer ghs_fake' },
egressFetch: async (input, init) => {
upstream.push({ url: String(input), headers: new Headers(init?.headers) })
return new Response('ok', { status: 200 })
}
}
)
async function proxied(sandboxId: string, host: string, headers: Record<string, string>) {
const token = await new SignJWT({ team_id: 'team_orca', project_id: 'prj_orca', sandbox_name: `orca-test-${sandboxId}` })
.setProtectedHeader({ alg: 'RS256', kid: 'v1' })
.setIssuer('https://oidc.vercel.com/team_orca')
.setAudience(PROXY_URL)
.setIssuedAt()
.setExpirationTime('5m')
.sign(privateKey)
const response = await ctx.h.send(
new Request(`${PROXY_URL}/v1/messages`, {
method: 'POST',
body: '{"model":"x"}',
headers: {
'vercel-forwarded-host': host,
'vercel-forwarded-scheme': 'https',
'vercel-forwarded-port': '443',
'vercel-forwarded-path': '/v1/messages',
'vercel-sandbox-oidc-token': token,
...headers
}
})
)
return response.status
}
return { ...ctx, proxied, upstream }
}
it('gives a shared workspace no placeholder and no route for the owner’s personal key; the team key still works', async () => {
const { h, create, proxied, upstream } = await placeholderSetup()
const id: string = (await create('team')).body.sandbox.id
const env = vmEnv(h)
expect(env.ANTHROPIC_API_KEY).toBe(`orca-ph-anthropic-api-key-${id}`)
expect(env).not.toHaveProperty('OPENAI_API_KEY')
expect(env).not.toHaveProperty('DB_PASSWORD')
const [box] = [...h.vercel.boxes.values()]
// No forward rule for the personal key: the host is plain allowlisted, nothing is swapped there.
expect(box!.policy.allow['api.openai.com']).toEqual([])
expect(await proxied(id, 'api.openai.com', { authorization: `Bearer orca-ph-openai-api-key-${id}` })).toBe(403)
expect(await proxied(id, 'api.anthropic.com', { 'x-api-key': `orca-ph-anthropic-api-key-${id}` })).toBe(200)
expect(upstream).toHaveLength(1)
expect(upstream[0]!.headers.get('x-api-key')).toBe(TEAM_KEY)
})
it('stops swapping the owner’s personal key at the proxy as soon as a running workspace is shared', async () => {
const { h, create, share, proxied, upstream } = await placeholderSetup()
const id: string = (await create()).body.sandbox.id
const placeholder = `orca-ph-openai-api-key-${id}`
expect(vmEnv(h).OPENAI_API_KEY).toBe(placeholder)
expect(await proxied(id, 'api.openai.com', { authorization: `Bearer ${placeholder}` })).toBe(200)
expect(upstream.at(-1)!.headers.get('authorization')).toBe(`Bearer ${PERSONAL_OPENAI}`)
expect((await share(id, 'team')).status).toBe(200)
expect(vmEnv(h, ENV_COMMAND)).not.toHaveProperty('OPENAI_API_KEY')
// A process still holding the old placeholder gets nothing for it.
expect(await proxied(id, 'api.openai.com', { authorization: `Bearer ${placeholder}` })).toBe(403)
expect(upstream).toHaveLength(1)
})
})
-21
View File
@@ -1,21 +0,0 @@
// "Copy link" on billing buttons: the Stripe Checkout or Customer Portal URL the button would open,
// minted the same way (same account, same order, same setup-session fallback) but returned instead.
import type { OrcaBillingCheckoutArgs, OrcaBillingLinkResult } from '../../shared/orca-billing'
import { createCheckoutUrl, createPortalUrl } from './billing-client'
import { mintHosted } from './billing-service'
import { withSetupSessionFallback } from './billing-setup-session-fallback'
export function getOrcaBillingCheckoutLink(
userDataPath: string,
args: OrcaBillingCheckoutArgs
): Promise<OrcaBillingLinkResult> {
return withSetupSessionFallback(args, (checkoutArgs) =>
mintHosted(userDataPath, (token, endpoints) =>
createCheckoutUrl(endpoints, token, checkoutArgs)
)
)
}
export function getOrcaBillingPortalLink(userDataPath: string): Promise<OrcaBillingLinkResult> {
return mintHosted(userDataPath, (token, endpoints) => createPortalUrl(endpoints, token))
}
+1 -1
View File
@@ -222,7 +222,7 @@ export async function getOrcaBillingTeamPlans(
type CreateHostedUrl = (token: string, endpoints: BillingEndpoints) => Promise<string>
/** Mints a Stripe-hosted Checkout/Portal URL for the active account without opening it. */
export async function mintHosted(
async function mintHosted(
userDataPath: string,
createUrl: CreateHostedUrl
): Promise<OrcaBillingLinkResult> {
@@ -73,11 +73,6 @@ export async function createCloudWorkspaceFromGitHub(
onProgress: (progress) => io.onLog?.(hostedProgressLine(progress))
}
)
if (io.signal?.aborted) {
// Cancelled just as it answered: nothing will open it, so it must not keep running (and billing).
await client.destroy(ready.sandbox.id).catch(() => undefined)
return { ok: false, code: 'failed', message: 'Cancelled.' }
}
return { ok: true, value: { sandboxId: ready.sandbox.id } }
} catch (error) {
const result = hostedCreateFailure(error)
@@ -23,7 +23,6 @@ const SETUP_SESSION_ID = /^cs_[A-Za-z0-9_-]{22}$/
export const HOSTED_ACCOUNT_CHANNELS = [
CH.getConfig,
CH.connectGitHub,
CH.gitHubInstallLink,
CH.getRepoAccess,
CH.listGitHubRepositories,
CH.createFromGitHub,
@@ -107,15 +106,6 @@ export function registerHostedAccountHandlers(
}
})
// "Copy link": the same install page, minted the same way, for another browser or profile.
ipcMain.handle(CH.gitHubInstallLink, async (_event, args?: RepoArgs) => {
try {
return { ok: true, value: await mintInstallUrl(args) }
} catch (error) {
return failure(error)
}
})
ipcMain.handle(CH.getRepoAccess, async (_event, args?: RepoArgs) => {
const target = repoTarget(args)
if (!target) {
@@ -1,5 +1,6 @@
// "Copy link" twins of Connect GitHub (App install) and Connect your GitHub (OAuth): the same page,
// minted the same way, returned instead of opened, and still only ever a github.com page.
// "Copy link" for Connect your GitHub (OAuth sign-in): the same page, minted the same way, returned
// instead of opened, and still only ever a github.com page. The App install has no link channel:
// Copy link is for sign-in pages only.
import { afterEach, expect, it, vi } from 'vitest'
const handlers = new Map<string, (...args: unknown[]) => unknown>()
@@ -56,25 +57,24 @@ function register(url: string) {
return { connectGitHub, connectGitHubUser }
}
it('registers the link channels with the window allowlist', () => {
expect(HOSTED_ACCOUNT_CHANNELS).toEqual(
expect.arrayContaining([CH.gitHubInstallLink, CH.gitHubUserConnectLink])
)
it('registers the OAuth link channel, and no App-install link channel', () => {
expect(HOSTED_ACCOUNT_CHANNELS).toContain(CH.gitHubUserConnectLink)
expect(HOSTED_ACCOUNT_CHANNELS).not.toContain('orcaCloudWorkspace:gitHubInstallLink')
})
it('returns the install page minted like Connect GitHub, without opening it', async () => {
it('Connect GitHub still opens the install page minted for the repository', async () => {
const url = 'https://github.com/apps/x/installations/new?state=s'
const { connectGitHub } = register(url)
expect(
await handlers.get(CH.gitHubInstallLink)?.({}, { repoUrl: REPO, setupSessionId: SESSION })
).toEqual({ ok: true, value: url })
await handlers.get(CH.connectGitHub)?.({}, { repoUrl: REPO, setupSessionId: SESSION })
).toEqual({ ok: true, value: null })
expect(connectGitHub).toHaveBeenLastCalledWith(undefined, {
repo: REPO,
setupSessionId: SESSION,
repoId: 7,
ownerId: 50
})
expect(openExternal).not.toHaveBeenCalled()
expect(openExternal).toHaveBeenCalledWith(url)
})
it('returns the OAuth page minted like Connect your GitHub, without opening it', async () => {
@@ -84,7 +84,7 @@ it('returns the OAuth page minted like Connect your GitHub, without opening it',
expect(openExternal).not.toHaveBeenCalled()
})
it('never hands out a page that is not on github.com', async () => {
it('never opens or hands out a page that is not on github.com', async () => {
for (const url of [
'https://github.com.evil.example/install',
'http://github.com/login/oauth/authorize',
@@ -92,7 +92,7 @@ it('never hands out a page that is not on github.com', async () => {
]) {
handlers.clear()
register(url)
expect(await handlers.get(CH.gitHubInstallLink)?.({}, {})).toMatchObject({
expect(await handlers.get(CH.connectGitHub)?.({}, {})).toMatchObject({
ok: false,
code: 'failed'
})
@@ -101,4 +101,5 @@ it('never hands out a page that is not on github.com', async () => {
code: 'failed'
})
}
expect(openExternal).not.toHaveBeenCalled()
})
@@ -12,7 +12,7 @@ import {
unlinkOrcaProfileFromCloud
} from '../orca-profiles/cloud-auth/profile-cloud-index'
import { ensureActiveOrcaProfile } from '../orca-profiles/profile-index-store'
import { getHostedSandboxConfig } from './hosted-sandbox-config'
import { getHostedSandboxConfig, isMfaRequiredRefusal } from './hosted-sandbox-config'
const state = { dir: '' }
installFakeAppEnvironment({ getPath: () => state.dir })
@@ -118,3 +118,21 @@ describe('getHostedSandboxConfig sandbox tokens', () => {
expect(claims(await b.getAccessToken()).sub).toBe('user-b')
})
})
describe('isMfaRequiredRefusal', () => {
it('recognizes the team MFA refusal and leaves the body readable', async () => {
const response = Response.json(
{ error: 'mfa_required', orgId: 'org_1', enforceAt: 5 },
{ status: 403 }
)
expect(await isMfaRequiredRefusal(response)).toBe(true)
expect(await response.json()).toMatchObject({ orgId: 'org_1' })
})
it('is false for other refusals and for bodies that are not JSON', async () => {
for (const body of [{ error: 'not_a_member' }, { error: 'sandbox_not_entitled' }, {}, null]) {
expect(await isMfaRequiredRefusal(Response.json(body, { status: 403 }))).toBe(false)
}
expect(await isMfaRequiredRefusal(new Response('<html>', { status: 403 }))).toBe(false)
})
})
@@ -30,6 +30,24 @@ export type HostedSandboxConfig = {
fetch?: typeof fetch
}
/** `reason` on the provider error when the team's MFA policy refused the token. */
export const MFA_REQUIRED_REASON = 'mfa_required'
/** Reads a copy of the body, so the caller can still read the response. */
export async function isMfaRequiredRefusal(response: Response): Promise<boolean> {
try {
const body: unknown = await response.clone().json()
return (
typeof body === 'object' &&
body !== null &&
'error' in body &&
body.error === MFA_REQUIRED_REASON
)
} catch {
return false
}
}
const SandboxTokenBody = z.object({
sandboxToken: z.string().min(1).max(8192),
expiresAt: z.number().int().positive()
@@ -232,6 +250,15 @@ async function mintSandboxToken(
if (response.status === 403 && requestedOrg && (await isNotAMember(response))) {
throw orgSwitchError(active)
}
if (response.status === 403 && (await isMfaRequiredRefusal(response))) {
// The team requires MFA and this person has none past the deadline. Signing in again
// would not help, so this is not a session error: the reason lets the UI show setup.
throw new EnvironmentProviderError(
'unauthorized',
'Your team requires two-factor authentication. Set it up to use its cloud workspaces.',
MFA_REQUIRED_REASON
)
}
if (response.status === 401 || response.status === 403) {
throw new OrcaCloudRequestError(response.status)
}
@@ -0,0 +1,105 @@
// GH-CREATE-CANCEL: a create cancelled in flight never leaves a sandbox running, for the owned
// create and the GitHub-only create alike (both use createSandboxWithProgress).
import { describe, expect, it, vi } from 'vitest'
import { EnvironmentProviderError } from '../environment-providers/environment-provider-driver'
import { HostedEntitlementDeniedError } from './hosted-environment-provider'
import { reclaimCancelledCreate } from './hosted-sandbox-create-reclaim'
import { createSandboxWithProgress } from './hosted-sandbox-driver'
const READY = {
sandbox: {
id: 'sbx_1',
workspaceId: 'web-1',
status: 'running' as const,
machineSize: 'standard' as const,
region: 'iad1',
session: null,
createdAt: 1
},
connection: { type: 'orca-server' as const, pairingCode: 'code', projectRoot: '/work' }
}
const BODY = { workspaceId: 'web-1', machineSize: 'standard' as const }
const quiet = { waitMs: 0, log: () => {} }
function client() {
return {
create: vi.fn(async () => READY),
bootPlan: vi.fn(async () => 'clone' as const),
cloneStatus: vi.fn(async () => ({ state: 'done' as const })),
destroy: vi.fn(async (id: string) => ({ id, status: 'destroyed' as const }))
}
}
describe('reclaimCancelledCreate', () => {
it('replays the create by its key and deletes the sandbox it gets back', async () => {
const api = client()
expect(await reclaimCancelledCreate(api, BODY, 'create:k1', quiet)).toBe(true)
expect(api.create).toHaveBeenCalledWith(BODY, undefined, 'create:k1')
expect(api.destroy).toHaveBeenCalledWith('sbx_1')
})
it('waits while the first create is still in progress (409), then deletes', async () => {
const api = client()
api.create
.mockRejectedValueOnce(new EnvironmentProviderError('conflict', 'idempotency_in_progress'))
.mockRejectedValueOnce(new EnvironmentProviderError('unavailable', 'try later'))
expect(await reclaimCancelledCreate(api, BODY, 'create:k1', quiet)).toBe(true)
expect(api.create).toHaveBeenCalledTimes(3)
expect(api.destroy).toHaveBeenCalledWith('sbx_1')
})
it('a refused replay means the cancelled create made nothing either', async () => {
const api = client()
api.create.mockRejectedValueOnce(new HostedEntitlementDeniedError('denied', 'no_subscription'))
expect(await reclaimCancelledCreate(api, BODY, 'create:k1', quiet)).toBe(true)
expect(api.destroy).not.toHaveBeenCalled()
})
it('gives up (false) when it can never tell', async () => {
const api = client()
api.create.mockRejectedValue(new EnvironmentProviderError('unavailable', 'down'))
expect(await reclaimCancelledCreate(api, BODY, 'create:k1', { ...quiet, attempts: 3 })).toBe(
false
)
})
})
describe('createSandboxWithProgress cancel', () => {
const spec = { workspaceId: 'web-1', machineSize: 'standard', idempotencyKey: 'create:k1' }
it('cancelled while the create was in flight: reclaims by key, then reports the cancel', async () => {
const api = client()
const controller = new AbortController()
api.create.mockImplementationOnce(async () => {
controller.abort()
throw new EnvironmentProviderError('aborted', 'Cancelled.')
})
await expect(
createSandboxWithProgress(api, spec, { signal: controller.signal })
).rejects.toMatchObject({ code: 'aborted' })
// The replay (no signal, same key) found the sandbox and deleted it.
expect(api.create).toHaveBeenLastCalledWith(expect.anything(), undefined, 'create:k1')
expect(api.destroy).toHaveBeenCalledWith('sbx_1')
})
it('cancelled just as the create answered: deletes the sandbox and reports the cancel', async () => {
const api = client()
const controller = new AbortController()
api.create.mockImplementationOnce(async () => {
controller.abort()
return READY
})
await expect(
createSandboxWithProgress(api, spec, { signal: controller.signal })
).rejects.toMatchObject({ code: 'aborted' })
expect(api.destroy).toHaveBeenCalledWith('sbx_1')
expect(api.create).toHaveBeenCalledTimes(1)
})
it('not cancelled: no replay, no delete', async () => {
const api = client()
await expect(createSandboxWithProgress(api, spec, {})).resolves.toBe(READY)
expect(api.create).toHaveBeenCalledTimes(1)
expect(api.destroy).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,64 @@
// A create cancelled while its request was in flight may still have made a sandbox on the control
// plane, and a sandbox bills (GH-CREATE-CANCEL). The control plane keys creates by Idempotency-Key
// and body: sending the same create again hands back the sandbox the first one made (or makes one, if
// the first never arrived), and that sandbox is deleted. Shared by the owned create (the recipe) and
// the GitHub-only create, which both go through createSandboxWithProgress.
import { isEnvironmentProviderError } from '../environment-providers/environment-provider-driver'
import type { HostedSandboxControlPlaneClient } from './hosted-sandbox-control-plane-client'
type CreateBody = Parameters<HostedSandboxControlPlaneClient['create']>[0]
const RECLAIM_ATTEMPTS = 8
const RECLAIM_WAIT_MS = 5_000
/** The first create may still be running (409 in progress) or the service briefly unreachable. */
function worthRetrying(error: unknown): boolean {
return (
isEnvironmentProviderError(error, 'conflict') ||
isEnvironmentProviderError(error, 'unavailable') ||
isEnvironmentProviderError(error, 'timeout') ||
!isEnvironmentProviderError(error)
)
}
/**
* Deletes whatever the cancelled create made. True once it is gone (or the control plane refused
* the create, so nothing was made); false when it still couldn't tell after every attempt.
*/
export async function reclaimCancelledCreate(
client: Pick<HostedSandboxControlPlaneClient, 'create' | 'destroy'>,
body: CreateBody,
idempotencyKey: string,
{
attempts = RECLAIM_ATTEMPTS,
waitMs = RECLAIM_WAIT_MS,
log = (message: string) => console.warn(message)
}: { attempts?: number; waitMs?: number; log?: (message: string) => void } = {}
): Promise<boolean> {
for (let attempt = 1; attempt <= attempts; attempt += 1) {
let sandboxId: string
try {
// No signal: this request is the cleanup and must not be cancelled with the create.
sandboxId = (await client.create(body, undefined, idempotencyKey)).sandbox.id
} catch (error) {
if (!worthRetrying(error)) {
// Refused (billing, sign-in, bad request): the cancelled create made nothing either.
return true
}
log(
`[orca-cloud] cancelled create: replay ${attempt}/${attempts} failed (${isEnvironmentProviderError(error) ? error.code : 'error'})`
)
await new Promise((resolve) => setTimeout(resolve, waitMs))
continue
}
try {
await client.destroy(sandboxId)
log(`[orca-cloud] cancelled create: deleted sandbox ${sandboxId}`)
return true
} catch {
await new Promise((resolve) => setTimeout(resolve, waitMs))
}
}
log('[orca-cloud] cancelled create: could not confirm the sandbox was deleted')
return false
}
@@ -25,6 +25,7 @@ import type {
} from './hosted-environment-provider'
import type { HostedSandboxControlPlaneClient } from './hosted-sandbox-control-plane-client'
import { takeSuspendReason } from './idle-sleep-requests'
import { reclaimCancelledCreate } from './hosted-sandbox-create-reclaim'
export const HOSTED_SANDBOX_DRIVER_ID = 'orca-cloud'
@@ -144,21 +145,34 @@ export async function createSandboxWithProgress(
)
.catch(() => undefined)
}
const ready = await client.create(
{
workspaceId: spec.workspaceId,
machineSize,
// Named rows: Home shows the workspace's name, never an untitled sandbox (PC-8).
...(spec.workspaceName?.trim() ? { title: spec.workspaceName.trim().slice(0, 120) } : {}),
...(spec.region ? { region: spec.region } : {}),
...(spec.repo ? { repo: spec.repo } : {})
},
ctx?.signal,
spec.idempotencyKey
)
const body = {
workspaceId: spec.workspaceId,
machineSize,
// Named rows: Home shows the workspace's name, never an untitled sandbox (PC-8).
...(spec.workspaceName?.trim() ? { title: spec.workspaceName.trim().slice(0, 120) } : {}),
...(spec.region ? { region: spec.region } : {}),
...(spec.repo ? { repo: spec.repo } : {})
}
let ready: HostedSandboxReadyResponse
try {
ready = await client.create(body, ctx?.signal, spec.idempotencyKey)
} catch (error) {
// GH-CREATE-CANCEL: cancelled in flight, the control plane may still have made it: find it by
// its key and delete it before reporting the cancel.
if (ctx?.signal?.aborted && spec.idempotencyKey) {
await reclaimCancelledCreate(client, body, spec.idempotencyKey)
}
throw error
}
if (ready.clone) {
// A cancelled, failed or stalled clone deletes the sandbox itself.
await waitForClone(client, ready.sandbox.id, ctx, { mode: ready.clone.mode ?? 'clone' })
}
if (ctx?.signal?.aborted) {
// Cancelled just as it answered: nothing will use it, so it must not keep running (and billing).
await client.destroy(ready.sandbox.id).catch(() => undefined)
throw new EnvironmentProviderError('aborted', 'Cancelled.')
}
ctx?.onProgress?.({ phase: 'connecting' })
return ready
}
@@ -2,7 +2,6 @@ import { ipcMain } from 'electron'
import { z } from 'zod'
import type {
OrcaBillingCheckoutArgs,
OrcaBillingLinkResult,
OrcaBillingOpenResult,
OrcaBillingOverageArgs,
OrcaBillingOverageResult,
@@ -27,10 +26,6 @@ import {
openOrcaBillingPortal,
setOrcaBillingOverage
} from '../../billing/billing-service'
import {
getOrcaBillingCheckoutLink,
getOrcaBillingPortalLink
} from '../../billing/billing-hosted-links'
import { getProfileUserDataPath } from '../../orca-profiles/profile-storage-paths'
import { ensureActiveOrcaProfile } from '../../orca-profiles/profile-index-store'
import { notifyUsageAlertIfDue } from '../../billing/usage-alert-notifier'
@@ -223,13 +218,4 @@ export function registerOrcaProfileBillingHandlers(store: Store): void {
ipcMain.handle('orcaProfiles:billingOpenPortal', async (): Promise<OrcaBillingOpenResult> =>
openOrcaBillingPortal(getProfileUserDataPath())
)
// "Copy link": the same Stripe URLs, minted but not opened (paste into another browser profile).
ipcMain.handle('orcaProfiles:billingPortalLink', async (): Promise<OrcaBillingLinkResult> =>
getOrcaBillingPortalLink(getProfileUserDataPath())
)
ipcMain.handle(
'orcaProfiles:billingCheckoutLink',
async (_event, rawArgs: unknown): Promise<OrcaBillingLinkResult> =>
getOrcaBillingCheckoutLink(getProfileUserDataPath(), billingCheckoutArgsFromUnknown(rawArgs))
)
}
@@ -11,6 +11,22 @@ import type {
OrcaProfileOrgMembersListArgs,
OrcaProfileOrgMembersListResult
} from '../../../shared/orca-profiles'
import type { OrcaAccountMfaResult } from '../../../shared/orca-account-mfa'
import { getOrcaProfileAccountMfa } from '../../orca-profiles/cloud-mfa/profile-cloud-mfa-service'
import {
ORCA_TEAM_MFA_GRACE_CHOICES,
type OrcaTeamMfaGrace,
type OrcaTeamMfaPendingResult,
type OrcaTeamMfaPolicyResult,
type OrcaTeamMfaPolicySetResult,
type OrcaTeamMfaRemindResult
} from '../../../shared/orca-team-mfa-policy'
import {
getOrcaTeamMfaPolicy,
listOrcaTeamMfaPending,
remindOrcaTeamMfa,
setOrcaTeamMfaPolicy
} from '../../orca-profiles/cloud-mfa/profile-cloud-team-mfa-service'
import { getProfileUserDataPath } from '../../orca-profiles/profile-storage-paths'
import {
changeOrcaProfileOrgMemberRole,
@@ -144,6 +160,48 @@ export function registerOrcaProfileOrgMemberHandlers(): void {
createOrcaProfileOrg(getProfileUserDataPath(), { name: orgCreateNameFromUnknown(rawArgs) })
)
ipcMain.handle('orcaProfiles:accountMfa', async (): Promise<OrcaAccountMfaResult> =>
getOrcaProfileAccountMfa(getProfileUserDataPath())
)
ipcMain.handle(
'orcaProfiles:teamMfaPolicy',
async (_event, rawArgs: unknown): Promise<OrcaTeamMfaPolicyResult> =>
getOrcaTeamMfaPolicy(getProfileUserDataPath(), orgMembersScopedArgs(rawArgs).orgId)
)
ipcMain.handle(
'orcaProfiles:teamMfaPolicySet',
async (_event, rawArgs: unknown): Promise<OrcaTeamMfaPolicySetResult> => {
const { orgId, record } = orgMembersScopedArgs(rawArgs)
// Only the fixed choices cross to the server; anything else is refused here.
const enforce: OrcaTeamMfaGrace | 'off' | undefined =
record.enforce === 'off'
? 'off'
: ORCA_TEAM_MFA_GRACE_CHOICES.find((choice) => choice === record.enforce)
if (enforce === undefined) {
return { status: 'failed', error: 'invalid_enforce' }
}
return setOrcaTeamMfaPolicy(getProfileUserDataPath(), { orgId, enforce })
}
)
ipcMain.handle(
'orcaProfiles:teamMfaPending',
async (_event, rawArgs: unknown): Promise<OrcaTeamMfaPendingResult> =>
listOrcaTeamMfaPending(getProfileUserDataPath(), orgMembersScopedArgs(rawArgs).orgId)
)
ipcMain.handle(
'orcaProfiles:teamMfaRemind',
async (_event, rawArgs: unknown): Promise<OrcaTeamMfaRemindResult> => {
const { orgId, record } = orgMembersScopedArgs(rawArgs)
const userId =
typeof record.userId === 'string' && record.userId.length <= 128 ? record.userId : undefined
return remindOrcaTeamMfa(getProfileUserDataPath(), { orgId, ...(userId ? { userId } : {}) })
}
)
ipcMain.handle(
'orcaProfiles:orgMembersList',
async (
@@ -0,0 +1,27 @@
import { describe, expect, it } from 'vitest'
import { normalizeAccountMfa } from './profile-cloud-mfa-service'
const API = 'https://cloud.orca.dev'
describe('normalizeAccountMfa', () => {
it('keeps the status and a setup link on Orca Cloud', () => {
expect(
normalizeAccountMfa({ mfa: 'off', setupUrl: `${API}/v1/account/security` }, API)
).toEqual({ mfa: 'off', setupUrl: `${API}/v1/account/security` })
expect(normalizeAccountMfa({ mfa: 'on', setupUrl: `${API}/x` }, `${API}/`).mfa).toBe('on')
})
it.each([
['another site', { mfa: 'off', setupUrl: 'https://evil.example/v1/account/security' }],
['a look-alike host', { mfa: 'off', setupUrl: 'https://cloud.orca.dev.evil.example/' }],
['plain http', { mfa: 'off', setupUrl: 'http://cloud.orca.dev/v1/account/security' }],
['credentials in the link', { mfa: 'off', setupUrl: 'https://user:pw@cloud.orca.dev/' }],
['a script link', { mfa: 'off', setupUrl: 'javascript:alert(1)' }],
['no link', { mfa: 'off' }],
['an unknown status', { mfa: 'pending', setupUrl: `${API}/v1/account/security` }],
['a boolean status', { mfa: true, setupUrl: `${API}/v1/account/security` }],
['nothing', null]
])('refuses %s', (_name, body) => {
expect(() => normalizeAccountMfa(body, API)).toThrow('invalid_orca_account_mfa')
})
})
@@ -0,0 +1,82 @@
import type { OrcaAccountMfa, OrcaAccountMfaResult } from '../../../shared/orca-account-mfa'
import type { OrcaCloudAuthConfig } from '../cloud-auth/profile-cloud-auth-config'
import {
getOrcaCloudAuthConfig,
isOrcaCloudDevAuthEnabled
} from '../cloud-auth/profile-cloud-auth-config'
import { OrcaCloudRequestError } from '../cloud-auth/profile-cloud-client'
import type { OrcaCloudSession } from '../cloud-session/profile-cloud-session-store'
import { extractErrorCode, requestInit } from '../cloud-org/profile-cloud-org-members-client'
import { runOrgMemberCall } from '../cloud-org/profile-cloud-org-members-service'
import { ensureActiveOrcaProfile } from '../profile-index-store'
/**
* The renderer opens `setupUrl` in the browser, so it must be a page on Orca Cloud's own origin:
* a compromised or misconfigured answer cannot send the person to another site to "set up MFA".
*/
export function normalizeAccountMfa(value: unknown, apiBaseUrl: string): OrcaAccountMfa {
const record: Record<string, unknown> =
typeof value === 'object' && value !== null ? { ...value } : {}
const mfa = record.mfa === 'on' || record.mfa === 'off' ? record.mfa : null
let setupUrl: URL | null = null
try {
setupUrl = typeof record.setupUrl === 'string' ? new URL(record.setupUrl) : null
} catch {
setupUrl = null
}
if (
!mfa ||
!setupUrl ||
setupUrl.origin !== new URL(apiBaseUrl).origin ||
setupUrl.username ||
setupUrl.password
) {
throw new Error('invalid_orca_account_mfa')
}
return { mfa, setupUrl: setupUrl.toString() }
}
async function fetchAccountMfa(
config: OrcaCloudAuthConfig,
session: OrcaCloudSession
): Promise<OrcaAccountMfa> {
const response = await fetch(
`${config.apiBaseUrl}/v1/desktop/auth/mfa`,
requestInit('GET', session.accessToken)
)
if (!response.ok) {
throw new OrcaCloudRequestError(response.status, await extractErrorCode(response))
}
const body: unknown = await response.json()
return normalizeAccountMfa(body, config.apiBaseUrl)
}
export async function getOrcaProfileAccountMfa(
userDataPath: string
): Promise<OrcaAccountMfaResult> {
const active = ensureActiveOrcaProfile(userDataPath)
// Local dev auth has no server and no factor to enrol.
if (isOrcaCloudDevAuthEnabled()) {
return { status: 'unsupported' }
}
const configState = getOrcaCloudAuthConfig()
if (!configState.configured) {
return { status: 'unconfigured' }
}
const result = await runOrgMemberCall(configState.config, active, userDataPath, (session) =>
fetchAccountMfa(configState.config, session)
)
switch (result.status) {
case 'ok':
return { status: 'ok', ...result.value }
case 'reconnect-required':
return { status: 'reconnect-required' }
case 'request-error':
// 404: an auth deployment from before this route, or a provider with no MFA status.
return result.error.statusCode === 404
? { status: 'unsupported' }
: { status: 'failed', error: result.error.message }
case 'failed':
return { status: 'failed', error: result.error }
}
}
@@ -0,0 +1,85 @@
import { describe, expect, it } from 'vitest'
import {
normalizePendingMembers,
normalizeTeamMfaPolicy,
sameOriginUrl
} from './profile-cloud-team-mfa-service'
const API = 'https://cloud.orca.dev'
const setupUrl = `${API}/v1/account/security`
describe('normalizeTeamMfaPolicy', () => {
it('reads a member answer: the deadline and their own state, no manager fields', () => {
expect(
normalizeTeamMfaPolicy(
{ policy: { enforceAt: 200, setAt: 100 }, self: { mfa: 'pending' }, setupUrl },
API
)
).toEqual({ policy: { enforceAt: 200, setAt: 100 }, self: 'pending', setupUrl })
})
it('reads a manager answer, including a policy the plan no longer covers', () => {
expect(
normalizeTeamMfaPolicy(
{
policy: null,
self: { mfa: 'on' },
setupUrl,
available: false,
pendingMembers: 3,
inactivePolicy: { enforceAt: 500 }
},
API
)
).toEqual({
policy: null,
self: 'on',
setupUrl,
manage: { available: false, pendingMembers: 3, inactiveEnforceAt: 500 }
})
})
it('never turns a malformed state into blocked', () => {
for (const self of [undefined, null, {}, { mfa: 'BLOCKED' }, { mfa: true }, 'blocked']) {
expect(normalizeTeamMfaPolicy({ policy: null, self, setupUrl }, API).self).toBe('unknown')
}
})
it('drops a half-formed deadline rather than guessing one', () => {
expect(
normalizeTeamMfaPolicy({ policy: { enforceAt: 'soon' }, self: { mfa: 'off' }, setupUrl }, API)
.policy
).toBeNull()
})
it('refuses an answer whose setup link is not on Orca Cloud', () => {
for (const link of ['https://evil.example/x', 'javascript:alert(1)', undefined, 7]) {
expect(() =>
normalizeTeamMfaPolicy({ policy: null, self: { mfa: 'off' }, setupUrl: link }, API)
).toThrow('invalid_orca_team_mfa_policy')
}
expect(sameOriginUrl('https://user:pw@cloud.orca.dev/x', API)).toBeNull()
expect(sameOriginUrl('http://cloud.orca.dev/x', API)).toBeNull()
})
})
describe('normalizePendingMembers', () => {
it('keeps members with an email and maps unknown states to off', () => {
expect(
normalizePendingMembers({
members: [
{ userId: 'u1', email: 'a@x.dev', displayName: 'Ada', mfa: 'pending' },
{ userId: null, email: 'b@x.dev', mfa: 'blocked' },
{ userId: 'u3', email: 'c@x.dev', mfa: 'whatever' },
{ userId: 'u4' },
'nope'
]
})
).toEqual([
{ userId: 'u1', email: 'a@x.dev', displayName: 'Ada', mfa: 'pending' },
{ userId: null, email: 'b@x.dev', mfa: 'blocked' },
{ userId: 'u3', email: 'c@x.dev', mfa: 'off' }
])
expect(normalizePendingMembers(null)).toEqual([])
})
})
@@ -0,0 +1,287 @@
import {
ORCA_TEAM_MFA_GRACE_CHOICES,
type OrcaTeamMfaGrace,
type OrcaTeamMfaPendingMember,
type OrcaTeamMfaPendingResult,
type OrcaTeamMfaPolicy,
type OrcaTeamMfaPolicyResult,
type OrcaTeamMfaPolicySetResult,
type OrcaTeamMfaRemindResult,
type OrcaTeamMfaSelfState
} from '../../../shared/orca-team-mfa-policy'
import {
getOrcaCloudAuthConfig,
isOrcaCloudDevAuthEnabled
} from '../cloud-auth/profile-cloud-auth-config'
import { OrcaCloudRequestError } from '../cloud-auth/profile-cloud-client'
import {
extractErrorCode,
orgMembersUrl,
requestInit
} from '../cloud-org/profile-cloud-org-members-client'
import {
runOrgMemberCall,
type OrgCallResult
} from '../cloud-org/profile-cloud-org-members-service'
import { ensureActiveOrcaProfile } from '../profile-index-store'
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null
}
const SELF_STATES: readonly OrcaTeamMfaSelfState[] = ['on', 'off', 'pending', 'blocked', 'unknown']
function finiteNumber(value: unknown): number | null {
return typeof value === 'number' && Number.isFinite(value) ? value : null
}
/** The setup link is opened in the browser, so only a page on Orca Cloud's own origin is kept. */
export function sameOriginUrl(value: unknown, apiBaseUrl: string): string | null {
if (typeof value !== 'string') {
return null
}
try {
const url = new URL(value)
return url.origin === new URL(apiBaseUrl).origin && !url.username && !url.password
? url.toString()
: null
} catch {
return null
}
}
function normalizeDeadline(value: unknown): { enforceAt: number; setAt: number } | null {
const record = isRecord(value) ? value : null
const enforceAt = finiteNumber(record?.enforceAt)
const setAt = finiteNumber(record?.setAt)
return enforceAt !== null && setAt !== null ? { enforceAt, setAt } : null
}
export function normalizeTeamMfaPolicy(value: unknown, apiBaseUrl: string): OrcaTeamMfaPolicy {
const record = isRecord(value) ? value : null
const setupUrl = sameOriginUrl(record?.setupUrl, apiBaseUrl)
if (!record || !setupUrl) {
throw new Error('invalid_orca_team_mfa_policy')
}
const selfRecord = isRecord(record.self) ? record.self : {}
// An unrecognized state is "unknown", never "blocked": only the server's word blocks anyone.
const self = SELF_STATES.find((state) => state === selfRecord.mfa) ?? 'unknown'
const pendingMembers = finiteNumber(record.pendingMembers)
const inactive = isRecord(record.inactivePolicy)
? finiteNumber(record.inactivePolicy.enforceAt)
: null
return {
policy: normalizeDeadline(record.policy),
self,
setupUrl,
// Present only when the server sent the manager fields; a member's answer has none.
...(typeof record.available === 'boolean'
? {
manage: {
available: record.available,
pendingMembers: pendingMembers ?? 0,
...(inactive !== null ? { inactiveEnforceAt: inactive } : {})
}
}
: {})
}
}
export function normalizePendingMembers(value: unknown): OrcaTeamMfaPendingMember[] {
const record = isRecord(value) ? value : null
const members = Array.isArray(record?.members) ? record.members : []
return members.flatMap((entry): OrcaTeamMfaPendingMember[] => {
const member = isRecord(entry) ? entry : null
const email = typeof member?.email === 'string' ? member.email.trim() : ''
if (!member || !email) {
return []
}
const displayName = typeof member.displayName === 'string' ? member.displayName.trim() : ''
return [
{
userId: typeof member.userId === 'string' && member.userId ? member.userId : null,
email,
...(displayName ? { displayName } : {}),
mfa: member.mfa === 'blocked' ? 'blocked' : member.mfa === 'pending' ? 'pending' : 'off'
}
]
})
}
async function request(url: string, init: RequestInit): Promise<unknown> {
const response = await fetch(url, init)
if (!response.ok) {
throw new OrcaCloudRequestError(response.status, await extractErrorCode(response))
}
const body: unknown = await response.json()
return body
}
type Unavailable = Extract<
OrcaTeamMfaPolicyResult,
{
status:
| 'unconfigured'
| 'reconnect-required'
| 'unsupported'
| 'forbidden'
| 'rate-limited'
| 'failed'
}
>
function unavailable(result: Exclude<OrgCallResult<unknown>, { status: 'ok' }>): Unavailable {
if (result.status === 'reconnect-required') {
return { status: 'reconnect-required' }
}
if (result.status === 'failed') {
return { status: 'failed', error: result.error }
}
const { statusCode, errorCode, message } = result.error
if (statusCode === 404 && !errorCode) {
// No JSON error: an auth deployment from before these routes.
return { status: 'unsupported' }
}
if (statusCode === 403) {
return { status: 'forbidden' }
}
if (statusCode === 429) {
return { status: 'rate-limited' }
}
return { status: 'failed', error: message }
}
async function call<T>(
userDataPath: string,
run: (apiBaseUrl: string, accessToken: string, url: (path: string) => string) => Promise<T>,
orgId: string
): Promise<OrgCallResult<T> | { status: 'unconfigured' } | { status: 'unsupported' }> {
const active = ensureActiveOrcaProfile(userDataPath)
// Local dev auth has no server, so no policy.
if (isOrcaCloudDevAuthEnabled()) {
return { status: 'unsupported' }
}
const configState = getOrcaCloudAuthConfig()
if (!configState.configured) {
return { status: 'unconfigured' }
}
const { config } = configState
return runOrgMemberCall(config, active, userDataPath, (session) =>
run(config.apiBaseUrl, session.accessToken, (path) => orgMembersUrl(config, orgId, path))
)
}
export async function getOrcaTeamMfaPolicy(
userDataPath: string,
orgId: string
): Promise<OrcaTeamMfaPolicyResult> {
const result = await call(
userDataPath,
async (apiBaseUrl, token, url) =>
normalizeTeamMfaPolicy(
await request(url('/mfa-policy'), requestInit('GET', token)),
apiBaseUrl
),
orgId
)
if (result.status === 'ok') {
return { status: 'ok', ...result.value }
}
return result.status === 'unconfigured' || result.status === 'unsupported'
? result
: unavailable(result)
}
export async function setOrcaTeamMfaPolicy(
userDataPath: string,
args: { orgId: string; enforce: OrcaTeamMfaGrace | 'off' }
): Promise<OrcaTeamMfaPolicySetResult> {
if (args.enforce !== 'off' && !ORCA_TEAM_MFA_GRACE_CHOICES.includes(args.enforce)) {
return { status: 'failed', error: 'invalid_enforce' }
}
const result = await call(
userDataPath,
async (_apiBaseUrl, token, url) => {
const init =
args.enforce === 'off'
? { ...requestInit('GET', token), method: 'DELETE' }
: { ...requestInit('POST', token, { enforce: args.enforce }), method: 'PUT' }
const answer = await request(url('/mfa-policy'), init)
const body = isRecord(answer) ? answer : null
return {
policy: normalizeDeadline(body?.policy),
pendingMembers: finiteNumber(body?.pendingMembers) ?? 0
}
},
args.orgId
)
if (result.status === 'ok') {
return { status: 'ok', ...result.value }
}
if (result.status === 'unconfigured' || result.status === 'unsupported') {
return result
}
if (result.status === 'request-error') {
const { errorCode } = result.error
if (errorCode === 'actor_needs_mfa') {
return { status: 'actor-needs-mfa' }
}
if (errorCode === 'mfa_enforcement_not_entitled') {
return { status: 'not-entitled' }
}
}
return unavailable(result)
}
export async function listOrcaTeamMfaPending(
userDataPath: string,
orgId: string
): Promise<OrcaTeamMfaPendingResult> {
const result = await call(
userDataPath,
async (_apiBaseUrl, token, url) =>
normalizePendingMembers(await request(url('/mfa-policy/pending'), requestInit('GET', token))),
orgId
)
if (result.status === 'ok') {
return { status: 'ok', members: result.value }
}
return result.status === 'unconfigured' || result.status === 'unsupported'
? result
: unavailable(result)
}
export async function remindOrcaTeamMfa(
userDataPath: string,
args: { orgId: string; userId?: string }
): Promise<OrcaTeamMfaRemindResult> {
const result = await call(
userDataPath,
async (_apiBaseUrl, token, url) => {
const answer = await request(
url('/mfa-policy/remind'),
requestInit('POST', token, args.userId ? { userId: args.userId } : {})
)
const body = isRecord(answer) ? answer : null
const delivery: 'log' | 'test-inbox' | 'unknown' =
body?.delivery === 'log' || body?.delivery === 'test-inbox' ? body.delivery : 'unknown'
return { recipients: finiteNumber(body?.recipients) ?? 0, delivery }
},
args.orgId
)
if (result.status === 'ok') {
return { status: 'ok', ...result.value }
}
if (result.status === 'unconfigured' || result.status === 'unsupported') {
return result
}
if (result.status === 'request-error') {
if (result.error.errorCode === 'no_policy') {
return { status: 'no-policy' }
}
if (result.error.errorCode === 'member_not_found') {
return { status: 'not-found' }
}
}
return unavailable(result)
}
@@ -32,7 +32,8 @@ function devSelf(): OrcaOrgMember {
userId: cleanEnvString(process.env.ORCA_CLOUD_DEV_USER_ID, 'dev-user'),
email: cleanEnvString(process.env.ORCA_CLOUD_DEV_EMAIL, 'dev@orca.local'),
displayName: cleanEnvString(process.env.ORCA_CLOUD_DEV_DISPLAY_NAME, 'Orca Dev'),
role: 'owner'
role: 'owner',
mfa: 'on'
}
}
@@ -44,10 +45,17 @@ function seedDevRoster(): DevOrgRoster {
userId: 'dev-teammate-1',
email: 'teammate@orca.local',
displayName: 'Dev Teammate',
role: 'admin'
role: 'admin',
mfa: 'off'
},
// Null user IDs exercise members who have not signed in yet.
{ userId: null, email: 'invited-member@orca.local', displayName: undefined, role: 'member' }
{
userId: null,
email: 'invited-member@orca.local',
displayName: undefined,
role: 'member',
mfa: 'off'
}
],
pendingInvites: [{ email: 'pending@orca.local', role: 'member', createdAt: Date.now() }]
}
@@ -1,3 +1,4 @@
import type { OrcaOrgMemberMfa } from '../../../shared/orca-account-mfa'
import type {
OrcaOrgMember,
OrcaOrgMembersRoster,
@@ -53,6 +54,22 @@ function optionalPictureUrl(value: unknown): string | undefined {
}
}
const MEMBER_MFA: readonly OrcaOrgMemberMfa[] = ['on', 'off', 'pending']
// Absent for plain members (the server leaves it out); an unknown value is dropped, never guessed.
function normalizeMemberMfa(
record: Record<string, unknown>
): Pick<OrcaOrgMember, 'mfa' | 'mfaDeadline'> {
const mfa = MEMBER_MFA.find((status) => status === record.mfa)
if (!mfa) {
return {}
}
const deadline = record.mfaDeadline
return mfa === 'pending' && typeof deadline === 'number' && Number.isFinite(deadline)
? { mfa, mfaDeadline: deadline }
: { mfa }
}
function normalizeMember(value: unknown): OrcaOrgMember | null {
if (!value || typeof value !== 'object') {
return null
@@ -70,7 +87,8 @@ function normalizeMember(value: unknown): OrcaOrgMember | null {
...(optionalPictureUrl(record.pictureUrl)
? { pictureUrl: optionalPictureUrl(record.pictureUrl) }
: {}),
role: normalizeRole(record.role, 'member')
role: normalizeRole(record.role, 'member'),
...normalizeMemberMfa(record)
}
}
@@ -29,4 +29,30 @@ describe('normalizeRoster', () => {
])
expect('pictureUrl' in roster.members[4]!).toBe(false)
})
it('keeps a known MFA status and drops anything else', () => {
const roster = normalizeRoster({
viewerRole: 'owner',
canManageMembers: true,
pendingInvites: [],
members: [
{ userId: 'a', email: 'a@x.dev', role: 'owner', mfa: 'on' },
{ userId: 'b', email: 'b@x.dev', role: 'member', mfa: 'off', mfaDeadline: 5 },
{ userId: 'c', email: 'c@x.dev', role: 'member', mfa: 'pending', mfaDeadline: 1_800_000 },
{ userId: 'd', email: 'd@x.dev', role: 'member', mfa: 'pending', mfaDeadline: 'soon' },
{ userId: 'e', email: 'e@x.dev', role: 'member', mfa: true },
{ userId: 'f', email: 'f@x.dev', role: 'member' }
]
})
expect(roster.members.map((m) => [m.mfa, m.mfaDeadline])).toEqual([
['on', undefined],
// A deadline only means something while the member is pending.
['off', undefined],
['pending', 1_800_000],
['pending', undefined],
[undefined, undefined],
[undefined, undefined]
])
expect('mfa' in roster.members[5]!).toBe(false)
})
})
@@ -20,7 +20,6 @@ export const orcaCloudWorkspaceApi = {
listCloudWorkspaceIds: () => ipcRenderer.invoke(CH.listCloudWorkspaceIds),
getConfig: () => ipcRenderer.invoke(CH.getConfig),
connectGitHub: (args) => ipcRenderer.invoke(CH.connectGitHub, args),
gitHubInstallLink: (args) => ipcRenderer.invoke(CH.gitHubInstallLink, args),
getGitHubUser: () => ipcRenderer.invoke(CH.getGitHubUser),
connectGitHubUser: () => ipcRenderer.invoke(CH.connectGitHubUser),
gitHubUserConnectLink: () => ipcRenderer.invoke(CH.gitHubUserConnectLink),
+17 -5
View File
@@ -1,3 +1,13 @@
import type {
OrcaTeamMfaPendingResult,
OrcaTeamMfaPolicyArgs,
OrcaTeamMfaPolicyResult,
OrcaTeamMfaPolicySetArgs,
OrcaTeamMfaPolicySetResult,
OrcaTeamMfaRemindArgs,
OrcaTeamMfaRemindResult
} from '../../shared/orca-team-mfa-policy'
import type { OrcaAccountMfaResult } from '../../shared/orca-account-mfa'
import type {
CloudSetupGetResult,
CloudSetupLinkResult,
@@ -45,7 +55,6 @@ import type {
} from '../../shared/orca-profiles'
import type {
OrcaBillingCheckoutArgs,
OrcaBillingLinkResult,
OrcaBillingOpenResult,
OrcaBillingOverageArgs,
OrcaBillingOverageResult,
@@ -85,6 +94,13 @@ export type OrcaProfileApi = {
refreshAuth: () => Promise<RefreshCurrentOrcaProfileAuthResult>
signOutCurrent: () => Promise<SignOutCurrentOrcaProfileResult>
selectOrg: (args: SelectOrcaProfileOrgArgs) => Promise<SelectOrcaProfileOrgResult>
/** The signed-in person's own two-factor state and where to manage it. */
accountMfa: () => Promise<OrcaAccountMfaResult>
/** The team's "require MFA" policy and the person's own state in it. */
teamMfaPolicy: (args: OrcaTeamMfaPolicyArgs) => Promise<OrcaTeamMfaPolicyResult>
teamMfaPolicySet: (args: OrcaTeamMfaPolicySetArgs) => Promise<OrcaTeamMfaPolicySetResult>
teamMfaPending: (args: OrcaTeamMfaPolicyArgs) => Promise<OrcaTeamMfaPendingResult>
teamMfaRemind: (args: OrcaTeamMfaRemindArgs) => Promise<OrcaTeamMfaRemindResult>
orgMembersList: (args: OrcaProfileOrgMembersListArgs) => Promise<OrcaProfileOrgMembersListResult>
orgMemberInvite: (
args: OrcaProfileOrgMemberInviteArgs
@@ -130,10 +146,6 @@ export type OrcaProfileApi = {
cloudSetupLink: (args: { sessionId: string }) => Promise<CloudSetupLinkResult>
/** Opens the Stripe Customer Portal in the browser. */
billingOpenPortal: () => Promise<OrcaBillingOpenResult>
/** "Copy link": a fresh Customer Portal URL, minted but not opened. */
billingPortalLink: () => Promise<OrcaBillingLinkResult>
/** "Copy link": the Checkout URL billingOpenCheckout would open, minted but not opened. */
billingCheckoutLink: (args: OrcaBillingCheckoutArgs) => Promise<OrcaBillingLinkResult>
/** The last 30 days of sandbox hours (breakdowns for owners and admins only). */
billingUsageHistory: (args: {
utcOffsetMinutes: number
+5 -2
View File
@@ -73,6 +73,11 @@ export const orcaProfilesApi = {
refreshAuth: () => ipcRenderer.invoke('orcaProfiles:refreshAuth'),
signOutCurrent: () => ipcRenderer.invoke('orcaProfiles:signOutCurrent'),
selectOrg: (args) => ipcRenderer.invoke('orcaProfiles:selectOrg', args),
accountMfa: () => ipcRenderer.invoke('orcaProfiles:accountMfa'),
teamMfaPolicy: (args) => ipcRenderer.invoke('orcaProfiles:teamMfaPolicy', args),
teamMfaPolicySet: (args) => ipcRenderer.invoke('orcaProfiles:teamMfaPolicySet', args),
teamMfaPending: (args) => ipcRenderer.invoke('orcaProfiles:teamMfaPending', args),
teamMfaRemind: (args) => ipcRenderer.invoke('orcaProfiles:teamMfaRemind', args),
orgMembersList: (args) => ipcRenderer.invoke('orcaProfiles:orgMembersList', args),
orgMemberInvite: (args) => ipcRenderer.invoke('orcaProfiles:orgMemberInvite', args),
orgInviteRevoke: (args) => ipcRenderer.invoke('orcaProfiles:orgInviteRevoke', args),
@@ -102,8 +107,6 @@ export const orcaProfilesApi = {
billingPlans: () => ipcRenderer.invoke('orcaProfiles:billingPlans'),
billingOpenCheckout: (args) => ipcRenderer.invoke('orcaProfiles:billingOpenCheckout', args),
billingOpenPortal: () => ipcRenderer.invoke('orcaProfiles:billingOpenPortal'),
billingPortalLink: () => ipcRenderer.invoke('orcaProfiles:billingPortalLink'),
billingCheckoutLink: (args) => ipcRenderer.invoke('orcaProfiles:billingCheckoutLink', args),
billingTeamPlans: (args) => ipcRenderer.invoke('orcaProfiles:billingTeamPlans', args),
billingUsageHistory: (args) => ipcRenderer.invoke('orcaProfiles:billingUsageHistory', args),
cloudSetupStart: (args) => ipcRenderer.invoke('orcaProfiles:cloudSetupStart', args),
@@ -1,7 +1,6 @@
import { ExternalLink } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { InlineError } from '@/components/ui/inline-error'
import { OpenExternalSplitButton } from '@/components/open-external/OpenExternalSplitButton'
import { billingPortalLink } from './billing-link'
import { useIntlLocale, useTranslate } from '@/i18n/use-translate'
import type { OrcaBillingEntitlement } from '../../../../shared/orca-billing'
@@ -63,20 +62,16 @@ export function PaymentIssueNotice({
}
action={
entitlement.canManageBilling ? (
<OpenExternalSplitButton
<Button
type="button"
variant="outline"
size="xs"
aria-disabled={busy || undefined}
link={billingPortalLink}
onClick={() => {
if (!busy) {
onUpdatePayment()
}
}}
onClick={busy ? undefined : onUpdatePayment}
>
{t('auto.components.billing.updatePayment', 'Update payment method')}
<ExternalLink />
</OpenExternalSplitButton>
</Button>
) : undefined
}
/>
@@ -14,8 +14,6 @@ import {
} from '../../../../shared/orca-billing'
import { openPlansPage } from './plans/plans-page-store'
import { PaymentIssueNotice } from './PaymentIssueNotice'
import { OpenExternalSplitButton } from '@/components/open-external/OpenExternalSplitButton'
import { billingPortalLink } from './billing-link'
import { OverageControls, UsageSummary } from './PlanBillingUsage'
import { denyReasonCopy, openFailureCopy, overageFailureCopy } from './plan-billing-copy'
import { PlanStatusBadge } from './PlanStatusBadge'
@@ -284,20 +282,16 @@ export function PlanBillingView({
</Button>
)}
{hasPlan && entitlement.canManageBilling && entitlement.payment.pastDueSince === null ? (
<OpenExternalSplitButton
<Button
type="button"
variant="outline"
size="sm"
aria-disabled={busy || undefined}
link={billingPortalLink}
onClick={() => {
if (!busy) {
onPortal()
}
}}
onClick={busy ? undefined : onPortal}
>
{t('auto.components.billing.manageBilling', 'Manage billing')}
<ExternalLink />
</OpenExternalSplitButton>
</Button>
) : null}
{hasPlan ? (
// Members have no other action here, so it gets the button's chrome (and its alignment).
@@ -1,56 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
const toastError = vi.fn()
vi.mock('sonner', () => ({ toast: { error: (...args: unknown[]) => toastError(...args) } }))
import { billingCheckoutLink, billingPortalLink } from './billing-link'
function stubApi(api: Record<string, unknown>): void {
vi.stubGlobal('window', { api: { orcaProfiles: api } })
}
afterEach(() => {
toastError.mockReset()
vi.unstubAllGlobals()
})
describe('billing "Copy link"', () => {
it('returns the minted Portal URL without opening anything', async () => {
const billingPortalLink$ = vi.fn(async () => ({
status: 'ok' as const,
url: 'https://billing.stripe.com/p/session/x'
}))
const billingOpenPortal = vi.fn()
stubApi({ billingPortalLink: billingPortalLink$, billingOpenPortal })
await expect(billingPortalLink()).resolves.toBe('https://billing.stripe.com/p/session/x')
expect(billingOpenPortal).not.toHaveBeenCalled()
expect(toastError).not.toHaveBeenCalled()
})
it('mints Checkout for the same order the button would open', async () => {
const mint = vi.fn(async () => ({
status: 'ok' as const,
url: 'https://checkout.stripe.com/c/pay/cs_1'
}))
stubApi({ billingCheckoutLink: mint })
const args = { plan: 'team', interval: 'year' as const, seats: 5 }
await expect(billingCheckoutLink(args)).resolves.toBe('https://checkout.stripe.com/c/pay/cs_1')
expect(mint).toHaveBeenCalledWith(args)
})
it('says why there is no link with the open path’s copy, then yields null', async () => {
stubApi({ billingPortalLink: async () => ({ status: 'forbidden' }) })
await expect(billingPortalLink()).resolves.toBeNull()
expect(toastError).toHaveBeenCalledWith('Only an owner or admin can manage billing.')
})
it('treats a rejected IPC as a failed billing read', async () => {
stubApi({
billingPortalLink: async () => {
throw new Error('boom')
}
})
await expect(billingPortalLink()).resolves.toBeNull()
expect(toastError).toHaveBeenCalledWith('Couldn’t reach billing. Try again.')
})
})
@@ -1,35 +0,0 @@
// "Copy link" for the Stripe buttons: mints the same Checkout/Portal URL the button opens, without
// opening it. A refusal (signed out, not an admin, no billing account…) is said in a toast with the
// open path's own copy, then null, so the split button adds nothing of its own.
import { toast } from 'sonner'
import { translate } from '@/i18n/i18n'
import type {
OrcaBillingCheckoutArgs,
OrcaBillingLinkResult
} from '../../../../shared/orca-billing'
import { openFailureCopy } from './plan-billing-copy'
async function linkOrToast(mint: () => Promise<OrcaBillingLinkResult>): Promise<string | null> {
const result = await mint().catch((error: unknown): OrcaBillingLinkResult => ({
status: 'failed',
error: String(error)
}))
if (result.status === 'ok') {
return result.url
}
const failure = openFailureCopy(result, translate)
if (failure) {
toast.error(failure)
}
return null
}
/** The Customer Portal URL "Manage billing" / "Update payment method" would open. */
export function billingPortalLink(): Promise<string | null> {
return linkOrToast(() => window.api.orcaProfiles.billingPortalLink())
}
/** The Checkout URL a plan's buy button would open for these args. */
export function billingCheckoutLink(args: OrcaBillingCheckoutArgs): Promise<string | null> {
return linkOrToast(() => window.api.orcaProfiles.billingCheckoutLink(args))
}
@@ -2,7 +2,6 @@ import { useEffect, useId, useRef } from 'react'
import { AlertCircle, Check, ExternalLink, Lock, RotateCcw, XCircle } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { LoadingSpinner } from '@/components/LoadingSpinner'
import { OpenExternalSplitButton } from '@/components/open-external/OpenExternalSplitButton'
import { useIntlLocale, useTranslate } from '@/i18n/use-translate'
import { cn } from '@/lib/class-names'
import { openFailureCopy } from '../plan-billing-copy'
@@ -21,8 +20,6 @@ export type CheckoutPanelProps = {
/** When the order was placed; the renewal date counts from it. */
now: number
onReopen: () => void
/** "Copy link" on Reopen / Try again: a fresh Checkout URL for this order (absent: no chevron). */
reopenLink?: () => Promise<string | null>
onKeepWaiting: () => void
onBack: () => void
/** Where "Contact us" goes when billing can't sell the plan (the plan's supportUrl, else Enterprise's contact). */
@@ -224,22 +221,13 @@ export function CheckoutPanel(props: CheckoutPanelProps): React.JSX.Element {
break
}
const reopenLabel = (
<>
const reopen = (
<Button type="button" onClick={props.onReopen}>
{phase.kind === 'canceled' || phase.kind === 'open-failed' ? <RotateCcw /> : null}
{phase.kind === 'canceled' || phase.kind === 'open-failed'
? t('auto.components.billing.checkout.tryAgain', 'Try again')
: t('auto.components.billing.checkout.reopen', 'Reopen checkout')}
{phase.kind === 'canceled' || phase.kind === 'open-failed' ? null : <ExternalLink />}
</>
)
const reopen = props.reopenLink ? (
<OpenExternalSplitButton link={props.reopenLink} onClick={props.onReopen}>
{reopenLabel}
</OpenExternalSplitButton>
) : (
<Button type="button" onClick={props.onReopen}>
{reopenLabel}
</Button>
)
const back = (
@@ -287,14 +275,14 @@ export function CheckoutPanel(props: CheckoutPanelProps): React.JSX.Element {
phase.result.status === 'plan-unavailable' &&
props.contactUrl &&
props.onContact ? (
<OpenExternalSplitButton
<Button
type="button"
variant="outline"
link={props.contactUrl}
onClick={() => props.contactUrl && props.onContact?.(props.contactUrl)}
>
{t('auto.components.billing.checkout.contactUs', 'Contact us')}
<ExternalLink />
</OpenExternalSplitButton>
</Button>
) : null}
{phase.kind === 'timed-out' ? (
<Button type="button" variant="outline" onClick={props.onKeepWaiting}>
@@ -1,9 +1,5 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import type {
OrcaBillingCheckoutArgs,
OrcaBillingOpenResult
} from '../../../../../shared/orca-billing'
import { billingCheckoutLink } from '../billing-link'
import type { OrcaBillingOpenResult } from '../../../../../shared/orca-billing'
import { getBillingGeneration, recordBillingStatusIfCurrent } from '../billing-summary-store'
import { installWindowVisibilityInterval } from '@/lib/window-activity/window-visibility-interval'
import {
@@ -32,21 +28,6 @@ export type CheckoutFlow = {
/** Restarts the watch window after a timeout. */
keepWaiting: () => void
reset: () => void
/** "Copy link" on the checkout button: mints this order's Checkout URL and starts the watch. */
copyLink: (order: CheckoutOrder) => Promise<string | null>
/** "Copy link" on Reopen: a fresh Checkout URL for the same order. */
copyReopenLink: () => Promise<string | null>
}
/** Joins an open setup session, so Checkout returns to its next step (T2 Compare plans). */
function checkoutArgsFor(order: CheckoutOrder): OrcaBillingCheckoutArgs {
const setupSessionId = activeCloudSetupSessionId()
return {
plan: order.planId,
interval: order.interval,
seats: order.seats,
...(setupSessionId ? { setupSessionId } : {})
}
}
/**
@@ -65,8 +46,15 @@ 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(checkoutArgsFor(order))
.billingOpenCheckout({
plan: order.planId,
interval: order.interval,
seats: order.seats,
...(setupSessionId ? { setupSessionId } : {})
})
.catch((error: unknown): OrcaBillingOpenResult => ({
status: 'failed',
error: String(error)
@@ -87,17 +75,6 @@ export function useCheckoutFlow({ onPaid }: { onPaid: (seats: number) => void })
})
}, [])
// "Copy link": the same Checkout session, minted but not opened. Paying from the pasted link
// (another browser profile) is watched exactly like an opened Checkout.
const copyLink = useCallback(async (order: CheckoutOrder): Promise<string | null> => {
const url = await billingCheckoutLink(checkoutArgsFor(order))
if (url) {
++runId.current
setPhase(nextPhaseAfterOpen(order, { status: 'opened' }, Date.now()))
}
return url
}, [])
const reset = useCallback(() => {
runId.current++
setPhase({ kind: 'idle' })
@@ -206,10 +183,5 @@ export function useCheckoutFlow({ onPaid }: { onPaid: (seats: number) => void })
}
}, [order])
const copyReopenLink = useCallback(
(): Promise<string | null> => (order ? copyLink(order) : Promise.resolve(null)),
[order, copyLink]
)
return { phase, start, reopen, keepWaiting, reset, copyLink, copyReopenLink }
return { phase, start, reopen, keepWaiting, reset }
}
@@ -1,5 +1,5 @@
import { Building2, ExternalLink } from 'lucide-react'
import { OpenExternalSplitButton } from '@/components/open-external/OpenExternalSplitButton'
import { Button } from '@/components/ui/button'
import { useIntlLocale, useTranslate } from '@/i18n/use-translate'
import { PlanCardShell } from './PlanCardShell'
import { planFeatureLines } from './plan-feature-copy'
@@ -46,16 +46,15 @@ export function EnterprisePlanCard({
footer={
contactUrl ? (
<>
<OpenExternalSplitButton
<Button
type="button"
variant="outline"
groupClassName="w-full"
className="flex-1"
link={contactUrl}
className="w-full"
onClick={() => onContactSales(contactUrl)}
>
{t('auto.components.billing.plans.contactSales', 'Contact sales')}
<ExternalLink />
</OpenExternalSplitButton>
</Button>
<p className="text-center text-xs text-muted-foreground">
{t(
'auto.components.billing.plans.entHint',
@@ -88,13 +88,6 @@ export function PlansDialogHost(): React.JSX.Element {
setOrderedAt(Date.now())
checkout.start({ planId, interval, seats: count })
}}
checkoutLink={async ({ planId, interval, seats: count }) => {
const url = await checkout.copyLink({ planId, interval, seats: count })
if (url) {
setOrderedAt(Date.now())
}
return url
}}
onManage={() => void openPortal()}
onContactSales={(url) => void window.api.shell.openUrl(url)}
onRetry={() => {
@@ -126,7 +119,6 @@ export function PlansDialogHost(): React.JSX.Element {
}
checkout.reopen()
}}
reopenLink={checkout.copyReopenLink}
contactUrl={plans.state === 'ready' ? planContactUrl(plans.model) : null}
onContact={(url) => void window.api.shell.openUrl(url)}
onKeepWaiting={checkout.keepWaiting}
@@ -49,13 +49,6 @@ describe("plans dialog from billing's catalog", () => {
expect(props.onContactSales).toHaveBeenCalledWith('https://orca.dev/enterprise')
})
it('gives checkout and Contact sales a "Copy link" chevron for the same order', () => {
const checkoutLink = vi.fn(async () => 'https://checkout.stripe.com/c/pay/cs_1')
render(<PlansView {...view({ checkoutLink })} />)
// One chevron on the checkout button, one on Contact sales.
expect(screen.getAllByRole('button', { name: 'More link options' })).toHaveLength(2)
})
it('offers only the intervals Stripe prices: no toggle with one', () => {
render(<PlansView {...view({ catalog: monthlyOnlyCatalogResult })} />)
expect(screen.queryByRole('radiogroup')).toBeNull()
@@ -36,12 +36,6 @@ export type PlansViewProps = {
/** Seats Checkout will bill: org members, or 1 for a personal account. */
seats: number
onCheckout: (args: { planId: string; interval: OrcaBillingInterval; seats: number }) => void
/** "Copy link" on the checkout button: the Checkout URL it would open (absent: no chevron). */
checkoutLink?: (args: {
planId: string
interval: OrcaBillingInterval
seats: number
}) => Promise<string | null>
onManage: () => void
onContactSales: (url: string) => void
onRetry: () => void
@@ -209,11 +203,6 @@ export function PlansView(props: PlansViewProps): React.JSX.Element {
notice={props.notice}
hideManage={paymentIssue}
onCheckout={() => props.onCheckout({ planId: team.planId, interval, seats })}
checkoutLink={
props.checkoutLink
? () => props.checkoutLink!({ planId: team.planId, interval, seats })
: undefined
}
onManage={props.onManage}
/>
{enterprise ? (
@@ -2,8 +2,6 @@ import { ExternalLink, Lock, Users } from 'lucide-react'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { InlineError } from '@/components/ui/inline-error'
import { OpenExternalSplitButton } from '@/components/open-external/OpenExternalSplitButton'
import { billingPortalLink } from '../billing-link'
import type { PlanBillingNotice } from '../PlanBillingSection'
import { LoadingSpinner } from '@/components/LoadingSpinner'
import { useIntlLocale, useTranslate } from '@/i18n/use-translate'
@@ -24,7 +22,6 @@ export function TeamPlanCard({
notice,
hideManage,
onCheckout,
checkoutLink,
onManage
}: {
team: TeamPlanModel
@@ -37,8 +34,6 @@ export function TeamPlanCard({
/** A payment banner already offers the same Portal action. */
hideManage: boolean
onCheckout: () => void
/** "Copy link": mints the Checkout URL the button opens (absent: a plain button). */
checkoutLink?: () => Promise<string | null>
onManage: () => void
}): React.JSX.Element {
const t = useTranslate()
@@ -131,41 +126,20 @@ export function TeamPlanCard({
</p>
)
} else if (mode === 'choose') {
const checkoutLabel = (
<>
{busy ? <LoadingSpinner /> : null}
{busy
? t('auto.components.billing.plans.waiting', 'Waiting for checkout…')
: t('auto.components.billing.plans.checkout', 'Continue to checkout')}
{busy ? null : <ExternalLink />}
</>
)
footer = (
<>
{checkoutLink ? (
<OpenExternalSplitButton
groupClassName="w-full"
className="flex-1"
aria-disabled={busy || undefined}
link={checkoutLink}
onClick={() => {
if (!busy) {
onCheckout()
}
}}
>
{checkoutLabel}
</OpenExternalSplitButton>
) : (
<Button
type="button"
className="w-full"
aria-disabled={busy || undefined}
onClick={busy ? undefined : onCheckout}
>
{checkoutLabel}
</Button>
)}
<Button
type="button"
className="w-full"
aria-disabled={busy || undefined}
onClick={busy ? undefined : onCheckout}
>
{busy ? <LoadingSpinner /> : null}
{busy
? t('auto.components.billing.plans.waiting', 'Waiting for checkout…')
: t('auto.components.billing.plans.checkout', 'Continue to checkout')}
{busy ? null : <ExternalLink />}
</Button>
{notice?.kind === 'error' ? (
<InlineError title={notice.text} />
) : (
@@ -189,21 +163,16 @@ export function TeamPlanCard({
</p>
) : (
<>
<OpenExternalSplitButton
<Button
type="button"
variant="outline"
groupClassName="w-full"
className="flex-1"
className="w-full"
aria-disabled={busy || undefined}
link={billingPortalLink}
onClick={() => {
if (!busy) {
onManage()
}
}}
onClick={busy ? undefined : onManage}
>
{t('auto.components.billing.manageBilling', 'Manage billing')}
<ExternalLink />
</OpenExternalSplitButton>
</Button>
{notice?.kind === 'error' ? (
<InlineError title={notice.text} />
) : (
@@ -1,3 +1,4 @@
import { useTeamMfaGate } from '@/components/team-mfa/TeamMfaGate'
import { useCallback, useEffect, useRef, useState } from 'react'
import { toast } from 'sonner'
import { Dialog, DialogContent, DialogDescription, DialogTitle } from '@/components/ui/dialog'
@@ -37,6 +38,7 @@ export function TeamPageBody({
const cloud = authStatus?.cloud
const orgId = cloud?.activeOrgId ?? null
const roster = useOrgRoster(orgId)
const mfa = useTeamMfaGate()
const billing = useOrcaBillingStatus(true)
const [userRefreshing, setUserRefreshing] = useState(false)
const [billingBusy, setBillingBusy] = useState(false)
@@ -174,6 +176,7 @@ export function TeamPageBody({
<>
<TeamPageView
org={org}
mfaNotice={mfa.blocked ?? mfa.banner}
viewerUserId={cloud?.userId ?? null}
roster={rosterResult}
billing={billing.result}
@@ -67,3 +67,90 @@ it('offers Leave from the ⋯ on your own row only', () => {
// A plain member has nothing to do on someone else's row.
expect(other.querySelector('button[aria-label^="Actions for"]')).toBeNull()
})
function renderList(
listRoster: OrcaOrgMembersRoster,
viewerUserId: string
): ReturnType<typeof render> {
return render(
<TeamMemberList
rows={teamRows(listRoster, viewerUserId)}
viewerRole={listRoster.viewerRole}
rowStates={{}}
canLeave
now={Date.UTC(2026, 10, 18)}
onChangeRole={noop}
onMakeOwner={noop}
onRemove={noop}
onResend={noop}
onRevoke={noop}
onLeave={noop}
/>
)
}
const rosterWithMfa: OrcaOrgMembersRoster = {
...roster,
members: [
{ ...roster.members[0]!, mfa: 'on' },
{ ...roster.members[1]!, mfa: 'pending', mfaDeadline: Date.UTC(2026, 10, 24, 12) }
],
pendingInvites: [{ email: 'alex@acme.dev', role: 'member', createdAt: Date.UTC(2026, 10, 17) }]
}
it.each(['owner', 'admin'] as const)('shows the MFA column to an %s', (viewerRole) => {
const { container } = renderList({ ...rosterWithMfa, viewerRole }, 'u-neil')
const cell = (key: string): Element =>
container.querySelector(`[data-team-row="${key}"] [data-team-mfa]`)!
expect(cell('member:u-neil').textContent).toBe('MFA on')
expect(cell('member:u-grace').textContent).toBe('MFA due Nov 24')
// A small muted badge, not bare text.
expect(cell('member:u-neil').querySelector('[data-slot="badge"]')).not.toBeNull()
// Invites keep an empty cell so the role column stays aligned.
expect(cell('invite:alex@acme.dev').textContent).toBe('')
})
it('hides the MFA column from a plain member, even if a roster carried the status', () => {
const { container } = renderList(
{ ...rosterWithMfa, viewerRole: 'member', canManageMembers: false },
'u-grace'
)
expect(container.querySelector('[data-team-mfa]')).toBeNull()
expect(container.textContent).not.toContain('MFA')
})
it('shows no MFA column when the server sent no status', () => {
const { container } = renderList(roster, 'u-neil')
expect(container.querySelector('[data-team-mfa]')).toBeNull()
})
it('leaves the cell blank, not "off", for a member with no status', () => {
const { container } = renderList(
{
...roster,
members: [{ ...roster.members[0]!, mfa: 'off' }, roster.members[1]!]
},
'u-neil'
)
const cell = (key: string): Element =>
container.querySelector(`[data-team-row="${key}"] [data-team-mfa]`)!
expect(cell('member:u-neil').textContent).toBe('MFA off')
expect(cell('member:u-grace').textContent).toBe('')
})
it('shows no MFA badge for a member who has not signed in yet', () => {
const { container } = renderList(
{
...roster,
members: [
{ ...roster.members[0]!, mfa: 'on' },
{ userId: null, email: 'linus@acme.dev', role: 'member', mfa: 'off' }
]
},
'u-neil'
)
const pending = container.querySelector(
'[data-team-row="member:linus@acme.dev"] [data-team-mfa]'
)!
expect(pending.textContent).toBe('')
})
@@ -29,6 +29,7 @@ import { useIntlLocale, useTranslate } from '@/i18n/use-translate'
import type { OrcaOrgMember, OrcaOrgRole } from '../../../../../shared/orca-profiles'
import { PersonAvatar } from './TeamAvatar'
import { invitedAsCopy, memberStatusLabel, roleDescription } from './team-copy'
import { memberMfaLabel, showMfaColumn } from './team-member-mfa'
import { assignableRoles, roleLabel } from './team-roles'
import type { TeamRow } from './team-roster-rows'
@@ -243,6 +244,7 @@ function RowMenu({
export function TeamMemberList(props: TeamMemberListProps): React.JSX.Element {
const t = useTranslate()
const locale = useIntlLocale()
const mfaColumn = showMfaColumn(props.rows, props.viewerRole)
return (
<ul
className="divide-y divide-border/60 overflow-hidden rounded-lg border border-border"
@@ -314,6 +316,21 @@ export function TeamMemberList(props: TeamMemberListProps): React.JSX.Element {
) : null}
</div>
{state.busy ? <LoadingSpinner className="size-3.5 shrink-0" /> : null}
{mfaColumn ? (
// Rendered for every row, invites included, so the role column stays aligned.
<span
data-team-mfa={row.kind === 'member' ? (row.member.mfa ?? '') : ''}
className="flex w-28 shrink-0"
>
{/* Only for members who have signed in: someone still pending has no account
state yet, so "off" would mislead. */}
{row.kind === 'member' &&
row.status === 'active' &&
memberMfaLabel(row.member, locale, t) ? (
<Badge variant="tag">{memberMfaLabel(row.member, locale, t)}</Badge>
) : null}
</span>
) : null}
{row.kind === 'member' ? (
<RoleControl
row={row}
@@ -128,6 +128,37 @@ export const memberReadOnly = defineFixture({
)
})
// What the server sends an owner or admin: every member carries an MFA status.
const rosterWithMfa: OrcaOrgMembersRoster = {
...roster,
members: [
{ ...roster.members[0]!, mfa: 'on' },
{ ...roster.members[1]!, mfa: 'off' },
{ ...roster.members[2]!, mfa: 'pending', mfaDeadline: NOW + 6 * DAY },
{ ...roster.members[3]!, mfa: 'off' }
]
}
export const ownerSeesMfaColumn = defineFixture({
width,
render: () => <Page roster={{ status: 'ok', roster: rosterWithMfa }} />
})
export const adminSeesMfaColumn = defineFixture({
width,
render: () => (
<Page
viewerUserId="u-ada"
roster={{ status: 'ok', roster: { ...rosterWithMfa, viewerRole: 'admin' } }}
/>
)
})
export const mfaColumnNarrow = defineFixture({
width: 640,
render: () => <Page roster={{ status: 'ok', roster: rosterWithMfa }} />
})
export const rowBusyAndError = defineFixture({
width,
render: () => (
@@ -26,6 +26,8 @@ import type { TeamPageArrival } from './team-page-store'
export type TeamPageViewProps = {
/** The active team, or null on a personal account. */
org: { orgId: string; name: string } | null
/** The team's MFA requirement for this person: the countdown banner or the setup screen. */
mfaNotice?: React.ReactNode
viewerUserId: string | null
roster: OrcaProfileOrgMembersListResult | null
billing: OrcaBillingStatusResult | null
@@ -114,6 +116,7 @@ export function TeamPageView(props: TeamPageViewProps): React.JSX.Element {
return (
<div className="space-y-6">
{props.mfaNotice ?? null}
<header className="flex items-center gap-3">
<TeamMark name={props.org.name} />
<div className="min-w-0 flex-1">
@@ -0,0 +1,40 @@
// The MFA column of the team list: who sees it and what each cell says. Pure, so the view and its
// tests share it.
import type { Translate } from '@/i18n/use-translate'
import type { OrcaOrgMember, OrcaOrgRole } from '../../../../../shared/orca-profiles'
import type { TeamRow } from './team-roster-rows'
/**
* Owners and admins only. The server already leaves the status out for everyone else; the role
* check keeps the column hidden even if a roster carrying it ever reached a member's desktop.
*/
export function showMfaColumn(rows: readonly TeamRow[], viewerRole: OrcaOrgRole): boolean {
return (
(viewerRole === 'owner' || viewerRole === 'admin') &&
rows.some((row) => row.kind === 'member' && row.member.mfa !== undefined)
)
}
/** Null when the provider said nothing about this member: shown as blank, never as "off". */
export function memberMfaLabel(
member: Pick<OrcaOrgMember, 'mfa' | 'mfaDeadline'>,
locale: string,
t: Translate
): string | null {
switch (member.mfa) {
case 'on':
return t('auto.components.billing.team.mfaOn', 'MFA on')
case 'off':
return t('auto.components.billing.team.mfaOff', 'MFA off')
case 'pending':
return member.mfaDeadline === undefined
? t('auto.components.billing.team.mfaPending', 'MFA pending')
: t('auto.components.billing.team.mfaPendingBy', 'MFA due {{value0}}', {
value0: new Intl.DateTimeFormat(locale, { month: 'short', day: 'numeric' }).format(
member.mfaDeadline
)
})
case undefined:
return null
}
}
@@ -6,6 +6,7 @@ import { InlineError } from '@/components/ui/inline-error'
import { Skeleton } from '@/components/ui/skeleton'
import { useTranslate } from '@/i18n/use-translate'
import { SignInAgainNotice } from '@/components/orca-cloud/SignInAgainButton'
import { TeamMfaRefused } from '@/components/team-mfa/TeamMfaAppBanner'
import { describeInlineError } from './cloud-workspace-errors'
import { openCloudWorkspacePicker } from './cloud-workspace-picker-store'
@@ -24,6 +25,16 @@ export function ErrorState({
onSignIn: () => void
}): React.JSX.Element {
const t = useTranslate()
if (reason === 'mfa_required') {
// The team's MFA policy refused this, so neither signing in again nor retrying helps: show
// the setup screen, and under it the plain sentence in case the policy could not be read.
return (
<>
<TeamMfaRefused />
<InlineError className="m-1" tone="neutral" title={describeInlineError(error, reason, t)} />
</>
)
}
if (error === 'unauthorized') {
return <SignInAgainNotice className="m-1" onSignIn={onSignIn} />
}
@@ -29,12 +29,23 @@ export function isUnknownServerFailure(error: string, status?: number): boolean
return status !== undefined && status >= 500 && !DESCRIBED_CODES.has(error)
}
/** The team's MFA policy refused the request: not a session problem, so never "sign in again". */
export function mfaRequiredMessage(t: Translate = translate): string {
return t(
'auto.components.teamMfa.requiredInline',
'Your team requires two-factor authentication. Set it up in Settings, Account to use its cloud workspaces.'
)
}
export function describeError(
error: string,
reason?: string,
t: Translate = translate,
owner?: CloudWorkspaceSeatOwner
): string {
if (reason === 'mfa_required') {
return mfaRequiredMessage(t)
}
if (error === 'not_found') {
return t(
'auto.components.cloudWorkspaces.errorNotFound',
@@ -133,6 +144,9 @@ export function describeInlineError(
reason?: string,
t: Translate = translate
): string {
if (reason === 'mfa_required') {
return mfaRequiredMessage(t)
}
if (error === 'unauthorized') {
return signInAgainMessage(t)
}
@@ -0,0 +1,68 @@
// A cloud workspace's share link: the org slug + W-number link when known, else the sandbox-id form.
import { toast } from 'sonner'
import { translate } from '@/i18n/i18n'
import { cloudWorkspaceShareLink } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire'
import { cloudWorkspaceIdentity, rememberCloudWorkspaces } from './cloud-workspace-identity'
// How long Copy link waits on the control plane before settling for the sandbox-id link.
const LINK_LOOKUP_MS = 3_000
async function lookUpLink(id: string): Promise<string | null> {
let timer: ReturnType<typeof setTimeout> | undefined
try {
const fetched = await Promise.race([
window.api.cloudWorkspaces.get(id),
new Promise<null>((resolve) => {
timer = setTimeout(() => resolve(null), LINK_LOOKUP_MS)
})
])
if (!fetched?.ok) {
return null
}
rememberCloudWorkspaces([fetched.value])
return fetched.value.link ?? null
} catch {
return null
} finally {
clearTimeout(timer)
}
}
/**
* The org slug + W-number link when the control plane gave one, else the sandbox id form, which
* opens for anyone with access. Never rejects: a device that didn't create the workspace (paired,
* offline, signed out) still gets a working link.
*/
export async function shareLinkFor(id: string, chatId?: string | null): Promise<string> {
const link = cloudWorkspaceIdentity(id)?.link ?? (await lookUpLink(id))
return cloudWorkspaceShareLink({ id, ...(link ? { link } : {}) }, chatId)
}
export async function copyCloudWorkspaceLink(
id: string,
chatId?: string | null,
options: { quiet?: boolean } = {}
): Promise<boolean> {
const link = await shareLinkFor(id, chatId)
try {
// Why: main-process clipboard, like every other renderer copy. navigator.clipboard needs a
// focused document with live user activation; after the link lookup (or from the menu or a
// shortcut) Electron rejects it with "Document is not focused".
await window.api.ui.writeClipboardText(link)
} catch (error) {
console.warn('[cloud-workspaces] copy link failed', error)
toast.error(
translate('auto.components.cloudWorkspaces.copyFailed', "Couldn't copy the link. Try again.")
)
return false
}
if (options.quiet) {
return true
}
toast.success(
chatId
? translate('auto.components.cloudWorkspaces.chatLinkCopied', 'Chat link copied')
: translate('auto.components.cloudWorkspaces.workspaceLinkCopied', 'Workspace link copied')
)
return true
}
@@ -11,8 +11,6 @@ import { activateAndRevealWorktree } from '@/lib/workspace/activation/worktree-a
import { refreshRuntimeProjectWorktreesAndLineage } from '@/hooks/runtime-project-refresh-scheduler'
import { RuntimeRpcCallError, unwrapRuntimeRpcResult } from '@/runtime/rpc/calls/runtime-rpc-result'
import type { CloudWorkspace } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire'
import { cloudWorkspaceShareLink } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire'
import { cloudWorkspaceIdentity, rememberCloudWorkspaces } from './cloud-workspace-identity'
import {
getWorktreeExecutionHostId,
toRuntimeExecutionHostId
@@ -66,7 +64,20 @@ function isPairingRejected(error: unknown): boolean {
return error instanceof Error && /\b(unauthori[sz]ed|device_revoked)\b/i.test(error.message)
}
async function connectAndReveal(environmentId: string, name: string): Promise<OpenOutcome> {
export type OpenCloudWorkspaceOptions = {
/**
* The server this open connects to, before any of its rows load. A GitHub-only create's sheet
* hides that server's rows until it hands off to them, so its pending row never doubles up.
*/
onHost?: (hostId: string) => void
}
async function connectAndReveal(
environmentId: string,
name: string,
options: OpenCloudWorkspaceOptions = {}
): Promise<OpenOutcome> {
options.onHost?.(toRuntimeExecutionHostId(environmentId))
const environments = await window.api.runtimeEnvironments.list()
useAppStore.getState().setRuntimeEnvironments(environments)
const environment = environments.find((e) => e.id === environmentId)
@@ -147,7 +158,11 @@ async function wakeIfAsleep(workspace: CloudWorkspace): Promise<OpenOutcome | nu
}
}
async function pairAndReveal(workspace: CloudWorkspace, name: string): Promise<OpenOutcome> {
async function pairAndReveal(
workspace: CloudWorkspace,
name: string,
options: OpenCloudWorkspaceOptions
): Promise<OpenOutcome> {
const api = window.api.cloudWorkspaces
const binding = (await api.environmentBindings())[workspace.id]
if (binding) {
@@ -161,7 +176,7 @@ async function pairAndReveal(workspace: CloudWorkspace, name: string): Promise<O
return refused
}
try {
return await connectAndReveal(binding.environmentId, name)
return await connectAndReveal(binding.environmentId, name, options)
} catch (error) {
// Only a rejected pairing is fixed by pairing again; anything else is surfaced as is.
if (!isPairingRejected(error)) {
@@ -213,10 +228,13 @@ async function pairAndReveal(workspace: CloudWorkspace, name: string): Promise<O
}
// Messages to this workspace now carry the sender line if it is shared with the team.
void refreshCloudMessageSenders().catch(() => undefined)
return await connectAndReveal(added.environment.id, name)
return await connectAndReveal(added.environment.id, name, options)
}
async function openOnce(workspace: CloudWorkspace): Promise<OpenOutcome> {
async function openOnce(
workspace: CloudWorkspace,
options: OpenCloudWorkspaceOptions
): Promise<OpenOutcome> {
const name = cloudWorkspaceTitle(workspace)
try {
if (workspace.access === 'owner') {
@@ -244,7 +262,7 @@ async function openOnce(workspace: CloudWorkspace): Promise<OpenOutcome> {
)
}
}
return await pairAndReveal(workspace, name)
return await pairAndReveal(workspace, name, options)
} catch (error) {
// Raw transport/RPC messages are not user copy; keep them for diagnostics only.
console.warn('[cloud-workspaces] open failed', error)
@@ -262,75 +280,18 @@ async function openOnce(workspace: CloudWorkspace): Promise<OpenOutcome> {
// instead of minting parallel grants.
const opening = new Map<string, Promise<OpenOutcome>>()
export function openCloudWorkspace(workspace: CloudWorkspace): Promise<OpenOutcome> {
export function openCloudWorkspace(
workspace: CloudWorkspace,
options: OpenCloudWorkspaceOptions = {}
): Promise<OpenOutcome> {
const existing = opening.get(workspace.id)
if (existing) {
return existing
}
const attempt = openOnce(workspace).finally(() => opening.delete(workspace.id))
const attempt = openOnce(workspace, options).finally(() => opening.delete(workspace.id))
opening.set(workspace.id, attempt)
return attempt
}
// How long Copy link waits on the control plane before settling for the sandbox-id link.
const LINK_LOOKUP_MS = 3_000
async function lookUpLink(id: string): Promise<string | null> {
let timer: ReturnType<typeof setTimeout> | undefined
try {
const fetched = await Promise.race([
window.api.cloudWorkspaces.get(id),
new Promise<null>((resolve) => {
timer = setTimeout(() => resolve(null), LINK_LOOKUP_MS)
})
])
if (!fetched?.ok) {
return null
}
rememberCloudWorkspaces([fetched.value])
return fetched.value.link ?? null
} catch {
return null
} finally {
clearTimeout(timer)
}
}
/**
* The org slug + W-number link when the control plane gave one, else the sandbox id form, which
* opens for anyone with access. Never rejects: a device that didn't create the workspace (paired,
* offline, signed out) still gets a working link.
*/
export async function shareLinkFor(id: string, chatId?: string | null): Promise<string> {
const link = cloudWorkspaceIdentity(id)?.link ?? (await lookUpLink(id))
return cloudWorkspaceShareLink({ id, ...(link ? { link } : {}) }, chatId)
}
export async function copyCloudWorkspaceLink(
id: string,
chatId?: string | null,
options: { quiet?: boolean } = {}
): Promise<boolean> {
const link = await shareLinkFor(id, chatId)
try {
// Why: main-process clipboard, like every other renderer copy. navigator.clipboard needs a
// focused document with live user activation; after the link lookup (or from the menu or a
// shortcut) Electron rejects it with "Document is not focused".
await window.api.ui.writeClipboardText(link)
} catch (error) {
console.warn('[cloud-workspaces] copy link failed', error)
toast.error(
translate('auto.components.cloudWorkspaces.copyFailed', "Couldn't copy the link. Try again.")
)
return false
}
if (options.quiet) {
return true
}
toast.success(
chatId
? translate('auto.components.cloudWorkspaces.chatLinkCopied', 'Chat link copied')
: translate('auto.components.cloudWorkspaces.workspaceLinkCopied', 'Workspace link copied')
)
return true
}
// Copy link lives beside it; re-exported so callers keep one import.
export { copyCloudWorkspaceLink, shareLinkFor } from './cloud-workspace-share-link'
@@ -0,0 +1,15 @@
import { toast } from 'sonner'
import type { Translate } from '@/i18n/use-translate'
/**
* "Shared with your team", with the one thing that changes for the owner (SEC-5): their personal
* secrets stop being injected once teammates can open the workspace.
*/
export function toastSharedWithTeam(t: Translate): void {
toast.success(t('auto.components.cloudWorkspaces.sharedWithYourTeam', 'Shared with your team'), {
description: t(
'auto.components.cloudWorkspaces.sharedPersonalSecretsNote',
'Your personal cloud secrets aren’t used in shared workspaces. Shared and repository secrets still are.'
)
})
}
@@ -21,6 +21,7 @@ import type { RowActions } from './CloudWorkspaceRowMenu'
import { CloudWorkspaceConfirmDialog, type PendingConfirm } from './CloudWorkspaceConfirmDialog'
import { CloudReadSnapshotSheet } from './CloudReadSnapshotSheet'
import { useCloudReadPanel } from './use-cloud-read-panel'
import { toastSharedWithTeam } from './shared-with-team-toast'
/** Names for every member id the rows show, and whether you are a team owner or admin. */
export function useMemberDirectory(
@@ -130,9 +131,7 @@ export function useCloudWorkspaceRowActions({
void refreshCloudMessageSenders().catch(() => undefined)
}
if (change.visibility === 'team') {
toast.success(
t('auto.components.cloudWorkspaces.sharedWithYourTeam', 'Shared with your team')
)
toastSharedWithTeam(t)
} else if (change.visibility === 'private') {
toast.success(
t(
@@ -1,20 +1,12 @@
// PROJ-MENU part 2: "Give Orca Cloud access to more repositories" moves out of the project list into
// the Add project menu, in its own "Orca Cloud" group: "Add a GitHub repository…".
import React from 'react'
import { Github, Link2 } from 'lucide-react'
import { Github } from 'lucide-react'
import { DropdownMenuItem, DropdownMenuSeparator } from '@/components/ui/dropdown-menu'
import { useTranslate } from '@/i18n/use-translate'
import { copyExternalLink } from '@/components/open-external/copy-external-link'
import { gitHubInstallLinkSource } from '@/lib/orca-cloud/github-link-sources'
import type { ProjectComboboxAddProjectMenu } from './ProjectComboboxAddProjectOption'
function FromGitHubItem({
onSelect,
onCopyLink
}: {
onSelect: () => void
onCopyLink: () => void
}): React.JSX.Element {
function FromGitHubItem({ onSelect }: { onSelect: () => void }): React.JSX.Element {
const t = useTranslate()
return (
<>
@@ -33,13 +25,6 @@ function FromGitHubItem({
{t('components.newWorkspace.cloudOnly.addRepositoryMenu', 'Add a GitHub repository…')}
</span>
</DropdownMenuItem>
{/* A menu row can't carry a chevron: the same GitHub page, copied for another browser. */}
<DropdownMenuItem onSelect={onCopyLink}>
<Link2 />
<span className="truncate">
{t('components.newWorkspace.cloudOnly.copyAddRepositoryLink', 'Copy GitHub link')}
</span>
</DropdownMenuItem>
</>
)
}
@@ -60,10 +45,6 @@ export function cloudAddProjectExtraItems(
closeMenus()
onMoreCloudAccess()
}}
onCopyLink={() => {
closeMenus()
void copyExternalLink(gitHubInstallLinkSource())
}}
/>
)
}
@@ -78,7 +78,7 @@ export function useCloudStartSteps({
onGranted: () => grantedRef.current?.(repoNameRef.current),
...(setupSessionId ? { setupSessionId } : {})
})
const { state, access: grant, repoName, owner, loading, openInstall, installLink } = repoAccess
const { state, access: grant, repoName, owner, loading, openInstall } = repoAccess
useEffect(() => {
repoNameRef.current = repoName
}, [repoName])
@@ -120,5 +120,5 @@ export function useCloudStartSteps({
),
[access, agentRow, availability, github, githubOverride, session, state]
)
return { steps, session, openInstall, installLink }
return { steps, session, openInstall }
}
@@ -0,0 +1,102 @@
// @vitest-environment happy-dom
// AUTH-ONLY-COPY-LINK: "Copy link" (the split's chevron) is for sign-in pages only, where people paste
// the URL into an incognito window. Billing, help, support and the GitHub App install keep a plain
// button, and nothing adds a "Copy … link" row next to them.
import { cleanup, render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, expect, it, vi } from 'vitest'
import { TooltipProvider } from '@/components/ui/tooltip'
import { PaymentIssueNotice } from '@/components/billing/PaymentIssueNotice'
import { sampleTeam } from '@/components/billing/plan-billing-fixtures'
import {
FailureActionRow,
type VmBuildFailureActions
} from '@/components/worktree-creation/VmBuildFailureActions'
import { translate } from '@/i18n/i18n'
import { OpenExternalSplitButton } from './OpenExternalSplitButton'
afterEach(cleanup)
const chevrons = (): number => document.querySelectorAll('[data-open-external-chevron]').length
const actions: VmBuildFailureActions = {
onFixWithAgent: vi.fn(),
onRetry: vi.fn(),
onEditRecipe: vi.fn(),
onOpenAnyway: vi.fn(),
onStartAgain: vi.fn(),
onDismiss: vi.fn(),
onSeePlans: vi.fn(),
onOpenBilling: vi.fn(),
onCreateLocally: vi.fn(),
onSignIn: vi.fn(),
onShowWorkspaces: vi.fn(),
onContactSupport: vi.fn(),
onConnectGitHub: vi.fn(),
onPushToGitHub: vi.fn()
}
function failureRow(kind: 'githubNotConnected' | 'noGithubRemote' | 'snapshotMissing'): void {
render(
<TooltipProvider>
<FailureActionRow
failure={{ kind }}
cloud
vmKept={false}
canFixWithAgent={false}
canManageBilling
signingIn={false}
connectingGitHub={false}
actions={actions}
t={translate}
/>
</TooltipProvider>
)
}
it('keeps the chevron on a sign-in button', () => {
render(
<OpenExternalSplitButton link="https://claude.ai/oauth/authorize" onClick={() => {}}>
Open again
</OpenExternalSplitButton>
)
expect(chevrons()).toBe(1)
})
it('"Update payment method" is a plain button', () => {
render(
<PaymentIssueNotice
entitlement={{
...sampleTeam,
payment: { pastDueSince: 1, graceEndsAt: null, suspendRunning: true }
}}
busy={false}
onUpdatePayment={() => {}}
/>
)
expect(screen.getByRole('button', { name: /Update payment method/ })).toBeTruthy()
expect(chevrons()).toBe(0)
})
it('Connect GitHub (App install) and "How to push to GitHub" are plain buttons', () => {
failureRow('githubNotConnected')
expect(screen.getByRole('button', { name: /Connect GitHub/ })).toBeTruthy()
expect(chevrons()).toBe(0)
cleanup()
failureRow('noGithubRemote')
expect(screen.getByRole('button', { name: /How to push to GitHub/ })).toBeTruthy()
expect(chevrons()).toBe(0)
})
it('"Contact support" has no "Copy support link" row beside it', async () => {
failureRow('snapshotMissing')
const more = screen.queryAllByRole('button').find((b) => b.getAttribute('aria-haspopup'))
expect(more).toBeTruthy()
await userEvent.setup().click(more!)
const menu = await screen.findByRole('menu')
const items = within(menu)
.getAllByRole('menuitem')
.map((item) => item.textContent?.trim())
expect(items.some((label) => label?.includes('Contact support'))).toBe(true)
expect(items.some((label) => /copy/i.test(label ?? ''))).toBe(false)
})
@@ -1,7 +1,6 @@
import React from 'react'
import { ExternalLink } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { OpenExternalSplitButton } from '@/components/open-external/OpenExternalSplitButton'
import { openAppHttpLink } from '@/lib/browser/navigation/app-http-link-open'
import { useTranslate } from '@/i18n/use-translate'
@@ -24,14 +23,10 @@ export function CloudCapabilityOffActions({
{t('cloudSetupPage.capability.tryAgain', 'Try again')}
</Button>
{contactUrl ? (
<OpenExternalSplitButton
variant="outline"
link={contactUrl}
onClick={() => openAppHttpLink(contactUrl)}
>
<Button type="button" variant="outline" onClick={() => openAppHttpLink(contactUrl)}>
{t('cloudSetupPage.capability.contact', 'Contact us')}
<ExternalLink aria-hidden />
</OpenExternalSplitButton>
</Button>
) : null}
</div>
)
@@ -36,8 +36,7 @@ function flow(rows: CloudSetupStep[], teamSwitch = false): CloudSetupFlow {
checkAgain: noop,
contactUrl: null,
reopenBrowser: noop,
reopenLink: null,
installGitHubLink: null
reopenLink: null
}
}
@@ -211,7 +211,7 @@ function StepActions({
</Button>
)
case 'github-install':
return browser(continueLabel, flow.installGitHub, flow.installGitHubLink)
return browser(continueLabel, flow.installGitHub)
case 'start-trial':
return (
<Button type="button" onClick={flow.startTrial} disabled={flow.busy}>
@@ -105,10 +105,11 @@ export type CloudSetupFlow = CloudSetupPageModel & {
/** Where "Contact us" goes when Orca Cloud isn't turned on for the team; null hides it. */
contactUrl: string | null
reopenBrowser: () => void
/** "Copy link" beside Reopen browser: a fresh one-time setup link; null without a session. */
/**
* "Copy link" beside Reopen browser on the sign-in step: a fresh one-time setup link. Null on
* other steps (plan, billing, GitHub App install) and without a session.
*/
reopenLink: ExternalLinkSource | null
/** "Copy link" beside the GitHub step's button: the same install page, minted without opening. */
installGitHubLink: ExternalLinkSource | null
}
export function useCloudSetupFlow(
@@ -135,8 +136,7 @@ export function useCloudSetupFlow(
const {
steps: rowSteps,
session,
openInstall,
installLink
openInstall
} = useCloudStartSteps({
availability,
access,
@@ -318,7 +318,7 @@ export function useCloudSetupFlow(
checkAgain,
contactUrl,
reopenBrowser: () => void reopenCloudSetup(sessionId, continueInBrowser),
reopenLink: cloudSetupLinkSource(sessionId),
installGitHubLink: installLink
// Copy link is for sign-in pages only (pasted into an incognito window or another profile).
reopenLink: signingIn || model.action === 'sign-in' ? cloudSetupLinkSource(sessionId) : null
}
}
@@ -17,8 +17,6 @@ import {
repoSlug,
runCloudSetupScript
} from '@/lib/orca-cloud/cloud-setup-notice-actions'
import { gitHubInstallLinkSource } from '@/lib/orca-cloud/github-link-sources'
import type { ExternalLinkSource } from '@/components/open-external/copy-external-link'
import { recheckCloudFetch } from '@/lib/orca-cloud/cloud-fetch-notice'
import { runVmEnvironmentCheck } from '@/runtime/ephemeral-vm/ephemeral-vm-environment-check'
import { hideCloudToast, showCloudToast, type CloudToastView } from './cloud-toast-stack'
@@ -38,8 +36,6 @@ export type CloudSetupNoticeLine = {
icon: React.ReactNode
run: () => void
pending?: boolean
/** Opens this page in the browser: "Copy link" beside it. */
link?: ExternalLinkSource
} | null
}
@@ -75,8 +71,7 @@ export function cloudSetupNoticeLine(
<GitPullRequestArrow />
),
run: handlers.install,
pending: handlers.installing,
link: gitHubInstallLinkSource({ repoUrl: record.repoUrl })
pending: handlers.installing
}
}
}
@@ -257,8 +252,7 @@ export function cloudSetupNoticesView(
label: line.action.label,
icon: line.action.icon,
onClick: line.action.run,
...(line.action.pending ? { pending: true } : {}),
...(line.action.link ? { link: line.action.link } : {})
...(line.action.pending ? { pending: true } : {})
}
}
: {}),
@@ -12,6 +12,7 @@ import {
} from 'lucide-react'
import { DropdownMenuItem, DropdownMenuSeparator } from '@/components/ui/dropdown-menu'
import { useTranslate } from '@/i18n/use-translate'
import { toastSharedWithTeam } from '@/components/cloud-workspaces/shared-with-team-toast'
import { isCloudSyncAvailable, requestCloudSyncFocus } from '@/lib/orca-cloud/cloud-sync-store'
import {
ConfirmationDialogContext,
@@ -178,14 +179,16 @@ async function setVisibility(
)
return
}
toast.success(
visibility === 'team'
? t('auto.components.cloudWorkspaces.sharedWithYourTeam', 'Shared with your team')
: t(
'auto.components.cloudWorkspaces.nowPrivate',
'Now private. Teammates’ devices were disconnected.'
)
)
if (visibility === 'team') {
toastSharedWithTeam(t)
} else {
toast.success(
t(
'auto.components.cloudWorkspaces.nowPrivate',
'Now private. Teammates’ devices were disconnected.'
)
)
}
reload()
}
@@ -13,8 +13,6 @@ import React, { useSyncExternalStore } from 'react'
import { TriangleAlert, X } from 'lucide-react'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { OpenExternalSplitButton } from '@/components/open-external/OpenExternalSplitButton'
import type { ExternalLinkSource } from '@/components/open-external/copy-external-link'
import { useTranslate } from '@/i18n/use-translate'
import { cn } from '@/lib/class-names'
import { BANNER_BODY_TEXT, BANNER_TONE } from '@/components/ui/banner-tone'
@@ -29,8 +27,6 @@ export type CloudToastAction = {
primary?: boolean
icon?: React.ReactNode
pending?: boolean
/** The action opens this page in the browser: its chevron offers "Copy link". */
link?: ExternalLinkSource
}
export type CloudToastLine = {
@@ -368,19 +364,7 @@ export function CloudToastCard({
<p className={cn('text-xs', BANNER_BODY_TEXT)}>{line.description}</p>
) : null}
</div>
{line.action?.link ? (
<OpenExternalSplitButton
size="xs"
variant={line.action.primary ? 'default' : 'outline'}
link={line.action.link}
onClick={() => (line.action?.pending ? undefined : line.action?.onClick())}
aria-disabled={line.action.pending || undefined}
aria-busy={line.action.pending || undefined}
>
{line.action.icon}
{line.action.label}
</OpenExternalSplitButton>
) : line.action ? (
{line.action ? (
<Button
type="button"
size="xs"
@@ -0,0 +1,43 @@
import { defineFixture } from '../../../../component-fixtures/component-fixture'
import { AccountMfaRowView } from './AccountMfaRow'
import type { AccountMfaState } from './use-account-mfa'
const width = 760
const noop = (): void => {}
const setupUrl = 'https://cloud.orca.dev/v1/account/security'
/** The row as it sits under the signed-in identity in Settings, Account. */
function row(state: AccountMfaState, frameWidth = width) {
return defineFixture({
width: frameWidth,
render: () => (
<div className="bg-background px-8 py-6">
<AccountMfaRowView state={state} onOpenSetup={noop} />
</div>
)
})
}
/** No second factor yet: why to add one, and Set up in browser (chevron: Copy link). */
export const off = row({ kind: 'known', mfa: 'off', setupUrl })
/** Enrolled: Manage in browser, for a new authenticator or the backup codes. */
export const on = row({ kind: 'known', mfa: 'on', setupUrl })
/** A narrow settings pane: the button wraps under the text. */
export const offNarrow = row({ kind: 'known', mfa: 'off', setupUrl }, 420)
/** The chevron's menu, open on Copy link. */
export const copyLinkMenu = defineFixture({
width,
render: () => (
<div className="bg-background px-8 pt-6 pb-24">
<AccountMfaRowView state={{ kind: 'known', mfa: 'off', setupUrl }} onOpenSetup={noop} />
</div>
),
interact: async (frame) => {
const chevron = frame.querySelector<HTMLButtonElement>('button[aria-haspopup="menu"]')
chevron?.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0 }))
await new Promise((resolve) => setTimeout(resolve, 50))
}
})
@@ -0,0 +1,72 @@
import { ShieldCheck } from 'lucide-react'
import { Badge } from '@/components/ui/badge'
import { OpenExternalSplitButton } from '@/components/open-external/OpenExternalSplitButton'
import { useTranslate } from '@/i18n/use-translate'
import { useAccountMfa, type AccountMfaState } from './use-account-mfa'
export type AccountMfaRowViewProps = {
state: AccountMfaState
onOpenSetup: () => void
}
/** One state of the row; renders nothing until the first status read answers. */
export function AccountMfaRowView({
state,
onOpenSetup
}: AccountMfaRowViewProps): React.JSX.Element | null {
const t = useTranslate()
if (state.kind === 'unknown') {
return null
}
const on = state.mfa === 'on'
return (
<div className="flex flex-wrap items-center gap-4 border-t border-border/60 pt-5">
<div className="flex size-11 shrink-0 items-center justify-center rounded-full bg-muted text-foreground">
<ShieldCheck className="size-5" />
</div>
<div className="min-w-0 flex-1 space-y-1">
<div className="flex flex-wrap items-center gap-2">
<p className="text-sm font-medium">
{t('auto.components.settings.orcaAccount.mfa.title', 'Two-factor authentication')}
</p>
<Badge variant="outline" className="text-[11px] text-muted-foreground">
{on
? t('auto.components.settings.orcaAccount.mfa.on', 'On')
: t('auto.components.settings.orcaAccount.mfa.off', 'Off')}
</Badge>
</div>
<p className="text-xs leading-5 text-muted-foreground" aria-live="polite">
{on
? t(
'auto.components.settings.orcaAccount.mfa.onDescription',
'Signing in asks for a code from your authenticator app. Keep your backup codes somewhere safe.'
)
: t(
'auto.components.settings.orcaAccount.mfa.offDescription',
'Add an authenticator app so a stolen password is not enough to sign in. You get backup codes too.'
)}
</p>
</div>
{/* Opens the account page in the browser; the chevron copies that link instead. */}
<OpenExternalSplitButton
variant="outline"
size="sm"
link={state.setupUrl}
onClick={onOpenSetup}
>
{on
? t('auto.components.settings.orcaAccount.mfa.manage', 'Manage in browser')
: t('auto.components.settings.orcaAccount.mfa.setUp', 'Set up in browser')}
</OpenExternalSplitButton>
</div>
)
}
/**
* "Two-factor authentication" under the signed-in identity. Mount it only while signed in to Orca
* Cloud.
*/
export function AccountMfaRow(): React.JSX.Element | null {
const mfa = useAccountMfa()
return <AccountMfaRowView state={mfa.state} onOpenSetup={mfa.openSetup} />
}
@@ -11,6 +11,7 @@ import { useAppStore } from '@/store/index'
import { OrcaProfileSignOutConfirmDialog } from '../../../orca-profiles/OrcaProfileSignOutConfirmDialog'
import { OrcaSignInButton, OrcaSignInWaitNotice } from '../../../OrcaSignInProgress'
import { useOrcaCloudApiAvailable } from '@/hooks/useOrcaCloudApiAvailability'
import { AccountMfaRow } from './AccountMfaRow'
import { GitHubIdentityRow } from './GitHubIdentityRow'
function accountStatusCopy(
@@ -135,6 +136,9 @@ export function OrcaAccountSettingsPane(): React.JSX.Element {
{/* The person's own GitHub for cloud commits; only signed in to Orca Cloud. */}
{connected && cloudAvailable ? <GitHubIdentityRow /> : null}
{/* Their own second factor: status, and a link to the account page that manages it. */}
{connected && cloudAvailable ? <AccountMfaRow /> : null}
{/* JA-16: with Orca Cloud the page is identity + Sign out only; plan, team and agents have
their own entries in the Orca Cloud group right beside it. */}
{cloudAvailable ? null : (
@@ -0,0 +1,90 @@
import { useCallback, useEffect, useState } from 'react'
import { installWindowVisibilityInterval } from '@/lib/window-activity/window-visibility-interval'
import type { OrcaAccountMfa } from '../../../../../../shared/orca-account-mfa'
/** Re-check every few seconds after the browser opened, for at most five minutes. */
export const ACCOUNT_MFA_POLL_MS = 3_000
export const ACCOUNT_MFA_WATCH_MAX_MS = 5 * 60_000
export type AccountMfaState =
/** Not read yet, every read failed, or this deployment has no MFA status: the row is hidden. */
| { kind: 'unknown' }
| ({ kind: 'known' } & OrcaAccountMfa)
export type AccountMfa = {
state: AccountMfaState
/** Opens the account's security page in the browser, then watches for the change. */
openSetup: () => void
}
/**
* The signed-in person's own two-factor state (mount only while signed in to Orca Cloud). Read on
* mount and when the window regains focus; polled lightly after the browser was opened, since the
* person enrols there and comes back.
*/
export function useAccountMfa(): AccountMfa {
const [state, setState] = useState<AccountMfaState>({ kind: 'unknown' })
const [watching, setWatching] = useState<'on' | 'off' | null>(null)
const refresh = useCallback(async (): Promise<void> => {
let result: Awaited<ReturnType<typeof window.api.orcaProfiles.accountMfa>> | null
try {
result = (await window.api.orcaProfiles.accountMfa()) ?? null
} catch {
result = null
}
// A failed read keeps what the row shows; the next focus or poll tries again.
if (result?.status === 'ok') {
setState({ kind: 'known', mfa: result.mfa, setupUrl: result.setupUrl })
}
}, [])
useEffect(() => {
void refresh()
const onFocus = (): void => void refresh()
const onVisibility = (): void => {
if (document.visibilityState === 'visible') {
void refresh()
}
}
window.addEventListener('focus', onFocus)
document.addEventListener('visibilitychange', onVisibility)
return () => {
window.removeEventListener('focus', onFocus)
document.removeEventListener('visibilitychange', onVisibility)
}
}, [refresh])
// Stop watching once the state differs from what it was when the browser opened.
const changed = watching !== null && state.kind === 'known' && state.mfa !== watching
useEffect(() => {
if (changed) {
setWatching(null)
}
}, [changed])
useEffect(() => {
if (watching === null) {
return
}
const stopPolling = installWindowVisibilityInterval({
run: () => void refresh(),
intervalMs: ACCOUNT_MFA_POLL_MS
})
const expire = setTimeout(() => setWatching(null), ACCOUNT_MFA_WATCH_MAX_MS)
return () => {
stopPolling()
clearTimeout(expire)
}
}, [watching, refresh])
const openSetup = useCallback((): void => {
if (state.kind !== 'known') {
return
}
void window.api.shell.openUrl(state.setupUrl)
setWatching(state.mfa)
}, [state])
return { state, openSetup }
}
@@ -199,7 +199,7 @@ function list(
initialMode={mode}
initialSaved={options.saved}
onSetUpAgent={noop}
description="Only you get these, in every Orca Cloud workspace you start."
description="Only you get these, in cloud workspaces you haven’t shared. Shared workspaces don’t get them."
/>
</Frame>
)
@@ -201,8 +201,8 @@ export function CloudSecretsPane({
) : null
}
description={t(
'cloudSecrets.personal.description',
'Only you get these, in every Orca Cloud workspace you start.'
'cloudSecrets.personal.descriptionUnshared',
'Only you get these, in cloud workspaces you haven’t shared. Shared workspaces don’t get them.'
)}
emptyTitle={t('cloudSecrets.personal.emptyTitle', 'No personal secrets yet')}
emptyDetail={t(
@@ -222,8 +222,8 @@ describe('without the Enterprise plan', () => {
expect(contact).toHaveLength(1)
fireEvent.click(contact[0]!)
expect(onContactSales).toHaveBeenCalledWith('https://orca.dev/enterprise')
// The Copy link chevron sits beside it (the open-in-browser rule).
expect(screen.getAllByRole('button', { name: 'More link options' })).toHaveLength(1)
// Contact sales is not a sign-in page: a plain button, no Copy link chevron (AUTH-ONLY-COPY-LINK).
expect(screen.queryAllByRole('button', { name: 'More link options' })).toHaveLength(0)
})
it('a team missing only the audit log keeps the button on that block, with no banner', () => {
@@ -9,7 +9,7 @@
// singleSignOn replaces the built-in single sign-on block (sso-scim)
// policies sign-in policies, e.g. "Require MFA" (mfa)
import { ExternalLink } from 'lucide-react'
import { OpenExternalSplitButton } from '@/components/open-external/OpenExternalSplitButton'
import { Button } from '@/components/ui/button'
import { useTranslate } from '@/i18n/use-translate'
import { SettingsGroup } from '../section-layout/SettingsGroup'
import { EnterpriseAuditLog, type EnterpriseAuditLogProps } from './EnterpriseAuditLog'
@@ -87,15 +87,15 @@ export function EnterpriseSettingsView({
)}
</p>
</div>
<OpenExternalSplitButton
<Button
type="button"
variant="outline"
size="sm"
link={contact.contactUrl}
onClick={() => onContactSales(contact.contactUrl)}
>
{t('settings.enterprise.contactUs', 'Contact us')}
<ExternalLink />
</OpenExternalSplitButton>
</Button>
</div>
) : banner ? (
<EnterpriseUpsellLine>{ssoUpsellBody}</EnterpriseUpsellLine>
@@ -1,7 +1,7 @@
// The one locked state for everything on Settings › Enterprise: what the feature is, that it is
// part of Enterprise, and Contact sales. The button opens the page; its chevron copies the link.
// part of Enterprise, and Contact sales. The button opens the page (Copy link is for sign-in pages only).
import { ExternalLink } from 'lucide-react'
import { OpenExternalSplitButton } from '@/components/open-external/OpenExternalSplitButton'
import { Button } from '@/components/ui/button'
import { useTranslate } from '@/i18n/use-translate'
/** Where Contact sales goes when billing has not answered yet (billing's own Enterprise page). */
@@ -29,15 +29,15 @@ export function EnterpriseUpsell({
<p className="text-sm font-medium">{title}</p>
<p className="text-xs text-muted-foreground text-pretty">{body}</p>
</div>
<OpenExternalSplitButton
<Button
type="button"
variant="outline"
size="sm"
link={contact.contactUrl}
onClick={() => onContactSales(contact.contactUrl)}
>
{t('auto.components.billing.enterpriseContactSales', 'Contact sales')}
<ExternalLink />
</OpenExternalSplitButton>
</Button>
</div>
)
}
@@ -22,6 +22,7 @@ import { lazyWithRetry } from '@/app-shell/startup/lazy-with-retry'
import { LocalGitToolchainScanBanner } from './LocalGitToolchainScanBanner'
import { SeveredTerminalDaemonBanner } from './SeveredTerminalDaemonBanner'
import { StalledTerminalDaemonBanner } from './StalledTerminalDaemonBanner'
import { TeamMfaSidebarBanner } from '@/components/team-mfa/TeamMfaAppBanner'
import { StartupWorktreeRefreshStatus } from './StartupWorktreeRefreshStatus'
// Load the shared Activity badge/list pipeline after the sidebar shell.
@@ -193,6 +194,7 @@ function Sidebar({
/>
<SeveredTerminalDaemonBanner />
<StalledTerminalDaemonBanner />
<TeamMfaSidebarBanner />
<React.Suspense
fallback={sidebarBody === 'agents' ? <div className="min-h-0 flex-1" /> : null}
>
@@ -0,0 +1,51 @@
// GH-CREATE-NO-ROW: a create with no project here yet (a GitHub-only Orca Cloud create) has a
// pending row atop the list when grouped by project, as in every other grouping; a create with a
// project still sits atop its own project.
import { describe, expect, it } from 'vitest'
import { repo, worktree } from './worktree-list-groups-test-fixtures'
import { buildRows } from './build-rows.test-fixture'
function rows(groupBy: 'repo' | 'none', pending: { creationId: string; repoId: string }[]) {
return buildRows(
groupBy,
[{ ...worktree, lastActivityAt: 1 }],
new Map([[repo.id, repo]]),
null,
new Set(),
undefined,
undefined,
'manual',
{},
undefined,
false,
undefined,
[],
new Set(),
new Map(),
new Map(),
pending
)
}
describe('pending row for a create with no project yet', () => {
it('by project: sits atop the list, before the first project header', () => {
const list = rows('repo', [{ creationId: 'gh-1', repoId: '' }])
expect(list[0]).toMatchObject({ type: 'pending-creation', creationId: 'gh-1' })
expect(list.filter((row) => row.type === 'pending-creation')).toHaveLength(1)
// No blank project header for it (it used to get one, keyed "repo:").
expect(list.filter((row) => row.type === 'header')).toHaveLength(1)
})
it('by project: a create with a project still sits atop that project only', () => {
const list = rows('repo', [{ creationId: 'local-1', repoId: repo.id }])
const header = list.findIndex((row) => row.type === 'header')
expect(header).toBeGreaterThanOrEqual(0)
expect(list.findIndex((row) => row.type === 'pending-creation')).toBeGreaterThan(header)
expect(list.filter((row) => row.type === 'pending-creation')).toHaveLength(1)
})
it('ungrouped: unchanged, every pending row on top', () => {
const list = rows('none', [{ creationId: 'gh-1', repoId: '' }])
expect(list[0]).toMatchObject({ type: 'pending-creation', creationId: 'gh-1' })
})
})
@@ -0,0 +1,64 @@
// @vitest-environment happy-dom
// A cloud create's billing refusal is a precondition, not an error: its sidebar status reads in
// muted text (the glyph carries the state); a real failure stays red.
import { cleanup, render, screen } from '@testing-library/react'
import { afterEach, describe, expect, it } from 'vitest'
import { useAppStore } from '@/store'
import { githubCreateRequest } from '@/lib/orca-cloud/start-cloud-workspace-from-github'
import type { PendingWorktreeCreation } from '@/lib/workspace/creation/pending-worktree-creation'
import { PendingWorktreeRow } from './PendingWorktreeRow'
afterEach(cleanup)
function failed(
errorCode: string | undefined,
log: string,
error: string
): PendingWorktreeCreation {
return {
creationId: 'c',
phase: 'provisioning-vm',
status: 'error',
startedAt: 1,
indeterminate: false,
loaderVisible: true,
error,
...(errorCode ? { errorCode } : {}),
provisioningLog: log,
request: githubCreateRequest({
repoUrl: 'https://github.com/acme/web',
fullName: 'acme/web',
prompt: 'Fix login',
agent: null
})
}
}
function statusLine(entry: PendingWorktreeCreation): HTMLElement {
useAppStore.setState({ pendingWorktreeCreations: { c: entry }, repos: [] })
render(<PendingWorktreeRow creationId="c" repoName={null} />)
const line = screen.getByText('Fix login').nextElementSibling
if (!(line instanceof HTMLElement)) {
throw new Error('no status line')
}
return line
}
describe('pending row status colour', () => {
it('billing refusal: muted', () => {
const line = statusLine(
failed(
'cloudPlanRequired',
'[orca-cloud] provisioning\nOrca Cloud: included_hours_exhausted',
'Orca Cloud workspaces need a plan with cloud hours.'
)
)
expect(line.className).toContain('text-muted-foreground')
expect(line.className).not.toContain('text-destructive')
})
it('a real failure: red', () => {
const line = statusLine(failed(undefined, '[orca-cloud] provisioning', 'fetch failed'))
expect(line.className).toContain('text-destructive')
})
})
@@ -10,6 +10,10 @@ import {
import { translate } from '@/i18n/i18n'
import { useTranslate, type Translate } from '@/i18n/use-translate'
import { vmBuildFailureSummary } from '@/components/worktree-creation/vm-build-failure-toast'
import {
classifyVmBuildFailure,
isBillingFailure
} from '@/components/worktree-creation/vm-build-failure'
import type { Repo } from '../../../../../../shared/repo-types'
function statusLabel(
@@ -67,6 +71,11 @@ export function PendingWorktreeRow({
const isError = entry.status === 'error'
const isOrcaCloud = entry.request.ephemeralVmRecipe?.provider === 'orca-cloud'
// A billing refusal is a precondition, not an error: muted text; the glyph carries the state.
const refused =
isError &&
isOrcaCloud &&
isBillingFailure(classifyVmBuildFailure({ entry, error: entry.error ?? null, cloud: true }))
return (
<div
className={cn(
@@ -104,7 +113,7 @@ export function PendingWorktreeRow({
<span
className={cn(
'block truncate text-[11px] tabular-nums',
isError ? 'text-destructive/90' : 'text-muted-foreground'
isError && !refused ? 'text-destructive/90' : 'text-muted-foreground'
)}
>
{statusLabel(entry, repos, t)}
@@ -0,0 +1,62 @@
// GH-CREATE-NO-ROW: a GitHub-only Orca Cloud create has a sidebar row while it builds, atop the list
// (it has no project here yet), with the cloud glyph from the start; the paired workspace's rows
// replace it on hand-off.
import { getDefaultSettings } from '../../../../../../shared/constants'
import { defineFixture } from '../../../../component-fixtures/component-fixture'
import { githubCreateRequest } from '@/lib/orca-cloud/start-cloud-workspace-from-github'
import type { PendingWorktreeCreation } from '@/lib/workspace/creation/pending-worktree-creation'
import { PendingWorktreeRow } from './PendingWorktreeRow'
const T0 = 1_700_000_000_000
function creation(
creationId: string,
patch: Partial<PendingWorktreeCreation> = {}
): PendingWorktreeCreation {
return {
creationId,
phase: 'provisioning-vm',
status: 'creating',
startedAt: T0,
indeterminate: false,
loaderVisible: true,
provisioningLog: '[orca-cloud] provisioning\n[orca-cloud] plan-clone',
provisioningLogStamps: [T0, T0 + 400],
request: githubCreateRequest({
repoUrl: 'https://github.com/nwparker/orca-sandbox-push-test',
fullName: 'nwparker/orca-sandbox-push-test',
prompt: 'Add a push test',
agent: 'claude',
composerRepoId: 'repo'
}),
...patch
}
}
const rows = {
building: creation('building'),
opening: creation('opening', { phase: 'creating' }),
failed: creation('failed', {
status: 'error',
error: 'Orca Cloud workspaces need a plan with cloud hours.',
errorCode: 'cloudPlanRequired',
provisioningLog: '[orca-cloud] provisioning\nOrca Cloud: included_hours_exhausted'
})
}
/** The sidebar's top while three GitHub-only creates are in flight: building, opening, refused. */
export const githubOnlyPendingRows = defineFixture({
width: 320,
store: {
settings: getDefaultSettings('/home/fixture'),
pendingWorktreeCreations: rows,
activePendingCreationId: 'building'
},
render: () => (
<div className="flex flex-col gap-1.5 bg-worktree-sidebar p-2 text-worktree-sidebar-foreground">
{Object.keys(rows).map((creationId) => (
<PendingWorktreeRow key={creationId} creationId={creationId} repoName={null} />
))}
</div>
)
})
@@ -0,0 +1,276 @@
import { useState } from 'react'
import { Loader2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { InlineError } from '@/components/ui/inline-error'
import { OpenExternalSplitButton } from '@/components/open-external/OpenExternalSplitButton'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue
} from '@/components/ui/select'
import { useIntlLocale, useTranslate } from '@/i18n/use-translate'
import {
ORCA_TEAM_MFA_GRACE_CHOICES,
type OrcaTeamMfaGrace,
type OrcaTeamMfaPendingMember,
type OrcaTeamMfaPolicy
} from '../../../../shared/orca-team-mfa-policy'
import { mfaCountdownLabel, mfaDeadlineDate, mfaGraceLabel } from './team-mfa-copy'
export type RequireMfaRowNotice =
| { kind: 'error'; message: string }
/** `emailed` false: the server recorded the reminder but its email delivery is off. */
| { kind: 'reminded'; recipients: number; emailed: boolean }
export type RequireMfaRowProps = {
/** The policy read for an owner or admin (`manage` present). */
policy: OrcaTeamMfaPolicy
/** Null until the pending list is read; shown only while a policy is in force. */
pending: OrcaTeamMfaPendingMember[] | null
now: number
busy: boolean
notice: RequireMfaRowNotice | null
onRequire: (grace: OrcaTeamMfaGrace) => void
onTurnOff: () => void
onRemind: (userId?: string) => void
onSetUpOwn: () => void
}
/**
* "Require MFA" in Settings, Enterprise, Multi-factor authentication. Rendered only for a team
* whose plan includes it; the pane shows its shared upsell otherwise.
*/
export function RequireMfaRow({
policy,
pending,
now,
busy,
notice,
onRequire,
onTurnOff,
onRemind,
onSetUpOwn
}: RequireMfaRowProps): React.JSX.Element {
const t = useTranslate()
const locale = useIntlLocale()
const [grace, setGrace] = useState<OrcaTeamMfaGrace>(14)
const active = policy.policy
const pendingCount = policy.manage?.pendingMembers ?? 0
// The server refuses a change from someone without MFA; say so before they try.
const needsOwnMfa = policy.self !== 'on'
const enforced = active !== null && active.enforceAt <= now
return (
<div className="space-y-4">
<div className="flex flex-wrap items-start gap-4">
<div className="min-w-0 flex-1 space-y-1">
<p className="text-sm font-medium">
{t('auto.components.teamMfa.rowTitle', 'Require two-factor authentication')}
</p>
<p className="text-xs leading-5 text-muted-foreground" aria-live="polite">
{active === null
? t(
'auto.components.teamMfa.rowOff',
'Members without it lose access to this team’s workspaces after the date you pick, until they set it up. They get an email now and reminders before the date.'
)
: enforced
? t(
'auto.components.teamMfa.rowEnforced',
'Required since {{value0}}. Members without it can’t use this team until they set it up.',
{ value0: mfaDeadlineDate(active.enforceAt, locale) }
)
: t(
'auto.components.teamMfa.rowScheduled',
'Required from {{value0}}. {{value1}}.',
{
value0: mfaDeadlineDate(active.enforceAt, locale),
value1: mfaCountdownLabel(active.enforceAt, now, t)
}
)}
</p>
</div>
{active === null ? (
<div className="flex shrink-0 items-center gap-2">
<Select
value={String(grace)}
onValueChange={(next) => {
const choice = ORCA_TEAM_MFA_GRACE_CHOICES.find((c) => String(c) === next)
if (choice !== undefined) {
setGrace(choice)
}
}}
>
<SelectTrigger
size="sm"
className="w-36"
aria-label={t('auto.components.teamMfa.graceLabel', 'When to start requiring it')}
>
<SelectValue />
</SelectTrigger>
<SelectContent align="end">
{ORCA_TEAM_MFA_GRACE_CHOICES.map((choice) => (
<SelectItem key={String(choice)} value={String(choice)}>
{mfaGraceLabel(choice, t)}
</SelectItem>
))}
</SelectContent>
</Select>
<Button
type="button"
size="sm"
aria-disabled={busy || needsOwnMfa || undefined}
onClick={() => {
if (!busy && !needsOwnMfa) {
onRequire(grace)
}
}}
>
{busy ? <Loader2 className="size-4 animate-spin" /> : null}
{t('auto.components.teamMfa.require', 'Require MFA')}
</Button>
</div>
) : (
<Button
type="button"
variant="outline"
size="sm"
aria-disabled={busy || needsOwnMfa || undefined}
onClick={() => {
if (!busy && !needsOwnMfa) {
onTurnOff()
}
}}
>
{busy ? <Loader2 className="size-4 animate-spin" /> : null}
{t('auto.components.teamMfa.turnOff', 'Stop requiring')}
</Button>
)}
</div>
{needsOwnMfa ? (
<InlineError
tone="neutral"
title={t(
'auto.components.teamMfa.ownMfaTitle',
'Set up two-factor authentication on your own account first'
)}
detail={t(
'auto.components.teamMfa.ownMfaBody',
'Only someone who already has it can change this, so nobody locks the team out.'
)}
action={
<OpenExternalSplitButton
variant="outline"
size="xs"
link={policy.setupUrl}
onClick={onSetUpOwn}
>
{t('auto.components.teamMfa.setUp', 'Set up MFA')}
</OpenExternalSplitButton>
}
/>
) : null}
{active === null && grace === 'now' && pendingCount > 0 && !needsOwnMfa ? (
<p className="text-xs leading-5 text-muted-foreground">
{t(
'auto.components.teamMfa.nowWarning',
'{{count}} members don’t have it yet and will lose access to this team right away.',
{
count: pendingCount,
defaultValue_one:
'{{count}} member doesn’t have it yet and will lose access to this team right away.'
}
)}
</p>
) : null}
{active !== null ? (
<div className="space-y-2 border-t border-border/60 pt-4">
<div className="flex flex-wrap items-center gap-3">
<p className="min-w-0 flex-1 text-sm">
{pendingCount === 0
? t('auto.components.teamMfa.allSet', 'Every member has it set up.')
: t('auto.components.teamMfa.pendingCount', '{{count}} members still need it', {
count: pendingCount,
defaultValue_one: '{{count}} member still needs it'
})}
</p>
{pendingCount > 0 ? (
<Button
type="button"
variant="outline"
size="sm"
aria-disabled={busy || undefined}
onClick={() => {
if (!busy) {
onRemind()
}
}}
>
{t('auto.components.teamMfa.remindAll', 'Remind everyone')}
</Button>
) : null}
</div>
{pending && pending.length > 0 ? (
<ul
className="divide-y divide-border/60 overflow-hidden rounded-lg border border-border"
aria-label={t('auto.components.teamMfa.pendingList', 'Members without MFA')}
>
{pending.map((member) => (
<li
key={member.userId ?? member.email}
className="flex min-h-10 items-center gap-3 bg-card px-3 py-1.5"
>
<div className="min-w-0 flex-1">
<p className="truncate text-sm">{member.displayName ?? member.email}</p>
{member.displayName ? (
<p className="truncate text-xs text-muted-foreground">{member.email}</p>
) : null}
</div>
<span className="shrink-0 text-xs text-muted-foreground">
{member.mfa === 'blocked'
? t('auto.components.teamMfa.memberBlocked', 'No access')
: t('auto.components.teamMfa.memberPending', 'Pending')}
</span>
{member.userId ? (
<Button
type="button"
variant="ghost"
size="xs"
aria-disabled={busy || undefined}
onClick={() => {
if (!busy && member.userId) {
onRemind(member.userId)
}
}}
>
{t('auto.components.teamMfa.remindOne', 'Remind')}
</Button>
) : null}
</li>
))}
</ul>
) : null}
</div>
) : null}
{notice?.kind === 'error' ? <InlineError title={notice.message} /> : null}
{notice?.kind === 'reminded' ? (
<p className="text-xs text-muted-foreground" role="status">
{notice.emailed
? t('auto.components.teamMfa.reminded', 'Reminder sent to {{count}} members.', {
count: notice.recipients,
defaultValue_one: 'Reminder sent to {{count}} member.'
})
: t(
'auto.components.teamMfa.remindedNoEmail',
'Reminder recorded, but email delivery is off on this server, so nothing was sent.'
)}
</p>
) : null}
</div>
)
}
@@ -0,0 +1,176 @@
import { defineFixture } from '../../component-fixtures/component-fixture'
import type {
OrcaTeamMfaPendingMember,
OrcaTeamMfaPolicy
} from '../../../../shared/orca-team-mfa-policy'
import { CloudToastCard } from '@/components/orca-cloud/cloud-toast-stack'
import { RequireMfaRow, type RequireMfaRowProps } from './RequireMfaRow'
import { TeamMfaBanner } from './TeamMfaBanner'
import { TeamMfaBlockedScreen } from './TeamMfaBlockedScreen'
const NOW = Date.UTC(2026, 10, 18, 15)
const DAY = 86_400_000
const setupUrl = 'https://cloud.orca.dev/v1/account/security'
const noop = (): void => {}
const width = 760
function frame(children: React.ReactNode, frameWidth = width) {
return defineFixture({
width: frameWidth,
render: () => <div className="bg-background px-8 py-6">{children}</div>
})
}
// ---- Banner: a member without MFA, before the deadline ----
const banner = (daysLeft: number, frameWidth = width) =>
frame(
<TeamMfaBanner
teamName="Acme Engineering"
enforceAt={NOW + daysLeft * DAY}
now={NOW}
setupUrl={setupUrl}
onSetUp={noop}
/>,
frameWidth
)
export const bannerTwoWeeks = banner(14)
export const bannerOneDay = banner(1)
export const bannerNarrow = banner(6, 420)
// ---- Sidebar banner stack: the app-level reminder, at sidebar widths ----
const sidebar = (daysLeft: number, sidebarWidth: number) =>
defineFixture({
width: sidebarWidth,
render: () => (
<div className="bg-worktree-sidebar py-2">
<TeamMfaBanner
variant="sidebar"
teamName="Acme Engineering"
enforceAt={NOW + daysLeft * DAY}
now={NOW}
setupUrl={setupUrl}
onSetUp={noop}
blocked={daysLeft < 0}
/>
</div>
)
})
export const sidebarTwoWeeks = sidebar(14, 280)
/** Three days or fewer: the warning look. */
export const sidebarThreeDays = sidebar(3, 280)
export const sidebarOneDay = sidebar(1, 280)
/** After the deadline: no access until set up. */
export const sidebarBlocked = sidebar(-2, 280)
/** The narrowest sidebar. */
export const sidebarBlockedNarrow = sidebar(-2, 220)
// ---- The one-time toast, for people who keep the sidebar collapsed ----
export const toast = frame(
<CloudToastCard
view={{
priority: 'action',
lines: [
{
key: 'mfa',
text: 'Acme Engineering requires MFA from December 2, 2026.',
action: { label: 'Set up MFA', primary: true, onClick: noop }
}
]
}}
onDismiss={noop}
/>,
420
)
// ---- Blocked screen: after the deadline ----
const blocked = (props: { checking?: boolean; stillMissing?: boolean; personal?: boolean }) =>
frame(
<TeamMfaBlockedScreen
teamName="Acme Engineering"
enforceAt={NOW - 2 * DAY}
setupUrl={setupUrl}
checking={props.checking === true}
stillMissing={props.stillMissing === true}
onSetUp={noop}
onRecheck={noop}
{...(props.personal === false ? {} : { onUsePersonal: noop })}
/>
)
export const blockedScreen = blocked({})
export const blockedChecking = blocked({ checking: true })
/** "I've set it up" found no MFA yet. */
export const blockedStillMissing = blocked({ stillMissing: true })
// ---- Settings, Enterprise, Multi-factor authentication ----
const pendingMembers: OrcaTeamMfaPendingMember[] = [
{ userId: 'u-ada', email: 'ada@acme.dev', displayName: 'Ada Lovelace', mfa: 'pending' },
{ userId: 'u-grace', email: 'grace@acme.dev', displayName: 'Grace Hopper', mfa: 'pending' },
{ userId: null, email: 'linus@acme.dev', mfa: 'pending' }
]
const off: OrcaTeamMfaPolicy = {
policy: null,
self: 'on',
setupUrl,
manage: { available: true, pendingMembers: 3 }
}
const scheduled: OrcaTeamMfaPolicy = {
...off,
policy: { enforceAt: NOW + 6 * DAY, setAt: NOW - 8 * DAY }
}
const row = (props: Partial<RequireMfaRowProps>) =>
frame(
<RequireMfaRow
policy={off}
pending={null}
now={NOW}
busy={false}
notice={null}
onRequire={noop}
onTurnOff={noop}
onRemind={noop}
onSetUpOwn={noop}
{...props}
/>
)
/** Not required yet: pick when, then Require MFA. */
export const rowOff = row({})
/** The admin has no MFA themselves: the change is held back until they add it. */
export const rowAdminNeedsOwnMfa = row({ policy: { ...off, self: 'off' } })
/** Scheduled: the date, the countdown, who is pending, and Remind. */
export const rowScheduled = row({ policy: scheduled, pending: pendingMembers })
/** Past the deadline: pending members have no access. */
export const rowEnforced = row({
policy: { ...off, policy: { enforceAt: NOW - 2 * DAY, setAt: NOW - 16 * DAY } },
pending: pendingMembers.map((member) => ({ ...member, mfa: 'blocked' as const }))
})
export const rowEveryoneSet = row({
policy: { ...scheduled, manage: { available: true, pendingMembers: 0 } },
pending: []
})
export const rowSaving = row({ policy: scheduled, pending: pendingMembers, busy: true })
export const rowReminded = row({
policy: scheduled,
pending: pendingMembers,
notice: { kind: 'reminded', recipients: 3, emailed: true }
})
/** The server is in log mode: say plainly that no email went out. */
export const rowRemindedNoEmail = row({
policy: scheduled,
pending: pendingMembers,
notice: { kind: 'reminded', recipients: 3, emailed: false }
})
export const rowError = row({
policy: scheduled,
pending: pendingMembers,
notice: { kind: 'error', message: 'Couldn’t save the change. Try again.' }
})
@@ -0,0 +1,75 @@
import { useEffect } from 'react'
import { hideCloudToast, showCloudToast } from '@/components/orca-cloud/cloud-toast-stack'
import { useIntlLocale, useTranslate } from '@/i18n/use-translate'
import { claimMfaToast, mfaDeadlineDate } from './team-mfa-copy'
import { useTeamMfaGate } from './TeamMfaGate'
/**
* The MFA notice in the sidebar's banner stack, for the active team: a countdown while there is
* still time, and "no access until you set it up" after the deadline. Renders nothing for a
* personal account, a team with no policy, or a member who already has MFA, which is almost
* everyone.
*
* The sidebar can be collapsed, so this is a reminder, not the enforcement surface: a refused
* team resource shows TeamMfaRefused in its own place whether or not the sidebar is visible.
*/
export function TeamMfaSidebarBanner(): React.JSX.Element | null {
const gate = useTeamMfaGate()
const t = useTranslate()
const locale = useIntlLocale()
const toast = gate.pendingToast
const orgId = toast?.orgId
const enforceAt = toast?.enforceAt
// One toast per team and deadline, for people who keep the sidebar collapsed. Not tied to any
// workspace, so it shows wherever they are; the sidebar card stays as the lasting reminder.
useEffect(() => {
if (!toast || orgId === undefined || enforceAt === undefined) {
return
}
if (!claimMfaToast(readLocalStorage(), orgId, enforceAt)) {
return
}
const id = `team-mfa:${orgId}`
showCloudToast(id, {
priority: 'action',
lines: [
{
key: 'mfa',
text: t('auto.components.teamMfa.toast', '{{value0}} requires MFA from {{value1}}.', {
value0: toast.teamName,
value1: mfaDeadlineDate(enforceAt, locale)
}),
action: {
label: t('auto.components.teamMfa.setUp', 'Set up MFA'),
primary: true,
// A plain button: toasts no longer carry a Copy link chevron (AUTH-ONLY-COPY-LINK).
// The sidebar card and Settings, Account keep the split button.
onClick: () => {
void window.api.shell.openUrl(toast.setupUrl)
hideCloudToast(id)
}
}
}
]
})
// Deliberately keyed on the team and deadline only: copy or locale changes must not re-show.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [orgId, enforceAt])
return gate.sidebarBanner
}
function readLocalStorage(): Storage | null {
try {
return window.localStorage
} catch {
return null
}
}
/**
* In place of a team resource the server refused with `mfa_required`: the setup screen, or (when
* the policy cannot be read to fill it in) nothing, so the caller's own error copy shows.
*/
export function TeamMfaRefused(): React.JSX.Element | null {
return useTeamMfaGate({ forceBlocked: true }).blocked
}
@@ -0,0 +1,125 @@
import { ShieldAlert } from 'lucide-react'
import { InlineError } from '@/components/ui/inline-error'
import { cn } from '@/lib/class-names'
import { OpenExternalSplitButton } from '@/components/open-external/OpenExternalSplitButton'
import { useIntlLocale, useTranslate } from '@/i18n/use-translate'
import { BANNER_BODY_TEXT, BANNER_TONE } from '@/components/ui/banner-tone'
import { mfaCountdownLabel, mfaDeadlineDate, mfaSoonTitle, mfaUrgency } from './team-mfa-copy'
export type TeamMfaBannerProps = {
teamName: string
/** Epoch ms from which the team is closed to members without MFA. */
enforceAt: number
now: number
setupUrl: string
onSetUp: () => void
/** The deadline has passed and the team is closed to this person until they set MFA up. */
blocked?: boolean
/** `sidebar`: the narrow stacked layout of the sidebar's banner stack. */
variant?: 'inline' | 'sidebar'
className?: string
}
/**
* Shown to a member whose team requires MFA and who has none yet, until the deadline: how long
* is left and the way to set it up. After the deadline the blocked screen takes over.
*/
export function TeamMfaBanner({
teamName,
enforceAt,
now,
setupUrl,
onSetUp,
blocked = false,
variant = 'inline',
className
}: TeamMfaBannerProps): React.JSX.Element {
const t = useTranslate()
const locale = useIntlLocale()
const urgency = mfaUrgency(enforceAt, now, blocked)
const title =
urgency === 'soon'
? mfaSoonTitle(teamName, enforceAt, now, t)
: blocked
? t(
'auto.components.teamMfa.bannerBlockedTitle',
'{{value0}} requires two-factor authentication',
{ value0: teamName }
)
: t(
'auto.components.teamMfa.bannerTitle',
'{{value0}} requires two-factor authentication. {{value1}}.',
{ value0: teamName, value1: mfaCountdownLabel(enforceAt, now, t) }
)
const detail = blocked
? t(
'auto.components.teamMfa.bannerBlockedBody',
'You can’t use this team’s workspaces until you set it up. Your personal account isn’t affected.'
)
: t(
'auto.components.teamMfa.bannerBody',
'Set it up by {{value0}}. After that you can’t use this team’s workspaces until you do.',
{ value0: mfaDeadlineDate(enforceAt, locale) }
)
const action = (
<OpenExternalSplitButton variant="outline" size="xs" link={setupUrl} onClick={onSetUp}>
{t('auto.components.teamMfa.setUp', 'Set up MFA')}
</OpenExternalSplitButton>
)
if (variant === 'sidebar') {
// Same shape as the other banners in the sidebar stack (StalledTerminalDaemonBanner): the
// column is narrow, so the action sits under the text.
return (
<section
role={blocked ? 'alert' : 'status'}
data-team-mfa-banner={urgency}
className={cn(
'mx-2 mb-2 shrink-0 rounded-md border p-2.5 text-worktree-sidebar-foreground',
// Quiet with time to spare; the shared warning look in the last three days; the
// destructive border of a real block after the deadline.
urgency === 'soon'
? cn(BANNER_TONE.warning.surface, BANNER_TONE.warning.border)
: 'bg-worktree-sidebar-accent/40',
urgency === 'blocked' && 'border-destructive/50',
urgency === 'quiet' && 'border-border',
className
)}
>
<div className="flex items-start gap-2">
<ShieldAlert
className={cn(
'mt-px size-3.5 shrink-0',
urgency === 'blocked'
? 'text-destructive'
: urgency === 'soon'
? BANNER_TONE.warning.icon
: 'text-muted-foreground'
)}
aria-hidden="true"
/>
<div className="min-w-0 flex-1 space-y-1.5">
<p className="text-xs font-semibold leading-snug">{title}</p>
<p
className={cn(
'text-xs leading-snug',
urgency === 'soon' ? BANNER_BODY_TEXT : 'text-muted-foreground'
)}
>
{detail}
</p>
{action}
</div>
</div>
</section>
)
}
return (
<InlineError
className={className}
tone={blocked ? 'error' : 'neutral'}
title={title}
detail={detail}
action={action}
/>
)
}
@@ -0,0 +1,93 @@
import { Loader2, ShieldAlert } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { OpenExternalSplitButton } from '@/components/open-external/OpenExternalSplitButton'
import { useIntlLocale, useTranslate } from '@/i18n/use-translate'
import { mfaDeadlineDate } from './team-mfa-copy'
export type TeamMfaBlockedScreenProps = {
teamName: string
enforceAt: number
setupUrl: string
/** A re-check is running (after "I've set it up", or on returning from the browser). */
checking: boolean
/** The last re-check still found no MFA. */
stillMissing: boolean
onSetUp: () => void
onRecheck: () => void
/** Switch to the personal account, which the team's policy does not affect. */
onUsePersonal?: () => void
}
/**
* In place of a team's content once its MFA deadline has passed for a member without MFA: what
* happened, the one thing to do, and a way to keep working outside the team meanwhile.
*/
export function TeamMfaBlockedScreen({
teamName,
enforceAt,
setupUrl,
checking,
stillMissing,
onSetUp,
onRecheck,
onUsePersonal
}: TeamMfaBlockedScreenProps): React.JSX.Element {
const t = useTranslate()
const locale = useIntlLocale()
return (
<div className="mx-auto flex max-w-md flex-col items-center gap-4 px-6 py-12 text-center">
<div className="flex size-11 items-center justify-center rounded-full bg-muted text-foreground">
<ShieldAlert className="size-5" />
</div>
<div className="space-y-2">
<h2 className="text-base font-medium">
{t(
'auto.components.teamMfa.blockedTitle',
'Set up two-factor authentication to use {{value0}}',
{ value0: teamName }
)}
</h2>
<p className="text-sm leading-6 text-muted-foreground">
{t(
'auto.components.teamMfa.blockedBody',
'{{value0}} has required it for all members since {{value1}}. Your workspaces and files are safe, and open again as soon as you add an authenticator app.',
{ value0: teamName, value1: mfaDeadlineDate(enforceAt, locale) }
)}
</p>
</div>
<div className="flex flex-wrap items-center justify-center gap-2">
<OpenExternalSplitButton size="sm" link={setupUrl} onClick={onSetUp}>
{t('auto.components.teamMfa.setUp', 'Set up MFA')}
</OpenExternalSplitButton>
<Button
type="button"
variant="outline"
size="sm"
// Not disabled while checking: that would drop keyboard focus. A second press waits.
aria-disabled={checking || undefined}
onClick={() => {
if (!checking) {
onRecheck()
}
}}
>
{checking ? <Loader2 className="size-4 animate-spin" /> : null}
{t('auto.components.teamMfa.recheck', 'I’ve set it up')}
</Button>
</div>
<p className="min-h-5 text-xs text-muted-foreground" aria-live="polite">
{stillMissing && !checking
? t(
'auto.components.teamMfa.stillMissing',
'Your account still has no two-factor authentication. Finish the setup in your browser, then try again.'
)
: null}
</p>
{onUsePersonal ? (
<Button type="button" variant="link-muted" size="sm" onClick={onUsePersonal}>
{t('auto.components.teamMfa.usePersonal', 'Use my personal account for now')}
</Button>
) : null}
</div>
)
}
@@ -0,0 +1,90 @@
import { useState } from 'react'
import { useAppStore } from '@/store'
import { TeamMfaBanner } from './TeamMfaBanner'
import { TeamMfaBlockedScreen } from './TeamMfaBlockedScreen'
import { teamMfaSurface } from './team-mfa-copy'
import { useTeamMfaPolicy } from './use-team-mfa-policy'
/**
* The active team's MFA requirement, for a surface that shows the team's cloud content.
*
* - `banner`: render above the content while the member still has time.
* - `blocked`: render in place of the content once the server refused the team's resources.
* `forceBlocked` is that refusal (`mfa_required`); the policy read alone also blocks when the
* server says so, so the screen shows without waiting for a failed request.
*
* Renders nothing for a personal account, a team with no policy, a member who has MFA, or a
* server without the policy API.
*/
export function useTeamMfaGate(options: { forceBlocked?: boolean } = {}): {
banner: React.JSX.Element | null
blocked: React.JSX.Element | null
/** The sidebar notice: the countdown, or "no access" once blocked. */
sidebarBanner: React.JSX.Element | null
/** Set while the member still has time: what the one-time toast needs. */
pendingToast: { orgId: string; teamName: string; enforceAt: number; setupUrl: string } | null
} {
const cloud = useAppStore((state) => state.orcaProfileAuthStatus?.cloud)
const selectOrg = useAppStore((state) => state.selectOrcaProfileOrg)
const orgId = cloud?.activeOrgId ?? null
const teamName = cloud?.activeOrgName ?? ''
const { policy, checking, refresh } = useTeamMfaPolicy(orgId)
const [now] = useState(() => Date.now())
const [stillMissing, setStillMissing] = useState(false)
if (!orgId || !policy?.policy) {
return { banner: null, blocked: null, sidebarBanner: null, pendingToast: null }
}
const surface = teamMfaSurface(policy)
const openSetup = (): void => {
void window.api.shell.openUrl(policy.setupUrl)
}
// The server's refusal wins over a policy read that has not caught up, unless that read now
// says the member has MFA (they just set it up; the next request will go through).
const isBlocked = surface === 'blocked' || (options.forceBlocked === true && policy.self !== 'on')
const line = (blocked: boolean, variant: 'inline' | 'sidebar' = 'inline'): React.JSX.Element => (
<TeamMfaBanner
variant={variant}
teamName={teamName}
enforceAt={policy.policy?.enforceAt ?? now}
now={now}
setupUrl={policy.setupUrl}
onSetUp={openSetup}
blocked={blocked}
/>
)
if (isBlocked) {
return {
banner: null,
sidebarBanner: line(true, 'sidebar'),
pendingToast: null,
blocked: (
<TeamMfaBlockedScreen
teamName={teamName}
enforceAt={policy.policy.enforceAt}
setupUrl={policy.setupUrl}
checking={checking}
stillMissing={stillMissing}
onSetUp={openSetup}
onRecheck={() => {
void refresh().then((next) => {
// Null: the read failed; say nothing rather than claim MFA is still missing.
setStillMissing(next !== null && next.self !== 'on')
})
}}
onUsePersonal={() => void selectOrg(null)}
/>
)
}
}
const pending = surface === 'banner'
return {
banner: pending ? line(false) : null,
sidebarBanner: pending ? line(false, 'sidebar') : null,
pendingToast: pending
? { orgId, teamName, enforceAt: policy.policy.enforceAt, setupUrl: policy.setupUrl }
: null,
blocked: null
}
}
@@ -0,0 +1,116 @@
// Copy and small rules shared by the MFA banner, the blocked screen and the Enterprise row. Pure,
// so the views and their tests agree on every boundary.
import type { Translate } from '@/i18n/use-translate'
import type { OrcaTeamMfaGrace, OrcaTeamMfaPolicy } from '../../../../shared/orca-team-mfa-policy'
const DAY_MS = 24 * 60 * 60 * 1000
/** Whole days left, rounded up; 0 once the deadline has passed. Matches the server and the emails. */
export function mfaDaysLeft(enforceAt: number, now: number): number {
return Math.max(0, Math.ceil((enforceAt - now) / DAY_MS))
}
/**
* What the person should see for this team:
* - `banner`: the team requires MFA, they have none, and there is still time.
* - `blocked`: the deadline passed; the team is closed to them until they set it up.
* - `none`: nothing to show (no policy, they have MFA, or their state is unknown).
* Only the server's `blocked` blocks: the desktop never decides that from the clock.
*/
export function teamMfaSurface(policy: OrcaTeamMfaPolicy | null): 'none' | 'banner' | 'blocked' {
if (!policy?.policy) {
return 'none'
}
if (policy.self === 'blocked') {
return 'blocked'
}
return policy.self === 'pending' ? 'banner' : 'none'
}
/** From this many days before the deadline the notice stops being quiet (design-squad). */
export const MFA_URGENT_DAYS = 3
/**
* How loud the notice is: quiet with more than three days left, a warning in the last three,
* and blocked only on the server's word (never from the clock).
*/
export type TeamMfaUrgency = 'quiet' | 'soon' | 'blocked'
export function mfaUrgency(enforceAt: number, now: number, blocked: boolean): TeamMfaUrgency {
if (blocked) {
return 'blocked'
}
return mfaDaysLeft(enforceAt, now) <= MFA_URGENT_DAYS ? 'soon' : 'quiet'
}
/** "Acme requires MFA in 2 days": the title once the deadline is close. */
export function mfaSoonTitle(teamName: string, enforceAt: number, now: number, t: Translate): string {
const days = mfaDaysLeft(enforceAt, now)
if (days <= 0) {
return t('auto.components.teamMfa.soonTitleNow', '{{value0}} requires MFA now', {
value0: teamName
})
}
return t('auto.components.teamMfa.soonTitle', '{{value0}} requires MFA in {{count}} days', {
value0: teamName,
count: days,
defaultValue_one: '{{value0}} requires MFA in {{count}} day'
})
}
/**
* The one-time toast is shown once per team and deadline, so a changed date announces itself
* again and a restart does not repeat it.
*/
export function mfaToastSeenKey(orgId: string, enforceAt: number): string {
return `orca.teamMfa.toastSeen:${orgId}:${enforceAt}`
}
/** True the first time for a deadline; records it. A storage failure shows it rather than hide it. */
export function claimMfaToast(
storage: Pick<Storage, 'getItem' | 'setItem'> | null,
orgId: string,
enforceAt: number
): boolean {
const key = mfaToastSeenKey(orgId, enforceAt)
try {
if (storage?.getItem(key) === '1') {
return false
}
storage?.setItem(key, '1')
} catch {
// Private mode or a full quota: showing it again next launch is the lesser problem.
}
return true
}
/** "6 days left", "1 day left", "Due now". i18next plurals, never ternaries on the count. */
export function mfaCountdownLabel(enforceAt: number, now: number, t: Translate): string {
const days = mfaDaysLeft(enforceAt, now)
if (days <= 0) {
return t('auto.components.teamMfa.dueNow', 'Due now')
}
return t('auto.components.teamMfa.daysLeft', '{{count}} days left', {
count: days,
defaultValue_one: '{{count}} day left'
})
}
export function mfaDeadlineDate(enforceAt: number, locale: string): string {
return new Intl.DateTimeFormat(locale, { month: 'long', day: 'numeric', year: 'numeric' }).format(
enforceAt
)
}
export function mfaGraceLabel(grace: OrcaTeamMfaGrace, t: Translate): string {
switch (grace) {
case 'now':
return t('auto.components.teamMfa.graceNow', 'Immediately')
case 7:
return t('auto.components.teamMfa.grace7', 'In 7 days')
case 14:
return t('auto.components.teamMfa.grace14', 'In 14 days')
case 30:
return t('auto.components.teamMfa.grace30', 'In 30 days')
}
}
@@ -0,0 +1,317 @@
// @vitest-environment happy-dom
import { cleanup, fireEvent, render } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { translate } from '@/i18n/i18n'
import type { OrcaTeamMfaPolicy } from '../../../../shared/orca-team-mfa-policy'
import { RequireMfaRow, type RequireMfaRowProps } from './RequireMfaRow'
import { TeamMfaBanner } from './TeamMfaBanner'
import { TeamMfaBlockedScreen } from './TeamMfaBlockedScreen'
import {
claimMfaToast,
mfaCountdownLabel,
mfaDaysLeft,
mfaSoonTitle,
mfaUrgency,
teamMfaSurface
} from './team-mfa-copy'
import { describeError, describeInlineError } from '../cloud-workspaces/cloud-workspace-errors'
afterEach(cleanup)
const DAY = 86_400_000
const NOW = Date.UTC(2026, 10, 18, 15)
const setupUrl = 'https://cloud.orca.dev/v1/account/security'
const policy = (over: Partial<OrcaTeamMfaPolicy> = {}): OrcaTeamMfaPolicy => ({
policy: { enforceAt: NOW + 6 * DAY, setAt: NOW - DAY },
self: 'pending',
setupUrl,
...over
})
describe('countdown', () => {
it('rounds up to whole days and stops at zero', () => {
expect(mfaDaysLeft(NOW + 7 * DAY, NOW)).toBe(7)
expect(mfaDaysLeft(NOW + 6 * DAY + 1, NOW)).toBe(7)
expect(mfaDaysLeft(NOW + DAY / 2, NOW)).toBe(1)
expect(mfaDaysLeft(NOW, NOW)).toBe(0)
expect(mfaDaysLeft(NOW - DAY, NOW)).toBe(0)
})
it('reads as days left, one day left, then due now', () => {
expect(mfaCountdownLabel(NOW + 6 * DAY, NOW, translate)).toBe('6 days left')
expect(mfaCountdownLabel(NOW + DAY, NOW, translate)).toBe('1 day left')
expect(mfaCountdownLabel(NOW, NOW, translate)).toBe('Due now')
})
})
describe('what the member sees', () => {
it('is the banner while pending and the blocked screen only on the server’s word', () => {
expect(teamMfaSurface(policy())).toBe('banner')
expect(teamMfaSurface(policy({ self: 'blocked' }))).toBe('blocked')
// Past the deadline by the local clock, but the server still says pending: not blocked.
expect(teamMfaSurface(policy({ policy: { enforceAt: NOW - DAY, setAt: NOW - 8 * DAY } }))).toBe(
'banner'
)
})
it('is nothing with MFA on, an unknown state, or no policy', () => {
expect(teamMfaSurface(policy({ self: 'on' }))).toBe('none')
expect(teamMfaSurface(policy({ self: 'unknown' }))).toBe('none')
expect(teamMfaSurface(policy({ policy: null, self: 'off' }))).toBe('none')
expect(teamMfaSurface(policy({ policy: null, self: 'blocked' }))).toBe('none')
expect(teamMfaSurface(null)).toBe('none')
})
})
describe('banner', () => {
it('names the team, the countdown and the date, and offers the setup action', () => {
const onSetUp = vi.fn()
const { container, getByRole } = render(
<TeamMfaBanner
teamName="Acme"
enforceAt={NOW + 6 * DAY}
now={NOW}
setupUrl={setupUrl}
onSetUp={onSetUp}
/>
)
expect(container.textContent).toContain('Acme requires two-factor authentication. 6 days left.')
expect(container.textContent).toContain('November 24, 2026')
fireEvent.click(getByRole('button', { name: 'Set up MFA' }))
expect(onSetUp).toHaveBeenCalledTimes(1)
})
})
describe('blocked screen', () => {
const screen = (props: { checking?: boolean; stillMissing?: boolean } = {}) => {
const handlers = { onSetUp: vi.fn(), onRecheck: vi.fn(), onUsePersonal: vi.fn() }
const view = render(
<TeamMfaBlockedScreen
teamName="Acme"
enforceAt={NOW - 2 * DAY}
setupUrl={setupUrl}
checking={props.checking === true}
stillMissing={props.stillMissing === true}
{...handlers}
/>
)
return { ...view, ...handlers }
}
it('says what to do, not a generic error, and keeps the personal account reachable', () => {
const view = screen()
expect(view.container.textContent).toContain('Set up two-factor authentication to use Acme')
expect(view.container.textContent).toContain('Your workspaces and files are safe')
fireEvent.click(view.getByRole('button', { name: 'Set up MFA' }))
fireEvent.click(view.getByRole('button', { name: 'I’ve set it up' }))
fireEvent.click(view.getByRole('button', { name: 'Use my personal account for now' }))
expect(view.onSetUp).toHaveBeenCalledTimes(1)
expect(view.onRecheck).toHaveBeenCalledTimes(1)
expect(view.onUsePersonal).toHaveBeenCalledTimes(1)
})
it('ignores a second re-check while one runs, and says when MFA is still missing', () => {
const checking = screen({ checking: true })
fireEvent.click(checking.getByRole('button', { name: 'I’ve set it up' }))
expect(checking.onRecheck).not.toHaveBeenCalled()
cleanup()
expect(screen({ stillMissing: true }).container.textContent).toContain(
'Your account still has no two-factor authentication'
)
})
})
describe('Require MFA row', () => {
const manage = { available: true, pendingMembers: 2 }
const row = (props: Partial<RequireMfaRowProps> = {}) => {
const handlers = {
onRequire: vi.fn(),
onTurnOff: vi.fn(),
onRemind: vi.fn(),
onSetUpOwn: vi.fn()
}
const view = render(
<RequireMfaRow
policy={policy({ policy: null, self: 'on', manage })}
pending={null}
now={NOW}
busy={false}
notice={null}
{...handlers}
{...props}
/>
)
return { ...view, ...handlers }
}
it('requires MFA with the chosen grace period, 14 days by default', () => {
const view = row()
fireEvent.click(view.getByRole('button', { name: 'Require MFA' }))
expect(view.onRequire).toHaveBeenCalledWith(14)
})
it('holds the change back from an admin without MFA, and points them to setup', () => {
const view = row({ policy: policy({ policy: null, self: 'off', manage }) })
fireEvent.click(view.getByRole('button', { name: 'Require MFA' }))
expect(view.onRequire).not.toHaveBeenCalled()
expect(view.container.textContent).toContain(
'Set up two-factor authentication on your own account first'
)
fireEvent.click(view.getByRole('button', { name: 'Set up MFA' }))
expect(view.onSetUpOwn).toHaveBeenCalledTimes(1)
})
it('holds turning it off back from an admin without MFA too', () => {
const view = row({ policy: policy({ self: 'pending', manage }) })
fireEvent.click(view.getByRole('button', { name: 'Stop requiring' }))
expect(view.onTurnOff).not.toHaveBeenCalled()
})
it('shows the date, who is pending, and reminds everyone or one member', () => {
const view = row({
policy: policy({ self: 'on', manage }),
pending: [
{ userId: 'u-ada', email: 'ada@acme.dev', displayName: 'Ada Lovelace', mfa: 'pending' },
{ userId: null, email: 'linus@acme.dev', mfa: 'pending' }
]
})
expect(view.container.textContent).toContain('Required from November 24, 2026. 6 days left.')
expect(view.container.textContent).toContain('2 members still need it')
fireEvent.click(view.getByRole('button', { name: 'Remind everyone' }))
expect(view.onRemind).toHaveBeenLastCalledWith()
// A member who never signed in to Orca has no id to remind by; only Ada gets a button.
const single = view.getAllByRole('button', { name: 'Remind' })
expect(single).toHaveLength(1)
fireEvent.click(single[0]!)
expect(view.onRemind).toHaveBeenLastCalledWith('u-ada')
})
it('says members have no access once the deadline passed', () => {
const view = row({
policy: policy({
self: 'on',
manage,
policy: { enforceAt: NOW - DAY, setAt: NOW - 8 * DAY }
}),
pending: [{ userId: 'u-ada', email: 'ada@acme.dev', mfa: 'blocked' }]
})
expect(view.container.textContent).toContain('Required since November 17, 2026')
expect(view.container.textContent).toContain('No access')
})
it('says plainly when a reminder was recorded but not emailed', () => {
const view = row({
policy: policy({ self: 'on', manage }),
notice: { kind: 'reminded', recipients: 2, emailed: false }
})
expect(view.container.textContent).toContain('nothing was sent')
expect(view.container.textContent).not.toContain('Reminder sent')
})
})
describe('the server refusal in cloud workspace errors', () => {
it('says to set up MFA, never to sign in again', () => {
for (const explain of [describeError, describeInlineError]) {
const message = explain('unauthorized', 'mfa_required', translate)
expect(message).toContain('requires two-factor authentication')
expect(message).not.toMatch(/sign in/i)
}
// Any other unauthorized answer is still the sign-in message.
expect(describeInlineError('unauthorized', undefined, translate)).not.toContain('two-factor')
})
})
describe('banner after the deadline', () => {
it('says there is no access until MFA is set up, and that the personal account is fine', () => {
const { container, getByRole } = render(
<TeamMfaBanner
teamName="Acme"
enforceAt={NOW - DAY}
now={NOW}
setupUrl={setupUrl}
onSetUp={() => {}}
blocked
variant="sidebar"
/>
)
// An alert once blocked; a quiet status while there is still time.
expect(container.querySelector('[data-team-mfa-banner="blocked"]')?.getAttribute('role')).toBe(
'alert'
)
expect(container.textContent).toContain('Acme requires two-factor authentication')
expect(container.textContent).toContain('until you set it up')
expect(container.textContent).toContain('Your personal account isn’t affected')
expect(container.textContent).not.toContain('days left')
expect(getByRole('button', { name: 'Set up MFA' })).toBeTruthy()
})
})
describe('escalation', () => {
it('is quiet with more than three days left, a warning in the last three, blocked on the server', () => {
expect(mfaUrgency(NOW + 14 * DAY, NOW, false)).toBe('quiet')
expect(mfaUrgency(NOW + 3 * DAY + 1, NOW, false)).toBe('quiet')
expect(mfaUrgency(NOW + 3 * DAY, NOW, false)).toBe('soon')
expect(mfaUrgency(NOW + DAY, NOW, false)).toBe('soon')
// Past the deadline by the clock but not blocked by the server: still only a warning.
expect(mfaUrgency(NOW - DAY, NOW, false)).toBe('soon')
expect(mfaUrgency(NOW + 14 * DAY, NOW, true)).toBe('blocked')
})
it('names the days in the title once it is close', () => {
expect(mfaSoonTitle('Acme', NOW + 2 * DAY, NOW, translate)).toBe('Acme requires MFA in 2 days')
expect(mfaSoonTitle('Acme', NOW + DAY, NOW, translate)).toBe('Acme requires MFA in 1 day')
expect(mfaSoonTitle('Acme', NOW - 1, NOW, translate)).toBe('Acme requires MFA now')
})
it('marks the sidebar card with its urgency', () => {
const card = (daysLeft: number, blocked = false): string | null | undefined =>
render(
<TeamMfaBanner
variant="sidebar"
teamName="Acme"
enforceAt={NOW + daysLeft * DAY}
now={NOW}
setupUrl={setupUrl}
onSetUp={() => {}}
blocked={blocked}
/>
)
.container.querySelector('[data-team-mfa-banner]')
?.getAttribute('data-team-mfa-banner')
expect(card(14)).toBe('quiet')
cleanup()
expect(card(2)).toBe('soon')
cleanup()
expect(card(-2, true)).toBe('blocked')
})
})
describe('one-time toast', () => {
const memory = (): Pick<Storage, 'getItem' | 'setItem'> => {
const map = new Map<string, string>()
return {
getItem: (key) => map.get(key) ?? null,
setItem: (key, value) => void map.set(key, value)
}
}
it('shows once per team and deadline, and again when the date changes', () => {
const storage = memory()
expect(claimMfaToast(storage, 'org_1', 100)).toBe(true)
expect(claimMfaToast(storage, 'org_1', 100)).toBe(false)
expect(claimMfaToast(storage, 'org_1', 200)).toBe(true)
expect(claimMfaToast(storage, 'org_2', 100)).toBe(true)
})
it('shows rather than hides when storage is unavailable', () => {
expect(claimMfaToast(null, 'org_1', 100)).toBe(true)
const broken = {
getItem: () => {
throw new Error('denied')
},
setItem: () => {}
}
expect(claimMfaToast(broken, 'org_1', 100)).toBe(true)
})
})
@@ -0,0 +1,70 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import type { OrcaTeamMfaPolicy } from '../../../../shared/orca-team-mfa-policy'
export type TeamMfaPolicyState = {
/** Null until a read answers, when signed out of a team, or when the server has no policy API. */
policy: OrcaTeamMfaPolicy | null
/** A read is running. */
checking: boolean
/** Re-reads now; resolves with what the server said (null when it could not be read). */
refresh: () => Promise<OrcaTeamMfaPolicy | null>
}
/**
* The active team's "require MFA" policy and the person's own state in it. Read when the team
* changes and when the window regains focus: the person sets MFA up in the browser and comes back.
* A failed read keeps the last answer, so a flaky network neither hides the banner nor blocks.
*/
export function useTeamMfaPolicy(orgId: string | null): TeamMfaPolicyState {
const [policy, setPolicy] = useState<OrcaTeamMfaPolicy | null>(null)
const [checking, setChecking] = useState(false)
// Answers for a team the person has since switched away from are dropped.
const current = useRef(orgId)
current.current = orgId
const refresh = useCallback(async (): Promise<OrcaTeamMfaPolicy | null> => {
if (!orgId) {
return null
}
setChecking(true)
let result: Awaited<ReturnType<typeof window.api.orcaProfiles.teamMfaPolicy>> | null
try {
result = (await window.api.orcaProfiles.teamMfaPolicy({ orgId })) ?? null
} catch {
result = null
}
if (current.current !== orgId) {
return null
}
setChecking(false)
if (result?.status !== 'ok') {
return null
}
const { status: _status, ...next } = result
setPolicy(next)
return next
}, [orgId])
useEffect(() => {
setPolicy(null)
setChecking(false)
if (!orgId) {
return
}
void refresh()
const onFocus = (): void => void refresh()
const onVisibility = (): void => {
if (document.visibilityState === 'visible') {
void refresh()
}
}
window.addEventListener('focus', onFocus)
document.addEventListener('visibilitychange', onVisibility)
return () => {
window.removeEventListener('focus', onFocus)
document.removeEventListener('visibilitychange', onVisibility)
}
}, [orgId, refresh])
return { policy, checking, refresh }
}
@@ -1,87 +0,0 @@
// @vitest-environment happy-dom
// COPY-LINK-RULE on the build sheet: "How to push to GitHub" is a split button whose chevron copies
// GitHub's guide; "Contact support" lives in the More menu, so a "Copy support link" item sits
// right below it.
import { cleanup, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }))
vi.mock('sonner', () => ({ toast }))
import { TooltipProvider } from '@/components/ui/tooltip'
import { FailureActionRow, type VmBuildFailureActions } from './VmBuildFailureActions'
import type { VmBuildFailure } from './vm-build-failure'
import { ORCA_SUPPORT_URL, PUSH_TO_GITHUB_URL } from './vm-build-repo-actions'
import { translate } from '@/i18n/i18n'
const writeClipboardText = vi.fn<(text: string) => Promise<void>>()
beforeEach(() => {
writeClipboardText.mockReset().mockResolvedValue(undefined)
Object.assign(window, { api: { ...window.api, ui: { writeClipboardText } } })
})
afterEach(cleanup)
const actions = (): VmBuildFailureActions => ({
onFixWithAgent: vi.fn(),
onRetry: vi.fn(),
onEditRecipe: vi.fn(),
onOpenAnyway: vi.fn(),
onStartAgain: vi.fn(),
onDismiss: vi.fn(),
onSeePlans: vi.fn(),
onOpenBilling: vi.fn(),
onCreateLocally: vi.fn(),
onSignIn: vi.fn(),
onShowWorkspaces: vi.fn(),
onContactSupport: vi.fn(),
onConnectGitHub: vi.fn(),
onPushToGitHub: vi.fn()
})
function row(failure: VmBuildFailure, handlers: VmBuildFailureActions) {
return render(
<TooltipProvider>
<FailureActionRow
failure={failure}
cloud
vmKept={false}
canFixWithAgent={false}
canManageBilling
signingIn={false}
connectingGitHub={false}
actions={handlers}
t={translate}
/>
</TooltipProvider>
)
}
describe('build sheet external links (COPY-LINK-RULE)', () => {
it('"How to push to GitHub" opens as before, and its chevron copies the guide without opening', async () => {
const handlers = actions()
row({ kind: 'noGithubRemote' }, handlers)
const user = userEvent.setup()
await user.click(screen.getByRole('button', { name: 'How to push to GitHub' }))
expect(handlers.onPushToGitHub).toHaveBeenCalledOnce()
expect(writeClipboardText).not.toHaveBeenCalled()
await user.click(screen.getByRole('button', { name: 'More link options' }))
await user.click(await screen.findByRole('menuitem', { name: 'Copy link' }))
await waitFor(() => expect(writeClipboardText).toHaveBeenCalledWith(PUSH_TO_GITHUB_URL))
expect(handlers.onPushToGitHub).toHaveBeenCalledOnce()
})
it('"Copy support link" sits right below "Contact support" and copies without opening', async () => {
const handlers = actions()
row({ kind: 'snapshotMissing' }, handlers)
const user = userEvent.setup()
await user.click(screen.getByRole('button', { name: /More/ }))
const items = (await screen.findAllByRole('menuitem')).map((item) => item.textContent)
expect(items).toEqual(['Contact support', 'Copy support link'])
await user.click(screen.getByRole('menuitem', { name: 'Copy support link' }))
await waitFor(() => expect(writeClipboardText).toHaveBeenCalledWith(ORCA_SUPPORT_URL))
expect(handlers.onContactSupport).not.toHaveBeenCalled()
})
})
@@ -7,7 +7,6 @@ import {
Github,
Loader2,
LifeBuoy,
Link2,
LogIn,
Monitor,
PanelLeft,
@@ -23,13 +22,6 @@ import {
DropdownMenuTrigger
} from '@/components/ui/dropdown-menu'
import type { Translate } from '@/i18n/use-translate'
import { OpenExternalSplitButton } from '@/components/open-external/OpenExternalSplitButton'
import {
copyExternalLink,
type ExternalLinkSource
} from '@/components/open-external/copy-external-link'
import { ORCA_SUPPORT_URL, PUSH_TO_GITHUB_URL } from './vm-build-repo-actions'
import { gitHubInstallLinkSource } from '@/lib/orca-cloud/github-link-sources'
import type { VmBuildFailure } from './vm-build-failure'
export type VmBuildFailureActions = {
@@ -61,8 +53,6 @@ type Action = {
pending?: boolean
/** Outline even when first: a way around the problem, not its fix. */
secondary?: boolean
/** Opens this page in the browser: a chevron beside it offers "Copy link". */
link?: ExternalLinkSource
/** A More-menu row that leaves Orca for the browser: marked like the Help menu's. */
external?: boolean
}
@@ -240,17 +230,6 @@ function failureActions(
icon: <LifeBuoy />,
onClick: actions.onContactSupport,
external: true
},
// A menu row can't carry the split's chevron: the same page, copied for another browser
// (COPY-LINK-RULE, as "Copy GitHub link" under "Add a GitHub repository…").
{
key: 'copySupportLink',
label: t(
'auto.components.worktree.creation.VmBuildFailureCard.copySupportLink',
'Copy support link'
),
icon: <Link2 />,
onClick: () => void copyExternalLink(ORCA_SUPPORT_URL)
}
]
}
@@ -270,9 +249,7 @@ function failureActions(
),
icon: connectingGitHub ? <Loader2 className="animate-spin" /> : <Github />,
onClick: actions.onConnectGitHub,
pending: connectingGitHub,
// The same install page connectOrcaCloudGitHub opens (no repository preselected).
link: gitHubInstallLinkSource()
pending: connectingGitHub
},
tryAgain
],
@@ -288,8 +265,7 @@ function failureActions(
'How to push to GitHub'
),
icon: <SquareArrowOutUpRight />,
onClick: actions.onPushToGitHub,
link: PUSH_TO_GITHUB_URL
onClick: actions.onPushToGitHub
},
// After pushing, the same create works without leaving the sheet.
tryAgain
@@ -339,37 +315,21 @@ export function FailureActionRow({
const destroys = vmKept
return (
<div className="flex flex-wrap items-center gap-2">
{primary.map((action, index) =>
action.link ? (
<OpenExternalSplitButton
key={action.key}
size="sm"
variant={index === 0 && !action.secondary ? 'default' : 'outline'}
link={action.link}
onClick={() => (action.pending ? undefined : action.onClick())}
disabled={action.disabled}
aria-disabled={action.pending || undefined}
aria-busy={action.pending || undefined}
>
{action.icon}
{action.label}
</OpenExternalSplitButton>
) : (
<Button
key={action.key}
type="button"
size="sm"
variant={index === 0 && !action.secondary ? 'default' : 'outline'}
onClick={action.pending ? undefined : action.onClick}
disabled={action.disabled}
aria-disabled={action.pending || undefined}
aria-busy={action.pending || undefined}
>
{action.icon}
{action.label}
</Button>
)
)}
{primary.map((action, index) => (
<Button
key={action.key}
type="button"
size="sm"
variant={index === 0 && !action.secondary ? 'default' : 'outline'}
onClick={action.pending ? undefined : action.onClick}
disabled={action.disabled}
aria-disabled={action.pending || undefined}
aria-busy={action.pending || undefined}
>
{action.icon}
{action.label}
</Button>
))}
{more.length > 0 ? (
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
@@ -1,58 +0,0 @@
// COPY-LINK-RULE on the build sheet: "How to push to GitHub" as a split button (its chevron menu
// open), and "Copy support link" right below "Contact support" in the More menu.
import { defineFixture } from '../../component-fixtures/component-fixture'
import {
CLOUD_RECIPE,
FAILED_LOG,
T0,
entry,
seedFixtureRepo,
sheet
} from './vm-build-sheet-fixture-support'
const settle = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 120))
// Radix menus open on pointerdown, not click.
function openMenu(selector: string) {
return async (frame: HTMLElement): Promise<void> => {
frame
.querySelector<HTMLButtonElement>(selector)
?.dispatchEvent(
new PointerEvent('pointerdown', { bubbles: true, button: 0, pointerType: 'mouse' })
)
await settle()
}
}
function failed(errorCode: string, error: string, log: string) {
return {
value: entry(
{ status: 'error', errorCode, provisioningLog: log, errorAt: T0 + 2_000 },
CLOUD_RECIPE
),
error
}
}
const noRemote = failed(
'cloudNoGithubRemote',
'Orca Cloud clones your code from GitHub, and this repository has no GitHub remote.',
''
)
const snapshot = failed('recipeExited', 'Recipe exited with code 1.', FAILED_LOG)
/** "How to push to GitHub" with its chevron open: Copy link. */
export const pushToGitHubCopyLink = defineFixture({
width: 760,
setup: () => seedFixtureRepo(null),
render: () => sheet(noRemote.value, noRemote.error, T0 + 2_000),
interact: openMenu('button[aria-label="More link options"]')
})
/** "Contact support" in More, with "Copy support link" right below it. */
export const contactSupportCopyLink = defineFixture({
width: 760,
setup: () => seedFixtureRepo(),
render: () => sheet(snapshot.value, snapshot.error, T0 + 2_000),
interact: openMenu('[data-vm-build-sheet] button[aria-haspopup="menu"]')
})
+12
View File
@@ -1362,6 +1362,18 @@
"unavailableCount_one": "{{count}} unavailable",
"unavailableCount_other": "{{count}} unavailable"
},
"teamMfa": {
"daysLeft_one": "{{count}} day left",
"daysLeft_other": "{{count}} days left",
"nowWarning_one": "{{count}} member doesn’t have it yet and will lose access to this team right away.",
"nowWarning_other": "{{count}} members don’t have it yet and will lose access to this team right away.",
"pendingCount_one": "{{count}} member still needs it",
"pendingCount_other": "{{count}} members still need it",
"reminded_one": "Reminder sent to {{count}} member.",
"reminded_other": "Reminder sent to {{count}} members.",
"soonTitle_one": "{{value0}} requires MFA in {{count}} day",
"soonTitle_other": "{{value0}} requires MFA in {{count}} days"
},
"teammates": {
"daySandboxHours_one": "{{hours}} sandbox hour",
"daySandboxHours_other": "{{hours}} sandbox hours"
+64 -6
View File
@@ -4714,8 +4714,7 @@
"trialLimitBodyCount_other": "Your trial can run {{count}} sandboxes at once. Put one to sleep or delete it, then try again. Nothing was created, and you weren’t charged.",
"teamLimitBodyNoSeatCount_one": "Your team can run {{count}} sandbox at once. Put it to sleep or delete it, then try again. Nothing was created, and you weren’t charged.",
"teamLimitBodyNoSeatCount_other": "Your team can run {{count}} sandboxes at once. Put one to sleep or delete it, then try again. Nothing was created, and you weren’t charged.",
"trialLimitTitle": "You’re at your trial’s limit of running sandboxes",
"copySupportLink": "Copy support link"
"trialLimitTitle": "You’re at your trial’s limit of running sandboxes"
},
"VmBuildLog": {
"jumpToError": "Jump to first error",
@@ -14079,6 +14078,15 @@
"keywordSignOut": "sign out",
"keywordRelay": "relay",
"keywordCloud": "cloud",
"mfa": {
"title": "Two-factor authentication",
"on": "On",
"off": "Off",
"onDescription": "Signing in asks for a code from your authenticator app. Keep your backup codes somewhere safe.",
"offDescription": "Add an authenticator app so a stolen password is not enough to sign in. You get backup codes too.",
"manage": "Manage in browser",
"setUp": "Set up in browser"
},
"github": {
"disconnectTitle": "Disconnect GitHub?",
"disconnectBody": "Commits in cloud workspaces will use Orca Cloud's name again.",
@@ -21273,6 +21281,10 @@
"makeOwnerTitle": "Make {{value0}} an owner?",
"members": "Members",
"membersList": "Team members and invites",
"mfaOn": "MFA on",
"mfaOff": "MFA off",
"mfaPending": "MFA pending",
"mfaPendingBy": "MFA due {{value0}}",
"nextInvoice": "Next invoice (est.)",
"nextInvoiceOn": "{{value0}} · {{value1}}",
"notAnEmail": "Not an email address",
@@ -21695,7 +21707,8 @@
"errorTrialSandboxLimit_one": "Your trial can run {{count}} sandbox at once. Put it to sleep or delete it, then try again.",
"errorTrialSandboxLimit_other": "Your trial can run {{count}} sandboxes at once. Put one to sleep or delete it, then try again.",
"errorTeamSandboxLimitNoSeat_one": "Your team can run {{count}} sandbox at once. Put it to sleep or delete it, then try again.",
"errorTeamSandboxLimitNoSeat_other": "Your team can run {{count}} sandboxes at once. Put one to sleep or delete it, then try again."
"errorTeamSandboxLimitNoSeat_other": "Your team can run {{count}} sandboxes at once. Put one to sleep or delete it, then try again.",
"sharedPersonalSecretsNote": "Your personal cloud secrets aren’t used in shared workspaces. Shared and repository secrets still are."
},
"orcaCloud": {
"QueuedPrompt": {
@@ -21772,6 +21785,52 @@
},
"NewWorkspaceComposerFooter": {
"create": "Create"
},
"teamMfa": {
"dueNow": "Due now",
"daysLeft_one": "{{count}} day left",
"daysLeft_other": "{{count}} days left",
"graceNow": "Immediately",
"grace7": "In 7 days",
"grace14": "In 14 days",
"grace30": "In 30 days",
"bannerTitle": "{{value0}} requires two-factor authentication. {{value1}}.",
"bannerBody": "Set it up by {{value0}}. After that you can’t use this team’s workspaces until you do.",
"bannerBlockedTitle": "{{value0}} requires two-factor authentication",
"soonTitleNow": "{{value0}} requires MFA now",
"soonTitle_one": "{{value0}} requires MFA in {{count}} day",
"soonTitle_other": "{{value0}} requires MFA in {{count}} days",
"toast": "{{value0}} requires MFA from {{value1}}.",
"bannerBlockedBody": "You can’t use this team’s workspaces until you set it up. Your personal account isn’t affected.",
"setUp": "Set up MFA",
"blockedTitle": "Set up two-factor authentication to use {{value0}}",
"blockedBody": "{{value0}} has required it for all members since {{value1}}. Your workspaces and files are safe, and open again as soon as you add an authenticator app.",
"recheck": "I’ve set it up",
"stillMissing": "Your account still has no two-factor authentication. Finish the setup in your browser, then try again.",
"usePersonal": "Use my personal account for now",
"rowTitle": "Require two-factor authentication",
"rowOff": "Members without it lose access to this team’s workspaces after the date you pick, until they set it up. They get an email now and reminders before the date.",
"rowEnforced": "Required since {{value0}}. Members without it can’t use this team until they set it up.",
"rowScheduled": "Required from {{value0}}. {{value1}}.",
"graceLabel": "When to start requiring it",
"require": "Require MFA",
"turnOff": "Stop requiring",
"ownMfaTitle": "Set up two-factor authentication on your own account first",
"ownMfaBody": "Only someone who already has it can change this, so nobody locks the team out.",
"nowWarning_one": "{{count}} member doesn’t have it yet and will lose access to this team right away.",
"nowWarning_other": "{{count}} members don’t have it yet and will lose access to this team right away.",
"allSet": "Every member has it set up.",
"pendingCount_one": "{{count}} member still needs it",
"pendingCount_other": "{{count}} members still need it",
"remindAll": "Remind everyone",
"pendingList": "Members without MFA",
"memberBlocked": "No access",
"memberPending": "Pending",
"remindOne": "Remind",
"reminded_one": "Reminder sent to {{count}} member.",
"reminded_other": "Reminder sent to {{count}} members.",
"remindedNoEmail": "Reminder recorded, but email delivery is off on this server, so nothing was sent.",
"requiredInline": "Your team requires two-factor authentication. Set it up in Settings, Account to use its cloud workspaces."
}
},
"i18n": {
@@ -24014,7 +24073,6 @@
"privateLabel": "Private",
"menuGroup": "Orca Cloud",
"addRepositoryMenu": "Add a GitHub repository…",
"copyAddRepositoryLink": "Copy GitHub link",
"waitingForGitHubAccess": "Waiting for GitHub access…",
"noNewRepositoryYet": "No new repository yet.",
"checkAgain": "Check again",
@@ -28153,9 +28211,9 @@
},
"setUpAgent": "Set up an agent",
"personal": {
"description": "Only you get these, in every Orca Cloud workspace you start.",
"emptyTitle": "No personal secrets yet",
"emptyDetail": "Add one or paste a .env file. New terminals and agents in your cloud workspaces get them as environment variables."
"emptyDetail": "Add one or paste a .env file. New terminals and agents in your cloud workspaces get them as environment variables.",
"descriptionUnshared": "Only you get these, in cloud workspaces you haven’t shared. Shared workspaces don’t get them."
},
"org": {
"description": "Everyone on your team gets these in their Orca Cloud workspaces.",
@@ -13,7 +13,7 @@
},
{
"path": "src/renderer/src/components/worktree-creation/VmBuildFailureActions.tsx",
"line": 412,
"line": 372,
"term": "VM",
"reason": "recipe-VM branch; cloud branch says sandbox"
},
@@ -1,19 +1,9 @@
// "Copy link" for the GitHub handoffs: the same single-use page Connect GitHub (App install) and
// Connect your GitHub (OAuth) open, minted the same way in main but returned instead of opened.
// "Copy link" for connecting your GitHub identity (OAuth sign-in): the same single-use page Connect
// your GitHub opens, minted the same way in main but returned instead of opened. Copy link is for
// sign-in pages only; the GitHub App install keeps a plain button.
import { requireLink, type ExternalLinkSource } from '@/components/open-external/copy-external-link'
import { cloudWorkspaceApi } from './orca-cloud-workspace-store'
/** The GitHub App install page; with a repository, GitHub preselects it (and a setup session returns). */
export function gitHubInstallLinkSource(args?: {
repoUrl?: string
setupSessionId?: string
}): ExternalLinkSource {
return async () => {
const result = await cloudWorkspaceApi()?.gitHubInstallLink(args)
return requireLink(result?.ok ? result.value : null)
}
}
/** GitHub's OAuth page for connecting the person's own GitHub identity. */
export function gitHubUserConnectLinkSource(): ExternalLinkSource {
return async () => {
@@ -47,7 +47,6 @@ function stub(
connectGitHub: vi.fn(unused),
getGitHubUser: vi.fn(unused),
connectGitHubUser: vi.fn(unused),
gitHubInstallLink: vi.fn(unused),
gitHubUserConnectLink: vi.fn(unused),
disconnectGitHubUser: vi.fn(unused),
getRepoAccess: vi.fn(unused),
@@ -37,7 +37,6 @@ function stub(
connectGitHub: vi.fn(unused),
getGitHubUser: vi.fn(unused),
connectGitHubUser: vi.fn(unused),
gitHubInstallLink: vi.fn(unused),
gitHubUserConnectLink: vi.fn(unused),
disconnectGitHubUser: vi.fn(unused),
getRepoAccess: vi.fn(unused),
@@ -42,7 +42,6 @@ function stubApi(overrides: Partial<OrcaCloudWorkspaceApi> = {}): OrcaCloudWorks
connectGitHub: vi.fn(async () => ok(null)),
getGitHubUser: vi.fn(async () => ok({ connected: false as const })),
connectGitHubUser: vi.fn(async () => ok(null)),
gitHubInstallLink: vi.fn(async () => ok('https://github.com/apps/x/installations/new')),
gitHubUserConnectLink: vi.fn(async () => ok('https://github.com/login/oauth/authorize')),
disconnectGitHubUser: vi.fn(async () => ok({ connected: false as const })),
getRepoAccess: vi.fn(async () =>
@@ -0,0 +1,117 @@
// @vitest-environment happy-dom
// GH-CREATE-CANCEL and GH-CREATE-NO-ROW for a GitHub-only Orca Cloud create: Cancel at any step
// leaves no workspace (the sandbox is deleted, which drops the pairing too), and a create that
// opens hands its pending row off to the paired server's rows, which stay hidden until then.
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { useAppStore } from '@/store'
type OpenOptions = { onHost?: (hostId: string) => void }
type OpenOutcome = { ok: true; worktreeId: string | null; hostId?: string }
const mocks = vi.hoisted(() => ({
open: vi.fn<(workspace: unknown, options?: OpenOptions) => Promise<OpenOutcome>>(),
launch: vi.fn()
}))
vi.mock('@/components/cloud-workspaces/open-cloud-workspace', () => ({
openCloudWorkspace: mocks.open
}))
vi.mock('@/lib/agent-session/launch/new-tab/launch-agent-in-new-tab', () => ({
launchAgentInNewTabWithOutcome: mocks.launch
}))
import { startCloudWorkspaceFromGitHub } from './start-cloud-workspace-from-github'
import { resetGitHubCreateKeysForTest } from './github-cloud-create-key'
const createFromGitHub = vi.fn<(args: unknown) => Promise<unknown>>()
const destroy = vi.fn(async () => ({ ok: true, value: undefined }))
beforeEach(() => {
resetGitHubCreateKeysForTest()
useAppStore.setState({ pendingWorktreeCreations: {}, activePendingCreationId: null })
createFromGitHub.mockResolvedValue({ ok: true, value: { sandboxId: 'sbx_1' } })
mocks.open.mockResolvedValue({ ok: true, worktreeId: null })
Object.assign(window, {
api: {
...window.api,
orcaCloudWorkspace: { createFromGitHub },
cloudWorkspaces: {
get: vi.fn(async (id: string) => ({ ok: true, value: { id } })),
destroy,
localWorkspaces: vi.fn(async () => []),
environmentBindings: vi.fn(async () => ({}))
},
ephemeralVm: {
onProvisionEvent: () => () => {},
cancelProvision: vi.fn(async () => ({ cancelled: true })),
// Cancel's cleanup looks for this create's runtime records; a GitHub-only create has none.
listRuntimes: vi.fn(async () => [])
}
}
})
})
afterEach(() => {
vi.clearAllMocks()
})
const REQUEST = {
repoUrl: 'https://github.com/acme/web',
fullName: 'acme/web',
prompt: '',
agent: null,
composerRepoId: 'repo-1'
}
const creationId = (): string =>
Object.keys(useAppStore.getState().pendingWorktreeCreations)[0] ?? ''
const cancel = (): void => useAppStore.getState().removePendingWorktreeCreation(creationId())
describe('Cancel leaves no workspace (GH-CREATE-CANCEL)', () => {
it('cancelled after the sandbox started, before it opened: deleted, never opened', async () => {
createFromGitHub.mockImplementationOnce(async () => {
cancel()
return { ok: true, value: { sandboxId: 'sbx_1' } }
})
expect(await startCloudWorkspaceFromGitHub(REQUEST)).toBe(false)
expect(mocks.open).not.toHaveBeenCalled()
expect(destroy).toHaveBeenCalledWith('sbx_1')
})
it('cancelled while it opened: the sandbox is deleted (its pairing and row go with it)', async () => {
mocks.open.mockImplementationOnce(async (_workspace, options) => {
options?.onHost?.('runtime:p')
cancel()
return { ok: true, worktreeId: 'w1', hostId: 'runtime:p' }
})
expect(await startCloudWorkspaceFromGitHub(REQUEST)).toBe(false)
expect(destroy).toHaveBeenCalledWith('sbx_1')
expect(useAppStore.getState().pendingWorktreeCreations).toEqual({})
})
it('cancelled while the create was in flight: main reclaims it; nothing opens here', async () => {
createFromGitHub.mockImplementationOnce(async () => {
cancel()
return { ok: false, code: 'failed', message: 'Cancelled.' }
})
expect(await startCloudWorkspaceFromGitHub(REQUEST)).toBe(false)
expect(window.api.ephemeralVm.cancelProvision).toHaveBeenCalled()
expect(mocks.open).not.toHaveBeenCalled()
})
})
describe('pending row hand-off (GH-CREATE-NO-ROW)', () => {
it('records the paired server while opening, and the hand-off drops the pending row', async () => {
let pairingHostIdDuringOpen: string | undefined
mocks.open.mockImplementationOnce(async (_workspace, options) => {
options?.onHost?.('runtime:p')
pairingHostIdDuringOpen =
useAppStore.getState().pendingWorktreeCreations[creationId()]?.pairingHostId
return { ok: true, worktreeId: null }
})
expect(await startCloudWorkspaceFromGitHub(REQUEST)).toBe(true)
expect(pairingHostIdDuringOpen).toBe('runtime:p')
expect(useAppStore.getState().pendingWorktreeCreations).toEqual({})
expect(destroy).not.toHaveBeenCalled()
})
})
@@ -9,6 +9,7 @@
import { useAppStore } from '@/store'
import { translate } from '@/i18n/i18n'
import { openCloudWorkspace } from '@/components/cloud-workspaces/open-cloud-workspace'
import { refreshCloudWorktreeBindings } from '@/components/cloud-workspaces/cloud-workspace-identity'
import { createNonSecureContextUuid } from '../../../../shared/non-secure-context-uuid'
import { isTuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent-config'
import { ORCA_CLOUD_RECIPE_ID } from '../../../../shared/hosted-sandbox/orca-cloud-recipe-id'
@@ -87,7 +88,12 @@ export function startCloudWorkspaceFromGitHub(request: StartFromGitHubRequest):
})
store.setActiveView('terminal')
store.setSidebarOpen(true)
return runGitHubCloudCreate(creationId)
return runTracked(creationId)
}
/** Cancel's "Deleting the sandbox…" waits for every step that may still own a sandbox. */
function runTracked(creationId: string): Promise<boolean> {
return trackOrcaCloudCreateStep(creationId, runGitHubCloudCreate(creationId))
}
/** The sheet's Retry (and the plans page's retry after checkout) for a GitHub-only create. */
@@ -114,7 +120,7 @@ export function retryGitHubCloudCreate(creationId: string): void {
})
store.setActivePendingWorktreeCreation(creationId)
store.setActiveView('terminal')
void runGitHubCloudCreate(creationId)
void runTracked(creationId)
}
function current(creationId: string) {
@@ -186,13 +192,27 @@ async function runGitHubCloudCreate(creationId: string): Promise<boolean> {
return false
}
if (!current(creationId)) {
// Cancelled while it started: main stopped the create and deleted what it had made.
startedSandboxes.delete(creationId)
// GH-CREATE-CANCEL: cancelled after the sandbox started but before it opened.
await discardSandbox(creationId, sandboxId)
return false
}
useAppStore.getState().updatePendingWorktreeCreation(creationId, { phase: 'creating' })
const workspace = await window.api.cloudWorkspaces.get(sandboxId).catch(() => null)
const opened = workspace?.ok ? await openCloudWorkspace(workspace.value) : null
const opened = workspace?.ok
? await openCloudWorkspace(workspace.value, {
// GH-CREATE-NO-ROW: that server's rows wait behind the pending row until the hand-off.
onHost: (hostId) =>
useAppStore
.getState()
.updatePendingWorktreeCreation(creationId, { pairingHostId: hostId })
})
: null
if (!current(creationId)) {
// GH-CREATE-CANCEL: cancelled while it opened. Opening can't be stopped half way, so the
// sandbox is deleted, which also drops this computer's pairing and its row.
await discardSandbox(creationId, sandboxId)
return false
}
if (!opened?.ok) {
// The sandbox exists from here on: Retry opens it and never creates it again.
return fail(
@@ -219,3 +239,14 @@ async function runGitHubCloudCreate(creationId: string): Promise<boolean> {
})
return true
}
/** A cancelled create's sandbox: deleted, so nothing keeps running (or billing) behind the cancel. */
async function discardSandbox(creationId: string, sandboxId: string): Promise<void> {
startedSandboxes.delete(creationId)
forgetGitHubCreateKey(creationId)
const result = await window.api.cloudWorkspaces.destroy(sandboxId).catch(() => null)
if (!result?.ok) {
console.warn('[orca-cloud] cancelled GitHub create: could not delete sandbox', sandboxId)
}
void refreshCloudWorktreeBindings().catch(() => undefined)
}
@@ -3,14 +3,12 @@
// network call; everything else comes from the control plane's GET /v1/github/repo-access (N2),
// cached 5 minutes. While a repository is waiting (an install in the browser, or an org owner's
// approval, D2), `poll` re-checks on the spec's cadence: every 2 s for 3 minutes, then every 10 s.
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useCallback, useEffect, useRef, useState } from 'react'
import { useAppStore } from '@/store'
import { normalizeGitRemoteUrl } from '../../../../shared/git/remotes/git-remote-identity'
import type { HostedGithubRepoAccessResponse } from '../../../../shared/hosted-sandbox/hosted-github-wire'
import type { Repo } from '../../../../shared/repo-types'
import type { ExternalLinkSource } from '@/components/open-external/copy-external-link'
import { cloudWorkspaceApi } from './orca-cloud-workspace-store'
import { gitHubInstallLinkSource } from './github-link-sources'
import { useOrcaCloudIdentityKey } from './orca-cloud-identity'
export type OrcaCloudRepoAccessState =
@@ -139,12 +137,7 @@ export function useOrcaCloudRepoAccess(
/** Fired once when a repository that was waiting becomes reachable (D2's "access granted"). */
onGranted?: () => void
} = {}
): OrcaCloudRepoAccess & {
refresh: () => void
openInstall: () => Promise<boolean>
/** "Copy link" for openInstall: the same single-use install page, minted without opening. */
installLink: ExternalLinkSource | null
} {
): OrcaCloudRepoAccess & { refresh: () => void; openInstall: () => Promise<boolean> } {
const repo = useAppStore((s) =>
repoId ? s.repos.find((entry) => entry.id === repoId) : undefined
)
@@ -218,14 +211,6 @@ export function useOrcaCloudRepoAccess(
return Boolean(result?.ok)
}, [repoUrl, setupSessionId])
const installLink = useMemo(
() =>
repoUrl
? gitHubInstallLinkSource({ repoUrl, ...(setupSessionId ? { setupSessionId } : {}) })
: null,
[repoUrl, setupSessionId]
)
return {
state: enabled || !repoUrl ? state : 'unknown',
...(current?.installUrl ? { installUrl: current.installUrl } : {}),
@@ -235,7 +220,6 @@ export function useOrcaCloudRepoAccess(
repoUrl,
loading: enabled && current === undefined,
refresh,
openInstall,
installLink
openInstall
}
}
@@ -125,3 +125,26 @@ describe('paired workspaces scoped by account (PAIRED-ACCOUNT-FILTER)', () => {
expect(hostsFor('team-two', paired()).hiddenHostIds.has('runtime:gh')).toBe(false)
})
})
describe('GH-CREATE-NO-ROW hand-off', () => {
it('hides the server a GitHub-only create is pairing to until its pending row hands off', () => {
const pairing = (pairingHostId?: string) =>
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the selector reads only these fields.
({
runtimeEnvironments: [{ id: 'p', name: 'web (cloud)', orcaCloudPaired: true }],
orcaProfileAuthStatus: { cloud: { userId: 'u1' } },
pendingWorktreeCreations: {
gh: {
creationId: 'gh',
request: { githubSource: { fullName: 'acme/web' } },
...(pairingHostId ? { pairingHostId } : {})
}
}
}) as unknown as Pick<AppState, 'runtimeEnvironments'>
const hidden = (state: Pick<AppState, 'runtimeEnvironments'>) => [
...parseOrcaCloudHostScopeKey(selectOrcaCloudHostScopeKey(state)).hiddenHostIds
]
expect(hidden(pairing())).toEqual([])
expect(hidden(pairing('runtime:p'))).toEqual(['runtime:p'])
})
})
@@ -13,7 +13,12 @@ import { isOrcaCloudRuntimeEnvironment } from '../../../../shared/remote-runtime
import type { Repo } from '../../../../shared/repo-types'
type CloudScopeState = Pick<AppState, 'runtimeEnvironments'> &
Partial<Pick<AppState, 'orcaProfileAuthStatus' | 'cloudAccountIdByEnvironmentId'>>
Partial<
Pick<
AppState,
'orcaProfileAuthStatus' | 'cloudAccountIdByEnvironmentId' | 'pendingWorktreeCreations'
>
>
/**
* Every Orca Cloud server this desktop runs, `+host` when the active team owns it and `-host`
@@ -30,7 +35,12 @@ type CloudScopeState = Pick<AppState, 'runtimeEnvironments'> &
export function selectOrcaCloudHostScopeKey(state: CloudScopeState): string {
const active = orcaCloudAccountId(state.orcaProfileAuthStatus?.cloud)
const owners = state.cloudAccountIdByEnvironmentId ?? {}
return (state.runtimeEnvironments ?? [])
// GH-CREATE-NO-ROW: a GitHub-only create's pending row stands for its server's rows until the
// hand-off removes it; both change in one store update, so the row never shows twice.
const handingOff = Object.values(state.pendingWorktreeCreations ?? {}).flatMap((entry) =>
entry.request.githubSource && entry.pairingHostId ? [`-${entry.pairingHostId}`] : []
)
const scoped = (state.runtimeEnvironments ?? [])
.filter((environment) => isOrcaCloudRuntimeEnvironment(environment))
.flatMap((environment) => {
const hostId = toRuntimeExecutionHostId(environment.id)
@@ -41,7 +51,7 @@ export function selectOrcaCloudHostScopeKey(state: CloudScopeState): string {
const inTeam = active !== null && owners[environment.id] === active
return [`${inTeam ? '+' : '-'}${hostId}`]
})
.join('\n')
return [...scoped, ...handingOff].join('\n')
}
export function parseOrcaCloudHostScopeKey(key: string): {
@@ -195,6 +195,8 @@ export type PendingWorktreeCreation = {
resumedAt?: number
/** VM creates: the provisioned VM's runtime environment, known once it answers. */
vmEnvironmentId?: string
/** GitHub-only Orca Cloud create: the server it is pairing to; its rows wait for the hand-off. */
pairingHostId?: string
// Local git checkout meter; absent when git emits none or creation runs over SSH/runtime.
checkoutProgress?: WorktreeCheckoutProgress
/** Phases entered so far with their start times, so the chat checklist can time each step. */
@@ -149,13 +149,7 @@ export function createRemovePendingWorktreeCreation(
.catch(() => undefined)
}
const cleanup = cleanUpCancelledVm(creationId, removedEntry.request, get)
// A GitHub-only create past its start is opening a sandbox that stays; nothing is deleted.
const opening = Boolean(removedEntry.request.githubSource) && removedEntry.phase === 'creating'
if (
removedEntry.status === 'creating' &&
isOrcaCloudCreateRequest(removedEntry.request) &&
!opening
) {
if (removedEntry.status === 'creating' && isOrcaCloudCreateRequest(removedEntry.request)) {
beginOrcaCloudCancelCleanup(creationId, cleanup ? [cleanup] : [], {
runtimeId: removedEntry.request.ephemeralVmRuntimeId,
createStartedAt: removedEntry.startedAt,
@@ -186,6 +186,7 @@ export type WorktreeSlice = {
pausedMs?: number
resumedAt?: number
vmEnvironmentId?: string
pairingHostId?: string
checkoutProgress?: PendingWorktreeCreation['checkoutProgress']
worktreeId?: string
heldChatMessage?: string
@@ -65,6 +65,11 @@ export function createWebOrcaProfilesApi(): Partial<PreloadApi> {
status: 'unconfigured',
auth: await webOrcaProfileAuthStatus()
}),
accountMfa: async () => ({ status: 'unconfigured' }),
teamMfaPolicy: async () => ({ status: 'unconfigured' }),
teamMfaPolicySet: async () => ({ status: 'unconfigured' }),
teamMfaPending: async () => ({ status: 'unconfigured' }),
teamMfaRemind: async () => ({ status: 'unconfigured' }),
orgMembersList: async () => ({ status: 'unconfigured' }),
orgMemberInvite: async () => ({ status: 'unconfigured' }),
orgInviteRevoke: async () => ({ status: 'unconfigured' }),
@@ -85,8 +90,6 @@ export function createWebOrcaProfilesApi(): Partial<PreloadApi> {
cloudSetupGet: async () => ({ status: 'unconfigured' }),
cloudSetupLink: async () => ({ status: 'unconfigured' }),
billingOpenPortal: async () => ({ status: 'unconfigured' }),
billingPortalLink: async () => ({ status: 'unconfigured' }),
billingCheckoutLink: async () => ({ status: 'unconfigured' }),
billingTeamPlans: async () => ({ status: 'unconfigured' }),
billingUsageHistory: async () => ({ status: 'unconfigured' }),
billingSetOverage: async () => ({ status: 'unconfigured' }),

Some files were not shown because too many files have changed in this diff Show More