Merge remote-tracking branch 'private/cloud/integration' into cloud/e3-open-egress

# Conflicts:
#	cloud/apps/sandbox-control/src/env.ts
#	cloud/apps/sandbox-control/src/lifecycle.ts
#	cloud/apps/sandbox-control/src/network-policy.ts
#	cloud/apps/sandbox-control/test/network-policy.test.ts
This commit is contained in:
Neil
2026-11-13 03:47:25 -08:00
192 changed files with 6610 additions and 608 deletions
@@ -15,7 +15,7 @@ concurrency:
env:
ORCA_BACKGROUND_LAUNCH: '1'
ORCA_DIAGNOSTICS_TOKEN_URL: https://www.onorca.dev/diagnostics/token
ORCA_DIAGNOSTICS_TOKEN_URL: https://orca.dev/diagnostics/token
ORCA_POSTHOG_WRITE_KEY: ci-build-comparison
NODE_OPTIONS: --max-old-space-size=4096
+16 -4
View File
@@ -63,10 +63,22 @@ function devKeysFor(env: Env): JWTVerifyGetKey | null {
return devKeys.keys
}
/**
* A comma-separated issuer var as jwtVerify's `issuer` option: the token's `iss` must equal one entry.
* Unset or empty: no issuer check (as before lists). Blank entries are ignored; a value with no
* entries left accepts no issuer.
*/
export function issuerList(value: string | undefined): string[] | undefined {
if (!value) {
return undefined
}
return value.split(',').map((issuer) => issuer.trim()).filter(Boolean)
}
let stagingKeys: { source: string; keys: JWTVerifyGetKey } | null = null
/** Staging auth's keys and issuer; never honored when BILLING_ENV is 'prod'. */
function stagingKeysFor(env: Env): { keys: JWTVerifyGetKey; issuer: string } | null {
function stagingKeysFor(env: Env): { keys: JWTVerifyGetKey; issuer: string[] | undefined } | null {
if (env.BILLING_ENV === 'prod' || !env.BILLING_STAGING_JWKS_URL || !env.BILLING_STAGING_AUTH_ISSUER) {
return null
}
@@ -76,7 +88,7 @@ function stagingKeysFor(env: Env): { keys: JWTVerifyGetKey; issuer: string } | n
keys: createRemoteJWKSet(new URL(env.BILLING_STAGING_JWKS_URL))
}
}
return { keys: stagingKeys.keys, issuer: env.BILLING_STAGING_AUTH_ISSUER }
return { keys: stagingKeys.keys, issuer: issuerList(env.BILLING_STAGING_AUTH_ISSUER) }
}
export function readBearer(value: string | null): string | null {
@@ -102,7 +114,7 @@ export async function authenticateDesktop(
if (!token) {
return null
}
const verify = (keys: JWTVerifyGetKey, issuer: string | undefined) =>
const verify = (keys: JWTVerifyGetKey, issuer: string | string[] | undefined) =>
jwtVerify(token, keys, {
audience: env.BILLING_JWT_AUDIENCE,
algorithms: ['ES256'],
@@ -114,7 +126,7 @@ export async function authenticateDesktop(
try {
// Production auth first; in dev only, then staging auth, then the operator key set.
const attempts: Array<() => ReturnType<typeof verify>> = [
() => verify(keysFor(env), env.BILLING_AUTH_ISSUER)
() => verify(keysFor(env), issuerList(env.BILLING_AUTH_ISSUER))
]
const staging = stagingKeysFor(env)
if (staging) {
@@ -1,7 +1,19 @@
// URLs of the cloud setup pages on Orca Cloud auth (auth.onorca.dev/cloud/setup/...).
import type { Env } from './env'
/** Thrown when CLOUD_SETUP_PAGES_URL is unset in prod; the index answers 503 billing_misconfigured. */
export class SetupPagesConfigError extends Error {
constructor() {
super('cloud_setup_pages_url_missing')
this.name = 'SetupPagesConfigError'
}
}
function pagesOrigin(env: Env): string {
if (!env.CLOUD_SETUP_PAGES_URL && env.BILLING_ENV === 'prod') {
// Prod must name its pages origin; the fallback below is only a dev/staging convenience.
throw new SetupPagesConfigError()
}
return (env.CLOUD_SETUP_PAGES_URL ?? 'https://auth.onorca.dev').replace(/\/$/, '')
}
+1
View File
@@ -51,6 +51,7 @@ export type Env = {
// BILLING_JWKS (inline set) is for local dev and tests only.
BILLING_JWKS_URL?: string
BILLING_JWKS?: string
// Accepted `iss` values, comma-separated (a single issuer is a one-item list); so is the staging one.
BILLING_AUTH_ISSUER?: string
BILLING_JWT_AUDIENCE: string
// 'dev' | 'prod'. Dev may also accept BILLING_DEV_JWKS (issuer 'orca-billing-dev-test', a secret
+7 -1
View File
@@ -55,6 +55,7 @@ import { entitlementsView, offersFor, plansView } from './plans-api'
import { reconcile } from './reconcile'
import type { Env } from './env'
import { MACHINE_SIZES, PlanConfigError, planCatalog, publicOffers } from './plans'
import { SetupPagesConfigError } from './cloud-setup-urls'
import { OverageRequestSchema, updateOverage } from './overage'
import { LiveModeRefusedError, StripeError, createStripeClient, type StripeClient } from './stripe'
import { UsageReportSchema, flushMeterReports, recordUsage, validateSegment } from './usage'
@@ -566,7 +567,12 @@ export async function handleRequest(request: Request, env: Env, ctx: ExecutionCo
if (error instanceof SyntaxError) {
return json({ error: 'invalid_json' }, 400)
}
if (error instanceof LiveModeRefusedError || error instanceof PlanConfigError || error instanceof CatalogUnavailableError) {
if (
error instanceof LiveModeRefusedError ||
error instanceof PlanConfigError ||
error instanceof CatalogUnavailableError ||
error instanceof SetupPagesConfigError
) {
return json({ error: 'billing_misconfigured' }, 503)
}
if (error instanceof MembershipUnavailableError) {
@@ -0,0 +1,63 @@
import { SignJWT, exportJWK, generateKeyPair } from 'jose'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { authenticateDesktop, issuerList } from '../src/auth'
import { createHarness } from './harness'
const PROD = 'https://login.onorca.dev'
const NEXT = 'https://login.example.dev'
const NOW = Date.UTC(2026, 0, 15)
async function issuerHarness(issuers: string) {
const { privateKey, publicKey } = await generateKeyPair('ES256')
const jwk = { ...(await exportJWK(publicKey)), kid: 'iss1', alg: 'ES256', use: 'sig' }
const h = await createHarness({ BILLING_JWKS: JSON.stringify({ keys: [jwk] }), BILLING_AUTH_ISSUER: issuers })
const accepts = async (issuer: string): Promise<boolean> => {
const iat = Math.floor(NOW / 1000)
const token = await new SignJWT({ sub: 'user_iss', purpose: 'billing' })
.setProtectedHeader({ alg: 'ES256', kid: 'iss1' })
.setIssuer(issuer)
.setAudience('orca-billing')
.setIssuedAt(iat)
.setExpirationTime(iat + 300)
.sign(privateKey)
const request = new Request('https://billing.test/v1/billing/entitlements', { headers: { authorization: `Bearer ${token}` } })
return (await authenticateDesktop(h.env, request)) !== null
}
return { accepts }
}
describe('BILLING_AUTH_ISSUER list', () => {
// jose checks exp/iat against Date; pin it so no wall clock is involved.
beforeEach(() => {
vi.useFakeTimers({ toFake: ['Date'] })
vi.setSystemTime(NOW)
})
afterEach(() => {
vi.useRealTimers()
})
it('parses a comma list, ignoring whitespace and empty entries', () => {
expect(issuerList(undefined)).toBeUndefined()
expect(issuerList('')).toBeUndefined()
expect(issuerList(PROD)).toEqual([PROD])
expect(issuerList(` ${PROD} ,, ${NEXT} , `)).toEqual([PROD, NEXT])
})
it('a single issuer behaves as before', async () => {
const h = await issuerHarness(PROD)
expect(await h.accepts(PROD)).toBe(true)
expect(await h.accepts(NEXT)).toBe(false)
})
it('a list accepts each listed issuer and rejects others', async () => {
const h = await issuerHarness(` ${PROD} , ,${NEXT},`)
expect(await h.accepts(PROD)).toBe(true)
expect(await h.accepts(NEXT)).toBe(true)
expect(await h.accepts('https://login.evil.dev')).toBe(false)
})
it('a value with no entries accepts no issuer', async () => {
const h = await issuerHarness(' , ')
expect(await h.accepts(PROD)).toBe(false)
})
})
@@ -0,0 +1,41 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { SetupPagesConfigError, setupPageUrl } from '../src/cloud-setup-urls'
import { createHarness } from './harness'
const NOW = Date.UTC(2026, 0, 15)
describe('CLOUD_SETUP_PAGES_URL', () => {
// The harness and jose read Date; pin it so no wall clock is involved.
beforeEach(() => {
vi.useFakeTimers({ toFake: ['Date'] })
vi.setSystemTime(NOW)
})
afterEach(() => {
vi.useRealTimers()
})
it('falls back to the current auth origin outside prod when unset', async () => {
for (const BILLING_ENV of [undefined, 'dev', 'staging']) {
const { env } = await createHarness({ BILLING_ENV })
expect(setupPageUrl(env, '/start', { session: 's1' })).toBe('https://auth.onorca.dev/cloud/setup/start?session=s1')
}
})
it('uses the configured origin in every environment', async () => {
for (const BILLING_ENV of ['dev', 'prod']) {
const { env } = await createHarness({ BILLING_ENV, CLOUD_SETUP_PAGES_URL: 'https://pages.test/' })
expect(setupPageUrl(env, '/plan', { session: 's1' })).toBe('https://pages.test/cloud/setup/plan?session=s1')
}
})
it('is a configuration error in prod when unset, answered as billing_misconfigured', async () => {
const h = await createHarness({ BILLING_ENV: 'prod' })
expect(() => setupPageUrl(h.env, '/start', { session: 's1' })).toThrow(SetupPagesConfigError)
const token = await h.desktopToken({ sub: 'u1', email: 'neil@acme.dev' })
const created = await h.call('POST', '/v1/cloud-setup/sessions', {
body: { repo: 'https://github.com/acme/web', needs: ['plan'], device: 'MacBook Pro' },
headers: { authorization: `Bearer ${token}` }
})
expect(created).toEqual({ status: 503, body: { error: 'billing_misconfigured' } })
})
})
@@ -10,6 +10,7 @@
# the variable of that name) and ORCA_BUILD_WITHHELD_SECRETS (names it lists that builds never get).
# `::orca-step:: <name>` lines mark progress.
# Exit codes: 10 clone, 20 install script, 30 recording the result, 40 a secret's value left on disk.
# ORCA_AUTO_INSTALL=1 (automatic environments, no install script): install from the lockfile, never failing.
set -uo pipefail
umask 022
# One stream: the provider replays stdout and stderr separately after the fact, so a failed build's
@@ -92,6 +93,65 @@ scan_secrets() {
return 1
}
# PARITY-AUTO-ENV-DEPS: an automatic environment (ORCA_AUTO_INSTALL=1, no install script) installs the
# first repo's JavaScript dependencies from its lockfile, so new workspaces start with them (the deps
# step below carries node_modules into each worktree). Soft by design: a failure, a lockfile out of date
# or the time cap leaves the clone as it was (no half-installed node_modules) and the build goes on.
# Package managers the image doesn't have (bun, uv, bundler, go, cargo) are only named in the log.
# ORCA_AUTO_INSTALL_TIMEOUT: tests only.
auto_install() {
local dir="$1" pm="" declared="" rc=0 started f
local cmd=() others=()
for f in bun.lock bun.lockb uv.lock poetry.lock Pipfile.lock Gemfile.lock go.sum Cargo.lock; do
[ -f "$dir/$f" ] && others+=("$f")
done
if [ -f "$dir/package.json" ]; then
# package.json's packageManager ("pnpm@9.1.0") wins over the lockfile guess.
declared=$(sed -n 's/.*"packageManager"[[:space:]]*:[[:space:]]*"\([a-z]*\)@.*/\1/p' "$dir/package.json" | head -n 1)
case "$declared" in
pnpm | yarn | npm) pm="$declared" ;;
*)
if [ -f "$dir/pnpm-lock.yaml" ]; then pm=pnpm
elif [ -f "$dir/yarn.lock" ]; then pm=yarn
elif [ -f "$dir/package-lock.json" ] || [ -f "$dir/npm-shrinkwrap.json" ]; then pm=npm
fi
;;
esac
fi
if [ "${#others[@]}" -gt 0 ]; then
echo "Not installed automatically: ${others[*]}. Add an install script to the environment to install these."
fi
if [ -z "$pm" ]; then
[ "${#others[@]}" -gt 0 ] || echo "No lockfile found; the build keeps the cloned repos."
return 0
fi
# Through corepack, so pnpm and yarn come at the version the repo pins (Node ships corepack).
case "$pm" in
pnpm) cmd=(corepack pnpm install --frozen-lockfile) ;;
yarn)
if [ -f "$dir/.yarnrc.yml" ]; then cmd=(corepack yarn install --immutable)
else cmd=(corepack yarn install --frozen-lockfile)
fi
;;
npm) cmd=(npm ci) ;;
esac
echo "Installing dependencies automatically: ${cmd[*]}"
started=$(date +%s)
(cd "$dir" && COREPACK_ENABLE_DOWNLOAD_PROMPT=0 timeout "${ORCA_AUTO_INSTALL_TIMEOUT:-900}" "${cmd[@]}") </dev/null || rc=$?
if [ "$rc" -ne 0 ]; then
if [ "$rc" -eq 124 ]; then
echo "Automatic install skipped: ${cmd[*]} took longer than 15 minutes."
else
echo "Automatic install skipped: ${cmd[*]} exited with status $rc (often a lockfile out of date)."
fi
echo "New workspaces start from the cloned repo and run their own setup."
# A half-installed tree must never be linked into workspaces.
find "$dir" -name node_modules -type d -prune -exec rm -rf {} + 2>/dev/null || true
return 0
fi
echo "Installed dependencies in $(($(date +%s) - started))s."
}
take_secrets
step() { printf '\n::orca-step:: %s\n' "$1"; }
started=$(date +%s)
@@ -153,6 +213,8 @@ if [ -s "$OUT/install.sh" ]; then
echo "::orca-error:: The install script exited with status $rc."
exit 20
fi
elif [ "${ORCA_AUTO_INSTALL:-}" = 1 ] && [ -n "$first" ]; then
auto_install "$first"
else
echo "No install script; the build keeps the cloned repos."
fi
+1 -1
View File
@@ -31,7 +31,7 @@ ref="${ORCA_REPO_REF:-}"
first_commit() {
if ! git -C "$P" rev-parse --verify --quiet HEAD >/dev/null; then
git -C "$P" checkout --quiet -B "${ref:-main}" 2>/dev/null || true
git -C "$P" -c user.name='Orca' -c user.email='cloud@onorca.dev' \
git -C "$P" -c user.name='Orca' -c user.email='noreply@orca.dev' \
commit --quiet --allow-empty -m 'Initial commit' && echo 'Empty repository: created a first commit.'
fi
}
File diff suppressed because one or more lines are too long
+2 -2
View File
@@ -41,14 +41,14 @@ hold_for_member_setup() {
fi
exit 1
}
# A commit under the workspace identity (Orca Cloud's name) says once per session how to use your own
# A commit under the workspace identity (Orca <noreply@orca.dev>) says once per session how to use your own
# (design-squad). /dev/shm is per boot: a wake or restart says it again.
nudge_once() {
[ "$sub" = commit ] || return 0
local mark="${ORCA_GIT_NUDGE_DIR:-/dev/shm}/orca-git-nudge-$(id -u)"
[ -e "$mark" ] && return 0
: >"$mark" 2>/dev/null || return 0
printf '%s\n' "orca: This commit uses Orca Cloud's name. Connect your GitHub in Settings → Account to use yours." >&2
printf '%s\n' "orca: This commit is authored as Orca <noreply@orca.dev>. Connect GitHub in Settings → Account to commit as yourself." >&2
}
# PUSH-RAW-PROMPT: a push, pull or fetch to github.com that no credential covers (neither the person's
# connected GitHub nor the App installation) must never fall through to git's own "Username for
@@ -54,9 +54,9 @@ user_home="$(getent passwd "$USER_NAME" | cut -d: -f6)"
# Commits outside a teammate's turn still need an author (images older than orca-sandbox-start's default).
if [ -n "$user_home" ]; then
sudo -u "$USER_NAME" env HOME="$user_home" git config --global user.email >/dev/null 2>&1 \
|| sudo -u "$USER_NAME" env HOME="$user_home" git config --global user.email 'cloud@users.noreply.orca.dev'
|| sudo -u "$USER_NAME" env HOME="$user_home" git config --global user.email 'noreply@orca.dev'
sudo -u "$USER_NAME" env HOME="$user_home" git config --global user.name >/dev/null 2>&1 \
|| sudo -u "$USER_NAME" env HOME="$user_home" git config --global user.name 'Orca Cloud'
|| sudo -u "$USER_NAME" env HOME="$user_home" git config --global user.name 'Orca'
fi
# CREATE-GIT-ASYNC: identities are in place, so `git` stops holding commits and pushes for this boot.
if [ -n "$user_home" ] && [ -d "$user_home/.orca-sandbox" ]; then
@@ -119,11 +119,16 @@ if [ -n "${ORCA_GIT_EXTRAHEADER:-}" ]; then
git config --global http.https://github.com/.extraheader "$ORCA_GIT_EXTRAHEADER"
fi
# Commits outside a teammate's turn (or before any member connected GitHub) need an author too.
# The fallback moved to orca.dev with the domain; a workspace still on the old default follows it.
[ "$(git config --global user.email 2>/dev/null || true)" = 'cloud@users.noreply.onorca.dev' ] \
&& git config --global user.email 'cloud@users.noreply.orca.dev'
git config --global user.email >/dev/null 2>&1 || git config --global user.email 'cloud@users.noreply.orca.dev'
git config --global user.name >/dev/null 2>&1 || git config --global user.name 'Orca Cloud'
# The fallback is noreply@orca.dev (DOMAIN-1); a workspace still on an earlier default follows it.
case "$(git config --global user.email 2>/dev/null || true)" in
cloud@users.noreply.onorca.dev | cloud@users.noreply.orca.dev)
git config --global user.email 'noreply@orca.dev' ;;
esac
git config --global user.email >/dev/null 2>&1 || git config --global user.email 'noreply@orca.dev'
# The fallback name is "Orca" (DOMAIN-1); a workspace still on the earlier default follows it.
[ "$(git config --global user.name 2>/dev/null || true)" = 'Orca Cloud' ] \
&& git config --global user.name 'Orca'
git config --global user.name >/dev/null 2>&1 || git config --global user.name 'Orca'
# First boot clones while orcad starts (orcad only needs the directory to exist); ready waits for both.
clone_pid=''
if [ ! -d "$PROJECT" ]; then
@@ -0,0 +1,12 @@
-- PARITY-FOLLOW: a member follows a teammate's workspace to keep it in their sidebar's Following
-- section; everyone who can see the workspace sees its followers. One row per member per
-- workspace. Rows go with the workspace (destroy) and with the member (removal); a follower who can
-- no longer see the workspace (it turned private) is left out of every read.
CREATE TABLE IF NOT EXISTS workspace_follows (
sandbox_id TEXT NOT NULL,
user_id TEXT NOT NULL,
account_id TEXT NOT NULL,
created_at INTEGER NOT NULL,
PRIMARY KEY (sandbox_id, user_id)
);
CREATE INDEX IF NOT EXISTS workspace_follows_member ON workspace_follows (account_id, user_id);
@@ -0,0 +1,5 @@
-- RS-2: a failed auth check (count_tokens) alone no longer revokes an Orca-account sign-in. It marks the
-- sign-in "needs check" (suspect_at); the credential stays usable at egress so the next real agent request
-- can confirm it: a later 401 revokes, a success clears it. Never tested against a real OAuth token, so the
-- probe is a signal, not a verdict (agent-credential-checks.ts).
ALTER TABLE agent_credentials ADD COLUMN suspect_at INTEGER;
@@ -1,12 +1,20 @@
// A provider 401 on an Orca-account request (the proxy swapped the real credential in) is a signal, not a
// verdict: one transient auth error must not sign a person out of every workspace. Before revoking, the
// control plane makes one cheap server-side auth check with the real credential (no tokens spent) and
// revokes only when that also says the credential is dead. The desktop can ask for the same check before a
// verdict: one transient auth error must not sign a person out of every workspace. The control plane makes
// one cheap server-side auth check with the real credential (no tokens spent). RS-2: that check alone never
// revokes either (it has never been tried against a real OAuth sign-in): a failed check marks the sign-in
// "needs check" (suspect), which stays usable at egress; a LATER real agent request that also gets a 401
// revokes it, and a real request that succeeds (or a passing check) clears it. The desktop can ask for the same check before a
// launch (POST /v1/agent-credentials/claude/verify). Checks are rate-limited per person and agent
// (agent_credentials.checked_at), passes are remembered (verified_at), and every keep or revoke is audited
// (agent_credential_audit).
import type { AccountProvider } from './account-providers'
import { markAgentCredentialRevoked, readUsableAgentCredential } from './agent-credentials'
import {
agentCredentialSuspectAt,
clearAgentCredentialSuspect,
markAgentCredentialRevoked,
markAgentCredentialSuspect,
readUsableAgentCredential
} from './agent-credentials'
import type { Keyring } from './secrets-crypto'
/** At most one auth check (and so one revoke) per person and agent per minute. */
@@ -15,7 +23,7 @@ export const CREDENTIAL_CHECK_INTERVAL_MS = 60_000
export const CREDENTIAL_VERIFIED_FRESH_MS = 10 * 60_000
export type CredentialVerdict = 'valid' | 'invalid' | 'unknown'
export type CheckOutcome = 'revoked' | 'kept' | 'skipped'
export type CheckOutcome = 'revoked' | 'suspect' | 'kept' | 'skipped'
type CheckContext = {
db: D1Database
@@ -28,7 +36,7 @@ type CheckContext = {
async function audit(
db: D1Database,
entry: { userId: string; agent: string; action: 'revoked' | 'kept'; reason: string; sandboxId: string | null; path: string | null; now: number }
entry: { userId: string; agent: string; action: 'revoked' | 'suspect' | 'kept'; reason: string; sandboxId: string | null; path: string | null; now: number }
): Promise<void> {
await db
.prepare(
@@ -74,6 +82,8 @@ async function checkCredential(
const base = { userId, agent, now, ...where }
if (verdict === 'valid') {
await db.prepare(`UPDATE agent_credentials SET verified_at = ? WHERE user_id = ? AND agent = ?`).bind(now, userId, agent).run()
// A passing check clears "needs check".
await clearAgentCredentialSuspect(db, userId, agent, now)
}
if (verdict !== 'invalid') {
// A pass on a pre-launch verify is routine; a 401 that didn't hold up, or any inconclusive check, is audited.
@@ -83,21 +93,67 @@ async function checkCredential(
}
return 'kept'
}
await markAgentCredentialRevoked(db, userId, agent, now)
// RS-2: the check's auth failure alone never revokes: the sign-in needs a real request to confirm it.
await markAgentCredentialSuspect(db, userId, agent, now)
await audit(db, {
...base,
action: 'revoked',
reason: trigger.kind === 'verify' ? 'verify_confirmed_auth_failure' : 'provider_401_confirmed_by_check'
action: 'suspect',
reason: trigger.kind === 'verify' ? 'verify_check_auth_failure' : 'provider_401_check_auth_failure'
})
return 'revoked'
return 'suspect'
}
export function handleAccountUnauthorized(
/**
* A real agent request got a 401 with the real credential swapped in. A sign-in already in question (a
* check failed after an EARLIER 401) is now confirmed dead: revoked. Otherwise one rate-limited check, which
* at most puts it in question.
*/
export async function handleAccountUnauthorized(
ctx: CheckContext & { sandboxId: string; path: string }
): Promise<CheckOutcome> {
// The 401 that triggered the failed check was consumed by that check, so any 401 seen here, with the
// sign-in already in question, is a different, later real request.
const suspectAt = await agentCredentialSuspectAt(ctx.db, ctx.userId, ctx.provider.agent)
if (suspectAt !== null) {
await markAgentCredentialRevoked(ctx.db, ctx.userId, ctx.provider.agent, ctx.now)
await audit(ctx.db, {
userId: ctx.userId,
agent: ctx.provider.agent,
action: 'revoked',
reason: 'provider_401_after_check_failure',
sandboxId: ctx.sandboxId,
path: ctx.path,
now: ctx.now
})
return 'revoked'
}
return checkCredential(ctx, { kind: 'egress_401', sandboxId: ctx.sandboxId, path: ctx.path })
}
/** RS-2: a real agent request with the real credential succeeded: a sign-in in question is fine after all. */
export async function handleAccountRequestSucceeded(ctx: {
db: D1Database
agent: AccountProvider['agent']
userId: string
sandboxId: string
path: string
now: number
}): Promise<boolean> {
const cleared = await clearAgentCredentialSuspect(ctx.db, ctx.userId, ctx.agent, ctx.now)
if (cleared) {
await audit(ctx.db, {
userId: ctx.userId,
agent: ctx.agent,
action: 'kept',
reason: 'request_succeeded_after_check_failure',
sandboxId: ctx.sandboxId,
path: ctx.path,
now: ctx.now
})
}
return cleared
}
/**
* Pre-launch verify: a pass within CREDENTIAL_VERIFIED_FRESH_MS answers at once; otherwise one check (rate
* limited). Returns what happened; the caller re-reads the state.
@@ -12,7 +12,11 @@ import type { SandboxCaller } from './auth'
import type { Env } from './env'
import type { Keyring, SecretBinding } from './secrets-crypto'
export type CredentialState = 'none' | 'active' | 'expiring' | 'expired' | 'revoked'
/**
* 'suspect' (RS-2): an auth check failed but no real request has confirmed it yet. Still usable at egress;
* shown to the desktop as expired + needsCheck (an older desktop reads a new state as 'none').
*/
export type CredentialState = 'none' | 'active' | 'expiring' | 'expired' | 'revoked' | 'suspect'
const EXPIRING_MS = 30 * 24 * 60 * 60_000
/** `claude setup-token` issues a one-year token. */
const CLAUDE_SETUP_TOKEN_TTL_MS = 365 * 24 * 60 * 60_000
@@ -27,6 +31,8 @@ type CredentialRow = {
label: string | null
expires_at: number | null
state: 'active' | 'revoked'
/** RS-2: when an auth check said this sign-in is dead; null when not in question. */
suspect_at?: number | null
updated_at: number
}
@@ -73,15 +79,18 @@ export function credentialState(row: Pick<CredentialRow, 'state' | 'expires_at'>
if (row.expires_at !== null && row.expires_at <= now) {
return 'expired'
}
if (row.suspect_at !== null && row.suspect_at !== undefined) {
return 'suspect'
}
if (row.expires_at !== null && row.expires_at - now <= EXPIRING_MS) {
return 'expiring'
}
return 'active'
}
/** Usable for a request now: active or expiring (still valid). */
/** Usable for a request now: active or expiring (still valid), or suspect (a real request must confirm it). */
export function isUsable(state: CredentialState): boolean {
return state === 'active' || state === 'expiring'
return state === 'active' || state === 'expiring' || state === 'suspect'
}
async function rowFor(db: D1Database, userId: string, agent: CredentialAgent): Promise<CredentialRow | null> {
@@ -106,7 +115,7 @@ export async function putAgentCredential(
ON CONFLICT (user_id, agent) DO UPDATE SET account_id = excluded.account_id, kek_id = excluded.kek_id,
wrapped_dek = excluded.wrapped_dek, ciphertext = excluded.ciphertext, label = excluded.label,
expires_at = excluded.expires_at, state = 'active', updated_at = excluded.updated_at,
checked_at = NULL, verified_at = NULL`
checked_at = NULL, verified_at = NULL, suspect_at = NULL`
)
.bind(input.userId, input.accountId, input.agent, sealed.kekId, sealed.wrappedDek, sealed.ciphertext, input.label ?? null, input.expiresAt ?? null, now, now)
.run()
@@ -114,21 +123,61 @@ export async function putAgentCredential(
/** The real value for egress, or null when there is none or it can't be used now. */
export async function readUsableAgentCredential(db: D1Database, keyring: Keyring, userId: string, agent: CredentialAgent, now: number): Promise<string | null> {
return (await readUsableAgentCredentialState(db, keyring, userId, agent, now)).value
}
/** The real value for egress, and whether the sign-in is in question (RS-2: a real request confirms it). */
export async function readUsableAgentCredentialState(
db: D1Database,
keyring: Keyring,
userId: string,
agent: CredentialAgent,
now: number
): Promise<{ value: string | null; suspect: boolean }> {
const row = await rowFor(db, userId, agent)
if (!isUsable(credentialState(row, now)) || !row) {
return null
const state = credentialState(row, now)
if (!isUsable(state) || !row) {
return { value: null, suspect: false }
}
try {
return await keyring.open(credentialBinding(userId, agent), { kekId: row.kek_id, wrappedDek: row.wrapped_dek, ciphertext: row.ciphertext })
const value = await keyring.open(credentialBinding(userId, agent), { kekId: row.kek_id, wrappedDek: row.wrapped_dek, ciphertext: row.ciphertext })
return { value, suspect: state === 'suspect' }
} catch {
console.log(JSON.stringify({ event: 'agent_credential_unreadable', agent }))
return null
return { value: null, suspect: false }
}
}
/** RS-2: an auth check failed. Not revoked: a real request must confirm it first. True when newly marked. */
export async function markAgentCredentialSuspect(db: D1Database, userId: string, agent: CredentialAgent, now: number): Promise<boolean> {
const result = await db
.prepare(`UPDATE agent_credentials SET suspect_at = ?, updated_at = ? WHERE user_id = ? AND agent = ? AND state = 'active' AND suspect_at IS NULL`)
.bind(now, now, userId, agent)
.run()
return result.meta.changes === 1
}
/** RS-2: a real request (or an auth check) succeeded: the sign-in is fine. True when it was in question. */
export async function clearAgentCredentialSuspect(db: D1Database, userId: string, agent: CredentialAgent, now: number): Promise<boolean> {
const result = await db
.prepare(`UPDATE agent_credentials SET suspect_at = NULL, updated_at = ? WHERE user_id = ? AND agent = ? AND suspect_at IS NOT NULL`)
.bind(now, userId, agent)
.run()
return result.meta.changes === 1
}
/** RS-2: when this sign-in was put in question, or null. */
export async function agentCredentialSuspectAt(db: D1Database, userId: string, agent: CredentialAgent): Promise<number | null> {
const row = await db
.prepare(`SELECT suspect_at FROM agent_credentials WHERE user_id = ? AND agent = ? AND state = 'active'`)
.bind(userId, agent)
.first<{ suspect_at: number | null }>()
return row?.suspect_at ?? null
}
/** The provider said the credential is no longer valid (401 at egress): stop using it until renewed. */
export async function markAgentCredentialRevoked(db: D1Database, userId: string, agent: CredentialAgent, now: number): Promise<void> {
await db.prepare(`UPDATE agent_credentials SET state = 'revoked', updated_at = ? WHERE user_id = ? AND agent = ?`).bind(now, userId, agent).run()
await db.prepare(`UPDATE agent_credentials SET state = 'revoked', suspect_at = NULL, updated_at = ? WHERE user_id = ? AND agent = ?`).bind(now, userId, agent).run()
}
export async function deleteAgentCredential(db: D1Database, userId: string, agent: CredentialAgent): Promise<boolean> {
@@ -141,11 +190,19 @@ export async function agentCredentialsView(db: D1Database, env: Env, userId: str
const view = (agent: CredentialAgent) => {
const row = results.find((r) => r.agent === agent) ?? null
const state = credentialState(row, now)
return { state, ...(row?.label ? { label: row.label } : {}), ...(row?.expires_at ? { expiresAt: row.expires_at } : {}) }
// RS-2: "needs check" reads as expired (the Renew strip) on every desktop, old ones included; newer
// desktops may read needsCheck. An unknown state would read as 'none' ("isn't set up") on old ones.
const wire = state === 'suspect' ? { state: 'expired' as const, needsCheck: true } : { state }
// RS-5: credentials saved before the fix carry an email or the Orca name; Claude's always reads true.
const label = agent === 'claude' && row ? CLAUDE_CREDENTIAL_LABEL : row?.label
return { ...wire, ...(label ? { label } : {}), ...(row?.expires_at ? { expiresAt: row.expires_at } : {}) }
}
return { claude: view('claude'), codex: view('codex'), providerEnabled: providerEnabled(env), providerState: providerStates(env) }
}
/** RS-5: what a stored Claude credential is called (the approved account itself can't be known). */
export const CLAUDE_CREDENTIAL_LABEL = 'Claude subscription'
// A Claude setup-token: `sk-ant-oat01-` then URL-safe characters. Shape-checked, never logged.
const CLAUDE_TOKEN = /^sk-ant-oat01-[A-Za-z0-9_-]{20,500}$/
export const PutClaudeSchema = z
@@ -173,7 +230,10 @@ export async function putClaudeCredential(db: D1Database, keyring: Keyring, env:
accountId: caller.accountId,
agent: 'claude',
value: token,
label: body.label?.trim() || caller.name || null,
// RS-5 (design-squad): a true label only. Neither this computer's Claude Code email nor the Orca
// name says which account approved the setup-token (it prints no email, and its inference-only
// scope can't read the profile), so a Claude credential is always "Claude subscription".
label: CLAUDE_CREDENTIAL_LABEL,
expiresAt: Math.min(body.expiresAt ?? now + CLAUDE_SETUP_TOKEN_TTL_MS, now + CLAUDE_SETUP_TOKEN_TTL_MS)
},
now
@@ -23,7 +23,7 @@ if [ ! -x "$O" ]; then echo '{"ok":false,"error":{"code":"orca_cli_missing"}}';
cd "$P" 2>/dev/null || cd "$HOME"
if [ "$1" = "--prepare" ]; then
shift
[ -d "$P/.git" ] || { git -C "$P" init -q && git -C "$P" -c user.name=Orca -c user.email=cloud@onorca.dev commit -q --allow-empty -m init; } >/dev/null 2>&1 || true
[ -d "$P/.git" ] || { git -C "$P" init -q && git -C "$P" -c user.name=Orca -c user.email=noreply@orca.dev commit -q --allow-empty -m init; } >/dev/null 2>&1 || true
"$O" repo add --path "$P" --json >/dev/null 2>&1 || true
C="$HOME/.claude.json"
if command -v jq >/dev/null 2>&1; then
+16 -4
View File
@@ -97,10 +97,22 @@ export function accountIdFor(claims: { sub: string; org?: string }): string {
return claims.org ? `org:${claims.org}` : `user:${claims.sub}`
}
/**
* A comma-separated issuer var as jwtVerify's `issuer` option: the token's `iss` must equal one entry.
* Unset or empty: no issuer check (as before lists). Blank entries are ignored; a value with no
* entries left accepts no issuer.
*/
export function issuerList(value: string | undefined): string[] | undefined {
if (!value) {
return undefined
}
return value.split(',').map((issuer) => issuer.trim()).filter(Boolean)
}
let stagingKeys: { source: string; keys: JWTVerifyGetKey } | null = null
/** Staging auth's keys and issuer; never honored in prod. Same accounts as billing dev (it trusts staging too). */
function stagingKeysFor(env: Env): { keys: JWTVerifyGetKey; issuer: string } | null {
function stagingKeysFor(env: Env): { keys: JWTVerifyGetKey; issuer: string[] | undefined } | null {
const source = env.SANDBOX_STAGING_JWKS_URL ?? (env.SANDBOX_STAGING_JWKS ? `inline:${env.SANDBOX_STAGING_JWKS}` : null)
if (env.SANDBOX_ENV === 'prod' || !source || !env.SANDBOX_STAGING_AUTH_ISSUER) {
return null
@@ -113,7 +125,7 @@ function stagingKeysFor(env: Env): { keys: JWTVerifyGetKey; issuer: string } | n
: createLocalJWKSet(JSON.parse(env.SANDBOX_STAGING_JWKS ?? '{"keys":[]}') as JSONWebKeySet)
}
}
return { keys: stagingKeys.keys, issuer: env.SANDBOX_STAGING_AUTH_ISSUER }
return { keys: stagingKeys.keys, issuer: issuerList(env.SANDBOX_STAGING_AUTH_ISSUER) }
}
/** Dev-only operator keys (issuer DEV_TEST_ISSUER) so live tests run before Orca auth mints sandbox tokens. */
@@ -124,7 +136,7 @@ async function verify(
token: string,
keys: JWTVerifyGetKey,
env: Env,
issuer: string | undefined,
issuer: string | string[] | undefined,
now: number
): Promise<SandboxCaller | null> {
try {
@@ -163,7 +175,7 @@ export async function authenticateDesktop(
}
const staging = stagingKeysFor(env)
const caller =
(await verify(token, keysFor(env), env, env.SANDBOX_AUTH_ISSUER, now)) ??
(await verify(token, keysFor(env), env, issuerList(env.SANDBOX_AUTH_ISSUER), now)) ??
(staging ? await verify(token, staging.keys, env, staging.issuer, now) : null)
if (caller || !env.SANDBOX_DEV_JWKS || env.SANDBOX_ENV === 'prod') {
if (!caller || (await tokenPredatesRemoval(env.SANDBOX_DB, caller))) {
@@ -1,8 +1,8 @@
// Automatic environments: Conductor-style "the repo is already there". An environment build (golden +
// the repo checked out, snapshotted) is opt-in for admins; without one every create of a repo cloned it
// from scratch (stablyai/orca: ~55 s). So the first create of a repo that no environment of the account
// lists makes a default environment for it (just the repo, blobless, no install script) and builds it in
// the background. Later creates boot from its active build (environments.ts resolveEnvironmentBoot) and
// lists makes a default environment for it (the repo, blobless, plus its lockfile's JavaScript
// dependencies; no install script) and builds it in the background. Later creates boot from its active build (environments.ts resolveEnvironmentBoot) and
// only fetch what changed. Scoped per account like every environment; the usual golden refresh keeps
// it on the current image. Unused for 14 days it is deleted with its snapshots, unless an admin edited
// it (that makes it an ordinary 'org' environment).
@@ -38,7 +38,9 @@ function autoConfig(environment: EnvironmentRow): BuildConfig {
envVarNames: [],
machineSize: environment.machine_size,
// History and trees only: a smaller snapshot and a faster build; file contents load on demand.
cloneFilter: 'blob:none'
cloneFilter: 'blob:none',
// Dependencies from the lockfile, so creates start warm (PARITY-AUTO-ENV-DEPS); soft on failure.
autoInstall: true
}
}
@@ -174,6 +174,18 @@ export const codexAccount: AccountProvider = {
log('codex_token_unauthorized', { userId })
waitUntil(refreshCodexCredential({ db, keyring, now: () => now }, userId))
},
// RS-4: a request still carrying this sandbox's placeholder once the account no longer applies gets a
// message saying what to do, not a bare proxy 403. Still a 403, never a 401: on a 401 from chatgpt.com
// Codex runs its own token refresh (against auth.openai.com, with a placeholder refresh token) and
// retries, so a 401 would only cost refresh attempts. On any other status Codex prints
// `unexpected status <code>: <body>`, so the body is the message, in ChatGPT's own error shape.
signedOut: {
status: 403,
contentType: 'application/json',
body: JSON.stringify({
detail: 'Orca Cloud can’t use your ChatGPT sign-in here. Check it in Orca: Settings → Agent accounts.'
})
},
credential: async (db, keyring, userId, now) => {
const value = await readUsableAgentCredential(db, keyring, userId, 'codex', now)
const tokens = value ? parseStoredCodex(value) : null
+3
View File
@@ -46,6 +46,7 @@ export type Env = {
// SANDBOX_JWKS (inline set) is for local dev and tests only.
SANDBOX_JWKS_URL?: string
SANDBOX_JWKS?: string
/** Accepted `iss` values, comma-separated (a single issuer is a one-item list). */
SANDBOX_AUTH_ISSUER?: string
SANDBOX_JWT_AUDIENCE: string
/** Dev-only operator key set (issuer `orca-sandbox-dev-test`); ignored when SANDBOX_ENV=prod. */
@@ -194,6 +195,8 @@ export type Env = {
PUBLIC_API_URL?: string
/** Comma list of extra egress hosts every VM may reach (dev: this Worker's workers.dev host). */
EGRESS_EXTRA_HOSTS?: string
/** Comma list of Orca platform egress hosts every VM may reach (default `*.onorca.dev`). */
ORCA_PLATFORM_HOST_SUFFIXES?: string
/** Workspace sandbox egress preset: `open` (default, any host) or `limited` (fail-closed allowlist). */
SANDBOX_EGRESS_PRESET?: string
/** GitHub App webhook secret (secret): verifies X-Hub-Signature-256 on /v1/github/webhook. */
@@ -94,6 +94,11 @@ export type BuildConfig = {
machineSize: MachineSize
/** `git clone --filter`: automatic environments clone blobless (auto-environments.ts). */
cloneFilter?: 'blob:none'
/**
* Automatic environments only, with no install script: install the first repo's JavaScript
* dependencies from its lockfile, never failing the build (environment-build.sh auto_install).
*/
autoInstall?: boolean
}
export type BuildResult = {
@@ -101,6 +106,35 @@ export type BuildResult = {
repos?: { url: string; dir: string; branch: string; commit: string; lockfiles: Record<string, string> }[]
diskUsedBytes?: number
diskTotalBytes?: number
/** AUTO-ENV-DEPS-LABEL: what an automatic environment's lockfile install did (read from its log). */
autoInstall?: AutoInstallOutcome
}
export type AutoInstallOutcome = { manager: 'pnpm' | 'yarn' | 'npm'; outcome: 'installed' | 'skipped' }
/**
* The automatic install's result, from environment-build.sh's own lines in the stored log (JSON lines
* of `{ data, stream }`): "Installing dependencies automatically: <cmd>", then "Installed dependencies
* in Ns." or "Automatic install skipped: …". Null when the build ran no automatic install.
*/
export function autoInstallFromLog(stored: string): AutoInstallOutcome | null {
let text = ''
for (const line of stored.split('\n')) {
try {
const parsed = JSON.parse(line) as { data?: unknown }
if (typeof parsed.data === 'string') {
text += parsed.data
}
} catch {
// A cut marker or a partial line: nothing to read.
}
}
const started = /^Installing dependencies automatically: (?:corepack )?(pnpm|yarn|npm)\b/m.exec(text)
if (!started) {
return null
}
const manager = started[1] as AutoInstallOutcome['manager']
return { manager, outcome: /^Installed dependencies in \d+s\.$/m.test(text) ? 'installed' : 'skipped' }
}
export type BuildDeps = {
@@ -368,7 +402,9 @@ async function bootBuild(deps: BuildDeps, row: BuildRow, config: BuildConfig): P
ORCA_INSTALL_SCRIPT_B64: base64(config.installScript),
ORCA_LOCKFILES: LOCKFILES.join(' '),
ORCA_DEPS_HOOK_B64: base64(ENVIRONMENT_DEPS_HOOK),
...(config.cloneFilter ? { ORCA_CLONE_FILTER: config.cloneFilter } : {})
...(config.cloneFilter ? { ORCA_CLONE_FILTER: config.cloneFilter } : {}),
// An admin's own install script always wins: auto_install runs only without one.
...(config.autoInstall && !config.installScript.trim() ? { ORCA_AUTO_INSTALL: '1' } : {})
}
// Counts only.
log('environment_build_secrets', {
@@ -459,7 +495,10 @@ const EXIT_STEPS: Record<number, { step: string; error: string }> = {
}
async function finalize(deps: BuildDeps, row: BuildRow, exitCode: number): Promise<BuildRow> {
await storeLogs(deps, row).catch((error: unknown) => log('environment_build_log_store_failed', { buildId: row.id, error: String(error).slice(0, 200) }))
const stored = await storeLogs(deps, row).catch((error: unknown) => {
log('environment_build_log_store_failed', { buildId: row.id, error: String(error).slice(0, 200) })
return ''
})
if (exitCode !== 0) {
const mapped = EXIT_STEPS[exitCode] ?? { step: 'install', error: `exit_${exitCode}` }
return (await failBuild(deps, row, mapped.step, mapped.error)) ?? row
@@ -475,8 +514,11 @@ async function finalize(deps: BuildDeps, row: BuildRow, exitCode: number): Promi
if (check.exitCode !== 0) {
return (await failBuild(deps, row, 'record', 'runtime_removed')) ?? row
}
const result = check.stdout.trim().split('\n').at(-1) ?? '{}'
JSON.parse(result)
const recordedResult = check.stdout.trim().split('\n').at(-1) ?? '{}'
const parsedResult = JSON.parse(recordedResult) as BuildResult
// The image's result.json predates the automatic install; the Worker reads that from the log.
const autoInstall = autoInstallFromLog(stored)
const result = autoInstall ? JSON.stringify({ ...parsedResult, autoInstall }) : recordedResult
// Recorded before the snapshot: if this Worker is cut off mid-snapshot, the next look adopts the
// snapshot by the build box's name (recoverInterrupted) with the result already in place.
const recorded = await transition(deps.db, row, { result }, deps.now())
@@ -676,9 +718,10 @@ export async function cancelBuild(deps: BuildDeps, caller: SandboxCaller, row: B
}
/** Copies the full provider log (bounded: head + tail) into D1 once the build is over. */
async function storeLogs(deps: BuildDeps, row: BuildRow, options: { live?: boolean } = {}): Promise<void> {
/** Stores the build's log (redacted, capped) and returns what it stored. */
async function storeLogs(deps: BuildDeps, row: BuildRow, options: { live?: boolean } = {}): Promise<string> {
if (!row.session_id || !row.command_id) {
return
return ''
}
// A still-running command (cancel, timeout) never ends its stream: keep what arrives in a few seconds.
const raw = await readUntil(
@@ -714,6 +757,7 @@ async function storeLogs(deps: BuildDeps, row: BuildRow, options: { live?: boole
deps.db.prepare('UPDATE environment_builds SET log_bytes = ?, log_truncated = ? WHERE id = ?').bind(text.length, truncated, row.id)
)
await deps.db.batch(statements)
return stored
}
/** Reads a stream until it ends or `ms` pass, whichever is first; what arrived is returned. */
@@ -77,6 +77,7 @@ export function buildView(row: BuildRow, activeBuildId: string | null) {
}),
diskUsedBytes: result?.diskUsedBytes ?? null,
diskTotalBytes: result?.diskTotalBytes ?? null,
autoInstall: result?.autoInstall ?? null,
logBytes: row.log_bytes,
logTruncated: row.log_truncated === 1
}
+57 -8
View File
@@ -59,6 +59,7 @@ import { provisionWorkspaceToken } from './api/settings'
import { docsPage, openApiDocument } from './api/openapi'
import { handleDeviceSessionsRoute } from './device-sessions'
import { removeMember } from './member-removal'
import { setFollow } from './workspace-follows'
import { createRoutinesApi } from './routines/api'
import { handleRoutineHook, isRoutineHookPath } from './routines/hooks'
import { tickRoutines } from './routines/runs'
@@ -123,7 +124,7 @@ import { SecretError, handleSecretsRoute, keyringFor, type SecretChange } from '
import { SecretsKmsError } from './secrets-kms'
import { refreshAfterSecretChange, refreshSandboxEnv } from './env-refresh'
import { ACCOUNT_PROVIDERS, accountProvider, isSharedWorkspace } from './account-providers'
import { handleAccountUnauthorized, verifyAccountCredential } from './agent-credential-checks'
import { handleAccountRequestSucceeded, handleAccountUnauthorized, verifyAccountCredential } from './agent-credential-checks'
import { codexBrokerTick, handleCodexBrokerRoute, type BrokerDeps } from './codex-broker'
import { refreshCodexLeases } from './codex-credentials'
import {
@@ -133,7 +134,7 @@ import {
deleteAgentCredential,
providerEnabled,
putClaudeCredential,
readUsableAgentCredential
readUsableAgentCredentialState
} from './agent-credentials'
import {
AgentSourceError,
@@ -201,6 +202,7 @@ import {
userAuthorizeUrl
} from './github-user-tokens'
import { MEMBER_GIT_WINDOW_MS, memberGitRoutes, memberSentWithin, recordMemberSend } from './member-git'
import { egressAllowlistFor } from './network-policy'
import { getWorkspacePrefs, putWorkspacePrefs } from './workspace-prefs'
import { getOrgSlug, putOrgSlug } from './org-slugs'
import {
@@ -210,6 +212,7 @@ import {
WORKSPACE_ERROR_STATUS,
WorkspaceError,
canOpen,
canSee,
isOrgAdmin,
listWorkspaces,
patchWorkspace,
@@ -396,6 +399,8 @@ function egressRoutes(env: Env, deps: Deps): (row: SandboxRow, host: string) =>
return []
}
let real: string | null = null
// RS-2: this sign-in is in question (a check failed); a real request here confirms or clears it.
let suspect = false
return [
{
header: provider.header,
@@ -420,7 +425,9 @@ function egressRoutes(env: Env, deps: Deps): (row: SandboxRow, host: string) =>
scheduleEnvRefresh(env, deps, row)
return signedOut('account_disabled')
}
real = await cachedAccountCredential(env.SANDBOX_DB, await keyring, row.user_id, agent, now)
const account = await cachedAccountCredential(env.SANDBOX_DB, await keyring, row.user_id, agent, now)
real = account.value
suspect = account.suspect
if (!real) {
scheduleEnvRefresh(env, deps, row)
return signedOut('no_agent_credential')
@@ -431,6 +438,25 @@ function egressRoutes(env: Env, deps: Deps): (row: SandboxRow, host: string) =>
// Reached only after the real credential was swapped in and sent (denied or unswapped requests
// never get here).
onUpstreamStatus: (status, request) => {
// RS-2: a real request the provider accepted (not a 401, not a server failure) clears "needs
// check". Only while it's in question, so a healthy account costs no writes.
if (suspect && !provider.onUnauthorized && status !== 401 && status < 500) {
suspect = false
const now = (deps.now ?? Date.now)()
const work = handleAccountRequestSucceeded({
db: env.SANDBOX_DB,
agent,
userId: row.user_id,
sandboxId: row.id,
path: request.path,
now
}).then((cleared) => (cleared ? forgetAccountCredential(row.user_id, agent) : undefined))
if (deps.waitUntil) {
deps.waitUntil(work.catch(() => undefined))
} else {
void work.catch(() => undefined)
}
}
if (status === 401) {
const now = (deps.now ?? Date.now)()
const waitUntil = (work: Promise<unknown>) => (deps.waitUntil ? deps.waitUntil(work.catch(() => undefined)) : void work.catch(() => undefined))
@@ -451,7 +477,13 @@ function egressRoutes(env: Env, deps: Deps): (row: SandboxRow, host: string) =>
fetch: deps.egressFetch ?? fetch
})
)
.then((outcome) => outcome === 'revoked')
.then((outcome) => {
// In question, not revoked: still usable; the next lookup reads the new state.
if (outcome === 'suspect') {
forgetAccountCredential(row.user_id, agent)
}
return outcome === 'revoked'
})
// Every running sandbox of this person drops the dead placeholder, not only this one.
const work = handled.then(async (changed) => {
if (!changed) {
@@ -508,14 +540,20 @@ function egressRoutes(env: Env, deps: Deps): (row: SandboxRow, host: string) =>
// Account credentials per person, decrypted at most once a minute per isolate; an edit or delete drops it.
const ACCOUNT_CACHE_MS = 10_000
const accountCache = new Map<string, { at: number; value: Promise<string | null> }>()
function cachedAccountCredential(db: D1Database, keyring: Keyring, userId: string, agent: 'claude' | 'codex', now: number): Promise<string | null> {
const accountCache = new Map<string, { at: number; value: Promise<{ value: string | null; suspect: boolean }> }>()
function cachedAccountCredential(
db: D1Database,
keyring: Keyring,
userId: string,
agent: 'claude' | 'codex',
now: number
): Promise<{ value: string | null; suspect: boolean }> {
const key = `${userId}:${agent}`
const hit = accountCache.get(key)
if (hit && now - hit.at < ACCOUNT_CACHE_MS) {
return hit.value
}
const value = readUsableAgentCredential(db, keyring, userId, agent, now)
const value = readUsableAgentCredentialState(db, keyring, userId, agent, now)
accountCache.set(key, { at: now, value })
value.catch(() => accountCache.delete(key))
return value
@@ -624,6 +662,9 @@ async function agentCredentialsRoute(request: Request, url: URL, env: Env, deps:
forgetAccountCredential(caller.userId, 'claude')
await refreshOwnersSandboxes(env, deps, caller.userId)
}
if (result.outcome === 'suspect') {
forgetAccountCredential(caller.userId, 'claude')
}
const view = await agentCredentialsView(db, env, caller.userId, now)
return noStore({ claude: view.claude, verifiedAt: result.verifiedAt, checked: result.outcome !== 'fresh' && result.outcome !== 'skipped' })
}
@@ -907,6 +948,7 @@ export async function lifecycleDeps(env: Env, deps: Deps): Promise<LifecycleDeps
config: {
pool: poolConfigFromEnv(env),
shareLinkSecret: shareSecret(env),
egressAllowlist: egressAllowlistFor(env.ORCA_PLATFORM_HOST_SUFFIXES),
extraEgressHosts: extraEgressHostsFor(env),
egressPreset: parseEgressPreset(env.SANDBOX_EGRESS_PRESET),
guardrails: guardrailsFromEnv(env),
@@ -2125,7 +2167,7 @@ async function workspaceRoute(request: Request, url: URL, env: Env, deps: Deps,
throw error
}
}
const match = /^\/v1\/team\/workspaces\/(sbx_[0-9a-f]{24})(?:\/(presence|wake|lease|grants|sent|read-snapshot)(?:\/(grt_[0-9a-f]{24}))?)?$/.exec(url.pathname)
const match = /^\/v1\/team\/workspaces\/(sbx_[0-9a-f]{24})(?:\/(presence|follow|wake|lease|grants|sent|read-snapshot)(?:\/(grt_[0-9a-f]{24}))?)?$/.exec(url.pathname)
if (!match) {
return fail('not_found', 404)
}
@@ -2154,6 +2196,13 @@ async function workspaceRoute(request: Request, url: URL, env: Env, deps: Deps,
await recordMemberSend(db, row.id, caller.userId, now)
return json({ ok: true })
}
if (route === 'PUT follow' || route === 'DELETE follow') {
// Following needs seeing it; an admin addressing a private row for management can't follow it.
if (!canSee(caller, row)) {
throw new WorkspaceError('not_found')
}
return json(await setFollow(db, caller, row, route === 'PUT follow', now))
}
if (route === 'POST presence') {
const body = PresenceSchema.safeParse(await readJson(request))
if (!body.success) {
+6 -1
View File
@@ -61,6 +61,7 @@ import { recordSessionEnd } from './session-cpu'
import { flushUsage, queueUsage } from './usage'
import { SANDBOX_VCPUS } from './machine-size'
import { isRegionalFailure } from './regions'
import { forgetWorkspaceFollows } from './workspace-follows'
export const LEASE_MS = 30 * 60_000
/**
@@ -148,6 +149,8 @@ export type LifecycleDeps = {
snapshotExpirationMs?: number
/** Warm pool (pool.ts); absent or size 0 means every create boots its own VM. */
pool?: PoolConfig
/** Base egress allowlist (egressAllowlistFor ORCA_PLATFORM_HOST_SUFFIXES); default DEFAULT_EGRESS_ALLOWLIST. */
egressAllowlist?: readonly string[]
/** Hosts allowed on top of the default egress allowlist (e.g. this control plane for the in-VM CLI). */
extraEgressHosts?: readonly string[]
/** Workspace sandbox egress (SANDBOX_EGRESS_PRESET); default DEFAULT_EGRESS_PRESET ("open"). */
@@ -317,7 +320,7 @@ export function egressPolicy(deps: LifecycleDeps, row: SandboxRow, gitToken?: st
}
// Limited: custom model-provider hosts (ANTHROPIC_BASE_URL / OPENAI_BASE_URL secrets) recorded at
// boot, MCP hosts the desktop declared, plus operator-configured extra hosts.
const allowlist = [...new Set([...DEFAULT_EGRESS_ALLOWLIST, ...(deps.config.extraEgressHosts ?? []), ...egressAllowHosts(row)])]
const allowlist = [...new Set([...(deps.config.egressAllowlist ?? DEFAULT_EGRESS_ALLOWLIST), ...(deps.config.extraEgressHosts ?? []), ...egressAllowHosts(row)])]
return compileNetworkPolicy({ mode: 'allowlist', allowlist, credentials: all })
}
@@ -1134,6 +1137,8 @@ export async function destroySandbox(deps: LifecycleDeps, row: SandboxRow): Prom
await markSnapshotsDeleted(deps.db, row.id, deps.now())
// Archive metadata (repo state, file tree) goes with the workspace.
await deps.db.prepare('DELETE FROM sandbox_archives WHERE sandbox_id = ?').bind(row.id).run()
// Nobody follows a workspace that is gone (PARITY-FOLLOW).
await forgetWorkspaceFollows(deps.db, row.id)
// So does its sealed read snapshot.
await deleteReadSnapshot(deps.db, row.id)
// And its per-workspace agent Source overrides.
@@ -63,7 +63,10 @@ function securityHeaders(formAction: string): Record<string, string> {
// Clickjacking: never framed. form-action also covers the 302 to the client after submit.
'x-frame-options': 'DENY',
'content-security-policy': `default-src 'none'; style-src 'unsafe-inline'; img-src 'none'; script-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self' ${formAction}`,
'referrer-policy': 'no-referrer',
// Not no-referrer: under no-referrer browsers send `Origin: null` on the form POST, which the
// same-origin check in oauth.ts refuses, so every real approval failed. same-origin still sends
// no referrer (and so none of the query) to any other origin.
'referrer-policy': 'same-origin',
'x-content-type-options': 'nosniff',
'cross-origin-opener-policy': 'same-origin'
}
@@ -9,6 +9,7 @@ import { memberChangeTime, recordMemberChange } from './member-changes'
import { revokeMemberReaderKeys } from './read-snapshots'
import { disableMemberRoutines } from './routines/runs'
import { forgetMemberPokes } from './team-presence'
import { forgetMemberFollows } from './workspace-follows'
export type MemberRemoval = {
keysRevoked: number
@@ -61,6 +62,8 @@ export async function removeMember(
const readerKeysRevoked = await revokeMemberReaderKeys(life.db, accountId, userId, now)
// Their Pokes opt-in goes (it doubles as proof of membership for receiving one).
await forgetMemberPokes(life.db, accountId, userId, now)
// They no longer follow anything here, and stop showing as anyone's follower.
await forgetMemberFollows(life.db, accountId, userId)
const grants = await revokeGrantsForMember(life, accountId, userId)
// Routines run with their creator's secrets: a departed member's stop, and nothing of theirs keeps running.
const routines = await disableMemberRoutines({ life }, accountId, userId)
@@ -44,8 +44,11 @@ export const EDITOR_REMOTE_SERVER_HOSTS: readonly string[] = [
'openvsxorg.blob.core.windows.net'
]
/** Registries, git hosting and agent model/sign-in hosts a coding VM needs. */
export const DEFAULT_EGRESS_ALLOWLIST: readonly string[] = [
/** Orca's own hosts when ORCA_PLATFORM_HOST_SUFFIXES is unset. */
export const DEFAULT_PLATFORM_HOST_SUFFIXES: readonly string[] = ['*.onorca.dev']
/** Registries, git hosting and agent model/sign-in hosts a coding VM needs (platform hosts excluded). */
const BASE_EGRESS_HOSTS: readonly string[] = [
'registry.npmjs.org',
'registry.yarnpkg.com',
'pypi.org',
@@ -97,11 +100,21 @@ export const DEFAULT_EGRESS_ALLOWLIST: readonly string[] = [
'models.dev',
// GitHub Copilot CLI: Copilot API (per plan: api.individual., api.business., ...).
'api.githubcopilot.com',
'*.githubcopilot.com',
'*.onorca.dev',
...EDITOR_REMOTE_SERVER_HOSTS
'*.githubcopilot.com'
]
/**
* The default allowlist with Orca's platform hosts from ORCA_PLATFORM_HOST_SUFFIXES (comma list, e.g.
* `*.onorca.dev`). Unset, blank or only commas: DEFAULT_PLATFORM_HOST_SUFFIXES.
*/
export function egressAllowlistFor(platformHostSuffixes?: string): readonly string[] {
const configured = (platformHostSuffixes ?? '').split(',').map((host) => host.trim()).filter(Boolean)
const platform = configured.length > 0 ? configured : DEFAULT_PLATFORM_HOST_SUFFIXES
return [...new Set([...BASE_EGRESS_HOSTS, ...platform, ...EDITOR_REMOTE_SERVER_HOSTS])]
}
export const DEFAULT_EGRESS_ALLOWLIST: readonly string[] = egressAllowlistFor()
/**
* Workspace sandbox egress presets. `open` (the default) reaches the whole internet, like Codespaces
* or Devin; `limited` is the fail-closed allowlist above. Credential routes apply under both.
@@ -136,7 +136,7 @@ echo "routine: agent exit $code"
if [ "$code" = 0 ] && [ "$post" = pr ] && [ -n "$start_sha" ]; then
git add -A >/dev/null 2>&1 || true
if ! git diff --cached --quiet 2>/dev/null; then
git -c user.name="Orca Routine" -c user.email="routines@onorca.dev" commit -q -m "$(cat "$D/title.txt")" -m "$summary" || note=commit_failed
git -c user.name="Orca Routine" -c user.email="noreply@orca.dev" commit -q -m "$(cat "$D/title.txt")" -m "$summary" || note=commit_failed
fi
if [ "$(git rev-parse HEAD)" != "$start_sha" ]; then
changed=true
@@ -0,0 +1,80 @@
// PARITY-FOLLOW: persistent Follow on a team workspace (Conductor's Following section and
// follower avatars).
// PUT /v1/team/workspaces/:id/follow -> {following: true, followers}
// DELETE /v1/team/workspaces/:id/follow -> {following: false, followers}
// Anyone who can see a workspace may follow it, and sees who else follows it (team workspaces are
// visible to the whole team). A private workspace's only viewer is its owner, so a teammate's old
// follow of a workspace that turned private is never shown and never counts. Archived workspaces
// may still be followed: they stay browsable.
import type { SandboxCaller } from './auth'
import type { SandboxRow } from './store'
/** Followers of each workspace, oldest follow first. */
export async function followersFor(db: D1Database, ids: readonly string[]): Promise<Map<string, string[]>> {
const out = new Map<string, string[]>()
if (ids.length === 0) {
return out
}
const { results } = await db
.prepare(
`SELECT sandbox_id, user_id FROM workspace_follows WHERE sandbox_id IN (${ids.map(() => '?').join(', ')})
ORDER BY created_at ASC, user_id ASC`
)
.bind(...ids)
.all<{ sandbox_id: string; user_id: string }>()
for (const row of results) {
const list = out.get(row.sandbox_id) ?? []
list.push(row.user_id)
out.set(row.sandbox_id, list)
}
return out
}
/**
* The followers a caller may be shown for a row: none unless the caller can see it (`seen`); for a
* private row, only its owner (the only member who can see it).
*/
export function visibleFollowers(
row: Pick<SandboxRow, 'visibility' | 'user_id'>,
seen: boolean,
followers: readonly string[]
): string[] {
if (!seen) {
return []
}
return row.visibility === 'team' ? [...followers] : followers.filter((id) => id === row.user_id)
}
/** The caller must be able to see the row (the route checks canSee first). */
export async function setFollow(
db: D1Database,
caller: SandboxCaller,
row: SandboxRow,
follow: boolean,
now: number
): Promise<{ following: boolean; followers: string[] }> {
if (follow) {
await db
.prepare(
`INSERT INTO workspace_follows (sandbox_id, user_id, account_id, created_at) VALUES (?, ?, ?, ?)
ON CONFLICT (sandbox_id, user_id) DO NOTHING`
)
.bind(row.id, caller.userId, row.account_id, now)
.run()
} else {
await db.prepare('DELETE FROM workspace_follows WHERE sandbox_id = ? AND user_id = ?').bind(row.id, caller.userId).run()
}
const followers = visibleFollowers(row, true, (await followersFor(db, [row.id])).get(row.id) ?? [])
return { following: followers.includes(caller.userId), followers }
}
/** The workspace is gone: nobody follows it any more. */
export async function forgetWorkspaceFollows(db: D1Database, sandboxId: string): Promise<void> {
await db.prepare('DELETE FROM workspace_follows WHERE sandbox_id = ?').bind(sandboxId).run()
}
/** The member left the account: their follows go, and they stop showing as a follower. */
export async function forgetMemberFollows(db: D1Database, accountId: string, userId: string): Promise<number> {
const result = await db.prepare('DELETE FROM workspace_follows WHERE account_id = ? AND user_id = ?').bind(accountId, userId).run()
return result.meta.changes
}
+11 -3
View File
@@ -4,6 +4,7 @@
// GET /v1/team/workspaces/:id
// PATCH /v1/team/workspaces/:id {title?, branch?, visibility?, section?, archived?, ownerUserId?, tokenUsdMicros?}
// POST /v1/team/workspaces/:id/presence {clientId, state: viewing|typing|left, chatId?}
// PUT|DELETE /v1/team/workspaces/:id/follow (workspace-follows.ts)
// GET /v1/team/links/resolve?w=<sandboxId>&c=<chatId> or ?org=<slug>&n=<number>&c=<chatId>
// Access rule: a workspace is visible to its owner, and to every member of the owning org when
// visibility is `team`. Org owners/admins additionally see private rows' metadata (scope=all) so a
@@ -15,6 +16,7 @@ import { getSandbox, touchActivity, updateRegistry, type SandboxRow } from './st
import { memberNamesFor } from './member-names'
import { recordTokenSpend } from './member-usage'
import { readSnapshotTimes } from './read-snapshots'
import { followersFor, visibleFollowers } from './workspace-follows'
import { sandboxView } from './wire'
import { accountForSlug, orgIdOf, slugForAccount } from './org-slugs'
import { ORCA_CLOUD_OVERAGE_CENTS_PER_HOUR } from '../../../../src/shared/hosted-sandbox/hosted-sandbox-wire'
@@ -172,15 +174,17 @@ function repoView(row: SandboxRow) {
export async function workspaceViews(db: D1Database, caller: SandboxCaller, rows: readonly SandboxRow[], now: number) {
const ids = rows.map((r) => r.id)
const [presence, compute, granted, readAt, slug] = await Promise.all([
const [presence, compute, granted, readAt, slug, follows] = await Promise.all([
presenceFor(db, ids, now),
computeMsFor(db, ids),
activeGrantUsers(db, ids, caller.userId),
readSnapshotTimes(db, ids),
rows.length > 0 ? slugForAccount(db, caller.accountId) : Promise.resolve(null)
rows.length > 0 ? slugForAccount(db, caller.accountId) : Promise.resolve(null),
followersFor(db, ids)
])
const followersOf = (row: SandboxRow) => visibleFollowers(row, canSee(caller, row), follows.get(row.id) ?? [])
const referenced = (row: SandboxRow, live: readonly PresenceRow[]) =>
[row.user_id, row.created_by, row.last_activity_by, ...live.map((p) => p.user_id)].filter(
[row.user_id, row.created_by, row.last_activity_by, ...live.map((p) => p.user_id), ...followersOf(row)].filter(
(id): id is string => typeof id === 'string'
)
const names = await memberNamesFor(
@@ -193,6 +197,7 @@ export async function workspaceViews(db: D1Database, caller: SandboxCaller, rows
// Private rows an admin sees for management show who/what, never live presence.
const showPresence = access !== 'none'
const live = showPresence ? (presence.get(row.id) ?? []) : []
const followers = followersOf(row)
const memberNames = Object.fromEntries(
referenced(row, live).flatMap((id) => (names.has(id) ? [[id, names.get(id)!]] : []))
)
@@ -214,6 +219,9 @@ export async function workspaceViews(db: D1Database, caller: SandboxCaller, rows
cost: costView(row, compute.get(row.id) ?? 0, now),
access,
presence: live.map((p) => ({ userId: p.user_id, clientId: p.client_id, state: p.state, chatId: p.chat_id, at: p.updated_at })),
// Who follows it (oldest first), and whether the caller does (PARITY-FOLLOW).
followers,
following: followers.includes(caller.userId),
// Display names (token `name` claim) for the ids above; the roster wins where it has one.
memberNames,
// When its sleeping read-only copy was saved ("As of"); only for those who may read it.
@@ -108,7 +108,8 @@ describe('Orca-account credentials (D11)', () => {
expect((await h.call('PUT', '/v1/agent-credentials/claude', { bearer: mia, body: { token: 'sk-ant-api03-not-a-setup-token' } })).body.reason).toBe('invalid_token')
const put = await h.call('PUT', '/v1/agent-credentials/claude', { bearer: mia, body: { token: SETUP_TOKEN, label: 'mia@example.com' } })
expect(put.status).toBe(200)
expect(put.body.claude).toMatchObject({ state: 'active', label: 'mia@example.com' })
// RS-5: never the email a client sends (it may be another account's): always "Claude subscription".
expect(put.body.claude).toMatchObject({ state: 'active', label: 'Claude subscription' })
expect(put.body.providerEnabled).toEqual({ claude: true, codex: false })
// Codex's flag was never turned on: `off`, which clients word differently from the kill switch.
expect(put.body.providerState).toEqual({ claude: 'on', codex: 'off' })
@@ -190,7 +191,7 @@ describe('egress-time Source (D10) and shared workspaces (D13)', () => {
expectSignedOut(refused)
})
it('a 401 from the provider marks the account revoked and the session falls off it', async () => {
it('a 401 confirmed by a later real 401 revokes the account and the session falls off it', async () => {
const { h, as, proxied, reply, lastEnv } = await setup()
const mia = await as('mia')
await h.call('PUT', '/v1/agent-credentials/claude', { bearer: mia, body: { token: SETUP_TOKEN } })
@@ -200,7 +201,11 @@ describe('egress-time Source (D10) and shared workspaces (D13)', () => {
const otherSession: string = other.body.sandbox.session.id
reply.status = 401
expect((await proxied(id, 'api.anthropic.com', { authorization: `Bearer orca-ph-claude-account-${id}` })).status).toBe(401)
// Confirmed by the control plane's own auth check (dead token), then revoked.
// RS-2: the auth check (dead token) only puts it in question; a later real request's 401 revokes it.
await vi.waitFor(async () =>
expect((await h.call('GET', '/v1/agent-credentials', { bearer: mia })).body.claude).toMatchObject({ state: 'expired', needsCheck: true })
)
expect((await proxied(id, 'api.anthropic.com', { authorization: `Bearer orca-ph-claude-account-${id}` })).status).toBe(401)
await vi.waitFor(async () => expect((await h.call('GET', '/v1/agent-credentials', { bearer: mia })).body.claude.state).toBe('revoked'))
// Already off the account: no placeholder in new shells, and the proxy refuses with a clear reason.
await vi.waitFor(() => expect(lastEnv(ENV_COMMAND).CLAUDE_CODE_OAUTH_TOKEN).toBeUndefined())
@@ -334,12 +339,62 @@ describe('a provider 401 revokes only when confirmed', () => {
expect(await state()).toBe('active')
})
it('a confirmed dead token is revoked once and audited', async () => {
it('RS-2: a failed auth check alone never revokes: "needs check" (shown as expired), still usable', async () => {
const { h, reply, send, state, auditRows, upstream, check } = await running()
reply.status = 401
await send()
await vi.waitFor(async () => expect(await auditRows()).toEqual([{ action: 'suspect', reason: 'provider_401_check_auth_failure', upstream_path: '/v1/messages' }]))
expect(await state()).toBe('expired')
const mia = await h.token('mia', undefined, 'sandbox')
expect((await h.call('GET', '/v1/agent-credentials', { bearer: mia })).body.claude).toMatchObject({ state: 'expired', needsCheck: true })
// The real credential still goes out, so the next real request can confirm it either way.
reply.status = 200
upstream.length = 0
await send()
expect(upstream.at(-1)?.headers.get('authorization')).toBe(`Bearer ${SETUP_TOKEN}`)
expect(check.calls).toBe(1)
})
it('RS-2: needs check + a later real 401 revokes (audited); the probe alone never did', async () => {
const { reply, send, state, auditRows } = await running()
reply.status = 401
await send()
await vi.waitFor(async () => expect((await auditRows()).map((row) => row.action)).toEqual(['suspect']))
await send()
await vi.waitFor(async () => expect(await state()).toBe('revoked'))
expect(await auditRows()).toEqual([{ action: 'revoked', reason: 'provider_401_confirmed_by_check', upstream_path: '/v1/messages' }])
expect(await auditRows()).toEqual([
{ action: 'suspect', reason: 'provider_401_check_auth_failure', upstream_path: '/v1/messages' },
{ action: 'revoked', reason: 'provider_401_after_check_failure', upstream_path: '/v1/messages' }
])
})
it('RS-2: needs check + a later real request that succeeds clears it back to active (audited)', async () => {
const { reply, send, state, auditRows } = await running()
reply.status = 401
await send()
await vi.waitFor(async () => expect((await auditRows()).map((row) => row.action)).toEqual(['suspect']))
reply.status = 200
await send()
await vi.waitFor(async () => expect(await state()).toBe('active'))
expect((await auditRows()).at(-1)).toEqual({ action: 'kept', reason: 'request_succeeded_after_check_failure', upstream_path: '/v1/messages' })
})
it('RS-2: a check that can\'t reach the provider changes nothing', async () => {
const ctx = await setup()
const mia = await ctx.as('mia')
await ctx.h.call('PUT', '/v1/agent-credentials/claude', { bearer: mia, body: { token: SETUP_TOKEN } })
const created = await ctx.h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-1', machineSize: 'standard' }, bearer: mia })
const id: string = created.body.sandbox.id
ctx.reply.status = 401
ctx.check.status = 0
await ctx.proxied(id, 'api.anthropic.com', { authorization: `Bearer orca-ph-claude-account-${id}` })
await vi.waitFor(async () =>
expect((await ctx.h.env.SANDBOX_DB.prepare('SELECT action, reason FROM agent_credential_audit').all()).results).toEqual([
{ action: 'kept', reason: 'check_inconclusive' }
])
)
expect((await ctx.h.call('GET', '/v1/agent-credentials', { bearer: mia })).body.claude).toEqual(expect.objectContaining({ state: 'active' }))
expect((await ctx.h.call('GET', '/v1/agent-credentials', { bearer: mia })).body.claude.needsCheck).toBeUndefined()
})
})
@@ -358,14 +413,14 @@ describe('POST /v1/agent-credentials/claude/verify (pre-launch check)', () => {
expect(check.calls).toBe(1)
})
it('a dead token is revoked (and audited); an inconclusive check keeps it', async () => {
it('RS-2: a dead token only needs a check (audited, never revoked by the probe); an inconclusive check keeps it', async () => {
const dead = await setup()
const mia = await dead.as('mia')
await dead.h.call('PUT', '/v1/agent-credentials/claude', { bearer: mia, body: { token: SETUP_TOKEN } })
const revoked = await dead.h.call('POST', '/v1/agent-credentials/claude/verify', { bearer: mia })
expect(revoked.body).toMatchObject({ claude: { state: 'revoked' }, checked: true, verifiedAt: null })
const suspect = await dead.h.call('POST', '/v1/agent-credentials/claude/verify', { bearer: mia })
expect(suspect.body).toMatchObject({ claude: { state: 'expired', needsCheck: true }, checked: true, verifiedAt: null })
const rows = (await dead.h.env.SANDBOX_DB.prepare('SELECT action, reason FROM agent_credential_audit').all()).results
expect(rows).toEqual([{ action: 'revoked', reason: 'verify_confirmed_auth_failure' }])
expect(rows).toEqual([{ action: 'suspect', reason: 'verify_check_auth_failure' }])
const flaky = await setup()
const ada = await flaky.as('ada')
@@ -0,0 +1,53 @@
import { SignJWT, exportJWK, generateKeyPair } from 'jose'
import { describe, expect, it } from 'vitest'
import { authenticateDesktop, issuerList } from '../src/auth'
import { createHarness } from './harness'
const PROD = 'https://login.onorca.dev'
const NEXT = 'https://login.example.dev'
async function issuerHarness(issuers: string) {
const { privateKey, publicKey } = await generateKeyPair('ES256')
const jwk = { ...(await exportJWK(publicKey)), kid: 'iss1', alg: 'ES256', use: 'sig' }
const h = await createHarness({ SANDBOX_JWKS: JSON.stringify({ keys: [jwk] }), SANDBOX_AUTH_ISSUER: issuers })
const accepts = async (issuer: string): Promise<boolean> => {
const iat = Math.floor(h.now() / 1000)
const token = await new SignJWT({ sub: 'user_iss', purpose: 'sandbox' })
.setProtectedHeader({ alg: 'ES256', kid: 'iss1' })
.setIssuer(issuer)
.setAudience('orca-sandbox')
.setIssuedAt(iat)
.setExpirationTime(iat + 300)
.sign(privateKey)
const request = new Request('https://sandbox.test/v1/config', { headers: { authorization: `Bearer ${token}` } })
return (await authenticateDesktop(h.env, request, h.now())) !== null
}
return { accepts }
}
describe('SANDBOX_AUTH_ISSUER list', () => {
it('parses a comma list, ignoring whitespace and empty entries', () => {
expect(issuerList(undefined)).toBeUndefined()
expect(issuerList('')).toBeUndefined()
expect(issuerList(PROD)).toEqual([PROD])
expect(issuerList(` ${PROD} ,, ${NEXT} , `)).toEqual([PROD, NEXT])
})
it('a single issuer behaves as before', async () => {
const h = await issuerHarness(PROD)
expect(await h.accepts(PROD)).toBe(true)
expect(await h.accepts(NEXT)).toBe(false)
})
it('a list accepts each listed issuer and rejects others', async () => {
const h = await issuerHarness(` ${PROD} , ,${NEXT},`)
expect(await h.accepts(PROD)).toBe(true)
expect(await h.accepts(NEXT)).toBe(true)
expect(await h.accepts('https://login.evil.dev')).toBe(false)
})
it('a value with no entries accepts no issuer', async () => {
const h = await issuerHarness(' , ')
expect(await h.accepts(PROD)).toBe(false)
})
})
@@ -35,16 +35,16 @@ async function setup() {
last_used_at: number | null
}[]
/** Lets the auto build's VM command succeed and finalizes it. */
async function finishBuild(as = 'alice') {
async function finishBuild(as = 'alice', output = '::orca-step:: clone\n') {
const env = environments().find((row) => row.deleted_at === null && !row.active_build_id)!
const build = h.raw.prepare('SELECT id FROM environment_builds WHERE environment_id = ? ORDER BY number DESC').get(env.id) as { id: string }
const command = [...h.vercel.buildCommands.values()].at(-1)!
command.logs = `${JSON.stringify({ data: '::orca-step:: clone\n', stream: 'stdout' })}\n`
command.logs = `${JSON.stringify({ data: output, stream: 'stdout' })}\n`
command.exitCode = 0
h.advance(1000)
const done = await h.call('GET', `/v1/environments/${env.id}/builds/${build.id}`, { as })
expect(done.body.build.status).toBe('succeeded')
return { env, buildId: build.id }
return { env, buildId: build.id, build: done.body.build }
}
return { h, settle, environments, finishBuild }
}
@@ -58,6 +58,8 @@ describe('automatic environments', () => {
expect(environments()).toMatchObject([{ kind: 'auto', name: 'acme/web', active_build_id: null }])
const command = [...h.vercel.buildCommands.values()].at(-1)!
expect(command.env.ORCA_CLONE_FILTER).toBe('blob:none')
// PARITY-AUTO-ENV-DEPS: its lockfile's dependencies too, so creates start warm.
expect(command.env.ORCA_AUTO_INSTALL).toBe('1')
const { buildId } = await finishBuild()
h.vercel.commands.length = 0
@@ -105,6 +107,30 @@ describe('automatic environments', () => {
expect(environments().filter((row) => row.kind === 'auto')).toHaveLength(2)
})
it('the build says what its lockfile install did (AUTO-ENV-DEPS-LABEL)', async () => {
const { h, settle, finishBuild } = await setup()
await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'w1', machineSize: 'standard', repo: { url: REPO } }, headers: FEATURES })
await settle()
const { build } = await finishBuild(
'alice',
'::orca-step:: install\nInstalling dependencies automatically: corepack pnpm install --frozen-lockfile\nInstalled dependencies in 42s.\n'
)
expect(build.autoInstall).toEqual({ manager: 'pnpm', outcome: 'installed' })
})
it("an admin's environment never installs automatically, with or without its own script", async () => {
const { h } = await setup()
const admin = await h.token('carol', 'acme', 'sandbox', { orgRole: 'admin' })
const created = await h.call('POST', '/v1/environments', {
bearer: admin,
body: { name: 'Web', repos: [{ url: 'acme/web' }], installScript: '' }
})
expect(created.status).toBe(200)
expect((await h.call('POST', `/v1/environments/${created.body.environment.id}/builds`, { bearer: admin })).status).toBe(200)
const command = [...h.vercel.buildCommands.values()].at(-1)!
expect(command.env.ORCA_AUTO_INSTALL).toBeUndefined()
})
it('boot-plan says clone before the environment exists and update after (PC-4)', async () => {
const { h, settle, finishBuild } = await setup()
const plan = async () => (await h.call('GET', `/v1/sandboxes/boot-plan?repo=${encodeURIComponent(REPO)}`)).body
@@ -368,7 +368,12 @@ describe('Codex account in workspaces (D10, D13)', () => {
const created = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-1', machineSize: 'standard' }, bearer: mia })
const id: string = created.body.sandbox.id
await h.env.SANDBOX_DB.prepare(`UPDATE sandboxes SET visibility = 'team' WHERE id = ?`).bind(id).run()
expect((await proxied(id, 'chatgpt.com', { authorization: `Bearer ${codexPlaceholder({ id })}` })).status).toBe(403)
const refused = await proxied(id, 'chatgpt.com', { authorization: `Bearer ${codexPlaceholder({ id })}` })
// RS-4: still a 403 (a 401 would start Codex's own token refresh), now with words Codex prints.
expect(refused.status).toBe(403)
expect(JSON.parse(refused.body)).toEqual({
detail: 'Orca Cloud can’t use your ChatGPT sign-in here. Check it in Orca: Settings → Agent accounts.'
})
expect(lastEnv('/opt/orca/bin/orca-sandbox-env').ORCA_CODEX_AUTH_PLACEHOLDER).toBeUndefined()
})
@@ -0,0 +1,24 @@
import { describe, expect, it } from 'vitest'
import { autoInstallFromLog } from '../src/environment-builds'
const stored = (...lines: string[]): string =>
lines.map((data) => JSON.stringify({ data: `${data}\n`, stream: 'stdout' })).join('\n')
describe('autoInstallFromLog (AUTO-ENV-DEPS-LABEL)', () => {
it('reads the manager and whether it installed', () => {
expect(
autoInstallFromLog(stored('Installing dependencies automatically: corepack yarn install --immutable', 'Installed dependencies in 9s.'))
).toEqual({ manager: 'yarn', outcome: 'installed' })
expect(
autoInstallFromLog(
stored('Installing dependencies automatically: npm ci', 'Automatic install skipped: npm ci exited with status 1 (often a lockfile out of date).')
)
).toEqual({ manager: 'npm', outcome: 'skipped' })
})
it('nothing for a build without an automatic install, or an unreadable log', () => {
expect(autoInstallFromLog(stored('No install script; the build keeps the cloned repos.'))).toBeNull()
expect(autoInstallFromLog(stored('Not installed automatically: uv.lock.'))).toBeNull()
expect(autoInstallFromLog('not json\n{"data":')).toBeNull()
})
})
@@ -0,0 +1,135 @@
// PARITY-AUTO-ENV-DEPS: an automatic environment installs the first repo's JavaScript dependencies
// from its lockfile, so creates start warm, and never fails its build over it. The real script's
// auto_install, run by a real bash against a scratch repo with stub package managers on PATH.
import { execFileSync } from 'node:child_process'
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { ENVIRONMENT_BUILD_SCRIPT, VM_SCRIPTS_HASH } from '../image/vm-scripts.generated'
const script = readFileSync(fileURLToPath(new URL('../image/env/environment-build.sh', import.meta.url).href), 'utf8')
const autoInstall = /^auto_install\(\) \{\n[\s\S]*?\n\}\n/m.exec(script)?.[0]
let dir: string
let repo: string
let bin: string
/** A stub command that logs its argv to calls.log and exits with $STUB_<NAME>_EXIT (default 0). */
function stub(name: string): void {
const exitVar = `STUB_${name.toUpperCase()}_EXIT`
writeFileSync(
join(bin, name),
`#!/usr/bin/env bash\necho "${name} $*" >>"${join(dir, 'calls.log')}"\n` +
// A failing install leaves a half-written tree behind, as real ones do.
`mkdir -p node_modules/.half packages/a/node_modules\nexit "\${${exitVar}:-0}"\n`
)
chmodSync(join(bin, name), 0o755)
}
function run(env: Record<string, string> = {}): { status: number; out: string; calls: string } {
const program = ['set -uo pipefail', autoInstall, 'auto_install "$REPO"', 'echo "status:$?"'].join('\n')
let out: string
let status = 0
try {
out = execFileSync('bash', ['--noprofile', '--norc', '-c', program], {
env: { PATH: `${bin}:${process.env.PATH}`, REPO: repo, ...env },
encoding: 'utf8'
})
} catch (error) {
const failed = error as { status: number; stdout: string }
status = failed.status
out = failed.stdout
}
const log = join(dir, 'calls.log')
return { status, out, calls: existsSync(log) ? readFileSync(log, 'utf8') : '' }
}
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), 'orca-auto-install-'))
repo = join(dir, 'repo')
bin = join(dir, 'bin')
mkdirSync(repo)
mkdirSync(bin)
stub('corepack')
stub('npm')
})
afterEach(() => rmSync(dir, { recursive: true, force: true }))
const file = (path: string, content = ''): void => writeFileSync(join(repo, path), content)
describe('environment-build.sh auto_install (PARITY-AUTO-ENV-DEPS)', () => {
it('is in the build script, runs only for automatic environments without an install script, and ships in the Worker', () => {
expect(autoInstall).toBeDefined()
expect(script).toMatch(/elif \[ "\$\{ORCA_AUTO_INSTALL:-\}" = 1 \] && \[ -n "\$first" \]; then\n {2}auto_install "\$first"\n/)
expect(ENVIRONMENT_BUILD_SCRIPT).toBe(script)
// env/ scripts ride in the Worker; the golden's VM scripts (and their hash) are untouched.
// Pin updated by DOMAIN-1 #666, which changes the VM scripts on purpose.
expect(VM_SCRIPTS_HASH).toBe('6e35ca58')
})
it('picks the package manager from the lockfile, frozen, through corepack', () => {
file('package.json', '{"name":"web"}')
file('pnpm-lock.yaml')
const pnpm = run()
expect(pnpm.out).toContain('status:0')
expect(pnpm.calls).toBe('corepack pnpm install --frozen-lockfile\n')
expect(pnpm.out).toMatch(/Installed dependencies in \d+s\./)
})
it('yarn berry is --immutable, classic --frozen-lockfile; npm is npm ci', () => {
file('package.json', '{}')
file('yarn.lock')
expect(run().calls).toBe('corepack yarn install --frozen-lockfile\n')
rmSync(join(dir, 'calls.log'))
file('.yarnrc.yml', 'nodeLinker: node-modules\n')
expect(run().calls).toBe('corepack yarn install --immutable\n')
rmSync(join(repo, 'yarn.lock'))
rmSync(join(repo, '.yarnrc.yml'))
rmSync(join(dir, 'calls.log'))
file('package-lock.json', '{}')
expect(run().calls).toBe('npm ci\n')
})
it("package.json's packageManager wins over the lockfile guess", () => {
file('package.json', '{"name":"web","packageManager":"pnpm@9.12.0"}')
file('package-lock.json', '{}')
expect(run().calls).toBe('corepack pnpm install --frozen-lockfile\n')
})
it('a failed install (often a lockfile out of date) never fails the build and leaves no half-installed tree', () => {
file('package.json', '{}')
file('pnpm-lock.yaml')
const failed = run({ STUB_COREPACK_EXIT: '1' })
expect(failed.status).toBe(0)
expect(failed.out).toContain('status:0')
expect(failed.out).toContain('Automatic install skipped: corepack pnpm install --frozen-lockfile exited with status 1')
expect(failed.out).toContain('New workspaces start from the cloned repo and run their own setup.')
expect(existsSync(join(repo, 'node_modules'))).toBe(false)
expect(existsSync(join(repo, 'packages/a/node_modules'))).toBe(false)
})
it('stops at the time cap and says so, still without failing', () => {
file('package.json', '{}')
file('package-lock.json', '{}')
writeFileSync(join(bin, 'npm'), '#!/usr/bin/env bash\nsleep 5\n')
chmodSync(join(bin, 'npm'), 0o755)
const slow = run({ ORCA_AUTO_INSTALL_TIMEOUT: '1' })
expect(slow.out).toContain('status:0')
expect(slow.out).toContain('took longer than 15 minutes')
})
it('names what the image cannot install, and does nothing without a lockfile', () => {
file('uv.lock')
file('Gemfile.lock')
const others = run()
expect(others.calls).toBe('')
expect(others.out).toContain('Not installed automatically: uv.lock Gemfile.lock.')
rmSync(join(repo, 'uv.lock'))
rmSync(join(repo, 'Gemfile.lock'))
const none = run()
expect(none.calls).toBe('')
expect(none.out).toContain('No lockfile found; the build keeps the cloned repos.')
})
})
@@ -9,7 +9,7 @@ import { fileURLToPath } from 'node:url'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
const SHIM = fileURLToPath(new URL('../image/vm/git', import.meta.url).href)
const NUDGE = "orca: This commit uses Orca Cloud's name. Connect your GitHub in Settings → Account to use yours."
const NUDGE = "orca: This commit is authored as Orca <noreply@orca.dev>. Connect GitHub in Settings → Account to commit as yourself."
let home = ''
let cwd = ''
@@ -425,6 +425,8 @@ describe('MCP authorization', () => {
const page = await h.send(new Request(`${ORIGIN}/oauth/authorize?${h.authorizeParams(client.client_id, challenge)}`))
expect(page.headers.get('x-frame-options')).toBe('DENY')
// Browsers only send a real Origin on the approval POST when the page's policy allows it (END-PASS: no-referrer broke every browser).
expect(page.headers.get('referrer-policy')).toBe('same-origin')
expect(page.headers.get('content-security-policy')).toContain("frame-ancestors 'none'")
expect(page.headers.get('content-security-policy')).toContain('form-action \'self\' http://127.0.0.1:33418')
expect(page.headers.get('set-cookie')).toMatch(/__Host-orca_mcp_csrf=\w+; Path=\/; Secure; HttpOnly; SameSite=Strict/)
@@ -1,5 +1,13 @@
import { describe, expect, it } from 'vitest'
import { DEFAULT_EGRESS_PRESET, EDITOR_REMOTE_SERVER_HOSTS, compileNetworkPolicy, gitBasicAuthorization, parseEgressPreset } from '../src/network-policy'
import {
DEFAULT_EGRESS_ALLOWLIST,
DEFAULT_EGRESS_PRESET,
EDITOR_REMOTE_SERVER_HOSTS,
compileNetworkPolicy,
egressAllowlistFor,
gitBasicAuthorization,
parseEgressPreset
} from '../src/network-policy'
const deny = { response: { statusCode: 403, body: 'orca-egress-denied', contentType: 'text/plain' } }
@@ -123,3 +131,26 @@ describe('compileNetworkPolicy', () => {
expect(allow['*']).toBeUndefined()
})
})
describe('ORCA_PLATFORM_HOST_SUFFIXES', () => {
it('unset (or blank) keeps the default allowlist exactly as before', () => {
const editorAt = DEFAULT_EGRESS_ALLOWLIST.length - EDITOR_REMOTE_SERVER_HOSTS.length
expect(DEFAULT_EGRESS_ALLOWLIST).toHaveLength(56)
expect(DEFAULT_EGRESS_ALLOWLIST.slice(editorAt - 2, editorAt)).toEqual(['*.githubcopilot.com', '*.onorca.dev'])
expect(DEFAULT_EGRESS_ALLOWLIST.slice(editorAt)).toEqual(EDITOR_REMOTE_SERVER_HOSTS)
for (const unset of [undefined, '', ' , ']) {
expect(egressAllowlistFor(unset)).toEqual(DEFAULT_EGRESS_ALLOWLIST)
}
})
it('replaces the platform hosts with the configured suffixes, once each', () => {
const allowlist = egressAllowlistFor(' *.onorca.dev , ,*.example.dev,')
expect(allowlist.filter((host) => host === '*.onorca.dev')).toHaveLength(1)
expect(allowlist).toContain('*.example.dev')
expect(allowlist).toHaveLength(DEFAULT_EGRESS_ALLOWLIST.length + 1)
expect(egressAllowlistFor('*.example.dev')).not.toContain('*.onorca.dev')
const { allow } = compileNetworkPolicy({ mode: 'allowlist', allowlist })
expect(allow['*.onorca.dev']).toEqual([])
expect(allow['*.example.dev']).toEqual([])
})
})
@@ -0,0 +1,93 @@
import { describe, expect, it } from 'vitest'
import { createHarness } from './harness'
const AUTH_TOKEN = 'a'.repeat(40)
async function team() {
const h = await createHarness({ OPERATOR_TOKEN: 'o'.repeat(40), MEMBER_REMOVED_TOKEN: AUTH_TOKEN })
type Who = { sub: string; orgRole: 'owner' | 'admin' | 'member' }
const req = async (who: Who, method: string, path: string, body?: unknown) =>
h.call(method, path, { bearer: await h.token(who.sub, 'acme', 'sandbox', { org_role: who.orgRole }), body })
const alice: Who = { sub: 'alice', orgRole: 'member' }
const bob: Who = { sub: 'bob', orgRole: 'member' }
const carol: Who = { sub: 'carol', orgRole: 'member' }
const olga: Who = { sub: 'olga', orgRole: 'admin' }
const create = async (who: Who, visibility: 'team' | 'private') => {
const made = await req(who, 'POST', '/v1/sandboxes', { workspaceId: `ws-${Math.random()}`, machineSize: 'standard', title: 'W' })
expect(made.status).toBe(200)
const id = made.body.sandbox.id as string
if (visibility === 'team') {
await req(who, 'PATCH', `/v1/team/workspaces/${id}`, { visibility: 'team' })
}
return id
}
const internal = (path: string, body: unknown) => h.call('POST', path, { body, bearer: AUTH_TOKEN })
return { h, req, alice, bob, carol, olga, create, internal }
}
describe('workspace follows (PARITY-FOLLOW)', () => {
it('follows and unfollows; everyone who can see it sees followers, oldest first', async () => {
const t = await team()
const id = await t.create(t.alice, 'team')
const bobFollow = await t.req(t.bob, 'PUT', `/v1/team/workspaces/${id}/follow`)
expect(bobFollow.status).toBe(200)
expect(bobFollow.body).toEqual({ following: true, followers: ['bob'] })
t.h.advance(1_000)
await t.req(t.carol, 'PUT', `/v1/team/workspaces/${id}/follow`)
// Following twice is a no-op, and keeps Bob first.
await t.req(t.bob, 'PUT', `/v1/team/workspaces/${id}/follow`)
const seenByAlice = (await t.req(t.alice, 'GET', `/v1/team/workspaces/${id}`)).body.workspace
expect(seenByAlice).toMatchObject({ followers: ['bob', 'carol'], following: false })
const listed = (await t.req(t.carol, 'GET', '/v1/team/workspaces?scope=team')).body.workspaces
expect(listed.find((w: { id: string }) => w.id === id)).toMatchObject({ followers: ['bob', 'carol'], following: true })
const unfollow = await t.req(t.bob, 'DELETE', `/v1/team/workspaces/${id}/follow`)
expect(unfollow.body).toEqual({ following: false, followers: ['carol'] })
})
it("can't follow a private workspace you can't see, and old follows vanish when it turns private", async () => {
const t = await team()
const secret = await t.create(t.alice, 'private')
expect((await t.req(t.bob, 'PUT', `/v1/team/workspaces/${secret}/follow`)).status).toBe(404)
// An admin may address a private row for management, but not follow it.
expect((await t.req(t.olga, 'PUT', `/v1/team/workspaces/${secret}/follow`)).status).toBe(404)
const shared = await t.create(t.alice, 'team')
await t.req(t.bob, 'PUT', `/v1/team/workspaces/${shared}/follow`)
t.h.advance(1_000)
await t.req(t.alice, 'PUT', `/v1/team/workspaces/${shared}/follow`)
await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${shared}`, { visibility: 'private' })
// The owner still sees their own follow; Bob's is never shown while it is private.
const own = (await t.req(t.alice, 'GET', `/v1/team/workspaces/${shared}`)).body.workspace
expect(own).toMatchObject({ followers: ['alice'], following: true })
const adminView = (await t.req(t.olga, 'GET', '/v1/team/workspaces?scope=all')).body.workspaces.find(
(w: { id: string }) => w.id === shared
)
expect(adminView.followers).toEqual([])
// Shared again: Bob's follow is back (it was hidden, not lost).
await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${shared}`, { visibility: 'team' })
expect((await t.req(t.bob, 'GET', `/v1/team/workspaces/${shared}`)).body.workspace).toMatchObject({
followers: ['bob', 'alice'],
following: true
})
})
it('forgets every follow of a destroyed workspace', async () => {
const t = await team()
const id = await t.create(t.alice, 'team')
await t.req(t.bob, 'PUT', `/v1/team/workspaces/${id}/follow`)
expect((await t.req(t.alice, 'DELETE', `/v1/sandboxes/${id}`)).status).toBe(200)
const left = t.h.raw.prepare('SELECT COUNT(*) AS n FROM workspace_follows WHERE sandbox_id = ?').get(id) as { n: number }
expect(left.n).toBe(0)
})
it("forgets a removed member's follows, so they stop showing as a follower", async () => {
const t = await team()
const id = await t.create(t.alice, 'team')
await t.req(t.bob, 'PUT', `/v1/team/workspaces/${id}/follow`)
await t.req(t.carol, 'PUT', `/v1/team/workspaces/${id}/follow`)
expect((await t.internal('/v1/internal/org-members/removed', { accountId: 'org:acme', userId: 'bob' })).status).toBe(200)
expect((await t.req(t.alice, 'GET', `/v1/team/workspaces/${id}`)).body.workspace.followers).toEqual(['carol'])
})
})
@@ -6,8 +6,11 @@ import { createRunTempDirectory, sweepStaleRunDirectories } from './vitest-run-t
const bases = []
// A run root past 50 chars falls back to /tmp (resolveRunTempBase), so a base under a long TMPDIR (the Linux
// premerge lane's is under the home directory) would test /tmp instead of the base it made. Keep POSIX bases short.
function makeBase() {
const base = mkdtempSync(join(tmpdir(), 'orca-run-temp-'))
const root = process.platform === 'win32' ? tmpdir() : '/tmp'
const base = mkdtempSync(join(root, 'ort-'))
bases.push(base)
return base
}
+35 -2
View File
@@ -6,11 +6,18 @@ import { MobileStateView } from '../../../src/components/MobileStateView'
import { CloudWorkspaceScreen } from '../../../src/cloud/CloudWorkspaceScreen'
import { resolveCloudWorkspaceLink } from '../../../src/cloud/cloud-workspace-prefs'
import { loadCloudControlPlane } from '../../../src/cloud/cloud-session'
import { CloudStateGlyph } from '../../../src/cloud/CloudStateGlyph'
import { setCloudReturnTo } from '../../../src/cloud/cloud-return-to'
import { cloudNumberLinkState } from '../../../src/cloud/cloud-screen-states'
import { useMobileTranslation } from '../../../src/i18n/use-mobile-translation'
import { colors } from '../../../src/theme/mobile-theme'
import { parseCloudWorkspaceLink } from '../../../../src/shared/cloud-workspaces/cloud-workspaces-wire'
type Resolved = { kind: 'loading' } | { kind: 'found'; sandboxId: string } | { kind: 'missing' }
type Resolved =
| { kind: 'loading' }
| { kind: 'found'; sandboxId: string }
| { kind: 'missing' }
| { kind: 'signin' }
/** Team links with a number (orca://cloud/<org>/W-123, the desktop's "Copy link") open here. */
export default function CloudWorkspaceNumberLinkRoute() {
@@ -26,8 +33,17 @@ export default function CloudWorkspaceNumberLinkRoute() {
const plane = parsed ? await loadCloudControlPlane() : null
const sandboxId =
plane && parsed ? await resolveCloudWorkspaceLink(plane, parsed.target) : null
const state = cloudNumberLinkState({
validLink: parsed !== null,
enrolled: plane !== null,
sandboxId
})
if (live) {
setResolved(sandboxId ? { kind: 'found', sandboxId } : { kind: 'missing' })
setResolved(
state === 'found' && sandboxId
? { kind: 'found', sandboxId }
: { kind: state === 'signin' ? 'signin' : 'missing' }
)
}
})().catch(() => live && setResolved({ kind: 'missing' }))
return () => {
@@ -41,6 +57,23 @@ export default function CloudWorkspaceNumberLinkRoute() {
<SafeAreaView style={{ flex: 1, backgroundColor: colors.bgBase }}>
{resolved.kind === 'loading' ? (
<MobileStateView loading title={t('cloud.link.opening', 'Opening workspace…')} />
) : resolved.kind === 'signin' ? (
// Same state as a share link opened before connecting: connect on Home, then come back here.
<MobileStateView
iconElement={<CloudStateGlyph />}
title={t('cloud.workspace.signIn', 'Sign in to Orca Cloud on this phone')}
message={t(
'cloud.workspace.signInDetail',
'This link opens a cloud workspace your team shared. Sign in to see it.'
)}
action={{
label: t('cloud.workspace.signInAction', 'Sign in'),
onPress: () => {
setCloudReturnTo(`/cloud/${params.org ?? ''}/${params.number ?? ''}`)
router.replace('/')
}
}}
/>
) : (
<MobileStateView
icon={Cloud}
+2 -38
View File
@@ -1,51 +1,15 @@
import { Text, View } from 'react-native'
import type { Translate } from '../i18n/mobile-i18n'
import { useMobileTranslation } from '../i18n/use-mobile-translation'
import { useMobileColorScheme } from '../theme/use-mobile-color-scheme'
import { CloudPhaseSteps } from './CloudPhaseSteps'
import { CloudStatusDot } from './CloudStatusDot'
import { CloudWakeSlowNote } from './CloudWakeSlowNote'
import type { CloudWorkspace } from './cloud-control-plane-client'
import { cloudSandboxHours, cloudStatusLabel } from './cloud-workspace-display'
import { cloudSpendLine, cloudStatusLabel } from './cloud-workspace-display'
import { statusSentence } from './cloud-workspace-copy'
import { cloudWorkspaceScreenStyles as styles } from './cloud-workspace-screen-styles'
import type { CloudWorkspaceRun } from './use-cloud-workspace-run'
/** Usage once, honestly: sandbox hours so far (what the plan meters), and whether it is using them
* now. No per-workspace dollars: included hours are not charged. */
function spendLine(
workspace: CloudWorkspace,
usage: { totalMs: number } | null,
awake: boolean,
t: Translate
): string | null {
const ms = usage ? usage.totalMs : workspace.sandboxMs
if (ms === null) {
return null
}
const { value, label } = cloudSandboxHours(ms)
if (!awake) {
return t(
'cloud.usage.asleep',
'{{hours}} sandbox hours so far. Uses no sandbox hours while asleep.',
{
count: value,
hours: label,
defaultValue_one: '{{hours}} sandbox hour so far. Uses no sandbox hours while asleep.'
}
)
}
return t(
'cloud.usage.running',
'{{hours}} sandbox hours so far. Uses sandbox hours while running.',
{
count: value,
hours: label,
defaultValue_one: '{{hours}} sandbox hour so far. Uses sandbox hours while running.'
}
)
}
export function CloudStatusCard(props: {
workspace: CloudWorkspace
run: CloudWorkspaceRun
@@ -61,7 +25,7 @@ export function CloudStatusCard(props: {
// Up but unreachable from this phone: a filled amber dot, as a desktop that can't connect.
const notConnected = run.kind === 'error' && workspace.status === 'running'
const awake = active || workspace.status === 'running' || workspace.status === 'creating'
const spend = spendLine(workspace, props.usage, awake, t)
const spend = cloudSpendLine(workspace, props.usage, awake, t)
return (
<View style={styles.statusCard}>
<View style={styles.statusHeadline}>
+14 -11
View File
@@ -333,17 +333,20 @@ export function CloudWorkspaceScreen({
/>
) : null}
<View style={styles.section}>
<Text style={styles.sectionHeading} accessibilityRole="header">
{t('cloud.prompt.heading', 'Ask an agent')}
</Text>
<CloudPromptComposer
awake={awake}
waking={active || workspace.status === 'waking'}
disabled={unavailable}
onSend={send}
/>
</View>
{/* Archived is read-only here: nothing can wake it from the phone, so no prompt box. */}
{workspace.status === 'archived' ? null : (
<View style={styles.section}>
<Text style={styles.sectionHeading} accessibilityRole="header">
{t('cloud.prompt.heading', 'Ask an agent')}
</Text>
<CloudPromptComposer
awake={awake}
waking={active || workspace.status === 'waking'}
disabled={unavailable}
onSend={send}
/>
</View>
)}
<CloudPromptQueueSection queue={queue} awake={awake} onRetry={() => void start('send')} />
<View style={styles.section}>
+1 -1
View File
@@ -137,7 +137,7 @@ export function NewCloudWorkspaceScreen() {
return
}
setStartedAt(null)
setError(createErrorMessage(failure, t, role))
setError(createErrorMessage(failure, t, role, repoUrl))
return
}
// The sandbox exists from here on: nothing below may report "couldn't create" or create again.
+105
View File
@@ -0,0 +1,105 @@
import { describe, expect, it } from 'vitest'
import { runCloudDelivery, type CloudDeliveryDeps } from './cloud-delivery-run'
import type { QueuedCloudPrompt } from './cloud-prompt-queue'
function prompt(id: string, status: QueuedCloudPrompt['status'] = 'queued'): QueuedCloudPrompt {
return {
id,
sandboxId: 'sbx_1',
text: `prompt ${id}`,
agent: 'claude',
operationId: `op-${id}`,
status,
createdAt: 1
}
}
/** An in-memory queue with the real delivery rules: failed prompts are skipped, not retried. */
function fakeQueue(initial: QueuedCloudPrompt[], overrides: Partial<CloudDeliveryDeps> = {}) {
let queue = [...initial]
const launched: string[] = []
const deps: CloudDeliveryDeps = {
listQueued: async () => queue,
ensureWorktree: async () => 'wt-1',
launch: async (_worktreeId, entry) => {
launched.push(entry.id)
return { agent: entry.agent }
},
deliverQueued: async (_sandboxId, deliver, errorCodeFor) => {
let delivered = 0
const failed: QueuedCloudPrompt[] = []
for (const entry of queue.filter((item) => item.status !== 'failed')) {
try {
await deliver(entry)
queue = queue.filter((item) => item.id !== entry.id)
delivered += 1
} catch (error) {
const code = errorCodeFor(error)
queue = queue.map((item) =>
item.id === entry.id ? { ...item, status: 'failed' as const, error: code } : item
)
failed.push({ ...entry, status: 'failed', error: code })
}
}
return { delivered, failed }
},
markWaitingFailed: async (_sandboxId, code) => {
queue = queue.map((item) =>
item.status === 'queued' ? { ...item, status: 'failed' as const, error: code } : item
)
},
errorCodeFor: (error) => (error instanceof Error ? error.message : 'launch_failed'),
...overrides
}
return { deps, launched, queue: () => queue }
}
describe('runCloudDelivery', () => {
it('opens when nothing is waiting, including when only failed prompts are left', async () => {
const empty = fakeQueue([])
expect(await runCloudDelivery('sbx_1', 'open', empty.deps)).toEqual({ kind: 'open' })
const onlyFailed = fakeQueue([prompt('a', 'failed')])
expect(await runCloudDelivery('sbx_1', 'open', onlyFailed.deps)).toEqual({ kind: 'open' })
expect(onlyFailed.launched).toEqual([])
})
it('reports the last launched agent after a delivery', async () => {
const run = fakeQueue([prompt('a'), prompt('b')])
expect(await runCloudDelivery('sbx_1', 'send', run.deps)).toEqual({
kind: 'launched',
worktreeId: 'wt-1',
agent: { agent: 'claude' }
})
expect(run.launched).toEqual(['a', 'b'])
})
it('a prompt that does not start still opens the workspace when the user asked to open it', async () => {
const run = fakeQueue([prompt('a')], {
launch: async () => {
throw new Error('launch_failed')
}
})
expect(await runCloudDelivery('sbx_1', 'open', run.deps)).toEqual({
kind: 'failed',
code: null,
open: true
})
expect(run.queue()[0]).toMatchObject({ status: 'failed', error: 'launch_failed' })
})
it('a failure before any launch marks every waiting prompt failed, so the next Open goes straight in', async () => {
const run = fakeQueue([prompt('a'), prompt('b')], {
ensureWorktree: async () => {
throw new Error('cloud_project_unavailable')
}
})
expect(await runCloudDelivery('sbx_1', 'send', run.deps)).toEqual({
kind: 'failed',
code: 'cloud_project_unavailable',
open: false
})
expect(run.queue().map((entry) => entry.status)).toEqual(['failed', 'failed'])
// The stuck-prompt bug: Open used to re-run this delivery and fail again forever.
expect(await runCloudDelivery('sbx_1', 'open', run.deps)).toEqual({ kind: 'open' })
})
})
+70
View File
@@ -0,0 +1,70 @@
import type { QueuedCloudPrompt } from './cloud-prompt-queue'
import type { CloudLaunchedAgent } from './cloud-workspace-host-operations'
/** What one delivery pass over a workspace's waiting prompts ended in. */
export type CloudDeliveryOutcome =
| { kind: 'open' }
| { kind: 'launched'; worktreeId: string; agent: CloudLaunchedAgent }
/** A prompt didn't start. `open`: the user asked to open the workspace, so it opens anyway. */
| { kind: 'failed'; code: string | null; open: boolean }
export type CloudDeliveryDeps = {
listQueued: (sandboxId: string) => Promise<QueuedCloudPrompt[]>
ensureWorktree: () => Promise<string>
launch: (worktreeId: string, prompt: QueuedCloudPrompt) => Promise<CloudLaunchedAgent>
deliverQueued: (
sandboxId: string,
deliver: (prompt: QueuedCloudPrompt) => Promise<void>,
errorCodeFor: (error: unknown) => string
) => Promise<{ delivered: number; failed: QueuedCloudPrompt[] }>
markWaitingFailed: (sandboxId: string, code: string) => Promise<void>
errorCodeFor: (error: unknown) => string
}
const waiting = (queue: QueuedCloudPrompt[]) => queue.some((prompt) => prompt.status !== 'failed')
/**
* Sends a workspace's waiting prompts once its host is connected. A prompt that can't start is
* marked failed (shown with Retry and Remove) rather than left waiting, so it never stands between
* the user and the workspace: "Open workspace" opens it whatever the prompts did.
*/
export async function runCloudDelivery(
sandboxId: string,
intent: 'open' | 'send',
deps: CloudDeliveryDeps
): Promise<CloudDeliveryOutcome> {
if (!waiting(await deps.listQueued(sandboxId))) {
return { kind: 'open' }
}
const launches: CloudLaunchedAgent[] = []
let worktreeId: string
let failed = 0
try {
worktreeId = await deps.ensureWorktree()
// Prompts typed while this ran are picked up too, so none is left "waiting" behind it.
for (let round = 0; round < 5; round++) {
const next = await deps.deliverQueued(
sandboxId,
async (prompt) => {
launches.push(await deps.launch(worktreeId, prompt))
},
deps.errorCodeFor
)
failed += next.failed.length
if (next.delivered + next.failed.length === 0 || !waiting(await deps.listQueued(sandboxId))) {
break
}
}
} catch (error) {
// Nothing was launched (the project or connection failed first): every waiting prompt says why
// instead of "Waiting to connect", and Open no longer tries to send them again.
const code = deps.errorCodeFor(error)
await deps.markWaitingFailed(sandboxId, code).catch(() => undefined)
return { kind: 'failed', code, open: intent === 'open' }
}
if (failed > 0) {
return { kind: 'failed', code: null, open: intent === 'open' }
}
const last = launches[launches.length - 1]
return last ? { kind: 'launched', worktreeId, agent: last } : { kind: 'open' }
}
+2 -2
View File
@@ -6,8 +6,8 @@ const TTL_MS = 10 * 60_000
let returnTo: { path: string; at: number } | null = null
export function setCloudReturnTo(path: string, now: number = Date.now()): void {
// Only an in-app cloud route, never an arbitrary destination.
returnTo = /^\/cloud\/[A-Za-z0-9_-]+$/.test(path) ? { path, at: now } : null
// Only an in-app cloud route (a workspace id, or a team slug and W-number), never anywhere else.
returnTo = /^\/cloud\/[A-Za-z0-9_-]+(?:\/W-[0-9]+)?$/.test(path) ? { path, at: now } : null
}
export function takeCloudReturnTo(now: number = Date.now()): string | null {
+31 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import { setCloudReturnTo, takeCloudReturnTo } from './cloud-return-to'
import { cloudHostGate, cloudMissingState } from './cloud-screen-states'
import { cloudHostGate, cloudMissingState, cloudNumberLinkState } from './cloud-screen-states'
const base = { isPending: false, isFetching: false, isError: false }
@@ -62,4 +62,34 @@ describe('return after connecting', () => {
setCloudReturnTo('/cloud/sbx_abc', 0)
expect(takeCloudReturnTo(11 * 60_000)).toBeNull()
})
it('returns to a W-number link too, but not to other nested paths', () => {
setCloudReturnTo('/cloud/orca-eval-team/W-589')
expect(takeCloudReturnTo()).toBe('/cloud/orca-eval-team/W-589')
setCloudReturnTo('/cloud/orca-eval-team/settings')
expect(takeCloudReturnTo()).toBeNull()
})
})
describe('W-number link', () => {
it('asks a phone not connected to Orca Cloud to sign in instead of calling it private or deleted', () => {
expect(cloudNumberLinkState({ validLink: true, enrolled: false, sandboxId: null })).toBe(
'signin'
)
})
it('opens the workspace it resolves to, and is missing when it resolves to none', () => {
expect(cloudNumberLinkState({ validLink: true, enrolled: true, sandboxId: 'sbx_1' })).toBe(
'found'
)
expect(cloudNumberLinkState({ validLink: true, enrolled: true, sandboxId: null })).toBe(
'missing'
)
})
it('is missing when the link is malformed, connected or not', () => {
expect(cloudNumberLinkState({ validLink: false, enrolled: false, sandboxId: null })).toBe(
'missing'
)
})
})
+21
View File
@@ -50,3 +50,24 @@ export function cloudHostGate(args: {
}
return args.status === 'sleeping' ? 'asleep' : 'pass'
}
export type CloudNumberLinkState = 'signin' | 'found' | 'missing'
/**
* A W-number link (orca://cloud/<org>/W-123). Only the control plane can say which workspace it
* names, so a phone not connected to Orca Cloud asks to sign in, like a share link does, rather
* than calling the workspace private or deleted. A malformed link is missing either way.
*/
export function cloudNumberLinkState(args: {
validLink: boolean
enrolled: boolean
sandboxId: string | null
}): CloudNumberLinkState {
if (!args.validLink) {
return 'missing'
}
if (!args.enrolled) {
return 'signin'
}
return args.sandboxId ? 'found' : 'missing'
}
+26 -2
View File
@@ -13,9 +13,14 @@ vi.mock('./cloud-workspace-attach', () => ({
import type { Translate } from '../i18n/mobile-i18n'
import { CloudRequestError } from './cloud-control-plane-request'
import { CloudAttachError } from './cloud-workspace-attach'
import { attachErrorMessage, readSnapshotRefusedMessage } from './cloud-workspace-copy'
import {
attachErrorMessage,
createErrorMessage,
readSnapshotRefusedMessage
} from './cloud-workspace-copy'
const t: Translate = (_key, fallback) => fallback
const t: Translate = (_key, fallback, options) =>
fallback.replace(/{{(\w+)}}/g, (_match, name: string) => String(options?.[name] ?? ''))
describe('cloud workspace copy', () => {
it('says a failed wake plainly, and keeps the generic line for anything else', () => {
@@ -39,4 +44,23 @@ describe('cloud workspace copy', () => {
expect(readSnapshotRefusedMessage('unsigned', t)).toBe(unsigned)
expect(readSnapshotRefusedMessage('bad_signature', t)).toBe(unsigned)
})
it('names the repo and the fix when Orca can’t access it (github_not_connected)', () => {
const denied = new CloudRequestError('conflict', 409, 'github_not_connected')
expect(createErrorMessage(denied, t, null, 'https://github.com/stablyai/orca-cloud')).toBe(
'Orca can’t access stablyai/orca-cloud. Check the name. If it’s private, give Orca access to it from Orca on your computer. Nothing was created, and you weren’t charged.'
)
expect(createErrorMessage(denied, t)).toContain('Orca can’t access this repository.')
// Never the generic line it used to fall back to.
expect(createErrorMessage(denied, t, null, 'https://github.com/a/b')).not.toContain(
'Couldn’t start'
)
})
it('names the repo when its clone fails', () => {
const clone = new CloudRequestError('provider_unavailable', 503, 'orcad_start_failed')
expect(createErrorMessage(clone, t, null, 'https://github.com/octocat/Hello-World')).toMatch(
/^Couldn’t clone octocat\/Hello-World\. /
)
})
})
+30 -6
View File
@@ -5,7 +5,7 @@ import { CloudRequestError } from './cloud-control-plane-request'
import type { CloudReadSnapshotRefusedError } from './cloud-read-snapshot'
import { CloudAttachError, type CloudAttachPhase } from './cloud-workspace-attach'
import { entitlementDeniedMessage } from './cloud-entitlement-copy'
import { formatElapsed } from './cloud-workspace-display'
import { cloudRepoLine, formatElapsed } from './cloud-workspace-display'
// What the cloud workspace screen says about each state and failure.
@@ -173,8 +173,11 @@ export function cloudPromptErrorMessage(code: string | undefined, t: Translate):
export function createErrorMessage(
error: unknown,
t: Translate,
role: CloudRole | null = null
role: CloudRole | null = null,
/** The repository URL asked for, so the message names what Orca couldn't reach. */
repoUrl: string | null = null
): string {
const repo = repoUrl ? cloudRepoLine({ repo: { url: repoUrl, branch: null } }) : null
if (error instanceof CloudRequestError) {
if (error.status === 401) {
return t(
@@ -185,11 +188,32 @@ export function createErrorMessage(
if (error.code === 'entitlement_denied') {
return entitlementDeniedMessage(error, role, 'create', t)
}
// Not public, and no GitHub connection covers it (private, or a mistyped name). A phone can't
// connect GitHub, so the fix points at the computer, like the desktop's "Give Orca access".
if (error.reason === 'github_not_connected') {
return repo
? t(
'cloud.error.repoAccess',
'Orca can’t access {{repo}}. Check the name. If it’s private, give Orca access to it from Orca on your computer. Nothing was created, and you weren’t charged.',
{ repo }
)
: t(
'cloud.error.repoAccessUnnamed',
'Orca can’t access this repository. Check the name. If it’s private, give Orca access to it from Orca on your computer. Nothing was created, and you weren’t charged.'
)
}
// The clone runs in a sandbox that already booted (and was metered): it's deleted, not "never created".
if (error.code === 'provider_unavailable' && error.reason === 'orcad_start_failed') {
return t(
'cloud.error.clone',
'Couldn’t clone the repository. Check the name and that the Orca Cloud GitHub app can see it. Nothing was created, and you weren’t charged.'
)
return repo
? t(
'cloud.error.cloneNamed',
'Couldn’t clone {{repo}}. Check the name, and that Orca has access to it (Give Orca access, in Orca on your computer). The sandbox was deleted.',
{ repo }
)
: t(
'cloud.error.cloneDeleted',
'Couldn’t clone the repository. Check the name, and that Orca has access to it (Give Orca access, in Orca on your computer). The sandbox was deleted.'
)
}
if (error.code === 'timeout' || error.code === 'network_error' || error.status >= 500) {
return t(
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest'
import { cloudSandboxHours } from './cloud-workspace-display'
import type { Translate } from '../i18n/mobile-i18n'
import { cloudSandboxHours, cloudSpendLine } from './cloud-workspace-display'
const HOUR = 3_600_000
@@ -11,3 +12,21 @@ describe('cloudSandboxHours', () => {
expect(cloudSandboxHours(0)).toEqual({ value: 0, label: '0' })
})
})
describe('cloudSpendLine', () => {
const t: Translate = (_key, fallback) => fallback
it('says an archived workspace uses no hours, not that it is asleep', () => {
const line = cloudSpendLine({ status: 'archived', sandboxMs: 3_600_000 }, null, false, t)
expect(line).toBe('{{hours}} sandbox hours used. Archived workspaces don’t use sandbox hours.')
})
it('keeps the asleep and running lines', () => {
expect(cloudSpendLine({ status: 'sleeping', sandboxMs: 1 }, null, false, t)).toContain(
'while asleep'
)
expect(cloudSpendLine({ status: 'running', sandboxMs: 1 }, null, true, t)).toContain(
'while running'
)
expect(cloudSpendLine({ status: 'running', sandboxMs: null }, null, true, t)).toBeNull()
})
})
@@ -108,3 +108,51 @@ export function nextCloudWorkspaceTitle(
}
return `${base} ${n}`
}
/** Usage once, honestly: sandbox hours so far (what the plan meters), and whether it is using them
* now. No per-workspace dollars: included hours are not charged. */
export function cloudSpendLine(
workspace: Pick<CloudWorkspace, 'sandboxMs' | 'status'>,
usage: { totalMs: number } | null,
awake: boolean,
t: Translate
): string | null {
const ms = usage ? usage.totalMs : workspace.sandboxMs
if (ms === null) {
return null
}
const { value, label } = cloudSandboxHours(ms)
// Archived is not "asleep" to the user: it can't be woken from here at all.
if (workspace.status === 'archived') {
return t(
'cloud.usage.archived',
'{{hours}} sandbox hours used. Archived workspaces don’t use sandbox hours.',
{
count: value,
hours: label,
defaultValue_one:
'{{hours}} sandbox hour used. Archived workspaces don’t use sandbox hours.'
}
)
}
if (!awake) {
return t(
'cloud.usage.asleep',
'{{hours}} sandbox hours so far. Uses no sandbox hours while asleep.',
{
count: value,
hours: label,
defaultValue_one: '{{hours}} sandbox hour so far. Uses no sandbox hours while asleep.'
}
)
}
return t(
'cloud.usage.running',
'{{hours}} sandbox hours so far. Uses sandbox hours while running.',
{
count: value,
hours: label,
defaultValue_one: '{{hours}} sandbox hour so far. Uses sandbox hours while running.'
}
)
}
+49 -68
View File
@@ -30,6 +30,7 @@ import {
launchCloudPrompt,
type CloudLaunchedAgent
} from './cloud-workspace-host-operations'
import { runCloudDelivery } from './cloud-delivery-run'
import { ownerForCloudError, roleForCloudError } from './cloud-entitlement-copy'
import { cloudWorkspaceProjectRoot } from './cloud-workspace-links'
import { removeHostAndCloseClient } from '../host-catalog/host-removal-lifecycle'
@@ -113,76 +114,56 @@ export function useCloudWorkspaceRun(sandboxId: string, workspace: CloudWorkspac
deliveryStarted.current = run
const client = host.client
const hostId = run.hostId
const intent = run.intent
void (async () => {
try {
const waiting = await listQueuedCloudPrompts(sandboxId)
if (!waiting.some((prompt) => prompt.status !== 'failed')) {
// Nothing to send: the connection is proven, so open the sandbox's workspaces.
if (mountedRef.current) {
setRun({ kind: 'idle' })
router.push(`/h/${hostId}`)
}
return
}
const projectRoot = (await cloudWorkspaceProjectRoot(sandboxId)) ?? undefined
const worktreeId = await ensureCloudProjectWorktree(client, projectRoot)
const launches: CloudLaunchedAgent[] = []
let failed = 0
// Prompts typed while this ran are picked up too, so none is left "waiting" behind it.
for (let round = 0; round < 5; round++) {
const next = await deliverQueuedCloudPrompts(
sandboxId,
async (prompt) => {
launches.push(await launchCloudPrompt(client, worktreeId, prompt))
},
cloudPromptErrorCode
)
failed += next.failed.length
const pending = await listQueuedCloudPrompts(sandboxId)
if (
next.delivered + next.failed.length === 0 ||
!pending.some((prompt) => prompt.status !== 'failed')
) {
break
}
}
invalidate()
if (!mountedRef.current) {
return
}
if (failed > 0) {
const stillQueued = (await listQueuedCloudPrompts(sandboxId)).some(
(prompt) => prompt.status !== 'failed'
)
setRun({
kind: 'error',
message: t(
'cloud.error.deliver',
'The workspace is running, but a prompt didn’t start. Your files are safe.'
),
retry: stillQueued ? 'send' : null
})
return
}
const last = launches[launches.length - 1]
if (last) {
// A cloud agent may still need its sign-in: say what happened before dropping into the
// session, and let the user pick the chat or the terminal.
setRun({ kind: 'launched', hostId, worktreeId, agent: last })
return
}
setRun({ kind: 'idle' })
router.push(`/h/${hostId}`)
} catch (error) {
if (mountedRef.current) {
// Delivery failures are about the prompt, not the sandbox: say which, never "something".
setRun({
kind: 'error',
message: cloudPromptErrorMessage(cloudPromptErrorCode(error), t),
retry: 'send'
})
}
const outcome = await runCloudDelivery(sandboxId, intent, {
listQueued: listQueuedCloudPrompts,
ensureWorktree: async () =>
ensureCloudProjectWorktree(
client,
(await cloudWorkspaceProjectRoot(sandboxId)) ?? undefined
),
launch: (worktreeId, prompt) => launchCloudPrompt(client, worktreeId, prompt),
deliverQueued: deliverQueuedCloudPrompts,
markWaitingFailed: markWaitingCloudPromptsFailed,
errorCodeFor: cloudPromptErrorCode
}).catch((error: unknown) => ({
kind: 'failed' as const,
code: cloudPromptErrorCode(error),
open: intent === 'open'
}))
invalidate()
if (!mountedRef.current) {
return
}
if (outcome.kind === 'launched') {
// A cloud agent may still need its sign-in: say what happened before dropping into the
// session, and let the user pick the chat or the terminal.
setRun({ kind: 'launched', hostId, worktreeId: outcome.worktreeId, agent: outcome.agent })
return
}
if (outcome.kind === 'failed') {
// Delivery failures are about the prompt, not the sandbox: say which, never "something".
// The failed prompts wait in the list with Retry and Remove; nothing retries them here.
setRun({
kind: 'error',
message:
outcome.code === null
? t(
'cloud.error.deliver',
'The workspace is running, but a prompt didn’t start. Your files are safe.'
)
: cloudPromptErrorMessage(outcome.code, t),
retry: null
})
if (!outcome.open) {
return
}
} else {
setRun({ kind: 'idle' })
}
// Nothing (more) to send, or the user asked to open: the connection is proven, so open it.
router.push(`/h/${hostId}`)
})()
}, [run, host.client, host.state, sandboxId, invalidate, router, t, title])
+32
View File
@@ -0,0 +1,32 @@
import { describe, expect, it } from 'vitest'
import { homeFeedLayout } from './home-feed-layout'
const enrollment = {
controlPlaneUrl: 'https://cp.example',
deviceSessionId: 'ds_1',
label: 'iPhone',
enrolledAt: 1
}
describe('homeFeedLayout', () => {
it('waits for the host catalog', () => {
expect(homeFeedLayout({ hostCatalogLoaded: false, hostCount: 0, enrollment })).toBe('loading')
})
it('shows the feed whenever a host is paired', () => {
expect(homeFeedLayout({ hostCatalogLoaded: true, hostCount: 1, enrollment: null })).toBe('feed')
})
it('keeps the Cloud section for an enrolled phone with no desktop paired', () => {
expect(homeFeedLayout({ hostCatalogLoaded: true, hostCount: 0, enrollment })).toBe('feed')
})
it('shows the pairing empty state only to a phone with neither', () => {
expect(homeFeedLayout({ hostCatalogLoaded: true, hostCount: 0, enrollment: null })).toBe(
'pair-desktop'
)
expect(homeFeedLayout({ hostCatalogLoaded: true, hostCount: 0, enrollment: undefined })).toBe(
'loading'
)
})
})
+27
View File
@@ -0,0 +1,27 @@
import type { CloudEnrollment } from '../cloud/cloud-device-identity'
export type HomeFeedLayout = 'loading' | 'pair-desktop' | 'feed'
/**
* The pairing empty state is only for a phone with nothing to show. A phone enrolled in Orca Cloud
* keeps its Cloud section with no desktop paired (unpaired later, or lost): the workspaces are
* reachable from the phone alone.
*/
export function homeFeedLayout(args: {
hostCatalogLoaded: boolean
hostCount: number
/** `undefined` while the keychain read is in flight. */
enrollment: CloudEnrollment | null | undefined
}): HomeFeedLayout {
if (!args.hostCatalogLoaded) {
return 'loading'
}
if (args.hostCount > 0) {
return 'feed'
}
// Wait for the enrollment read rather than flash the pairing screen at an enrolled phone.
if (args.enrollment === undefined) {
return 'loading'
}
return args.enrollment ? 'feed' : 'pair-desktop'
}
+8 -2
View File
@@ -12,6 +12,7 @@ import type { AgentListRowHandlers } from '../../agents/MobileAgentListRows'
import type { HostCatalogEntry } from '../../host-catalog/host-profile'
import { MobileHomeAppUpdateCard } from '../MobileHomeAppUpdateCard'
import { MobileHomeCloudSection } from '../MobileHomeCloudSection'
import { homeFeedLayout } from '../home-feed-layout'
import { MobileHomeEmptyState } from '../MobileHomeEmptyState'
import { MobileHomeHostList } from '../MobileHomeHostList'
import { MobileHomeActiveAgents } from '../MobileHomeActiveAgents'
@@ -52,10 +53,15 @@ export function MobileHomeFeedTab(props: {
}, [data.connectedHosts, data.allClients, cloudHostIds])
const title = <MobileHomeTabHeader title={t('home.tabs.feed', 'Feed')} />
// Keychain reads can outlast the splash; show the title instead of a blank frame.
if (!data.hostCatalogLoaded) {
const layout = homeFeedLayout({
hostCatalogLoaded: data.hostCatalogLoaded,
hostCount: data.hostCatalog.length,
enrollment
})
if (layout === 'loading') {
return title
}
if (data.hostCatalog.length === 0) {
if (layout === 'pair-desktop') {
return (
<MobileHomeEmptyState
contentMaxWidth={contentMaxWidth}
+2
View File
@@ -154,6 +154,8 @@
}
},
"usage": {
"archived_one": "{{hours}} sandbox hour used. Archived workspaces don’t use sandbox hours.",
"archived_other": "{{hours}} sandbox hours used. Archived workspaces don’t use sandbox hours.",
"asleep_one": "{{hours}} sandbox hour so far. Uses no sandbox hours while asleep.",
"asleep_other": "{{hours}} sandbox hours so far. Uses no sandbox hours while asleep.",
"running_one": "{{hours}} sandbox hour so far. Uses sandbox hours while running.",
+8 -3
View File
@@ -5098,12 +5098,15 @@
"failed": "The workspace couldn’t start. Try again, or open it on your desktop.",
"revoked": "This phone’s Orca Cloud access ended. Connect it again from Home.",
"network": "Couldn’t reach Orca Cloud. Check your connection and try again.",
"clone": "Couldn’t clone the repository. Check the name and that the Orca Cloud GitHub app can see it. Nothing was created, and you weren’t charged.",
"createUnknown": "Lost the connection while starting it. It may still appear in your list. Try again to pick it up.",
"rateLimited": "Too many new workspaces at once. Wait a minute, then try again.",
"create": "Couldn’t start your cloud workspace. Nothing was created, and you weren’t charged.",
"deliver": "The workspace is running, but a prompt didn’t start. Your files are safe.",
"restartOwner": "Only the workspace’s owner can restart it. Your files are safe."
"restartOwner": "Only the workspace’s owner can restart it. Your files are safe.",
"repoAccess": "Orca can’t access {{repo}}. Check the name. If it’s private, give Orca access to it from Orca on your computer. Nothing was created, and you weren’t charged.",
"repoAccessUnnamed": "Orca can’t access this repository. Check the name. If it’s private, give Orca access to it from Orca on your computer. Nothing was created, and you weren’t charged.",
"cloneNamed": "Couldn’t clone {{repo}}. Check the name, and that Orca has access to it (Give Orca access, in Orca on your computer). The sandbox was deleted.",
"cloneDeleted": "Couldn’t clone the repository. Check the name, and that Orca has access to it (Give Orca access, in Orca on your computer). The sandbox was deleted."
},
"workspace": {
"title": "Cloud workspace",
@@ -5283,7 +5286,9 @@
"asleep_one": "{{hours}} sandbox hour so far. Uses no sandbox hours while asleep.",
"asleep_other": "{{hours}} sandbox hours so far. Uses no sandbox hours while asleep.",
"running_one": "{{hours}} sandbox hour so far. Uses sandbox hours while running.",
"running_other": "{{hours}} sandbox hours so far. Uses sandbox hours while running."
"running_other": "{{hours}} sandbox hours so far. Uses sandbox hours while running.",
"archived_one": "{{hours}} sandbox hour used. Archived workspaces don’t use sandbox hours.",
"archived_other": "{{hours}} sandbox hours used. Archived workspaces don’t use sandbox hours."
},
"host": {
"asleep": "{{name}} is asleep",
+3 -1
View File
@@ -149,7 +149,9 @@ export function registerCloudSecretsHandlers(userDataPath: string): void {
})
ipcMain.handle('cloudSecrets:effective', (_event, raw: unknown) => {
const request = EffectiveRequest.safeParse(raw ?? {})
return request.success ? attempt(client, (c) => c.effective(request.data.repo, undefined, request.data.workspace)) : invalid
return request.success
? attempt(client, (c) => c.effective(request.data.repo, undefined, request.data.workspace))
: invalid
})
// One desktop-sealed key, unsealed here and sent once to the user's personal Cloud secrets; the
// renderer names it (agent + variable) and never sees the value. Each call is one explicit click.
@@ -14,6 +14,7 @@ import {
CloudWorkspaceListResponseSchema,
CloudWorkspacePresenceResponseSchema,
CloudWorkspaceResponseSchema,
CloudWorkspaceFollowSchema,
OrgPromptsSchema,
type CloudWorkspaceLinkTarget,
type CloudWorkspaceListQuery,
@@ -157,6 +158,9 @@ export function createCloudWorkspacesClient(options: CloudWorkspacesClientOption
async patch(id: string, patch: CloudWorkspacePatch) {
return call('PATCH', ws(id), CloudWorkspaceResponseSchema.extend({}).passthrough(), patch)
},
async follow(id: string, follow: boolean) {
return call(follow ? 'PUT' : 'DELETE', `${ws(id)}/follow`, CloudWorkspaceFollowSchema)
},
async noteSent(id: string) {
await call('POST', `${ws(id)}/sent`, NoteSentSchema, {})
},
@@ -213,6 +213,7 @@ export function createCloudWorkspacesService(deps: {
return reader.read(id)
}),
get: (id: string) => wrap(() => client.get(id)),
follow: (id: string, follow: boolean) => wrap(() => client.follow(id, follow)),
patch: (id: string, patch: CloudWorkspacePatch) =>
wrap(async () => (await client.patch(id, patch)).workspace),
resolveLink: (target: CloudWorkspaceLinkTarget, chatId?: string | null) =>
@@ -76,6 +76,7 @@ export async function readRepoSetupImports(
return {
envVarNames: envNames.names,
...(first ? { installScript: first.setup } : {}),
...(first?.ubuntuNote ? { ubuntuNote: first.ubuntuNote } : {}),
sources
}
}
+9
View File
@@ -193,6 +193,15 @@ export function registerCloudWorkspacesHandlers(
? s.patch(parsed.data.id, parsed.data.patch)
: INVALID
})
handle('cloudWorkspaces:follow', async (args) => {
const parsed = z.object({ id: Id, follow: z.boolean() }).safeParse(args)
const s = await getService()
return !s
? NOT_CONFIGURED
: parsed.success
? s.follow(parsed.data.id, parsed.data.follow)
: INVALID
})
handle('cloudWorkspaces:resolveLink', async (args) => {
const parsed = z
.object({ target: LinkTarget, chatId: ChatId.nullable().optional() })
@@ -67,6 +67,7 @@ describe('createAgentCredentialsClient', () => {
[409, { error: 'broker_in_progress' }],
[429, { error: 'rate_limited' }],
[502, { error: 'broker_unavailable' }],
[502, { error: 'device_auth_disabled' }],
[503, { error: 'no_golden_image' }],
[503, { error: 'not_configured' }],
[401, { error: 'unauthorized' }]
@@ -76,7 +77,7 @@ describe('createAgentCredentialsClient', () => {
return Response.json(body, { status })
})
const codes: string[] = []
for (let i = 0; i < 8; i++) {
for (let i = 0; i < 9; i++) {
const error = await failure(() =>
i < 2 ? client.putClaude(TOKEN) : client.startCodexBroker()
)
@@ -90,6 +91,7 @@ describe('createAgentCredentialsClient', () => {
'broker_in_progress',
'rate_limited',
'broker_unavailable',
'device_auth_disabled',
'no_golden_image',
'not_configured',
'signed_out'
@@ -107,6 +107,7 @@ const SERVER_CODES = new Map<string, OrcaCloudAgentsErrorCode>([
['broker_in_progress', 'broker_in_progress'],
['rate_limited', 'rate_limited'],
['broker_unavailable', 'broker_unavailable'],
['device_auth_disabled', 'device_auth_disabled'],
['no_golden_image', 'no_golden_image'],
['not_configured', 'not_configured']
])
@@ -155,7 +155,6 @@ describe('service: the code from the strip, Settings or the chat UI', () => {
children.push(child)
return child
},
readClaudeEmail: () => null,
openExternal: vi.fn(async () => {}),
broadcast: (setups) => broadcasts.push(setups),
identity: () => 'p1:u1'
@@ -2,8 +2,11 @@
// person pastes it into Orca: the bare `code#state`, or the whole callback URL copied from the address
// bar. Normalized here before it is typed into the waiting `claude setup-token`; never logged or kept.
// Anthropic's codes and states are URL-safe base64 joined by '#'.
const CODE_SHAPE = /^[A-Za-z0-9_-]{8,512}(?:#[A-Za-z0-9_-]{8,512})?$/
// Anthropic's codes and states are URL-safe base64 joined by '#'. RS-1: Claude Code (2.1.323, its
// pasted-code prompt) trims the line, splits it on '#', and refuses anything without both halves
// ("Invalid code. Please make sure the full code was copied."), so a code without its state is refused
// here, before it reaches the CLI.
const CODE_SHAPE = /^[A-Za-z0-9_-]{8,512}#[A-Za-z0-9_-]{8,512}$/
const CALLBACK_HOSTS = new Set([
'platform.claude.com',
'console.anthropic.com',
@@ -13,7 +16,8 @@ const CALLBACK_HOSTS = new Set([
/** The code the CLI expects, or null when the paste isn't one (the caller says so, without echoing it). */
export function normalizeClaudeSetupCode(raw: string): string | null {
const value = raw.trim()
// A code copied across a wrapped line keeps its pieces; URL-safe base64 has no whitespace of its own.
const value = raw.replace(/\s+/g, '')
// A setup-token or API key pasted here is not a sign-in code; it never goes to the CLI's prompt.
if (/^sk-ant-/i.test(value)) {
return null
@@ -30,10 +34,10 @@ export function normalizeClaudeSetupCode(raw: string): string | null {
}
const code = url.searchParams.get('code')
const state = url.searchParams.get('state')
if (!code) {
if (!code || !state) {
return null
}
const joined = state ? `${code}#${state}` : code
const joined = `${code}#${state}`
return CODE_SHAPE.test(joined) ? joined : null
}
return CODE_SHAPE.test(value) ? value : null
@@ -0,0 +1,151 @@
// RS-1: `claude setup-token` output and pasted codes as Claude Code really produces them. Every fixture
// below is built from Claude Code 2.1.323's own bundled source (read from the installed CLI binary, never
// run): the success block is
// ✓ Long-lived authentication token created successfully! (Ink <Text color="success">)
// Your OAuth token (valid for <duration>): (gap: 1 between rows)
// <token> (Ink <Text color="warning">, wraps at width)
// Store this token securely. You won't be able to see it again.
// Use this token by setting: export CLAUDE_CODE_OAUTH_TOKEN=<token>
// the sign-in link is an OSC 8 hyperlink (`assumeSupport: true`) around the dim URL text, the prompt is
// "Paste code here if prompted > ", and a pasted line is trimmed and split on '#': without both halves the
// CLI answers "Invalid code. Please make sure the full code was copied."; a code from another sign-in gets
// "That code is not from this sign-in. Paste the code shown after opening the address above."; a code the
// server refuses gets "That code wasn't accepted. It may be incomplete, expired, …". A pseudo-terminal
// ends every line with CRLF. All tokens and codes here are fake.
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
findAuthorizeUrl,
findSetupToken,
runClaudeSetupToken,
type SetupTokenProcess
} from './claude-setup-token-runner'
import { normalizeClaudeSetupCode } from './claude-setup-code'
const TOKEN = `sk-ant-oat01-${'Zz9_-q'.repeat(16)}`
const AUTHORIZE =
'https://claude.ai/oauth/authorize?code=true&client_id=fake&response_type=code&redirect_uri=https%3A%2F%2Fplatform.claude.com%2Foauth%2Fcode%2Fcallback&state=FAKEstate0123456789'
const ESC = '\u001b'
const green = (text: string) => `${ESC}[32m${text}${ESC}[39m`
const yellow = (text: string) => `${ESC}[33m${text}${ESC}[39m`
const dim = (text: string) => `${ESC}[2m${text}${ESC}[22m`
const osc8 = (url: string, text: string) => `${ESC}]8;;${url}${ESC}\\${text}${ESC}]8;;${ESC}\\`
const crlf = (...lines: string[]) => lines.join('\r\n')
function successBlock(tokenRows: string[]): string {
return crlf(
'',
green('✓ Long-lived authentication token created successfully!'),
'',
'Your OAuth token (valid for 1 year):',
'',
...tokenRows.map(yellow),
'',
dim("Store this token securely. You won't be able to see it again."),
'',
dim('Use this token by setting: export CLAUDE_CODE_OAUTH_TOKEN=<token>'),
''
)
}
describe('findSetupToken on real output (Claude Code 2.1.323)', () => {
it('reads the token from the CRLF, coloured success block, ignoring the "<token>" hint line', () => {
expect(findSetupToken(successBlock([TOKEN]), false)).toBe(TOKEN)
})
it('a token Ink wrapped at the terminal width is joined, never captured cut short', () => {
for (const width of [40, 64, 80]) {
const rows = TOKEN.match(new RegExp(`.{1,${width}}`, 'g')) ?? []
expect(rows.length).toBeGreaterThan(1)
expect(findSetupToken(successBlock(rows), false)).toBe(TOKEN)
}
})
it('a wrapped row padded with trailing spaces (Ink fills the line) still joins', () => {
const rows = [`${TOKEN.slice(0, 50)} `, TOKEN.slice(50)]
expect(findSetupToken(successBlock(rows), false)).toBe(TOKEN)
})
it('a banner before and trailing lines after never extend or replace the token', () => {
const banner = crlf(`${ESC}[?25l${ESC}[2K${ESC}[1G${dim('Welcome to Claude Code')}`, '')
const after = crlf('', `${ESC}[?25h`, 'Press Enter to continue')
expect(findSetupToken(`${banner}${successBlock([TOKEN])}${after}`, false)).toBe(TOKEN)
})
})
describe('findAuthorizeUrl on real output (Claude Code 2.1.323)', () => {
it('finds the link inside its OSC 8 hyperlink, with CRLF around it', () => {
const screen = crlf(
`${dim("Browser didn't open? Use the url below to sign in ")}claude.ai`,
osc8(AUTHORIZE, dim(AUTHORIZE)),
'',
'Paste code here if prompted > '
)
expect(findAuthorizeUrl(screen)).toBe(AUTHORIZE)
})
})
describe('normalizeClaudeSetupCode on real pastes', () => {
const CODE = 'FAKEcode0123456789abcdef#FAKEstate0123456789'
it('takes the bare code#state and the full callback URL, both as code#state', () => {
expect(normalizeClaudeSetupCode(` ${CODE}\r\n`)).toBe(CODE)
expect(
normalizeClaudeSetupCode(
'https://platform.claude.com/oauth/code/callback?code=FAKEcode0123456789abcdef&state=FAKEstate0123456789'
)
).toBe(CODE)
})
it('joins a code copied across a wrapped line', () => {
expect(normalizeClaudeSetupCode('FAKEcode0123\n456789abcdef#FAKEstate01234\r\n56789')).toBe(
CODE
)
})
it('refuses a code without its state (the CLI would answer "Invalid code")', () => {
expect(normalizeClaudeSetupCode('FAKEcode0123456789abcdef')).toBeNull()
expect(
normalizeClaudeSetupCode(
'https://platform.claude.com/oauth/code/callback?code=FAKEcode0123456789abcdef'
)
).toBeNull()
})
})
describe('runClaudeSetupToken: the CLI refusing a pasted code (Claude Code 2.1.323 wording)', () => {
beforeEach(() => vi.useFakeTimers())
afterEach(() => vi.useRealTimers())
for (const refusal of [
'Invalid code. Please make sure the full code was copied.',
'That code is not from this sign-in. Paste the code shown after opening the address above.',
"That code wasn't accepted. It may be incomplete, expired, already used, or from an earlier sign-in attempt. Sign in again to get a new code."
]) {
it(`starts over on "${refusal.slice(0, 32)}…"`, async () => {
let onData: (chunk: string) => void = () => {}
const writes: string[] = []
const child: SetupTokenProcess = {
onData: (listener) => {
onData = listener
},
onExit: () => {},
kill: () => {},
write: (data) => void writes.push(data)
}
const submits: ((code: string) => boolean)[] = []
const onCodeRejected = vi.fn()
const controller = new AbortController()
void runClaudeSetupToken({
spawn: async () => child,
signal: controller.signal,
timeoutMs: 60_000,
onAcceptsCode: (submit) => void submits.push(submit),
onCodeRejected
})
await vi.advanceTimersByTimeAsync(0)
onData(crlf(osc8(AUTHORIZE, AUTHORIZE), 'Paste code here if prompted > '))
expect(submits[0]?.('FAKEcode0123456789abcdef#FAKEstate0123456789')).toBe(true)
await vi.advanceTimersByTimeAsync(200)
onData(crlf('', refusal, 'Paste code here if prompted > '))
expect(onCodeRejected).toHaveBeenCalledTimes(1)
controller.abort()
})
}
})
@@ -51,15 +51,41 @@ const DENIED =
/\baccess_denied\b|authorization (?:request )?(?:was )?denied|sign-?in (?:was )?denied|login (?:was )?denied/i
const AUTHORIZE_HOSTS = new Set(['claude.ai', 'claude.com', 'console.anthropic.com'])
const LINK = /https:\/\/[^\s"'<>]+(?=\s)/g
// The CLI's answer to a pasted code it could not exchange; it then waits for Enter to start over.
const CODE_REJECTED = /code wasn.t accepted|Invalid authorization code|OAuth error/i
// The CLI's answer to a pasted code it could not take; it then waits for Enter to start over. RS-1: the
// wording is Claude Code's own (2.1.323): an exchange the server refused ("That code wasn't accepted…"),
// a paste without both halves ("Invalid code. Please make sure the full code was copied."), and a code
// from another sign-in ("That code is not from this sign-in…").
const CODE_REJECTED =
/code wasn.t accepted|Invalid authorization code|Invalid code\b|code is not from this sign-in|OAuth error/i
// Ink reads a chunk ending in Enter as a paste; the code and the Enter go in separately.
const ENTER_AFTER_CODE_MS = 150
// Long enough to read the rejection; then Enter starts a fresh sign-in (new link, new code).
const RETRY_AFTER_REJECT_MS = 500
function plainText(raw: string): string {
return raw.replace(INLINE_ESCAPE, '').replace(TERMINAL_ESCAPE, '\n')
// RS-1: a pseudo-terminal ends lines with CRLF; one line break, not two (a blank line means a gap).
return raw.replace(/\r\n/g, '\n').replace(INLINE_ESCAPE, '').replace(TERMINAL_ESCAPE, '\n')
}
// RS-1: Claude Code prints the token as one Ink <Text>, which wraps at the terminal's width (2.1.323:
// `Your OAuth token (valid for …):`, the token, then a blank line and `Store this token securely…`).
// Orca's pty is 1000 columns, so it shouldn't wrap; if it ever does, the continuation is the very next
// line and holds only token characters, while the line after the whole token is blank. Join those, so a
// wrapped token is never captured cut short.
// A line that starts a new copy of the token (a repaint) is never a continuation.
const WRAPPED_TOKEN =
/(sk-ant-oat01-[A-Za-z0-9_-]+)[ \t]*\n[ \t]*(?!sk-ant-)([A-Za-z0-9_-]+)[ \t]*(?=\n|$)/g
function joinWrappedToken(plain: string): string {
let joined = plain
for (let pass = 0; pass < 8; pass += 1) {
const next = joined.replace(WRAPPED_TOKEN, '$1$2')
if (next === joined) {
return joined
}
joined = next
}
return joined
}
/**
@@ -68,7 +94,7 @@ function plainText(raw: string): string {
* a repaint never beats the whole one. Exported for tests; callers never log its result.
*/
export function findSetupToken(text: string, final: boolean): string | null {
const plain = plainText(text)
const plain = joinWrappedToken(plainText(text))
let found: string | null = null
for (const match of plain.matchAll(TOKEN_CANDIDATE)) {
const end = (match.index ?? 0) + match[0].length
@@ -46,6 +46,12 @@ describe('startCodexBrokerSession', () => {
expect(updates.at(-1)).toEqual({ phase: 'failed', error: 'not_a_chatgpt_login' })
})
it('RS-3: device-code sign-in turned off on the ChatGPT account keeps its own reason', async () => {
const { session, updates } = harness([{ status: 'failed', error: 'device_auth_disabled' }])
await session.done
expect(updates.at(-1)).toEqual({ phase: 'failed', error: 'device_auth_disabled' })
})
it('cancels the broker when the code expires', async () => {
const { session, updates, client } = harness(
Array.from({ length: 20 }, () => ({ status: 'pending' as const }))
@@ -44,8 +44,13 @@ const POLL_MS = 3_000
const MAX_WAIT_MS = 20 * 60_000
// A transient poll failure is retried; this many in a row ends the setup.
const MAX_POLL_FAILURES = 5
function isBrokerFailure(error: string): error is 'not_a_chatgpt_login' | 'store_failed' {
return error === 'not_a_chatgpt_login' || error === 'store_failed'
function isBrokerFailure(
error: string
): error is 'not_a_chatgpt_login' | 'store_failed' | 'device_auth_disabled' {
// RS-3: device-code sign-in turned off on the ChatGPT account gets its own words, not "couldn't save".
return (
error === 'not_a_chatgpt_login' || error === 'store_failed' || error === 'device_auth_disabled'
)
}
function defaultSleep(ms: number, signal: AbortSignal): Promise<void> {
@@ -9,10 +9,6 @@ import {
import { withCloudBuildDefaults } from '../cloud-build-defaults'
import { getHostedSandboxConfig } from '../hosted-sandbox/hosted-sandbox-config'
import { orcaCloudSandboxIdFor } from '../hosted-sandbox/orca-cloud-sandbox-id'
import {
claudeStateFile,
readClaudeFolderLogin
} from '../claude-accounts/sign-in/claude-account-folder'
import { ensureActiveOrcaProfile } from '../orca-profiles/profile-index-store'
import { getOrcaProfileIndexGeneration } from '../orca-profiles/profile-index-generation'
import { createAgentCredentialsClient } from './agent-credentials-client'
@@ -61,14 +57,6 @@ function broadcast(setups: OrcaCloudAgentSetups): void {
}
}
function readClaudeEmail(): string | null {
try {
return readClaudeFolderLogin(claudeStateFile(process.env.CLAUDE_CONFIG_DIR))?.email ?? null
} catch {
return null
}
}
/** The signed-in Orca user, re-read only when the profile index changes (sign-in, sign-out, switch). */
function orcaIdentityReader(userDataPath: string): () => string | null {
let cached: { generation: number; identity: string | null } | null = null
@@ -110,7 +98,6 @@ function serviceFor(userDataPath: string): OrcaCloudAgentsService {
})
: null,
spawnSetupToken: spawnClaudeSetupTokenPty,
readClaudeEmail,
openExternal: (url) => shell.openExternal(url),
broadcast,
identity: orcaIdentityReader(userDataPath)
@@ -86,7 +86,6 @@ describe('orca cloud agents service', () => {
const service = createOrcaCloudAgentsService({
client,
spawnSetupToken: async () => child,
readClaudeEmail: () => 'a@acme.dev',
openExternal,
broadcast: (setups) => broadcasts.push(setups),
identity
@@ -102,7 +101,7 @@ describe('orca cloud agents service', () => {
}
}
it('captures the setup-token in main and stores it with the local account as label', async () => {
it('captures the setup-token in main and stores it with no label (RS-5: the server names it truly)', async () => {
const { service, child, broadcasts, client, openExternal } = setup()
const reply = service.start('claude')
await tick()
@@ -117,7 +116,8 @@ describe('orca cloud agents service', () => {
child.emit(`Your OAuth token (valid for 1 year):\n\n${TOKEN}\n\nStore this token`)
child.exit()
await tick()
expect(client.putClaude).toHaveBeenCalledWith(TOKEN, 'a@acme.dev')
// RS-5: never this computer's Claude Code email; it may belong to another account.
expect(client.putClaude).toHaveBeenCalledWith(TOKEN, undefined)
expect(service.setups().claude).toEqual({ phase: 'saved' })
expectNoToken(reply, broadcasts, service.setups(), await service.status())
})
@@ -211,7 +211,6 @@ describe('orca cloud agents service', () => {
const service = createOrcaCloudAgentsService({
client: null,
spawnSetupToken: async () => fakeChild(),
readClaudeEmail: () => null,
openExternal: vi.fn(),
broadcast: vi.fn()
})
@@ -29,8 +29,6 @@ import {
export type OrcaCloudAgentsServiceDeps = {
client: AgentCredentialsClient | null
spawnSetupToken: SpawnSetupToken
/** The Claude account signed in on this computer, used as the stored credential's label. */
readClaudeEmail: () => string | null
openExternal: (url: string) => Promise<void>
broadcast: (setups: OrcaCloudAgentSetups) => void
/**
@@ -161,7 +159,8 @@ export function createOrcaCloudAgentsService(deps: OrcaCloudAgentsServiceDeps) {
isSignInUrl: (url) => isProviderSignInUrl('claude', url),
onSetup: (setup) => update('claude', setup),
onToken: async (token) => {
await storeClaude(token, deps.readClaudeEmail(), owner)
// RS-5: no label: this computer's Claude Code email may be another account's; the server names it.
await storeClaude(token, null, owner)
},
onDone: () => {
if (claudeRun === run) {
@@ -2,6 +2,7 @@ import type { OrcaProfileAuthStatus } from '../../../shared/orca-profiles'
import type { ActiveOrcaProfileState } from '../profile-index-store'
import { getOrcaCloudAuthConfig, isOrcaCloudDevAuthEnabled } from './profile-cloud-auth-config'
import { readCloudSession } from '../cloud-session/profile-cloud-session-owner'
import { getReconnectReason } from '../cloud-session/profile-cloud-reconnect-reason'
export function getOrcaProfileAuthStatusFromProfile(
active: ActiveOrcaProfileState,
@@ -48,12 +49,14 @@ export function getOrcaProfileAuthStatusFromProfile(
}
}
const reconnectReason = getReconnectReason(active.profile.id)
return {
activeProfileId: active.profile.id,
configured,
state: 'reconnect-required',
persistence: 'none',
cloud,
...(reconnectReason ? { reconnectReason } : {}),
credentialError:
session.status === 'decrypt-failed' || session.status === 'unreadable'
? session.error
@@ -38,7 +38,9 @@ export class OrcaCloudRequestError extends Error {
// Preserve the server error discriminator so callers can distinguish business 4xx outcomes.
constructor(
public readonly statusCode: number,
public readonly errorCode?: string
public readonly errorCode?: string,
/** Auth's finer `reason` beside `error` (a refused refresh: expired, revoked, sso_required…). */
public readonly reason?: string
) {
super(`orca_cloud_request_failed_${statusCode}`)
this.name = 'OrcaCloudRequestError'
@@ -171,18 +173,23 @@ export function isAmbiguousCloudRequestFailure(error: unknown): boolean {
}
// Proxies, CDNs and gateways answer with HTML; only the auth server's JSON carries a verdict.
async function readCloudErrorCode(response: Response): Promise<string | undefined> {
async function readCloudError(response: Response): Promise<{ error?: string; reason?: string }> {
if (!response.headers.get('content-type')?.toLowerCase().includes('application/json')) {
await cancelUnreadResponseBody(response)
return undefined
return {}
}
try {
const body: unknown = await response.json()
return body && typeof body === 'object' && 'error' in body && typeof body.error === 'string'
? body.error
: undefined
if (!body || typeof body !== 'object') {
return {}
}
return {
...('error' in body && typeof body.error === 'string' ? { error: body.error } : {}),
// Additive: older auth deployments send no reason.
...('reason' in body && typeof body.reason === 'string' ? { reason: body.reason } : {})
}
} catch {
return undefined
return {}
}
}
@@ -199,7 +206,8 @@ async function postJson<T>(url: string, body: unknown, options?: PostJsonOptions
signal: AbortSignal.timeout(options?.timeoutMs ?? CLOUD_REQUEST_TIMEOUT_MS)
})
if (!response.ok) {
throw new OrcaCloudRequestError(response.status, await readCloudErrorCode(response))
const failure = await readCloudError(response)
throw new OrcaCloudRequestError(response.status, failure.error, failure.reason)
}
return (await response.json()) as T
}
@@ -35,7 +35,7 @@ describe('normalizeTeamMfaPolicy', () => {
policy: null,
self: 'on',
setupUrl,
manage: { available: false, pendingMembers: 3, inactiveEnforceAt: 500 }
manage: { available: false, pendingMembers: 3, inactiveEnforceAt: 500, ssoHandled: false }
})
})
@@ -63,6 +63,34 @@ describe('normalizeTeamMfaPolicy', () => {
})
})
describe('single sign-on', () => {
it('reads the delegated state and the team-level flag', () => {
const read = normalizeTeamMfaPolicy(
{
policy: { enforceAt: 200, setAt: 100 },
self: { mfa: 'delegated' },
setupUrl,
available: true,
pendingMembers: 0,
ssoHandled: true
},
API
)
expect(read.self).toBe('delegated')
expect(read.manage?.ssoHandled).toBe(true)
})
it('treats anything but true as not handled', () => {
for (const ssoHandled of [undefined, 'true', 1, null]) {
const read = normalizeTeamMfaPolicy(
{ policy: null, self: { mfa: 'on' }, setupUrl, available: true, ssoHandled },
API
)
expect(read.manage?.ssoHandled).toBe(false)
}
})
})
describe('normalizePendingMembers', () => {
it('keeps members with an email and maps unknown states to off', () => {
expect(
@@ -29,7 +29,14 @@ 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']
const SELF_STATES: readonly OrcaTeamMfaSelfState[] = [
'on',
'off',
'pending',
'blocked',
'unknown',
'delegated'
]
function finiteNumber(value: unknown): number | null {
return typeof value === 'number' && Number.isFinite(value) ? value : null
@@ -80,7 +87,8 @@ export function normalizeTeamMfaPolicy(value: unknown, apiBaseUrl: string): Orca
manage: {
available: record.available,
pendingMembers: pendingMembers ?? 0,
...(inactive !== null ? { inactiveEnforceAt: inactive } : {})
...(inactive !== null ? { inactiveEnforceAt: inactive } : {}),
ssoHandled: record.ssoHandled === true
}
}
: {})
@@ -229,6 +237,9 @@ export async function setOrcaTeamMfaPolicy(
if (errorCode === 'mfa_enforcement_not_entitled') {
return { status: 'not-entitled' }
}
if (errorCode === 'sso_team_needs_notice') {
return { status: 'sso-needs-notice' }
}
}
return unavailable(result)
}
@@ -6,7 +6,10 @@ import type {
OrcaProfileOrgDeleteResult
} from '../../../shared/orca-org-delete'
import { ensureActiveOrcaProfile } from '../profile-index-store'
import { getOrcaCloudAuthConfig, isOrcaCloudDevAuthEnabled } from '../cloud-auth/profile-cloud-auth-config'
import {
getOrcaCloudAuthConfig,
isOrcaCloudDevAuthEnabled
} from '../cloud-auth/profile-cloud-auth-config'
import type { OrcaCloudRequestError } from '../cloud-auth/profile-cloud-client'
import { removeDevOrganization } from '../cloud-auth/profile-cloud-dev-auth'
import { runOrgMemberCall } from './profile-cloud-org-members-service'
@@ -54,7 +54,7 @@ function optionalPictureUrl(value: unknown): string | undefined {
}
}
const MEMBER_MFA: readonly OrcaOrgMemberMfa[] = ['on', 'off', 'pending']
const MEMBER_MFA: readonly OrcaOrgMemberMfa[] = ['on', 'off', 'pending', 'sso']
// Absent for plain members (the server leaves it out); an unknown value is dropped, never guessed.
function normalizeMemberMfa(
@@ -128,7 +128,8 @@ export function normalizeRoster(value: unknown): OrcaOrgMembersRoster {
pendingInvites,
// Malformed roles must not widen UI permissions; the server still authorizes mutations.
viewerRole: normalizeRole(record.viewerRole, 'member'),
canManageMembers: record.canManageMembers === true
canManageMembers: record.canManageMembers === true,
...(record.directoryManaged === true ? { directoryManaged: true } : {})
}
}
@@ -0,0 +1,92 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { OrcaCloudAuthConfig } from '../cloud-auth/profile-cloud-auth-config'
import { OrcaCloudRequestError, refreshOrcaCloudSession } from '../cloud-auth/profile-cloud-client'
import type { OrcaCloudSession } from './profile-cloud-session-store'
import {
getReconnectReason,
reconnectReasonFromRefusal,
rememberReconnectReason
} from './profile-cloud-reconnect-reason'
const base = 'https://auth.test'
const config: OrcaCloudAuthConfig = {
apiBaseUrl: base,
authorizeEndpoint: `${base}/a`,
sessionEndpoint: `${base}/s`,
refreshEndpoint: `${base}/r`,
capabilitiesEndpoint: `${base}/c`,
profileEndpoint: `${base}/p`,
orgEndpoint: `${base}/o`,
logoutEndpoint: `${base}/l`,
relayTokenEndpoint: `${base}/rt`,
connectorTokenEndpoint: `${base}/ct`,
relayDirectorUrl: base,
clientId: 'orca-desktop',
scope: 'openid'
}
const session: OrcaCloudSession = {
accessToken: 'token',
refreshToken: 'refresh',
expiresAt: 0,
capabilities: { flags: {}, refreshedAt: 0 }
}
afterEach(() => {
vi.unstubAllGlobals()
rememberReconnectReason('p1', undefined)
})
async function refusal(body: unknown): Promise<unknown> {
vi.stubGlobal(
'fetch',
vi.fn(
async () =>
new Response(JSON.stringify(body), {
status: 401,
headers: { 'content-type': 'application/json' }
})
)
)
return refreshOrcaCloudSession(config, session).catch((error: unknown) => error)
}
describe('why a sign-in ended', () => {
it('a refused refresh carries auth’s reason beside its error', async () => {
const error = await refusal({ error: 'invalid_refresh_token', reason: 'sso_required' })
expect(error).toBeInstanceOf(OrcaCloudRequestError)
expect(error).toMatchObject({
statusCode: 401,
errorCode: 'invalid_refresh_token',
reason: 'sso_required'
})
})
it('an older auth with no reason, or a non-string one, reads as none', async () => {
expect(await refusal({ error: 'invalid_refresh_token' })).toMatchObject({ reason: undefined })
expect(await refusal({ error: 'invalid_refresh_token', reason: 7 })).toMatchObject({
reason: undefined
})
})
it('only single sign-on is told apart; every other reason stays the generic sign-in-again', () => {
expect(reconnectReasonFromRefusal('sso_required')).toBe('sso-required')
for (const reason of [
'expired',
'signed_out',
'revoked',
'reused',
'something_new',
undefined
]) {
expect(reconnectReasonFromRefusal(reason)).toBeUndefined()
}
})
it('is remembered per profile and cleared by a refusal without one', () => {
rememberReconnectReason('p1', 'sso-required')
expect(getReconnectReason('p1')).toBe('sso-required')
expect(getReconnectReason('p2')).toBeUndefined()
rememberReconnectReason('p1', undefined)
expect(getReconnectReason('p1')).toBeUndefined()
})
})
@@ -0,0 +1,31 @@
// Why auth ended a profile's sign-in, when it said so in a way worth telling the person apart from
// "your session expired". Today that is one case: their team turned on single sign-on, and the
// sign-in they had predates it (refresh refused with `reason: "sso_required"`).
//
// Kept in memory only: after a restart the generic sign-in-again copy shows, which is still true,
// and the sign-in page offers SSO either way.
import type { OrcaProfileReconnectReason } from '../../../shared/orca-profile-reconnect-reason'
const reasons = new Map<string, OrcaProfileReconnectReason>()
/** Auth's `reason` on a refused refresh, mapped to what the app explains; undefined for the rest. */
export function reconnectReasonFromRefusal(
reason: string | undefined
): OrcaProfileReconnectReason | undefined {
return reason === 'sso_required' ? 'sso-required' : undefined
}
export function rememberReconnectReason(
profileId: string,
reason: OrcaProfileReconnectReason | undefined
): void {
if (reason) {
reasons.set(profileId, reason)
} else {
reasons.delete(profileId)
}
}
export function getReconnectReason(profileId: string): OrcaProfileReconnectReason | undefined {
return reasons.get(profileId)
}
@@ -16,6 +16,10 @@ import {
wasRefreshTokenAmbiguouslyAttempted
} from './profile-cloud-refresh-replay-guard'
import { emitOrcaCloudSessionInvalidated } from './profile-cloud-session-invalidation'
import {
reconnectReasonFromRefusal,
rememberReconnectReason
} from './profile-cloud-reconnect-reason'
import {
commitCloudSessionRotation,
readCloudSession,
@@ -65,6 +69,14 @@ function isRefreshTokenRejected(error: unknown): boolean {
)
}
// Kept before the session is cleared, so the status the renderer re-reads already says why.
function rememberRefusalReason(profileId: string, error: unknown): void {
rememberReconnectReason(
profileId,
reconnectReasonFromRefusal(error instanceof OrcaCloudRequestError ? error.reason : undefined)
)
}
const inflightCloudSessionRefreshes = new Map<string, Promise<OrcaCloudSession>>()
class StaleCloudSessionMutationError extends Error {
@@ -218,6 +230,7 @@ export async function readFreshOrcaCloudSession(
}
} catch (error) {
if (isRefreshTokenRejected(error)) {
rememberRefusalReason(active.profile.id, error)
warnIfPossibleRefreshReplay(active.profile.id, userDataPath, session.session)
clearCloudSessionIfUnchanged(active.profile.id, userDataPath, session.session)
return { status: 'reconnect-required' }
@@ -239,6 +252,7 @@ export async function forceRefreshOrcaCloudSession(
}
} catch (error) {
if (isRefreshTokenRejected(error)) {
rememberRefusalReason(active.profile.id, error)
warnIfPossibleRefreshReplay(active.profile.id, userDataPath, session)
clearCloudSessionIfUnchanged(active.profile.id, userDataPath, session)
return { status: 'reconnect-required' }
@@ -41,7 +41,8 @@ describe('normalizeRoster', () => {
{ 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' }
{ userId: 'f', email: 'f@x.dev', role: 'member' },
{ userId: 'g', email: 'g@x.dev', role: 'member', mfa: 'sso' }
]
})
expect(roster.members.map((m) => [m.mfa, m.mfaDeadline])).toEqual([
@@ -51,7 +52,8 @@ describe('normalizeRoster', () => {
['pending', 1_800_000],
['pending', undefined],
[undefined, undefined],
[undefined, undefined]
[undefined, undefined],
['sso', undefined]
])
expect('mfa' in roster.members[5]!).toBe(false)
})
+3
View File
@@ -1,5 +1,6 @@
import type {
CloudWorkspace,
CloudWorkspaceFollow,
CloudWorkspaceGrant,
CloudOrgSlug,
CloudWorkspaceLinkTarget,
@@ -37,6 +38,8 @@ export type CloudWorkspacesApi = {
list: (query: CloudWorkspaceListQuery) => Promise<CloudWorkspaceListResult>
get: (id: string) => Promise<CloudWorkspacesResult<CloudWorkspace>>
patch: (id: string, patch: CloudWorkspacePatch) => Promise<CloudWorkspacesResult<CloudWorkspace>>
/** Follow or unfollow a team workspace (PARITY-FOLLOW): the caller's state and its followers. */
follow: (id: string, follow: boolean) => Promise<CloudWorkspacesResult<CloudWorkspaceFollow>>
/** Resolves either link form; a slug link for another org fails with reason `other_org` and its `orgId`. */
resolveLink: (
target: CloudWorkspaceLinkTarget,
@@ -6,6 +6,7 @@ export const cloudWorkspacesApi = {
list: (query) => ipcRenderer.invoke('cloudWorkspaces:list', query),
get: (id) => ipcRenderer.invoke('cloudWorkspaces:get', { id }),
patch: (id, patch) => ipcRenderer.invoke('cloudWorkspaces:patch', { id, patch }),
follow: (id, follow) => ipcRenderer.invoke('cloudWorkspaces:follow', { id, follow }),
resolveLink: (target, chatId) =>
ipcRenderer.invoke('cloudWorkspaces:resolveLink', { target, chatId }),
openGrant: (id) => ipcRenderer.invoke('cloudWorkspaces:openGrant', { id }),
@@ -11,6 +11,7 @@ import { hasCustomTitleBar } from './app-window-chrome'
import type { AppChromeLayout } from './use-app-chrome-layout'
import { RunActionButton } from '../components/run-actions/RunActionButton'
import { CloudWorkspaceNumberChip } from '../components/cloud-workspaces/CloudWorkspaceNumberChip'
import { CloudWorkspacePeople } from '../components/cloud-workspaces/CloudWorkspacePeople'
export function RightSidebarToggle(): React.JSX.Element {
const t = useTranslate()
@@ -70,7 +71,10 @@ export function TitlebarMainStrip({ layout }: { layout: AppChromeLayout }): Reac
/>
)}
{layout.workspaceChromeActive && !layout.creationLayoutActive && activeWorktreeId ? (
<CloudWorkspaceNumberChip worktreeId={activeWorktreeId} />
<>
<CloudWorkspacePeople worktreeId={activeWorktreeId} />
<CloudWorkspaceNumberChip worktreeId={activeWorktreeId} />
</>
) : null}
{layout.workspaceChromeActive && !layout.creationLayoutActive && activeWorktreeId ? (
<RunActionButton worktreeId={activeWorktreeId} />
@@ -175,16 +175,21 @@ export function UnexpectedSignoutCard(): React.JSX.Element | null {
</div>
<p className="text-sm text-muted-foreground">
{email
{authStatus?.reconnectReason === 'sso-required'
? t(
'auto.components.UnexpectedSignoutCard.7b4d9e1f2a',
'Sign in again as {{value0}} to restore Artifact sharing, Orca Relay, and skill sharing.',
{ value0: email }
'auto.components.UnexpectedSignoutCard.ssoRequired',
'Your team now requires single sign-on. Sign in again and choose Sign in with SSO.'
)
: t(
'auto.components.UnexpectedSignoutCard.5a1c8d3e6f',
'Sign in again to restore Artifact sharing, Orca Relay, and skill sharing.'
)}
: email
? t(
'auto.components.UnexpectedSignoutCard.7b4d9e1f2a',
'Sign in again as {{value0}} to restore Artifact sharing, Orca Relay, and skill sharing.',
{ value0: email }
)
: t(
'auto.components.UnexpectedSignoutCard.5a1c8d3e6f',
'Sign in again to restore Artifact sharing, Orca Relay, and skill sharing.'
)}
</p>
<Collapsible open={expanded} onOpenChange={setExpanded}>
@@ -113,8 +113,10 @@ describe('shared workspaces (D13)', () => {
expect(owner.withoutPersonal).toBe(true)
expect(owner.missing).toEqual(['NPM_TOKEN'])
expect(
cloudPanelSectionsData({ ...base, sharing: { shared: false, ownerName: null, isOwner: true } })
.missing
cloudPanelSectionsData({
...base,
sharing: { shared: false, ownerName: null, isOwner: true }
}).missing
).toEqual([])
})
@@ -250,64 +250,64 @@ export function SecretRequestCard({
density="compact"
/>
) : (
<div data-secret-request-field="" className="flex flex-col gap-1.5">
<Label htmlFor={`${id}-value`} className="sr-only">
{t('secretRequest.valueLabel', 'Value for {{name}}', { name: model.name })}
</Label>
<div className="flex items-start gap-2">
<div
className="min-w-0 flex-1"
onKeyDown={(event) => {
if (event.key === 'Enter' && canSave) {
event.preventDefault()
actions.onAdd()
}
}}
>
<SecretValueInput
id={`${id}-value`}
value={model.value}
onChange={actions.onValueChange}
placeholder={t('secretRequest.valuePlaceholder', 'Value')}
invalid={model.fieldError !== null}
<div data-secret-request-field="" className="flex flex-col gap-1.5">
<Label htmlFor={`${id}-value`} className="sr-only">
{t('secretRequest.valueLabel', 'Value for {{name}}', { name: model.name })}
</Label>
<div className="flex items-start gap-2">
<div
className="min-w-0 flex-1"
onKeyDown={(event) => {
if (event.key === 'Enter' && canSave) {
event.preventDefault()
actions.onAdd()
}
}}
>
<SecretValueInput
id={`${id}-value`}
value={model.value}
onChange={actions.onValueChange}
placeholder={t('secretRequest.valuePlaceholder', 'Value')}
invalid={model.fieldError !== null}
disabled={saving}
describedBy={model.fieldError ? `${errorId} ${helpId}` : helpId}
/>
</div>
<SecretRequestScopeControl
name={model.name}
scopes={model.scopes}
scope={model.scope}
disabled={saving}
describedBy={model.fieldError ? `${errorId} ${helpId}` : helpId}
onChange={actions.onScopeChange}
/>
</div>
<SecretRequestScopeControl
name={model.name}
scopes={model.scopes}
scope={model.scope}
disabled={saving}
onChange={actions.onScopeChange}
/>
{model.fieldError ? (
<p id={errorId} role="alert" className="text-xs text-destructive">
{model.fieldError}
</p>
) : null}
<p id={helpId} className="text-xs leading-5 text-muted-foreground">
{t(
'secretRequest.helpBeforeSave',
'Saves to your Cloud secrets. Commands in this workspace can read it as ${{name}}.',
{ name: model.name }
)}
{model.sharedWorkspace
? ` ${t(
'secretRequest.sharedRepoOnly',
'This workspace is shared, so it only gets repository and shared values.'
)}`
: null}
</p>
{model.suggestedRepo && model.scopes.includes('repo') ? (
<p className="text-xs text-muted-foreground">
{t('secretRequest.repoHint', '{{agent}} suggested Repository', {
agent: agentName
})}
</p>
) : null}
</div>
{model.fieldError ? (
<p id={errorId} role="alert" className="text-xs text-destructive">
{model.fieldError}
</p>
) : null}
<p id={helpId} className="text-xs leading-5 text-muted-foreground">
{t(
'secretRequest.helpBeforeSave',
'Saves to your Cloud secrets. Commands in this workspace can read it as ${{name}}.',
{ name: model.name }
)}
{model.sharedWorkspace
? ` ${t(
'secretRequest.sharedRepoOnly',
'This workspace is shared, so it only gets repository and shared values.'
)}`
: null}
</p>
{model.suggestedRepo && model.scopes.includes('repo') ? (
<p className="text-xs text-muted-foreground">
{t('secretRequest.repoHint', '{{agent}} suggested Repository', {
agent: agentName
})}
</p>
) : null}
</div>
)}
{model.phase === 'failed' ? (
<InlineError
@@ -0,0 +1,29 @@
// Repo-scope write check for the S4-b secret request card (use-secret-request-card.ts), split out to keep that
// hook under the file-length limit.
/** Whether this person can write the workspace repo's scope; asked once per repo per session. */
const repoWriteCache = new Map<string, Promise<boolean>>()
export function canWriteRepo(repoKey: string): Promise<boolean> {
let pending = repoWriteCache.get(repoKey)
if (!pending) {
const api = window.api.cloudSecrets
pending = api
? api.effective({ repo: repoKey }).then(
(result) => result.ok && result.value.caller.canWrite.repo,
() => false
)
: Promise.resolve(false)
// A failed read is retried next time rather than cached as "no".
void pending.then((value) => {
if (!value) {
repoWriteCache.delete(repoKey)
}
})
repoWriteCache.set(repoKey, pending)
}
return pending
}
export function resetSecretRequestCardCachesForTests(): void {
repoWriteCache.clear()
}
@@ -108,7 +108,9 @@ describe('S4-b secret request card', () => {
render(<Harness />)
await act(async () => {})
expect(workspaceSharing).toHaveBeenCalledWith({ runtimeEnvironmentId: 'env-1' })
expect(screen.getByText('This workspace is shared, so it doesn’t get personal secrets.')).toBeTruthy()
expect(
screen.getByText('This workspace is shared, so it doesn’t get personal secrets.')
).toBeTruthy()
expect(screen.queryByLabelText('Value for NPM_TOKEN')).toBeNull()
expect(screen.getByRole('button', { name: 'Add secret' }).getAttribute('aria-disabled')).toBe(
'true'
@@ -29,6 +29,7 @@ import {
} from '../../../../shared/secret-request-contract'
import { cloudWorkspaceSecretsMode } from '@/lib/orca-cloud/cloud-workspace-secrets-mode'
import type { CloudSecretsErrorCode } from '../../../../shared/cloud-secrets/cloud-secrets-wire'
import { canWriteRepo } from './secret-request-repo-write'
import type {
SecretRequestCardActions,
SecretRequestCardModel,
@@ -46,33 +47,7 @@ const TRANSPORT_FAILURES: ReadonlySet<CloudSecretsErrorCode> = new Set([
'unknown'
])
/** Whether this person can write the workspace repo's scope; asked once per repo per session. */
const repoWriteCache = new Map<string, Promise<boolean>>()
function canWriteRepo(repoKey: string): Promise<boolean> {
let pending = repoWriteCache.get(repoKey)
if (!pending) {
const api = window.api.cloudSecrets
pending = api
? api.effective({ repo: repoKey }).then(
(result) => result.ok && result.value.caller.canWrite.repo,
() => false
)
: Promise.resolve(false)
// A failed read is retried next time rather than cached as "no".
void pending.then((value) => {
if (!value) {
repoWriteCache.delete(repoKey)
}
})
repoWriteCache.set(repoKey, pending)
}
return pending
}
export function resetSecretRequestCardCachesForTests(): void {
repoWriteCache.clear()
}
export { resetSecretRequestCardCachesForTests } from './secret-request-repo-write'
function useWorkspaceRepoKey(worktreeId: string | null): string | null {
return useAppStore((state) => {
@@ -220,7 +195,9 @@ export function useSecretRequestCard(args: {
: repoScope
? ['personal', 'repo']
: ['personal']
const effectiveScope: SecretRequestScope = scopes.includes(scope) ? scope : (scopes[0] ?? 'personal')
const effectiveScope: SecretRequestScope = scopes.includes(scope)
? scope
: (scopes[0] ?? 'personal')
const add = useCallback(async () => {
const api = window.api.cloudSecrets
@@ -259,7 +236,17 @@ export function useSecretRequestCard(args: {
requestId,
outcome === 'provided' ? 'saved' : 'savedAfterExpiry'
)
}, [value, local, scopes.length, environmentId, requestId, effectiveScope, repoKey, event.name, t])
}, [
value,
local,
scopes.length,
environmentId,
requestId,
effectiveScope,
repoKey,
event.name,
t
])
const phase: SecretRequestCardPhase =
local === 'saving'
@@ -354,3 +354,9 @@ function AwaitingPane({
</div>
)
}
/** RS-3: device code sign-in is off for this ChatGPT account (a fixable setting: amber, not red). */
export const notSetUpDeviceAuthOff = fixture({
agent: 'codex',
setUp: { setup: { phase: 'failed', error: 'device_auth_disabled' } }
})
@@ -2,7 +2,10 @@
// once" runs the same one-time setup as Settings › Accounts › Orca Cloud (S0) right in the pane,
// and once it's saved the strip offers "Start {{agent}}". Pure: the strip renders what this returns.
import type { Translate } from '@/i18n/use-translate'
import { setupFailureCopy } from '@/components/settings/agent-accounts/orca-cloud-accounts-copy'
import {
setupFailureCopy,
setupFailureTone
} from '@/components/settings/agent-accounts/orca-cloud-accounts-copy'
import type { OrcaCloudAgentSetup } from '../../../../shared/orca-cloud-agents/orca-cloud-agents-wire'
import type { HostAgentSignInAgent } from '../../../../shared/host-agent-sign-in-status'
import { HOST_AGENT_SIGN_IN_AGENT_NAME } from '../../../../shared/host-agent-sign-in-status'
@@ -206,7 +209,7 @@ export function cloudAgentSetupStripModel(args: {
const copy = setupFailureCopy(args.agent, setup.error, t)
return {
...need,
status: 'error',
status: setupFailureTone(setup.error),
title: copy.title,
detail: copy.detail ?? need.detail,
// An expired sign-in: "Open again" starts a fresh one with a new link (main restarts it).
@@ -102,8 +102,8 @@ it.each(['owner', 'admin'] as const)('shows the MFA column to an %s', (viewerRol
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')
expect(cell('member:u-neil').textContent).toBe('2FA on')
expect(cell('member:u-grace').textContent).toBe('2FA 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.
@@ -134,7 +134,7 @@ it('leaves the cell blank, not "off", for a member with no status', () => {
)
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-neil').textContent).toBe('2FA off')
expect(cell('member:u-grace').textContent).toBe('')
})
@@ -154,3 +154,51 @@ it('shows no MFA badge for a member who has not signed in yet', () => {
)!
expect(pending.textContent).toBe('')
})
it('a team its identity provider manages: no role or remove controls, and the row says why', () => {
const managed = teamRows({ ...roster, directoryManaged: true }, 'u-neil')
expect(managed.map((row) => [row.key, row.manageable])).toEqual([
['member:u-neil', false],
['member:u-grace', false]
])
const { container } = render(
<TeamMemberList
rows={managed}
viewerRole="owner"
rowStates={{}}
canLeave
now={Date.UTC(2026, 10, 18)}
onChangeRole={noop}
onMakeOwner={noop}
onRemove={noop}
onResend={noop}
onRevoke={noop}
onLeave={noop}
/>
)
const grace = container.querySelector('[data-team-row="member:u-grace"]')!
// The role is text, not a select, and names the identity provider as its owner.
expect(grace.querySelector('[role="combobox"]')).toBeNull()
expect(grace.querySelector('[title="Managed by your identity provider"]')?.textContent).toBe(
'Member'
)
// Without the flag the owner can still manage the same member.
expect(teamRows(roster, 'u-neil').find((row) => row.key === 'member:u-grace')?.manageable).toBe(
true
)
})
it('shows a member whose two-factor is their identity provider’s as via SSO', () => {
const { container } = renderList(
{
...roster,
members: [
{ ...roster.members[0]!, mfa: 'on' },
{ ...roster.members[1]!, mfa: 'sso' }
]
},
'u-neil'
)
const cell = container.querySelector('[data-team-row="member:u-grace"] [data-team-mfa]')!
expect(cell.textContent).toBe('2FA via SSO')
})

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