mirror of
https://github.com/stablyai/orca.git
synced 2026-11-19 04:23:57 +00:00
Merge remote-tracking branch 'private/cloud/integration' into cloud/w2-squad-p1
This commit is contained in:
@@ -64,8 +64,8 @@ export type PlanCatalog = { team: TeamPlan; enterprise: EnterpriseOffer }
|
||||
export const DEFAULT_PLANS: PlanCatalog = {
|
||||
team: {
|
||||
label: 'Team',
|
||||
monthlyPriceLabel: '$50/seat/mo',
|
||||
annualPriceLabel: '$480/seat/yr',
|
||||
monthlyPriceLabel: '$50 per seat per month',
|
||||
annualPriceLabel: '$480 per seat, billed yearly',
|
||||
monthlyPriceCentsPerSeat: 5000,
|
||||
annualPriceCentsPerSeat: 48000,
|
||||
includedHoursPerSeat: 60,
|
||||
@@ -138,7 +138,8 @@ export function publicOffers(catalog: PlanCatalog) {
|
||||
concurrentSandboxesPerSeat: team.concurrentSandboxesPerSeat,
|
||||
idleSleepMinutes: team.idleSleepMinutes,
|
||||
overageCentsPerHour: team.overageCentsPerHour,
|
||||
defaultSpendCapCents: team.defaultSpendCapCents
|
||||
defaultSpendCapCents: team.defaultSpendCapCents,
|
||||
maxSpendCapCents: team.maxSpendCapCents
|
||||
},
|
||||
enterprise: catalog.enterprise
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ describe('config: tax and plan catalog', () => {
|
||||
it('takes Team numbers and labels and the Enterprise contact from BILLING_PLANS', async () => {
|
||||
const h = await createHarness({
|
||||
BILLING_PLANS: JSON.stringify({
|
||||
team: { includedHoursPerSeat: 40, monthlyPriceLabel: '$45/seat/mo', defaultSpendCapCents: 5000 },
|
||||
team: { includedHoursPerSeat: 40, monthlyPriceLabel: '$45 per seat per month', defaultSpendCapCents: 5000 },
|
||||
enterprise: { contactUrl: 'https://example.test/sales' }
|
||||
})
|
||||
})
|
||||
@@ -33,8 +33,8 @@ describe('config: tax and plan catalog', () => {
|
||||
expect(entitlement.body.offers).toEqual({
|
||||
team: {
|
||||
label: 'Team',
|
||||
monthlyPriceLabel: '$45/seat/mo',
|
||||
annualPriceLabel: '$480/seat/yr',
|
||||
monthlyPriceLabel: '$45 per seat per month',
|
||||
annualPriceLabel: '$480 per seat, billed yearly',
|
||||
monthlyPriceCentsPerSeat: 5000,
|
||||
annualPriceCentsPerSeat: 48000,
|
||||
largeMachineWeight: 1,
|
||||
@@ -42,7 +42,8 @@ describe('config: tax and plan catalog', () => {
|
||||
concurrentSandboxesPerSeat: 3,
|
||||
idleSleepMinutes: 15,
|
||||
overageCentsPerHour: 100,
|
||||
defaultSpendCapCents: 5000
|
||||
defaultSpendCapCents: 5000,
|
||||
maxSpendCapCents: 500_000
|
||||
},
|
||||
enterprise: { label: 'Enterprise', priceLabel: 'Custom', contactUrl: 'https://example.test/sales' }
|
||||
})
|
||||
|
||||
@@ -221,7 +221,7 @@ describe('entitlements, overage and usage', () => {
|
||||
canManageBilling: true,
|
||||
period: { start: PERIOD_START * 1000, end: PERIOD_END * 1000 }
|
||||
})
|
||||
expect(entitlement.body.offers.team).toMatchObject({ monthlyPriceLabel: '$50/seat/mo', annualPriceLabel: '$480/seat/yr' })
|
||||
expect(entitlement.body.offers.team).toMatchObject({ monthlyPriceLabel: '$50 per seat per month', annualPriceLabel: '$480 per seat, billed yearly' })
|
||||
expect(entitlement.body.offers.enterprise).toMatchObject({ label: 'Enterprise', priceLabel: 'Custom' })
|
||||
|
||||
for (let i = 0; i < 4; i++) {
|
||||
|
||||
@@ -160,6 +160,15 @@ describe('Worker-embedded image scripts', () => {
|
||||
const generated = readFileSync(fileURLToPath(new URL('./vm-scripts.generated.ts', import.meta.url).href), 'utf8')
|
||||
expect(generated).toBe(renderVmScriptsModule())
|
||||
})
|
||||
|
||||
it('installs every VM script and makes zsh read the session env hook once', () => {
|
||||
const provision = readFileSync(fileURLToPath(new URL('./provision-golden.sh', import.meta.url).href), 'utf8')
|
||||
const loop = provision.match(/^for name in (.+); do$/m)?.[1].split(' ') ?? []
|
||||
expect(new Set(loop)).toEqual(new Set(VM_SCRIPTS))
|
||||
expect(provision).toContain(
|
||||
"grep -q zz-orca-session-env /etc/zsh/zshenv ||\n echo '[ -r /etc/profile.d/zz-orca-session-env.sh ] && . /etc/profile.d/zz-orca-session-env.sh' | sudo tee -a /etc/zsh/zshenv"
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('agents the image ships', () => {
|
||||
|
||||
@@ -9,6 +9,7 @@ export const VM_SCRIPTS = [
|
||||
'orca-sandbox-drain',
|
||||
'orca-sandbox-env',
|
||||
'orca-session-env.sh',
|
||||
'orca-env',
|
||||
'orca-egress-probe',
|
||||
'orca-image-wipe',
|
||||
'orca-share-proxy',
|
||||
@@ -20,6 +21,8 @@ export const VM_SCRIPTS = [
|
||||
'orca-sandbox-grant',
|
||||
'orca-sandbox-revoke',
|
||||
'orca-sandbox-members',
|
||||
'orca-sandbox-read-snapshot',
|
||||
'orca-read-snapshot.cjs',
|
||||
'orca-git-as',
|
||||
'orca-git-identity',
|
||||
'orcad-boot',
|
||||
|
||||
@@ -209,7 +209,7 @@ if [ -n "${NOVNC_VERSION:-}" ]; then
|
||||
fi
|
||||
|
||||
log 'Orca entry points'
|
||||
for name in orca-sandbox-start orca-sandbox-drain orca-sandbox-env orca-session-env.sh orca-egress-probe orca-image-wipe orca-share-proxy orca-sshd orca-ssh-keys orca-desktop-start orca-desktop-proxy orca-desktop-page.js orca-sandbox-grant orca-sandbox-revoke orca-sandbox-members orca-git-as orca-git-identity orcad-boot git; do
|
||||
for name in orca-sandbox-start orca-sandbox-drain orca-sandbox-env orca-session-env.sh orca-env orca-egress-probe orca-image-wipe orca-share-proxy orca-sshd orca-ssh-keys orca-desktop-start orca-desktop-proxy orca-desktop-page.js orca-sandbox-grant orca-sandbox-revoke orca-sandbox-members orca-sandbox-read-snapshot orca-read-snapshot.cjs orca-git-as orca-git-identity orcad-boot git; do
|
||||
var="ORCA_VM_SCRIPT_${name//[-.]/_}"
|
||||
printf '%s' "${!var}" | base64 -d >"$ORCA_HOME/bin/$name"
|
||||
chmod 0755 "$ORCA_HOME/bin/$name"
|
||||
@@ -238,6 +238,14 @@ if [ -f /etc/bash.bashrc ]; then
|
||||
grep -q zz-orca-session-env /etc/bash.bashrc ||
|
||||
echo '[ -r /etc/profile.d/zz-orca-session-env.sh ] && . /etc/profile.d/zz-orca-session-env.sh' | sudo tee -a /etc/bash.bashrc >/dev/null
|
||||
fi
|
||||
if [ -f /etc/bash.bashrc ]; then
|
||||
# Ubuntu: zsh reads /etc/zsh/zshenv for every shell, so new zsh shells match bash (`orca-env` covers
|
||||
# shells that were already open).
|
||||
sudo install -d -m 0755 /etc/zsh
|
||||
sudo touch /etc/zsh/zshenv
|
||||
grep -q zz-orca-session-env /etc/zsh/zshenv ||
|
||||
echo '[ -r /etc/profile.d/zz-orca-session-env.sh ] && . /etc/profile.d/zz-orca-session-env.sh' | sudo tee -a /etc/zsh/zshenv >/dev/null
|
||||
fi
|
||||
sudo chown -R root:root "$ORCA_HOME"
|
||||
|
||||
log 'smoke: orcad reaches ready on loopback (and warms the V8 compile cache: ~1.5 s off every boot)'
|
||||
|
||||
File diff suppressed because one or more lines are too long
Executable
+85
@@ -0,0 +1,85 @@
|
||||
#!/usr/bin/env bash
|
||||
# Prints shell lines that bring the current shell up to date with this session's cloud env (secrets
|
||||
# saved after the shell started): eval "$(orca-env)" or, in fish: orca-env --fish | source
|
||||
# Reads /dev/shm/orca-env-<uid>/session.env (written by orca-sandbox-env, `NAME=<base64>` lines) and
|
||||
# prints an export for each name, plus an unset for each name in $ORCA_SESSION_ENV_NAMES that is gone.
|
||||
# Never writes a file. Values are single-quoted, so quotes, newlines and $ in them stay literal.
|
||||
set -euo pipefail
|
||||
fish=''
|
||||
case "${1-}" in
|
||||
'') ;;
|
||||
--fish) fish=1 ;;
|
||||
-h | --help)
|
||||
printf 'usage: eval "$(orca-env)" (fish: orca-env --fish | source)\n'
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
printf 'orca-env: unknown option %s\n' "$1" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
# ORCA_SESSION_ENV_FILE is for tests; secrets can't set ORCA_* names.
|
||||
file="${ORCA_SESSION_ENV_FILE:-/dev/shm/orca-env-$(id -u)/session.env}"
|
||||
set -f # names are split below, never globbed
|
||||
# Not written yet (or not a cloud VM): nothing to change, like the shell hook.
|
||||
[ -r "$file" ] || exit 0
|
||||
|
||||
# 'it'\''s' for POSIX shells; fish single quotes escape only \ and '.
|
||||
quote() {
|
||||
local v="$1"
|
||||
if [ -n "$fish" ]; then
|
||||
v="${v//\\/\\\\}"
|
||||
v="${v//\'/\\\'}"
|
||||
printf "'%s'" "$v"
|
||||
else
|
||||
printf "'%s'" "${v//\'/\'\\\'\'}"
|
||||
fi
|
||||
}
|
||||
|
||||
# The control plane's reserved names and prefixes (cloud/apps/sandbox-control/src/secrets.ts; a test
|
||||
# keeps this in sync): a session file never sets what would hijack the shell or Orca's own processes.
|
||||
skip_name() {
|
||||
case "$1" in
|
||||
'' | *[!A-Z0-9_]* | [0-9]*) return 0 ;;
|
||||
LD_* | DYLD_* | ORCA_* | VERCEL_* | BASH_FUNC_* | GIT_CONFIG*) return 0 ;;
|
||||
PATH | HOME | USER | LOGNAME | SHELL | PWD | OLDPWD | LANG | TERM | TMPDIR | IFS | ENV | \
|
||||
BASH_ENV | PS4 | PROMPT_COMMAND | SHELLOPTS | BASHOPTS | NODE_OPTIONS | NODE_PATH | \
|
||||
NODE_EXTRA_CA_CERTS | NODE_TLS_REJECT_UNAUTHORIZED | SSL_CERT_FILE | SSL_CERT_DIR | \
|
||||
CURL_CA_BUNDLE | REQUESTS_CA_BUNDLE | HTTP_PROXY | HTTPS_PROXY | ALL_PROXY | NO_PROXY | \
|
||||
PYTHONPATH | PYTHONSTARTUP | PERL5OPT | RUBYOPT | JAVA_TOOL_OPTIONS | GIT_SSH | \
|
||||
GIT_SSH_COMMAND | GIT_ASKPASS | GIT_EXEC_PATH | GIT_PROXY_COMMAND | SSH_AUTH_SOCK | \
|
||||
GH_TOKEN | GITHUB_TOKEN | CLAUDE_CODE_OAUTH_TOKEN) return 0 ;;
|
||||
esac
|
||||
return 1
|
||||
}
|
||||
|
||||
names=' '
|
||||
while IFS= read -r line || [ -n "$line" ]; do
|
||||
name="${line%%=*}"
|
||||
skip_name "$name" && continue
|
||||
# $(...) drops trailing newlines; the x keeps them.
|
||||
value="$(printf '%s' "${line#*=}" | base64 -d 2>/dev/null; printf x)"
|
||||
value="${value%x}"
|
||||
if [ -n "$fish" ]; then
|
||||
printf 'set -gx %s %s\n' "$name" "$(quote "$value")"
|
||||
else
|
||||
printf 'export %s=%s\n' "$name" "$(quote "$value")"
|
||||
fi
|
||||
names="$names$name "
|
||||
done <"$file"
|
||||
for name in ${ORCA_SESSION_ENV_NAMES-}; do
|
||||
skip_name "$name" && continue
|
||||
case "$names" in *" $name "*) continue ;; esac
|
||||
if [ -n "$fish" ]; then
|
||||
printf 'set -e %s\n' "$name"
|
||||
else
|
||||
printf 'unset %s\n' "$name"
|
||||
fi
|
||||
done
|
||||
names="${names# }"
|
||||
names="${names% }"
|
||||
if [ -n "$fish" ]; then
|
||||
printf 'set -gx ORCA_SESSION_ENV_NAMES %s\n' "$(quote "$names")"
|
||||
else
|
||||
printf 'export ORCA_SESSION_ENV_NAMES=%s\n' "$(quote "$names")"
|
||||
fi
|
||||
@@ -0,0 +1,409 @@
|
||||
#!/usr/bin/env node
|
||||
// Gathers what a sleeping workspace should still show (recent chats per agent session, agent
|
||||
// status, git status/diff summary, PR link) from the running orcad over its local socket, then seals
|
||||
// it to the reader keys the control plane passed, so only ciphertext leaves the VM.
|
||||
// Run by orca-sandbox-read-snapshot right before the drain. Env:
|
||||
// ORCA_READ_SNAPSHOT_ID rsn_<24 hex> ORCA_READ_WORKSPACE_ID sbx_<24 hex>
|
||||
// ORCA_READ_RECIPIENTS JSON [{keyId, publicKeyB64}] ORCA_READ_REASON sleep|rollover
|
||||
// ORCA_USER_DATA_PATH orcad's data dir (orca-runtime.json lives there)
|
||||
// Prints one JSON line: {v:1, snapshotId, workspaceId, nonceB64, ciphertextB64, recipients[], stats}.
|
||||
// Construction (keep in sync with src/shared/cloud-workspaces/read-snapshot.ts in the app):
|
||||
// body = AES-256-GCM(dek, nonce, JSON, AAD "orca-cloud-read-v1:<workspaceId>:<snapshotId>")
|
||||
// wrapped = AES-256-GCM(HKDF-SHA256(X25519(eph, reader), eph||reader, "orca-cloud-read-wrap-v1"),
|
||||
// nonce_i, dek, AAD "orca-cloud-read-wrap-v1:<workspaceId>:<snapshotId>:<keyId>")
|
||||
'use strict'
|
||||
const crypto = require('node:crypto')
|
||||
const fs = require('node:fs')
|
||||
const net = require('node:net')
|
||||
const path = require('node:path')
|
||||
|
||||
const INFO = 'orca-cloud-read-v1'
|
||||
const WRAP_INFO = 'orca-cloud-read-wrap-v1'
|
||||
const PROJECT = '/vercel/sandbox/project'
|
||||
const LIMITS = { sessions: 12, messagesPerSession: 60, messageChars: 4000, changes: 200, commits: 10 }
|
||||
/** Plaintext budget: sealed + base64 it stays under the control plane's 220 kB and the 256 kB stdout cap. */
|
||||
const MAX_PLAIN_BYTES = 150_000
|
||||
const CALL_TIMEOUT_MS = 5_000
|
||||
const TOTAL_BUDGET_MS = 20_000
|
||||
|
||||
function b64(bytes) {
|
||||
return Buffer.from(bytes).toString('base64')
|
||||
}
|
||||
|
||||
function x25519PublicKey(raw) {
|
||||
return crypto.createPublicKey({ key: { kty: 'OKP', crv: 'X25519', x: Buffer.from(raw).toString('base64url') }, format: 'jwk' })
|
||||
}
|
||||
|
||||
function gcmSeal(key, nonce, plain, aad) {
|
||||
const cipher = crypto.createCipheriv('aes-256-gcm', key, nonce)
|
||||
cipher.setAAD(Buffer.from(aad))
|
||||
return Buffer.concat([cipher.update(plain), cipher.final(), cipher.getAuthTag()])
|
||||
}
|
||||
|
||||
/** Seals `payload` (an object) to every recipient; a malformed key is skipped, not fatal. */
|
||||
function seal(payload, recipients, workspaceId, snapshotId) {
|
||||
const scope = `${workspaceId}:${snapshotId}`
|
||||
const dek = crypto.randomBytes(32)
|
||||
const nonce = crypto.randomBytes(12)
|
||||
const ciphertext = gcmSeal(dek, nonce, Buffer.from(JSON.stringify(payload)), `${INFO}:${scope}`)
|
||||
const sealedTo = []
|
||||
for (const recipient of recipients) {
|
||||
const reader = Buffer.from(String(recipient.publicKeyB64 || ''), 'base64')
|
||||
if (reader.length !== 32 || !/^rk_[0-9a-f]{24}$/.test(String(recipient.keyId || ''))) {
|
||||
continue
|
||||
}
|
||||
let shared
|
||||
const eph = crypto.generateKeyPairSync('x25519')
|
||||
try {
|
||||
shared = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: x25519PublicKey(reader) })
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
if (shared.every((byte) => byte === 0)) {
|
||||
continue
|
||||
}
|
||||
const ephRaw = Buffer.from(eph.publicKey.export({ format: 'jwk' }).x, 'base64url')
|
||||
const kek = Buffer.from(crypto.hkdfSync('sha256', shared, Buffer.concat([ephRaw, reader]), WRAP_INFO, 32))
|
||||
const wrapNonce = crypto.randomBytes(12)
|
||||
const wrapped = gcmSeal(kek, wrapNonce, dek, `${WRAP_INFO}:${scope}:${recipient.keyId}`)
|
||||
sealedTo.push({ keyId: recipient.keyId, ephemeralPublicKeyB64: b64(ephRaw), nonceB64: b64(wrapNonce), wrappedKeyB64: b64(wrapped) })
|
||||
}
|
||||
dek.fill(0)
|
||||
return { v: 1, snapshotId, workspaceId, nonceB64: b64(nonce), ciphertextB64: b64(ciphertext), recipients: sealedTo }
|
||||
}
|
||||
|
||||
// --- gathering -------------------------------------------------------------------------------
|
||||
|
||||
/** One request per connection, like the CLI. A streaming method resolves on its first frame. */
|
||||
function rpc(metadata, method, params, timeoutMs = CALL_TIMEOUT_MS) {
|
||||
return new Promise((resolve) => {
|
||||
const transport = (metadata.transports || [metadata.transport]).find((t) => t && (t.kind === 'unix' || t.kind === 'named-pipe'))
|
||||
if (!transport) {
|
||||
resolve(null)
|
||||
return
|
||||
}
|
||||
const socket = net.createConnection(transport.endpoint)
|
||||
const id = crypto.randomUUID()
|
||||
let buffer = ''
|
||||
let done = false
|
||||
const finish = (value) => {
|
||||
if (!done) {
|
||||
done = true
|
||||
clearTimeout(timer)
|
||||
socket.destroy()
|
||||
resolve(value)
|
||||
}
|
||||
}
|
||||
const timer = setTimeout(() => finish(null), timeoutMs)
|
||||
socket.setEncoding('utf8')
|
||||
socket.on('error', () => finish(null))
|
||||
socket.on('close', () => finish(null))
|
||||
socket.on('connect', () => socket.write(`${JSON.stringify({ id, authToken: metadata.authToken, method, params })}\n`))
|
||||
socket.on('data', (chunk) => {
|
||||
buffer += chunk
|
||||
let newline
|
||||
while ((newline = buffer.indexOf('\n')) !== -1) {
|
||||
const line = buffer.slice(0, newline)
|
||||
buffer = buffer.slice(newline + 1)
|
||||
let frame
|
||||
try {
|
||||
frame = JSON.parse(line)
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
if (!frame || frame.id !== id) {
|
||||
continue
|
||||
}
|
||||
finish(frame.ok === true ? frame.result : null)
|
||||
return
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v)
|
||||
const str = (v, max) => (typeof v === 'string' ? v.slice(0, max) : null)
|
||||
const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null)
|
||||
|
||||
function messagesOf(history) {
|
||||
const items = isObj(history) && isObj(history.page) && Array.isArray(history.page.items) ? history.page.items : []
|
||||
const out = []
|
||||
for (const item of items) {
|
||||
const body = isObj(item) && isObj(item.body) ? item.body : null
|
||||
if (!body || body.kind !== 'message' || !Array.isArray(body.blocks)) {
|
||||
continue
|
||||
}
|
||||
const role = body.role
|
||||
if (role !== 'user' && role !== 'assistant' && role !== 'system') {
|
||||
continue
|
||||
}
|
||||
const text = body.blocks
|
||||
.filter((b) => isObj(b) && b.type === 'text' && typeof b.text === 'string')
|
||||
.map((b) => b.text)
|
||||
.join('\n')
|
||||
.trim()
|
||||
if (text) {
|
||||
out.push({ itemId: String(item.itemId).slice(0, 200), role, text: text.slice(0, LIMITS.messageChars), at: num(item.observedAt) ?? 0 })
|
||||
}
|
||||
}
|
||||
return { messages: out, hasOlder: isObj(history) && isObj(history.page) && history.page.hasOlder === true }
|
||||
}
|
||||
|
||||
function gitOf(status, log) {
|
||||
if (!isObj(status) && !isObj(log)) {
|
||||
return null
|
||||
}
|
||||
const entries = isObj(status) && Array.isArray(status.entries) ? status.entries.filter(isObj) : []
|
||||
let added = 0
|
||||
let removed = 0
|
||||
let counted = false
|
||||
const changes = entries.slice(0, LIMITS.changes).map((e) => {
|
||||
const a = num(e.added)
|
||||
const r = num(e.removed)
|
||||
if (a !== null || r !== null) {
|
||||
counted = true
|
||||
}
|
||||
return { path: String(e.path).slice(0, 1024), status: str(e.status, 20) || 'modified', area: str(e.area, 20) || 'unstaged', added: a, removed: r }
|
||||
})
|
||||
for (const e of entries) {
|
||||
added += num(e.added) || 0
|
||||
removed += num(e.removed) || 0
|
||||
}
|
||||
const items = isObj(log) && Array.isArray(log.items) ? log.items.filter(isObj) : []
|
||||
return {
|
||||
branch: isObj(status) && typeof status.branch === 'string' ? status.branch.replace(/^refs\/heads\//, '') : null,
|
||||
head: isObj(status) ? str(status.head, 64) : null,
|
||||
changes,
|
||||
changeCount: entries.length,
|
||||
added: counted ? added : null,
|
||||
removed: counted ? removed : null,
|
||||
commits: items.slice(0, LIMITS.commits).map((c) => ({
|
||||
id: String(c.id).slice(0, 64),
|
||||
subject: String(c.subject ?? '').slice(0, 300),
|
||||
author: str(c.author, 120),
|
||||
at: num(c.timestamp)
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
function prOf(linked) {
|
||||
if (!isObj(linked) || num(linked.number) === null || typeof linked.url !== 'string' || !linked.url.startsWith('https://')) {
|
||||
return null
|
||||
}
|
||||
return {
|
||||
number: linked.number,
|
||||
title: String(linked.title ?? '').slice(0, 300),
|
||||
state: str(linked.state, 20) || 'open',
|
||||
url: linked.url.slice(0, 500),
|
||||
checksStatus: str(linked.checksStatus, 20),
|
||||
checksSummary: str(linked.checksSummary, 200)
|
||||
}
|
||||
}
|
||||
|
||||
const STATUSES = new Set(['working', 'attention', 'idle'])
|
||||
const PANE_PREFIX = 'structured-agent-session-'
|
||||
|
||||
/**
|
||||
* Chats as orcad stores them (agent-session-journal.db, read-only): every session's provider, name
|
||||
* and last turn, open tabs first. The local socket can't stream agentSession.subscribeStatus, and
|
||||
* worktree.ps lists only agents that are live right now, so this is the complete list.
|
||||
*/
|
||||
function storedSessions(dataDir) {
|
||||
let db
|
||||
try {
|
||||
const { DatabaseSync } = require('node:sqlite')
|
||||
db = new DatabaseSync(path.join(dataDir, 'agent-session-journal.db'), { readOnly: true })
|
||||
const open = new Set(db.prepare('SELECT session_id FROM agent_session_tabs').all().map((r) => r.session_id))
|
||||
const out = []
|
||||
for (const row of db.prepare('SELECT session_id, record_json FROM agent_session_records').all()) {
|
||||
let record
|
||||
try {
|
||||
record = JSON.parse(row.record_json)
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
const last = isObj(record.lastTurn) ? record.lastTurn : {}
|
||||
out.push({
|
||||
sessionId: row.session_id,
|
||||
agent: str(record.provider, 40),
|
||||
title: str(record.conversationName, 200) || str(last.prompt, 200),
|
||||
status: last.state === 'running' || last.state === 'submitted' ? 'working' : last.state === 'settled' ? 'idle' : 'unknown',
|
||||
turnOutcome: str(last.outcome, 40),
|
||||
updatedAt: num(record.updatedAt),
|
||||
open: open.has(row.session_id),
|
||||
lastPrompt: str(last.prompt, LIMITS.messageChars),
|
||||
lastReply: str(last.reply, LIMITS.messageChars),
|
||||
lastAt: num(last.at)
|
||||
})
|
||||
}
|
||||
return out
|
||||
} catch {
|
||||
return []
|
||||
} finally {
|
||||
try {
|
||||
db && db.close()
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
/** Live agent rows from worktree.ps, keyed by session id (their status wins over the stored one). */
|
||||
function liveAgents(worktrees) {
|
||||
const out = new Map()
|
||||
for (const w of worktrees) {
|
||||
for (const a of Array.isArray(w.agents) ? w.agents.filter(isObj) : []) {
|
||||
const tab = typeof a.paneKey === 'string' ? a.paneKey.split(':')[0] : ''
|
||||
if (!tab.startsWith(PANE_PREFIX)) {
|
||||
continue
|
||||
}
|
||||
const state = a.mainAgent && typeof a.mainAgent.state === 'string' ? a.mainAgent.state : a.state
|
||||
out.set(tab.slice(PANE_PREFIX.length), {
|
||||
agent: str(a.agentType, 40),
|
||||
title: str(a.conversationName, 200) || str(a.taskTitle, 200) || str(a.displayName, 200),
|
||||
status: state === 'working' ? 'working' : state === 'blocked' || state === 'waiting' || state === 'attention' ? 'attention' : 'idle',
|
||||
updatedAt: num(a.updatedAt)
|
||||
})
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** `call(method, params)` -> result | null. Never throws: a missing piece is left out. */
|
||||
async function gather(call, { workspaceId, snapshotId, reason, now, deadline, listSessions = () => [] }) {
|
||||
const timeLeft = () => deadline - Date.now()
|
||||
const ps = await call('worktree.ps', { limit: 20 })
|
||||
const worktrees = isObj(ps) && Array.isArray(ps.worktrees) ? ps.worktrees.filter(isObj) : []
|
||||
const project = worktrees.find((w) => w.path === PROJECT) || worktrees[0] || null
|
||||
const selector = project && typeof project.path === 'string' ? `path:${project.path}` : `path:${PROJECT}`
|
||||
const [status, log] = await Promise.all([
|
||||
call('git.status', { worktree: selector, includeLineStats: true }),
|
||||
call('git.history', { worktree: selector, limit: LIMITS.commits })
|
||||
])
|
||||
const live = liveAgents(worktrees)
|
||||
const byId = new Map()
|
||||
for (const s of listSessions()) {
|
||||
byId.set(s.sessionId, s)
|
||||
}
|
||||
for (const [sessionId, a] of live) {
|
||||
byId.set(sessionId, { ...(byId.get(sessionId) || { sessionId, open: true }), ...Object.fromEntries(Object.entries(a).filter(([, v]) => v !== null)) })
|
||||
}
|
||||
// Open chats first, then newest activity.
|
||||
const picked = [...byId.values()]
|
||||
.filter((s) => typeof s.sessionId === 'string')
|
||||
.sort((a, b) => Number(Boolean(b.open)) - Number(Boolean(a.open)) || (num(b.updatedAt) || 0) - (num(a.updatedAt) || 0))
|
||||
.slice(0, LIMITS.sessions)
|
||||
const sessions = []
|
||||
for (const s of picked) {
|
||||
const history = timeLeft() > 1_000 ? await call('agentSession.history', { sessionId: s.sessionId, direction: 'tail', limit: LIMITS.messagesPerSession }) : null
|
||||
let { messages, hasOlder } = messagesOf(history)
|
||||
if (messages.length === 0) {
|
||||
// No readable history (or out of time): the stored last turn still says what happened.
|
||||
const at = s.lastAt || s.updatedAt || 0
|
||||
messages = [
|
||||
...(s.lastPrompt ? [{ itemId: `${s.sessionId}:last-prompt`, role: 'user', text: s.lastPrompt, at }] : []),
|
||||
...(s.lastReply ? [{ itemId: `${s.sessionId}:last-reply`, role: 'assistant', text: s.lastReply, at }] : [])
|
||||
]
|
||||
hasOlder = hasOlder || messages.length > 0
|
||||
}
|
||||
sessions.push({
|
||||
sessionId: s.sessionId.slice(0, 200),
|
||||
agent: s.agent || null,
|
||||
title: s.title || null,
|
||||
status: STATUSES.has(s.status) ? s.status : 'unknown',
|
||||
turnOutcome: s.turnOutcome || null,
|
||||
updatedAt: num(s.updatedAt),
|
||||
messages: messages.slice(-LIMITS.messagesPerSession),
|
||||
truncated: hasOlder || messages.length > LIMITS.messagesPerSession
|
||||
})
|
||||
}
|
||||
return {
|
||||
v: 1,
|
||||
workspaceId,
|
||||
snapshotId,
|
||||
capturedAt: now,
|
||||
reason,
|
||||
git: gitOf(status, log),
|
||||
pr: prOf(project && project.linkedPR),
|
||||
sessions
|
||||
}
|
||||
}
|
||||
|
||||
/** Cuts the oldest messages (then long texts, then sessions) until the JSON fits the budget. */
|
||||
function fitToBudget(payload, maxBytes = MAX_PLAIN_BYTES) {
|
||||
const size = () => Buffer.byteLength(JSON.stringify(payload))
|
||||
let guard = 0
|
||||
while (size() > maxBytes && guard++ < 10_000) {
|
||||
const longest = payload.sessions.reduce((best, s) => (!best || s.messages.length > best.messages.length ? s : best), null)
|
||||
if (longest && longest.messages.length > 4) {
|
||||
longest.messages.shift()
|
||||
longest.truncated = true
|
||||
continue
|
||||
}
|
||||
const longText = payload.sessions.flatMap((s) => s.messages).find((m) => m.text.length > 500)
|
||||
if (longText) {
|
||||
longText.text = `${longText.text.slice(0, 500)}…`
|
||||
continue
|
||||
}
|
||||
if (payload.git && payload.git.changes.length > 20) {
|
||||
payload.git.changes = payload.git.changes.slice(0, 20)
|
||||
continue
|
||||
}
|
||||
if (payload.sessions.length > 1) {
|
||||
payload.sessions.pop()
|
||||
continue
|
||||
}
|
||||
payload.sessions = []
|
||||
break
|
||||
}
|
||||
return payload
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const started = Date.now()
|
||||
const env = process.env
|
||||
const snapshotId = env.ORCA_READ_SNAPSHOT_ID || ''
|
||||
const workspaceId = env.ORCA_READ_WORKSPACE_ID || ''
|
||||
if (!/^rsn_[0-9a-f]{24}$/.test(snapshotId) || !/^sbx_[0-9a-f]{24}$/.test(workspaceId)) {
|
||||
process.stderr.write('bad ids\n')
|
||||
process.exit(2)
|
||||
}
|
||||
let recipients
|
||||
try {
|
||||
recipients = JSON.parse(env.ORCA_READ_RECIPIENTS || '[]')
|
||||
} catch {
|
||||
recipients = null
|
||||
}
|
||||
if (!Array.isArray(recipients) || recipients.length === 0) {
|
||||
process.stderr.write('no recipients\n')
|
||||
process.exit(2)
|
||||
}
|
||||
const dataDir = env.ORCA_USER_DATA_PATH || path.join(env.HOME || '', '.orcad-data')
|
||||
let metadata
|
||||
try {
|
||||
metadata = JSON.parse(fs.readFileSync(path.join(dataDir, 'orca-runtime.json'), 'utf8'))
|
||||
} catch {
|
||||
metadata = null
|
||||
}
|
||||
if (!metadata || !metadata.authToken) {
|
||||
process.stderr.write('orcad not running\n')
|
||||
process.exit(3)
|
||||
}
|
||||
const deadline = started + TOTAL_BUDGET_MS
|
||||
const call = (method, params) => rpc(metadata, method, params, Math.max(250, Math.min(CALL_TIMEOUT_MS, deadline - Date.now())))
|
||||
const payload = fitToBudget(
|
||||
await gather(call, { workspaceId, snapshotId, reason: (env.ORCA_READ_REASON || 'sleep').slice(0, 20), now: Date.now(), deadline, listSessions: () => storedSessions(dataDir) })
|
||||
)
|
||||
const out = seal(payload, recipients, workspaceId, snapshotId)
|
||||
// Timing only: counts and sizes would describe the plaintext to the control plane's logs.
|
||||
out.stats = { collectMs: Date.now() - started }
|
||||
process.stdout.write(`${JSON.stringify(out)}\n`)
|
||||
}
|
||||
|
||||
module.exports = { seal, gather, fitToBudget, messagesOf, gitOf, prOf, rpc, storedSessions, liveAgents }
|
||||
|
||||
if (require.main === module) {
|
||||
// A fixed message: an error text could carry workspace content into the control plane's logs.
|
||||
main().catch(() => {
|
||||
process.stderr.write('read snapshot failed\n')
|
||||
process.exit(1)
|
||||
})
|
||||
}
|
||||
@@ -44,7 +44,8 @@ while IFS= read -r line; do
|
||||
OPENAI_MODEL) openai_model="$(printf '%s' "$b64" | base64 -d)" ;;
|
||||
ANTHROPIC_MODEL) anthropic_model="$(printf '%s' "$b64" | base64 -d)" ;;
|
||||
AI_GATEWAY_API_KEY) gateway_key=1 ;;
|
||||
GEMINI_API_KEY) gemini_key=1 ;;
|
||||
GEMINI_API_KEY | GOOGLE_API_KEY) gemini_key="${gemini_key:-gemini-api-key}" ;;
|
||||
GOOGLE_GENAI_USE_VERTEXAI) case "$(printf '%s' "$b64" | base64 -d)" in true | 1) gemini_key=vertex-ai ;; esac ;;
|
||||
# Claude Code asks once per key whether to use ANTHROPIC_API_KEY; it remembers the last 20 chars.
|
||||
ANTHROPIC_API_KEY) anthropic_key_tail="$(printf '%s' "$b64" | base64 -d | tail -c 20)" ;;
|
||||
esac
|
||||
@@ -160,7 +161,9 @@ if (isObject(g)) {
|
||||
general.disableAutoUpdate ??= true
|
||||
general.disableUpdateNag ??= true
|
||||
section(g, "privacy").usageStatisticsEnabled ??= false
|
||||
if (process.env.ORCA_GEMINI_KEY) section(section(g, "security"), "auth").selectedType ??= "gemini-api-key"
|
||||
// gemini-api-key or vertex-ai (GOOGLE_GENAI_USE_VERTEXAI=true with an API key): headless runs
|
||||
// refuse to start without a method ("Invalid auth method selected").
|
||||
if (process.env.ORCA_GEMINI_KEY) section(section(g, "security"), "auth").selectedType ??= process.env.ORCA_GEMINI_KEY
|
||||
if (JSON.stringify(g) !== gBefore) write(geminiSettingsFile, g)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
#!/usr/bin/env bash
|
||||
# Seals a read-only snapshot of this workspace (chats, agent status, git, PR) to the reader keys the
|
||||
# control plane passes, right before the drain. Only ciphertext is printed (one JSON line); see
|
||||
# orca-read-snapshot.cjs. Exit 3: orcad isn't running (nothing to read).
|
||||
set -euo pipefail
|
||||
umask 077
|
||||
ORCA_HOME=/opt/orca
|
||||
export ORCA_USER_DATA_PATH="${ORCA_USER_DATA_PATH:-$HOME/.orcad-data}"
|
||||
node="$(find "$ORCA_HOME/runtime/runtimes" -type f -name node | head -n 1)"
|
||||
[ -n "$node" ] || { echo 'node not found' >&2; exit 1; }
|
||||
exec timeout 35 "$node" "$ORCA_HOME/bin/orca-read-snapshot.cjs"
|
||||
@@ -0,0 +1,45 @@
|
||||
-- Read a sleeping workspace without waking it (gap 5). Every device keeps one X25519 "reader key";
|
||||
-- only the public half is stored here. At each drain the VM seals a compact snapshot (chats, agent
|
||||
-- status, git, PR) to the reader keys allowed to open the workspace; this database keeps only that
|
||||
-- ciphertext and one wrapped content key per reader key, never plaintext.
|
||||
CREATE TABLE IF NOT EXISTS reader_keys (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL,
|
||||
account_id TEXT NOT NULL,
|
||||
dev INTEGER NOT NULL DEFAULT 0,
|
||||
public_key TEXT NOT NULL,
|
||||
device_kind TEXT NOT NULL,
|
||||
device_label TEXT NOT NULL,
|
||||
-- A phone's key dies with its device session (unpair, revoke, member removal).
|
||||
device_session_id TEXT,
|
||||
created_at INTEGER NOT NULL,
|
||||
last_seen_at INTEGER NOT NULL,
|
||||
revoked_at INTEGER,
|
||||
revoked_by TEXT
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS reader_keys_live ON reader_keys (account_id, user_id, public_key) WHERE revoked_at IS NULL;
|
||||
CREATE INDEX IF NOT EXISTS reader_keys_account ON reader_keys (account_id, revoked_at);
|
||||
CREATE INDEX IF NOT EXISTS reader_keys_device_session ON reader_keys (device_session_id);
|
||||
|
||||
-- One snapshot per workspace, replaced at every drain.
|
||||
CREATE TABLE IF NOT EXISTS read_snapshots (
|
||||
sandbox_id TEXT PRIMARY KEY,
|
||||
snapshot_id TEXT NOT NULL,
|
||||
stored_at INTEGER NOT NULL,
|
||||
bytes INTEGER NOT NULL,
|
||||
nonce TEXT NOT NULL,
|
||||
ciphertext TEXT NOT NULL
|
||||
);
|
||||
|
||||
-- The snapshot's content key wrapped to one reader key. Deleting a row is how access is pruned
|
||||
-- (member removed, workspace made private, key revoked) without waking the VM.
|
||||
CREATE TABLE IF NOT EXISTS read_snapshot_keys (
|
||||
sandbox_id TEXT NOT NULL,
|
||||
key_id TEXT NOT NULL,
|
||||
snapshot_id TEXT NOT NULL,
|
||||
ephemeral_public_key TEXT NOT NULL,
|
||||
nonce TEXT NOT NULL,
|
||||
wrapped_key TEXT NOT NULL,
|
||||
PRIMARY KEY (sandbox_id, key_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS read_snapshot_keys_key ON read_snapshot_keys (key_id);
|
||||
@@ -0,0 +1,13 @@
|
||||
-- Per-person agent Source (agent-sources contract §2): "Your sign-in" or "API key", as a default
|
||||
-- (scope 'default'), a per-workspace override (scope = sandbox id), or the one-time sign-in offer answer
|
||||
-- (scope 'offer', source 'accepted'|'declined'). Rows for a sandbox go with it.
|
||||
CREATE TABLE agent_sources (
|
||||
user_id TEXT NOT NULL,
|
||||
account_id TEXT NOT NULL,
|
||||
scope TEXT NOT NULL,
|
||||
agent TEXT NOT NULL CHECK (agent IN ('claude', 'codex')),
|
||||
source TEXT NOT NULL CHECK (source IN ('sign-in', 'key', 'accepted', 'declined')),
|
||||
updated_at INTEGER NOT NULL,
|
||||
PRIMARY KEY (user_id, scope, agent)
|
||||
);
|
||||
CREATE INDEX agent_sources_scope ON agent_sources (scope);
|
||||
@@ -0,0 +1,20 @@
|
||||
-- U22: each session's measured CPU, for internal fair-use review only. Customers keep flat
|
||||
-- sandbox hours: nothing here feeds usage_outbox, billing or any customer-facing route.
|
||||
-- One row per provider session (idempotent); active_cpu_ms stays NULL until Vercel reports it
|
||||
-- after the VM stops, and a cron sweep retries the ones still missing. Additive.
|
||||
CREATE TABLE session_cpu (
|
||||
session_id TEXT PRIMARY KEY,
|
||||
sandbox_id TEXT NOT NULL,
|
||||
account_id TEXT NOT NULL,
|
||||
user_id TEXT,
|
||||
vcpus INTEGER NOT NULL,
|
||||
memory_mb INTEGER,
|
||||
active_cpu_ms INTEGER,
|
||||
wall_ms INTEGER NOT NULL,
|
||||
started_at INTEGER,
|
||||
ended_at INTEGER NOT NULL,
|
||||
fetched_at INTEGER,
|
||||
attempts INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE INDEX session_cpu_account_ended ON session_cpu (account_id, ended_at);
|
||||
CREATE INDEX session_cpu_pending ON session_cpu (ended_at) WHERE active_cpu_ms IS NULL;
|
||||
@@ -0,0 +1,20 @@
|
||||
// Worker mirror of src/shared/agent-credentials/agent-credential-names.ts (agent-sources contract §1);
|
||||
// test/agent-credential-names.test.ts fails if the two lists drift.
|
||||
export type CredentialAgent = 'claude' | 'codex'
|
||||
export const AGENT_CREDENTIAL_NAMES: Record<CredentialAgent, readonly string[]> = {
|
||||
claude: [
|
||||
'ANTHROPIC_API_KEY',
|
||||
'ANTHROPIC_AUTH_TOKEN',
|
||||
'ANTHROPIC_BASE_URL',
|
||||
'ANTHROPIC_MODEL',
|
||||
'ANTHROPIC_SMALL_FAST_MODEL',
|
||||
'CLAUDE_CODE_USE_BEDROCK',
|
||||
'CLAUDE_CODE_USE_VERTEX',
|
||||
'AWS_BEARER_TOKEN_BEDROCK',
|
||||
'ANTHROPIC_VERTEX_PROJECT_ID',
|
||||
'CLOUD_ML_REGION'
|
||||
],
|
||||
codex: ['OPENAI_API_KEY', 'OPENAI_BASE_URL', 'OPENAI_MODEL']
|
||||
}
|
||||
|
||||
export const CREDENTIAL_AGENTS: readonly CredentialAgent[] = ['claude', 'codex']
|
||||
@@ -0,0 +1,183 @@
|
||||
// Agent Source per person (agent-sources contract §2): "Your sign-in" or "API key", per agent, as a
|
||||
// default plus an optional per-workspace override, and the one-time "Use my sign-in" offer answer (D8).
|
||||
// GET /v1/agent-sources[?workspaceId=<sandbox id>]
|
||||
// PUT /v1/agent-sources {agent, source: 'sign-in'|'key'|null, workspaceId?}
|
||||
// PUT /v1/agent-sources/offer {agent, answer: 'accepted'|'declined'}
|
||||
// A sandbox applies its OWNER's effective source: with 'sign-in', that agent's credential names are left
|
||||
// out of the session env (and so out of egress routes, the allowlist and gateway derivation), letting
|
||||
// the agent's own login inside the sandbox win. Variables are never touched.
|
||||
import { z } from 'zod'
|
||||
import { AGENT_CREDENTIAL_NAMES, CREDENTIAL_AGENTS, type CredentialAgent } from './agent-credential-names'
|
||||
import type { SandboxCaller } from './auth'
|
||||
import { memberNamesFor } from './member-names'
|
||||
import { effectiveSecrets } from './secrets'
|
||||
import { getSandbox, type SandboxRow } from './store'
|
||||
|
||||
export type AgentSource = 'sign-in' | 'key'
|
||||
type OfferAnswer = 'unanswered' | 'accepted' | 'declined'
|
||||
const DEFAULT_SCOPE = 'default'
|
||||
const OFFER_SCOPE = 'offer'
|
||||
|
||||
type SourceRow = { scope: string; agent: CredentialAgent; source: string }
|
||||
|
||||
const AgentSchema = z.enum(['claude', 'codex'])
|
||||
export const PutSourceSchema = z
|
||||
.object({
|
||||
agent: AgentSchema,
|
||||
source: z.enum(['sign-in', 'key']).nullable(),
|
||||
workspaceId: z.string().min(1).max(128).optional()
|
||||
})
|
||||
.strict()
|
||||
export const PutOfferSchema = z.object({ agent: AgentSchema, answer: z.enum(['accepted', 'declined']) }).strict()
|
||||
|
||||
export class AgentSourceError extends Error {
|
||||
constructor(
|
||||
readonly status: 400 | 403 | 404,
|
||||
readonly code: string,
|
||||
readonly reason?: string
|
||||
) {
|
||||
super(reason ? `${code}:${reason}` : code)
|
||||
}
|
||||
}
|
||||
|
||||
async function rowsFor(db: D1Database, userId: string, scopes: string[]): Promise<SourceRow[]> {
|
||||
const { results } = await db
|
||||
.prepare(`SELECT scope, agent, source FROM agent_sources WHERE user_id = ? AND scope IN (${scopes.map(() => '?').join(', ')})`)
|
||||
.bind(userId, ...scopes)
|
||||
.all<SourceRow>()
|
||||
return results
|
||||
}
|
||||
|
||||
function byAgent(rows: SourceRow[], scope: string): Record<CredentialAgent, AgentSource | null> {
|
||||
const out = { claude: null, codex: null } as Record<CredentialAgent, AgentSource | null>
|
||||
for (const row of rows) {
|
||||
if (row.scope === scope && (row.source === 'sign-in' || row.source === 'key')) {
|
||||
out[row.agent] = row.source
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** Agents whose owner chose "Your sign-in" for this sandbox (override first, then default). */
|
||||
export async function signInAgentsFor(db: D1Database, row: Pick<SandboxRow, 'id' | 'user_id'>): Promise<Set<CredentialAgent>> {
|
||||
const rows = await rowsFor(db, row.user_id, [row.id, DEFAULT_SCOPE])
|
||||
const workspace = byAgent(rows, row.id)
|
||||
const defaults = byAgent(rows, DEFAULT_SCOPE)
|
||||
return new Set(CREDENTIAL_AGENTS.filter((agent) => (workspace[agent] ?? defaults[agent]) === 'sign-in'))
|
||||
}
|
||||
|
||||
/** Drops the credential names of agents on "Your sign-in" (after preset derivation, so derived ones go too). */
|
||||
export function withoutSignInCredentials<T extends Record<string, unknown>>(env: T, signIn: ReadonlySet<CredentialAgent>): T {
|
||||
if (signIn.size === 0) {
|
||||
return env
|
||||
}
|
||||
const next: Record<string, unknown> = { ...env }
|
||||
for (const agent of signIn) {
|
||||
for (const name of AGENT_CREDENTIAL_NAMES[agent]) {
|
||||
delete next[name]
|
||||
}
|
||||
}
|
||||
return next as T
|
||||
}
|
||||
|
||||
/** Some agent key the caller's sessions would get covers this agent (the gateway key covers both). */
|
||||
function coveredByKey(names: ReadonlySet<string>): Record<CredentialAgent, boolean> {
|
||||
const gateway = names.has('AI_GATEWAY_API_KEY')
|
||||
return {
|
||||
claude: gateway || ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'AWS_BEARER_TOKEN_BEDROCK', 'CLAUDE_CODE_USE_BEDROCK', 'CLAUDE_CODE_USE_VERTEX'].some((n) => names.has(n)),
|
||||
codex: gateway || names.has('OPENAI_API_KEY')
|
||||
}
|
||||
}
|
||||
|
||||
async function ownedWorkspace(db: D1Database, caller: SandboxCaller, workspaceId: string): Promise<SandboxRow> {
|
||||
const row = await getSandbox(db, workspaceId)
|
||||
if (!row || row.account_id !== caller.accountId || row.status === 'destroyed') {
|
||||
throw new AgentSourceError(404, 'not_found')
|
||||
}
|
||||
return row
|
||||
}
|
||||
|
||||
export async function agentSourcesView(db: D1Database, caller: SandboxCaller, workspaceId: string | null) {
|
||||
const row = workspaceId ? await ownedWorkspace(db, caller, workspaceId) : null
|
||||
// The sandbox applies its owner's choice (shared sandboxes, v1): show the owner's, not the caller's.
|
||||
const subject = row ? row.user_id : caller.userId
|
||||
const rows = await rowsFor(db, subject, [DEFAULT_SCOPE, OFFER_SCOPE, ...(row ? [row.id] : [])])
|
||||
const defaults = byAgent(rows, DEFAULT_SCOPE)
|
||||
const workspace = row ? byAgent(rows, row.id) : null
|
||||
const effective = await effectiveSecrets(db, caller, row?.repo_url ?? null)
|
||||
const covered = coveredByKey(new Set(effective.map((secret) => secret.name)))
|
||||
const offerRows = rows.filter((r) => r.scope === OFFER_SCOPE)
|
||||
const signInOffer = Object.fromEntries(
|
||||
CREDENTIAL_AGENTS.map((agent) => [
|
||||
agent,
|
||||
(offerRows.find((r) => r.agent === agent)?.source as OfferAnswer | undefined) ?? 'unanswered'
|
||||
])
|
||||
) as Record<CredentialAgent, OfferAnswer>
|
||||
const resolved = Object.fromEntries(
|
||||
CREDENTIAL_AGENTS.map((agent) => {
|
||||
const chosen = workspace?.[agent] ?? null
|
||||
if (chosen) {
|
||||
return [agent, { source: chosen, origin: 'workspace' }]
|
||||
}
|
||||
if (defaults[agent]) {
|
||||
return [agent, { source: defaults[agent], origin: 'default' }]
|
||||
}
|
||||
return [agent, { source: covered[agent] ? 'key' : null, origin: 'implicit' }]
|
||||
})
|
||||
)
|
||||
let owner: { userId: string; displayName: string | null; isCaller: boolean } | null = null
|
||||
if (row) {
|
||||
const names = await memberNamesFor(db, caller.accountId, [row.user_id])
|
||||
owner = { userId: row.user_id, displayName: names.get(row.user_id) ?? null, isCaller: row.user_id === caller.userId }
|
||||
}
|
||||
return { defaults, workspace, effective: resolved, coveredByKey: covered, signInOffer, owner }
|
||||
}
|
||||
|
||||
async function upsert(db: D1Database, caller: SandboxCaller, scope: string, agent: CredentialAgent, source: string | null, now: number) {
|
||||
if (source === null) {
|
||||
await db.prepare('DELETE FROM agent_sources WHERE user_id = ? AND scope = ? AND agent = ?').bind(caller.userId, scope, agent).run()
|
||||
return
|
||||
}
|
||||
await db
|
||||
.prepare(
|
||||
`INSERT INTO agent_sources (user_id, account_id, scope, agent, source, updated_at) VALUES (?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT (user_id, scope, agent) DO UPDATE SET source = excluded.source, account_id = excluded.account_id, updated_at = excluded.updated_at`
|
||||
)
|
||||
.bind(caller.userId, caller.accountId, scope, agent, source, now)
|
||||
.run()
|
||||
}
|
||||
|
||||
/** Returns the sandbox whose session env must refresh (a running one whose owner's source changed), if any. */
|
||||
export async function putAgentSource(db: D1Database, caller: SandboxCaller, body: z.infer<typeof PutSourceSchema>, now: number) {
|
||||
let row: SandboxRow | null = null
|
||||
if (body.workspaceId) {
|
||||
row = await ownedWorkspace(db, caller, body.workspaceId)
|
||||
if (row.user_id !== caller.userId) {
|
||||
throw new AgentSourceError(403, 'forbidden', 'owner_only')
|
||||
}
|
||||
}
|
||||
// D9: accepted while the sandbox is still starting; its first boot reads the row.
|
||||
await upsert(db, caller, row ? row.id : DEFAULT_SCOPE, body.agent, body.source, now)
|
||||
return row
|
||||
}
|
||||
|
||||
export async function putOfferAnswer(db: D1Database, caller: SandboxCaller, body: z.infer<typeof PutOfferSchema>, now: number) {
|
||||
await upsert(db, caller, OFFER_SCOPE, body.agent, body.answer, now)
|
||||
}
|
||||
|
||||
/** Running sandboxes of this person that a default change affects (no workspace override for that agent). */
|
||||
export async function runningSandboxesForDefault(db: D1Database, userId: string, agent: CredentialAgent): Promise<SandboxRow[]> {
|
||||
const { results } = await db
|
||||
.prepare(
|
||||
`SELECT s.* FROM sandboxes s WHERE s.user_id = ? AND s.status = 'running'
|
||||
AND NOT EXISTS (SELECT 1 FROM agent_sources a WHERE a.user_id = s.user_id AND a.scope = s.id AND a.agent = ?)
|
||||
LIMIT 200`
|
||||
)
|
||||
.bind(userId, agent)
|
||||
.all<SandboxRow>()
|
||||
return results
|
||||
}
|
||||
|
||||
export async function deleteAgentSourcesForSandbox(db: D1Database, sandboxId: string): Promise<void> {
|
||||
await db.prepare('DELETE FROM agent_sources WHERE scope = ?').bind(sandboxId).run()
|
||||
}
|
||||
@@ -32,6 +32,7 @@
|
||||
// Operator (OPERATOR_TOKEN): /v1/internal/* (see operator.ts)
|
||||
// Public share links (src/share-gateway.ts): /s/<token>/*, plus the root-path cookie fallback
|
||||
// Vercel network-policy forwardURL target (Vercel sandbox OIDC): /v1/egress/proxy
|
||||
import { ReadSnapshotRouteError, getReadSnapshot, handleReaderKeysRoute, pruneReadSnapshotToOwner, revokeDeviceSessionReaderKeys } from './read-snapshots'
|
||||
import { refreshStaleEnvironments } from './environment-golden-refresh'
|
||||
import { ORCA_CLOUD_IDLE_SLEEP_MINUTES } from '../../../../src/shared/hosted-sandbox/hosted-sandbox-wire'
|
||||
import { z } from 'zod'
|
||||
@@ -89,12 +90,21 @@ import { GuardrailError, consumeCreateToken, guardrailsFromEnv } from './guardra
|
||||
import { handleOperator, isOperator } from './operator'
|
||||
import { DEFAULT_RETENTION, type RetentionConfig } from './retention'
|
||||
import { reconcile } from './reconcile'
|
||||
import { egressSecretHosts, secretPlaceholder } from './secret-egress'
|
||||
import { egressSecretHosts, placeholderValues, secretPlaceholder } from './secret-egress'
|
||||
import { SecretError, handleSecretsRoute, keyringFor, type SecretChange } from './secrets'
|
||||
import { refreshAfterSecretChange, refreshSandboxEnv } from './env-refresh'
|
||||
import {
|
||||
AgentSourceError,
|
||||
PutOfferSchema,
|
||||
PutSourceSchema,
|
||||
agentSourcesView,
|
||||
putAgentSource,
|
||||
putOfferAnswer,
|
||||
runningSandboxesForDefault
|
||||
} from './agent-sources'
|
||||
import { EgressHostsSchema, egressUserHosts, normalizeUserHosts, setEgressUserHosts } from './egress-hosts'
|
||||
import { cachedProviderEnv } from './session-env'
|
||||
import { credentialTargets } from './provider-env'
|
||||
import { credentialTargets, type CredentialTarget } from './provider-env'
|
||||
import type { Keyring } from './secrets-crypto'
|
||||
import { ProviderError, type SandboxProviderApi } from './sandbox-provider'
|
||||
import { DesktopCommandError, VmCommandError, startDesktop } from './sandbox-vm-commands'
|
||||
@@ -150,12 +160,14 @@ import {
|
||||
isOrgAdmin,
|
||||
listWorkspaces,
|
||||
patchWorkspace,
|
||||
assertCanManageWorkspace,
|
||||
reportPresence,
|
||||
requireVisible,
|
||||
resolveLink,
|
||||
workspaceViews
|
||||
} from './workspaces'
|
||||
import { rememberCallerName } from './member-names'
|
||||
import { sweepSessionCpu } from './session-cpu'
|
||||
import type { SandboxCaller } from './auth'
|
||||
|
||||
const MAX_JSON_BYTES = 16 * 1024
|
||||
@@ -251,17 +263,7 @@ function egressRoutes(env: Env, deps: Deps): (row: SandboxRow, host: string) =>
|
||||
: null
|
||||
}
|
||||
})
|
||||
return async (row, host) => {
|
||||
if (host === 'github.com') {
|
||||
return members.routes(row, host)
|
||||
}
|
||||
if (host === 'api.github.com') {
|
||||
return [
|
||||
// Members first: a member placeholder must never fall through to the app's token.
|
||||
...(await members.routes(row, host)),
|
||||
{ header: 'authorization', placeholders: githubPlaceholderHeaders(row), credential: () => broker.authorizationFor(row, host) }
|
||||
]
|
||||
}
|
||||
const secretRoutes = (row: SandboxRow, host: string): ProxiedRoute[] => {
|
||||
const entries = egressSecretHosts(row).filter((candidate) => candidate.host === host)
|
||||
const keyring = keyringFor(env)
|
||||
if (entries.length === 0 || !keyring) {
|
||||
@@ -270,7 +272,7 @@ function egressRoutes(env: Env, deps: Deps): (row: SandboxRow, host: string) =>
|
||||
return entries.flatMap((entry) =>
|
||||
Object.entries(entry.headers).map(([header, format]): ProxiedRoute => ({
|
||||
header,
|
||||
placeholders: [format(secretPlaceholder(row, entry.secret))],
|
||||
placeholders: placeholderValues(entry, header, secretPlaceholder(row, entry.secret)),
|
||||
label: entry.secret,
|
||||
...(entry.paths ? { pathAllowed: requestMatches(entry.paths) } : {}),
|
||||
...(entry.keepResponseFields ? { keepResponseFields: entry.keepResponseFields } : {}),
|
||||
@@ -287,13 +289,34 @@ function egressRoutes(env: Env, deps: Deps): (row: SandboxRow, host: string) =>
|
||||
}))
|
||||
)
|
||||
}
|
||||
return async (row, host) => {
|
||||
if (host === 'github.com') {
|
||||
return members.routes(row, host)
|
||||
}
|
||||
if (host === 'api.github.com') {
|
||||
return [
|
||||
// Members first: a member placeholder must never fall through to the app's token.
|
||||
...(await members.routes(row, host)),
|
||||
{ header: 'authorization', placeholders: githubPlaceholderHeaders(row), credential: () => broker.authorizationFor(row, host) },
|
||||
// A user's own GitHub token for Copilot CLI (COPILOT_GITHUB_TOKEN), on its own placeholder.
|
||||
...secretRoutes(row, host)
|
||||
]
|
||||
}
|
||||
return secretRoutes(row, host)
|
||||
}
|
||||
}
|
||||
|
||||
/** Exact method and path (the query string is ignored). */
|
||||
function requestMatches(allowed: readonly { method: string; path: string }[]): (method: string, path: string) => boolean {
|
||||
/** Method and path (the query string is ignored); a prefix entry matches below a normalized path only. */
|
||||
function requestMatches(allowed: NonNullable<CredentialTarget['paths']>): (method: string, path: string) => boolean {
|
||||
return (method, path) => {
|
||||
const pathname = path.split('?')[0]
|
||||
return allowed.some((entry) => entry.method === method.toUpperCase() && entry.path === pathname)
|
||||
const pathname = path.split('?')[0] ?? ''
|
||||
// A prefix grant never stretches across encoded or dot segments into another API.
|
||||
const plain = /^(\/[A-Za-z0-9._~-]+)+\/?$/.test(pathname) && !/(^|\/)\.\.?(\/|$)/.test(pathname)
|
||||
return allowed.some(
|
||||
(entry) =>
|
||||
entry.method === method.toUpperCase() &&
|
||||
(entry.prefix ? plain && pathname.startsWith(entry.path) : entry.path === pathname)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -890,6 +913,14 @@ export async function handleRequest(request: Request, env: Env, deps: Deps = {})
|
||||
const state = await createConnectState(env.SANDBOX_DB, connect.stateSecret, { accountId: `dev:${sub}`, userId: sub }, (deps.now ?? Date.now)())
|
||||
return Response.redirect(authorizeUrl(connect, url.origin, state), 302)
|
||||
}
|
||||
if (url.pathname === '/v1/reader-keys' || url.pathname.startsWith('/v1/reader-keys/')) {
|
||||
const now = (deps.now ?? Date.now)()
|
||||
const caller = await authenticateDesktop(env, request, now)
|
||||
if (!caller) {
|
||||
return fail('unauthorized', 401)
|
||||
}
|
||||
return await handleReaderKeysRoute(request, url, { db: env.SANDBOX_DB, caller, now, readJson: () => readJson(request) })
|
||||
}
|
||||
if (url.pathname === '/v1/device-sessions' || url.pathname.startsWith('/v1/device-sessions/')) {
|
||||
const now = (deps.now ?? Date.now)()
|
||||
const caller = await authenticateDesktop(env, request, now)
|
||||
@@ -905,6 +936,10 @@ export async function handleRequest(request: Request, env: Env, deps: Deps = {})
|
||||
onRevoked:
|
||||
deps.onDeviceSessionRevoked ??
|
||||
(async (deviceSessionId) => {
|
||||
// Its reader key: independent of the grant cleanup below, so neither failure blocks the other.
|
||||
await revokeDeviceSessionReaderKeys(env.SANDBOX_DB, deviceSessionId, now).catch((error: unknown) =>
|
||||
console.log(JSON.stringify({ event: 'device_reader_key_revoke_failed', id: deviceSessionId, error: String(error).slice(0, 120) }))
|
||||
)
|
||||
const life = await lifecycleDeps(env, deps)
|
||||
if (life) {
|
||||
await revokeGrantsForDeviceSession(life, deviceSessionId)
|
||||
@@ -1048,6 +1083,16 @@ export async function handleRequest(request: Request, env: Env, deps: Deps = {})
|
||||
}
|
||||
return response
|
||||
}
|
||||
if (url.pathname === '/v1/agent-sources' || url.pathname === '/v1/agent-sources/offer') {
|
||||
const caller = await authenticateDesktop(env, request, (deps.now ?? Date.now)())
|
||||
if (!caller) {
|
||||
return fail('unauthorized', 401)
|
||||
}
|
||||
if (caller.deviceSessionId) {
|
||||
return fail('forbidden', 403, 'device_session')
|
||||
}
|
||||
return await agentSourcesRoute(request, url, env, deps, caller)
|
||||
}
|
||||
if (isEnvironmentRoute(url.pathname)) {
|
||||
const caller = await authenticateDesktop(env, request, (deps.now ?? Date.now)())
|
||||
if (!caller) {
|
||||
@@ -1337,7 +1382,7 @@ async function workspaceRoute(request: Request, url: URL, env: Env, deps: Deps,
|
||||
if (url.pathname === '/v1/team/workspaces') {
|
||||
return request.method === 'GET' ? json(await listWorkspaces(db, caller, url, now)) : fail('not_found', 404)
|
||||
}
|
||||
const match = /^\/v1\/team\/workspaces\/(sbx_[0-9a-f]{24})(?:\/(presence|wake|lease|grants|sent)(?:\/(grt_[0-9a-f]{24}))?)?$/.exec(url.pathname)
|
||||
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)
|
||||
if (!match) {
|
||||
return fail('not_found', 404)
|
||||
}
|
||||
@@ -1348,6 +1393,16 @@ async function workspaceRoute(request: Request, url: URL, env: Env, deps: Deps,
|
||||
if (route === 'GET ') {
|
||||
return json({ workspace: await view() })
|
||||
}
|
||||
if (route === 'GET read-snapshot') {
|
||||
try {
|
||||
return json(await getReadSnapshot(db, caller, row, url.searchParams.get('keyId'), now))
|
||||
} catch (error) {
|
||||
if (error instanceof ReadSnapshotRouteError) {
|
||||
return fail(error.code, error.status)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
if (route === 'POST sent') {
|
||||
// The caller's own client: "I just sent a message here" (opens their git-as-sender window).
|
||||
if (!canOpen(caller, row)) {
|
||||
@@ -1374,15 +1429,37 @@ async function workspaceRoute(request: Request, url: URL, env: Env, deps: Deps,
|
||||
return fail('invalid_request', 400)
|
||||
}
|
||||
const { archived, ...rest } = body.data
|
||||
// Archive/unarchive are lifecycle changes, not labels: the sandbox really stops (snapshot kept
|
||||
// with a TTL) or comes back asleep. Permissions are checked by patchWorkspace first.
|
||||
let patched = await patchWorkspace(db, caller, row, archived === undefined ? body.data : { ...rest, archived }, now)
|
||||
if (archived === true && (patched.row.status === 'running' || patched.row.status === 'suspended')) {
|
||||
const stopped = await archiveSandbox(life, patched.row, {}, workspaceConfig(env, deps))
|
||||
patched = { ...patched, row: (await getSandbox(env.SANDBOX_DB, stopped.id)) ?? patched.row }
|
||||
} else if (archived === false && patched.row.status === 'archived') {
|
||||
const restored = await restoreArchivedToSleeping(life, patched.row)
|
||||
patched = { ...patched, row: (await getSandbox(env.SANDBOX_DB, restored.id)) ?? patched.row }
|
||||
// Archive/unarchive are lifecycle changes, not labels. The lifecycle runs FIRST and is what
|
||||
// sets archived_at, so a failed or refused archive never labels a running sandbox archived.
|
||||
let archivedNow = false
|
||||
if (archived !== undefined) {
|
||||
assertCanManageWorkspace(caller, row)
|
||||
if (archived && row.archived_at === null) {
|
||||
if (row.status !== 'running' && row.status !== 'suspended') {
|
||||
// Starting, waking or going to sleep: nothing changes; the client asks to try again.
|
||||
return fail('conflict', 409, `sandbox_${row.status}`)
|
||||
}
|
||||
await archiveSandbox(life, row, {}, workspaceConfig(env, deps))
|
||||
archivedNow = true
|
||||
} else if (!archived && row.status === 'archived') {
|
||||
await restoreArchivedToSleeping(life, row)
|
||||
} else if (!archived && row.archived_at !== null) {
|
||||
// A label-only archive from before archive stopped the sandbox: clear the label.
|
||||
await patchWorkspace(db, caller, row, { archived: false }, now)
|
||||
}
|
||||
}
|
||||
const current = (await getSandbox(env.SANDBOX_DB, row.id)) ?? row
|
||||
let patched: Awaited<ReturnType<typeof patchWorkspace>> =
|
||||
Object.keys(rest).length > 0
|
||||
? await patchWorkspace(db, caller, current, rest, now)
|
||||
: { row: current, revoke: 'none' }
|
||||
if (archivedNow && patched.revoke === 'none') {
|
||||
// Archiving disconnects teammates' devices, as before.
|
||||
patched = { ...patched, revoke: 'non_owner' }
|
||||
}
|
||||
if (patched.revoke !== 'none') {
|
||||
// Readers lose the sleeping copy at once, before (and regardless of) the VM-side revokes.
|
||||
await pruneReadSnapshotToOwner(db, patched.row)
|
||||
}
|
||||
const revoked =
|
||||
patched.revoke === 'none' ? null : await revokeForAccessChange(life, patched.row, patched.revoke, caller.userId)
|
||||
@@ -1555,6 +1632,11 @@ export default {
|
||||
// Counts only; no ids, tokens or pairing material.
|
||||
const summary = await reconcile(life)
|
||||
console.log(JSON.stringify({ event: 'reconcile', ...summary }))
|
||||
// Internal fair-use review (U22): retry sessions whose CPU the stop couldn't read yet.
|
||||
const cpu = await sweepSessionCpu(life.db, life.provider, life.now())
|
||||
if (cpu.checked > 0) {
|
||||
console.log(JSON.stringify({ event: 'session_cpu_sweep', ...cpu }))
|
||||
}
|
||||
const retried = await retryPendingMessages(life).catch(() => -1)
|
||||
if (retried !== 0) {
|
||||
console.log(JSON.stringify({ event: 'message_retry', retried }))
|
||||
@@ -1636,3 +1718,54 @@ export class EnvironmentBuildRunner implements DurableObject {
|
||||
await this.state.storage.setAlarm(Date.now() + next)
|
||||
}
|
||||
}
|
||||
|
||||
async function agentSourcesRoute(request: Request, url: URL, env: Env, deps: Deps, caller: SandboxCaller): Promise<Response> {
|
||||
const db = env.SANDBOX_DB
|
||||
const now = (deps.now ?? Date.now)()
|
||||
// Labels for the owner block on teammates' views; a failure here must never fail the request.
|
||||
await rememberCallerName(db, caller, now).catch(() => undefined)
|
||||
const noStore = (body: unknown) => Response.json(body, { headers: { 'cache-control': 'no-store' } })
|
||||
try {
|
||||
if (request.method === 'GET' && url.pathname === '/v1/agent-sources') {
|
||||
return noStore(await agentSourcesView(db, caller, url.searchParams.get('workspaceId')))
|
||||
}
|
||||
if (request.method === 'PUT' && url.pathname === '/v1/agent-sources/offer') {
|
||||
const body = PutOfferSchema.safeParse(await readJson(request))
|
||||
if (!body.success) {
|
||||
return fail('invalid_request', 400)
|
||||
}
|
||||
await putOfferAnswer(db, caller, body.data, now)
|
||||
return noStore(await agentSourcesView(db, caller, null))
|
||||
}
|
||||
if (request.method === 'PUT' && url.pathname === '/v1/agent-sources') {
|
||||
const body = PutSourceSchema.safeParse(await readJson(request))
|
||||
if (!body.success) {
|
||||
return fail('invalid_request', 400)
|
||||
}
|
||||
const row = await putAgentSource(db, caller, body.data, now)
|
||||
// A running sandbox picks the change up in new shells within seconds (same path as a secret edit).
|
||||
const targets = row ? (row.status === 'running' ? [row] : []) : await runningSandboxesForDefault(db, caller.userId, body.data.agent)
|
||||
if (targets.length > 0) {
|
||||
const work = lifecycleDeps(env, deps).then(async (life) => {
|
||||
if (life) {
|
||||
for (const target of targets) {
|
||||
await refreshSandboxEnv(life, target).catch(() => false)
|
||||
}
|
||||
}
|
||||
})
|
||||
if (deps.waitUntil) {
|
||||
deps.waitUntil(work.catch(() => undefined))
|
||||
} else {
|
||||
await work
|
||||
}
|
||||
}
|
||||
return noStore(await agentSourcesView(db, caller, body.data.workspaceId ?? null))
|
||||
}
|
||||
return fail('not_found', 404)
|
||||
} catch (error) {
|
||||
if (error instanceof AgentSourceError) {
|
||||
return fail(error.code, error.status, error.reason)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// Sandbox lifecycle: one persistent provider sandbox per Orca workspace, with an Orca-owned lease,
|
||||
// a forced stop before the provider's 24h cap, usage metering and write-ahead rows.
|
||||
import { deleteAgentSourcesForSandbox } from './agent-sources'
|
||||
import type { EntitlementClient, MachineSize } from './entitlements'
|
||||
import { parseGitHubRepo, type GitHubAppMinter } from './github-app'
|
||||
import {
|
||||
@@ -17,9 +18,10 @@ import { memberPlaceholder, type MemberGitIdentity } from './github-user-tokens'
|
||||
import { connectedMembers, memberGitConfigs } from './member-git'
|
||||
import type { RetentionConfig } from './retention'
|
||||
import type { ProviderSandboxState, SandboxProviderApi } from './sandbox-provider'
|
||||
import { egressSecretHosts, secretPlaceholder } from './secret-egress'
|
||||
import { egressSecretHosts, placeholderValues, secretPlaceholder } from './secret-egress'
|
||||
import { egressAllowHosts, sessionSecretEnv, type SessionSecrets } from './session-env'
|
||||
import type { Keyring } from './secrets-crypto'
|
||||
import { captureReadSnapshot, deleteReadSnapshot } from './read-snapshots'
|
||||
import { ORCAD_PORT, SHARE_PROXY_PORT, drainOrcad, runningOrcad, startOrcad, type OrcadReady, type StartInputs } from './sandbox-vm-commands'
|
||||
import { WORKSPACE_PRELUDE_SCRIPT } from '../image/vm-scripts.generated'
|
||||
import { resolveEnvironmentBoot, type BootSource } from './environments'
|
||||
@@ -41,6 +43,7 @@ import {
|
||||
type SandboxRow,
|
||||
type SessionFields
|
||||
} from './store'
|
||||
import { recordSessionEnd } from './session-cpu'
|
||||
import { flushUsage, queueUsage } from './usage'
|
||||
import { SANDBOX_VCPUS } from './machine-size'
|
||||
import { isRegionalFailure } from './regions'
|
||||
@@ -232,11 +235,11 @@ export function egressPolicy(deps: LifecycleDeps, row: SandboxRow, gitToken?: st
|
||||
// Model API keys swapped at egress (phase 2); each host also ends in the 403 deny rule, except a
|
||||
// host whose client sends its own short-lived token on later calls (Cursor).
|
||||
...egressSecretHosts(row).flatMap((entry) =>
|
||||
Object.entries(entry.headers).map(
|
||||
([header, format]): CredentialRoute => ({
|
||||
Object.keys(entry.headers).map(
|
||||
(header): CredentialRoute => ({
|
||||
host: entry.host,
|
||||
header,
|
||||
placeholders: [format(secretPlaceholder(row, entry.secret))],
|
||||
placeholders: placeholderValues(entry, header, secretPlaceholder(row, entry.secret)),
|
||||
via: 'forward',
|
||||
forwardURL: proxyUrl,
|
||||
...(entry.allowUnclaimed ? { allowUnclaimed: true } : {})
|
||||
@@ -659,23 +662,34 @@ export async function failAndRelease(deps: LifecycleDeps, row: SandboxRow): Prom
|
||||
export async function stopForSuspend(
|
||||
deps: LifecycleDeps,
|
||||
row: SandboxRow,
|
||||
options: { drainSeconds?: number } = {}
|
||||
options: { drainSeconds?: number; reason?: 'sleep' | 'rollover'; captureRead?: boolean } = {}
|
||||
): Promise<SandboxRow> {
|
||||
if (row.session_id) {
|
||||
// While orcad still serves: what a sleeping workspace shows to readers (sealed on the VM).
|
||||
// Skipped for Restart (orcad isn't answering) and Archive (an archived workspace isn't readable).
|
||||
if (options.captureRead !== false) {
|
||||
await captureReadSnapshot(deps, row, options.reason ?? 'sleep').catch(() => undefined)
|
||||
}
|
||||
await drainOrcad(deps.provider, row.session_id, options.drainSeconds)
|
||||
const stopped = await deps.provider.stopSession(row.session_id)
|
||||
if (stopped.snapshotId) {
|
||||
await recordSnapshots(deps.db, row.id, [stopped.snapshotId], deps.now())
|
||||
}
|
||||
await queueUsage(deps.db, row, deps.now())
|
||||
// Internal CPU review (U22): never throws, never touches the meter.
|
||||
await recordSessionEnd(deps.db, row, deps.now(), stopped.usage, deps.now())
|
||||
} else {
|
||||
await queueUsage(deps.db, row, deps.now())
|
||||
}
|
||||
await queueUsage(deps.db, row, deps.now())
|
||||
await deps.hooks?.afterStop?.(row).catch(() => undefined)
|
||||
return claim(deps, row, { status: 'suspended', ...NO_SESSION })
|
||||
}
|
||||
|
||||
/** The provider ended the session on its own (lease lapsed): bill up to when it stopped. */
|
||||
export async function markProviderStopped(deps: LifecycleDeps, row: SandboxRow): Promise<SandboxRow> {
|
||||
await queueUsage(deps.db, row, Math.min(deps.now(), row.lease_expires_at ?? deps.now()))
|
||||
const endedAt = Math.min(deps.now(), row.lease_expires_at ?? deps.now())
|
||||
await queueUsage(deps.db, row, endedAt)
|
||||
await recordSessionEnd(deps.db, row, endedAt, null, deps.now())
|
||||
await deps.hooks?.afterStop?.(row).catch(() => undefined)
|
||||
return claim(deps, row, { status: 'suspended', ...NO_SESSION })
|
||||
}
|
||||
@@ -778,7 +792,7 @@ export async function rolloverSandbox(deps: LifecycleDeps, row: SandboxRow): Pro
|
||||
throw new GuardrailError('maintenance')
|
||||
}
|
||||
const suspending = await claim(deps, row, { status: 'suspending' })
|
||||
const stopped = await stopForSuspend(deps, suspending)
|
||||
const stopped = await stopForSuspend(deps, suspending, { reason: 'rollover' })
|
||||
await flushUsage(deps.db, deps.entitlements, deps.now(), row.id)
|
||||
return wake(deps, await claim(deps, stopped, { status: 'resuming' }))
|
||||
}
|
||||
@@ -802,6 +816,8 @@ export async function destroySandbox(deps: LifecycleDeps, row: SandboxRow): Prom
|
||||
}
|
||||
let destroying = row.status === 'destroying' ? row : await claim(deps, row, { status: 'destroying' })
|
||||
const settled = await queueUsage(deps.db, destroying, deps.now())
|
||||
// A live session ends with the delete (no-op once suspended: the row has no session then).
|
||||
await recordSessionEnd(deps.db, destroying, deps.now(), null, deps.now())
|
||||
if (settled !== destroying.usage_settled_at) {
|
||||
destroying = await claim(deps, destroying, { usage_settled_at: settled })
|
||||
}
|
||||
@@ -825,6 +841,10 @@ 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()
|
||||
// So does its sealed read snapshot.
|
||||
await deleteReadSnapshot(deps.db, row.id)
|
||||
// And its per-workspace agent Source overrides.
|
||||
await deleteAgentSourcesForSandbox(deps.db, row.id)
|
||||
const destroyed = await claim(deps, destroying, {
|
||||
status: 'destroyed',
|
||||
...NO_SESSION,
|
||||
|
||||
@@ -6,6 +6,7 @@ import { revokeMemberDeviceSessions } from './device-sessions'
|
||||
import { revokeGrantsForMember } from './grants'
|
||||
import type { LifecycleDeps } from './lifecycle'
|
||||
import { memberChangeTime, recordMemberChange } from './member-changes'
|
||||
import { revokeMemberReaderKeys } from './read-snapshots'
|
||||
import { disableMemberRoutines } from './routines/runs'
|
||||
|
||||
export type MemberRemoval = {
|
||||
@@ -14,6 +15,7 @@ export type MemberRemoval = {
|
||||
grantsRevoked: number
|
||||
grantsQueued: number
|
||||
routinesDisabled: number
|
||||
readerKeysRevoked: number
|
||||
}
|
||||
|
||||
export async function removeMember(
|
||||
@@ -37,6 +39,8 @@ export async function removeMember(
|
||||
])
|
||||
// Their phones sign as them; then every workspace device they were granted (phones' included).
|
||||
const devicesRevoked = await revokeMemberDeviceSessions(life.db, accountId, userId, now)
|
||||
// No device of theirs can open a sleeping workspace's read snapshot again (wrapped keys deleted).
|
||||
const readerKeysRevoked = await revokeMemberReaderKeys(life.db, accountId, userId, now)
|
||||
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)
|
||||
@@ -45,7 +49,8 @@ export async function removeMember(
|
||||
devicesRevoked,
|
||||
grantsRevoked: grants.revoked,
|
||||
grantsQueued: grants.queued,
|
||||
routinesDisabled: routines.disabled
|
||||
routinesDisabled: routines.disabled,
|
||||
readerKeysRevoked
|
||||
}
|
||||
await audit(life.db, { accountId, type: 'system', id: 'auth', userId }, { action: 'member.removed', detail: { ...result, runsCancelled: routines.cancelled } }, now)
|
||||
return result
|
||||
|
||||
@@ -80,6 +80,8 @@ export const DEFAULT_EGRESS_ALLOWLIST: readonly string[] = [
|
||||
'accounts.google.com',
|
||||
// Vercel AI Gateway: Anthropic/OpenAI-compatible endpoint teams point agents at (ANTHROPIC_BASE_URL).
|
||||
'ai-gateway.vercel.sh',
|
||||
// Vertex AI express mode (GOOGLE_API_KEY with GOOGLE_GENAI_USE_VERTEXAI=true).
|
||||
'aiplatform.googleapis.com',
|
||||
// Gemini CLI signed in with Google: Code Assist API and the account lookup after OAuth.
|
||||
'cloudcode-pa.googleapis.com',
|
||||
'www.googleapis.com',
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
// DELETE /v1/internal/github/bindings {installationId, accountId?}
|
||||
// POST /v1/internal/members/role-changed {accountId, userId, role} re-cap their keys and MCP grants (auth calls this)
|
||||
// POST /v1/internal/members/removed {accountId, userId} revoke a departed member's keys, phones and workspace grants, disable their routines (auth calls this)
|
||||
// GET /v1/internal/fair-use?days=30 per-account CPU utilisation + fair-use flag (U22; internal only, never billed)
|
||||
// POST /v1/internal/session-cpu/sweep fetch CPU for recently stopped sessions now (the cron does this every 5 min)
|
||||
import { z } from 'zod'
|
||||
import { audit } from './api/audit'
|
||||
import { syncMemberRole } from './api/member-role-sync'
|
||||
@@ -18,6 +20,7 @@ import { guardrails, type LifecycleDeps } from './lifecycle'
|
||||
import { drainAll, housekeeping } from './retention'
|
||||
import { memberChangeTime, recordMemberChange } from './member-changes'
|
||||
import { removeMember } from './member-removal'
|
||||
import { fairUseReport, FAIR_USE_WINDOW_DAYS, sweepSessionCpu } from './session-cpu'
|
||||
import { listByStatus } from './store'
|
||||
|
||||
const KillSwitchBody = z.object({ enabled: z.boolean(), drain: z.boolean().optional() }).strict()
|
||||
@@ -141,6 +144,15 @@ export async function handleOperator(
|
||||
const removal = await removeMember(life, body.data.accountId, body.data.userId, now, body.data.changedAt)
|
||||
return Response.json({ revoked: removal.keysRevoked, ...removal })
|
||||
}
|
||||
case 'GET /v1/internal/fair-use': {
|
||||
const days = Number(new URL(request.url).searchParams.get('days') ?? FAIR_USE_WINDOW_DAYS)
|
||||
if (!Number.isInteger(days) || days < 1 || days > 90) {
|
||||
return Response.json({ error: 'invalid_request' }, { status: 400 })
|
||||
}
|
||||
return Response.json(await fairUseReport(life.db, now, days), { headers: { 'cache-control': 'no-store' } })
|
||||
}
|
||||
case 'POST /v1/internal/session-cpu/sweep':
|
||||
return Response.json({ sweep: await sweepSessionCpu(life.db, life.provider, now) })
|
||||
default:
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -8,6 +8,14 @@ const AI_GATEWAY_OPENAI_BASE_URL = `https://${AI_GATEWAY_HOST}/v1`
|
||||
|
||||
export const GEMINI_HOST = 'generativelanguage.googleapis.com'
|
||||
export const CURSOR_API_HOST = 'api2.cursor.sh'
|
||||
export const VERTEX_HOST = 'aiplatform.googleapis.com'
|
||||
/** Copilot's API, per plan; which one a token uses comes from GitHub at sign-in. */
|
||||
export const COPILOT_API_HOSTS = [
|
||||
'api.githubcopilot.com',
|
||||
'api.individual.githubcopilot.com',
|
||||
'api.business.githubcopilot.com',
|
||||
'api.enterprise.githubcopilot.com'
|
||||
] as const
|
||||
|
||||
export const BASE_URL_NAMES: ReadonlySet<string> = new Set(['ANTHROPIC_BASE_URL', 'OPENAI_BASE_URL', 'COPILOT_PROVIDER_BASE_URL'])
|
||||
const HOST = /^([a-z0-9-]+\.)+[a-z]{2,63}$/
|
||||
@@ -81,8 +89,8 @@ export type CredentialTarget = {
|
||||
} & CredentialPolicy
|
||||
|
||||
export type CredentialPolicy = {
|
||||
/** Only these requests may carry the key (exact method, path up to an optional query). Absent: any. */
|
||||
paths?: readonly { method: string; path: string }[]
|
||||
/** Only these requests may carry the key (method, then the path up to its query: exact, or a prefix). Absent: any. */
|
||||
paths?: readonly { method: string; path: string; prefix?: true }[]
|
||||
/**
|
||||
* The host stays reachable without the placeholder. Cursor trades the key for a short-lived access
|
||||
* token and sends that on every later call, so a 403 for unclaimed requests would break it.
|
||||
@@ -93,6 +101,8 @@ export type CredentialPolicy = {
|
||||
* headers that set state either); anything else is refused.
|
||||
*/
|
||||
keepResponseFields?: readonly string[]
|
||||
/** More ways the client may send the key in a header (gh-style `token <value>`). */
|
||||
altHeaderFormats?: Record<string, readonly ((value: string) => string)[]>
|
||||
}
|
||||
|
||||
const bearer = (value: string) => `Bearer ${value}`
|
||||
@@ -102,11 +112,15 @@ const raw = (value: string) => value
|
||||
export type ValueScopes = Readonly<Record<string, string>>
|
||||
|
||||
type CredentialSpec = CredentialPolicy & {
|
||||
/** Hosts (of the default ones) that stay open without the placeholder. */
|
||||
allowUnclaimedHosts?: readonly string[]
|
||||
/** Per-host request limits, over `paths`. */
|
||||
pathsByHost?: Readonly<Record<string, NonNullable<CredentialPolicy['paths']>>>
|
||||
secret: string
|
||||
/** Env var that may point this key at a custom host (honoured only from the key's own scope). */
|
||||
baseUrl?: string
|
||||
/** Host without a base URL; null: the key is only routed together with its base URL. */
|
||||
defaultHost: string | null
|
||||
/** Hosts without a base URL (a base URL replaces them); empty: only routed with its base URL. */
|
||||
defaultHosts: readonly string[]
|
||||
headers: Record<string, (value: string) => string>
|
||||
}
|
||||
|
||||
@@ -120,23 +134,23 @@ const CREDENTIALS: readonly CredentialSpec[] = [
|
||||
{
|
||||
secret: 'ANTHROPIC_API_KEY',
|
||||
baseUrl: 'ANTHROPIC_BASE_URL',
|
||||
defaultHost: 'api.anthropic.com',
|
||||
defaultHosts: ['api.anthropic.com'],
|
||||
headers: { 'x-api-key': raw, authorization: bearer }
|
||||
},
|
||||
{
|
||||
secret: 'ANTHROPIC_AUTH_TOKEN',
|
||||
baseUrl: 'ANTHROPIC_BASE_URL',
|
||||
defaultHost: 'api.anthropic.com',
|
||||
defaultHosts: ['api.anthropic.com'],
|
||||
headers: { authorization: bearer, 'x-api-key': raw }
|
||||
},
|
||||
// AI SDK clients (OpenCode's `vercel/...` models) read the gateway key directly.
|
||||
{ secret: 'AI_GATEWAY_API_KEY', defaultHost: AI_GATEWAY_HOST, headers: { authorization: bearer, 'x-api-key': raw } },
|
||||
{ secret: 'OPENAI_API_KEY', baseUrl: 'OPENAI_BASE_URL', defaultHost: 'api.openai.com', headers: { authorization: bearer } },
|
||||
{ secret: 'GEMINI_API_KEY', defaultHost: GEMINI_HOST, headers: { 'x-goog-api-key': raw } },
|
||||
{ secret: 'GOOGLE_GENERATIVE_AI_API_KEY', defaultHost: GEMINI_HOST, headers: { 'x-goog-api-key': raw } },
|
||||
{ secret: 'AI_GATEWAY_API_KEY', defaultHosts: [AI_GATEWAY_HOST], headers: { authorization: bearer, 'x-api-key': raw } },
|
||||
{ secret: 'OPENAI_API_KEY', baseUrl: 'OPENAI_BASE_URL', defaultHosts: ['api.openai.com'], headers: { authorization: bearer } },
|
||||
{ secret: 'GEMINI_API_KEY', defaultHosts: [GEMINI_HOST], headers: { 'x-goog-api-key': raw } },
|
||||
{ secret: 'GOOGLE_GENERATIVE_AI_API_KEY', defaultHosts: [GEMINI_HOST], headers: { 'x-goog-api-key': raw } },
|
||||
{
|
||||
secret: 'CURSOR_API_KEY',
|
||||
defaultHost: CURSOR_API_HOST,
|
||||
defaultHosts: [CURSOR_API_HOST],
|
||||
headers: { authorization: bearer },
|
||||
paths: [{ method: 'POST', path: '/auth/exchange_user_api_key' }],
|
||||
allowUnclaimed: true,
|
||||
@@ -144,16 +158,37 @@ const CREDENTIALS: readonly CredentialSpec[] = [
|
||||
// and exchanges the key again when it expires; with one it would persist a long-lived credential.
|
||||
keepResponseFields: ['accessToken']
|
||||
},
|
||||
// Gemini CLI and the Google GenAI SDK read GOOGLE_API_KEY for the Gemini API and for Vertex AI
|
||||
// express mode (GOOGLE_GENAI_USE_VERTEXAI=true).
|
||||
{ secret: 'GOOGLE_API_KEY', defaultHosts: [GEMINI_HOST, VERTEX_HOST], headers: { 'x-goog-api-key': raw } },
|
||||
{
|
||||
// A user's own GitHub token for Copilot CLI (fine-grained PAT with Copilot Requests). Copilot
|
||||
// checks it on api.github.com, then calls its API with it. The Copilot hosts stay open without
|
||||
// the placeholder: a session token Copilot gets back is sent there too.
|
||||
secret: 'COPILOT_GITHUB_TOKEN',
|
||||
defaultHosts: ['api.github.com', ...COPILOT_API_HOSTS],
|
||||
headers: { authorization: bearer },
|
||||
altHeaderFormats: { authorization: [(value: string) => `token ${value}`] },
|
||||
allowUnclaimedHosts: [...COPILOT_API_HOSTS],
|
||||
// On GitHub's API the user's token checks Copilot access and nothing else: the rest of the API
|
||||
// (repos, gists, ...) stays out of reach of whatever runs in the workspace.
|
||||
pathsByHost: {
|
||||
'api.github.com': [
|
||||
{ method: 'GET', path: '/user' },
|
||||
{ method: 'GET', path: '/copilot_internal/', prefix: true }
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
secret: 'COPILOT_PROVIDER_API_KEY',
|
||||
baseUrl: 'COPILOT_PROVIDER_BASE_URL',
|
||||
defaultHost: null,
|
||||
defaultHosts: [],
|
||||
headers: { authorization: bearer, 'api-key': raw }
|
||||
},
|
||||
{
|
||||
secret: 'COPILOT_PROVIDER_BEARER_TOKEN',
|
||||
baseUrl: 'COPILOT_PROVIDER_BASE_URL',
|
||||
defaultHost: null,
|
||||
defaultHosts: [],
|
||||
headers: { authorization: bearer }
|
||||
}
|
||||
]
|
||||
@@ -167,7 +202,7 @@ export function credentialShape(secret: string): Omit<CredentialTarget, 'host'>
|
||||
if (!spec) {
|
||||
return null
|
||||
}
|
||||
const { baseUrl: _baseUrl, defaultHost: _defaultHost, ...shape } = spec
|
||||
const { baseUrl: _baseUrl, defaultHosts: _defaultHosts, allowUnclaimedHosts: _openHosts, pathsByHost: _paths, ...shape } = spec
|
||||
return shape
|
||||
}
|
||||
|
||||
@@ -175,25 +210,43 @@ export function credentialShape(secret: string): Omit<CredentialTarget, 'host'>
|
||||
* A base URL only redirects a credential from the same scope: a member's personal base URL must
|
||||
* never route the org's shared key to a host the member picked (the proxy would hand it over).
|
||||
*/
|
||||
function hostFor(env: Record<string, string>, spec: CredentialSpec, scopes?: ValueScopes): string | null {
|
||||
function hostsFor(env: Record<string, string>, spec: CredentialSpec, scopes?: ValueScopes): readonly string[] {
|
||||
const base = spec.baseUrl ? env[spec.baseUrl] : undefined
|
||||
if (!base || !spec.baseUrl) {
|
||||
return spec.defaultHost
|
||||
return spec.defaultHosts
|
||||
}
|
||||
if (scopes && scopes[spec.baseUrl] !== scopes[spec.secret]) {
|
||||
return spec.defaultHost
|
||||
return spec.defaultHosts
|
||||
}
|
||||
return baseUrlHost(base)
|
||||
const host = baseUrlHost(base)
|
||||
return host ? [host] : []
|
||||
}
|
||||
|
||||
/** Where each model credential in `env` is used, so the egress proxy can swap it in on that host only. */
|
||||
/** How a credential is sent and policed on one of its hosts. */
|
||||
export function credentialTarget(secret: string, host: string): CredentialTarget | null {
|
||||
const spec = CREDENTIALS.find((candidate) => candidate.secret === secret)
|
||||
const shape = credentialShape(secret)
|
||||
if (!spec || !shape) {
|
||||
return null
|
||||
}
|
||||
const { allowUnclaimed: _open, ...rest } = shape
|
||||
const open = spec.allowUnclaimed || spec.allowUnclaimedHosts?.includes(host)
|
||||
const paths = spec.pathsByHost?.[host] ?? spec.paths
|
||||
return { ...rest, ...(open ? { allowUnclaimed: true as const } : {}), ...(paths ? { paths } : {}), host }
|
||||
}
|
||||
|
||||
/** Where each model credential in `env` is used, so the egress proxy can swap it in on those hosts only. */
|
||||
export function credentialTargets(env: Record<string, string>, scopes?: ValueScopes): CredentialTarget[] {
|
||||
const targets: CredentialTarget[] = []
|
||||
for (const spec of CREDENTIALS) {
|
||||
const host = env[spec.secret] ? hostFor(env, spec, scopes) : null
|
||||
const shape = host ? credentialShape(spec.secret) : null
|
||||
if (host && shape) {
|
||||
targets.push({ ...shape, host })
|
||||
if (!env[spec.secret]) {
|
||||
continue
|
||||
}
|
||||
for (const host of hostsFor(env, spec, scopes)) {
|
||||
const target = credentialTarget(spec.secret, host)
|
||||
if (target) {
|
||||
targets.push(target)
|
||||
}
|
||||
}
|
||||
}
|
||||
return targets
|
||||
|
||||
@@ -0,0 +1,459 @@
|
||||
// Read a sleeping workspace without waking it (gap 5), end-to-end encrypted:
|
||||
// PUT /v1/reader-keys {publicKeyB64, deviceLabel, deviceKind} register this device's X25519 key
|
||||
// GET /v1/reader-keys the caller's live keys
|
||||
// DELETE /v1/reader-keys/:id
|
||||
// GET /v1/team/workspaces/:id/read-snapshot?keyId=rk_… the body + only that key's wrapped key
|
||||
// At every drain the control plane asks the VM (image/vm/orca-sandbox-read-snapshot) to seal a
|
||||
// compact snapshot to the reader keys allowed to open the workspace, and stores the ciphertext.
|
||||
// D1, backups and logs hold only ciphertext and never a reader secret. Trust model: like W4 grants,
|
||||
// the control plane at runtime chooses the recipient keys and drives the VM, so it is trusted not to
|
||||
// add its own key (same as relaying grant keys). Access mirrors canOpen at read time, and pruning
|
||||
// (removal, private, revoke) deletes wrapped keys at once, without the VM.
|
||||
import { z } from 'zod'
|
||||
import type { SandboxCaller } from './auth'
|
||||
import { ensureEntryPoints } from './golden-images'
|
||||
import type { LifecycleDeps } from './lifecycle'
|
||||
import type { SandboxRow } from './store'
|
||||
import { WorkspaceError, canOpen, isOwner } from './workspaces'
|
||||
|
||||
export const READ_SNAPSHOT_COMMAND = '/opt/orca/bin/orca-sandbox-read-snapshot'
|
||||
const READ_SNAPSHOT_TIMEOUT_MS = 40_000
|
||||
/** Above this the VM trims the payload; anything bigger here is refused (D1 rows stay small). */
|
||||
export const MAX_READ_SNAPSHOT_BYTES = 220_000
|
||||
/** A sleeping workspace is sealed to at most this many devices (newest first). */
|
||||
export const MAX_READ_RECIPIENTS = 64
|
||||
const MAX_KEYS_PER_USER = 12
|
||||
|
||||
const B64_32 = z
|
||||
.string()
|
||||
.regex(/^[A-Za-z0-9+/]{43}=$/)
|
||||
.refine((value) => atob(value).length === 32, 'expected 32 bytes')
|
||||
const B64_NONCE = z.string().regex(/^[A-Za-z0-9+/]{16}$/)
|
||||
const KEY_ID = /^rk_[0-9a-f]{24}$/
|
||||
const SNAPSHOT_ID = /^rsn_[0-9a-f]{24}$/
|
||||
|
||||
export const ReaderKeyRequestSchema = z
|
||||
.object({
|
||||
publicKeyB64: B64_32,
|
||||
deviceLabel: z.string().trim().min(1).max(80).regex(/^[^\u0000-\u001f]+$/),
|
||||
deviceKind: z.enum(['desktop', 'mobile'])
|
||||
})
|
||||
.strict()
|
||||
|
||||
export type ReaderKeyRow = {
|
||||
id: string
|
||||
user_id: string
|
||||
account_id: string
|
||||
dev: number
|
||||
public_key: string
|
||||
device_kind: string
|
||||
device_label: string
|
||||
device_session_id: string | null
|
||||
created_at: number
|
||||
last_seen_at: number
|
||||
revoked_at: number | null
|
||||
revoked_by: string | null
|
||||
}
|
||||
|
||||
export class ReadSnapshotRouteError extends Error {
|
||||
constructor(
|
||||
readonly code: 'not_found' | 'no_snapshot' | 'not_sealed_for_key' | 'invalid_request',
|
||||
readonly status: number
|
||||
) {
|
||||
super(code)
|
||||
}
|
||||
}
|
||||
|
||||
function randomHexId(prefix: string): string {
|
||||
const bytes = crypto.getRandomValues(new Uint8Array(12))
|
||||
return `${prefix}_${Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')}`
|
||||
}
|
||||
|
||||
function readerKeyView(row: ReaderKeyRow) {
|
||||
return {
|
||||
id: row.id,
|
||||
deviceKind: row.device_kind,
|
||||
deviceLabel: row.device_label,
|
||||
createdAt: row.created_at,
|
||||
lastSeenAt: row.last_seen_at
|
||||
}
|
||||
}
|
||||
|
||||
/** Idempotent per (caller, public key): the same id comes back and lastSeenAt moves. */
|
||||
export async function registerReaderKey(
|
||||
db: D1Database,
|
||||
caller: SandboxCaller,
|
||||
body: z.infer<typeof ReaderKeyRequestSchema>,
|
||||
now: number
|
||||
): Promise<ReaderKeyRow> {
|
||||
const live = await db
|
||||
.prepare('SELECT * FROM reader_keys WHERE account_id = ? AND user_id = ? AND public_key = ? AND revoked_at IS NULL')
|
||||
.bind(caller.accountId, caller.userId, body.publicKeyB64)
|
||||
.first<ReaderKeyRow>()
|
||||
if (live) {
|
||||
// A phone's key must stay bound to the session that registered it; another session (or a
|
||||
// desktop token) presenting the same public key is refused rather than rebinding it.
|
||||
if ((live.device_session_id ?? null) !== (caller.deviceSessionId ?? null)) {
|
||||
throw new ReadSnapshotRouteError('invalid_request', 409)
|
||||
}
|
||||
await db
|
||||
.prepare('UPDATE reader_keys SET last_seen_at = ?, device_label = ? WHERE id = ?')
|
||||
.bind(now, body.deviceLabel, live.id)
|
||||
.run()
|
||||
return { ...live, last_seen_at: now, device_label: body.deviceLabel }
|
||||
}
|
||||
const row: ReaderKeyRow = {
|
||||
id: randomHexId('rk'),
|
||||
user_id: caller.userId,
|
||||
account_id: caller.accountId,
|
||||
dev: caller.dev ? 1 : 0,
|
||||
public_key: body.publicKeyB64,
|
||||
// A phone token is a phone, whatever it claims.
|
||||
device_kind: caller.deviceSessionId ? 'mobile' : body.deviceKind,
|
||||
device_label: body.deviceLabel,
|
||||
device_session_id: caller.deviceSessionId ?? null,
|
||||
created_at: now,
|
||||
last_seen_at: now,
|
||||
revoked_at: null,
|
||||
revoked_by: null
|
||||
}
|
||||
const inserted = await db
|
||||
.prepare(
|
||||
`INSERT INTO reader_keys (id, user_id, account_id, dev, public_key, device_kind, device_label, device_session_id, created_at, last_seen_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING`
|
||||
)
|
||||
.bind(row.id, row.user_id, row.account_id, row.dev, row.public_key, row.device_kind, row.device_label, row.device_session_id, now, now)
|
||||
.run()
|
||||
if (inserted.meta.changes === 0) {
|
||||
// A concurrent PUT of the same key won the race: answer with its row.
|
||||
return registerReaderKey(db, caller, body, now)
|
||||
}
|
||||
// Bounded per member: the least recently seen keys beyond the cap are retired.
|
||||
const { results: stale } = await db
|
||||
.prepare(
|
||||
`SELECT id FROM reader_keys WHERE account_id = ? AND user_id = ? AND revoked_at IS NULL
|
||||
ORDER BY last_seen_at DESC, created_at DESC LIMIT -1 OFFSET ?`
|
||||
)
|
||||
.bind(caller.accountId, caller.userId, MAX_KEYS_PER_USER)
|
||||
.all<{ id: string }>()
|
||||
if (stale.length > 0) {
|
||||
await revokeReaderKeys(db, stale.map((s) => s.id), 'system:key_limit', now)
|
||||
}
|
||||
return row
|
||||
}
|
||||
|
||||
/** Revokes the keys and deletes every wrapped snapshot key they had (no VM involved). */
|
||||
export async function revokeReaderKeys(db: D1Database, ids: readonly string[], by: string, now: number): Promise<number> {
|
||||
let revoked = 0
|
||||
for (let i = 0; i < ids.length; i += 50) {
|
||||
const chunk = ids.slice(i, i + 50)
|
||||
const marks = chunk.map(() => '?').join(',')
|
||||
const [update] = await db.batch([
|
||||
db.prepare(`UPDATE reader_keys SET revoked_at = ?, revoked_by = ? WHERE id IN (${marks}) AND revoked_at IS NULL`).bind(now, by, ...chunk),
|
||||
db.prepare(`DELETE FROM read_snapshot_keys WHERE key_id IN (${marks})`).bind(...chunk)
|
||||
])
|
||||
revoked += update?.meta.changes ?? 0
|
||||
}
|
||||
return revoked
|
||||
}
|
||||
|
||||
async function revokeWhere(db: D1Database, where: string, binds: (string | number)[], by: string, now: number): Promise<number> {
|
||||
const { results } = await db
|
||||
.prepare(`SELECT id FROM reader_keys WHERE ${where} AND revoked_at IS NULL`)
|
||||
.bind(...binds)
|
||||
.all<{ id: string }>()
|
||||
return revokeReaderKeys(db, results.map((r) => r.id), by, now)
|
||||
}
|
||||
|
||||
/** A member left the account: none of their devices may read any of its workspaces again. */
|
||||
export function revokeMemberReaderKeys(db: D1Database, accountId: string, userId: string, now: number): Promise<number> {
|
||||
return revokeWhere(db, 'account_id = ? AND user_id = ?', [accountId, userId], 'system:member_removed', now)
|
||||
}
|
||||
|
||||
/** A phone was unpaired or revoked: its reader key goes with it. */
|
||||
export function revokeDeviceSessionReaderKeys(db: D1Database, deviceSessionId: string, now: number): Promise<number> {
|
||||
return revokeWhere(db, 'device_session_id = ?', [deviceSessionId], 'system:device_revoked', now)
|
||||
}
|
||||
|
||||
/**
|
||||
* Visibility or owner changed: drop every wrapped key of this workspace whose holder is not its
|
||||
* (new) owner. Team members get back in at the next drain if it becomes team-visible again.
|
||||
*/
|
||||
export async function pruneReadSnapshotToOwner(db: D1Database, row: SandboxRow): Promise<number> {
|
||||
const result = await db
|
||||
.prepare(
|
||||
`DELETE FROM read_snapshot_keys WHERE sandbox_id = ? AND key_id NOT IN
|
||||
(SELECT id FROM reader_keys WHERE account_id = ? AND user_id = ? AND revoked_at IS NULL)`
|
||||
)
|
||||
.bind(row.id, row.account_id, row.user_id)
|
||||
.run()
|
||||
return result.meta.changes
|
||||
}
|
||||
|
||||
export async function deleteReadSnapshot(db: D1Database, sandboxId: string): Promise<void> {
|
||||
await db.batch([
|
||||
db.prepare('DELETE FROM read_snapshot_keys WHERE sandbox_id = ?').bind(sandboxId),
|
||||
db.prepare('DELETE FROM read_snapshots WHERE sandbox_id = ?').bind(sandboxId)
|
||||
])
|
||||
}
|
||||
|
||||
/** The live keys allowed to open this workspace right now (owner; every member when team-visible). */
|
||||
export async function readerKeysFor(db: D1Database, row: SandboxRow, now: number): Promise<{ id: string; public_key: string }[]> {
|
||||
if (row.archived_at !== null) {
|
||||
return []
|
||||
}
|
||||
const team = row.visibility === 'team'
|
||||
const { results } = await db
|
||||
.prepare(
|
||||
`SELECT k.id, k.public_key FROM reader_keys k
|
||||
LEFT JOIN device_sessions d ON d.id = k.device_session_id
|
||||
WHERE k.account_id = ? AND k.revoked_at IS NULL ${team ? '' : 'AND k.user_id = ?'}
|
||||
-- A phone key counts only while its device session is live (not revoked, not expired).
|
||||
AND (k.device_session_id IS NULL OR (d.revoked_at IS NULL AND d.expires_at > ?))
|
||||
ORDER BY (k.user_id = ?) DESC, k.last_seen_at DESC LIMIT ?`
|
||||
)
|
||||
.bind(...(team ? [row.account_id] : [row.account_id, row.user_id]), now, row.user_id, MAX_READ_RECIPIENTS)
|
||||
.all<{ id: string; public_key: string }>()
|
||||
return results
|
||||
}
|
||||
|
||||
const VmOutputSchema = z
|
||||
.object({
|
||||
v: z.literal(1),
|
||||
snapshotId: z.string().regex(SNAPSHOT_ID),
|
||||
workspaceId: z.string(),
|
||||
nonceB64: B64_NONCE,
|
||||
ciphertextB64: z.string().regex(/^[A-Za-z0-9+/]+=*$/).max(MAX_READ_SNAPSHOT_BYTES),
|
||||
recipients: z
|
||||
.array(
|
||||
z
|
||||
.object({
|
||||
keyId: z.string().regex(KEY_ID),
|
||||
ephemeralPublicKeyB64: B64_32,
|
||||
nonceB64: B64_NONCE,
|
||||
wrappedKeyB64: z.string().regex(/^[A-Za-z0-9+/]{64}$/)
|
||||
})
|
||||
.strict()
|
||||
)
|
||||
.max(MAX_READ_RECIPIENTS),
|
||||
// Timing only: nothing about the plaintext's shape is logged here.
|
||||
stats: z.object({ collectMs: z.number().int().min(0).max(600_000) }).strict().optional()
|
||||
})
|
||||
.strict()
|
||||
|
||||
type CaptureOutcome =
|
||||
| { captured: true; snapshotId: string; recipients: number; bytes: number; stats?: { collectMs: number } }
|
||||
| { captured: false; reason: string }
|
||||
export type CaptureResult = CaptureOutcome & { ms: number }
|
||||
|
||||
/**
|
||||
* Best effort, before orcad drains: the VM gathers and seals the snapshot (it never leaves the VM
|
||||
* in plaintext); this stores the ciphertext and replaces the previous one. A failure keeps the old
|
||||
* snapshot and never blocks the sleep.
|
||||
*/
|
||||
export async function captureReadSnapshot(deps: LifecycleDeps, row: SandboxRow, reason: string): Promise<CaptureResult> {
|
||||
const started = deps.now()
|
||||
const done = (r: CaptureOutcome): CaptureResult => {
|
||||
const result: CaptureResult = { ...r, ms: deps.now() - started }
|
||||
console.log(JSON.stringify({ event: 'read_snapshot', sandboxId: row.id, reason, ...result }))
|
||||
return result
|
||||
}
|
||||
if (!row.session_id) {
|
||||
return done({ captured: false, reason: 'no_session' })
|
||||
}
|
||||
const keys = await readerKeysFor(deps.db, row, deps.now())
|
||||
if (keys.length === 0) {
|
||||
return done({ captured: false, reason: 'no_reader_keys' })
|
||||
}
|
||||
const snapshotId = randomHexId('rsn')
|
||||
const sessionId = row.session_id
|
||||
let stdout: string
|
||||
try {
|
||||
// VMs booted from an older image get the current entry points (this script) first.
|
||||
await ensureEntryPoints(deps, sessionId).catch(() => undefined)
|
||||
const result = await deps.provider.runCommand(sessionId, {
|
||||
command: READ_SNAPSHOT_COMMAND,
|
||||
env: {
|
||||
ORCA_READ_SNAPSHOT_ID: snapshotId,
|
||||
ORCA_READ_WORKSPACE_ID: row.id,
|
||||
ORCA_READ_REASON: reason,
|
||||
ORCA_READ_RECIPIENTS: JSON.stringify(keys.map((k) => ({ keyId: k.id, publicKeyB64: k.public_key })))
|
||||
},
|
||||
timeoutMs: READ_SNAPSHOT_TIMEOUT_MS
|
||||
})
|
||||
if (result.exitCode !== 0) {
|
||||
return done({ captured: false, reason: `exit_${result.exitCode}:${result.stderr.trim().slice(0, 120)}` })
|
||||
}
|
||||
stdout = result.stdout
|
||||
} catch (error) {
|
||||
return done({ captured: false, reason: `run_failed:${String(error).slice(0, 120)}` })
|
||||
}
|
||||
let parsed: z.infer<typeof VmOutputSchema>
|
||||
try {
|
||||
const line = stdout.trim().split('\n').pop() ?? ''
|
||||
const out = VmOutputSchema.safeParse(JSON.parse(line))
|
||||
if (!out.success) {
|
||||
return done({ captured: false, reason: 'bad_output' })
|
||||
}
|
||||
parsed = out.data
|
||||
} catch {
|
||||
return done({ captured: false, reason: 'bad_output' })
|
||||
}
|
||||
const asked = new Set(keys.map((k) => k.id))
|
||||
if (parsed.snapshotId !== snapshotId || parsed.workspaceId !== row.id || parsed.recipients.some((r) => !asked.has(r.keyId))) {
|
||||
return done({ captured: false, reason: 'mismatched_output' })
|
||||
}
|
||||
const now = deps.now()
|
||||
const statements = [
|
||||
deps.db.prepare('DELETE FROM read_snapshot_keys WHERE sandbox_id = ?').bind(row.id),
|
||||
deps.db
|
||||
.prepare(
|
||||
`INSERT INTO read_snapshots (sandbox_id, snapshot_id, stored_at, bytes, nonce, ciphertext) VALUES (?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(sandbox_id) DO UPDATE SET snapshot_id = excluded.snapshot_id, stored_at = excluded.stored_at,
|
||||
bytes = excluded.bytes, nonce = excluded.nonce, ciphertext = excluded.ciphertext`
|
||||
)
|
||||
.bind(row.id, snapshotId, now, parsed.ciphertextB64.length, parsed.nonceB64, parsed.ciphertextB64),
|
||||
...parsed.recipients.map((r) =>
|
||||
deps.db
|
||||
.prepare(
|
||||
'INSERT INTO read_snapshot_keys (sandbox_id, key_id, snapshot_id, ephemeral_public_key, nonce, wrapped_key) VALUES (?, ?, ?, ?, ?, ?)'
|
||||
)
|
||||
.bind(row.id, r.keyId, snapshotId, r.ephemeralPublicKeyB64, r.nonceB64, r.wrappedKeyB64)
|
||||
),
|
||||
// A key revoked (or a member removed) while the VM was sealing must not slip back in.
|
||||
deps.db
|
||||
.prepare(
|
||||
`DELETE FROM read_snapshot_keys WHERE sandbox_id = ? AND key_id IN (SELECT id FROM reader_keys WHERE revoked_at IS NOT NULL)`
|
||||
)
|
||||
.bind(row.id)
|
||||
]
|
||||
await deps.db.batch(statements)
|
||||
// The workspace may have been made private while sealing: re-apply the current rule.
|
||||
const current = await deps.db.prepare('SELECT * FROM sandboxes WHERE id = ?').bind(row.id).first<SandboxRow>()
|
||||
if (current && current.visibility !== 'team') {
|
||||
await pruneReadSnapshotToOwner(deps.db, current)
|
||||
}
|
||||
return done({
|
||||
captured: true,
|
||||
snapshotId,
|
||||
recipients: parsed.recipients.length,
|
||||
bytes: parsed.ciphertextB64.length,
|
||||
...(parsed.stats ? { stats: parsed.stats } : {})
|
||||
})
|
||||
}
|
||||
|
||||
/** For workspace views: when each workspace's snapshot was stored (only rows the caller can open). */
|
||||
export async function readSnapshotTimes(db: D1Database, ids: readonly string[]): Promise<Map<string, number>> {
|
||||
const out = new Map<string, number>()
|
||||
for (let i = 0; i < ids.length; i += 90) {
|
||||
const chunk = ids.slice(i, i + 90)
|
||||
if (chunk.length === 0) {
|
||||
continue
|
||||
}
|
||||
const { results } = await db
|
||||
.prepare(`SELECT sandbox_id, stored_at FROM read_snapshots WHERE sandbox_id IN (${chunk.map(() => '?').join(',')})`)
|
||||
.bind(...chunk)
|
||||
.all<{ sandbox_id: string; stored_at: number }>()
|
||||
for (const r of results) {
|
||||
out.set(r.sandbox_id, r.stored_at)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export async function getReadSnapshot(db: D1Database, caller: SandboxCaller, row: SandboxRow, keyId: string | null, now: number) {
|
||||
// Belt and braces over canOpen: a private workspace's snapshot opens only for its owner.
|
||||
if (!canOpen(caller, row) || (row.visibility !== 'team' && !isOwner(caller, row))) {
|
||||
throw new WorkspaceError('not_found')
|
||||
}
|
||||
if (!keyId || !KEY_ID.test(keyId)) {
|
||||
throw new ReadSnapshotRouteError('invalid_request', 400)
|
||||
}
|
||||
// The key must be the caller's own, live one: nobody fetches another member's wrapped key.
|
||||
const key = await db
|
||||
.prepare('SELECT * FROM reader_keys WHERE id = ? AND account_id = ? AND user_id = ? AND revoked_at IS NULL')
|
||||
.bind(keyId, caller.accountId, caller.userId)
|
||||
.first<ReaderKeyRow>()
|
||||
// A phone reads only with its own key (least privilege; desktop tokens have no device session).
|
||||
if (!key || (caller.deviceSessionId && key.device_session_id !== caller.deviceSessionId)) {
|
||||
throw new ReadSnapshotRouteError('invalid_request', 400)
|
||||
}
|
||||
const snapshot = await db
|
||||
.prepare('SELECT * FROM read_snapshots WHERE sandbox_id = ?')
|
||||
.bind(row.id)
|
||||
.first<{ snapshot_id: string; stored_at: number; nonce: string; ciphertext: string }>()
|
||||
if (!snapshot) {
|
||||
throw new ReadSnapshotRouteError('no_snapshot', 404)
|
||||
}
|
||||
const wrapped = await db
|
||||
.prepare('SELECT * FROM read_snapshot_keys WHERE sandbox_id = ? AND key_id = ? AND snapshot_id = ?')
|
||||
.bind(row.id, keyId, snapshot.snapshot_id)
|
||||
.first<{ ephemeral_public_key: string; nonce: string; wrapped_key: string }>()
|
||||
if (!wrapped) {
|
||||
throw new ReadSnapshotRouteError('not_sealed_for_key', 404)
|
||||
}
|
||||
if (now - key.last_seen_at > 60 * 60_000) {
|
||||
await db.prepare('UPDATE reader_keys SET last_seen_at = ? WHERE id = ?').bind(now, key.id).run()
|
||||
}
|
||||
return {
|
||||
snapshot: {
|
||||
v: 1 as const,
|
||||
snapshotId: snapshot.snapshot_id,
|
||||
workspaceId: row.id,
|
||||
storedAt: snapshot.stored_at,
|
||||
nonceB64: snapshot.nonce,
|
||||
ciphertextB64: snapshot.ciphertext,
|
||||
recipient: {
|
||||
keyId,
|
||||
ephemeralPublicKeyB64: wrapped.ephemeral_public_key,
|
||||
nonceB64: wrapped.nonce,
|
||||
wrappedKeyB64: wrapped.wrapped_key
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
export type ReaderKeysRouteDeps = { db: D1Database; caller: SandboxCaller; now: number; readJson: () => Promise<unknown> }
|
||||
|
||||
export async function handleReaderKeysRoute(request: Request, url: URL, deps: ReaderKeysRouteDeps): Promise<Response> {
|
||||
const json = (body: unknown, status = 200) => Response.json(body, { status, headers: { 'cache-control': 'no-store' } })
|
||||
const match = /^\/v1\/reader-keys(?:\/(rk_[0-9a-f]{24}))?$/.exec(url.pathname)
|
||||
if (!match) {
|
||||
return json({ error: 'not_found' }, 404)
|
||||
}
|
||||
const [, id] = match
|
||||
try {
|
||||
if (!id && request.method === 'PUT') {
|
||||
const body = ReaderKeyRequestSchema.safeParse(await deps.readJson())
|
||||
if (!body.success) {
|
||||
return json({ error: 'invalid_request' }, 400)
|
||||
}
|
||||
return json({ readerKey: readerKeyView(await registerReaderKey(deps.db, deps.caller, body.data, deps.now)) })
|
||||
}
|
||||
if (!id && request.method === 'GET') {
|
||||
const { results } = await deps.db
|
||||
.prepare('SELECT * FROM reader_keys WHERE account_id = ? AND user_id = ? AND revoked_at IS NULL ORDER BY last_seen_at DESC')
|
||||
.bind(deps.caller.accountId, deps.caller.userId)
|
||||
.all<ReaderKeyRow>()
|
||||
return json({ readerKeys: results.map(readerKeyView) })
|
||||
}
|
||||
if (id && request.method === 'DELETE') {
|
||||
const owned = await deps.db
|
||||
.prepare('SELECT id FROM reader_keys WHERE id = ? AND account_id = ? AND user_id = ? AND revoked_at IS NULL')
|
||||
.bind(id, deps.caller.accountId, deps.caller.userId)
|
||||
.first<{ id: string }>()
|
||||
if (!owned) {
|
||||
return json({ error: 'not_found' }, 404)
|
||||
}
|
||||
await revokeReaderKeys(deps.db, [id], deps.caller.userId, deps.now)
|
||||
return json({ ok: true })
|
||||
}
|
||||
return json({ error: 'not_found' }, 404)
|
||||
} catch (error) {
|
||||
if (error instanceof ReadSnapshotRouteError) {
|
||||
return json({ error: error.code }, error.status)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
@@ -114,6 +114,23 @@ function detailOf(run: RunRow): RunDetail {
|
||||
}
|
||||
}
|
||||
|
||||
/** Untrusted context in a prompt, in UTF-8 bytes; the whole prompt stays far below one argv entry's 128 KiB. */
|
||||
export const MAX_CONTEXT_BYTES = 48 * 1024
|
||||
|
||||
function truncateUtf8(text: string, maxBytes: number): string {
|
||||
let bytes = 0
|
||||
let end = 0
|
||||
for (const char of text) {
|
||||
const size = new TextEncoder().encode(char).length
|
||||
if (bytes + size > maxBytes) {
|
||||
break
|
||||
}
|
||||
bytes += size
|
||||
end += char.length
|
||||
}
|
||||
return text.slice(0, end)
|
||||
}
|
||||
|
||||
/** The agent's full prompt: the routine's prompt, what happens to its output, and fenced untrusted context. */
|
||||
export function composePrompt(routine: Pick<RoutineRow, 'prompt' | 'post_results'>, detail: RunDetail): string {
|
||||
const parts = [routine.prompt.trim()]
|
||||
@@ -128,6 +145,14 @@ export function composePrompt(routine: Pick<RoutineRow, 'prompt' | 'post_results
|
||||
}
|
||||
if (detail.context !== undefined && detail.context !== null) {
|
||||
let context = JSON.stringify(detail.context, null, 2)
|
||||
// The prompt reaches some agents as one argv entry (Linux caps one at 128 KiB): indentation of a
|
||||
// deeply nested payload must not push it over, so a large context is sent compact, then cut.
|
||||
if (new TextEncoder().encode(context).length > MAX_CONTEXT_BYTES) {
|
||||
context = JSON.stringify(detail.context)
|
||||
}
|
||||
if (new TextEncoder().encode(context).length > MAX_CONTEXT_BYTES) {
|
||||
context = `${truncateUtf8(context, MAX_CONTEXT_BYTES)}\n[truncated]`
|
||||
}
|
||||
// A payload cannot close the fence early.
|
||||
context = context.replaceAll('</untrusted_context>', '<\\/untrusted_context>')
|
||||
parts.push(
|
||||
|
||||
@@ -95,9 +95,43 @@ codex)
|
||||
--output-last-message "$D/last.txt" - >"$D/agent.out" 2>"$D/agent.err" <"$D/prompt.txt" || code=$?
|
||||
summary="$(head -c 6000 "$D/last.txt" 2>/dev/null || true)"
|
||||
;;
|
||||
opencode)
|
||||
# "--" ends the flags, so a prompt starting with "-" stays the message.
|
||||
timeout --kill-after=20 "$limit" opencode run --auto --format json -- "$(cat "$D/prompt.txt")" \
|
||||
>"$D/agent.out" 2>"$D/agent.err" </dev/null || code=$?
|
||||
# JSON events: the final message is the last text part (tool output never becomes the summary).
|
||||
summary="$(jq -rs 'map(select(.type == "text")) | last | .part.text // empty' "$D/agent.out" 2>/dev/null | head -c 6000)"
|
||||
;;
|
||||
gemini)
|
||||
# --prompt=TEXT, not "-p TEXT": a prompt starting with "-" would read as a flag.
|
||||
timeout --kill-after=20 "$limit" gemini --yolo --output-format json --prompt="$(cat "$D/prompt.txt")" \
|
||||
>"$D/agent.out" 2>"$D/agent.err" </dev/null || code=$?
|
||||
summary="$(jq -r '.response // empty' "$D/agent.out" 2>/dev/null | head -c 6000)"
|
||||
if [ "$code" = 0 ] && [ -n "$(jq -r '.error // empty' "$D/agent.out" 2>/dev/null)" ]; then code=1; fi
|
||||
;;
|
||||
cursor)
|
||||
timeout --kill-after=20 "$limit" cursor-agent --print --force --trust --output-format json -- "$(cat "$D/prompt.txt")" \
|
||||
>"$D/agent.out" 2>"$D/agent.err" </dev/null || code=$?
|
||||
summary="$(jq -rs 'map(select(type == "object" and .type == "result")) | last | .result // empty' "$D/agent.out" 2>/dev/null | head -c 6000)"
|
||||
;;
|
||||
copilot)
|
||||
# --silent: only the agent's response, no tool output or stats.
|
||||
timeout --kill-after=20 "$limit" copilot --allow-all --silent --prompt="$(cat "$D/prompt.txt")" \
|
||||
>"$D/agent.out" 2>"$D/agent.err" </dev/null || code=$?
|
||||
summary="$(head -c 6000 "$D/agent.out" 2>/dev/null || true)"
|
||||
;;
|
||||
*) code=2; note=unknown_agent; finish ;;
|
||||
esac
|
||||
[ -n "$summary" ] || summary="$(tail -c 2000 "$D/agent.out" 2>/dev/null || true)"
|
||||
# The summary can be posted publicly (comment / PR body): no session secret value leaves in it, even
|
||||
# one an agent printed (AWS keys and plain env secrets are real values in this VM).
|
||||
summary="$(ORCA_SUMMARY="$summary" node -e '
|
||||
let s = process.env.ORCA_SUMMARY || ""
|
||||
for (const name of (process.env.ORCA_SESSION_ENV_NAMES || "").split(/\s+/)) {
|
||||
const value = process.env[name]
|
||||
if (value && value.length >= 8) s = s.split(value).join("[redacted]")
|
||||
}
|
||||
process.stdout.write(s)' 2>/dev/null)" || summary=""
|
||||
echo "routine: agent exit $code"
|
||||
if [ "$code" = 0 ] && [ "$post" = pr ] && [ -n "$start_sha" ]; then
|
||||
git add -A >/dev/null 2>&1 || true
|
||||
|
||||
@@ -27,6 +27,18 @@ export type ProviderSession = {
|
||||
timeoutMs: number
|
||||
}
|
||||
|
||||
/** A session's measured usage (internal fair-use review only; never metered or sent to billing). */
|
||||
export type ProviderSessionUsage = {
|
||||
sessionId: string
|
||||
status: ProviderSessionStatus
|
||||
/** Vercel reports this only once the VM has stopped. */
|
||||
activeCpuMs: number | null
|
||||
durationMs: number | null
|
||||
vcpus: number | null
|
||||
memoryMb: number | null
|
||||
stoppedAt: number | null
|
||||
}
|
||||
|
||||
export type ProviderRoute = { port: number; url: string }
|
||||
|
||||
export type ProviderSandboxState = {
|
||||
@@ -87,7 +99,9 @@ export type SandboxProviderApi = {
|
||||
createSandbox(params: CreateSandboxParams): Promise<ProviderSandboxState>
|
||||
/** `resume: true` boots a stopped persistent sandbox from its latest snapshot. Null when absent. */
|
||||
getSandbox(name: string, options: { resume: boolean }): Promise<ProviderSandboxState | null>
|
||||
stopSession(sessionId: string): Promise<{ snapshotId: string | null }>
|
||||
stopSession(sessionId: string): Promise<{ snapshotId: string | null; usage?: ProviderSessionUsage | null }>
|
||||
/** A session's usage, stopped or not. Null when the provider no longer knows it. Optional: CPU review is best-effort. */
|
||||
getSessionUsage?(sessionId: string): Promise<ProviderSessionUsage | null>
|
||||
extendTimeout(sessionId: string, durationMs: number): Promise<ProviderSession>
|
||||
updateNetworkPolicy(sessionId: string, policy: NetworkPolicy): Promise<void>
|
||||
/** Sets the full exposed-port list on the sandbox (live on a running session); returns its routes. */
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
// Codex) hang under Vercel transform rules, so these hosts always take the forwardURL path through
|
||||
// /v1/egress/proxy, the same path api.github.com uses. Placeholders are not secrets: the proxy
|
||||
// authenticates the sandbox by Vercel's OIDC token, the placeholder only marks which header to swap.
|
||||
import { SWAPPED_CREDENTIALS, credentialShape, credentialTargets, type CredentialTarget, type ValueScopes } from './provider-env'
|
||||
import { SWAPPED_CREDENTIALS, credentialTarget, credentialTargets, type CredentialTarget, type ValueScopes } from './provider-env'
|
||||
import type { SandboxRow } from './store'
|
||||
|
||||
export type SecretEgressHost = CredentialTarget
|
||||
@@ -24,21 +24,28 @@ export function encodeEgressSecretHosts(targets: readonly CredentialTarget[]): s
|
||||
|
||||
/** Credential routes recorded on the row for this session. */
|
||||
export function egressSecretHosts(row: Pick<SandboxRow, 'egress_secret_hosts'>): SecretEgressHost[] {
|
||||
const recorded: Record<string, string> = {}
|
||||
const recorded = new Map<string, Set<string>>()
|
||||
for (const entry of (row.egress_secret_hosts ?? '').split(',').filter(Boolean)) {
|
||||
const at = entry.indexOf('@')
|
||||
const [secret, host] = at === -1 ? [LEGACY_HOSTS[entry], entry] : [entry.slice(0, at), entry.slice(at + 1)]
|
||||
if (secret && host) {
|
||||
recorded[secret] = host
|
||||
recorded.set(secret, (recorded.get(secret) ?? new Set()).add(host))
|
||||
}
|
||||
}
|
||||
// Header shapes and policies come from the code, never from the row. The base URL value is only
|
||||
// used to pick the default-vs-custom host, and the recorded host is what was allowlisted at boot.
|
||||
return SWAPPED_CREDENTIALS.flatMap((secret) => {
|
||||
const host = recorded[secret]
|
||||
const shape = host ? credentialShape(secret) : null
|
||||
return host && shape ? [{ ...shape, host }] : []
|
||||
})
|
||||
// used to pick the default-vs-custom host, and the recorded hosts are what was allowlisted at boot.
|
||||
return SWAPPED_CREDENTIALS.flatMap((secret) =>
|
||||
[...(recorded.get(secret) ?? [])].flatMap((host) => {
|
||||
const target = credentialTarget(secret, host)
|
||||
return target ? [target] : []
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
/** Every header value the VM may send a credential's placeholder in. */
|
||||
export function placeholderValues(target: CredentialTarget, header: string, placeholder: string): string[] {
|
||||
const format = target.headers[header]
|
||||
return format ? [format(placeholder), ...(target.altHeaderFormats?.[header] ?? []).map((alt) => alt(placeholder))] : []
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
// U22: internal-only CPU tracking. Customers keep flat sandbox hours; this records each session's
|
||||
// measured active CPU (Vercel reports it after the VM stops) so operators can spot fair-use outliers.
|
||||
// Never touches usage_outbox, billing or a customer route, and never blocks a stop: every entry
|
||||
// point swallows its own failures, and the cron sweep fills in what the stop couldn't read.
|
||||
import { SANDBOX_VCPUS } from './machine-size'
|
||||
import type { ProviderSessionUsage, SandboxProviderApi } from './sandbox-provider'
|
||||
import type { SandboxRow } from './store'
|
||||
|
||||
export const FAIR_USE_WINDOW_DAYS = 30
|
||||
/** Average active CPU over vCPU-time above this flags an account for review. */
|
||||
export const FAIR_USE_THRESHOLD = 0.6
|
||||
/** Sessions older than this without CPU are given up on (the provider may have forgotten them). */
|
||||
const SWEEP_WINDOW_MS = 7 * 24 * 60 * 60_000
|
||||
const SWEEP_MAX_ATTEMPTS = 12
|
||||
const SWEEP_BATCH = 25
|
||||
|
||||
/**
|
||||
* Records a session that just ended; idempotent per session id. `usage` is whatever the stop
|
||||
* answered (often no CPU yet). Never throws.
|
||||
*/
|
||||
export async function recordSessionEnd(
|
||||
db: D1Database,
|
||||
row: SandboxRow,
|
||||
endedAt: number,
|
||||
usage: ProviderSessionUsage | null | undefined,
|
||||
now: number
|
||||
): Promise<void> {
|
||||
try {
|
||||
if (!row.session_id) {
|
||||
return
|
||||
}
|
||||
const vcpus = positive(usage?.vcpus) ?? SANDBOX_VCPUS
|
||||
const startedAt = row.session_started_at
|
||||
const wallMs = positive(usage?.durationMs) ?? (startedAt !== null ? Math.max(0, endedAt - startedAt) : 0)
|
||||
await db
|
||||
.prepare(
|
||||
`INSERT OR IGNORE INTO session_cpu
|
||||
(session_id, sandbox_id, account_id, user_id, vcpus, memory_mb, wall_ms, started_at, ended_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
||||
)
|
||||
.bind(row.session_id, row.id, row.account_id, row.user_id ?? null, vcpus, positive(usage?.memoryMb), wallMs, startedAt, endedAt)
|
||||
.run()
|
||||
if (usage) {
|
||||
await applyUsage(db, row.session_id, usage, now)
|
||||
}
|
||||
} catch {
|
||||
// Internal review data only: a D1 or shape problem must never fail the stop.
|
||||
}
|
||||
}
|
||||
|
||||
/** Fills CPU on a pending row; first answer wins (re-fetching never rewrites a recorded value). */
|
||||
async function applyUsage(db: D1Database, sessionId: string, usage: ProviderSessionUsage, now: number): Promise<boolean> {
|
||||
if (usage.activeCpuMs === null || !Number.isFinite(usage.activeCpuMs) || usage.activeCpuMs < 0) {
|
||||
return false
|
||||
}
|
||||
const result = await db
|
||||
.prepare(
|
||||
`UPDATE session_cpu SET active_cpu_ms = ?, fetched_at = ?,
|
||||
wall_ms = COALESCE(?, wall_ms), vcpus = COALESCE(?, vcpus), memory_mb = COALESCE(?, memory_mb)
|
||||
WHERE session_id = ? AND active_cpu_ms IS NULL`
|
||||
)
|
||||
.bind(
|
||||
Math.round(usage.activeCpuMs),
|
||||
now,
|
||||
positive(usage.durationMs),
|
||||
positive(usage.vcpus),
|
||||
positive(usage.memoryMb),
|
||||
sessionId
|
||||
)
|
||||
.run()
|
||||
return (result.meta?.changes ?? 0) > 0
|
||||
}
|
||||
|
||||
export type SessionCpuSweep = { checked: number; recorded: number; failed: number }
|
||||
|
||||
/** Cron: asks the provider again for recent sessions still missing CPU. Never throws. */
|
||||
export async function sweepSessionCpu(
|
||||
db: D1Database,
|
||||
provider: Pick<SandboxProviderApi, 'getSessionUsage'>,
|
||||
now: number
|
||||
): Promise<SessionCpuSweep> {
|
||||
const summary: SessionCpuSweep = { checked: 0, recorded: 0, failed: 0 }
|
||||
if (!provider.getSessionUsage) {
|
||||
return summary
|
||||
}
|
||||
let pending: { session_id: string }[]
|
||||
try {
|
||||
pending = (
|
||||
await db
|
||||
.prepare(
|
||||
`SELECT session_id FROM session_cpu
|
||||
WHERE active_cpu_ms IS NULL AND ended_at >= ? AND attempts < ?
|
||||
ORDER BY ended_at DESC LIMIT ?`
|
||||
)
|
||||
.bind(now - SWEEP_WINDOW_MS, SWEEP_MAX_ATTEMPTS, SWEEP_BATCH)
|
||||
.all<{ session_id: string }>()
|
||||
).results
|
||||
} catch {
|
||||
return summary
|
||||
}
|
||||
for (const { session_id } of pending) {
|
||||
summary.checked++
|
||||
try {
|
||||
const usage = await provider.getSessionUsage(session_id)
|
||||
if (usage && (await applyUsage(db, session_id, usage, now))) {
|
||||
summary.recorded++
|
||||
continue
|
||||
}
|
||||
} catch {
|
||||
summary.failed++
|
||||
}
|
||||
await db
|
||||
.prepare('UPDATE session_cpu SET attempts = attempts + 1 WHERE session_id = ?')
|
||||
.bind(session_id)
|
||||
.run()
|
||||
.catch(() => undefined)
|
||||
}
|
||||
return summary
|
||||
}
|
||||
|
||||
export type FairUseAccount = {
|
||||
accountId: string
|
||||
sessions: number
|
||||
activeCpuMs: number
|
||||
vcpuMs: number
|
||||
/** sum(active_cpu_ms) / sum(wall_ms × vcpus), 0..1 (null when there is no measured time). */
|
||||
cpuUtilization: number | null
|
||||
fairUseFlag: boolean
|
||||
}
|
||||
|
||||
export type FairUseReport = {
|
||||
windowDays: number
|
||||
since: number
|
||||
threshold: number
|
||||
/** Ended sessions in the window still waiting for the provider's CPU figure (excluded from the math). */
|
||||
pendingSessions: number
|
||||
accounts: FairUseAccount[]
|
||||
}
|
||||
|
||||
/** Operator-only. Per account over the window; highest utilisation first. */
|
||||
export async function fairUseReport(db: D1Database, now: number, windowDays = FAIR_USE_WINDOW_DAYS): Promise<FairUseReport> {
|
||||
const since = now - windowDays * 24 * 60 * 60_000
|
||||
const { results } = await db
|
||||
.prepare(
|
||||
`SELECT account_id, COUNT(*) AS sessions, SUM(active_cpu_ms) AS active_cpu_ms, SUM(wall_ms * vcpus) AS vcpu_ms
|
||||
FROM session_cpu WHERE ended_at >= ? AND active_cpu_ms IS NOT NULL
|
||||
GROUP BY account_id`
|
||||
)
|
||||
.bind(since)
|
||||
.all<{ account_id: string; sessions: number; active_cpu_ms: number; vcpu_ms: number }>()
|
||||
const pending = await db
|
||||
.prepare('SELECT COUNT(*) AS n FROM session_cpu WHERE ended_at >= ? AND active_cpu_ms IS NULL')
|
||||
.bind(since)
|
||||
.first<{ n: number }>()
|
||||
const accounts = results
|
||||
.map((row): FairUseAccount => {
|
||||
const vcpuMs = Number(row.vcpu_ms) || 0
|
||||
const activeCpuMs = Number(row.active_cpu_ms) || 0
|
||||
const ratio = vcpuMs > 0 ? activeCpuMs / vcpuMs : null
|
||||
return {
|
||||
accountId: row.account_id,
|
||||
sessions: Number(row.sessions),
|
||||
activeCpuMs,
|
||||
vcpuMs,
|
||||
cpuUtilization: ratio === null ? null : Math.round(ratio * 10_000) / 10_000,
|
||||
fairUseFlag: ratio !== null && ratio > FAIR_USE_THRESHOLD
|
||||
}
|
||||
})
|
||||
.sort((a, b) => (b.cpuUtilization ?? -1) - (a.cpuUtilization ?? -1))
|
||||
return { windowDays, since, threshold: FAIR_USE_THRESHOLD, pendingSessions: Number(pending?.n ?? 0), accounts }
|
||||
}
|
||||
|
||||
function positive(value: number | null | undefined): number | null {
|
||||
return typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.round(value) : null
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
// presets filled in, and with egress placeholders on, model keys swapped for placeholders. The same
|
||||
// answer drives the egress allowlist and the proxy's credential routes, at boot and on refresh.
|
||||
import type { LifecycleDeps } from './lifecycle'
|
||||
import { signInAgentsFor, withoutSignInCredentials } from './agent-sources'
|
||||
import { deriveProviderEnv, deriveProviderScopes, providerHosts } from './provider-env'
|
||||
import { applySecretPlaceholders, encodeEgressSecretHosts } from './secret-egress'
|
||||
import { resolveSandboxSecrets } from './secrets'
|
||||
@@ -26,8 +27,11 @@ export async function resolvedProviderEnv(
|
||||
keyring: Keyring,
|
||||
row: Pick<SandboxRow, 'id' | 'account_id' | 'user_id' | 'repo_url'>
|
||||
): Promise<ProviderEnv> {
|
||||
const { env: stored, scopes } = await resolveSandboxSecrets(db, keyring, row)
|
||||
const env = deriveProviderEnv(stored)
|
||||
const [{ env: stored, scopes }, signIn] = await Promise.all([
|
||||
resolveSandboxSecrets(db, keyring, row),
|
||||
signInAgentsFor(db, row)
|
||||
])
|
||||
const env = withoutSignInCredentials(deriveProviderEnv(stored), signIn)
|
||||
return { env, scopes: deriveProviderScopes(stored, env, scopes) }
|
||||
}
|
||||
|
||||
@@ -70,7 +74,9 @@ export async function sessionSecretEnv(
|
||||
return EMPTY
|
||||
}
|
||||
const { env: stored, scopes: storedScopes, skipped } = await resolveSandboxSecrets(deps.db, deps.secrets.keyring, row)
|
||||
const env = deriveProviderEnv(stored)
|
||||
// Agents on "Your sign-in" (owner's choice): their credentials never reach this session.
|
||||
const signIn = await signInAgentsFor(deps.db, row)
|
||||
const env = withoutSignInCredentials(deriveProviderEnv(stored), signIn)
|
||||
const scopes = deriveProviderScopes(stored, env, storedScopes)
|
||||
const egressAllowHosts = providerHosts(env).join(',') || null
|
||||
// Counts only.
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
type CommandResult,
|
||||
type ProviderSandboxState,
|
||||
type ProviderSession,
|
||||
type ProviderSessionUsage,
|
||||
type SandboxProviderApi
|
||||
} from './sandbox-provider'
|
||||
|
||||
@@ -26,7 +27,13 @@ const Session = z.looseObject({
|
||||
id: z.string(),
|
||||
status: Status,
|
||||
startedAt: z.number().optional(),
|
||||
timeout: z.number()
|
||||
timeout: z.number(),
|
||||
// Usage fields (SDK 3.9.1). activeCpuDurationMs only appears once the VM has stopped.
|
||||
vcpus: z.number().optional(),
|
||||
memory: z.number().optional(),
|
||||
duration: z.number().optional(),
|
||||
stoppedAt: z.number().optional(),
|
||||
activeCpuDurationMs: z.number().optional()
|
||||
})
|
||||
const Sandbox = z.looseObject({
|
||||
name: z.string(),
|
||||
@@ -104,6 +111,15 @@ export function createVercelSandboxApi(
|
||||
startedAt: session.startedAt ?? null,
|
||||
timeoutMs: session.timeout
|
||||
})
|
||||
const toUsage = (session: z.infer<typeof Session>): ProviderSessionUsage => ({
|
||||
sessionId: session.id,
|
||||
status: session.status,
|
||||
activeCpuMs: session.activeCpuDurationMs ?? null,
|
||||
durationMs: session.duration ?? null,
|
||||
vcpus: session.vcpus ?? null,
|
||||
memoryMb: session.memory ?? null,
|
||||
stoppedAt: session.stoppedAt ?? null
|
||||
})
|
||||
const toState = (body: z.infer<typeof SandboxAndSession>): ProviderSandboxState => ({
|
||||
sandbox: {
|
||||
name: body.sandbox.name,
|
||||
@@ -163,8 +179,22 @@ export function createVercelSandboxApi(
|
||||
|
||||
async stopSession(sessionId) {
|
||||
const response = await request('POST', `/v2/sandboxes/sessions/${encodeURIComponent(sessionId)}/stop`)
|
||||
const body = await json(z.looseObject({ snapshot: Snapshot.optional() }), response)
|
||||
return { snapshotId: body.snapshot?.id ?? null }
|
||||
const body = await json(z.looseObject({ snapshot: Snapshot.optional(), session: z.unknown().optional() }), response)
|
||||
// Usage is internal-only and best-effort: a session shape we can't read never fails the stop.
|
||||
const session = Session.safeParse(body.session)
|
||||
return { snapshotId: body.snapshot?.id ?? null, usage: session.success ? toUsage(session.data) : null }
|
||||
},
|
||||
|
||||
async getSessionUsage(sessionId) {
|
||||
try {
|
||||
const response = await request('GET', `/v2/sandboxes/sessions/${encodeURIComponent(sessionId)}`)
|
||||
return toUsage((await json(z.looseObject({ session: Session }), response)).session)
|
||||
} catch (error) {
|
||||
if (error instanceof ProviderError && error.status === 404) {
|
||||
return null
|
||||
}
|
||||
throw error
|
||||
}
|
||||
},
|
||||
|
||||
async extendTimeout(sessionId, durationMs) {
|
||||
|
||||
@@ -233,7 +233,7 @@ export async function restartSandbox(deps: LifecycleDeps, row: SandboxRow): Prom
|
||||
throw new LifecycleError('conflict', `sandbox_${current.status}`)
|
||||
}
|
||||
const suspending = await claim(deps, current, { status: 'suspending' })
|
||||
const stopped = await stopForSuspend(deps, suspending, { drainSeconds: RESTART_DRAIN_SECONDS })
|
||||
const stopped = await stopForSuspend(deps, suspending, { drainSeconds: RESTART_DRAIN_SECONDS, captureRead: false })
|
||||
await flushUsage(deps.db, deps.entitlements, deps.now(), row.id)
|
||||
return wake(deps, await claim(deps, stopped, { status: 'resuming' }))
|
||||
}
|
||||
@@ -300,7 +300,7 @@ export async function archiveSandbox(
|
||||
let stopped = row
|
||||
if (row.status === 'running') {
|
||||
// Short drain: the desktop's Sleep normally ran first; a long drain would outlive the caller.
|
||||
stopped = await stopForSuspend(deps, await claim(deps, row, { status: 'suspending' }), { drainSeconds: ARCHIVE_DRAIN_SECONDS })
|
||||
stopped = await stopForSuspend(deps, await claim(deps, row, { status: 'suspending' }), { drainSeconds: ARCHIVE_DRAIN_SECONDS, captureRead: false })
|
||||
await flushUsage(deps.db, deps.entitlements, deps.now(), row.id)
|
||||
}
|
||||
const ttl = config.archiveTtlMs ?? DEFAULT_ARCHIVE_TTL_MS
|
||||
|
||||
@@ -13,6 +13,7 @@ import type { SandboxCaller } from './auth'
|
||||
import type { MachineSize } from './entitlements'
|
||||
import { getSandbox, touchActivity, updateRegistry, type SandboxRow } from './store'
|
||||
import { memberNamesFor } from './member-names'
|
||||
import { readSnapshotTimes } from './read-snapshots'
|
||||
import { sandboxView } from './wire'
|
||||
import { ORCA_CLOUD_OVERAGE_CENTS_PER_HOUR } from '../../../../src/shared/hosted-sandbox/hosted-sandbox-wire'
|
||||
|
||||
@@ -68,6 +69,13 @@ function canManage(caller: SandboxCaller, row: SandboxRow): boolean {
|
||||
return row.account_id === caller.accountId && (row.user_id === caller.userId || isOrgAdmin(caller))
|
||||
}
|
||||
|
||||
/** Owner or a team admin; anyone else gets forbidden (or not_found when they can't see it). */
|
||||
export function assertCanManageWorkspace(caller: SandboxCaller, row: SandboxRow): void {
|
||||
if (!canManage(caller, row)) {
|
||||
throw new WorkspaceError(canSee(caller, row) ? 'forbidden' : 'not_found', 'owner_or_admin_only')
|
||||
}
|
||||
}
|
||||
|
||||
/** A row the caller may address by id; anything else is indistinguishable from a missing one. */
|
||||
export async function requireVisible(db: D1Database, caller: SandboxCaller, id: string): Promise<SandboxRow> {
|
||||
const row = await getSandbox(db, id)
|
||||
@@ -162,10 +170,11 @@ 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] = await Promise.all([
|
||||
const [presence, compute, granted, readAt] = await Promise.all([
|
||||
presenceFor(db, ids, now),
|
||||
computeMsFor(db, ids),
|
||||
activeGrantUsers(db, ids, caller.userId)
|
||||
activeGrantUsers(db, ids, caller.userId),
|
||||
readSnapshotTimes(db, ids)
|
||||
])
|
||||
const referenced = (row: SandboxRow, live: readonly PresenceRow[]) =>
|
||||
[row.user_id, row.created_by, row.last_activity_by, ...live.map((p) => p.user_id)].filter(
|
||||
@@ -199,7 +208,9 @@ export async function workspaceViews(db: D1Database, caller: SandboxCaller, rows
|
||||
access,
|
||||
presence: live.map((p) => ({ userId: p.user_id, clientId: p.client_id, state: p.state, chatId: p.chat_id, at: p.updated_at })),
|
||||
// Display names (token `name` claim) for the ids above; the roster wins where it has one.
|
||||
memberNames
|
||||
memberNames,
|
||||
// When its sleeping read-only copy was saved ("As of"); only for those who may read it.
|
||||
readSnapshotAt: canOpen(caller, row) ? (readAt.get(row.id) ?? null) : null
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -281,6 +292,9 @@ export async function patchWorkspace(
|
||||
} else if (!canManage(caller, row)) {
|
||||
throw new WorkspaceError(canSee(caller, row) ? 'forbidden' : 'not_found', 'owner_or_admin_only')
|
||||
}
|
||||
if (patch.archived === true) {
|
||||
throw new WorkspaceError('invalid_request', 'archive_via_lifecycle')
|
||||
}
|
||||
if (patch.visibility === 'team' && !row.account_id.includes('org:')) {
|
||||
// A personal account has no team to share with.
|
||||
throw new WorkspaceError('invalid_request', 'personal_account')
|
||||
@@ -299,7 +313,9 @@ export async function patchWorkspace(
|
||||
...(patch.branch !== undefined ? { repo_branch: patch.branch } : {}),
|
||||
...(patch.visibility !== undefined ? { visibility: patch.visibility } : {}),
|
||||
...(patch.section !== undefined ? { section: patch.section } : {}),
|
||||
...(patch.archived !== undefined ? { archived_at: patch.archived ? (row.archived_at ?? now) : null } : {}),
|
||||
// Archiving is a lifecycle change (archiveSandbox stops the VM, then sets archived_at); this edit
|
||||
// can only clear a label left by an older label-only archive.
|
||||
...(patch.archived === false ? { archived_at: null } : {}),
|
||||
...(patch.ownerUserId !== undefined ? { user_id: patch.ownerUserId } : {}),
|
||||
...(patch.tokenUsdMicros !== undefined ? { token_usd_micros: patch.tokenUsdMicros } : {})
|
||||
})
|
||||
|
||||
@@ -4,7 +4,9 @@
|
||||
import { SignJWT, createLocalJWKSet, exportJWK, generateKeyPair } from 'jose'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { compileNetworkPolicy } from '../src/network-policy'
|
||||
import { credentialTargets } from '../src/provider-env'
|
||||
import { SWAPPED_CREDENTIALS, credentialTargets } from '../src/provider-env'
|
||||
import { AGENT_KEY_NAMES } from '../src/secrets'
|
||||
import { CLOUD_SWAPPED_CREDENTIALS, cloudSecretStoredOnVm } from '../../../../src/shared/cloud-secrets/cloud-secret-rules'
|
||||
import { egressSecretHosts, encodeEgressSecretHosts } from '../src/secret-egress'
|
||||
import { ENV_COMMAND } from '../src/sandbox-vm-commands'
|
||||
import { createHarness } from './harness'
|
||||
@@ -59,6 +61,22 @@ describe('credential routes for Gemini, Cursor and Copilot BYOK', () => {
|
||||
expect(credentialTargets(env, { COPILOT_PROVIDER_BASE_URL: 'user:mia', COPILOT_PROVIDER_API_KEY: 'org:acme' })).toEqual([])
|
||||
})
|
||||
|
||||
it('routes GOOGLE_API_KEY to the Gemini API and Vertex AI, and COPILOT_GITHUB_TOKEN to GitHub and the Copilot API', () => {
|
||||
const targets = credentialTargets({ GOOGLE_API_KEY: GEMINI_KEY, COPILOT_GITHUB_TOKEN: COPILOT_KEY })
|
||||
expect(targets.map((t) => `${t.secret}@${t.host}${t.allowUnclaimed ? ' open' : ''}`)).toEqual([
|
||||
'GOOGLE_API_KEY@generativelanguage.googleapis.com',
|
||||
'GOOGLE_API_KEY@aiplatform.googleapis.com',
|
||||
'COPILOT_GITHUB_TOKEN@api.github.com',
|
||||
'COPILOT_GITHUB_TOKEN@api.githubcopilot.com open',
|
||||
'COPILOT_GITHUB_TOKEN@api.individual.githubcopilot.com open',
|
||||
'COPILOT_GITHUB_TOKEN@api.business.githubcopilot.com open',
|
||||
'COPILOT_GITHUB_TOKEN@api.enterprise.githubcopilot.com open'
|
||||
])
|
||||
// Several hosts per credential survive the row encoding.
|
||||
const row = { egress_secret_hosts: encodeEgressSecretHosts(targets) }
|
||||
expect(egressSecretHosts(row).map((t) => `${t.secret}@${t.host}`)).toEqual(targets.map((t) => `${t.secret}@${t.host}`))
|
||||
})
|
||||
|
||||
it('round-trips through the row with the policy taken from code, never from the row', () => {
|
||||
const row = {
|
||||
egress_secret_hosts: encodeEgressSecretHosts(credentialTargets({ CURSOR_API_KEY: CURSOR_KEY, GEMINI_API_KEY: GEMINI_KEY }))
|
||||
@@ -174,6 +192,38 @@ describe('egress swap on a sandbox with the new keys', () => {
|
||||
expect(logs.some((line) => line.includes('"event":"egress_swap"') && line.includes('"credential":"GEMINI_API_KEY"'))).toBe(true)
|
||||
})
|
||||
|
||||
it('Copilot token: swapped on api.github.com next to the workspace token, in Bearer or gh-style token form', async () => {
|
||||
const { h, id, send, upstream } = await setup()
|
||||
const mia = await h.token('mia', undefined, 'sandbox')
|
||||
expect((await h.call('PUT', '/v1/secrets/personal/COPILOT_GITHUB_TOKEN', { body: { value: COPILOT_KEY }, bearer: mia })).status).toBe(200)
|
||||
const ph = `orca-ph-copilot-github-token-${id}`
|
||||
const policy = [...h.vercel.boxes.values()][0]!.policy
|
||||
const values = policy.allow['api.github.com']!.flatMap((rule) => ('match' in rule && rule.match?.headers ? [rule.match.headers[0]!.value.exact] : []))
|
||||
expect(values).toEqual(expect.arrayContaining([`Bearer ${ph}`, `token ${ph}`, `Bearer orca-ph-${id}`]))
|
||||
expect(policy.allow['api.github.com']!.at(-1)).toEqual(DENY)
|
||||
expect(policy.allow['api.individual.githubcopilot.com']!.some((rule) => 'response' in rule)).toBe(false)
|
||||
for (const header of [`Bearer ${ph}`, `token ${ph}`]) {
|
||||
expect((await send('api.github.com', 'GET', '/copilot_internal/user', { authorization: header })).status).toBe(200)
|
||||
expect(upstream.at(-1)!.headers.get('authorization')).toBe(`Bearer ${COPILOT_KEY}`)
|
||||
}
|
||||
expect((await send('api.github.com', 'GET', '/user', { authorization: `Bearer ${ph}` })).status).toBe(200)
|
||||
// The rest of GitHub's API is out of reach of the user's token, however the path is dressed up.
|
||||
const sent = upstream.length
|
||||
for (const [method, path] of [
|
||||
['GET', '/user/repos'],
|
||||
['POST', '/copilot_internal/user'],
|
||||
['GET', '/copilot_internal/../user/repos'],
|
||||
['GET', '/copilot_internal/%2e%2e/user/repos'],
|
||||
['GET', '/copilot_internal//../gists'],
|
||||
['DELETE', '/repos/acme/app']
|
||||
]) {
|
||||
expect(await send('api.github.com', method!, path!, { authorization: `Bearer ${ph}` }), path).toEqual({ status: 403, body: 'path_not_allowed' })
|
||||
}
|
||||
expect(upstream).toHaveLength(sent)
|
||||
expect((await send('api.individual.githubcopilot.com', 'POST', '/chat/completions', { authorization: `Bearer ${ph}` })).status).toBe(200)
|
||||
expect(upstream.at(-1)!.url).toBe('https://api.individual.githubcopilot.com/chat/completions')
|
||||
})
|
||||
|
||||
it('Cursor: only the key exchange carries the key, and the refresh token never reaches the VM', async () => {
|
||||
const { id, send, upstream, setReply } = await setup()
|
||||
setReply(() => new Response(JSON.stringify({ accessToken: 'at-short', refreshToken: 'rt-long-lived' }), { status: 200, headers: { 'content-type': 'application/json', 'content-length': '60' } }))
|
||||
@@ -224,3 +274,19 @@ describe('egress swap on a sandbox with the new keys', () => {
|
||||
expect(JSON.stringify(env)).not.toContain(COPILOT_KEY)
|
||||
})
|
||||
})
|
||||
|
||||
describe('every agent credential is either swapped or marked "stored on workspace"', () => {
|
||||
it('leaves no agent key reaching the VM raw without the warning', () => {
|
||||
const settings = /(_MODEL|_BASE_URL|_REGION|_PROJECT|_PROJECT_ID)$|^CLAUDE_CODE_USE_/
|
||||
for (const name of AGENT_KEY_NAMES) {
|
||||
if (settings.test(name)) {
|
||||
continue
|
||||
}
|
||||
const swapped = SWAPPED_CREDENTIALS.includes(name)
|
||||
expect(swapped !== cloudSecretStoredOnVm(name), `${name}: swapped=${swapped}`).toBe(true)
|
||||
}
|
||||
expect(SWAPPED_CREDENTIALS.includes('COPILOT_GITHUB_TOKEN')).toBe(true)
|
||||
// The desktop's mirror (what it offers to save from this computer) matches the proxy exactly.
|
||||
expect([...CLOUD_SWAPPED_CREDENTIALS].sort()).toEqual([...SWAPPED_CREDENTIALS].sort())
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { AGENT_CREDENTIAL_NAMES } from '../src/agent-credential-names'
|
||||
import { ENV_COMMAND, START_COMMAND } from '../src/sandbox-vm-commands'
|
||||
import { createHarness } from './harness'
|
||||
|
||||
const KEK = Buffer.alloc(32, 7).toString('base64')
|
||||
const PROXY_URL = 'https://sandbox.test/v1/egress/proxy'
|
||||
const TEAM_KEY = 'sk-ant-api03-TEAM-fake-0000-aaaa'
|
||||
const GATEWAY_KEY = 'vck_fake-gateway-key-0000-aaaa-bbbb'
|
||||
|
||||
let logs: string[] = []
|
||||
beforeEach(() => {
|
||||
logs = []
|
||||
for (const method of ['log', 'info', 'warn', 'error', 'debug'] as const) {
|
||||
vi.spyOn(console, method).mockImplementation((...args: unknown[]) => {
|
||||
logs.push(args.map((arg) => (typeof arg === 'string' ? arg : JSON.stringify(arg))).join(' '))
|
||||
})
|
||||
}
|
||||
})
|
||||
afterEach(() => {
|
||||
for (const value of [TEAM_KEY, GATEWAY_KEY]) {
|
||||
expect(logs.join('\n')).not.toContain(value)
|
||||
}
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
function decode(encoded: string | undefined): Record<string, string> {
|
||||
return Object.fromEntries(
|
||||
(encoded ?? '')
|
||||
.split('\n')
|
||||
.filter(Boolean)
|
||||
.map((line) => {
|
||||
const at = line.indexOf('=')
|
||||
return [line.slice(0, at), Buffer.from(line.slice(at + 1), 'base64').toString('utf8')]
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
async function setup(overrides: Record<string, string> = {}) {
|
||||
const h = await createHarness({ SECRETS_KEK: KEK, ...overrides })
|
||||
const as = (sub: string, org?: string, role?: string, name?: string) =>
|
||||
h.token(sub, org, 'sandbox', { ...(role ? { orgRole: role } : {}), ...(name ? { name } : {}) })
|
||||
const put = (scope: string, name: string, value: string, bearer: string) =>
|
||||
h.call('PUT', `/v1/secrets/${scope}/${name}`, { body: { value }, bearer })
|
||||
const lastEnv = (command: string) => decode(h.vercel.commands.filter((c) => c.command === command).at(-1)?.env.ORCA_SECRET_ENV)
|
||||
return { h, as, put, lastEnv }
|
||||
}
|
||||
|
||||
describe('per-agent credential names', () => {
|
||||
it('the Worker mirror matches the shared module verbatim', () => {
|
||||
const shared = readFileSync(fileURLToPath(new URL('../../../../src/shared/agent-credentials/agent-credential-names.ts', import.meta.url).href), 'utf8')
|
||||
for (const [agent, names] of Object.entries(AGENT_CREDENTIAL_NAMES)) {
|
||||
const block = new RegExp(`${agent}: \\[([^\\]]*)\\]`).exec(shared)?.[1] ?? ''
|
||||
expect(block.match(/'[A-Z0-9_]+'/g)?.map((n) => n.slice(1, -1))).toEqual([...names])
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('/v1/agent-sources', () => {
|
||||
it('implicit default follows key coverage, explicit choices win, and the offer is per person', async () => {
|
||||
const { h, as, put } = await setup()
|
||||
const ada = await as('ada', 'acme', 'admin')
|
||||
const mia = await as('mia', 'acme', 'member')
|
||||
let view = await h.call('GET', '/v1/agent-sources', { bearer: mia })
|
||||
expect(view.body.effective).toEqual({ claude: { source: null, origin: 'implicit' }, codex: { source: null, origin: 'implicit' } })
|
||||
expect(view.body.signInOffer).toEqual({ claude: 'unanswered', codex: 'unanswered' })
|
||||
await put('org', 'ANTHROPIC_API_KEY', TEAM_KEY, ada)
|
||||
view = await h.call('GET', '/v1/agent-sources', { bearer: mia })
|
||||
expect(view.body.coveredByKey).toEqual({ claude: true, codex: false })
|
||||
expect(view.body.effective.claude).toEqual({ source: 'key', origin: 'implicit' })
|
||||
view = await h.call('PUT', '/v1/agent-sources', { bearer: mia, body: { agent: 'claude', source: 'sign-in' } })
|
||||
expect(view.body.effective.claude).toEqual({ source: 'sign-in', origin: 'default' })
|
||||
view = await h.call('PUT', '/v1/agent-sources/offer', { bearer: mia, body: { agent: 'claude', answer: 'declined' } })
|
||||
expect(view.body.signInOffer.claude).toBe('declined')
|
||||
// Ada's answers are hers alone.
|
||||
expect((await h.call('GET', '/v1/agent-sources', { bearer: ada })).body.signInOffer.claude).toBe('unanswered')
|
||||
expect((await h.call('PUT', '/v1/agent-sources', { bearer: mia, body: { agent: 'gemini', source: 'key' } })).status).toBe(400)
|
||||
})
|
||||
|
||||
it('"Your sign-in" keeps that agent\'s credentials (incl. gateway-derived) out of the session, live, and only that agent\'s', async () => {
|
||||
const { h, as, put, lastEnv } = await setup({ SECRETS_EGRESS_PLACEHOLDERS: 'on', EGRESS_PROXY_URL: PROXY_URL })
|
||||
const ada = await as('ada', 'acme', 'admin')
|
||||
const mia = await as('mia', 'acme', 'member', 'Mia Chen')
|
||||
await put('org', 'AI_GATEWAY_API_KEY', GATEWAY_KEY, ada)
|
||||
await put('personal', 'APP_MODE', 'dev', mia)
|
||||
const created = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-1', machineSize: 'standard' }, bearer: mia })
|
||||
const id: string = created.body.sandbox.id
|
||||
expect(Object.keys(lastEnv(START_COMMAND))).toEqual(expect.arrayContaining(['ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_BASE_URL', 'OPENAI_API_KEY']))
|
||||
const view = await h.call('PUT', '/v1/agent-sources', { bearer: mia, body: { agent: 'claude', source: 'sign-in', workspaceId: id } })
|
||||
expect(view.body.effective.claude).toEqual({ source: 'sign-in', origin: 'workspace' })
|
||||
expect(view.body.owner).toEqual({ userId: 'mia', displayName: 'Mia Chen', isCaller: true })
|
||||
const env = lastEnv(ENV_COMMAND)
|
||||
for (const name of AGENT_CREDENTIAL_NAMES.claude) {
|
||||
expect(env[name]).toBeUndefined()
|
||||
}
|
||||
expect(env.OPENAI_API_KEY).toMatch(/^orca-ph-openai-api-key-/)
|
||||
expect(env.APP_MODE).toBe('dev')
|
||||
const row = await h.env.SANDBOX_DB.prepare('SELECT egress_secret_hosts FROM sandboxes WHERE id = ?').bind(id).first<{ egress_secret_hosts: string }>()
|
||||
expect(row!.egress_secret_hosts).not.toContain('ANTHROPIC')
|
||||
// Back to the key: it returns in new shells.
|
||||
await h.call('PUT', '/v1/agent-sources', { bearer: mia, body: { agent: 'claude', source: null, workspaceId: id } })
|
||||
expect(lastEnv(ENV_COMMAND).ANTHROPIC_AUTH_TOKEN).toMatch(/^orca-ph-anthropic-auth-token-/)
|
||||
})
|
||||
|
||||
it('a default applies to running sandboxes without an override; only the owner sets a workspace source', async () => {
|
||||
const { h, as, put, lastEnv } = await setup()
|
||||
const ada = await as('ada', 'acme', 'admin', 'Ada Lovelace')
|
||||
const mia = await as('mia', 'acme', 'member')
|
||||
await put('org', 'OPENAI_API_KEY', 'sk-proj-team-fake-1234-zzzz', ada)
|
||||
const created = await h.call('POST', '/v1/sandboxes', { body: { workspaceId: 'ws-ada', machineSize: 'standard' }, bearer: ada })
|
||||
const id: string = created.body.sandbox.id
|
||||
await h.call('PUT', '/v1/agent-sources', { bearer: ada, body: { agent: 'codex', source: 'sign-in' } })
|
||||
expect(lastEnv(ENV_COMMAND).OPENAI_API_KEY).toBeUndefined()
|
||||
const forbidden = await h.call('PUT', '/v1/agent-sources', { bearer: mia, body: { agent: 'codex', source: 'key', workspaceId: id } })
|
||||
expect(forbidden.status).toBe(403)
|
||||
expect(forbidden.body.reason).toBe('owner_only')
|
||||
const teammate = await h.call('GET', `/v1/agent-sources?workspaceId=${id}`, { bearer: mia })
|
||||
expect(teammate.body.owner).toEqual({ userId: 'ada', displayName: 'Ada Lovelace', isCaller: false })
|
||||
expect(teammate.body.effective.codex).toEqual({ source: 'sign-in', origin: 'default' })
|
||||
expect((await h.call('GET', `/v1/agent-sources?workspaceId=${id}`, { bearer: await as('zed', 'other', 'admin') })).status).toBe(404)
|
||||
})
|
||||
|
||||
it('a workspace source set while the sandbox is still starting applies at its first boot (D9)', async () => {
|
||||
const { h, as, put, lastEnv } = await setup()
|
||||
const mia = await as('mia')
|
||||
await put('personal', 'ANTHROPIC_API_KEY', TEAM_KEY, mia)
|
||||
const id = 'sbx_creating_fake'
|
||||
await h.env.SANDBOX_DB.prepare(
|
||||
`INSERT INTO sandboxes (id, account_id, user_id, workspace_id, provider, provider_name, status, machine_size, region, generation, created_at, updated_at)
|
||||
VALUES (?, 'user:mia', 'mia', 'ws-c', 'vercel', 'orca-test-x', 'creating', 'standard', 'iad1', 0, 1, 1)`
|
||||
).bind(id).run()
|
||||
const put1 = await h.call('PUT', '/v1/agent-sources', { bearer: mia, body: { agent: 'claude', source: 'sign-in', workspaceId: id } })
|
||||
expect(put1.status).toBe(200)
|
||||
expect(put1.body.effective.claude.source).toBe('sign-in')
|
||||
})
|
||||
})
|
||||
@@ -191,7 +191,7 @@ describe('member removal', () => {
|
||||
const { secret } = (await h.call('POST', '/v1/api-keys', { bearer: member, body: { name: 'bob ci', scopes: ['workspaces:read'] } })).body
|
||||
expect((await h.call('GET', '/v1/me', { bearer: secret })).status).toBe(200)
|
||||
const removed = await h.call('POST', '/v1/internal/members/removed', { bearer: 'o'.repeat(40), body: { accountId: 'org:acme', userId: 'bob' } })
|
||||
expect(removed.body).toEqual({ revoked: 1, keysRevoked: 1, devicesRevoked: 0, grantsRevoked: 0, grantsQueued: 0, routinesDisabled: 0 })
|
||||
expect(removed.body).toEqual({ revoked: 1, keysRevoked: 1, devicesRevoked: 0, grantsRevoked: 0, grantsQueued: 0, routinesDisabled: 0, readerKeysRevoked: 0 })
|
||||
expect((await h.call('GET', '/v1/me', { bearer: secret })).status).toBe(401)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -83,6 +83,10 @@ export type FakeVercel = SandboxProviderApi & GoldenImageProviderApi & {
|
||||
snapshotExpirations: Map<string, number>
|
||||
/** Simulates the provider ending a session at its timeout. */
|
||||
expire(name: string): void
|
||||
/** activeCpuDurationMs per session, as GET session reports it once stopped (stop answers without it). */
|
||||
sessionCpu: Map<string, number>
|
||||
/** GET session fails (provider outage) when set. */
|
||||
failSessionUsage: boolean
|
||||
}
|
||||
|
||||
export function createFakeVercel(now: () => number): FakeVercel {
|
||||
@@ -122,6 +126,8 @@ export function createFakeVercel(now: () => number): FakeVercel {
|
||||
|
||||
const buildCommands = new Map<string, FakeBuildCommand>()
|
||||
const fake: FakeVercel = {
|
||||
sessionCpu: new Map(),
|
||||
failSessionUsage: false,
|
||||
boxes,
|
||||
snapshots,
|
||||
commands,
|
||||
@@ -222,7 +228,19 @@ export function createFakeVercel(now: () => number): FakeVercel {
|
||||
},
|
||||
async stopSession(sessionId) {
|
||||
const box = bySession(sessionId)
|
||||
return { snapshotId: box.status === 'running' ? stop(box) : null }
|
||||
const startedAt = box.startedAt
|
||||
const snapshotId = box.status === 'running' ? stop(box) : null
|
||||
return {
|
||||
snapshotId,
|
||||
usage: { sessionId, status: 'stopped', activeCpuMs: null, durationMs: now() - startedAt, vcpus: box.params.vcpus, memoryMb: box.params.vcpus * 2048, stoppedAt: now() }
|
||||
}
|
||||
},
|
||||
async getSessionUsage(sessionId) {
|
||||
if (fake.failSessionUsage) {
|
||||
throw new ProviderError(503, null)
|
||||
}
|
||||
const cpu = fake.sessionCpu.get(sessionId)
|
||||
return cpu === undefined ? null : { sessionId, status: 'stopped', activeCpuMs: cpu, durationMs: null, vcpus: null, memoryMb: null, stoppedAt: null }
|
||||
},
|
||||
async extendTimeout(sessionId, durationMs) {
|
||||
const box = bySession(sessionId)
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
// orca-env (image/vm/orca-env): prints lines that bring a running shell up to date with the session
|
||||
// env file. Values must survive quoting exactly (quotes, newlines, $, backslashes) in POSIX shells
|
||||
// and fish, and names that were removed must be unset.
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { 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'
|
||||
|
||||
const ORCA_ENV = fileURLToPath(new URL('../image/vm/orca-env', import.meta.url).href)
|
||||
|
||||
const TRICKY: Record<string, string> = {
|
||||
SINGLE: "it's a 'quoted' value",
|
||||
DOUBLE: 'say "hi" and \\"escaped\\"',
|
||||
DOLLAR: '$HOME $(touch /tmp/orca-env-pwned) `id` ${PATH}',
|
||||
NEWLINES: 'line one\nline two\n\n',
|
||||
BACKSLASH: 'C:\\path\\to\\ \\n not-a-newline \\',
|
||||
SEMI: 'a; echo pwned; b && c | d',
|
||||
EMPTY: ''
|
||||
}
|
||||
|
||||
let dir = ''
|
||||
let envFile = ''
|
||||
|
||||
beforeEach(() => {
|
||||
dir = mkdtempSync(join(tmpdir(), 'orca-env-'))
|
||||
envFile = join(dir, 'session.env')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
function writeSessionEnv(values: Record<string, string>, extraLines: string[] = []): void {
|
||||
const lines = Object.entries(values).map(([name, value]) => `${name}=${Buffer.from(value).toString('base64')}`)
|
||||
writeFileSync(envFile, [...lines, ...extraLines].join('\n') + '\n')
|
||||
}
|
||||
|
||||
function orcaEnv(args: string[], names = ''): string {
|
||||
const result = spawnSync('bash', [ORCA_ENV, ...args], {
|
||||
encoding: 'utf8',
|
||||
env: { PATH: process.env.PATH, ORCA_SESSION_ENV_FILE: envFile, ORCA_SESSION_ENV_NAMES: names }
|
||||
})
|
||||
expect(result.stderr).toBe('')
|
||||
expect(result.status).toBe(0)
|
||||
return result.stdout
|
||||
}
|
||||
|
||||
/** Runs `script` in `shell` and returns the env it ends with, read back as JSON through node. */
|
||||
function envAfter(shell: string, args: string[], script: string, initial: Record<string, string> = {}) {
|
||||
const dump = `"${process.execPath}" -e 'process.stdout.write(JSON.stringify(process.env))'`
|
||||
const result = spawnSync(shell, ['-c', `${script}\n${dump}`], {
|
||||
encoding: 'utf8',
|
||||
env: {
|
||||
PATH: process.env.PATH,
|
||||
// A throwaway HOME keeps this machine's rc files out of it.
|
||||
HOME: dir,
|
||||
ORCA_SESSION_ENV_FILE: envFile,
|
||||
ORCA_ENV_BIN: ORCA_ENV,
|
||||
...initial
|
||||
}
|
||||
})
|
||||
expect(result.stderr, shell).toBe('')
|
||||
return JSON.parse(result.stdout) as Record<string, string>
|
||||
}
|
||||
|
||||
function hasShell(shell: string): boolean {
|
||||
return !spawnSync(shell, ['-c', 'true']).error
|
||||
}
|
||||
|
||||
describe('orca-env', () => {
|
||||
it('exports every session name with its exact value in bash, sh and zsh', () => {
|
||||
writeSessionEnv(TRICKY)
|
||||
for (const shell of ['bash', 'sh', 'zsh'].filter(hasShell)) {
|
||||
const env = envAfter(shell, [], 'eval "$(bash "$ORCA_ENV_BIN")"')
|
||||
for (const [name, value] of Object.entries(TRICKY)) {
|
||||
expect(env[name], `${shell} ${name}`).toBe(value)
|
||||
}
|
||||
expect(env.ORCA_SESSION_ENV_NAMES).toBe(Object.keys(TRICKY).join(' '))
|
||||
}
|
||||
})
|
||||
|
||||
it('exports the exact values in fish', () => {
|
||||
if (!hasShell('fish')) {
|
||||
return
|
||||
}
|
||||
writeSessionEnv(TRICKY)
|
||||
const env = envAfter('fish', ['--fish'], 'bash $ORCA_ENV_BIN --fish | source')
|
||||
for (const [name, value] of Object.entries(TRICKY)) {
|
||||
expect(env[name], name).toBe(value)
|
||||
}
|
||||
})
|
||||
|
||||
it('unsets names the session env no longer has, in POSIX shells and fish', () => {
|
||||
writeSessionEnv({ KEPT: 'new' })
|
||||
const initial = { KEPT: 'old', GONE: 'stale', MINE: 'untouched', ORCA_SESSION_ENV_NAMES: 'KEPT GONE' }
|
||||
expect(orcaEnv([], 'KEPT GONE')).toContain('unset GONE\n')
|
||||
expect(orcaEnv(['--fish'], 'KEPT GONE')).toContain('set -e GONE\n')
|
||||
const shells: [string, string][] = [['bash', 'eval "$(bash "$ORCA_ENV_BIN")"']]
|
||||
if (hasShell('fish')) {
|
||||
shells.push(['fish', 'bash $ORCA_ENV_BIN --fish | source'])
|
||||
}
|
||||
for (const [shell, script] of shells) {
|
||||
const env = envAfter(shell, [], script, initial)
|
||||
expect(env.KEPT, shell).toBe('new')
|
||||
expect(env.GONE, shell).toBeUndefined()
|
||||
expect(env.MINE, shell).toBe('untouched')
|
||||
expect(env.ORCA_SESSION_ENV_NAMES, shell).toBe('KEPT')
|
||||
}
|
||||
})
|
||||
|
||||
it('skips names the shell hook skips and globs nothing', () => {
|
||||
writeSessionEnv({ GOOD: 'x' }, ['PATH=L3RtcA==', 'ORCA_X=eA==', 'LD_PRELOAD=eA==', 'lower=eA==', 'not a line'])
|
||||
const out = orcaEnv([], '* ORCA_TOKEN')
|
||||
expect(out).toBe("export GOOD='x'\nexport ORCA_SESSION_ENV_NAMES='GOOD'\n")
|
||||
})
|
||||
|
||||
it("never sets or unsets the control plane's reserved names and prefixes (kept in sync with secrets.ts)", () => {
|
||||
const source = readFileSync(fileURLToPath(new URL('../src/secrets.ts', import.meta.url).href), 'utf8')
|
||||
const quoted = (text: string | undefined): string[] => [...(text ?? '').matchAll(/'([A-Z0-9_]+)'/g)].map((m) => m[1])
|
||||
const names = quoted(source.match(/const RESERVED_NAMES[^=]*= new Set\(\[([\s\S]*?)\]\)/)?.[1])
|
||||
const prefixes = quoted(source.match(/const RESERVED_PREFIXES = \[([^\]]*)\]/)?.[1])
|
||||
expect(names.length).toBeGreaterThan(30)
|
||||
expect(prefixes.length).toBeGreaterThan(3)
|
||||
const blocked = [...names, ...prefixes.map((prefix) => `${prefix}X`)]
|
||||
writeSessionEnv({ GOOD: 'x', ...Object.fromEntries(blocked.map((name) => [name, 'evil'])) })
|
||||
const out = orcaEnv([], blocked.join(' '))
|
||||
expect(out).toBe("export GOOD='x'\nexport ORCA_SESSION_ENV_NAMES='GOOD'\n")
|
||||
})
|
||||
|
||||
it('prints nothing before the session env exists and never writes a file', () => {
|
||||
const result = spawnSync('bash', [ORCA_ENV], {
|
||||
encoding: 'utf8',
|
||||
cwd: dir,
|
||||
env: { PATH: process.env.PATH, ORCA_SESSION_ENV_FILE: join(dir, 'missing'), ORCA_SESSION_ENV_NAMES: 'A B' }
|
||||
})
|
||||
expect(result.status).toBe(0)
|
||||
expect(result.stdout).toBe('')
|
||||
expect(spawnSync('ls', ['-A', dir], { encoding: 'utf8' }).stdout).toBe('')
|
||||
})
|
||||
|
||||
it('rejects unknown options', () => {
|
||||
const result = spawnSync('bash', [ORCA_ENV, '--zsh'], { encoding: 'utf8' })
|
||||
expect(result.status).toBe(2)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,323 @@
|
||||
import { mkdtempSync } from 'node:fs'
|
||||
import { createRequire } from 'node:module'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { DatabaseSync } from 'node:sqlite'
|
||||
import { SignJWT, exportJWK, generateKeyPair } from 'jose'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { generateGrantRecipientKey, nodeSealedGrantPrimitives } from '../../../../src/main/cloud-workspaces/sealed-grant-node'
|
||||
import { openReadSnapshot, type ReadSnapshot } from '../../../../src/shared/cloud-workspaces/read-snapshot'
|
||||
import type { RunCommandParams } from '../src/sandbox-provider'
|
||||
import { MAX_READ_RECIPIENTS, READ_SNAPSHOT_COMMAND } from '../src/read-snapshots'
|
||||
import { createHarness } from './harness'
|
||||
|
||||
// The real VM collector + sealer (image/vm/orca-read-snapshot.cjs), fed a fake orcad.
|
||||
const require = createRequire(import.meta.url)
|
||||
const vm = require('../image/vm/orca-read-snapshot.cjs') as {
|
||||
seal: (payload: unknown, recipients: unknown[], workspaceId: string, snapshotId: string) => Record<string, unknown>
|
||||
gather: (call: (method: string, params: unknown) => Promise<unknown>, opts: Record<string, unknown>) => Promise<Record<string, unknown>>
|
||||
fitToBudget: <T>(payload: T, maxBytes?: number) => T
|
||||
storedSessions: (dataDir: string) => Record<string, unknown>[]
|
||||
}
|
||||
|
||||
const SECRET_LINE = 'the deploy key is in 1password, not in the repo'
|
||||
|
||||
function fakeOrcad(method: string, params?: unknown): unknown {
|
||||
switch (method) {
|
||||
case 'worktree.ps':
|
||||
return {
|
||||
worktrees: [
|
||||
{
|
||||
path: '/vercel/sandbox/project',
|
||||
// Live right now: its status wins over the stored one.
|
||||
agents: [{ paneKey: 'structured-agent-session-chat-2:leaf-1', agentType: 'codex', state: 'working', conversationName: 'Add tests', updatedAt: 1 }],
|
||||
linkedPR: { number: 42, title: 'Fix login', state: 'open', url: 'https://github.com/acme/app/pull/42', checksStatus: 'success', checksSummary: '3/3 passed' }
|
||||
}
|
||||
]
|
||||
}
|
||||
case 'git.status':
|
||||
return { branch: 'refs/heads/fix/login', head: 'abc1234', entries: [{ path: 'src/login.ts', status: 'modified', area: 'unstaged', added: 12, removed: 3 }] }
|
||||
case 'git.history':
|
||||
return { items: [{ id: 'abc1234', subject: 'Fix the login redirect', author: 'Alice', timestamp: 1 }] }
|
||||
case 'agentSession.history':
|
||||
// chat-2 has no readable history yet: its stored last turn stands in.
|
||||
if ((params as { sessionId?: string })?.sessionId === 'chat-2') {
|
||||
return null
|
||||
}
|
||||
return {
|
||||
page: {
|
||||
hasOlder: false,
|
||||
items: [
|
||||
{ itemId: 'i1', observedAt: 1, body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'Why does login loop?' }] } },
|
||||
{ itemId: 'i2', observedAt: 2, body: { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: SECRET_LINE }] } },
|
||||
{ itemId: 'i3', observedAt: 3, body: { kind: 'tool', blocks: [] } }
|
||||
]
|
||||
}
|
||||
}
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** What orca-sandbox-read-snapshot does on a VM, minus the socket: gather from orcad, then seal. */
|
||||
async function runVmSealer(params: RunCommandParams): Promise<string> {
|
||||
const env = params.env ?? {}
|
||||
const payload = vm.fitToBudget(
|
||||
await vm.gather(async (method, params) => fakeOrcad(method, params), {
|
||||
workspaceId: env.ORCA_READ_WORKSPACE_ID,
|
||||
snapshotId: env.ORCA_READ_SNAPSHOT_ID,
|
||||
reason: env.ORCA_READ_REASON,
|
||||
now: 1_800_000_000_000,
|
||||
deadline: Date.now() + 10_000,
|
||||
// What orcad's session store holds (agent-session-journal.db on the VM).
|
||||
listSessions: () => [
|
||||
{ sessionId: 'chat-1', agent: 'claude', title: 'Fix login', status: 'idle', turnOutcome: 'success', updatedAt: 2, open: true },
|
||||
{ sessionId: 'chat-2', agent: 'codex', title: 'Add tests', status: 'idle', updatedAt: 1, open: true, lastPrompt: 'Add tests', lastReply: null, lastAt: 1 }
|
||||
]
|
||||
})
|
||||
)
|
||||
const out = vm.seal(payload, JSON.parse(env.ORCA_READ_RECIPIENTS ?? '[]'), env.ORCA_READ_WORKSPACE_ID!, env.ORCA_READ_SNAPSHOT_ID!)
|
||||
return `${JSON.stringify(out)}\n`
|
||||
}
|
||||
|
||||
async function setup() {
|
||||
vi.spyOn(console, 'log').mockImplementation((line: string) => { if (process.env.DBG && String(line).includes('read_snapshot')) process.stderr.write(line + '\n') })
|
||||
const h = await createHarness({ OPERATOR_TOKEN: 'o'.repeat(40) })
|
||||
// The fake's runCommand awaits whatever the handler returns, so the real (async) sealer can run.
|
||||
let vmUp = true
|
||||
h.vercel.commandHandler = ((params: RunCommandParams) => {
|
||||
if (params.command !== READ_SNAPSHOT_COMMAND) {
|
||||
return undefined
|
||||
}
|
||||
return vmUp
|
||||
? runVmSealer(params).then((stdout) => ({ exitCode: 0, stdout, stderr: '' }))
|
||||
: { exitCode: 3, stdout: '', stderr: 'orcad not running' }
|
||||
}) as never
|
||||
type Who = { sub: string; org: string; role: 'owner' | 'admin' | 'member' }
|
||||
const as = (sub: string, role: Who['role'] = 'member', org = 'acme'): Who => ({ sub, org, role })
|
||||
const req = async (who: Who, method: string, path: string, body?: unknown) =>
|
||||
h.call(method, path, { bearer: await h.token(who.sub, who.org, 'sandbox', { org_role: who.role }), body })
|
||||
const alice = as('alice')
|
||||
const bob = as('bob')
|
||||
const created = await req(alice, 'POST', '/v1/sandboxes', {
|
||||
workspaceId: 'ws-1',
|
||||
machineSize: 'standard',
|
||||
title: 'Fix login',
|
||||
repo: { url: 'https://github.com/acme/app', ref: 'fix/login' }
|
||||
})
|
||||
expect(created.status).toBe(200)
|
||||
const id = created.body.sandbox.id as string
|
||||
const register = async (who: Who, kind: 'desktop' | 'mobile' = 'desktop', bearer?: string) => {
|
||||
const key = generateGrantRecipientKey()
|
||||
const res = bearer
|
||||
? await h.call('PUT', '/v1/reader-keys', { bearer, body: { publicKeyB64: key.publicKeyB64, deviceLabel: `${who.sub} ${kind}`, deviceKind: kind } })
|
||||
: await req(who, 'PUT', '/v1/reader-keys', { publicKeyB64: key.publicKeyB64, deviceLabel: `${who.sub} ${kind}`, deviceKind: kind })
|
||||
expect(res.status).toBe(200)
|
||||
return { ...key, id: res.body.readerKey.id as string }
|
||||
}
|
||||
/** Sleep the workspace (the drain seals first). `orcadDown`: the VM script finds no orcad. */
|
||||
const sleep = async (who: Who = alice, orcadDown = false) => {
|
||||
vmUp = !orcadDown
|
||||
return req(who, 'POST', `/v1/sandboxes/${id}/suspend`)
|
||||
}
|
||||
const read = (who: Who, keyId: string, bearer?: string) =>
|
||||
bearer
|
||||
? h.call('GET', `/v1/team/workspaces/${id}/read-snapshot?keyId=${keyId}`, { bearer })
|
||||
: req(who, 'GET', `/v1/team/workspaces/${id}/read-snapshot?keyId=${keyId}`)
|
||||
const open = async (body: { snapshot: never }, secretKey: Uint8Array): Promise<ReadSnapshot> =>
|
||||
openReadSnapshot(body.snapshot, id, secretKey, nodeSealedGrantPrimitives)
|
||||
return { h, req, as, alice, bob, id, register, sleep, read, open }
|
||||
}
|
||||
|
||||
describe('read snapshots of sleeping workspaces (E2EE)', () => {
|
||||
it('seals at sleep to the owner devices; the control plane stores only ciphertext; the VM stays asleep', async () => {
|
||||
const t = await setup()
|
||||
const laptop = await t.register(t.alice)
|
||||
const phone = await t.register(t.alice, 'mobile')
|
||||
expect((await t.sleep()).status).toBe(200)
|
||||
const row = t.h.raw.prepare('SELECT status FROM sandboxes WHERE id = ?').get(t.id) as { status: string }
|
||||
expect(row.status).toBe('suspended')
|
||||
|
||||
const before = t.h.vercel.commands.length
|
||||
for (const key of [laptop, phone]) {
|
||||
const res = await t.read(t.alice, key.id)
|
||||
expect(res.status).toBe(200)
|
||||
const snap = await t.open(res.body, key.secretKey)
|
||||
expect(snap.sessions.map((s) => [s.agent, s.title, s.status])).toEqual([
|
||||
['claude', 'Fix login', 'idle'],
|
||||
['codex', 'Add tests', 'working']
|
||||
])
|
||||
expect(snap.sessions[0]!.messages.map((m) => m.text)).toEqual(['Why does login loop?', SECRET_LINE])
|
||||
expect(snap.git).toMatchObject({ branch: 'fix/login', changeCount: 1, added: 12, removed: 3 })
|
||||
expect(snap.pr).toMatchObject({ number: 42, url: 'https://github.com/acme/app/pull/42', checksStatus: 'success' })
|
||||
// Only this device's wrapped key is handed out.
|
||||
expect(res.body.snapshot.recipient.keyId).toBe(key.id)
|
||||
}
|
||||
// Reading never touched the VM.
|
||||
expect(t.h.vercel.commands.length).toBe(before)
|
||||
expect((t.h.raw.prepare('SELECT status FROM sandboxes WHERE id = ?').get(t.id) as { status: string }).status).toBe('suspended')
|
||||
// Nothing readable at rest.
|
||||
const dump = JSON.stringify([
|
||||
t.h.raw.prepare('SELECT * FROM read_snapshots').all(),
|
||||
t.h.raw.prepare('SELECT * FROM read_snapshot_keys').all()
|
||||
])
|
||||
expect(dump).not.toContain('1password')
|
||||
expect(dump).not.toContain('login loop')
|
||||
// The list says when, for "As of" without fetching the blob.
|
||||
const list = await t.req(t.alice, 'GET', '/v1/team/workspaces?scope=mine')
|
||||
expect(list.body.workspaces[0].readSnapshotAt).toBe(t.h.now())
|
||||
})
|
||||
|
||||
it('opens for teammates only on team workspaces; private stays owner-only; bad keys and other people’s keys are refused', async () => {
|
||||
const t = await setup()
|
||||
const own = await t.register(t.alice)
|
||||
const bobs = await t.register(t.bob)
|
||||
await t.sleep()
|
||||
// Private: Bob can't see it at all, and was never a recipient.
|
||||
expect((await t.read(t.bob, bobs.id)).body).toEqual({ error: 'not_found' })
|
||||
await t.req(t.alice, 'POST', `/v1/sandboxes/${t.id}/resume`)
|
||||
await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${t.id}`, { visibility: 'team' })
|
||||
await t.sleep()
|
||||
const res = await t.read(t.bob, bobs.id)
|
||||
expect(res.status).toBe(200)
|
||||
expect((await t.open(res.body, bobs.secretKey)).sessions).toHaveLength(2)
|
||||
// Bob can't fetch Alice's wrapped key, nor open his blob with another key.
|
||||
expect((await t.read(t.bob, own.id)).status).toBe(400)
|
||||
await expect(t.open(res.body, own.secretKey)).rejects.toThrow('decrypt_failed')
|
||||
// Another org's member sees nothing.
|
||||
const mallory = t.as('mallory', 'member', 'evil')
|
||||
const mk = await t.register(mallory)
|
||||
expect((await t.read(mallory, mk.id)).status).toBe(404)
|
||||
})
|
||||
|
||||
it('making it private prunes teammates at once, without the VM', async () => {
|
||||
const t = await setup()
|
||||
await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${t.id}`, { visibility: 'team' })
|
||||
const own = await t.register(t.alice)
|
||||
const bobs = await t.register(t.bob)
|
||||
await t.sleep()
|
||||
expect((await t.read(t.bob, bobs.id)).status).toBe(200)
|
||||
await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${t.id}`, { visibility: 'private' })
|
||||
expect((await t.read(t.bob, bobs.id)).status).toBe(404)
|
||||
expect(t.h.raw.prepare('SELECT key_id FROM read_snapshot_keys').all()).toEqual([{ key_id: own.id }])
|
||||
// Even back to team: Bob's wrapped key is gone until the next sleep re-seals.
|
||||
await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${t.id}`, { visibility: 'team' })
|
||||
expect((await t.read(t.bob, bobs.id)).body).toEqual({ error: 'not_sealed_for_key' })
|
||||
})
|
||||
|
||||
it('a removed member can no longer read, and their wrapped keys are deleted', async () => {
|
||||
const t = await setup()
|
||||
await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${t.id}`, { visibility: 'team' })
|
||||
await t.register(t.alice)
|
||||
const bobs = await t.register(t.bob)
|
||||
await t.sleep()
|
||||
expect((await t.read(t.bob, bobs.id)).status).toBe(200)
|
||||
const removed = await t.h.call('POST', '/v1/internal/org-members/removed', { bearer: 'o'.repeat(40), body: { accountId: 'org:acme', userId: 'bob' } })
|
||||
expect(removed.body.readerKeysRevoked).toBe(1)
|
||||
// A token minted after removal (stale org claim) still gets nothing: key revoked, wrapped key gone.
|
||||
t.h.advance(1000)
|
||||
const again = await t.read(t.bob, bobs.id)
|
||||
expect(again.status).not.toBe(200)
|
||||
expect(t.h.raw.prepare('SELECT key_id FROM read_snapshot_keys WHERE key_id = ?').all(bobs.id)).toEqual([])
|
||||
// Next sleep is not sealed to him either.
|
||||
await t.req(t.alice, 'POST', `/v1/sandboxes/${t.id}/resume`)
|
||||
await t.sleep()
|
||||
expect(t.h.raw.prepare('SELECT key_id FROM read_snapshot_keys WHERE key_id = ?').all(bobs.id)).toEqual([])
|
||||
})
|
||||
|
||||
it('a device added after the last sleep gets not_sealed_for_key; no snapshot yet is no_snapshot', async () => {
|
||||
const t = await setup()
|
||||
const first = await t.register(t.alice)
|
||||
expect((await t.read(t.alice, first.id)).body).toEqual({ error: 'no_snapshot' })
|
||||
await t.sleep()
|
||||
const later = await t.register(t.alice)
|
||||
expect((await t.read(t.alice, later.id)).body).toEqual({ error: 'not_sealed_for_key' })
|
||||
expect((await t.read(t.alice, 'rk_nope')).status).toBe(400)
|
||||
})
|
||||
|
||||
it('registration is idempotent, per member capped, and a key revoke drops its wrapped key', async () => {
|
||||
const t = await setup()
|
||||
const key = generateGrantRecipientKey()
|
||||
const body = { publicKeyB64: key.publicKeyB64, deviceLabel: 'Mac', deviceKind: 'desktop' }
|
||||
const a = await t.req(t.alice, 'PUT', '/v1/reader-keys', body)
|
||||
const b = await t.req(t.alice, 'PUT', '/v1/reader-keys', body)
|
||||
expect(a.body.readerKey.id).toBe(b.body.readerKey.id)
|
||||
expect((await t.req(t.alice, 'PUT', '/v1/reader-keys', { ...body, publicKeyB64: 'AAAA' })).status).toBe(400)
|
||||
await t.sleep()
|
||||
expect((await t.read(t.alice, a.body.readerKey.id)).status).toBe(200)
|
||||
expect((await t.req(t.bob, 'DELETE', `/v1/reader-keys/${a.body.readerKey.id}`)).status).toBe(404)
|
||||
expect((await t.req(t.alice, 'DELETE', `/v1/reader-keys/${a.body.readerKey.id}`)).body).toEqual({ ok: true })
|
||||
expect((await t.read(t.alice, a.body.readerKey.id)).status).toBe(400)
|
||||
// Re-registering a revoked key yields a new id (never resurrected), with nothing sealed to it.
|
||||
const c = await t.req(t.alice, 'PUT', '/v1/reader-keys', body)
|
||||
expect(c.body.readerKey.id).not.toBe(a.body.readerKey.id)
|
||||
for (let i = 0; i < 14; i++) {
|
||||
await t.register(t.alice)
|
||||
}
|
||||
expect((await t.req(t.alice, 'GET', '/v1/reader-keys')).body.readerKeys).toHaveLength(12)
|
||||
})
|
||||
|
||||
it('a phone key dies with its device session', async () => {
|
||||
const t = await setup()
|
||||
const { privateKey, publicKey } = await generateKeyPair('Ed25519', { extractable: true })
|
||||
const publicKeyB64 = Buffer.from((await exportJWK(publicKey)).x!, 'base64url').toString('base64')
|
||||
const enrolled = await t.h.call('POST', '/v1/device-sessions', {
|
||||
body: { label: 'iPhone', platform: 'ios', publicKeyB64 },
|
||||
bearer: await t.h.token('alice', 'acme', 'sandbox', { org_role: 'member' })
|
||||
})
|
||||
const sessionId = enrolled.body.deviceSession.id as string
|
||||
const phoneToken = async () => {
|
||||
const iat = Math.floor(t.h.now() / 1000)
|
||||
return new SignJWT({}).setProtectedHeader({ alg: 'EdDSA', kid: sessionId }).setIssuer('orca-device').setSubject(sessionId)
|
||||
.setAudience('orca-sandbox').setIssuedAt(iat).setExpirationTime(iat + 120).sign(privateKey)
|
||||
}
|
||||
const key = await t.register(t.alice, 'mobile', await phoneToken())
|
||||
await t.sleep()
|
||||
const res = await t.read(t.alice, key.id, await phoneToken())
|
||||
expect(res.status).toBe(200)
|
||||
expect((await t.open(res.body, key.secretKey)).sessions[0]!.messages[1]!.text).toBe(SECRET_LINE)
|
||||
await t.h.call('DELETE', `/v1/device-sessions/${sessionId}`, { bearer: await t.h.token('alice', 'acme') })
|
||||
expect(t.h.raw.prepare('SELECT revoked_by FROM reader_keys WHERE id = ?').get(key.id)).toEqual({ revoked_by: 'system:device_revoked' })
|
||||
expect(t.h.raw.prepare('SELECT * FROM read_snapshot_keys WHERE key_id = ?').all(key.id)).toEqual([])
|
||||
})
|
||||
|
||||
it('a failed capture keeps the previous snapshot and never blocks the sleep', async () => {
|
||||
const t = await setup()
|
||||
const key = await t.register(t.alice)
|
||||
await t.sleep()
|
||||
const first = (await t.read(t.alice, key.id)).body.snapshot.snapshotId
|
||||
await t.req(t.alice, 'POST', `/v1/sandboxes/${t.id}/resume`)
|
||||
// The VM script finds no orcad (exit 3).
|
||||
expect((await t.sleep(t.alice, true)).status).toBe(200)
|
||||
expect((await t.read(t.alice, key.id)).body.snapshot.snapshotId).toBe(first)
|
||||
})
|
||||
|
||||
it('the VM sealer bounds what it seals and caps recipients', () => {
|
||||
const big = {
|
||||
v: 1,
|
||||
sessions: Array.from({ length: 3 }, (_, i) => ({ sessionId: `s${i}`, messages: Array.from({ length: 60 }, (_, j) => ({ itemId: `${j}`, role: 'user', text: 'x'.repeat(4000), at: j })) })),
|
||||
git: { changes: [] }
|
||||
}
|
||||
const fitted = vm.fitToBudget(big, 150_000)
|
||||
expect(Buffer.byteLength(JSON.stringify(fitted))).toBeLessThanOrEqual(150_000)
|
||||
expect(MAX_READ_RECIPIENTS).toBe(64)
|
||||
// A malformed recipient is skipped, not fatal.
|
||||
const out = vm.seal({ v: 1 }, [{ keyId: 'rk_bad', publicKeyB64: 'x' }, { keyId: 'rk_000000000000000000000000', publicKeyB64: generateGrantRecipientKey().publicKeyB64 }], 'sbx_0', 'rsn_0') as { recipients: unknown[] }
|
||||
expect(out.recipients).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('lists chats from orcad’s session store (read-only), open tabs and last turns included', () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'orcad-'))
|
||||
const db = new DatabaseSync(join(dir, 'agent-session-journal.db'))
|
||||
db.exec('CREATE TABLE agent_session_records (session_id TEXT PRIMARY KEY, record_json TEXT NOT NULL); CREATE TABLE agent_session_tabs (tab_id TEXT PRIMARY KEY, session_id TEXT NOT NULL, position INTEGER NOT NULL)')
|
||||
const record = { provider: 'claude', conversationName: 'Gap5 live check', updatedAt: 5, lastTurn: { state: 'settled', outcome: 'success', prompt: 'What is this repo?', reply: 'Hello World!', at: 4 } }
|
||||
db.prepare('INSERT INTO agent_session_records VALUES (?, ?)').run('claude_1', JSON.stringify(record))
|
||||
db.prepare('INSERT INTO agent_session_records VALUES (?, ?)').run('broken', '{not json')
|
||||
db.prepare('INSERT INTO agent_session_tabs VALUES (?, ?, 0)').run('structured-agent-session-claude_1', 'claude_1')
|
||||
db.close()
|
||||
expect(vm.storedSessions(dir)).toEqual([
|
||||
expect.objectContaining({ sessionId: 'claude_1', agent: 'claude', title: 'Gap5 live check', status: 'idle', turnOutcome: 'success', open: true, lastPrompt: 'What is this repo?', lastReply: 'Hello World!' })
|
||||
])
|
||||
expect(vm.storedSessions(join(dir, 'missing'))).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { ORCA_CLOUD_IMAGE_AGENTS } from '../../../../src/shared/hosted-sandbox/orca-cloud-image-agents'
|
||||
import type { GitHubAppMinter } from '../src/github-app'
|
||||
import type { RunCommandParams } from '../src/sandbox-provider'
|
||||
import { redactLog } from '../src/routines/vm-runner'
|
||||
@@ -199,6 +200,26 @@ describe('routine runs (state machine on the fake provider)', () => {
|
||||
])
|
||||
})
|
||||
|
||||
it('runs every agent the image ships, headless, and refuses any other', async () => {
|
||||
const h = await harness()
|
||||
for (const agent of ORCA_CLOUD_IMAGE_AGENTS) {
|
||||
const created = await h.create({ name: `r-${agent}`, agent })
|
||||
expect(created.status, agent).toBe(201)
|
||||
expect(created.body.routine.agent).toBe(agent)
|
||||
const run = (await h.call('POST', `/v1/routines/${created.body.routine.id}/run`)).body.run
|
||||
await h.tick()
|
||||
const start = h.runnerCalls.find((c) => c.mode === 'start' && c.args.includes(run.id))!
|
||||
expect(start.args[5]).toBe(agent)
|
||||
// The worker has a headless command for it (an unknown agent ends as unknown_agent).
|
||||
expect(start.args.at(-1)).toMatch(new RegExp(`^${agent}\\)$`, 'm'))
|
||||
h.runs.set(run.id, h.done())
|
||||
await h.tick()
|
||||
}
|
||||
expect((await h.create({ agent: 'aider' })).body.reason).toMatch(/^agent/)
|
||||
const routine = (await h.create({ name: 'patch-me' })).body.routine
|
||||
expect((await h.call('PATCH', `/v1/routines/${routine.id}`, { body: { agent: 'gemini' } })).body.routine.agent).toBe('gemini')
|
||||
})
|
||||
|
||||
it('pr mode: falls back to opening the PR from the control plane when gh did not report one', async () => {
|
||||
const h = await harness()
|
||||
const routine = (await h.create({ postResults: 'pr' })).body.routine
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
// U22: internal-only per-session CPU, fair-use report, and its operator gate.
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { FAIR_USE_THRESHOLD, fairUseReport, recordSessionEnd, sweepSessionCpu } from '../src/session-cpu'
|
||||
import type { SandboxRow } from '../src/store'
|
||||
import { createVercelSandboxApi } from '../src/vercel-sandbox-api'
|
||||
import { createFakeD1 } from './d1-fake'
|
||||
import { createHarness } from './harness'
|
||||
|
||||
const OPERATOR = 'o'.repeat(40)
|
||||
const MIN = 60_000
|
||||
const create = { workspaceId: 'ws-1', machineSize: 'standard' }
|
||||
|
||||
async function operator(h: Awaited<ReturnType<typeof createHarness>>, method: string, path: string) {
|
||||
const response = await h.send(
|
||||
new Request(`https://sandbox.test${path}`, { method, headers: { authorization: `Bearer ${OPERATOR}` } })
|
||||
)
|
||||
return { status: response.status, body: (await response.json()) as any }
|
||||
}
|
||||
|
||||
function client(answer: (url: URL, method: string) => Response) {
|
||||
return createVercelSandboxApi({
|
||||
token: 'vercel_test_token',
|
||||
teamId: 'team_orca',
|
||||
projectId: 'prj_orca',
|
||||
fetch: async (input, init) => answer(new URL(String(input)), init?.method ?? 'GET')
|
||||
})
|
||||
}
|
||||
|
||||
const stoppedSession = {
|
||||
id: 'sess_1',
|
||||
status: 'stopped',
|
||||
startedAt: 1000,
|
||||
timeout: 1_800_000,
|
||||
memory: 16384,
|
||||
vcpus: 8,
|
||||
region: 'iad1',
|
||||
duration: 600_000,
|
||||
stoppedAt: 601_000,
|
||||
activeCpuDurationMs: 123_456
|
||||
}
|
||||
|
||||
describe('Vercel session usage mapping', () => {
|
||||
it('maps activeCpuDurationMs, duration, vcpus and memory from GET session', async () => {
|
||||
let seen: URL | null = null
|
||||
const api = client((url) => ((seen = url), Response.json({ session: stoppedSession, routes: [] })))
|
||||
expect(await api.getSessionUsage!('sess_1')).toEqual({
|
||||
sessionId: 'sess_1',
|
||||
status: 'stopped',
|
||||
activeCpuMs: 123_456,
|
||||
durationMs: 600_000,
|
||||
vcpus: 8,
|
||||
memoryMb: 16384,
|
||||
stoppedAt: 601_000
|
||||
})
|
||||
expect(seen!.pathname).toBe('/api/v2/sandboxes/sessions/sess_1')
|
||||
})
|
||||
|
||||
it('a running session has no CPU yet; a forgotten one is null', async () => {
|
||||
const running = client(() => Response.json({ session: { id: 's', status: 'running', timeout: 1, vcpus: 8 } }))
|
||||
expect(await running.getSessionUsage!('s')).toMatchObject({ activeCpuMs: null, vcpus: 8, durationMs: null })
|
||||
const gone = client(() => Response.json({ error: { code: 'not_found' } }, { status: 404 }))
|
||||
expect(await gone.getSessionUsage!('s')).toBeNull()
|
||||
})
|
||||
|
||||
it('reads usage off the stop response, and an unreadable session never fails the stop', async () => {
|
||||
const withSession = client(() => Response.json({ session: stoppedSession, snapshot: { id: 'snap_1', status: 'created', sourceSessionId: 'sess_1' } }))
|
||||
expect(await withSession.stopSession('sess_1')).toMatchObject({ snapshotId: 'snap_1', usage: { activeCpuMs: 123_456 } })
|
||||
const odd = client(() => Response.json({ session: { id: 7 }, snapshot: { id: 'snap_1', status: 'created', sourceSessionId: 'sess_1' } }))
|
||||
expect(await odd.stopSession('sess_1')).toEqual({ snapshotId: 'snap_1', usage: null })
|
||||
})
|
||||
})
|
||||
|
||||
function row(overrides: Partial<SandboxRow> = {}): SandboxRow {
|
||||
return {
|
||||
id: 'sbx_1',
|
||||
account_id: 'user:alice',
|
||||
user_id: 'alice',
|
||||
session_id: 'sess_1',
|
||||
session_started_at: 1_000,
|
||||
...overrides
|
||||
} as SandboxRow
|
||||
}
|
||||
|
||||
describe('session CPU storage', () => {
|
||||
it('is idempotent per session and the first recorded CPU wins', async () => {
|
||||
const { db, raw } = createFakeD1()
|
||||
await recordSessionEnd(db, row(), 61_000, null, 61_000)
|
||||
await recordSessionEnd(db, row(), 99_000, null, 99_000)
|
||||
const usage = { sessionId: 'sess_1', status: 'stopped' as const, activeCpuMs: 30_000, durationMs: 60_000, vcpus: 8, memoryMb: 16384, stoppedAt: 61_000 }
|
||||
await recordSessionEnd(db, row(), 99_000, usage, 100_000)
|
||||
await recordSessionEnd(db, row(), 99_000, { ...usage, activeCpuMs: 1 }, 200_000)
|
||||
const rows = raw.prepare('SELECT * FROM session_cpu').all() as any[]
|
||||
expect(rows).toHaveLength(1)
|
||||
expect(rows[0]).toMatchObject({ session_id: 'sess_1', sandbox_id: 'sbx_1', account_id: 'user:alice', user_id: 'alice', ended_at: 61_000, active_cpu_ms: 30_000, wall_ms: 60_000, vcpus: 8, memory_mb: 16384, fetched_at: 100_000 })
|
||||
})
|
||||
|
||||
it('never throws, even when D1 does', async () => {
|
||||
const broken = { prepare: () => { throw new Error('d1 down') } } as unknown as D1Database
|
||||
await expect(recordSessionEnd(broken, row(), 1, null, 1)).resolves.toBeUndefined()
|
||||
expect(await sweepSessionCpu(broken, { getSessionUsage: async () => null }, 1)).toEqual({ checked: 0, recorded: 0, failed: 0 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('session CPU through the lifecycle', () => {
|
||||
it('suspend records the session (wall time, vCPUs) without touching the meter; the sweep fills CPU later', async () => {
|
||||
const h = await createHarness({ OPERATOR_TOKEN: OPERATOR })
|
||||
const { body } = await h.call('POST', '/v1/sandboxes', { body: create })
|
||||
const sessionId = [...h.vercel.boxes.values()][0]!.sessionId
|
||||
h.advance(10 * MIN)
|
||||
expect((await h.call('POST', `/v1/sandboxes/${body.sandbox.id}/suspend`)).status).toBe(200)
|
||||
|
||||
const [recorded] = h.raw.prepare('SELECT * FROM session_cpu').all() as any[]
|
||||
expect(recorded).toMatchObject({ session_id: sessionId, sandbox_id: body.sandbox.id, account_id: 'user:alice', vcpus: 8, wall_ms: 10 * MIN, active_cpu_ms: null })
|
||||
// Billing sees exactly the flat-hours segment, with no CPU anywhere in it.
|
||||
expect(h.billing.usage).toHaveLength(1)
|
||||
expect(Object.keys(h.billing.usage[0]!).sort()).toEqual(['accountId', 'endedAt', 'machineSize', 'sandboxId', 'startedAt', 'usageId', 'userId'])
|
||||
|
||||
h.vercel.sessionCpu.set(sessionId, 4 * 8 * MIN)
|
||||
expect((await operator(h, 'POST', '/v1/internal/session-cpu/sweep')).body).toEqual({ sweep: { checked: 1, recorded: 1, failed: 0 } })
|
||||
expect((await operator(h, 'POST', '/v1/internal/session-cpu/sweep')).body.sweep.checked).toBe(0)
|
||||
const report = await operator(h, 'GET', '/v1/internal/fair-use')
|
||||
expect(report.body.accounts).toEqual([
|
||||
{ accountId: 'user:alice', sessions: 1, activeCpuMs: 32 * MIN, vcpuMs: 80 * MIN, cpuUtilization: 0.4, fairUseFlag: false }
|
||||
])
|
||||
})
|
||||
|
||||
it('a failing CPU fetch never blocks suspend or usage reporting; the sweep backs off', async () => {
|
||||
const h = await createHarness({ OPERATOR_TOKEN: OPERATOR })
|
||||
const { body } = await h.call('POST', '/v1/sandboxes', { body: create })
|
||||
h.vercel.failSessionUsage = true
|
||||
// Even a D1 table missing entirely must not fail the stop.
|
||||
h.raw.exec('ALTER TABLE session_cpu RENAME TO session_cpu_hidden')
|
||||
h.advance(5 * MIN)
|
||||
expect((await h.call('POST', `/v1/sandboxes/${body.sandbox.id}/suspend`)).status).toBe(200)
|
||||
expect(h.billing.usage).toHaveLength(1)
|
||||
h.raw.exec('ALTER TABLE session_cpu_hidden RENAME TO session_cpu')
|
||||
|
||||
expect((await h.call('POST', `/v1/sandboxes/${body.sandbox.id}/resume`)).status).toBe(200)
|
||||
h.advance(5 * MIN)
|
||||
expect((await h.call('POST', `/v1/sandboxes/${body.sandbox.id}/suspend`)).status).toBe(200)
|
||||
expect(h.billing.usage).toHaveLength(2)
|
||||
expect((await operator(h, 'POST', '/v1/internal/session-cpu/sweep')).body.sweep).toEqual({ checked: 1, recorded: 0, failed: 1 })
|
||||
expect((h.raw.prepare('SELECT attempts FROM session_cpu').get() as any).attempts).toBe(1)
|
||||
})
|
||||
|
||||
it('a session the provider ended on its own is recorded too', async () => {
|
||||
const h = await createHarness()
|
||||
const { body } = await h.call('POST', '/v1/sandboxes', { body: create })
|
||||
const box = [...h.vercel.boxes.values()][0]!
|
||||
h.advance(31 * MIN)
|
||||
h.vercel.expire(box.params.name)
|
||||
await h.reconcile()
|
||||
expect(h.raw.prepare('SELECT sandbox_id, wall_ms FROM session_cpu').all()).toEqual([{ sandbox_id: body.sandbox.id, wall_ms: 30 * MIN }])
|
||||
})
|
||||
})
|
||||
|
||||
describe('fair-use report', () => {
|
||||
async function seed(db: D1Database, account: string, session: string, wallMs: number, vcpus: number, cpuMs: number | null, endedAt: number) {
|
||||
await recordSessionEnd(db, row({ id: `sbx_${session}`, account_id: account, session_id: session, session_started_at: endedAt - wallMs }), endedAt, null, endedAt)
|
||||
if (cpuMs !== null) {
|
||||
await recordSessionEnd(db, row({ session_id: session }), endedAt, { sessionId: session, status: 'stopped', activeCpuMs: cpuMs, durationMs: wallMs, vcpus, memoryMb: null, stoppedAt: endedAt }, endedAt)
|
||||
}
|
||||
}
|
||||
|
||||
it('averages active CPU over wall × vCPUs per account and flags only above 60%', async () => {
|
||||
const { db } = createFakeD1()
|
||||
const now = 100 * 24 * 60 * MIN
|
||||
const hour = 60 * MIN
|
||||
await seed(db, 'org:heavy', 'h1', hour, 8, 6 * hour, now - hour) // 75%
|
||||
await seed(db, 'org:heavy', 'h2', hour, 8, 4 * hour, now - 2 * hour) // 50% → combined 62.5%
|
||||
await seed(db, 'org:edge', 'e1', hour, 8, 4.8 * hour, now - hour) // exactly 60%: not over
|
||||
await seed(db, 'user:light', 'l1', 2 * hour, 4, 0.8 * hour, now - hour) // 10%
|
||||
await seed(db, 'user:light', 'old', hour, 8, 8 * hour, now - 31 * 24 * hour) // outside the window
|
||||
await seed(db, 'user:light', 'pending', hour, 8, null, now - hour) // no CPU yet: excluded
|
||||
const report = await fairUseReport(db, now)
|
||||
expect(report).toMatchObject({ windowDays: 30, threshold: FAIR_USE_THRESHOLD, pendingSessions: 1 })
|
||||
expect(report.accounts.map((a) => [a.accountId, a.sessions, a.cpuUtilization, a.fairUseFlag])).toEqual([
|
||||
['org:heavy', 2, 0.625, true],
|
||||
['org:edge', 1, 0.6, false],
|
||||
['user:light', 1, 0.1, false]
|
||||
])
|
||||
expect(report.accounts[0]).toMatchObject({ activeCpuMs: 10 * hour, vcpuMs: 16 * hour })
|
||||
})
|
||||
})
|
||||
|
||||
describe('fair-use auth gate', () => {
|
||||
it('refuses customer tokens, wrong tokens and an unset operator token; accepts the operator', async () => {
|
||||
const h = await createHarness({ OPERATOR_TOKEN: OPERATOR })
|
||||
expect((await h.call('GET', '/v1/internal/fair-use')).status).toBe(404)
|
||||
expect((await h.call('GET', '/v1/internal/fair-use', { bearer: 'x'.repeat(40) })).status).toBe(404)
|
||||
expect((await h.call('POST', '/v1/internal/session-cpu/sweep')).status).toBe(404)
|
||||
expect((await operator(h, 'GET', '/v1/internal/fair-use')).body).toMatchObject({ windowDays: 30, accounts: [] })
|
||||
expect((await operator(h, 'GET', '/v1/internal/fair-use?days=0')).status).toBe(400)
|
||||
|
||||
const closed = await createHarness()
|
||||
const response = await closed.send(
|
||||
new Request('https://sandbox.test/v1/internal/fair-use', { headers: { authorization: `Bearer ${OPERATOR}` } })
|
||||
)
|
||||
expect(response.status).toBe(404)
|
||||
})
|
||||
})
|
||||
@@ -101,6 +101,52 @@ describe('workspace registry', () => {
|
||||
expect(t.h.vercel.snapshotExpirations.get(name)).toBe(104 * 24 * 60 * MIN)
|
||||
})
|
||||
|
||||
it('refuses to archive a sandbox that is starting or mid-transition, and leaves the row unchanged', async () => {
|
||||
const t = await team()
|
||||
for (const status of ['creating', 'suspending']) {
|
||||
t.h.raw.prepare(`UPDATE sandboxes SET status = ? WHERE id = ?`).run(status, t.id)
|
||||
const busy = await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${t.id}`, { archived: true })
|
||||
expect(busy).toMatchObject({ status: 409, body: { reason: `sandbox_${status}` } })
|
||||
}
|
||||
t.h.raw.prepare(`UPDATE sandboxes SET status = 'resuming' WHERE id = ?`).run(t.id)
|
||||
const res = await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${t.id}`, { archived: true })
|
||||
expect(res).toMatchObject({ status: 409, body: { error: 'conflict', reason: 'sandbox_resuming' } })
|
||||
expect(t.h.raw.prepare('SELECT status, archived_at FROM sandboxes WHERE id = ?').get(t.id)).toEqual({
|
||||
status: 'resuming',
|
||||
archived_at: null
|
||||
})
|
||||
})
|
||||
|
||||
it('archives an asleep sandbox without waking it', async () => {
|
||||
const t = await team()
|
||||
await t.req(t.alice, 'POST', `/v1/sandboxes/${t.id}/suspend`)
|
||||
const { START_COMMAND } = await import('../src/sandbox-vm-commands')
|
||||
const starts = t.h.vercel.commands.filter((c) => c.command === START_COMMAND).length
|
||||
const res = await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${t.id}`, { archived: true })
|
||||
expect(res.status).toBe(200)
|
||||
expect(t.h.raw.prepare('SELECT status FROM sandboxes WHERE id = ?').get(t.id)).toEqual({ status: 'archived' })
|
||||
expect(t.h.vercel.commands.filter((c) => c.command === START_COMMAND)).toHaveLength(starts)
|
||||
expect(t.h.vercel.boxes.get(`orca-test-${t.id}`)!.status).toBe('stopped')
|
||||
})
|
||||
|
||||
it('never labels a running sandbox archived when the archive itself fails', async () => {
|
||||
const t = await team()
|
||||
const { ProviderError } = await import('../src/sandbox-provider')
|
||||
t.h.vercel.stopSession = async () => {
|
||||
throw new ProviderError(500, 'internal_error')
|
||||
}
|
||||
const res = await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${t.id}`, { archived: true })
|
||||
expect(res.status).toBeGreaterThanOrEqual(500)
|
||||
expect((t.h.raw.prepare('SELECT archived_at FROM sandboxes WHERE id = ?').get(t.id) as { archived_at: number | null }).archived_at).toBeNull()
|
||||
})
|
||||
|
||||
it('only the owner or a team admin can archive', async () => {
|
||||
const t = await team()
|
||||
await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${t.id}`, { visibility: 'team' })
|
||||
expect((await t.req(t.bob, 'PATCH', `/v1/team/workspaces/${t.id}`, { archived: true })).status).toBe(403)
|
||||
expect(t.h.vercel.boxes.get(`orca-test-${t.id}`)!.status).toBe('running')
|
||||
})
|
||||
|
||||
it('reports cost from metered compute at the billing rate, plus reported token spend', async () => {
|
||||
const t = await team()
|
||||
t.h.advance(90 * MIN)
|
||||
@@ -253,7 +299,7 @@ describe('workspace grants (E2EE pairing through the control plane)', () => {
|
||||
await t.req(t.alice, 'PATCH', `/v1/team/workspaces/${t.id}`, { visibility: 'team' })
|
||||
await t.req(t.bob, 'POST', `/v1/team/workspaces/${t.id}/grants`, { recipientPublicKeyB64: generateGrantRecipientKey().publicKeyB64, deviceLabel: 'b', deviceKind: 'desktop' })
|
||||
const res = await t.h.call('POST', '/v1/internal/org-members/removed', { bearer: 'o'.repeat(40), body: { accountId: 'org:acme', userId: 'bob' } })
|
||||
expect(res.body).toEqual({ revoked: 1, queued: 0, keysRevoked: 0, devicesRevoked: 0, grantsRevoked: 1, grantsQueued: 0, routinesDisabled: 0 })
|
||||
expect(res.body).toEqual({ revoked: 1, queued: 0, keysRevoked: 0, devicesRevoked: 0, grantsRevoked: 1, grantsQueued: 0, routinesDisabled: 0, readerKeysRevoked: 0 })
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -11,6 +11,8 @@
|
||||
"main": "src/index.ts",
|
||||
"compatibility_date": "2026-11-01",
|
||||
"workers_dev": true,
|
||||
// Preview aliases (wrangler versions upload --preview-alias) must stay reachable for pre-merge VM tests.
|
||||
"preview_urls": true,
|
||||
"d1_databases": [
|
||||
{
|
||||
"binding": "SANDBOX_DB",
|
||||
|
||||
@@ -0,0 +1,309 @@
|
||||
import { ExternalLink } from 'lucide-react-native'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { Animated, Easing, Linking, Pressable, Text, View } from 'react-native'
|
||||
import type {
|
||||
ReadSnapshot,
|
||||
ReadSnapshotGit,
|
||||
ReadSnapshotPr
|
||||
} from '../../../src/shared/cloud-workspaces/read-snapshot'
|
||||
import type { Translate } from '../i18n/mobile-i18n'
|
||||
import { getUiIntlLocale } from '../i18n/ui-intl-locale'
|
||||
import { useMobileTranslation } from '../i18n/use-mobile-translation'
|
||||
import { useReducedMotionEnabled } from '../platform/use-reduced-motion'
|
||||
import { colors } from '../theme/mobile-theme'
|
||||
import { useMobileColorScheme } from '../theme/use-mobile-color-scheme'
|
||||
import { formatTimeAgo } from '../worktree/agent-row-display'
|
||||
import { CloudErrorBanner } from './CloudErrorBanner'
|
||||
import { CloudStatusDot } from './CloudStatusDot'
|
||||
import { CloudReadSnapshotSessions } from './CloudReadSnapshotSessions'
|
||||
import { CloudReadSnapshotRollbackError, type CloudReadSnapshotResult } from './cloud-read-snapshot'
|
||||
import { readSnapshotStyles as styles } from './cloud-read-snapshot-styles'
|
||||
import { cloudStatusLabel } from './cloud-workspace-display'
|
||||
import { cloudWorkspaceScreenStyles as screen } from './cloud-workspace-screen-styles'
|
||||
|
||||
const GIT_PATHS_SHOWN = 5
|
||||
|
||||
export function formatReadSnapshotAbsolute(at: number): string {
|
||||
try {
|
||||
return new Intl.DateTimeFormat(getUiIntlLocale(), {
|
||||
dateStyle: 'medium',
|
||||
timeStyle: 'short'
|
||||
}).format(at)
|
||||
} catch {
|
||||
return new Date(at).toLocaleString()
|
||||
}
|
||||
}
|
||||
|
||||
/** "As of 5m ago" (relative); the absolute time is the long-press / screen-reader form. */
|
||||
export function formatReadSnapshotAsOf(at: number, now: number, t: Translate): string {
|
||||
return now - at < 60_000
|
||||
? t('cloud.snapshot.asOfJustNow', 'As of just now')
|
||||
: t('cloud.snapshot.asOf', 'As of {{ago}} ago', { ago: formatTimeAgo(at, now) })
|
||||
}
|
||||
|
||||
/**
|
||||
* The asleep workspace's read-only "Latest from this workspace": what its PR, agents and git looked
|
||||
* like when it went to sleep, opened on this phone. Never wakes the sandbox.
|
||||
*/
|
||||
export function CloudReadSnapshotSection(props: {
|
||||
result: CloudReadSnapshotResult | undefined
|
||||
/** When the result was fetched: the clock "As of" counts from (no impure clock read in render). */
|
||||
fetchedAt: number
|
||||
loading: boolean
|
||||
/** Wake was tapped: the header says Waking (the copy stays readable until it is open). */
|
||||
waking: boolean
|
||||
onRetry: () => void
|
||||
}) {
|
||||
useMobileColorScheme()
|
||||
const t = useMobileTranslation()
|
||||
const { result } = props
|
||||
// Gone or not openable: the screen itself says so; this area has nothing to add.
|
||||
if (!props.loading && result?.state === 'not_found') {
|
||||
return null
|
||||
}
|
||||
return (
|
||||
<View style={screen.section}>
|
||||
<View style={styles.headingRow}>
|
||||
<Text style={[screen.sectionHeading, styles.headingText]} accessibilityRole="header">
|
||||
{t('cloud.snapshot.heading', 'Latest from this workspace')}
|
||||
</Text>
|
||||
<View style={styles.headingState} accessible accessibilityLiveRegion="polite">
|
||||
<CloudStatusDot status={props.waking ? 'waking' : 'sleeping'} size={8} />
|
||||
<Text style={styles.headingStateText}>
|
||||
{cloudStatusLabel(props.waking ? 'waking' : 'sleeping', t)}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
{props.loading || !result ? (
|
||||
<SnapshotSkeleton />
|
||||
) : result.state === 'ready' ? (
|
||||
<SnapshotBody snapshot={result.snapshot} now={props.fetchedAt} />
|
||||
) : result.state === 'no_snapshot' ? (
|
||||
<Notice
|
||||
text={t(
|
||||
'cloud.snapshot.empty',
|
||||
'Nothing saved yet. Orca saves a read-only copy each time this workspace goes to sleep.'
|
||||
)}
|
||||
/>
|
||||
) : result.state === 'not_sealed_for_key' ? (
|
||||
<Notice
|
||||
text={t(
|
||||
'cloud.snapshot.notSealedForKey',
|
||||
'This device was added after the workspace went to sleep. Wake it once to read it here.'
|
||||
)}
|
||||
/>
|
||||
) : result.state === 'error' && result.error instanceof CloudReadSnapshotRollbackError ? (
|
||||
// Trying again cannot help: the newer copy only comes back from the workspace itself.
|
||||
<CloudErrorBanner
|
||||
message={t(
|
||||
'cloud.snapshot.rollback',
|
||||
'Orca Cloud sent an older copy than the one you last saw, so it isn’t shown. Wake the workspace to see it as it is now.'
|
||||
)}
|
||||
onRetry={null}
|
||||
/>
|
||||
) : (
|
||||
<CloudErrorBanner
|
||||
message={t(
|
||||
'cloud.snapshot.error',
|
||||
'Couldn’t load the latest from this workspace. Your files are safe.'
|
||||
)}
|
||||
onRetry={props.onRetry}
|
||||
/>
|
||||
)}
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function Notice({ text }: { text: string }) {
|
||||
return (
|
||||
<View style={styles.notice} accessible accessibilityRole="text">
|
||||
<Text style={styles.noticeText}>{text}</Text>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function SnapshotSkeleton() {
|
||||
const t = useMobileTranslation()
|
||||
const reducedMotion = useReducedMotionEnabled() !== false
|
||||
const pulse = useRef(new Animated.Value(1)).current
|
||||
useEffect(() => {
|
||||
if (reducedMotion) {
|
||||
pulse.setValue(1)
|
||||
return
|
||||
}
|
||||
const loop = Animated.loop(
|
||||
Animated.sequence([
|
||||
Animated.timing(pulse, {
|
||||
toValue: 0.45,
|
||||
duration: 800,
|
||||
easing: Easing.inOut(Easing.quad),
|
||||
useNativeDriver: true
|
||||
}),
|
||||
Animated.timing(pulse, {
|
||||
toValue: 1,
|
||||
duration: 800,
|
||||
easing: Easing.inOut(Easing.quad),
|
||||
useNativeDriver: true
|
||||
})
|
||||
])
|
||||
)
|
||||
loop.start()
|
||||
return () => loop.stop()
|
||||
}, [reducedMotion, pulse])
|
||||
return (
|
||||
<Animated.View
|
||||
style={[styles.skeletonCard, { opacity: pulse }]}
|
||||
accessible
|
||||
accessibilityRole="progressbar"
|
||||
accessibilityLabel={t('cloud.snapshot.loading', 'Loading the latest from this workspace…')}
|
||||
>
|
||||
<View style={[styles.skeletonBar, { width: '35%' }]} />
|
||||
<View style={[styles.skeletonBar, { width: '80%' }]} />
|
||||
<View style={[styles.skeletonBar, { width: '60%' }]} />
|
||||
</Animated.View>
|
||||
)
|
||||
}
|
||||
|
||||
function SnapshotBody({ snapshot, now }: { snapshot: ReadSnapshot; now: number }) {
|
||||
const t = useMobileTranslation()
|
||||
const [absolute, setAbsolute] = useState(false)
|
||||
const exact = formatReadSnapshotAbsolute(snapshot.capturedAt)
|
||||
const empty = !snapshot.pr && !snapshot.git && snapshot.sessions.length === 0
|
||||
return (
|
||||
<View>
|
||||
<Pressable
|
||||
accessibilityRole="text"
|
||||
accessibilityLabel={t('cloud.snapshot.asOfExact', 'As of {{time}}', { time: exact })}
|
||||
onLongPress={() => setAbsolute((value) => !value)}
|
||||
style={styles.asOfButton}
|
||||
>
|
||||
<Text style={styles.asOf}>
|
||||
{absolute
|
||||
? t('cloud.snapshot.asOfExact', 'As of {{time}}', { time: exact })
|
||||
: formatReadSnapshotAsOf(snapshot.capturedAt, Math.max(now, snapshot.capturedAt), t)}
|
||||
</Text>
|
||||
</Pressable>
|
||||
<View style={styles.stack}>
|
||||
{snapshot.pr ? <PrCard pr={snapshot.pr} /> : null}
|
||||
<CloudReadSnapshotSessions sessions={snapshot.sessions} />
|
||||
{snapshot.git ? <GitCard git={snapshot.git} /> : null}
|
||||
{empty ? (
|
||||
<Notice
|
||||
text={t(
|
||||
'cloud.snapshot.quiet',
|
||||
'No agents, changes or pull request when it went to sleep.'
|
||||
)}
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function prStateLabel(pr: ReadSnapshotPr, t: Translate): string {
|
||||
switch (pr.state.toLowerCase()) {
|
||||
case 'merged':
|
||||
return t('cloud.snapshot.pr.merged', 'Merged')
|
||||
case 'closed':
|
||||
return t('cloud.snapshot.pr.closed', 'Closed')
|
||||
case 'draft':
|
||||
return t('cloud.snapshot.pr.draft', 'Draft')
|
||||
default:
|
||||
return t('cloud.snapshot.pr.open', 'Open')
|
||||
}
|
||||
}
|
||||
|
||||
function prChecksLabel(pr: ReadSnapshotPr, t: Translate): string | null {
|
||||
switch (pr.checksStatus?.toLowerCase()) {
|
||||
case 'success':
|
||||
case 'passed':
|
||||
case 'passing':
|
||||
return t('cloud.snapshot.checks.passing', 'Checks passing')
|
||||
case 'failure':
|
||||
case 'failed':
|
||||
case 'failing':
|
||||
return t('cloud.snapshot.checks.failing', 'Checks failing')
|
||||
case 'pending':
|
||||
case 'running':
|
||||
return t('cloud.snapshot.checks.pending', 'Checks running')
|
||||
// No status, or one this build doesn't name: the VM's own summary line, if any.
|
||||
case undefined:
|
||||
default:
|
||||
return pr.checksSummary
|
||||
}
|
||||
}
|
||||
|
||||
function PrCard({ pr }: { pr: ReadSnapshotPr }) {
|
||||
const t = useMobileTranslation()
|
||||
const failing = /fail/i.test(pr.checksStatus ?? '')
|
||||
const meta = [prStateLabel(pr, t), prChecksLabel(pr, t)].filter(Boolean).join(' · ')
|
||||
const title = t('cloud.snapshot.pr.title', '#{{number}} {{title}}', {
|
||||
number: pr.number,
|
||||
title: pr.title
|
||||
})
|
||||
return (
|
||||
<View style={screen.card}>
|
||||
<Pressable
|
||||
accessibilityRole="link"
|
||||
accessibilityLabel={`${title}, ${meta}`}
|
||||
accessibilityHint={t('cloud.snapshot.pr.hint', 'Opens the pull request')}
|
||||
onPress={() => void Linking.openURL(pr.url).catch(() => undefined)}
|
||||
style={({ pressed }) => [styles.row, pressed && screen.pressed]}
|
||||
>
|
||||
<View style={styles.rowText}>
|
||||
<Text style={styles.rowTitle} numberOfLines={2}>
|
||||
{title}
|
||||
</Text>
|
||||
<Text style={[styles.rowMeta, failing && { color: colors.statusRed }]} numberOfLines={1}>
|
||||
{meta}
|
||||
</Text>
|
||||
</View>
|
||||
<ExternalLink size={16} color={colors.textMuted} />
|
||||
</Pressable>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function GitCard({ git }: { git: ReadSnapshotGit }) {
|
||||
const t = useMobileTranslation()
|
||||
const count = git.changeCount
|
||||
const files =
|
||||
count === 1
|
||||
? t('cloud.snapshot.git.files_one', '{{count}} changed file', { count })
|
||||
: t('cloud.snapshot.git.files_other', '{{count}} changed files', { count })
|
||||
const more = count - Math.min(git.changes.length, GIT_PATHS_SHOWN)
|
||||
return (
|
||||
<View style={screen.card}>
|
||||
<View style={styles.gitBody} accessible>
|
||||
{git.branch ? (
|
||||
<Text style={styles.rowTitle} numberOfLines={1}>
|
||||
{git.branch}
|
||||
</Text>
|
||||
) : null}
|
||||
<View style={styles.gitHeadline}>
|
||||
<Text style={styles.rowMeta}>
|
||||
{count === 0 ? t('cloud.snapshot.git.clean', 'No uncommitted changes') : files}
|
||||
</Text>
|
||||
{git.added !== null ? (
|
||||
<Text style={[styles.mono, styles.added]}>+{git.added}</Text>
|
||||
) : null}
|
||||
{git.removed !== null ? (
|
||||
<Text style={[styles.mono, styles.removed]}>−{git.removed}</Text>
|
||||
) : null}
|
||||
</View>
|
||||
{git.changes.slice(0, GIT_PATHS_SHOWN).map((change) => (
|
||||
<Text key={`${change.area}:${change.path}`} style={styles.mono} numberOfLines={1}>
|
||||
{change.path}
|
||||
</Text>
|
||||
))}
|
||||
{more > 0 ? (
|
||||
<Text style={styles.rowMeta}>
|
||||
{more === 1
|
||||
? t('cloud.snapshot.git.more_one', 'and {{count}} more', { count: more })
|
||||
: t('cloud.snapshot.git.more_other', 'and {{count}} more', { count: more })}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import { ChevronDown, ChevronRight } from 'lucide-react-native'
|
||||
import { useState } from 'react'
|
||||
import { Pressable, Text, View } from 'react-native'
|
||||
import type {
|
||||
ReadSnapshotMessage,
|
||||
ReadSnapshotSession
|
||||
} from '../../../src/shared/cloud-workspaces/read-snapshot'
|
||||
import type { Translate } from '../i18n/mobile-i18n'
|
||||
import { useMobileTranslation } from '../i18n/use-mobile-translation'
|
||||
import { MobileNativeChatMarkdown } from '../session/native-chat/MobileNativeChatMarkdown'
|
||||
import { colors } from '../theme/mobile-theme'
|
||||
import { useMobileColorScheme } from '../theme/use-mobile-color-scheme'
|
||||
import { cloudAgentLabel } from './CloudAgentPicker'
|
||||
import { readSnapshotStyles as styles } from './cloud-read-snapshot-styles'
|
||||
import { cloudWorkspaceScreenStyles as screen } from './cloud-workspace-screen-styles'
|
||||
|
||||
export function readSnapshotSessionStatus(
|
||||
session: Pick<ReadSnapshotSession, 'status' | 'turnOutcome'>,
|
||||
t: Translate
|
||||
): string | null {
|
||||
switch (session.status) {
|
||||
case 'working':
|
||||
return t('cloud.snapshot.status.working', 'Working')
|
||||
case 'attention':
|
||||
return t('cloud.snapshot.status.attention', 'Needs you')
|
||||
case 'idle':
|
||||
return session.turnOutcome
|
||||
? t('cloud.snapshot.status.done', 'Done')
|
||||
: t('cloud.snapshot.status.idle', 'Idle')
|
||||
case 'unknown':
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** The product name ("Claude Code", "Codex") from the app's one agent-name table, never the raw id. */
|
||||
function agentName(agent: string | null, t: Translate): string {
|
||||
const trimmed = agent?.trim()
|
||||
return trimmed ? cloudAgentLabel(trimmed) : t('cloud.snapshot.agentFallback', 'Agent')
|
||||
}
|
||||
|
||||
/** Agents as they were when the workspace went to sleep; each opens to the tail of its chat. */
|
||||
export function CloudReadSnapshotSessions({ sessions }: { sessions: ReadSnapshotSession[] }) {
|
||||
useMobileColorScheme()
|
||||
const t = useMobileTranslation()
|
||||
const [open, setOpen] = useState<ReadonlySet<string>>(new Set())
|
||||
if (sessions.length === 0) {
|
||||
return null
|
||||
}
|
||||
const toggle = (id: string) =>
|
||||
setOpen((current) => {
|
||||
const next = new Set(current)
|
||||
if (!next.delete(id)) {
|
||||
next.add(id)
|
||||
}
|
||||
return next
|
||||
})
|
||||
return (
|
||||
<View style={screen.card}>
|
||||
{sessions.map((session, index) => {
|
||||
const expanded = open.has(session.sessionId)
|
||||
const name = agentName(session.agent, t)
|
||||
const status = readSnapshotSessionStatus(session, t)
|
||||
const title = session.title?.trim() || name
|
||||
const meta = [title === name ? null : name, status].filter(Boolean).join(' · ')
|
||||
const Chevron = expanded ? ChevronDown : ChevronRight
|
||||
return (
|
||||
<View key={session.sessionId} style={index > 0 ? styles.rowDivider : undefined}>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ expanded }}
|
||||
accessibilityLabel={[title, meta].filter(Boolean).join(', ')}
|
||||
accessibilityHint={t('cloud.snapshot.sessionHint', 'Shows the end of this chat')}
|
||||
onPress={() => toggle(session.sessionId)}
|
||||
style={({ pressed }) => [styles.row, pressed && screen.pressed]}
|
||||
>
|
||||
<View style={styles.rowText}>
|
||||
<Text style={styles.rowTitle} numberOfLines={2}>
|
||||
{title}
|
||||
</Text>
|
||||
{meta ? (
|
||||
<Text
|
||||
style={[
|
||||
styles.rowMeta,
|
||||
session.status === 'attention' && styles.rowMetaAttention
|
||||
]}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{meta}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
<Chevron size={18} color={colors.textMuted} />
|
||||
</Pressable>
|
||||
{expanded ? <Transcript session={session} agent={name} /> : null}
|
||||
</View>
|
||||
)
|
||||
})}
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function Transcript({ session, agent }: { session: ReadSnapshotSession; agent: string }) {
|
||||
const t = useMobileTranslation()
|
||||
return (
|
||||
<View style={styles.transcript}>
|
||||
{session.truncated ? (
|
||||
<Text style={styles.truncatedNote}>
|
||||
{t('cloud.snapshot.truncated', 'Earlier messages aren’t in this copy.')}
|
||||
</Text>
|
||||
) : null}
|
||||
{session.messages.length === 0 ? (
|
||||
<Text style={styles.truncatedNote}>
|
||||
{t('cloud.snapshot.noMessages', 'No messages in this chat yet.')}
|
||||
</Text>
|
||||
) : (
|
||||
session.messages.map((message) => (
|
||||
<Bubble key={message.itemId} message={message} agent={agent} />
|
||||
))
|
||||
)}
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function Bubble({ message, agent }: { message: ReadSnapshotMessage; agent: string }) {
|
||||
const t = useMobileTranslation()
|
||||
if (message.role === 'user') {
|
||||
return (
|
||||
<View style={styles.bubbleUser}>
|
||||
<Text style={styles.roleLabel}>{t('cloud.snapshot.role.you', 'You')}</Text>
|
||||
<Text style={styles.userText} selectable>
|
||||
{message.text}
|
||||
</Text>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
if (message.role === 'system') {
|
||||
return (
|
||||
<View style={styles.bubbleSystem}>
|
||||
<Text style={styles.roleLabel}>{t('cloud.snapshot.role.system', 'System')}</Text>
|
||||
<Text style={styles.systemText} selectable>
|
||||
{message.text}
|
||||
</Text>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<View style={styles.bubbleAssistant}>
|
||||
<Text style={styles.roleLabel}>{agent}</Text>
|
||||
<MobileNativeChatMarkdown content={message.text} />
|
||||
</View>
|
||||
)
|
||||
}
|
||||
@@ -27,21 +27,21 @@ function spendLine(
|
||||
if (!awake) {
|
||||
return t(
|
||||
'cloud.usage.asleep',
|
||||
'{{hours}} sandbox hours so far · no sandbox hours while asleep',
|
||||
'{{hours}} sandbox hours so far. Uses no sandbox hours while asleep.',
|
||||
{
|
||||
count: value,
|
||||
hours: label,
|
||||
defaultValue_one: '{{hours}} sandbox hour so far · no sandbox hours while asleep'
|
||||
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',
|
||||
'{{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'
|
||||
defaultValue_one: '{{hours}} sandbox hour so far. Uses sandbox hours while running.'
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ import { CloudAgentStartedCard } from './CloudAgentStartedCard'
|
||||
import { CloudErrorBanner } from './CloudErrorBanner'
|
||||
import { CloudPromptComposer } from './CloudPromptComposer'
|
||||
import { CloudPromptQueueSection } from './CloudPromptQueueSection'
|
||||
import { CloudReadSnapshotSection } from './CloudReadSnapshotSection'
|
||||
import { CloudStatusCard } from './CloudStatusCard'
|
||||
import { CloudWorkspaceActions } from './CloudWorkspaceActions'
|
||||
import { archiveCloudWorkspace, sleepCloudWorkspace } from './cloud-control-plane-client'
|
||||
@@ -41,7 +42,8 @@ import {
|
||||
cloudScrollBottomPadding,
|
||||
cloudWorkspaceScreenStyles as styles
|
||||
} from './cloud-workspace-screen-styles'
|
||||
import { useCloudWorkspaceRun } from './use-cloud-workspace-run'
|
||||
import { useCloudReadSnapshot } from './use-cloud-read-snapshot'
|
||||
import { useCloudWorkspaceRun, type CloudWorkspaceRun } from './use-cloud-workspace-run'
|
||||
import {
|
||||
useCloudEnrollment,
|
||||
useCloudWorkspace,
|
||||
@@ -65,12 +67,19 @@ export function CloudWorkspaceScreen({
|
||||
const enrollment = useCloudEnrollment()
|
||||
const { workspace, isPending, isFetching, refetch } = useCloudWorkspace(enrollment, sandboxId)
|
||||
const live = useCloudWorkspaceLiveStatus(sandboxId, workspace?.status === 'running')
|
||||
// Asleep: read its last sealed snapshot instead of waking it. Nothing here ever wakes it.
|
||||
const asleep = workspace?.status === 'sleeping'
|
||||
const snapshot = useCloudReadSnapshot(sandboxId, asleep, workspace?.readSnapshotAt ?? null)
|
||||
const invalidate = useInvalidateCloudWorkspaces()
|
||||
const { run, active, start, fail, clearError, openSession } = useCloudWorkspaceRun(
|
||||
sandboxId,
|
||||
workspace
|
||||
)
|
||||
const [queue, setQueue] = useState<QueuedCloudPrompt[]>([])
|
||||
// The run as it was when wake was tapped: until the run moves on (start() first reads the
|
||||
// keychain), the button already reads Waking rather than keeping "Wake to continue".
|
||||
const [wakeTappedAt, setWakeTappedAt] = useState<CloudWorkspaceRun | null>(null)
|
||||
const wakePending = wakeTappedAt !== null && wakeTappedAt === run
|
||||
const [busyAction, setBusyAction] = useState<'sleep' | 'archive' | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
@@ -184,8 +193,17 @@ export function CloudWorkspaceScreen({
|
||||
workspace.status === 'creating' ||
|
||||
workspace.status === 'stopping' ||
|
||||
workspace.status === 'archived'
|
||||
const primaryLabel =
|
||||
run.kind === 'launched'
|
||||
const waking =
|
||||
wakePending ||
|
||||
run.kind === 'attaching' ||
|
||||
run.kind === 'delivering' ||
|
||||
workspace.status === 'waking'
|
||||
// Asleep, or waking from it: the read-only copy stays readable (header says Waking) until it opens.
|
||||
const showSnapshot = asleep || (waking && !awake && snapshot.data !== undefined)
|
||||
const busy = active || wakePending
|
||||
const primaryLabel = wakePending
|
||||
? phaseLabel('waking', t)
|
||||
: run.kind === 'launched'
|
||||
? t('cloud.action.openSession', 'Open session')
|
||||
: run.kind === 'attaching'
|
||||
? phaseLabel(run.phase, t)
|
||||
@@ -197,8 +215,10 @@ export function CloudWorkspaceScreen({
|
||||
? t('cloud.status.archived', 'Archived')
|
||||
: awake
|
||||
? t('cloud.action.open', 'Open workspace')
|
||||
: t('cloud.action.wakeOpen', 'Wake and open workspace')
|
||||
const primaryDisabled = active || unavailable
|
||||
: asleep
|
||||
? t('cloud.action.wakeToContinue', 'Wake to continue')
|
||||
: t('cloud.action.wakeOpen', 'Wake and open workspace')
|
||||
const primaryDisabled = busy || unavailable
|
||||
|
||||
return (
|
||||
<SafeAreaView style={styles.container} edges={['top']}>
|
||||
@@ -234,6 +254,17 @@ export function CloudWorkspaceScreen({
|
||||
onRetry={run.retry ? () => void start(run.retry ?? 'open') : null}
|
||||
/>
|
||||
) : null}
|
||||
{showSnapshot ? (
|
||||
<CloudReadSnapshotSection
|
||||
waking={waking}
|
||||
result={snapshot.data}
|
||||
fetchedAt={snapshot.dataUpdatedAt}
|
||||
loading={
|
||||
snapshot.isPending || (snapshot.isFetching && snapshot.data?.state === 'error')
|
||||
}
|
||||
onRetry={() => void snapshot.refetch()}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<View style={styles.section}>
|
||||
<Text style={styles.sectionHeading} accessibilityRole="header">
|
||||
@@ -284,18 +315,25 @@ export function CloudWorkspaceScreen({
|
||||
<View style={[styles.actionBar, { paddingBottom: Math.max(insets.bottom, spacing.md) }]}>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ disabled: primaryDisabled, busy: active }}
|
||||
accessibilityState={{ disabled: primaryDisabled, busy }}
|
||||
disabled={primaryDisabled}
|
||||
onPress={() => (run.kind === 'launched' ? openSession('chat') : void start('open'))}
|
||||
onPress={() => {
|
||||
if (run.kind === 'launched') {
|
||||
openSession('chat')
|
||||
return
|
||||
}
|
||||
setWakeTappedAt(run)
|
||||
void start('open').finally(() => setWakeTappedAt(null))
|
||||
}}
|
||||
style={({ pressed }) => [
|
||||
styles.primary,
|
||||
primaryDisabled && !active && styles.primaryDisabled,
|
||||
primaryDisabled && !busy && styles.primaryDisabled,
|
||||
pressed && styles.pressed
|
||||
]}
|
||||
>
|
||||
{active ? <ActivityIndicator size="small" color={colors.bgBase} /> : null}
|
||||
{busy ? <ActivityIndicator size="small" color={colors.bgBase} /> : null}
|
||||
<Text
|
||||
style={[styles.primaryText, primaryDisabled && !active && styles.primaryTextDisabled]}
|
||||
style={[styles.primaryText, primaryDisabled && !busy && styles.primaryTextDisabled]}
|
||||
>
|
||||
{primaryLabel}
|
||||
</Text>
|
||||
|
||||
@@ -42,6 +42,8 @@ export type CloudWorkspace = {
|
||||
/** Awake time so far, from the team registry; the plan meters hours, not per-workspace dollars. */
|
||||
sandboxMs: number | null
|
||||
createdByUserId: string | null
|
||||
/** When the last sleeping read snapshot was stored (ms); null when none or unknown. */
|
||||
readSnapshotAt: number | null
|
||||
}
|
||||
const SANDBOX_STATUS: Record<string, CloudWorkspaceStatus> = {
|
||||
creating: 'creating',
|
||||
@@ -93,7 +95,8 @@ function fromRegistry(row: TeamWorkspace): CloudWorkspace {
|
||||
createdAt: row.createdAt,
|
||||
lastActivityAt: row.lastActivityAt,
|
||||
sandboxMs: row.cost.computeMs,
|
||||
createdByUserId: row.createdBy
|
||||
createdByUserId: row.createdBy,
|
||||
readSnapshotAt: row.readSnapshotAt ?? null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,7 +111,8 @@ function fromSandbox(row: z.infer<typeof SandboxViewSchema>): CloudWorkspace {
|
||||
createdAt: row.createdAt,
|
||||
lastActivityAt: null,
|
||||
sandboxMs: null,
|
||||
createdByUserId: null
|
||||
createdByUserId: null,
|
||||
readSnapshotAt: null
|
||||
}
|
||||
}
|
||||
// Lists archived rows as `archived` rather than folding them into `suspended` (W2 lifecycle).
|
||||
|
||||
@@ -23,7 +23,7 @@ const ErrorBodySchema = z.object({ error: z.string(), reason: z.string().optiona
|
||||
|
||||
export async function cloudRequest<T>(
|
||||
plane: CloudControlPlane,
|
||||
method: 'GET' | 'POST' | 'PATCH' | 'DELETE',
|
||||
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE',
|
||||
path: string,
|
||||
schema: z.ZodType<T>,
|
||||
init: {
|
||||
|
||||
@@ -3,6 +3,7 @@ import nacl from 'tweetnacl'
|
||||
import { z } from 'zod'
|
||||
import { randomBytes } from '../transport/encryption/e2ee'
|
||||
import { decodeBase64Bytes, encodeBase64Bytes } from '../transport/encryption/base64-byte-codec'
|
||||
import { clearCloudReaderKey } from './cloud-reader-key'
|
||||
|
||||
// This phone's own Orca Cloud key and enrollment. Kept off iCloud Keychain and backups, like pairing
|
||||
// credentials, so a restored phone has to be enrolled again rather than inheriting access.
|
||||
@@ -91,6 +92,8 @@ export async function saveCloudEnrollment(enrollment: CloudEnrollment): Promise<
|
||||
export async function clearCloudEnrollment(): Promise<void> {
|
||||
const seed = randomBytes(32)
|
||||
await write(seed, null)
|
||||
// The reader key goes with the session: snapshots sealed to it stay unreadable here.
|
||||
await clearCloudReaderKey().catch(() => undefined)
|
||||
cached = Promise.resolve(fromSeed(seed, null))
|
||||
listeners.forEach((listener) => listener())
|
||||
}
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import {
|
||||
classifyEntitlementDenial,
|
||||
type OrcaEntitlementDenialKind
|
||||
} from '../../../src/shared/orca-billing'
|
||||
import type { Translate } from '../i18n/mobile-i18n'
|
||||
import {
|
||||
readCloudRole,
|
||||
@@ -13,25 +17,20 @@ import { CloudRequestError, type CloudControlPlane } from './cloud-control-plane
|
||||
|
||||
type Denial = 'hours' | 'cap' | 'payment' | 'plan' | 'teamLimit' | 'memberLimit' | 'other'
|
||||
|
||||
// The shared classifier names the category; the phone keeps its own wording per category.
|
||||
const DENIALS: Record<OrcaEntitlementDenialKind, Denial> = {
|
||||
plan: 'plan',
|
||||
hours: 'hours',
|
||||
spendCap: 'cap',
|
||||
payment: 'payment',
|
||||
teamLimit: 'teamLimit',
|
||||
memberLimit: 'memberLimit',
|
||||
machineSize: 'other',
|
||||
other: 'other'
|
||||
}
|
||||
|
||||
function denialOf(reason: string | undefined): Denial {
|
||||
switch (reason) {
|
||||
case 'included_hours_exhausted':
|
||||
return 'hours'
|
||||
case 'overage_cap_reached':
|
||||
return 'cap'
|
||||
case 'payment_past_due':
|
||||
case 'payment_grace_expired':
|
||||
return 'payment'
|
||||
case 'no_subscription':
|
||||
case 'subscription_inactive':
|
||||
return 'plan'
|
||||
case 'concurrency_limit':
|
||||
return 'teamLimit'
|
||||
case 'member_concurrency_limit':
|
||||
return 'memberLimit'
|
||||
default:
|
||||
return 'other'
|
||||
}
|
||||
return DENIALS[classifyEntitlementDenial(reason)]
|
||||
}
|
||||
|
||||
export function isEntitlementDenied(error: unknown): error is CloudRequestError {
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import { StyleSheet } from 'react-native'
|
||||
import { colors, radii, spacing, typography } from '../theme/mobile-theme'
|
||||
import { themedStyleSheet } from '../theme/themed-styles'
|
||||
|
||||
// The asleep workspace's read-only "Latest from this workspace" area; scheme-aware like every cloud card.
|
||||
export const readSnapshotStyles = themedStyleSheet(() => ({
|
||||
headingRow: { flexDirection: 'row', alignItems: 'baseline', gap: spacing.sm },
|
||||
headingText: { flex: 1 },
|
||||
headingState: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: 6,
|
||||
marginBottom: spacing.sm,
|
||||
paddingHorizontal: spacing.xs
|
||||
},
|
||||
headingStateText: { fontSize: 13, color: colors.textSecondary },
|
||||
asOf: {
|
||||
fontSize: 13,
|
||||
lineHeight: 18,
|
||||
color: colors.textMuted,
|
||||
marginBottom: spacing.sm,
|
||||
paddingHorizontal: spacing.xs
|
||||
},
|
||||
asOfButton: { alignSelf: 'flex-start', minHeight: 32, justifyContent: 'center' },
|
||||
stack: { gap: spacing.sm },
|
||||
row: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: spacing.sm,
|
||||
paddingHorizontal: spacing.lg,
|
||||
paddingVertical: spacing.md,
|
||||
minHeight: 52
|
||||
},
|
||||
rowDivider: {
|
||||
borderTopWidth: StyleSheet.hairlineWidth,
|
||||
borderTopColor: colors.borderSubtle
|
||||
},
|
||||
rowText: { flex: 1, gap: 2 },
|
||||
rowTitle: { fontSize: 15, lineHeight: 20, color: colors.textPrimary },
|
||||
rowMeta: { fontSize: 13, lineHeight: 18, color: colors.textSecondary },
|
||||
rowMetaAttention: { color: colors.statusAmber },
|
||||
mono: {
|
||||
fontFamily: typography.monoFamily,
|
||||
fontSize: 12,
|
||||
lineHeight: 17,
|
||||
color: colors.textSecondary
|
||||
},
|
||||
added: { color: colors.gitDecorationAdded },
|
||||
removed: { color: colors.gitDecorationDeleted },
|
||||
gitBody: { paddingHorizontal: spacing.lg, paddingVertical: spacing.md, gap: 6 },
|
||||
gitHeadline: { flexDirection: 'row', alignItems: 'baseline', gap: spacing.sm, flexWrap: 'wrap' },
|
||||
transcript: {
|
||||
paddingHorizontal: spacing.md,
|
||||
paddingBottom: spacing.md,
|
||||
gap: spacing.sm
|
||||
},
|
||||
truncatedNote: {
|
||||
fontSize: 12,
|
||||
color: colors.textMuted,
|
||||
textAlign: 'center',
|
||||
paddingVertical: spacing.xs
|
||||
},
|
||||
roleLabel: { fontSize: 11, fontWeight: '600', color: colors.textMuted, marginBottom: 2 },
|
||||
bubbleUser: {
|
||||
alignSelf: 'flex-end',
|
||||
maxWidth: '88%',
|
||||
backgroundColor: colors.chatUserSurface,
|
||||
borderWidth: StyleSheet.hairlineWidth,
|
||||
borderColor: colors.chatUserBorder,
|
||||
borderRadius: radii.surface,
|
||||
paddingHorizontal: spacing.md,
|
||||
paddingVertical: spacing.sm
|
||||
},
|
||||
bubbleAssistant: {
|
||||
alignSelf: 'stretch',
|
||||
paddingHorizontal: spacing.xs,
|
||||
paddingVertical: 2
|
||||
},
|
||||
bubbleSystem: {
|
||||
alignSelf: 'stretch',
|
||||
paddingHorizontal: spacing.sm,
|
||||
paddingVertical: spacing.xs,
|
||||
borderRadius: radii.control,
|
||||
backgroundColor: colors.bgRaised
|
||||
},
|
||||
userText: { fontSize: 15, lineHeight: 21, color: colors.textPrimary },
|
||||
systemText: { fontSize: 13, lineHeight: 18, color: colors.textSecondary },
|
||||
notice: {
|
||||
backgroundColor: colors.bgPanel,
|
||||
borderRadius: radii.surface,
|
||||
borderWidth: StyleSheet.hairlineWidth,
|
||||
borderColor: colors.borderSubtle,
|
||||
paddingHorizontal: spacing.lg,
|
||||
paddingVertical: spacing.md
|
||||
},
|
||||
noticeText: { fontSize: typography.bodySize, lineHeight: 20, color: colors.textSecondary },
|
||||
skeletonCard: {
|
||||
backgroundColor: colors.bgPanel,
|
||||
borderRadius: radii.surface,
|
||||
borderWidth: StyleSheet.hairlineWidth,
|
||||
borderColor: colors.borderSubtle,
|
||||
padding: spacing.lg,
|
||||
gap: spacing.md
|
||||
},
|
||||
skeletonBar: { height: 10, borderRadius: 5, backgroundColor: colors.bgRaised }
|
||||
}))
|
||||
@@ -0,0 +1,331 @@
|
||||
import {
|
||||
createCipheriv,
|
||||
createPublicKey,
|
||||
diffieHellman,
|
||||
generateKeyPairSync,
|
||||
hkdfSync,
|
||||
randomBytes
|
||||
} from 'node:crypto'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { store } = vi.hoisted(() => ({ store: new Map<string, string>() }))
|
||||
vi.mock('expo-secure-store', () => ({
|
||||
WHEN_UNLOCKED_THIS_DEVICE_ONLY: 'WHEN_UNLOCKED_THIS_DEVICE_ONLY',
|
||||
getItemAsync: async (key: string) => store.get(key) ?? null,
|
||||
setItemAsync: async (key: string, value: string) => void store.set(key, value),
|
||||
deleteItemAsync: async (key: string) => void store.delete(key)
|
||||
}))
|
||||
vi.mock('./cloud-device-identity', () => ({
|
||||
loadCloudDeviceIdentity: async () => ({
|
||||
publicKeyB64: 'x',
|
||||
secretKey: new Uint8Array(64),
|
||||
enrollment: {
|
||||
controlPlaneUrl: 'https://cloud.test',
|
||||
deviceSessionId: 'ds_1',
|
||||
label: 'Neil’s iPhone',
|
||||
enrolledAt: 1
|
||||
}
|
||||
})
|
||||
}))
|
||||
|
||||
import type { SealedReadSnapshot } from '../../../src/shared/cloud-workspaces/read-snapshot'
|
||||
import type { CloudControlPlane } from './cloud-control-plane-request'
|
||||
import {
|
||||
CLOUD_READER_KEY_REFRESH_MS,
|
||||
ensureCloudReaderKey,
|
||||
readCloudWorkspaceSnapshot,
|
||||
resetCloudReadSnapshotPins
|
||||
} from './cloud-read-snapshot'
|
||||
import { loadCloudReaderKey } from './cloud-reader-key'
|
||||
|
||||
// Seals exactly as the header of src/shared/cloud-workspaces/read-snapshot.ts says the VM does.
|
||||
function sealLikeVm(args: {
|
||||
readerPublicKeyB64: string
|
||||
keyId: string
|
||||
workspaceId: string
|
||||
snapshotId: string
|
||||
payload: unknown
|
||||
}): SealedReadSnapshot {
|
||||
const dek = randomBytes(32)
|
||||
const nonce = randomBytes(12)
|
||||
const body = createCipheriv('aes-256-gcm', dek, nonce)
|
||||
body.setAAD(Buffer.from(`orca-cloud-read-v1:${args.workspaceId}:${args.snapshotId}`))
|
||||
const ciphertext = Buffer.concat([
|
||||
body.update(JSON.stringify(args.payload), 'utf8'),
|
||||
body.final(),
|
||||
body.getAuthTag()
|
||||
])
|
||||
const readerPublic = Buffer.from(args.readerPublicKeyB64, 'base64')
|
||||
const eph = generateKeyPairSync('x25519')
|
||||
const ephRaw = Buffer.from(eph.publicKey.export({ format: 'jwk' }).x!, 'base64url')
|
||||
const shared = diffieHellman({
|
||||
privateKey: eph.privateKey,
|
||||
publicKey: createPublicKey({
|
||||
key: { kty: 'OKP', crv: 'X25519', x: readerPublic.toString('base64url') },
|
||||
format: 'jwk'
|
||||
})
|
||||
})
|
||||
const kek = Buffer.from(
|
||||
hkdfSync('sha256', shared, Buffer.concat([ephRaw, readerPublic]), 'orca-cloud-read-wrap-v1', 32)
|
||||
)
|
||||
const wrapNonce = randomBytes(12)
|
||||
const wrap = createCipheriv('aes-256-gcm', kek, wrapNonce)
|
||||
wrap.setAAD(
|
||||
Buffer.from(`orca-cloud-read-wrap-v1:${args.workspaceId}:${args.snapshotId}:${args.keyId}`)
|
||||
)
|
||||
const wrapped = Buffer.concat([wrap.update(dek), wrap.final(), wrap.getAuthTag()])
|
||||
return {
|
||||
v: 1,
|
||||
snapshotId: args.snapshotId,
|
||||
workspaceId: args.workspaceId,
|
||||
storedAt: 2,
|
||||
nonceB64: nonce.toString('base64'),
|
||||
ciphertextB64: ciphertext.toString('base64'),
|
||||
recipient: {
|
||||
keyId: args.keyId,
|
||||
ephemeralPublicKeyB64: ephRaw.toString('base64'),
|
||||
nonceB64: wrapNonce.toString('base64'),
|
||||
wrappedKeyB64: wrapped.toString('base64')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const PAYLOAD = {
|
||||
v: 1,
|
||||
workspaceId: 'sbx_1',
|
||||
snapshotId: 'snap_1',
|
||||
capturedAt: 1_700_000_000_000,
|
||||
reason: 'sleep',
|
||||
pr: {
|
||||
number: 42,
|
||||
title: 'Fix login',
|
||||
state: 'open',
|
||||
url: 'https://github.com/o/r/pull/42',
|
||||
checksStatus: 'success',
|
||||
checksSummary: null
|
||||
},
|
||||
git: { branch: 'fix-login', changes: [{ path: 'a.ts', added: 3, removed: 1 }], changeCount: 1 },
|
||||
sessions: [
|
||||
{
|
||||
sessionId: 's1',
|
||||
agent: 'claude',
|
||||
title: 'Login bug',
|
||||
status: 'idle',
|
||||
turnOutcome: 'completed',
|
||||
messages: [
|
||||
{ itemId: 'm1', role: 'user', text: 'fix it', at: 1 },
|
||||
{ itemId: 'm2', role: 'assistant', text: '**Done**', at: 2 }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
type Call = { method: string; url: string; body: unknown }
|
||||
|
||||
function fakePlane(handle: (call: Call) => { status: number; body: unknown }): {
|
||||
plane: CloudControlPlane
|
||||
calls: Call[]
|
||||
} {
|
||||
const calls: Call[] = []
|
||||
const fakeFetch: typeof fetch = async (input, init) => {
|
||||
const call = {
|
||||
method: init?.method ?? 'GET',
|
||||
url: String(input),
|
||||
body: init?.body ? JSON.parse(String(init.body)) : undefined
|
||||
}
|
||||
calls.push(call)
|
||||
const reply = handle(call)
|
||||
return new Response(JSON.stringify(reply.body), { status: reply.status })
|
||||
}
|
||||
const plane: CloudControlPlane = {
|
||||
baseUrl: 'https://cloud.test',
|
||||
token: () => 'tok',
|
||||
fetch: fakeFetch
|
||||
}
|
||||
return { plane, calls }
|
||||
}
|
||||
|
||||
const registered = (id = 'rk_aaaaaaaaaaaaaaaaaaaaaaaa') => ({
|
||||
status: 200,
|
||||
body: {
|
||||
readerKey: { id, deviceKind: 'mobile', deviceLabel: 'x', createdAt: 1, lastSeenAt: 1 }
|
||||
}
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
store.clear()
|
||||
resetCloudReadSnapshotPins()
|
||||
})
|
||||
|
||||
describe('ensureCloudReaderKey', () => {
|
||||
it('registers once as a mobile key, then only again after 6 h or when forced', async () => {
|
||||
let clock = 1_000
|
||||
const now = () => clock
|
||||
const { plane, calls } = fakePlane(() => registered())
|
||||
const first = await ensureCloudReaderKey(plane, { now })
|
||||
const key = await loadCloudReaderKey('ds_1')
|
||||
expect(first?.keyId).toBe('rk_aaaaaaaaaaaaaaaaaaaaaaaa')
|
||||
expect(calls).toHaveLength(1)
|
||||
expect(calls[0]).toMatchObject({
|
||||
method: 'PUT',
|
||||
url: 'https://cloud.test/v1/reader-keys',
|
||||
body: { publicKeyB64: key.publicKeyB64, deviceLabel: 'Neil’s iPhone', deviceKind: 'mobile' }
|
||||
})
|
||||
await ensureCloudReaderKey(plane, { now })
|
||||
expect(calls).toHaveLength(1)
|
||||
clock += CLOUD_READER_KEY_REFRESH_MS
|
||||
await ensureCloudReaderKey(plane, { now })
|
||||
expect(calls).toHaveLength(2)
|
||||
await ensureCloudReaderKey(plane, { now, force: true })
|
||||
expect(calls).toHaveLength(3)
|
||||
})
|
||||
})
|
||||
|
||||
describe('readCloudWorkspaceSnapshot', () => {
|
||||
it('opens a snapshot the VM sealed to this phone (node:crypto seal, Hermes primitives open)', async () => {
|
||||
const key = await loadCloudReaderKey('ds_1')
|
||||
const keyId = 'rk_bbbbbbbbbbbbbbbbbbbbbbbb'
|
||||
const sealed = sealLikeVm({
|
||||
readerPublicKeyB64: key.publicKeyB64,
|
||||
keyId,
|
||||
workspaceId: 'sbx_1',
|
||||
snapshotId: 'snap_1',
|
||||
payload: PAYLOAD
|
||||
})
|
||||
const { plane, calls } = fakePlane((call) =>
|
||||
call.method === 'PUT' ? registered(keyId) : { status: 200, body: { snapshot: sealed } }
|
||||
)
|
||||
const result = await readCloudWorkspaceSnapshot(plane, 'sbx_1')
|
||||
expect(calls[1]?.url).toBe(
|
||||
`https://cloud.test/v1/team/workspaces/sbx_1/read-snapshot?keyId=${keyId}`
|
||||
)
|
||||
expect(calls.some((call) => /wake/.test(call.url))).toBe(false)
|
||||
expect(result.state).toBe('ready')
|
||||
if (result.state !== 'ready') {
|
||||
return
|
||||
}
|
||||
expect(result.snapshot.capturedAt).toBe(PAYLOAD.capturedAt)
|
||||
expect(result.snapshot.pr?.number).toBe(42)
|
||||
expect(result.snapshot.git?.branch).toBe('fix-login')
|
||||
expect(result.snapshot.sessions[0]?.messages.map((m) => m.role)).toEqual(['user', 'assistant'])
|
||||
})
|
||||
|
||||
it('refuses a snapshot sealed for another workspace', async () => {
|
||||
const key = await loadCloudReaderKey('ds_1')
|
||||
const sealed = sealLikeVm({
|
||||
readerPublicKeyB64: key.publicKeyB64,
|
||||
keyId: 'rk_111111111111111111111111',
|
||||
workspaceId: 'sbx_other',
|
||||
snapshotId: 'snap_1',
|
||||
payload: { ...PAYLOAD, workspaceId: 'sbx_other' }
|
||||
})
|
||||
const { plane } = fakePlane((call) =>
|
||||
call.method === 'PUT'
|
||||
? registered('rk_111111111111111111111111')
|
||||
: { status: 200, body: { snapshot: sealed } }
|
||||
)
|
||||
const result = await readCloudWorkspaceSnapshot(plane, 'sbx_1')
|
||||
expect(result.state).toBe('error')
|
||||
})
|
||||
|
||||
it('fails closed when the wrapped key is for another key id', async () => {
|
||||
const key = await loadCloudReaderKey('ds_1')
|
||||
const sealed = sealLikeVm({
|
||||
readerPublicKeyB64: key.publicKeyB64,
|
||||
keyId: 'rk_111111111111111111111111',
|
||||
workspaceId: 'sbx_1',
|
||||
snapshotId: 'snap_1',
|
||||
payload: PAYLOAD
|
||||
})
|
||||
sealed.recipient.keyId = 'rk_222222222222222222222222'
|
||||
const { plane } = fakePlane((call) =>
|
||||
call.method === 'PUT'
|
||||
? registered('rk_222222222222222222222222')
|
||||
: { status: 200, body: { snapshot: sealed } }
|
||||
)
|
||||
const result = await readCloudWorkspaceSnapshot(plane, 'sbx_1')
|
||||
expect(result).toMatchObject({ state: 'error', error: { code: 'decrypt_failed' } })
|
||||
})
|
||||
|
||||
it.each(['no_snapshot', 'not_sealed_for_key', 'not_found'] as const)(
|
||||
'maps 404 %s to its state',
|
||||
async (code) => {
|
||||
const { plane } = fakePlane((call) =>
|
||||
call.method === 'PUT' ? registered() : { status: 404, body: { error: code } }
|
||||
)
|
||||
await expect(readCloudWorkspaceSnapshot(plane, 'sbx_1')).resolves.toEqual({ state: code })
|
||||
}
|
||||
)
|
||||
|
||||
it('does not renew the key on not_sealed_for_key', async () => {
|
||||
const { plane, calls } = fakePlane((call) =>
|
||||
call.method === 'PUT' ? registered() : { status: 404, body: { error: 'not_sealed_for_key' } }
|
||||
)
|
||||
await readCloudWorkspaceSnapshot(plane, 'sbx_1')
|
||||
expect(calls.map((c) => c.method)).toEqual(['PUT', 'GET'])
|
||||
})
|
||||
|
||||
it('refuses a snapshot older than one already shown for the workspace (rollback pin)', async () => {
|
||||
const key = await loadCloudReaderKey('ds_1')
|
||||
const keyId = `rk_${'c'.repeat(24)}`
|
||||
const seal = (snapshotId: string, capturedAt: number) =>
|
||||
sealLikeVm({
|
||||
readerPublicKeyB64: key.publicKeyB64,
|
||||
keyId,
|
||||
workspaceId: 'sbx_pin',
|
||||
snapshotId,
|
||||
payload: { ...PAYLOAD, workspaceId: 'sbx_pin', snapshotId, capturedAt }
|
||||
})
|
||||
let next = seal('snap_new', 2_000)
|
||||
const { plane } = fakePlane((call) =>
|
||||
call.method === 'PUT' ? registered(keyId) : { status: 200, body: { snapshot: next } }
|
||||
)
|
||||
expect((await readCloudWorkspaceSnapshot(plane, 'sbx_pin')).state).toBe('ready')
|
||||
next = seal('snap_old', 1_000)
|
||||
expect(await readCloudWorkspaceSnapshot(plane, 'sbx_pin')).toMatchObject({
|
||||
state: 'error',
|
||||
error: { name: 'CloudReadSnapshotRollbackError', capturedAt: 1_000, newestShownAt: 2_000 }
|
||||
})
|
||||
next = seal('snap_same', 2_000)
|
||||
expect((await readCloudWorkspaceSnapshot(plane, 'sbx_pin')).state).toBe('ready')
|
||||
next = seal('snap_newer', 3_000)
|
||||
expect((await readCloudWorkspaceSnapshot(plane, 'sbx_pin')).state).toBe('ready')
|
||||
next = seal('snap_same', 2_000)
|
||||
expect((await readCloudWorkspaceSnapshot(plane, 'sbx_pin')).state).toBe('error')
|
||||
})
|
||||
|
||||
it('re-registers once on invalid_request and asks again', async () => {
|
||||
let gets = 0
|
||||
const { plane, calls } = fakePlane((call) => {
|
||||
if (call.method === 'PUT') {
|
||||
return registered(
|
||||
gets === 0 ? 'rk_000000000000000000000000' : 'rk_ffffffffffffffffffffffff'
|
||||
)
|
||||
}
|
||||
gets += 1
|
||||
return gets === 1
|
||||
? { status: 400, body: { error: 'invalid_request' } }
|
||||
: { status: 404, body: { error: 'no_snapshot' } }
|
||||
})
|
||||
await expect(readCloudWorkspaceSnapshot(plane, 'sbx_1')).resolves.toEqual({
|
||||
state: 'no_snapshot'
|
||||
})
|
||||
expect(calls.map((c) => c.method)).toEqual(['PUT', 'GET', 'PUT', 'GET'])
|
||||
expect(calls[3]?.url).toContain('keyId=rk_ffffffffffffffffffffffff')
|
||||
})
|
||||
|
||||
it('returns a 401 as an error carrying the status, for the caller to forget the session', async () => {
|
||||
const { plane } = fakePlane((call) =>
|
||||
call.method === 'PUT' ? registered() : { status: 401, body: { error: 'unauthorized' } }
|
||||
)
|
||||
const result = await readCloudWorkspaceSnapshot(plane, 'sbx_1')
|
||||
expect(result).toMatchObject({ state: 'error', error: { status: 401 } })
|
||||
})
|
||||
|
||||
it('returns a malformed reply as an error', async () => {
|
||||
const { plane } = fakePlane((call) =>
|
||||
call.method === 'PUT' ? registered() : { status: 200, body: { snapshot: { v: 2 } } }
|
||||
)
|
||||
expect((await readCloudWorkspaceSnapshot(plane, 'sbx_1')).state).toBe('error')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,190 @@
|
||||
import {
|
||||
CloudReadSnapshotResponseSchema,
|
||||
CloudReaderKeyResponseSchema
|
||||
} from '../../../src/shared/cloud-workspaces/cloud-workspaces-wire'
|
||||
import {
|
||||
openReadSnapshot,
|
||||
type ReadSnapshot,
|
||||
type SealedReadSnapshot
|
||||
} from '../../../src/shared/cloud-workspaces/read-snapshot'
|
||||
import {
|
||||
CloudRequestError,
|
||||
cloudRequest,
|
||||
type CloudControlPlane
|
||||
} from './cloud-control-plane-request'
|
||||
import { loadCloudDeviceIdentity } from './cloud-device-identity'
|
||||
import { loadCloudReaderKey, saveCloudReaderKeyRegistration } from './cloud-reader-key'
|
||||
import { CLOUD_SEALED_PRIMITIVES } from './cloud-sealed-grant'
|
||||
|
||||
// Reads a sleeping workspace's sealed snapshot without waking it. The control plane relays only
|
||||
// ciphertext plus this phone's own wrapped key; the reader key's secret opens it on the phone.
|
||||
|
||||
/** Re-register at most this often; the control plane bumps lastSeenAt on each. */
|
||||
export const CLOUD_READER_KEY_REFRESH_MS = 6 * 60 * 60 * 1000
|
||||
|
||||
export type CloudReadSnapshotResult =
|
||||
| { state: 'ready'; snapshot: ReadSnapshot }
|
||||
/** Nothing captured yet: it is captured each time the workspace goes to sleep. */
|
||||
| { state: 'no_snapshot' }
|
||||
/** A snapshot exists, but this phone's key was added (or renewed) after it last slept. */
|
||||
| { state: 'not_sealed_for_key' }
|
||||
/** Gone, or this phone may no longer open it. */
|
||||
| { state: 'not_found' }
|
||||
/** Anything else; a 401 here means the session was revoked (see forgetRevokedCloudSession). */
|
||||
| { state: 'error'; error: unknown }
|
||||
|
||||
const inflight = new Map<string, Promise<{ keyId: string; secretKey: Uint8Array }>>()
|
||||
|
||||
/**
|
||||
* This phone's reader key, registered with the control plane (PUT /v1/reader-keys) when it never
|
||||
* was, when the last registration is over 6 h old, or when `force` is set. Null before enrollment.
|
||||
*/
|
||||
export async function ensureCloudReaderKey(
|
||||
plane: CloudControlPlane,
|
||||
options: { force?: boolean; now?: () => number } = {}
|
||||
): Promise<{ keyId: string; secretKey: Uint8Array } | null> {
|
||||
const enrollment = (await loadCloudDeviceIdentity()).enrollment
|
||||
if (!enrollment) {
|
||||
return null
|
||||
}
|
||||
const now = options.now ?? Date.now
|
||||
const sessionId = enrollment.deviceSessionId
|
||||
const running = inflight.get(sessionId)
|
||||
if (running) {
|
||||
return running
|
||||
}
|
||||
const task = (async () => {
|
||||
const key = await loadCloudReaderKey(sessionId)
|
||||
const registered = key.registration
|
||||
if (
|
||||
!options.force &&
|
||||
registered &&
|
||||
now() - registered.registeredAt < CLOUD_READER_KEY_REFRESH_MS
|
||||
) {
|
||||
return { keyId: registered.keyId, secretKey: key.secretKey }
|
||||
}
|
||||
const reply = await cloudRequest(
|
||||
plane,
|
||||
'PUT',
|
||||
'/v1/reader-keys',
|
||||
CloudReaderKeyResponseSchema,
|
||||
{
|
||||
body: {
|
||||
publicKeyB64: key.publicKeyB64,
|
||||
deviceLabel: enrollment.label.trim().slice(0, 80) || 'Orca mobile',
|
||||
deviceKind: 'mobile'
|
||||
},
|
||||
timeoutMs: 15_000
|
||||
}
|
||||
)
|
||||
const keyId = reply.readerKey.id
|
||||
await saveCloudReaderKeyRegistration(key, { keyId, registeredAt: now() })
|
||||
return { keyId, secretKey: key.secretKey }
|
||||
})()
|
||||
inflight.set(sessionId, task)
|
||||
try {
|
||||
return await task
|
||||
} finally {
|
||||
inflight.delete(sessionId)
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchSealed(
|
||||
plane: CloudControlPlane,
|
||||
sandboxId: string,
|
||||
keyId: string,
|
||||
signal?: AbortSignal
|
||||
): Promise<SealedReadSnapshot> {
|
||||
const reply = await cloudRequest(
|
||||
plane,
|
||||
'GET',
|
||||
`/v1/team/workspaces/${encodeURIComponent(sandboxId)}/read-snapshot?keyId=${encodeURIComponent(keyId)}`,
|
||||
CloudReadSnapshotResponseSchema,
|
||||
{ signal, timeoutMs: 20_000 }
|
||||
)
|
||||
return reply.snapshot
|
||||
}
|
||||
|
||||
/** A snapshot older than one this phone already showed for the workspace: a rollback, refused. */
|
||||
export class CloudReadSnapshotRollbackError extends Error {
|
||||
constructor(
|
||||
readonly capturedAt: number,
|
||||
readonly newestShownAt: number
|
||||
) {
|
||||
super('read_snapshot_rollback')
|
||||
this.name = 'CloudReadSnapshotRollbackError'
|
||||
}
|
||||
}
|
||||
|
||||
// Per workspace, the newest capturedAt opened this app session. The control plane relays the
|
||||
// ciphertext, so it could replay an older (validly sealed) snapshot; this pins it forward.
|
||||
const newestShown = new Map<string, number>()
|
||||
|
||||
/** Test seam: forget the per-workspace rollback pins. */
|
||||
export function resetCloudReadSnapshotPins(): void {
|
||||
newestShown.clear()
|
||||
}
|
||||
|
||||
type MissingState = 'no_snapshot' | 'not_sealed_for_key' | 'not_found'
|
||||
|
||||
const isMissingState = (code: string): code is MissingState =>
|
||||
code === 'no_snapshot' || code === 'not_sealed_for_key' || code === 'not_found'
|
||||
|
||||
function missingState(error: unknown): MissingState | null {
|
||||
return error instanceof CloudRequestError && error.status === 404 && isMissingState(error.code)
|
||||
? error.code
|
||||
: null
|
||||
}
|
||||
|
||||
/** The sleeping workspace's last snapshot, opened on this phone; never wakes the sandbox. */
|
||||
export async function readCloudWorkspaceSnapshot(
|
||||
plane: CloudControlPlane,
|
||||
sandboxId: string,
|
||||
options: { signal?: AbortSignal; now?: () => number } = {}
|
||||
): Promise<CloudReadSnapshotResult> {
|
||||
const { signal, now } = options
|
||||
try {
|
||||
let reader = await ensureCloudReaderKey(plane, { now })
|
||||
if (!reader) {
|
||||
return { state: 'error', error: new CloudRequestError('not_enrolled', 0) }
|
||||
}
|
||||
let sealed: SealedReadSnapshot
|
||||
try {
|
||||
sealed = await fetchSealed(plane, sandboxId, reader.keyId, signal)
|
||||
} catch (error) {
|
||||
if (
|
||||
!(error instanceof CloudRequestError) ||
|
||||
error.status !== 400 ||
|
||||
error.code !== 'invalid_request'
|
||||
) {
|
||||
throw error
|
||||
}
|
||||
// A key id the control plane no longer takes: register again and ask once more.
|
||||
reader = await ensureCloudReaderKey(plane, { force: true, now })
|
||||
if (!reader) {
|
||||
throw error
|
||||
}
|
||||
sealed = await fetchSealed(plane, sandboxId, reader.keyId, signal)
|
||||
}
|
||||
// The AAD binds exactly the sandbox row id this phone asked for.
|
||||
const snapshot = await openReadSnapshot(
|
||||
sealed,
|
||||
sandboxId,
|
||||
reader.secretKey,
|
||||
CLOUD_SEALED_PRIMITIVES
|
||||
)
|
||||
const pinned = newestShown.get(sandboxId)
|
||||
if (pinned !== undefined && snapshot.capturedAt < pinned) {
|
||||
return {
|
||||
state: 'error',
|
||||
error: new CloudReadSnapshotRollbackError(snapshot.capturedAt, pinned)
|
||||
}
|
||||
}
|
||||
newestShown.set(sandboxId, snapshot.capturedAt)
|
||||
return { state: 'ready', snapshot }
|
||||
} catch (error) {
|
||||
// not_sealed_for_key only means the snapshot predates this key: nothing to renew here.
|
||||
const missing = missingState(error)
|
||||
return missing ? { state: missing } : { state: 'error', error }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { store, options } = vi.hoisted(() => {
|
||||
const options: unknown[] = []
|
||||
return { store: new Map<string, string>(), options }
|
||||
})
|
||||
vi.mock('expo-secure-store', () => ({
|
||||
WHEN_UNLOCKED_THIS_DEVICE_ONLY: 'WHEN_UNLOCKED_THIS_DEVICE_ONLY',
|
||||
getItemAsync: vi.fn(async (key: string, opts: unknown) => {
|
||||
options.push(opts)
|
||||
return store.get(key) ?? null
|
||||
}),
|
||||
setItemAsync: vi.fn(async (key: string, value: string, opts: unknown) => {
|
||||
options.push(opts)
|
||||
store.set(key, value)
|
||||
}),
|
||||
deleteItemAsync: vi.fn(async (key: string) => {
|
||||
store.delete(key)
|
||||
})
|
||||
}))
|
||||
|
||||
import nacl from 'tweetnacl'
|
||||
import {
|
||||
clearCloudReaderKey,
|
||||
loadCloudReaderKey,
|
||||
saveCloudReaderKeyRegistration
|
||||
} from './cloud-reader-key'
|
||||
|
||||
const STORE_KEY = 'orca.cloud-reader.v1'
|
||||
|
||||
beforeEach(() => {
|
||||
store.clear()
|
||||
options.length = 0
|
||||
})
|
||||
|
||||
describe('cloud reader key store', () => {
|
||||
it('generates one X25519 key lazily, this device only, and keeps it', async () => {
|
||||
const [a, b] = await Promise.all([loadCloudReaderKey('ds_1'), loadCloudReaderKey('ds_1')])
|
||||
expect(a.publicKeyB64).toBe(b.publicKeyB64)
|
||||
expect(a.secretKey).toHaveLength(32)
|
||||
expect(a.registration).toBeNull()
|
||||
expect(Buffer.from(nacl.scalarMult.base(a.secretKey)).toString('base64')).toBe(a.publicKeyB64)
|
||||
expect(options).toContainEqual({ keychainAccessible: 'WHEN_UNLOCKED_THIS_DEVICE_ONLY' })
|
||||
expect(options.every((o) => JSON.stringify(o).includes('WHEN_UNLOCKED_THIS_DEVICE_ONLY'))).toBe(
|
||||
true
|
||||
)
|
||||
expect((await loadCloudReaderKey('ds_1')).publicKeyB64).toBe(a.publicKeyB64)
|
||||
})
|
||||
|
||||
it('records the registration for the same key only', async () => {
|
||||
const key = await loadCloudReaderKey('ds_1')
|
||||
await saveCloudReaderKeyRegistration(key, { keyId: 'rk_1', registeredAt: 5 })
|
||||
expect((await loadCloudReaderKey('ds_1')).registration).toEqual({
|
||||
keyId: 'rk_1',
|
||||
registeredAt: 5
|
||||
})
|
||||
await saveCloudReaderKeyRegistration(
|
||||
{ deviceSessionId: 'ds_1', publicKeyB64: 'other' },
|
||||
{ keyId: 'rk_2', registeredAt: 6 }
|
||||
)
|
||||
expect((await loadCloudReaderKey('ds_1')).registration?.keyId).toBe('rk_1')
|
||||
})
|
||||
|
||||
it('mints a new key for a new device session', async () => {
|
||||
const first = await loadCloudReaderKey('ds_1')
|
||||
await saveCloudReaderKeyRegistration(first, { keyId: 'rk_1', registeredAt: 5 })
|
||||
const second = await loadCloudReaderKey('ds_2')
|
||||
expect(second.publicKeyB64).not.toBe(first.publicKeyB64)
|
||||
expect(second.registration).toBeNull()
|
||||
})
|
||||
|
||||
it('replaces an unreadable item and drops the key on clear', async () => {
|
||||
store.set(STORE_KEY, '{not json')
|
||||
const key = await loadCloudReaderKey('ds_1')
|
||||
expect(key.secretKey).toHaveLength(32)
|
||||
await clearCloudReaderKey()
|
||||
expect(store.has(STORE_KEY)).toBe(false)
|
||||
expect((await loadCloudReaderKey('ds_1')).publicKeyB64).not.toBe(key.publicKeyB64)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,104 @@
|
||||
import * as SecureStore from 'expo-secure-store'
|
||||
import nacl from 'tweetnacl'
|
||||
import { z } from 'zod'
|
||||
import { decodeBase64Bytes, encodeBase64Bytes } from '../transport/encryption/base64-byte-codec'
|
||||
|
||||
// This phone's long-lived X25519 "reader key": sleeping workspaces seal their read-only snapshot to
|
||||
// its public half. The secret never leaves this keychain item (off iCloud Keychain and backups), and
|
||||
// it is bound to one device session, so a new enrollment never inherits an old session's key.
|
||||
const STORE_KEY = 'orca.cloud-reader.v1'
|
||||
const OPTIONS: SecureStore.SecureStoreOptions = {
|
||||
keychainAccessible: SecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY
|
||||
}
|
||||
|
||||
const RegistrationSchema = z.object({ keyId: z.string().min(1), registeredAt: z.number() })
|
||||
const StoredSchema = z.object({
|
||||
deviceSessionId: z.string().min(1),
|
||||
secretKeyB64: z.string(),
|
||||
registration: RegistrationSchema.nullable()
|
||||
})
|
||||
|
||||
export type CloudReaderKeyRegistration = z.infer<typeof RegistrationSchema>
|
||||
|
||||
export type CloudReaderKey = {
|
||||
deviceSessionId: string
|
||||
publicKeyB64: string
|
||||
secretKey: Uint8Array
|
||||
/** The control plane's id for this key (`rk_…`), once registered. */
|
||||
registration: CloudReaderKeyRegistration | null
|
||||
}
|
||||
|
||||
type Stored = z.infer<typeof StoredSchema>
|
||||
|
||||
// Every read-modify-write runs in order, so two callers never mint two keys.
|
||||
let queue: Promise<unknown> = Promise.resolve()
|
||||
function serial<T>(task: () => Promise<T>): Promise<T> {
|
||||
const next = queue.then(task, task)
|
||||
queue = next.catch(() => undefined)
|
||||
return next
|
||||
}
|
||||
|
||||
async function readStored(): Promise<Stored | null> {
|
||||
const raw = await SecureStore.getItemAsync(STORE_KEY, OPTIONS)
|
||||
if (!raw) {
|
||||
return null
|
||||
}
|
||||
try {
|
||||
const parsed = StoredSchema.safeParse(JSON.parse(raw))
|
||||
return parsed.success && decodeBase64Bytes(parsed.data.secretKeyB64).length === 32
|
||||
? parsed.data
|
||||
: null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function toKey(stored: Stored): CloudReaderKey {
|
||||
const secretKey = decodeBase64Bytes(stored.secretKeyB64)
|
||||
return {
|
||||
deviceSessionId: stored.deviceSessionId,
|
||||
publicKeyB64: encodeBase64Bytes(nacl.scalarMult.base(new Uint8Array(secretKey))),
|
||||
secretKey,
|
||||
registration: stored.registration
|
||||
}
|
||||
}
|
||||
|
||||
/** This session's reader key, generated on first use (only once the phone is enrolled). */
|
||||
export function loadCloudReaderKey(deviceSessionId: string): Promise<CloudReaderKey> {
|
||||
return serial(async () => {
|
||||
const stored = await readStored()
|
||||
if (stored && stored.deviceSessionId === deviceSessionId) {
|
||||
return toKey(stored)
|
||||
}
|
||||
const pair = nacl.box.keyPair()
|
||||
const fresh: Stored = {
|
||||
deviceSessionId,
|
||||
secretKeyB64: encodeBase64Bytes(new Uint8Array(pair.secretKey)),
|
||||
registration: null
|
||||
}
|
||||
await SecureStore.setItemAsync(STORE_KEY, JSON.stringify(fresh), OPTIONS)
|
||||
return toKey(fresh)
|
||||
})
|
||||
}
|
||||
|
||||
/** Records the control plane's id, unless the key was replaced or dropped meanwhile. */
|
||||
export function saveCloudReaderKeyRegistration(
|
||||
key: Pick<CloudReaderKey, 'deviceSessionId' | 'publicKeyB64'>,
|
||||
registration: CloudReaderKeyRegistration | null
|
||||
): Promise<void> {
|
||||
return serial(async () => {
|
||||
const stored = await readStored()
|
||||
if (!stored || stored.deviceSessionId !== key.deviceSessionId) {
|
||||
return
|
||||
}
|
||||
if (toKey(stored).publicKeyB64 !== key.publicKeyB64) {
|
||||
return
|
||||
}
|
||||
await SecureStore.setItemAsync(STORE_KEY, JSON.stringify({ ...stored, registration }), OPTIONS)
|
||||
})
|
||||
}
|
||||
|
||||
/** Drops the key with the cloud session: nothing this phone could read outlives its access. */
|
||||
export function clearCloudReaderKey(): Promise<void> {
|
||||
return serial(() => SecureStore.deleteItemAsync(STORE_KEY, OPTIONS))
|
||||
}
|
||||
@@ -9,8 +9,8 @@ import {
|
||||
type SealedGrantPrimitives
|
||||
} from '../../../src/shared/cloud-workspaces/sealed-grant'
|
||||
|
||||
// Hermes has no WebCrypto, so the shared opener runs on pure-JS primitives here.
|
||||
const PRIMITIVES: SealedGrantPrimitives = {
|
||||
// Hermes has no WebCrypto, so the shared openers (grants, read snapshots) run on pure-JS primitives.
|
||||
export const CLOUD_SEALED_PRIMITIVES: SealedGrantPrimitives = {
|
||||
x25519: (secretKey, publicKey) =>
|
||||
nacl.scalarMult(new Uint8Array(secretKey), new Uint8Array(publicKey)),
|
||||
x25519PublicKey: (secretKey) => nacl.scalarMult.base(new Uint8Array(secretKey)),
|
||||
@@ -29,5 +29,5 @@ export function openCloudSealedGrant(
|
||||
grantId: string,
|
||||
recipientSecretKey: Uint8Array
|
||||
): Promise<OpenedGrant> {
|
||||
return openSealedGrant(sealed, grantId, recipientSecretKey, PRIMITIVES, 'mobile')
|
||||
return openSealedGrant(sealed, grantId, recipientSecretKey, CLOUD_SEALED_PRIMITIVES, 'mobile')
|
||||
}
|
||||
|
||||
@@ -37,7 +37,9 @@ export function attachErrorMessage(
|
||||
'cloud.error.pairing',
|
||||
'The workspace is running, but this phone couldn’t connect to it. Your files are safe.'
|
||||
)
|
||||
default:
|
||||
case 'not_found':
|
||||
return t('cloud.workspace.missing', 'This workspace is gone or you no longer have access.')
|
||||
case 'failed':
|
||||
return t(
|
||||
'cloud.error.failed',
|
||||
'The workspace couldn’t start. Try again, or open it on your desktop.'
|
||||
@@ -128,6 +130,9 @@ export function cloudPromptErrorMessage(code: string | undefined, t: Translate):
|
||||
return t('cloud.prompt.errorNotConnected', 'This phone couldn’t reach the workspace')
|
||||
case 'cloud_agent_unknown':
|
||||
return t('cloud.prompt.errorAgent', 'That agent isn’t installed in this workspace')
|
||||
// An older queue entry may carry no code: it failed to launch all the same.
|
||||
case undefined:
|
||||
case 'launch_failed':
|
||||
default:
|
||||
return t('cloud.prompt.errorLaunch', 'The agent didn’t start')
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { readCloudWorkspaceSnapshot, type CloudReadSnapshotResult } from './cloud-read-snapshot'
|
||||
import {
|
||||
forgetRevokedCloudSession,
|
||||
loadCloudControlPlane,
|
||||
useCloudHostRemoval
|
||||
} from './cloud-session'
|
||||
|
||||
/**
|
||||
* The sleeping workspace's read-only snapshot, fetched only while it is asleep and never waking it.
|
||||
* Keyed by `readSnapshotAt`, so a newer sleep refetches; kept in memory only (never persisted).
|
||||
*/
|
||||
export function useCloudReadSnapshot(
|
||||
sandboxId: string,
|
||||
asleep: boolean,
|
||||
readSnapshotAt: number | null
|
||||
) {
|
||||
const removal = useCloudHostRemoval()
|
||||
return useQuery<CloudReadSnapshotResult>({
|
||||
queryKey: ['orca-cloud', 'read-snapshot', sandboxId, readSnapshotAt],
|
||||
enabled: asleep,
|
||||
queryFn: async ({ signal }) => {
|
||||
const plane = await loadCloudControlPlane()
|
||||
if (!plane) {
|
||||
return { state: 'error', error: new Error('not_enrolled') }
|
||||
}
|
||||
const result = await readCloudWorkspaceSnapshot(plane, sandboxId, { signal })
|
||||
if (result.state === 'error') {
|
||||
await forgetRevokedCloudSession(result.error, removal)
|
||||
}
|
||||
return result
|
||||
},
|
||||
// A snapshot only changes when the workspace sleeps again, which changes the key above.
|
||||
staleTime: 5 * 60_000,
|
||||
gcTime: 60_000,
|
||||
retry: false
|
||||
})
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
type CloudEnrollment
|
||||
} from './cloud-device-identity'
|
||||
import { pruneCloudHostsMissingFrom } from './cloud-host-pruning'
|
||||
import { ensureCloudReaderKey } from './cloud-read-snapshot'
|
||||
import {
|
||||
cloudHostRemover,
|
||||
forgetRevokedCloudSession,
|
||||
@@ -75,6 +76,8 @@ export function useCloudWorkspaces(enrollment: CloudEnrollment | null | undefine
|
||||
try {
|
||||
const startedAt = Date.now()
|
||||
const list = await listCloudWorkspaces(plane, signal)
|
||||
// Keeps this phone's reader key registered (at most every 6 h) so the next sleep seals to it.
|
||||
void ensureCloudReaderKey(plane).catch(() => undefined)
|
||||
if (list.complete) {
|
||||
// A linked workspace the list lacks is checked by id; one the registry says is gone
|
||||
// (destroyed, or no longer shared) stops being retried.
|
||||
|
||||
@@ -2,6 +2,7 @@ import { ChevronRight, Cloud, Plus, RotateCw } from 'lucide-react-native'
|
||||
import { Fragment, useState } from 'react'
|
||||
import { ActivityIndicator, Pressable, Text, View } from 'react-native'
|
||||
import { CloudStatusDot } from '../cloud/CloudStatusDot'
|
||||
import { formatReadSnapshotAsOf } from '../cloud/CloudReadSnapshotSection'
|
||||
import type { CloudWorkspace } from '../cloud/cloud-control-plane-client'
|
||||
import { CloudEnrollmentError, enrollCloudDevice } from '../cloud/cloud-device-enrollment'
|
||||
import type { CloudEnrollment } from '../cloud/cloud-device-identity'
|
||||
@@ -154,10 +155,17 @@ function CloudWorkspaceRow({
|
||||
ago: formatTimeAgo(workspace.createdAt, reference)
|
||||
})
|
||||
// "Created just now · just now" says one thing twice: the activity time adds nothing yet.
|
||||
// Asleep with a saved read-only copy: say how fresh that copy is; it opens without waking.
|
||||
const when =
|
||||
createdLine && lastActive - workspace.createdAt < 60_000
|
||||
? null
|
||||
: formatTimeAgo(lastActive, reference)
|
||||
workspace.status === 'sleeping' && workspace.readSnapshotAt
|
||||
? formatReadSnapshotAsOf(
|
||||
workspace.readSnapshotAt,
|
||||
Math.max(reference, workspace.readSnapshotAt),
|
||||
t
|
||||
)
|
||||
: createdLine && lastActive - workspace.createdAt < 60_000
|
||||
? null
|
||||
: formatTimeAgo(lastActive, reference)
|
||||
const line = [status, detail, when].filter(Boolean).join(' · ')
|
||||
return (
|
||||
<Pressable
|
||||
|
||||
@@ -141,11 +141,19 @@
|
||||
}
|
||||
},
|
||||
"cloud": {
|
||||
"snapshot": {
|
||||
"git": {
|
||||
"files_one": "{{count}} changed file",
|
||||
"files_other": "{{count}} changed files",
|
||||
"more_one": "and {{count}} more",
|
||||
"more_other": "and {{count}} more"
|
||||
}
|
||||
},
|
||||
"usage": {
|
||||
"asleep_one": "{{hours}} sandbox hour so far · no sandbox hours while asleep",
|
||||
"asleep_other": "{{hours}} sandbox hours so far · 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"
|
||||
"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."
|
||||
}
|
||||
},
|
||||
"components": {
|
||||
|
||||
@@ -5049,7 +5049,8 @@
|
||||
"openSession": "Open session",
|
||||
"settingUp": "Starting…",
|
||||
"open": "Open workspace",
|
||||
"wakeOpen": "Wake and open workspace"
|
||||
"wakeOpen": "Wake and open workspace",
|
||||
"wakeToContinue": "Wake to continue"
|
||||
},
|
||||
"phase": {
|
||||
"delivering": "Starting your agent",
|
||||
@@ -5148,11 +5149,57 @@
|
||||
"slowQueued": "Taking longer than usual. Your files are safe. Your prompt sends as soon as it’s awake.",
|
||||
"slow": "Taking longer than usual. Your files are safe."
|
||||
},
|
||||
"snapshot": {
|
||||
"heading": "Latest from this workspace",
|
||||
"loading": "Loading the latest from this workspace…",
|
||||
"empty": "Nothing saved yet. Orca saves a read-only copy each time this workspace goes to sleep.",
|
||||
"notSealedForKey": "This device was added after the workspace went to sleep. Wake it once to read it here.",
|
||||
"error": "Couldn’t load the latest from this workspace. Your files are safe.",
|
||||
"rollback": "Orca Cloud sent an older copy than the one you last saw, so it isn’t shown. Wake the workspace to see it as it is now.",
|
||||
"asOf": "As of {{ago}} ago",
|
||||
"asOfJustNow": "As of just now",
|
||||
"asOfExact": "As of {{time}}",
|
||||
"quiet": "No agents, changes or pull request when it went to sleep.",
|
||||
"agentFallback": "Agent",
|
||||
"sessionHint": "Shows the end of this chat",
|
||||
"truncated": "Earlier messages aren’t in this copy.",
|
||||
"noMessages": "No messages in this chat yet.",
|
||||
"status": {
|
||||
"working": "Working",
|
||||
"attention": "Needs you",
|
||||
"done": "Done",
|
||||
"idle": "Idle"
|
||||
},
|
||||
"role": {
|
||||
"you": "You",
|
||||
"system": "System"
|
||||
},
|
||||
"pr": {
|
||||
"title": "#{{number}} {{title}}",
|
||||
"hint": "Opens the pull request",
|
||||
"open": "Open",
|
||||
"merged": "Merged",
|
||||
"closed": "Closed",
|
||||
"draft": "Draft"
|
||||
},
|
||||
"checks": {
|
||||
"passing": "Checks passing",
|
||||
"failing": "Checks failing",
|
||||
"pending": "Checks running"
|
||||
},
|
||||
"git": {
|
||||
"files_one": "{{count}} changed file",
|
||||
"files_other": "{{count}} changed files",
|
||||
"clean": "No uncommitted changes",
|
||||
"more_one": "and {{count}} more",
|
||||
"more_other": "and {{count}} more"
|
||||
}
|
||||
},
|
||||
"usage": {
|
||||
"asleep_one": "{{hours}} sandbox hour so far · no sandbox hours while asleep",
|
||||
"asleep_other": "{{hours}} sandbox hours so far · 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"
|
||||
"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."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -246,6 +246,11 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [
|
||||
],
|
||||
load: async () => (await import('./handlers/cloud-env.js')).CLOUD_ENV_HANDLERS
|
||||
},
|
||||
{
|
||||
name: 'secret',
|
||||
keys: ['secret request'],
|
||||
load: async () => (await import('./handlers/secret.js')).SECRET_HANDLERS
|
||||
},
|
||||
{
|
||||
name: 'speech',
|
||||
keys: ['speech openai-key status', 'speech openai-key set', 'speech openai-key clear'],
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { RuntimeClientError } from '../runtime/types'
|
||||
import { parseSecretRequestWait, runSecretRequest, type SecretRequestCliInput } from './secret'
|
||||
|
||||
const HINT =
|
||||
'STRIPE_KEY is set for new shells in this workspace. To use it in this shell: eval "$(orca-env)" (fish: orca-env --fish | source).'
|
||||
|
||||
function harness(answers: { request: unknown; statuses?: string[] }) {
|
||||
const clock = { now: 0 }
|
||||
const calls: { method: string; params: unknown }[] = []
|
||||
const printed: string[] = []
|
||||
const statuses = [...(answers.statuses ?? [])]
|
||||
return {
|
||||
calls,
|
||||
printed,
|
||||
deps: {
|
||||
call: async <T>(method: string, params: unknown): Promise<T> => {
|
||||
calls.push({ method, params })
|
||||
if (method === 'secrets.request') {
|
||||
if (answers.request instanceof Error) {
|
||||
throw answers.request
|
||||
}
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: canned reply for this method.
|
||||
return answers.request as T
|
||||
}
|
||||
const status = statuses.shift() ?? 'pending'
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: canned requestStatus reply.
|
||||
return { requestId: 'sr_abcdefgh', name: 'STRIPE_KEY', status, expiresAt: 0 } as T
|
||||
},
|
||||
sleep: async (ms: number) => {
|
||||
clock.now += ms
|
||||
},
|
||||
now: () => clock.now,
|
||||
print: (line: string) => printed.push(line)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const base: SecretRequestCliInput = {
|
||||
name: 'STRIPE_KEY',
|
||||
reason: 'Run the checkout tests',
|
||||
waitSec: null,
|
||||
json: false,
|
||||
worktreeId: 'wt-1'
|
||||
}
|
||||
|
||||
describe('orca secret request', () => {
|
||||
it('names no terminal or agent: orcad derives them from verified launch evidence', async () => {
|
||||
const h = harness({ request: { requestId: 'sr_abcdefgh', status: 'pending' } })
|
||||
await runSecretRequest({ ...base, scope: 'repo' }, h.deps)
|
||||
expect(h.calls[0]).toEqual({
|
||||
method: 'secrets.request',
|
||||
params: {
|
||||
name: 'STRIPE_KEY',
|
||||
reason: 'Run the checkout tests',
|
||||
scope: 'repo',
|
||||
worktreeId: 'wt-1'
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
it('without --wait, reports the pending request and exits 0', async () => {
|
||||
const h = harness({ request: { requestId: 'sr_abcdefgh', status: 'pending' } })
|
||||
await expect(runSecretRequest(base, h.deps)).resolves.toBe(0)
|
||||
expect(h.printed).toEqual([
|
||||
'Asked the person for STRIPE_KEY (sr_abcdefgh). Add --wait <sec> to wait for the answer.'
|
||||
])
|
||||
})
|
||||
|
||||
it('with --wait, polls until provided and prints the D4 reload hint exactly', async () => {
|
||||
const h = harness({
|
||||
request: { requestId: 'sr_abcdefgh', status: 'pending' },
|
||||
statuses: ['pending', 'pending', 'provided']
|
||||
})
|
||||
await expect(runSecretRequest({ ...base, waitSec: 60 }, h.deps)).resolves.toBe(0)
|
||||
expect(h.printed).toEqual([HINT])
|
||||
expect(h.calls.filter((c) => c.method === 'secrets.requestStatus')).toHaveLength(3)
|
||||
})
|
||||
|
||||
it('prints JSON with the hint when provided', async () => {
|
||||
const h = harness({
|
||||
request: { requestId: 'sr_abcdefgh', status: 'pending' },
|
||||
statuses: ['provided']
|
||||
})
|
||||
await runSecretRequest({ ...base, waitSec: 60, json: true }, h.deps)
|
||||
expect(JSON.parse(h.printed[0])).toEqual({
|
||||
requestId: 'sr_abcdefgh',
|
||||
name: 'STRIPE_KEY',
|
||||
status: 'provided',
|
||||
hint: HINT
|
||||
})
|
||||
})
|
||||
|
||||
it('exits 1 when declined, expired, or the wait runs out', async () => {
|
||||
for (const [status, line] of [
|
||||
['declined', 'The person declined to provide STRIPE_KEY.'],
|
||||
['expired', 'The request for STRIPE_KEY expired before anyone answered it.']
|
||||
]) {
|
||||
const h = harness({
|
||||
request: { requestId: 'sr_abcdefgh', status: 'pending' },
|
||||
statuses: [status]
|
||||
})
|
||||
await expect(runSecretRequest({ ...base, waitSec: 60 }, h.deps)).resolves.toBe(1)
|
||||
expect(h.printed).toEqual([line])
|
||||
}
|
||||
const h = harness({ request: { requestId: 'sr_abcdefgh', status: 'pending' } })
|
||||
await expect(runSecretRequest({ ...base, waitSec: 5 }, h.deps)).resolves.toBe(1)
|
||||
expect(h.printed[0]).toBe(
|
||||
'Still waiting for STRIPE_KEY (sr_abcdefgh). Run the same command again to keep waiting.'
|
||||
)
|
||||
})
|
||||
|
||||
it('reports already-set without polling', async () => {
|
||||
const h = harness({ request: { requestId: null, status: 'already-set' } })
|
||||
await expect(runSecretRequest({ ...base, waitSec: 60 }, h.deps)).resolves.toBe(0)
|
||||
expect(h.calls).toHaveLength(1)
|
||||
expect(h.printed[0]).toContain('STRIPE_KEY is already set in this workspace.')
|
||||
})
|
||||
|
||||
it('explains refusals in words', async () => {
|
||||
const h = harness({
|
||||
request: new RuntimeClientError('runtime_error', 'use_sign_in_or_cloud_secrets')
|
||||
})
|
||||
await expect(runSecretRequest({ ...base, name: 'ANTHROPIC_API_KEY' }, h.deps)).rejects.toThrow(
|
||||
"ANTHROPIC_API_KEY is an agent credential: it comes from the person's sign-in or Orca Cloud secrets and can't be requested."
|
||||
)
|
||||
})
|
||||
|
||||
it('parses --wait', () => {
|
||||
expect(parseSecretRequestWait(undefined)).toBeNull()
|
||||
expect(parseSecretRequestWait(true)).toBe(900)
|
||||
expect(parseSecretRequestWait('30')).toBe(30)
|
||||
expect(parseSecretRequestWait('99999')).toBe(3600)
|
||||
expect(() => parseSecretRequestWait('soon')).toThrow('--wait takes a number of seconds')
|
||||
expect(() => parseSecretRequestWait('0')).toThrow()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,200 @@
|
||||
import type { CommandHandler } from '../dispatch'
|
||||
import { getOptionalStringFlag, getRequiredStringFlag } from '../flags'
|
||||
import { RuntimeClientError } from '../runtime/types'
|
||||
import {
|
||||
SECRET_REQUEST_ERRORS,
|
||||
SECRET_REQUEST_REASON_MAX,
|
||||
SECRETS_REQUEST_METHOD,
|
||||
SECRETS_REQUEST_STATUS_METHOD,
|
||||
secretReloadHint,
|
||||
type SecretRequestScope,
|
||||
type SecretRequestStatus,
|
||||
type SecretsRequestParams,
|
||||
type SecretsRequestResult,
|
||||
type SecretsRequestStatusResult
|
||||
} from '../../shared/secret-request-contract'
|
||||
|
||||
const DEFAULT_WAIT_SEC = 900
|
||||
const MAX_WAIT_SEC = 3600
|
||||
const POLL_MS = 2000
|
||||
|
||||
export type SecretRequestOutcome = SecretRequestStatus | 'already-set'
|
||||
|
||||
export type SecretRequestCliDeps = {
|
||||
call: <T>(method: string, params: unknown) => Promise<T>
|
||||
sleep: (ms: number) => Promise<void>
|
||||
now: () => number
|
||||
print: (line: string) => void
|
||||
}
|
||||
|
||||
export type SecretRequestCliInput = {
|
||||
name: string
|
||||
reason: string
|
||||
scope?: SecretRequestScope
|
||||
waitSec: number | null
|
||||
json: boolean
|
||||
worktreeId?: string
|
||||
}
|
||||
|
||||
/** Returns the exit code. */
|
||||
export async function runSecretRequest(
|
||||
input: SecretRequestCliInput,
|
||||
deps: SecretRequestCliDeps
|
||||
): Promise<number> {
|
||||
const params: SecretsRequestParams = {
|
||||
name: input.name,
|
||||
reason: input.reason,
|
||||
...(input.scope ? { scope: input.scope } : {}),
|
||||
// The calling terminal (and so the agent) travels as launch evidence that orcad verifies.
|
||||
...(input.worktreeId ? { worktreeId: input.worktreeId } : {})
|
||||
}
|
||||
let created: SecretsRequestResult
|
||||
try {
|
||||
created = await deps.call<SecretsRequestResult>(SECRETS_REQUEST_METHOD, params)
|
||||
} catch (error) {
|
||||
throw explainRequestError(error, input.name)
|
||||
}
|
||||
if (created.status === 'already-set') {
|
||||
return finish(input, deps, { requestId: null, status: 'already-set' })
|
||||
}
|
||||
const requestId = created.requestId
|
||||
if (input.waitSec === null) {
|
||||
return finish(input, deps, { requestId, status: 'pending' })
|
||||
}
|
||||
const deadline = deps.now() + input.waitSec * 1000
|
||||
for (;;) {
|
||||
const current = await deps.call<SecretsRequestStatusResult>(SECRETS_REQUEST_STATUS_METHOD, {
|
||||
requestId
|
||||
})
|
||||
if (current.status !== 'pending' || deps.now() >= deadline) {
|
||||
return finish(input, deps, { requestId, status: current.status, waited: true })
|
||||
}
|
||||
await deps.sleep(Math.min(POLL_MS, Math.max(0, deadline - deps.now())))
|
||||
}
|
||||
}
|
||||
|
||||
function finish(
|
||||
input: SecretRequestCliInput,
|
||||
deps: SecretRequestCliDeps,
|
||||
result: { requestId: string | null; status: SecretRequestOutcome; waited?: boolean }
|
||||
): number {
|
||||
const answered = result.status === 'provided' || result.status === 'already-set'
|
||||
const exitCode = answered || (result.status === 'pending' && !result.waited) ? 0 : 1
|
||||
if (input.json) {
|
||||
deps.print(
|
||||
JSON.stringify(
|
||||
{
|
||||
requestId: result.requestId,
|
||||
name: input.name,
|
||||
status: result.status,
|
||||
...(result.status === 'provided' || result.status === 'already-set'
|
||||
? { hint: secretReloadHint(input.name) }
|
||||
: {})
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
)
|
||||
return exitCode
|
||||
}
|
||||
deps.print(formatSecretRequestOutcome(input.name, result.requestId, result.status, result.waited))
|
||||
return exitCode
|
||||
}
|
||||
|
||||
export function formatSecretRequestOutcome(
|
||||
name: string,
|
||||
requestId: string | null,
|
||||
status: SecretRequestOutcome,
|
||||
waited = false
|
||||
): string {
|
||||
switch (status) {
|
||||
case 'provided':
|
||||
return secretReloadHint(name)
|
||||
case 'already-set':
|
||||
return `${name} is already set in this workspace. If this shell doesn't have it yet: eval "$(orca-env)" (fish: orca-env --fish | source).`
|
||||
case 'declined':
|
||||
return `The person declined to provide ${name}.`
|
||||
case 'expired':
|
||||
return `The request for ${name} expired before anyone answered it.`
|
||||
case 'pending':
|
||||
return waited
|
||||
? `Still waiting for ${name} (${requestId}). Run the same command again to keep waiting.`
|
||||
: `Asked the person for ${name} (${requestId}). Add --wait <sec> to wait for the answer.`
|
||||
}
|
||||
}
|
||||
|
||||
const ERROR_MESSAGES: Record<string, (name: string) => string> = {
|
||||
[SECRET_REQUEST_ERRORS.invalidName]: (name) =>
|
||||
`${name} is not a valid secret name: use A-Z, 0-9 and _, not starting with a digit.`,
|
||||
[SECRET_REQUEST_ERRORS.reservedName]: (name) =>
|
||||
`${name} is reserved: Orca or the system manages it, so it can't be a secret.`,
|
||||
[SECRET_REQUEST_ERRORS.subscriptionTokenRefused]: () =>
|
||||
'CLAUDE_CODE_OAUTH_TOKEN is never stored. Ask the person to sign Claude in instead.',
|
||||
[SECRET_REQUEST_ERRORS.agentCredential]: (name) =>
|
||||
`${name} is an agent credential: it comes from the person's sign-in or Orca Cloud secrets and can't be requested.`,
|
||||
[SECRET_REQUEST_ERRORS.tooManyPending]: () =>
|
||||
'This workspace already has 3 secret requests waiting. Wait for one to be answered.',
|
||||
[SECRET_REQUEST_ERRORS.rateLimited]: () =>
|
||||
'This workspace asked for 10 secrets in the last hour. Try again later.',
|
||||
[SECRET_REQUEST_ERRORS.unavailable]: () =>
|
||||
'Secret requests work only inside an Orca Cloud workspace.'
|
||||
}
|
||||
|
||||
function explainRequestError(error: unknown, name: string): unknown {
|
||||
if (!(error instanceof RuntimeClientError)) {
|
||||
return error
|
||||
}
|
||||
const explain = ERROR_MESSAGES[error.message]
|
||||
return explain ? new RuntimeClientError(error.message, explain(name)) : error
|
||||
}
|
||||
|
||||
export function parseSecretRequestWait(value: string | boolean | undefined): number | null {
|
||||
if (value === undefined) {
|
||||
return null
|
||||
}
|
||||
if (value === true) {
|
||||
return DEFAULT_WAIT_SEC
|
||||
}
|
||||
const seconds = Number(value)
|
||||
if (typeof value !== 'string' || !/^\d+$/.test(value) || seconds < 1) {
|
||||
throw new RuntimeClientError('invalid_argument', '--wait takes a number of seconds')
|
||||
}
|
||||
return Math.min(seconds, MAX_WAIT_SEC)
|
||||
}
|
||||
|
||||
function parseScope(value: string | undefined): SecretRequestScope | undefined {
|
||||
if (value === undefined || value === 'personal' || value === 'repo') {
|
||||
return value
|
||||
}
|
||||
throw new RuntimeClientError('invalid_argument', '--scope is personal or repo')
|
||||
}
|
||||
|
||||
export const SECRET_HANDLERS: Record<string, CommandHandler> = {
|
||||
'secret request': async ({ flags, client, json }) => {
|
||||
const name = getRequiredStringFlag(flags, 'name')
|
||||
const reason = getRequiredStringFlag(flags, 'reason').trim()
|
||||
if (reason.length === 0 || reason.length > SECRET_REQUEST_REASON_MAX) {
|
||||
throw new RuntimeClientError(
|
||||
'invalid_argument',
|
||||
`--reason must be 1-${SECRET_REQUEST_REASON_MAX} characters`
|
||||
)
|
||||
}
|
||||
process.exitCode = await runSecretRequest(
|
||||
{
|
||||
name,
|
||||
reason,
|
||||
scope: parseScope(getOptionalStringFlag(flags, 'scope')),
|
||||
waitSec: parseSecretRequestWait(flags.get('wait')),
|
||||
json,
|
||||
worktreeId: process.env.ORCA_WORKTREE_ID || undefined
|
||||
},
|
||||
{
|
||||
call: async <T>(method: string, params: unknown) =>
|
||||
(await client.call<T>(method, params)).result,
|
||||
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
||||
now: Date.now,
|
||||
print: (line) => console.log(line)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -93,6 +93,7 @@ export const ROOT_HELP_TEXT_PRIMARY = [
|
||||
' cloud messages List or show messages sent to a cloud workspace',
|
||||
' cloud sessions List agent sessions in a cloud workspace',
|
||||
' cloud projects list List Orca Cloud projects',
|
||||
' secret request Ask the person for a secret this workspace needs',
|
||||
'',
|
||||
'Automations:',
|
||||
' automations list List scheduled Orca automations',
|
||||
|
||||
@@ -28,6 +28,8 @@ export function createAgentLaunchCallerEvidence(
|
||||
}
|
||||
|
||||
const AGENT_LAUNCH_METHODS: ReadonlySet<string> = new Set(['agent.launch', 'agent.launchReplay'])
|
||||
/** Methods where orcad names the calling terminal (and its agent) from the shell's launch evidence. */
|
||||
const TERMINAL_CALLER_METHODS: ReadonlySet<string> = new Set(['secrets.request'])
|
||||
|
||||
/** The caller evidence one request carries, read from this process's environment once. */
|
||||
export class OrchestrationRequestEvidence {
|
||||
@@ -58,6 +60,11 @@ export class OrchestrationRequestEvidence {
|
||||
compatibilityInvocationId: request.requestId ?? base.compatibilityInvocationId
|
||||
}
|
||||
}
|
||||
if (TERMINAL_CALLER_METHODS.has(method)) {
|
||||
// Terminal evidence only: it identifies a caller on this host, never on a remote server.
|
||||
const shell = this.remoteRead.orchestrationCompatibilityEvidence
|
||||
return request.remote || !shell ? {} : { orchestrationCompatibilityEvidence: shell }
|
||||
}
|
||||
return AGENT_LAUNCH_METHODS.has(method) && !request.remote && this.agentLaunchCaller
|
||||
? { orchestrationCompatibilityEvidence: this.agentLaunchCaller }
|
||||
: {}
|
||||
|
||||
@@ -26,3 +26,40 @@ describe('caller evidence on requests to another server', () => {
|
||||
).toEqual({ agentSessionId: '11111111-1111-4111-8111-111111111111' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('terminal evidence on secret requests', () => {
|
||||
const SHELL = {
|
||||
...CHAT,
|
||||
ORCA_TERMINAL_HANDLE: 'term_1',
|
||||
ORCA_PANE_KEY: 'tab:leaf',
|
||||
ORCA_AGENT_LAUNCH_TOKEN: 'tok'
|
||||
}
|
||||
|
||||
it('sends the shell evidence (never the chat id) to this host so orcad can verify the caller', () => {
|
||||
const evidence = new OrchestrationRequestEvidence(SHELL)
|
||||
expect(
|
||||
evidence.envelopeFor('secrets.request', {
|
||||
remote: false,
|
||||
mutation: false,
|
||||
requestId: undefined
|
||||
})
|
||||
).toEqual({
|
||||
orchestrationCompatibilityEvidence: {
|
||||
terminalHandle: 'term_1',
|
||||
paneKey: 'tab:leaf',
|
||||
launchToken: 'tok'
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
it('sends nothing to another server', () => {
|
||||
const evidence = new OrchestrationRequestEvidence(SHELL)
|
||||
expect(
|
||||
evidence.envelopeFor('secrets.request', {
|
||||
remote: true,
|
||||
mutation: false,
|
||||
requestId: undefined
|
||||
})
|
||||
).toEqual({})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -26,6 +26,7 @@ import { VM_COMMAND_SPECS } from './vm'
|
||||
import { VM_ENV_COMMAND_SPECS } from './vm-env'
|
||||
import { CLOUD_ENV_COMMAND_SPECS } from './cloud-env'
|
||||
import { CLOUD_SSH_COMMAND_SPECS } from './cloud-ssh'
|
||||
import { SECRET_COMMAND_SPECS } from './secret'
|
||||
import { SKILL_COMMAND_SPECS } from './skills'
|
||||
import { ARTIFACT_COMMAND_SPECS } from './artifacts'
|
||||
import { SEARCH_COMMAND_SPECS } from './search'
|
||||
@@ -66,6 +67,7 @@ export const COMMAND_SPECS: CommandSpec[] = [
|
||||
...VM_ENV_COMMAND_SPECS,
|
||||
...CLOUD_ENV_COMMAND_SPECS,
|
||||
...CLOUD_SSH_COMMAND_SPECS,
|
||||
...SECRET_COMMAND_SPECS,
|
||||
...EMULATOR_COMMAND_SPECS,
|
||||
...SKILL_COMMAND_SPECS,
|
||||
...SEARCH_COMMAND_SPECS,
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { CommandSpec } from '../args'
|
||||
import { LOCAL_COMMAND_FLAGS } from '../args'
|
||||
|
||||
export const SECRET_COMMAND_SPECS: CommandSpec[] = [
|
||||
{
|
||||
path: ['secret', 'request'],
|
||||
summary: 'Ask the person to provide a secret for this workspace',
|
||||
usage:
|
||||
'orca secret request <NAME> --reason "<why>" [--scope personal|repo] [--wait <sec>] [--json]',
|
||||
allowedFlags: [...LOCAL_COMMAND_FLAGS, 'name', 'reason', 'scope', 'wait'],
|
||||
positionalArgs: ['name'],
|
||||
notes: [
|
||||
'Orca shows the person a card with NAME and your reason; they type the value. The value never passes through you or this command.',
|
||||
'Once provided, NAME is set for new shells in this workspace. In the current shell run eval "$(orca-env)" (fish: orca-env --fish | source).',
|
||||
'--reason (at most 200 characters) is shown to the person as your words. Say what the secret unblocks.',
|
||||
'--scope is a hint: the person chooses where it is saved.',
|
||||
'--wait <sec> waits for an answer (default without a number: 900). Running the same request again while it is pending waits on it rather than asking twice.',
|
||||
"Agent keys (ANTHROPIC_*, OPENAI_* and similar) cannot be requested: they come from the person's sign-in or Orca Cloud secrets.",
|
||||
'Exits 1 when the request is declined, expires, or --wait ends without an answer.'
|
||||
],
|
||||
examples: [
|
||||
'orca secret request STRIPE_TEST_KEY --reason "Run the checkout integration tests" --wait 600',
|
||||
'orca secret request SENTRY_DSN --reason "Upload source maps in the release script" --json'
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -132,8 +132,8 @@ describe('billing client', () => {
|
||||
const offers = {
|
||||
team: {
|
||||
label: 'Team',
|
||||
monthlyPriceLabel: '$50/seat/mo',
|
||||
annualPriceLabel: '$480/seat/yr',
|
||||
monthlyPriceLabel: '$50 per seat per month',
|
||||
annualPriceLabel: '$480 per seat, billed yearly',
|
||||
includedHoursPerSeat: 60,
|
||||
concurrentSandboxesPerSeat: 3,
|
||||
idleSleepMinutes: 15,
|
||||
|
||||
@@ -111,7 +111,8 @@ const OffersSchema = z
|
||||
concurrentSandboxesPerSeat: z.number().int().nonnegative(),
|
||||
idleSleepMinutes: z.number().int().positive(),
|
||||
overageCentsPerHour: z.number().int().positive(),
|
||||
defaultSpendCapCents: z.number().int().nonnegative()
|
||||
defaultSpendCapCents: z.number().int().nonnegative(),
|
||||
maxSpendCapCents: z.number().int().positive().nullable().catch(null)
|
||||
}),
|
||||
enterprise: z.object({
|
||||
label: z.string().max(40),
|
||||
|
||||
@@ -14,6 +14,16 @@ import { withCloudBuildDefaults } from '../cloud-build-defaults'
|
||||
import { getHostedSandboxConfig } from '../hosted-sandbox/hosted-sandbox-config'
|
||||
import { HOSTED_SANDBOX_DRIVER_ID } from '../hosted-sandbox/hosted-sandbox-driver'
|
||||
import { getOrcaCloudAvailability } from '../hosted-sandbox/hosted-sandbox-install'
|
||||
import { isTuiAgent } from '../../shared/agent-launch/catalog/tui-agent-config'
|
||||
import {
|
||||
cloudSecretNameError,
|
||||
cloudSecretSwapped,
|
||||
cloudSecretValueError
|
||||
} from '../../shared/cloud-secrets/cloud-secret-rules'
|
||||
import {
|
||||
desktopKeyValueForCloud,
|
||||
setCloudDesktopKeysUserDataPath
|
||||
} from '../hosted-sandbox/cloud-desktop-keys'
|
||||
import {
|
||||
cloudSecretsFailureCode,
|
||||
createCloudSecretsClient,
|
||||
@@ -45,6 +55,10 @@ const BatchRequest = z
|
||||
)
|
||||
const EffectiveRequest = z.object({ repo: Repo.optional() })
|
||||
const RefreshRequest = z.object({ runtimeEnvironmentId: z.string().min(1).max(256) })
|
||||
const SaveDesktopKeyRequest = z.object({
|
||||
agent: z.string().refine(isTuiAgent),
|
||||
envName: Name
|
||||
})
|
||||
|
||||
const CHANNELS = [
|
||||
'cloudSecrets:status',
|
||||
@@ -53,7 +67,8 @@ const CHANNELS = [
|
||||
'cloudSecrets:remove',
|
||||
'cloudSecrets:batch',
|
||||
'cloudSecrets:effective',
|
||||
'cloudSecrets:refreshEnv'
|
||||
'cloudSecrets:refreshEnv',
|
||||
'cloudSecrets:saveDesktopKey'
|
||||
] as const
|
||||
|
||||
async function attempt<T>(
|
||||
@@ -85,6 +100,7 @@ function sandboxIdFor(userDataPath: string, runtimeEnvironmentId: string): strin
|
||||
}
|
||||
|
||||
export function registerCloudSecretsHandlers(userDataPath: string): void {
|
||||
setCloudDesktopKeysUserDataPath(userDataPath)
|
||||
// Packaged integration builds read no shell env; their control-plane URL is baked in.
|
||||
const config = getHostedSandboxConfig(
|
||||
userDataPath,
|
||||
@@ -137,6 +153,32 @@ export function registerCloudSecretsHandlers(userDataPath: string): void {
|
||||
const request = EffectiveRequest.safeParse(raw ?? {})
|
||||
return request.success ? attempt(client, (c) => c.effective(request.data.repo)) : 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.
|
||||
ipcMain.handle('cloudSecrets:saveDesktopKey', async (_event, raw: unknown) => {
|
||||
const request = SaveDesktopKeyRequest.safeParse(raw)
|
||||
if (!request.success || !isTuiAgent(request.data.agent)) {
|
||||
return invalid
|
||||
}
|
||||
const { agent, envName } = request.data
|
||||
const nameError = cloudSecretNameError(envName)
|
||||
if (nameError) {
|
||||
return { ok: false, error: nameError }
|
||||
}
|
||||
// Only keys the workspace gets as a stand-in: anything else would sit there in full.
|
||||
if (!cloudSecretSwapped(envName)) {
|
||||
return { ok: false, error: 'not_swappable' }
|
||||
}
|
||||
const value = await desktopKeyValueForCloud(agent, envName)
|
||||
if (!value) {
|
||||
return { ok: false, error: 'not_found' }
|
||||
}
|
||||
const valueError = cloudSecretValueError(envName, value)
|
||||
if (valueError) {
|
||||
return { ok: false, error: valueError }
|
||||
}
|
||||
return attempt(client, (c) => c.put({ scope: 'personal' }, envName, value))
|
||||
})
|
||||
ipcMain.handle('cloudSecrets:refreshEnv', (_event, raw: unknown) => {
|
||||
const request = RefreshRequest.safeParse(raw)
|
||||
if (!request.success) {
|
||||
|
||||
@@ -0,0 +1,282 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { CloudWorkspacesError, type ReadSnapshotFetch } from './cloud-workspaces-client'
|
||||
import {
|
||||
createReadSnapshotReader,
|
||||
READER_KEY_REFRESH_MS,
|
||||
type ReaderKeyAccess
|
||||
} from './cloud-read-snapshot-reader'
|
||||
import { generateGrantRecipientKey } from './sealed-grant-node'
|
||||
import { sealReadSnapshotForTest } from './read-snapshot-sealer.test-fixture'
|
||||
|
||||
const SBX = 'sbx_0123456789abcdef01234567'
|
||||
const KEY_A = 'rk_aaaaaaaaaaaaaaaaaaaaaaaa'
|
||||
const KEY_B = 'rk_bbbbbbbbbbbbbbbbbbbbbbbb'
|
||||
|
||||
const payload = {
|
||||
v: 1,
|
||||
workspaceId: SBX,
|
||||
snapshotId: 'snap_1',
|
||||
capturedAt: 1_700_000_000_000,
|
||||
reason: 'sleep',
|
||||
git: {
|
||||
branch: 'main',
|
||||
head: 'abc1234',
|
||||
changes: [{ path: 'src/a.ts', status: 'modified', area: 'unstaged', added: 3, removed: 1 }],
|
||||
changeCount: 1,
|
||||
added: 3,
|
||||
removed: 1,
|
||||
commits: [{ id: 'abc1234', subject: 'Fix', author: 'Ada', at: 1 }]
|
||||
},
|
||||
pr: {
|
||||
number: 42,
|
||||
title: 'Fix it',
|
||||
state: 'open',
|
||||
url: 'https://github.com/acme/web/pull/42',
|
||||
checksStatus: 'success',
|
||||
checksSummary: '3/3 passed'
|
||||
},
|
||||
sessions: [
|
||||
{
|
||||
sessionId: 's1',
|
||||
agent: 'claude',
|
||||
title: 'Fix the bug',
|
||||
status: 'idle',
|
||||
turnOutcome: 'done',
|
||||
updatedAt: 2,
|
||||
messages: [{ itemId: 'm1', role: 'assistant', text: 'Done.', at: 2 }],
|
||||
truncated: false
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
function setup(options: { identity?: string | null; keychain?: boolean } = {}) {
|
||||
const key = generateGrantRecipientKey()
|
||||
let identity: string | null = options.identity === undefined ? 'me' : options.identity
|
||||
const readerKey: ReaderKeyAccess = {
|
||||
identity: () => identity,
|
||||
load: async () =>
|
||||
options.keychain === false
|
||||
? { ok: false, reason: 'keychain_unavailable', message: 'no keychain' }
|
||||
: { ok: true, key },
|
||||
peek: async () => (options.keychain === false ? null : key)
|
||||
}
|
||||
let now = 10_000
|
||||
const ids = [KEY_A]
|
||||
const registerReaderKey = vi.fn(async () => ({
|
||||
id: ids[0]!,
|
||||
deviceKind: 'desktop' as const,
|
||||
deviceLabel: 'test',
|
||||
createdAt: 1,
|
||||
lastSeenAt: 1
|
||||
}))
|
||||
let capturedAt = payload.capturedAt
|
||||
const getReadSnapshot = vi.fn(async (_id: string, keyId: string): Promise<ReadSnapshotFetch> => ({
|
||||
kind: 'sealed',
|
||||
sealed: sealReadSnapshotForTest({
|
||||
payload: { ...payload, capturedAt },
|
||||
workspaceId: SBX,
|
||||
snapshotId: 'snap_1',
|
||||
readerPublicKeyB64: key.publicKeyB64,
|
||||
keyId,
|
||||
storedAt: 5
|
||||
})
|
||||
}))
|
||||
const deleteReaderKey = vi.fn(async (_keyId: string, _timeoutMs?: number) => {})
|
||||
const reader = createReadSnapshotReader({
|
||||
client: { registerReaderKey, getReadSnapshot, deleteReaderKey },
|
||||
readerKey,
|
||||
deviceLabel: () => 'test-mac',
|
||||
now: () => now
|
||||
})
|
||||
return {
|
||||
reader,
|
||||
key,
|
||||
ids,
|
||||
registerReaderKey,
|
||||
getReadSnapshot,
|
||||
deleteReaderKey,
|
||||
setCapturedAt: (at: number) => {
|
||||
capturedAt = at
|
||||
},
|
||||
tick: (ms: number) => {
|
||||
now += ms
|
||||
},
|
||||
setIdentity: (next: string | null) => {
|
||||
identity = next
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
describe('createReadSnapshotReader', () => {
|
||||
it('registers the key, then opens a snapshot sealed to it (independent sealer roundtrip)', async () => {
|
||||
const t = setup()
|
||||
const result = await t.reader.read(SBX)
|
||||
expect(t.registerReaderKey).toHaveBeenCalledWith({
|
||||
publicKeyB64: t.key.publicKeyB64,
|
||||
deviceLabel: 'test-mac',
|
||||
deviceKind: 'desktop'
|
||||
})
|
||||
expect(t.getReadSnapshot).toHaveBeenCalledWith(SBX, KEY_A)
|
||||
expect(result.state).toBe('ready')
|
||||
if (result.state !== 'ready') {
|
||||
return
|
||||
}
|
||||
expect(result.storedAt).toBe(5)
|
||||
expect(result.snapshot.capturedAt).toBe(payload.capturedAt)
|
||||
expect(result.snapshot.pr?.number).toBe(42)
|
||||
expect(result.snapshot.git?.changes[0]).toMatchObject({ path: 'src/a.ts', added: 3 })
|
||||
expect(result.snapshot.sessions[0]).toMatchObject({ agent: 'claude', status: 'idle' })
|
||||
})
|
||||
|
||||
it('reuses the registration for 6 h, then refreshes it', async () => {
|
||||
const t = setup()
|
||||
await t.reader.register()
|
||||
await t.reader.read(SBX)
|
||||
expect(t.registerReaderKey).toHaveBeenCalledTimes(1)
|
||||
t.tick(READER_KEY_REFRESH_MS)
|
||||
await t.reader.read(SBX)
|
||||
expect(t.registerReaderKey).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('shares one registration between concurrent callers', async () => {
|
||||
const t = setup()
|
||||
await Promise.all([t.reader.register(), t.reader.read(SBX), t.reader.read(SBX)])
|
||||
expect(t.registerReaderKey).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('registers again after an account switch', async () => {
|
||||
const t = setup()
|
||||
await t.reader.read(SBX)
|
||||
t.setIdentity('someone-else')
|
||||
await t.reader.read(SBX)
|
||||
expect(t.registerReaderKey).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it.each(['no_snapshot', 'not_found'] as const)('reports %s as a state', async (kind) => {
|
||||
const t = setup()
|
||||
t.getReadSnapshot.mockResolvedValueOnce({ kind })
|
||||
expect(await t.reader.read(SBX)).toEqual({ state: kind })
|
||||
})
|
||||
|
||||
it('reports not_sealed_for_key when the snapshot predates a freshly registered key', async () => {
|
||||
const t = setup()
|
||||
t.getReadSnapshot.mockResolvedValueOnce({ kind: 'not_sealed_for_key' })
|
||||
expect(await t.reader.read(SBX)).toEqual({ state: 'not_sealed_for_key' })
|
||||
expect(t.registerReaderKey).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('never re-registers on not_sealed_for_key (the snapshot just predates the key)', async () => {
|
||||
const t = setup()
|
||||
await t.reader.register()
|
||||
t.ids[0] = KEY_B
|
||||
t.getReadSnapshot.mockResolvedValueOnce({ kind: 'not_sealed_for_key' })
|
||||
expect(await t.reader.read(SBX)).toEqual({ state: 'not_sealed_for_key' })
|
||||
expect(t.registerReaderKey).toHaveBeenCalledTimes(1)
|
||||
expect(t.getReadSnapshot).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('re-registers at most once on invalid_request', async () => {
|
||||
const t = setup()
|
||||
await t.reader.register()
|
||||
t.getReadSnapshot
|
||||
.mockRejectedValueOnce(new CloudWorkspacesError(400, 'invalid_request'))
|
||||
.mockRejectedValueOnce(new CloudWorkspacesError(400, 'invalid_request'))
|
||||
await expect(t.reader.read(SBX)).rejects.toMatchObject({ code: 'invalid_request' })
|
||||
expect(t.registerReaderKey).toHaveBeenCalledTimes(2)
|
||||
expect(t.getReadSnapshot).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('refuses a snapshot older than one already shown (rollback pin), per workspace and account', async () => {
|
||||
const t = setup()
|
||||
t.setCapturedAt(2_000)
|
||||
expect((await t.reader.read(SBX)).state).toBe('ready')
|
||||
// The same snapshot again is fine; a newer one moves the pin.
|
||||
expect((await t.reader.read(SBX)).state).toBe('ready')
|
||||
t.setCapturedAt(3_000)
|
||||
expect((await t.reader.read(SBX)).state).toBe('ready')
|
||||
t.setCapturedAt(2_500)
|
||||
expect(await t.reader.read(SBX)).toEqual({ state: 'stale' })
|
||||
// Another account on this computer has its own pin.
|
||||
t.setIdentity('someone-else')
|
||||
expect((await t.reader.read(SBX)).state).toBe('ready')
|
||||
})
|
||||
|
||||
it('revokes the registered key server-side on sign-out', async () => {
|
||||
const t = setup()
|
||||
await t.reader.register()
|
||||
await t.reader.revoke(1_000)
|
||||
expect(t.deleteReaderKey).toHaveBeenCalledWith(KEY_A, 1_000)
|
||||
expect(t.registerReaderKey).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('learns the key id before revoking when this run never registered', async () => {
|
||||
const t = setup()
|
||||
await t.reader.revoke(1_000)
|
||||
expect(t.registerReaderKey).toHaveBeenCalledTimes(1)
|
||||
expect(t.deleteReaderKey).toHaveBeenCalledWith(KEY_A, 1_000)
|
||||
})
|
||||
|
||||
it('revokes nothing without a key or when signed out', async () => {
|
||||
await setup({ keychain: false }).reader.revoke(1_000)
|
||||
const signedOut = setup({ identity: null })
|
||||
await signedOut.reader.revoke(1_000)
|
||||
expect(signedOut.deleteReaderKey).not.toHaveBeenCalled()
|
||||
expect(signedOut.registerReaderKey).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('re-registers on invalid_request for a remembered key id', async () => {
|
||||
const t = setup()
|
||||
await t.reader.register()
|
||||
t.ids[0] = KEY_B
|
||||
t.getReadSnapshot.mockRejectedValueOnce(new CloudWorkspacesError(400, 'invalid_request'))
|
||||
expect((await t.reader.read(SBX)).state).toBe('ready')
|
||||
expect(t.getReadSnapshot).toHaveBeenLastCalledWith(SBX, KEY_B)
|
||||
})
|
||||
|
||||
it('is off with a clear reason without an OS keychain', async () => {
|
||||
const t = setup({ keychain: false })
|
||||
expect(await t.reader.read(SBX)).toEqual({
|
||||
state: 'unavailable',
|
||||
reason: 'keychain_unavailable',
|
||||
message: 'no keychain'
|
||||
})
|
||||
expect(t.registerReaderKey).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refuses when signed out', async () => {
|
||||
const t = setup({ identity: null })
|
||||
await expect(t.reader.read(SBX)).rejects.toMatchObject({ code: 'unauthorized' })
|
||||
})
|
||||
|
||||
it('turns a snapshot sealed to another key into snapshot_unreadable', async () => {
|
||||
const t = setup()
|
||||
const other = generateGrantRecipientKey()
|
||||
t.getReadSnapshot.mockResolvedValueOnce({
|
||||
kind: 'sealed',
|
||||
sealed: sealReadSnapshotForTest({
|
||||
payload,
|
||||
workspaceId: SBX,
|
||||
snapshotId: 'snap_1',
|
||||
readerPublicKeyB64: other.publicKeyB64,
|
||||
keyId: KEY_A
|
||||
})
|
||||
})
|
||||
await expect(t.reader.read(SBX)).rejects.toMatchObject({
|
||||
code: 'snapshot_unreadable',
|
||||
reason: 'decrypt_failed'
|
||||
})
|
||||
})
|
||||
|
||||
it('refuses a snapshot of another workspace', async () => {
|
||||
const t = setup()
|
||||
const sealed = sealReadSnapshotForTest({
|
||||
payload: { ...payload, workspaceId: 'sbx_ffffffffffffffffffffffff' },
|
||||
workspaceId: 'sbx_ffffffffffffffffffffffff',
|
||||
snapshotId: 'snap_1',
|
||||
readerPublicKeyB64: t.key.publicKeyB64,
|
||||
keyId: KEY_A
|
||||
})
|
||||
t.getReadSnapshot.mockResolvedValueOnce({ kind: 'sealed', sealed })
|
||||
await expect(t.reader.read(SBX)).rejects.toMatchObject({ reason: 'wrong_workspace' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,194 @@
|
||||
// Reads a sleeping Orca Cloud workspace from the sealed snapshot it left on the control plane,
|
||||
// without waking the VM. This device's reader key is registered with the control plane (on start,
|
||||
// after a sign-in or account switch, and at most every 6 h after); the VM seals each snapshot to
|
||||
// the reader keys registered when it went to sleep.
|
||||
import { hostname } from 'node:os'
|
||||
import { openReadSnapshot, ReadSnapshotError } from '../../shared/cloud-workspaces/read-snapshot'
|
||||
import type { CloudReadSnapshotState } from '../../shared/cloud-workspaces/read-snapshot-state'
|
||||
import { CloudWorkspacesError, type CloudWorkspacesClient } from './cloud-workspaces-client'
|
||||
import type { CloudReaderKey, ReaderKeyLoad } from './cloud-reader-key-store'
|
||||
import { nodeSealedGrantPrimitives } from './sealed-grant-node'
|
||||
|
||||
export const READER_KEY_REFRESH_MS = 6 * 60 * 60_000
|
||||
|
||||
export type ReaderKeyAccess = {
|
||||
/** Who is asking (profile, user, account); null when signed out. Registrations are per identity. */
|
||||
identity: () => string | null
|
||||
/** This profile's key (created on first use), or why there can be none. */
|
||||
load: () => Promise<ReaderKeyLoad>
|
||||
/** The key only if one already exists (sign-out must not create one just to delete it). */
|
||||
peek?: () => Promise<CloudReaderKey | null>
|
||||
}
|
||||
|
||||
type Registration = { identity: string; publicKeyB64: string; keyId: string; at: number }
|
||||
type Ready = { key: CloudReaderKey; keyId: string; fresh: boolean; identity: string }
|
||||
type Unavailable = { unavailable: Extract<ReaderKeyLoad, { ok: false }> }
|
||||
|
||||
export function createReadSnapshotReader(deps: {
|
||||
client: Pick<CloudWorkspacesClient, 'registerReaderKey' | 'getReadSnapshot' | 'deleteReaderKey'>
|
||||
readerKey: ReaderKeyAccess
|
||||
deviceLabel?: () => string
|
||||
now?: () => number
|
||||
}) {
|
||||
const now = deps.now ?? Date.now
|
||||
let registration: Registration | null = null
|
||||
let inflight: { tag: string; promise: Promise<Registration> } | null = null
|
||||
// Highest payload capturedAt opened per (profile/user/account, workspace). Memory only: a
|
||||
// restart forgets it, but within a run a replayed older snapshot is refused.
|
||||
const newestShown = new Map<string, number>()
|
||||
|
||||
async function ensure(force = false): Promise<Ready | Unavailable> {
|
||||
const identity = deps.readerKey.identity()
|
||||
if (!identity) {
|
||||
throw new CloudWorkspacesError(401, 'unauthorized')
|
||||
}
|
||||
const loaded = await deps.readerKey.load()
|
||||
if (!loaded.ok) {
|
||||
return { unavailable: loaded }
|
||||
}
|
||||
const { key } = loaded
|
||||
const known = registration
|
||||
if (
|
||||
!force &&
|
||||
known &&
|
||||
known.identity === identity &&
|
||||
known.publicKeyB64 === key.publicKeyB64 &&
|
||||
now() - known.at < READER_KEY_REFRESH_MS
|
||||
) {
|
||||
return { key, keyId: known.keyId, fresh: false, identity }
|
||||
}
|
||||
// Concurrent reads (and the start-up registration) share one PUT per identity and key.
|
||||
const tag = `${identity}\0${key.publicKeyB64}`
|
||||
let shared = !force && inflight?.tag === tag ? inflight : null
|
||||
if (!shared) {
|
||||
const promise = deps.client
|
||||
.registerReaderKey({
|
||||
publicKeyB64: key.publicKeyB64,
|
||||
deviceLabel: (deps.deviceLabel?.() ?? hostname()).slice(0, 80) || 'Desktop',
|
||||
deviceKind: 'desktop'
|
||||
})
|
||||
.then((readerKey) => {
|
||||
const next = {
|
||||
identity,
|
||||
publicKeyB64: key.publicKeyB64,
|
||||
keyId: readerKey.id,
|
||||
at: now()
|
||||
}
|
||||
// A sign-out or account switch while this was in flight must not adopt the old id.
|
||||
if (deps.readerKey.identity() === identity) {
|
||||
registration = next
|
||||
}
|
||||
return next
|
||||
})
|
||||
const entry = { tag, promise }
|
||||
shared = entry
|
||||
inflight = entry
|
||||
void promise
|
||||
.catch(() => undefined)
|
||||
.finally(() => {
|
||||
if (inflight === entry) {
|
||||
inflight = null
|
||||
}
|
||||
})
|
||||
}
|
||||
const done = await shared.promise
|
||||
return { key, keyId: done.keyId, fresh: true, identity }
|
||||
}
|
||||
|
||||
async function fetchWith(sandboxId: string, ready: Ready) {
|
||||
try {
|
||||
return await deps.client.getReadSnapshot(sandboxId, ready.keyId)
|
||||
} catch (error) {
|
||||
// A remembered id the server no longer accepts: register again (a revoked key gets a new id).
|
||||
if (
|
||||
!ready.fresh &&
|
||||
error instanceof CloudWorkspacesError &&
|
||||
error.status === 400 &&
|
||||
error.code === 'invalid_request'
|
||||
) {
|
||||
const again = await ensure(true)
|
||||
if ('unavailable' in again) {
|
||||
throw error
|
||||
}
|
||||
return { ready: again, fetched: await deps.client.getReadSnapshot(sandboxId, again.keyId) }
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
/** Best effort: make sure the control plane knows this device's key before workspaces sleep. */
|
||||
async register(): Promise<void> {
|
||||
await ensure().catch(() => undefined)
|
||||
},
|
||||
|
||||
/**
|
||||
* Sign-out: revoke this device's key server-side so no later sleep seals to it. Learns the id
|
||||
* (idempotent PUT) when this run never registered. Throws on failure; callers bound and ignore.
|
||||
*/
|
||||
async revoke(timeoutMs: number): Promise<void> {
|
||||
const identity = deps.readerKey.identity()
|
||||
const key = (await deps.readerKey.peek?.()) ?? null
|
||||
if (!identity || !key) {
|
||||
return
|
||||
}
|
||||
const known = registration
|
||||
const keyId =
|
||||
known && known.identity === identity && known.publicKeyB64 === key.publicKeyB64
|
||||
? known.keyId
|
||||
: (
|
||||
await deps.client.registerReaderKey({
|
||||
publicKeyB64: key.publicKeyB64,
|
||||
deviceLabel: (deps.deviceLabel?.() ?? hostname()).slice(0, 80) || 'Desktop',
|
||||
deviceKind: 'desktop'
|
||||
})
|
||||
).id
|
||||
registration = null
|
||||
await deps.client.deleteReaderKey(keyId, timeoutMs)
|
||||
},
|
||||
|
||||
async read(sandboxId: string): Promise<CloudReadSnapshotState> {
|
||||
const first = await ensure()
|
||||
if ('unavailable' in first) {
|
||||
return {
|
||||
state: 'unavailable',
|
||||
reason: first.unavailable.reason,
|
||||
message: first.unavailable.message
|
||||
}
|
||||
}
|
||||
let ready = first
|
||||
const answer = await fetchWith(sandboxId, ready)
|
||||
const fetched = 'ready' in answer ? answer.fetched : answer
|
||||
if ('ready' in answer) {
|
||||
ready = answer.ready
|
||||
}
|
||||
// not_sealed_for_key only means the snapshot predates this key: report it, never re-register.
|
||||
if (fetched.kind !== 'sealed') {
|
||||
return { state: fetched.kind }
|
||||
}
|
||||
try {
|
||||
const snapshot = await openReadSnapshot(
|
||||
fetched.sealed,
|
||||
sandboxId,
|
||||
ready.key.secretKey,
|
||||
nodeSealedGrantPrimitives
|
||||
)
|
||||
// Rollback pin: never show a copy older than one already shown for this workspace here.
|
||||
const pinKey = `${first.identity}\0${sandboxId}`
|
||||
const pinned = newestShown.get(pinKey)
|
||||
if (pinned !== undefined && snapshot.capturedAt < pinned) {
|
||||
return { state: 'stale' }
|
||||
}
|
||||
newestShown.set(pinKey, snapshot.capturedAt)
|
||||
return { state: 'ready', snapshot, storedAt: fetched.sealed.storedAt }
|
||||
} catch (error) {
|
||||
if (error instanceof ReadSnapshotError) {
|
||||
throw new CloudWorkspacesError(0, 'snapshot_unreadable', error.code)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export type ReadSnapshotReader = ReturnType<typeof createReadSnapshotReader>
|
||||
@@ -0,0 +1,161 @@
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
vi.mock('electron', () => ({
|
||||
app: { getPath: () => tmpdir() },
|
||||
safeStorage: {
|
||||
isEncryptionAvailable: () => false,
|
||||
encryptString: () => Buffer.alloc(0),
|
||||
decryptString: () => ''
|
||||
}
|
||||
}))
|
||||
|
||||
import {
|
||||
createCloudReaderKeyStore,
|
||||
revokeCloudReaderKeyBestEffort,
|
||||
setCloudReaderKeyRevoker,
|
||||
type ReaderKeyCodec
|
||||
} from './cloud-reader-key-store'
|
||||
import { x25519PublicKeyOf } from './sealed-grant-node'
|
||||
import { base64ToBytes, bytesToBase64 } from '../../shared/cloud-workspaces/sealed-grant'
|
||||
|
||||
// Reversible stand-in for the OS keychain: the file must never hold the raw secret.
|
||||
const codec: ReaderKeyCodec = {
|
||||
encrypt: (plain) => Buffer.from(`sealed:${Buffer.from(plain).toString('hex')}`),
|
||||
decrypt: (sealed) => {
|
||||
const text = sealed.toString()
|
||||
if (!text.startsWith('sealed:')) {
|
||||
throw new Error('bad seal')
|
||||
}
|
||||
return Buffer.from(text.slice(7), 'hex').toString()
|
||||
}
|
||||
}
|
||||
|
||||
let dir: string
|
||||
beforeEach(() => {
|
||||
dir = mkdtempSync(join(tmpdir(), 'reader-key-'))
|
||||
})
|
||||
afterEach(() => {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
const storeWith = (next: () => ReaderKeyCodec | null = () => codec) =>
|
||||
createCloudReaderKeyStore({
|
||||
pathFor: (profileId) => join(dir, profileId, 'key.enc'),
|
||||
codec: next,
|
||||
now: () => 1_700_000_000_000
|
||||
})
|
||||
|
||||
describe('createCloudReaderKeyStore', async () => {
|
||||
it('creates one key per profile lazily and keeps it sealed on disk', async () => {
|
||||
const store = storeWith()
|
||||
const first = await store.load('p1')
|
||||
expect(first.ok).toBe(true)
|
||||
if (!first.ok) {
|
||||
return
|
||||
}
|
||||
expect(first.key.secretKey).toHaveLength(32)
|
||||
const derived = x25519PublicKeyOf(first.key.secretKey)
|
||||
expect(first.key.publicKeyB64).toBe(bytesToBase64(derived))
|
||||
const file = readFileSync(join(dir, 'p1', 'key.enc'), 'utf8')
|
||||
expect(file).not.toContain(bytesToBase64(first.key.secretKey))
|
||||
expect(JSON.parse(file)).toMatchObject({ version: 1, format: 'electron-safe-storage-v1' })
|
||||
|
||||
const second = await store.load('p2')
|
||||
expect(second.ok && second.key.publicKeyB64).not.toBe(first.key.publicKeyB64)
|
||||
})
|
||||
|
||||
it('reads the same key back after a restart', async () => {
|
||||
const first = await storeWith().load('p1')
|
||||
const again = await storeWith().load('p1')
|
||||
expect(first.ok && again.ok).toBe(true)
|
||||
if (first.ok && again.ok) {
|
||||
expect(again.key.publicKeyB64).toBe(first.key.publicKeyB64)
|
||||
expect(base64ToBytes(bytesToBase64(again.key.secretKey))).toEqual(first.key.secretKey)
|
||||
}
|
||||
})
|
||||
|
||||
it('is off with a reason when the OS keychain is missing, and writes nothing', async () => {
|
||||
const store = storeWith(() => null)
|
||||
expect(await store.load('p1')).toMatchObject({ ok: false, reason: 'keychain_unavailable' })
|
||||
expect(existsSync(join(dir, 'p1', 'key.enc'))).toBe(false)
|
||||
})
|
||||
|
||||
it('replaces a key the keychain can no longer open', async () => {
|
||||
const first = await storeWith().load('p1')
|
||||
writeFileSync(
|
||||
join(dir, 'p1', 'key.enc'),
|
||||
JSON.stringify({ version: 1, format: 'electron-safe-storage-v1', ciphertext: 'AAAA' })
|
||||
)
|
||||
const replaced = await storeWith().load('p1')
|
||||
expect(replaced.ok).toBe(true)
|
||||
expect(first.ok && replaced.ok && replaced.key.publicKeyB64 !== first.key.publicKeyB64).toBe(
|
||||
true
|
||||
)
|
||||
})
|
||||
|
||||
it('clear drops the key from memory and disk (sign-out)', async () => {
|
||||
const store = storeWith()
|
||||
const first = await store.load('p1')
|
||||
await store.clear('p1')
|
||||
expect(existsSync(join(dir, 'p1', 'key.enc'))).toBe(false)
|
||||
const next = await store.load('p1')
|
||||
expect(first.ok && next.ok && next.key.publicKeyB64 !== first.key.publicKeyB64).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('revokeCloudReaderKeyBestEffort', async () => {
|
||||
afterEach(() => setCloudReaderKeyRevoker(null))
|
||||
|
||||
it('runs the registered revoker with the timeout', async () => {
|
||||
const revoke = vi.fn(async (_timeoutMs: number) => {})
|
||||
setCloudReaderKeyRevoker(revoke)
|
||||
await revokeCloudReaderKeyBestEffort(500)
|
||||
expect(revoke).toHaveBeenCalledWith(500)
|
||||
})
|
||||
|
||||
it('never blocks sign-out: a hung or failing revoke resolves within the timeout', async () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
setCloudReaderKeyRevoker(() => new Promise(() => {}))
|
||||
let settled = false
|
||||
const done = revokeCloudReaderKeyBestEffort(30).then(() => {
|
||||
settled = true
|
||||
})
|
||||
await vi.advanceTimersByTimeAsync(29)
|
||||
expect(settled).toBe(false)
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
await done
|
||||
expect(settled).toBe(true)
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
setCloudReaderKeyRevoker(async () => {
|
||||
throw new Error('offline')
|
||||
})
|
||||
await expect(revokeCloudReaderKeyBestEffort(30)).resolves.toBeUndefined()
|
||||
setCloudReaderKeyRevoker(null)
|
||||
await expect(revokeCloudReaderKeyBestEffort(30)).resolves.toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('peek', async () => {
|
||||
it('returns the existing key and never creates one', async () => {
|
||||
const store = storeWith()
|
||||
expect(await store.peek('p1')).toBeNull()
|
||||
expect(existsSync(join(dir, 'p1', 'key.enc'))).toBe(false)
|
||||
const loaded = await store.load('p1')
|
||||
const fresh = await storeWith().peek('p1')
|
||||
expect(loaded.ok && fresh?.publicKeyB64 === loaded.key.publicKeyB64).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('concurrent first loads', () => {
|
||||
it('mint a single key', async () => {
|
||||
const store = storeWith()
|
||||
const [a, b] = await Promise.all([store.load('p1'), store.load('p1')])
|
||||
expect(a.ok && b.ok && a.key.publicKeyB64 === b.key.publicKeyB64).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,234 @@
|
||||
// This device's long-lived X25519 "reader key", one per Orca profile. A sleeping Orca Cloud
|
||||
// workspace seals its read snapshot to every registered reader key allowed to open it; the secret
|
||||
// half never leaves this machine. It is sealed by the OS keychain (safeStorage at level 'os'); with
|
||||
// no real keychain the feature is off rather than keeping a long-lived secret in the clear.
|
||||
import { readFile, rm } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { assessSecretProtection } from '../host/electron-secret-store'
|
||||
import { guardedSafeStorage } from '../host/safe-storage-availability'
|
||||
import { writeSecureJsonFile } from '../../shared/secure-storage/secure-file'
|
||||
import { base64ToBytes, bytesToBase64 } from '../../shared/cloud-workspaces/sealed-grant'
|
||||
import { getOrcaProfileDirectory } from '../orca-profiles/profile-storage-paths'
|
||||
import { generateGrantRecipientKey, x25519PublicKeyOf } from './sealed-grant-node'
|
||||
|
||||
export const READER_KEY_FILE_NAME = 'cloud-reader-key.json.enc'
|
||||
|
||||
export type ReaderKeyCodec = {
|
||||
encrypt: (plain: string) => Buffer
|
||||
decrypt: (sealed: Buffer) => string
|
||||
}
|
||||
|
||||
export type CloudReaderKey = {
|
||||
/** 32-byte X25519 secret. Callers must not keep or zero it; the store owns the buffer. */
|
||||
secretKey: Uint8Array
|
||||
publicKeyB64: string
|
||||
}
|
||||
|
||||
export type ReaderKeyLoad =
|
||||
| { ok: true; key: CloudReaderKey }
|
||||
| { ok: false; reason: 'keychain_unavailable' | 'storage_failed'; message: string }
|
||||
|
||||
type PersistedReaderKey = {
|
||||
version: 1
|
||||
format: 'electron-safe-storage-v1'
|
||||
createdAt: number
|
||||
ciphertext: string
|
||||
}
|
||||
|
||||
const KEYCHAIN_MESSAGE =
|
||||
'Reading sleeping workspaces needs the OS keychain to protect this device’s key.'
|
||||
|
||||
/** The OS keychain, or null when it is missing or only obfuscates (Linux basic_text). */
|
||||
export function osReaderKeyCodec(): ReaderKeyCodec | null {
|
||||
try {
|
||||
if (!guardedSafeStorage.isEncryptionAvailable() || assessSecretProtection().level !== 'os') {
|
||||
return null
|
||||
}
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
return {
|
||||
encrypt: (plain) => guardedSafeStorage.encryptString(plain),
|
||||
decrypt: (sealed) => guardedSafeStorage.decryptString(sealed)
|
||||
}
|
||||
}
|
||||
|
||||
export function getCloudReaderKeyPath(profileId: string, userDataPath: string): string {
|
||||
return join(getOrcaProfileDirectory(profileId, userDataPath), READER_KEY_FILE_NAME)
|
||||
}
|
||||
|
||||
export function createCloudReaderKeyStore(deps: {
|
||||
pathFor: (profileId: string) => string
|
||||
codec: () => ReaderKeyCodec | null
|
||||
now?: () => number
|
||||
}) {
|
||||
const cache = new Map<string, CloudReaderKey>()
|
||||
// One load per key file at a time, so two first reads can never mint two keys.
|
||||
const loading = new Map<string, Promise<ReaderKeyLoad>>()
|
||||
|
||||
/** The sealed key on disk, or null when there is none or this keychain cannot open it. */
|
||||
async function readExisting(path: string, codec: ReaderKeyCodec): Promise<CloudReaderKey | null> {
|
||||
let text: string
|
||||
try {
|
||||
text = await readFile(path, 'utf8')
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(text)
|
||||
if (
|
||||
!isRecord(parsed) ||
|
||||
parsed.version !== 1 ||
|
||||
parsed.format !== 'electron-safe-storage-v1' ||
|
||||
typeof parsed.ciphertext !== 'string'
|
||||
) {
|
||||
return null
|
||||
}
|
||||
const secretKey = base64ToBytes(codec.decrypt(Buffer.from(parsed.ciphertext, 'base64')))
|
||||
if (secretKey.length !== 32) {
|
||||
return null
|
||||
}
|
||||
return { secretKey, publicKeyB64: bytesToBase64(x25519PublicKeyOf(secretKey)) }
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
async function loadUncached(path: string, codec: ReaderKeyCodec): Promise<ReaderKeyLoad> {
|
||||
const existing = await readExisting(path, codec)
|
||||
if (existing) {
|
||||
cache.set(path, existing)
|
||||
return { ok: true, key: existing }
|
||||
}
|
||||
// A new key only means snapshots taken before it are not readable here until the next sleep.
|
||||
const fresh = generateGrantRecipientKey()
|
||||
try {
|
||||
const persisted: PersistedReaderKey = {
|
||||
version: 1,
|
||||
format: 'electron-safe-storage-v1',
|
||||
createdAt: (deps.now ?? Date.now)(),
|
||||
ciphertext: codec.encrypt(bytesToBase64(fresh.secretKey)).toString('base64')
|
||||
}
|
||||
// Once per profile; the shared writer applies owner-only permissions (and Windows ACLs).
|
||||
writeSecureJsonFile(path, persisted)
|
||||
} catch (error) {
|
||||
fresh.secretKey.fill(0)
|
||||
return {
|
||||
ok: false,
|
||||
reason: 'storage_failed',
|
||||
message: `Could not save this device’s reader key: ${String(error).slice(0, 120)}`
|
||||
}
|
||||
}
|
||||
const key = { secretKey: fresh.secretKey, publicKeyB64: fresh.publicKeyB64 }
|
||||
cache.set(path, key)
|
||||
return { ok: true, key }
|
||||
}
|
||||
|
||||
return {
|
||||
/** The profile's existing key, if any; never creates one. */
|
||||
async peek(profileId: string): Promise<CloudReaderKey | null> {
|
||||
const codec = deps.codec()
|
||||
const path = deps.pathFor(profileId)
|
||||
const cached = cache.get(path)
|
||||
if (cached || !codec) {
|
||||
return cached ?? null
|
||||
}
|
||||
const existing = await readExisting(path, codec)
|
||||
if (existing) {
|
||||
cache.set(path, existing)
|
||||
}
|
||||
return existing
|
||||
},
|
||||
/** The profile's key, created on first use. A key the keychain can no longer open is replaced. */
|
||||
async load(profileId: string): Promise<ReaderKeyLoad> {
|
||||
const codec = deps.codec()
|
||||
if (!codec) {
|
||||
return { ok: false, reason: 'keychain_unavailable', message: KEYCHAIN_MESSAGE }
|
||||
}
|
||||
const path = deps.pathFor(profileId)
|
||||
const cached = cache.get(path)
|
||||
if (cached) {
|
||||
return { ok: true, key: cached }
|
||||
}
|
||||
let pending = loading.get(path)
|
||||
if (!pending) {
|
||||
pending = loadUncached(path, codec).finally(() => loading.delete(path))
|
||||
loading.set(path, pending)
|
||||
}
|
||||
return pending
|
||||
},
|
||||
/** Sign-out: the next account on this profile gets a new key (never one an old account knew). */
|
||||
async clear(profileId: string): Promise<void> {
|
||||
const path = deps.pathFor(profileId)
|
||||
// A first load still in flight would otherwise write its key back after this.
|
||||
await loading.get(path)
|
||||
cache.get(path)?.secretKey.fill(0)
|
||||
cache.delete(path)
|
||||
await rm(path, { force: true })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
export type CloudReaderKeyStore = ReturnType<typeof createCloudReaderKeyStore>
|
||||
|
||||
let defaultStore: { userDataPath: string; store: CloudReaderKeyStore } | null = null
|
||||
|
||||
/** The process-wide store for this user data directory (the OS keychain codec). */
|
||||
export function getCloudReaderKeyStore(userDataPath: string): CloudReaderKeyStore {
|
||||
if (defaultStore?.userDataPath !== userDataPath) {
|
||||
defaultStore = {
|
||||
userDataPath,
|
||||
store: createCloudReaderKeyStore({
|
||||
pathFor: (profileId) => getCloudReaderKeyPath(profileId, userDataPath),
|
||||
codec: osReaderKeyCodec
|
||||
})
|
||||
}
|
||||
}
|
||||
return defaultStore.store
|
||||
}
|
||||
|
||||
// Sign-out revokes the key server-side through the cloud workspaces service (it owns the client
|
||||
// and the registration id). A seam so profile code never loads that service.
|
||||
let revoker: ((timeoutMs: number) => Promise<void>) | null = null
|
||||
|
||||
export function setCloudReaderKeyRevoker(next: typeof revoker): void {
|
||||
revoker = next
|
||||
}
|
||||
|
||||
export const READER_KEY_REVOKE_TIMEOUT_MS = 2_500
|
||||
|
||||
/** Best effort and bounded: resolves within `timeoutMs` whatever the network does. */
|
||||
export async function revokeCloudReaderKeyBestEffort(
|
||||
timeoutMs = READER_KEY_REVOKE_TIMEOUT_MS
|
||||
): Promise<void> {
|
||||
const run = revoker
|
||||
if (!run) {
|
||||
return
|
||||
}
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
try {
|
||||
await Promise.race([
|
||||
Promise.resolve()
|
||||
.then(() => run(timeoutMs))
|
||||
.catch(() => undefined),
|
||||
new Promise<void>((resolve) => {
|
||||
timer = setTimeout(resolve, timeoutMs)
|
||||
})
|
||||
])
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
}
|
||||
}
|
||||
|
||||
/** Sign-out / profile reset hook: drop the profile's reader key (memory and disk). */
|
||||
export async function clearCloudReaderKey(profileId: string, userDataPath: string): Promise<void> {
|
||||
try {
|
||||
await getCloudReaderKeyStore(userDataPath).clear(profileId)
|
||||
} catch (error) {
|
||||
console.error(`[orca-cloud] clearing the reader key failed: ${String(error)}`)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { CloudWorkspaceSchema } from '../../shared/cloud-workspaces/cloud-workspaces-wire'
|
||||
import { createCloudWorkspacesClient } from './cloud-workspaces-client'
|
||||
|
||||
const SBX = 'sbx_0123456789abcdef01234567'
|
||||
const KEY = 'rk_aaaaaaaaaaaaaaaaaaaaaaaa'
|
||||
|
||||
function clientAnswering(status: number, body: unknown) {
|
||||
const fetch = vi.fn<typeof globalThis.fetch>(
|
||||
async () => new Response(JSON.stringify(body), { status })
|
||||
)
|
||||
const client = createCloudWorkspacesClient({
|
||||
baseUrl: 'https://cp.example.test',
|
||||
getAccessToken: async () => 'tok',
|
||||
fetch
|
||||
})
|
||||
return { client, fetch }
|
||||
}
|
||||
|
||||
const sealed = {
|
||||
v: 1,
|
||||
snapshotId: 'snap_1',
|
||||
workspaceId: SBX,
|
||||
storedAt: 5,
|
||||
nonceB64: 'AAAAAAAAAAAAAAAA',
|
||||
ciphertextB64: 'AAAA',
|
||||
recipient: {
|
||||
keyId: KEY,
|
||||
ephemeralPublicKeyB64: 'AAAA',
|
||||
nonceB64: 'AAAA',
|
||||
wrappedKeyB64: 'AAAA'
|
||||
}
|
||||
}
|
||||
|
||||
describe('cloud workspaces client: read snapshots', () => {
|
||||
it('PUTs the reader key and returns its id', async () => {
|
||||
const { client, fetch } = clientAnswering(200, {
|
||||
readerKey: { id: KEY, deviceKind: 'desktop', deviceLabel: 'mac', createdAt: 1, lastSeenAt: 2 }
|
||||
})
|
||||
const key = await client.registerReaderKey({
|
||||
publicKeyB64: 'pub',
|
||||
deviceLabel: 'mac',
|
||||
deviceKind: 'desktop'
|
||||
})
|
||||
expect(key.id).toBe(KEY)
|
||||
const [url, init] = fetch.mock.calls[0]!
|
||||
expect(String(url)).toBe('https://cp.example.test/v1/reader-keys')
|
||||
expect(init?.method).toBe('PUT')
|
||||
expect(JSON.parse(String(init?.body))).toEqual({
|
||||
publicKeyB64: 'pub',
|
||||
deviceLabel: 'mac',
|
||||
deviceKind: 'desktop'
|
||||
})
|
||||
})
|
||||
|
||||
it('DELETEs a reader key by id', async () => {
|
||||
const { client, fetch } = clientAnswering(200, { ok: true })
|
||||
await client.deleteReaderKey(KEY, 2_000)
|
||||
const [url, init] = fetch.mock.calls[0]!
|
||||
expect(String(url)).toBe(`https://cp.example.test/v1/reader-keys/${KEY}`)
|
||||
expect(init?.method).toBe('DELETE')
|
||||
})
|
||||
|
||||
it('GETs the sealed snapshot for this key', async () => {
|
||||
const { client, fetch } = clientAnswering(200, { snapshot: sealed })
|
||||
expect(await client.getReadSnapshot(SBX, KEY)).toEqual({ kind: 'sealed', sealed })
|
||||
expect(String(fetch.mock.calls[0]![0])).toBe(
|
||||
`https://cp.example.test/v1/team/workspaces/${SBX}/read-snapshot?keyId=${KEY}`
|
||||
)
|
||||
})
|
||||
|
||||
it.each(['not_found', 'no_snapshot', 'not_sealed_for_key'] as const)(
|
||||
'maps 404 %s to a typed result',
|
||||
async (code) => {
|
||||
const { client } = clientAnswering(404, { error: code })
|
||||
expect(await client.getReadSnapshot(SBX, KEY)).toEqual({ kind: code })
|
||||
}
|
||||
)
|
||||
|
||||
it('keeps other failures as errors', async () => {
|
||||
await expect(
|
||||
clientAnswering(404, { error: 'something_else' }).client.getReadSnapshot(SBX, KEY)
|
||||
).rejects.toMatchObject({ status: 404, code: 'something_else' })
|
||||
await expect(
|
||||
clientAnswering(400, { error: 'invalid_request' }).client.getReadSnapshot(SBX, KEY)
|
||||
).rejects.toMatchObject({ status: 400, code: 'invalid_request' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('CloudWorkspaceSchema.readSnapshotAt', () => {
|
||||
const base = {
|
||||
id: SBX,
|
||||
workspaceId: 'w',
|
||||
status: 'suspended',
|
||||
machineSize: 'standard',
|
||||
region: 'iad1',
|
||||
createdAt: 1,
|
||||
title: null,
|
||||
repo: null,
|
||||
visibility: 'team',
|
||||
section: null,
|
||||
archivedAt: null,
|
||||
createdBy: 'u',
|
||||
ownerUserId: 'u',
|
||||
lastActivityAt: 1,
|
||||
lastActivityBy: null,
|
||||
cost: {
|
||||
computeMs: 0,
|
||||
rateUsdMicrosPerHour: 0,
|
||||
computeUsdMicros: 0,
|
||||
tokenUsdMicros: null,
|
||||
totalUsdMicros: 0
|
||||
},
|
||||
access: 'can_open',
|
||||
presence: []
|
||||
}
|
||||
it('is optional for older control planes and nullable', () => {
|
||||
expect(CloudWorkspaceSchema.parse(base).readSnapshotAt).toBeUndefined()
|
||||
expect(CloudWorkspaceSchema.parse({ ...base, readSnapshotAt: null }).readSnapshotAt).toBeNull()
|
||||
expect(CloudWorkspaceSchema.parse({ ...base, readSnapshotAt: 9 }).readSnapshotAt).toBe(9)
|
||||
})
|
||||
})
|
||||
@@ -2,7 +2,10 @@
|
||||
// hosted sandbox driver: a short-lived Orca token (aud=orca-sandbox), never a provider credential.
|
||||
import { z } from 'zod'
|
||||
import { errorMessage } from '../../shared/error-message'
|
||||
import type { SealedReadSnapshot } from '../../shared/cloud-workspaces/read-snapshot'
|
||||
import {
|
||||
CloudReadSnapshotResponseSchema,
|
||||
CloudReaderKeyResponseSchema,
|
||||
CloudWorkspaceGrantIssuedSchema,
|
||||
CloudWorkspaceGrantListSchema,
|
||||
CloudWorkspaceLinkResponseSchema,
|
||||
@@ -38,6 +41,15 @@ const CONTROL_TIMEOUT_MS = 20_000
|
||||
// Opening a sleeping teammate workspace includes a VM boot.
|
||||
const GRANT_TIMEOUT_MS = 120_000
|
||||
const MAX_RESPONSE_BYTES = 512 * 1024
|
||||
// A read snapshot carries chat tails (bounded by READ_SNAPSHOT_LIMITS), base64 over AES-GCM.
|
||||
const MAX_READ_SNAPSHOT_BYTES = 16 * 1024 * 1024
|
||||
|
||||
/** The read-snapshot 404s are states, not failures: each has its own copy. */
|
||||
const READ_SNAPSHOT_MISSES = ['not_found', 'no_snapshot', 'not_sealed_for_key'] as const
|
||||
export type ReadSnapshotMiss = (typeof READ_SNAPSHOT_MISSES)[number]
|
||||
export type ReadSnapshotFetch =
|
||||
| { kind: 'sealed'; sealed: SealedReadSnapshot }
|
||||
| { kind: ReadSnapshotMiss }
|
||||
|
||||
export function createCloudWorkspacesClient(options: CloudWorkspacesClientOptions) {
|
||||
const doFetch = options.fetch ?? fetch
|
||||
@@ -48,7 +60,8 @@ export function createCloudWorkspacesClient(options: CloudWorkspacesClientOption
|
||||
path: string,
|
||||
schema: z.ZodType<T>,
|
||||
body?: unknown,
|
||||
timeoutMs = CONTROL_TIMEOUT_MS
|
||||
timeoutMs = CONTROL_TIMEOUT_MS,
|
||||
maxBytes = MAX_RESPONSE_BYTES
|
||||
): Promise<T> {
|
||||
const signal = AbortSignal.timeout(timeoutMs)
|
||||
let token: string
|
||||
@@ -80,7 +93,7 @@ export function createCloudWorkspacesClient(options: CloudWorkspacesClientOption
|
||||
)
|
||||
}
|
||||
const text = await response.text()
|
||||
if (text.length > MAX_RESPONSE_BYTES) {
|
||||
if (text.length > maxBytes) {
|
||||
throw new CloudWorkspacesError(response.status, 'invalid_response')
|
||||
}
|
||||
let payload: unknown = null
|
||||
@@ -177,6 +190,46 @@ export function createCloudWorkspacesClient(options: CloudWorkspacesClientOption
|
||||
}
|
||||
return call('GET', `/v1/team/links/resolve?${params}`, CloudWorkspaceLinkResponseSchema)
|
||||
},
|
||||
/** Idempotent per (user, account, public key): the same id comes back, lastSeenAt bumped. */
|
||||
async registerReaderKey(body: {
|
||||
publicKeyB64: string
|
||||
deviceLabel: string
|
||||
deviceKind: 'desktop' | 'mobile'
|
||||
}) {
|
||||
return (await call('PUT', '/v1/reader-keys', CloudReaderKeyResponseSchema, body)).readerKey
|
||||
},
|
||||
/** Server-side revoke: wrapped keys for it are pruned and it is never resurrected. */
|
||||
async deleteReaderKey(keyId: string, timeoutMs = CONTROL_TIMEOUT_MS): Promise<void> {
|
||||
await call(
|
||||
'DELETE',
|
||||
`/v1/reader-keys/${encodeURIComponent(keyId)}`,
|
||||
NoteSentSchema.passthrough(),
|
||||
undefined,
|
||||
timeoutMs
|
||||
)
|
||||
},
|
||||
async getReadSnapshot(id: string, keyId: string): Promise<ReadSnapshotFetch> {
|
||||
try {
|
||||
const { snapshot } = await call(
|
||||
'GET',
|
||||
`${ws(id)}/read-snapshot?${new URLSearchParams({ keyId })}`,
|
||||
CloudReadSnapshotResponseSchema,
|
||||
undefined,
|
||||
CONTROL_TIMEOUT_MS,
|
||||
MAX_READ_SNAPSHOT_BYTES
|
||||
)
|
||||
return { kind: 'sealed', sealed: snapshot }
|
||||
} catch (error) {
|
||||
const miss =
|
||||
error instanceof CloudWorkspacesError && error.status === 404
|
||||
? READ_SNAPSHOT_MISSES.find((code) => code === error.code)
|
||||
: undefined
|
||||
if (miss) {
|
||||
return { kind: miss }
|
||||
}
|
||||
throw error
|
||||
}
|
||||
},
|
||||
getOrgPrompts(): Promise<OrgPrompts> {
|
||||
return call('GET', '/v1/team/prompts', OrgPromptsSchema)
|
||||
},
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
type CloudWorkspacesClient
|
||||
} from './cloud-workspaces-client'
|
||||
import { generateGrantRecipientKey, nodeSealedGrantPrimitives } from './sealed-grant-node'
|
||||
import { createReadSnapshotReader, type ReaderKeyAccess } from './cloud-read-snapshot-reader'
|
||||
|
||||
const PRESENCE_BEAT_MS = 20_000
|
||||
/** Renew a teammate-opened workspace's lease well before the control plane's 30 min lease lapses. */
|
||||
@@ -52,6 +53,8 @@ export function createCloudWorkspacesService(deps: {
|
||||
config: HostedSandboxConfig
|
||||
clientId: string
|
||||
fetch?: typeof fetch
|
||||
/** This profile's reader key (sleeping-workspace snapshots); absent: reading them is off. */
|
||||
readerKey?: ReaderKeyAccess
|
||||
}) {
|
||||
const client: CloudWorkspacesClient = createCloudWorkspacesClient({
|
||||
baseUrl: deps.config.controlPlaneUrl,
|
||||
@@ -69,6 +72,11 @@ export function createCloudWorkspacesService(deps: {
|
||||
let heartbeat: ReturnType<typeof setInterval> | null = null
|
||||
let leaseSandboxId: string | null = null
|
||||
let leaseRenewedAt = 0
|
||||
const reader = deps.readerKey
|
||||
? createReadSnapshotReader({ client, readerKey: deps.readerKey })
|
||||
: null
|
||||
// Register the key up front: a workspace seals its snapshot to the keys known when it sleeps.
|
||||
void reader?.register()
|
||||
|
||||
function localWorkspaces(): LocalCloudWorkspace[] {
|
||||
const out: LocalCloudWorkspace[] = []
|
||||
@@ -126,7 +134,23 @@ export function createCloudWorkspacesService(deps: {
|
||||
|
||||
return {
|
||||
available: true as const,
|
||||
list: (query: CloudWorkspaceListQuery) => wrap(() => client.list(query)),
|
||||
list: (query: CloudWorkspaceListQuery) =>
|
||||
wrap(async () => {
|
||||
const workspaces = await client.list(query)
|
||||
// Cheap when already registered; catches a sign-in or account switch since the last list.
|
||||
void reader?.register()
|
||||
return workspaces
|
||||
}),
|
||||
/** Sign-out: revoke this device's reader key server-side (callers bound the wait). */
|
||||
revokeReaderKey: (timeoutMs: number) => reader?.revoke(timeoutMs) ?? Promise.resolve(),
|
||||
/** A sleeping workspace's sealed snapshot, opened on this device; never wakes it. */
|
||||
readSnapshot: (id: string) =>
|
||||
wrap(async () => {
|
||||
if (!reader) {
|
||||
throw new CloudWorkspacesError(0, 'not_configured')
|
||||
}
|
||||
return reader.read(id)
|
||||
}),
|
||||
get: (id: string) => wrap(() => client.get(id)),
|
||||
patch: (id: string, patch: CloudWorkspacePatch) =>
|
||||
wrap(async () => (await client.patch(id, patch)).workspace),
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
// Test-only sealer: the VM's construction (see read-snapshot.ts header) with node:crypto, so the
|
||||
// desktop opener is checked against an independent implementation rather than itself.
|
||||
import {
|
||||
createCipheriv,
|
||||
createPublicKey,
|
||||
diffieHellman,
|
||||
generateKeyPairSync,
|
||||
hkdfSync,
|
||||
randomBytes
|
||||
} from 'node:crypto'
|
||||
import type { SealedReadSnapshot } from '../../shared/cloud-workspaces/read-snapshot'
|
||||
|
||||
const b64 = (bytes: Uint8Array): string => Buffer.from(bytes).toString('base64')
|
||||
|
||||
function gcm(key: Uint8Array, nonce: Uint8Array, plain: Uint8Array, aad: string): Buffer {
|
||||
const cipher = createCipheriv('aes-256-gcm', key, nonce)
|
||||
cipher.setAAD(Buffer.from(aad, 'utf8'))
|
||||
return Buffer.concat([cipher.update(plain), cipher.final(), cipher.getAuthTag()])
|
||||
}
|
||||
|
||||
export function sealReadSnapshotForTest(args: {
|
||||
payload: unknown
|
||||
workspaceId: string
|
||||
snapshotId: string
|
||||
readerPublicKeyB64: string
|
||||
keyId: string
|
||||
storedAt?: number
|
||||
}): SealedReadSnapshot {
|
||||
const { workspaceId, snapshotId, keyId } = args
|
||||
const dek = randomBytes(32)
|
||||
const nonce = randomBytes(12)
|
||||
const body = gcm(
|
||||
dek,
|
||||
nonce,
|
||||
Buffer.from(JSON.stringify(args.payload), 'utf8'),
|
||||
`orca-cloud-read-v1:${workspaceId}:${snapshotId}`
|
||||
)
|
||||
const readerPublic = Buffer.from(args.readerPublicKeyB64, 'base64')
|
||||
const ephemeral = generateKeyPairSync('x25519')
|
||||
const ephemeralPublic = Buffer.from(ephemeral.publicKey.export({ format: 'jwk' }).x!, 'base64url')
|
||||
const shared = diffieHellman({
|
||||
privateKey: ephemeral.privateKey,
|
||||
publicKey: createPublicKey({
|
||||
key: { kty: 'OKP', crv: 'X25519', x: readerPublic.toString('base64url') },
|
||||
format: 'jwk'
|
||||
})
|
||||
})
|
||||
const kek = Buffer.from(
|
||||
hkdfSync(
|
||||
'sha256',
|
||||
shared,
|
||||
Buffer.concat([ephemeralPublic, readerPublic]),
|
||||
Buffer.from('orca-cloud-read-wrap-v1', 'utf8'),
|
||||
32
|
||||
)
|
||||
)
|
||||
const wrapNonce = randomBytes(12)
|
||||
const wrapped = gcm(
|
||||
kek,
|
||||
wrapNonce,
|
||||
dek,
|
||||
`orca-cloud-read-wrap-v1:${workspaceId}:${snapshotId}:${keyId}`
|
||||
)
|
||||
return {
|
||||
v: 1,
|
||||
snapshotId,
|
||||
workspaceId,
|
||||
storedAt: args.storedAt ?? 1_000,
|
||||
nonceB64: b64(nonce),
|
||||
ciphertextB64: b64(body),
|
||||
recipient: {
|
||||
keyId,
|
||||
ephemeralPublicKeyB64: b64(ephemeralPublic),
|
||||
nonceB64: b64(wrapNonce),
|
||||
wrappedKeyB64: b64(wrapped)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,8 @@ function privateKeyFor(secret: Uint8Array, publicKey: Uint8Array) {
|
||||
})
|
||||
}
|
||||
|
||||
function publicKeyOf(secret: Uint8Array): Uint8Array {
|
||||
/** X25519 public key for a 32-byte secret (synchronous, unlike the primitives' contract). */
|
||||
export function x25519PublicKeyOf(secret: Uint8Array): Uint8Array {
|
||||
// Node derives the public half when only `d` is given via PKCS#8; JWK import needs `x`, so go through DER.
|
||||
const pkcs8 = Buffer.concat([
|
||||
Buffer.from('302e020100300506032b656e04220420', 'hex'),
|
||||
@@ -33,10 +34,10 @@ function publicKeyOf(secret: Uint8Array): Uint8Array {
|
||||
}
|
||||
|
||||
export const nodeSealedGrantPrimitives: SealedGrantPrimitives = {
|
||||
x25519PublicKey: publicKeyOf,
|
||||
x25519PublicKey: x25519PublicKeyOf,
|
||||
x25519(secret, peer) {
|
||||
const shared = diffieHellman({
|
||||
privateKey: privateKeyFor(secret, publicKeyOf(secret)),
|
||||
privateKey: privateKeyFor(secret, x25519PublicKeyOf(secret)),
|
||||
publicKey: createPublicKey({
|
||||
key: { kty: 'OKP', crv: 'X25519', x: b64url(peer) },
|
||||
format: 'jwk'
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const runtimes: { runtimeEnvironmentId: string; recipe?: { provider?: string } }[] = []
|
||||
const environments = new Map<string, { source?: string; endpoints: { endpoint: string }[] }>()
|
||||
let launchEnv: Record<string, string> = {}
|
||||
const launchCalls: unknown[][] = []
|
||||
|
||||
vi.mock('../../shared/ephemeral-vm-runtime-store', () => ({
|
||||
listEphemeralVmRuntimes: () => runtimes
|
||||
}))
|
||||
vi.mock('../../shared/remote-runtime/host-store/runtime-environment-store', () => ({
|
||||
resolveEnvironment: (_userData: string, id: string) => {
|
||||
const environment = environments.get(id)
|
||||
if (!environment) {
|
||||
throw new Error('unknown environment')
|
||||
}
|
||||
return environment
|
||||
}
|
||||
}))
|
||||
vi.mock('../agent-api-keys/agent-api-key-launch-env', () => ({
|
||||
resolveAgentApiKeyLaunchEnv: async (...args: unknown[]) => {
|
||||
launchCalls.push(args)
|
||||
return launchEnv
|
||||
},
|
||||
withAgentApiKeyLaunchEnv: async (env: Record<string, string> | undefined, ...args: unknown[]) => {
|
||||
launchCalls.push(args)
|
||||
return { ...env, ...launchEnv }
|
||||
}
|
||||
}))
|
||||
const sshTargets = new Map<
|
||||
string,
|
||||
{ host: string; label: string; configHost?: string; proxyCommand?: string }
|
||||
>()
|
||||
vi.mock('../ssh/targets/ssh-target-registry', () => ({
|
||||
getSshTargetRegistryStore: () => ({ getTarget: (id: string) => sshTargets.get(id) })
|
||||
}))
|
||||
|
||||
const { desktopKeyValueForCloud, isOrcaCloudRuntimeEnvironment } =
|
||||
await import('./cloud-desktop-keys')
|
||||
|
||||
beforeEach(() => {
|
||||
runtimes.length = 0
|
||||
environments.clear()
|
||||
launchEnv = {}
|
||||
launchCalls.length = 0
|
||||
sshTargets.clear()
|
||||
})
|
||||
|
||||
describe('isOrcaCloudRuntimeEnvironment', () => {
|
||||
it('is true for an Orca Cloud runtime and false for another VM recipe or a paired machine', () => {
|
||||
runtimes.push({ runtimeEnvironmentId: 'env-cloud', recipe: { provider: 'orca-cloud' } })
|
||||
runtimes.push({ runtimeEnvironmentId: 'env-own-vm', recipe: { provider: 'my-recipes' } })
|
||||
environments.set('env-mac', {
|
||||
source: 'manual',
|
||||
endpoints: [{ endpoint: 'wss://192.168.1.4:6768' }]
|
||||
})
|
||||
expect(isOrcaCloudRuntimeEnvironment('/u', 'env-cloud')).toBe(true)
|
||||
expect(isOrcaCloudRuntimeEnvironment('/u', 'env-own-vm')).toBe(false)
|
||||
expect(isOrcaCloudRuntimeEnvironment('/u', 'env-mac')).toBe(false)
|
||||
})
|
||||
|
||||
it('fails closed: a VM with no provider record, or a host on a Vercel Sandbox route, counts as Orca Cloud', () => {
|
||||
runtimes.push({ runtimeEnvironmentId: 'env-unknown-recipe' })
|
||||
environments.set('env-vm', { source: 'ephemeral-vm', endpoints: [{ endpoint: 'wss://x' }] })
|
||||
environments.set('env-paired-cloud', {
|
||||
source: 'manual',
|
||||
endpoints: [{ endpoint: 'wss://sb-abc123.vercel.run' }]
|
||||
})
|
||||
expect(isOrcaCloudRuntimeEnvironment('/u', 'env-unknown-recipe')).toBe(true)
|
||||
expect(isOrcaCloudRuntimeEnvironment('/u', 'env-vm')).toBe(true)
|
||||
expect(isOrcaCloudRuntimeEnvironment('/u', 'env-paired-cloud')).toBe(true)
|
||||
expect(isOrcaCloudRuntimeEnvironment('/u', 'env-missing')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('desktopKeyValueForCloud', () => {
|
||||
it('reads only keys set for every host, for one agent and one variable', async () => {
|
||||
launchEnv = { GEMINI_API_KEY: 'AIzaSy-real', OTHER: 'x' }
|
||||
expect(await desktopKeyValueForCloud('gemini', 'GEMINI_API_KEY')).toBe('AIzaSy-real')
|
||||
expect(await desktopKeyValueForCloud('gemini', 'CURSOR_API_KEY')).toBeNull()
|
||||
expect(launchCalls[0]).toEqual(['gemini', 'runtime:orca-cloud'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('withHostAgentApiKeyEnv', () => {
|
||||
it('adds no desktop keys to a launch on an Orca Cloud VM', async () => {
|
||||
runtimes.push({ runtimeEnvironmentId: 'env-cloud', recipe: { provider: 'orca-cloud' } })
|
||||
launchEnv = { GEMINI_API_KEY: 'AIzaSy-real' }
|
||||
const params = { agent: 'gemini', kind: 'explicit' }
|
||||
const { setCloudDesktopKeysUserDataPath, withHostAgentApiKeyEnv } =
|
||||
await import('./cloud-desktop-keys')
|
||||
setCloudDesktopKeysUserDataPath('/u')
|
||||
const readStatus = vi.fn()
|
||||
expect(
|
||||
await withHostAgentApiKeyEnv('env-cloud', 'terminal.createAgentSession', params, readStatus)
|
||||
).toBe(params)
|
||||
expect(launchCalls).toEqual([])
|
||||
expect(readStatus).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('withHostAgentApiKeyLaunchEnv (SSH)', () => {
|
||||
it('sends no desktop keys over SSH into an Orca Cloud workspace, and does elsewhere', async () => {
|
||||
const { withHostAgentApiKeyLaunchEnv } = await import('./cloud-desktop-keys')
|
||||
launchEnv = { CURSOR_API_KEY: 'key_real' }
|
||||
sshTargets.set('t-cloud', {
|
||||
host: 'orca-api-7f3a',
|
||||
label: 'orca-api-7f3a',
|
||||
configHost: 'orca-api-7f3a'
|
||||
})
|
||||
sshTargets.set('t-proxy', {
|
||||
host: 'box',
|
||||
label: 'box',
|
||||
proxyCommand: '/Applications/Orca.app/bin/orca ssh-proxy env-1'
|
||||
})
|
||||
sshTargets.set('t-devbox', { host: 'devbox.lan', label: 'devbox' })
|
||||
expect(await withHostAgentApiKeyLaunchEnv({ A: '1' }, 'cursor', 't-cloud')).toEqual({ A: '1' })
|
||||
expect(await withHostAgentApiKeyLaunchEnv({ A: '1' }, 'cursor', 't-proxy')).toEqual({ A: '1' })
|
||||
expect(launchCalls).toEqual([])
|
||||
expect(await withHostAgentApiKeyLaunchEnv({ A: '1' }, 'cursor', 't-devbox')).toEqual({
|
||||
A: '1',
|
||||
CURSOR_API_KEY: 'key_real'
|
||||
})
|
||||
expect(await withHostAgentApiKeyLaunchEnv(undefined, 'cursor', null)).toEqual({
|
||||
CURSOR_API_KEY: 'key_real'
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,126 @@
|
||||
// Desktop-sealed agent API keys (Settings → Agent API Keys) and Orca Cloud workspaces. On any other
|
||||
// host those keys ride each agent launch as plain env. An Orca Cloud VM must never hold a model key,
|
||||
// so they are not sent there at all: the user saves a key as a personal Cloud secret instead (one key
|
||||
// per click), and the VM then gets a placeholder the egress proxy swaps.
|
||||
import {
|
||||
resolveAgentApiKeyLaunchEnv,
|
||||
withAgentApiKeyLaunchEnv
|
||||
} from '../agent-api-keys/agent-api-key-launch-env'
|
||||
import { withAgentApiKeyRuntimeEnv } from '../agent-api-keys/agent-api-key-runtime-call'
|
||||
import { isCloudSshAlias } from '../cloud-ssh/cloud-ssh-config'
|
||||
import { getSshTargetRegistryStore } from '../ssh/targets/ssh-target-registry'
|
||||
import { listEphemeralVmRuntimes } from '../../shared/ephemeral-vm-runtime-store'
|
||||
import { resolveEnvironment } from '../../shared/remote-runtime/host-store/runtime-environment-store'
|
||||
import { getConnectionExecutionHostId, toRuntimeExecutionHostId } from '../../shared/execution-host'
|
||||
import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent'
|
||||
|
||||
// Set once the desktop starts (registerCloudSecretsHandlers); this module stays free of Electron
|
||||
// because launch assembly that the headless runtime also loads imports it.
|
||||
let desktopUserDataPath: string | null = null
|
||||
export function setCloudDesktopKeysUserDataPath(path: string): void {
|
||||
desktopUserDataPath = path
|
||||
}
|
||||
|
||||
/** Orca Cloud sandboxes answer on Vercel Sandbox routes. */
|
||||
const ORCA_CLOUD_ENDPOINT_HOST = /\.vercel\.run$/i
|
||||
|
||||
function endpointHost(endpoint: string): string | null {
|
||||
try {
|
||||
return new URL(endpoint).hostname
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `environmentId` is an Orca Cloud VM. Fails closed: a VM-provisioned host this desktop has no
|
||||
* provider record for, or any host on a Vercel Sandbox route, counts as Orca Cloud.
|
||||
*/
|
||||
export function isOrcaCloudRuntimeEnvironment(
|
||||
userDataPath: string,
|
||||
environmentId: string
|
||||
): boolean {
|
||||
const runtime = listEphemeralVmRuntimes(userDataPath).find(
|
||||
(record) => record.runtimeEnvironmentId === environmentId
|
||||
)
|
||||
if (runtime) {
|
||||
return runtime.recipe?.provider === 'orca-cloud' || runtime.recipe?.provider === undefined
|
||||
}
|
||||
let environment: ReturnType<typeof resolveEnvironment> | null = null
|
||||
try {
|
||||
environment = resolveEnvironment(userDataPath, environmentId)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
if (environment.source === 'ephemeral-vm') {
|
||||
return true
|
||||
}
|
||||
return (environment.endpoints ?? []).some((endpoint) => {
|
||||
const host = endpointHost(endpoint.endpoint)
|
||||
return host !== null && ORCA_CLOUD_ENDPOINT_HOST.test(host)
|
||||
})
|
||||
}
|
||||
|
||||
/** A host id no host-scoped key names, so only keys set for every host match (the ones a new VM would get). */
|
||||
const ANY_CLOUD_HOST = toRuntimeExecutionHostId('orca-cloud')
|
||||
|
||||
/** The sealed value of the desktop key `envName` for `agent`, unsealed for one cloud write. */
|
||||
export async function desktopKeyValueForCloud(
|
||||
agent: TuiAgent,
|
||||
envName: string
|
||||
): Promise<string | null> {
|
||||
const env = await resolveAgentApiKeyLaunchEnv(agent, ANY_CLOUD_HOST)
|
||||
return env[envName] ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* A runtime call's params with this computer's Agent API Keys for the agent it starts, except on an
|
||||
* Orca Cloud VM: there they would sit in plaintext, so the user saves them as Cloud secrets instead
|
||||
* (the VM then only sees egress placeholders).
|
||||
*/
|
||||
export async function withHostAgentApiKeyEnv(
|
||||
environmentId: string,
|
||||
method: string,
|
||||
params: unknown,
|
||||
readStatus: Parameters<typeof withAgentApiKeyRuntimeEnv>[3]
|
||||
): Promise<unknown> {
|
||||
// Without the desktop's records nothing can be ruled out, so no keys go anywhere.
|
||||
if (
|
||||
desktopUserDataPath === null ||
|
||||
isOrcaCloudRuntimeEnvironment(desktopUserDataPath, environmentId)
|
||||
) {
|
||||
return params
|
||||
}
|
||||
return withAgentApiKeyRuntimeEnv(environmentId, method, params, readStatus)
|
||||
}
|
||||
|
||||
/**
|
||||
* An SSH target that reaches an Orca Cloud workspace (`orca ssh` writes `orca-*` aliases that proxy
|
||||
* through the Orca CLI; OpenSSH config Includes can surface them as targets).
|
||||
*/
|
||||
export function isOrcaCloudSshConnection(connectionId: string | null | undefined): boolean {
|
||||
if (!connectionId) {
|
||||
return false
|
||||
}
|
||||
const target = getSshTargetRegistryStore()?.getTarget(connectionId)
|
||||
if (!target) {
|
||||
return false
|
||||
}
|
||||
return (
|
||||
[target.configHost, target.host, target.label].some(
|
||||
(value) => value !== undefined && isCloudSshAlias(value)
|
||||
) || /\bssh-proxy\b/.test(target.proxyCommand ?? '')
|
||||
)
|
||||
}
|
||||
|
||||
/** A local or SSH launch env with this computer's Agent API Keys, except over SSH into an Orca Cloud workspace. */
|
||||
export async function withHostAgentApiKeyLaunchEnv(
|
||||
env: Record<string, string> | undefined,
|
||||
agent: TuiAgent | undefined,
|
||||
connectionId: string | null | undefined
|
||||
): Promise<Record<string, string> | undefined> {
|
||||
if (isOrcaCloudSshConnection(connectionId)) {
|
||||
return env
|
||||
}
|
||||
return withAgentApiKeyLaunchEnv(env, agent, getConnectionExecutionHostId(connectionId))
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { ReadSnapshot } from '../../shared/cloud-workspaces/read-snapshot'
|
||||
import { createCloudReadMemo } from './cloud-offline-cloud-read'
|
||||
|
||||
const snap: ReadSnapshot = {
|
||||
v: 1,
|
||||
workspaceId: 'sbx',
|
||||
snapshotId: 'snap',
|
||||
capturedAt: 1,
|
||||
reason: 'sleep',
|
||||
git: null,
|
||||
pr: null,
|
||||
sessions: []
|
||||
}
|
||||
|
||||
describe('createCloudReadMemo', () => {
|
||||
it('reads once per workspace while fresh, again after forget', async () => {
|
||||
const read = vi.fn(async () => snap)
|
||||
const memo = createCloudReadMemo(read)
|
||||
expect(await memo.get('w')).toBe(snap)
|
||||
expect(await memo.get('w')).toBe(snap)
|
||||
expect(read).toHaveBeenCalledTimes(1)
|
||||
memo.forget('w')
|
||||
await memo.get('w')
|
||||
expect(read).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('never throws and never waits past its budget; a late answer serves the next call', async () => {
|
||||
let resolve: (value: ReadSnapshot) => void = () => {}
|
||||
const read = vi.fn(() => new Promise<ReadSnapshot>((r) => (resolve = r)))
|
||||
const memo = createCloudReadMemo(read, { waitMs: 10 })
|
||||
expect(await memo.get('w')).toBeNull()
|
||||
resolve(snap)
|
||||
expect(await memo.get('w')).toBe(snap)
|
||||
expect(read).toHaveBeenCalledTimes(1)
|
||||
const failing = createCloudReadMemo(async () => {
|
||||
throw new Error('offline')
|
||||
})
|
||||
expect(await failing.get('w')).toBeNull()
|
||||
})
|
||||
|
||||
it('is a no-op without a reader', async () => {
|
||||
expect(await createCloudReadMemo(undefined).get('w')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,82 @@
|
||||
// The asleep view's reads of a workspace's sealed sleep snapshot (Orca Cloud), memoized: the
|
||||
// snapshot only changes when the workspace wakes and sleeps again, and the view polls.
|
||||
import type { ReadSnapshot } from '../../shared/cloud-workspaces/read-snapshot'
|
||||
import type { CloudOfflineSnapshot } from '../../shared/hosted-sandbox/cloud-workspace-offline-api'
|
||||
import type { CloudOfflineCache } from './cloud-offline-cache'
|
||||
import { buildOfflineSnapshot } from './cloud-offline-snapshot'
|
||||
import { mergeCloudReadSnapshot } from './cloud-offline-snapshot-merge'
|
||||
|
||||
/** The workspace's sealed sleep snapshot opened on this device, or null (none, unreadable). */
|
||||
export type CloudSnapshotReader = (workspaceId: string) => Promise<ReadSnapshot | null>
|
||||
|
||||
const TTL_MS = 2 * 60_000
|
||||
const FAILED_TTL_MS = 30_000
|
||||
/** The asleep view never waits long on the network; a slow read lands on the next poll. */
|
||||
const WAIT_MS = 3_000
|
||||
|
||||
type Entry = { at: number; ttl: number; promise: Promise<ReadSnapshot | null> }
|
||||
|
||||
export function createCloudReadMemo(
|
||||
read: CloudSnapshotReader | undefined,
|
||||
options: { waitMs?: number; now?: () => number } = {}
|
||||
) {
|
||||
const now = options.now ?? Date.now
|
||||
const entries = new Map<string, Entry>()
|
||||
const memo = {
|
||||
/** Resolves null (never throws) when there is none, it failed, or it is not back in time. */
|
||||
async get(workspaceId: string): Promise<ReadSnapshot | null> {
|
||||
if (!read) {
|
||||
return null
|
||||
}
|
||||
let entry = entries.get(workspaceId)
|
||||
if (!entry || now() - entry.at >= entry.ttl) {
|
||||
const fresh: Entry = {
|
||||
at: now(),
|
||||
ttl: TTL_MS,
|
||||
promise: read(workspaceId).catch(() => null)
|
||||
}
|
||||
void fresh.promise.then((value) => {
|
||||
if (value === null) {
|
||||
fresh.ttl = FAILED_TTL_MS
|
||||
}
|
||||
})
|
||||
entries.set(workspaceId, fresh)
|
||||
entry = fresh
|
||||
}
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
const late = new Promise<null>((resolve) => {
|
||||
timer = setTimeout(() => resolve(null), options.waitMs ?? WAIT_MS)
|
||||
})
|
||||
try {
|
||||
return await Promise.race([entry.promise, late])
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
}
|
||||
},
|
||||
/** Awake again: the next sleep leaves a new snapshot. */
|
||||
forget(workspaceId: string): void {
|
||||
entries.delete(workspaceId)
|
||||
},
|
||||
clear(): void {
|
||||
entries.clear()
|
||||
},
|
||||
/**
|
||||
* The asleep view: this computer's cached copy, with newer sections from the workspace's own
|
||||
* sleep snapshot while it is asleep. Any cloud failure leaves the cached copy as it was.
|
||||
*/
|
||||
async snapshot(
|
||||
cache: CloudOfflineCache,
|
||||
info: { environmentId: string; asleep: boolean },
|
||||
workspaceId: string
|
||||
): Promise<CloudOfflineSnapshot> {
|
||||
const local = await buildOfflineSnapshot(cache, info.environmentId, workspaceId, info.asleep)
|
||||
if (!info.asleep) {
|
||||
memo.forget(workspaceId)
|
||||
return local
|
||||
}
|
||||
const remote = await memo.get(workspaceId)
|
||||
return remote ? mergeCloudReadSnapshot(local, remote) : local
|
||||
}
|
||||
}
|
||||
return memo
|
||||
}
|
||||
@@ -29,12 +29,8 @@ import {
|
||||
import { createOwedWorkBeat } from './cloud-offline-beat'
|
||||
import { setCloudOfflineReset } from './cloud-offline-reset'
|
||||
import { safeStorageCodec, setCloudOfflineObserver } from './cloud-offline-seam'
|
||||
import {
|
||||
archiveCheckoutsFromCache,
|
||||
buildOfflineSnapshot,
|
||||
stringParam,
|
||||
terminalHandlesOf
|
||||
} from './cloud-offline-snapshot'
|
||||
import { archiveCheckoutsFromCache, stringParam, terminalHandlesOf } from './cloud-offline-snapshot'
|
||||
import { createCloudReadMemo, type CloudSnapshotReader } from './cloud-offline-cloud-read'
|
||||
import { getHostedWorkspaceService, setArchiveCheckoutsProvider } from './hosted-workspace-service'
|
||||
|
||||
type CloudRuntimeInfo = {
|
||||
@@ -71,6 +67,11 @@ export function installCloudOfflineService(deps: {
|
||||
windows: () => readonly BrowserWindow[]
|
||||
/** The control plane says the workspace is archived (nothing wakes or sends to it). */
|
||||
isArchived: (workspaceId: string) => Promise<boolean>
|
||||
/**
|
||||
* The workspace's own sealed sleep snapshot, opened on this device (never wakes it). Null when
|
||||
* there is none or it cannot be read; the view then shows this computer's copy alone.
|
||||
*/
|
||||
readCloudSnapshot?: CloudSnapshotReader
|
||||
codec?: OfflineCacheCodec | null
|
||||
log?: (line: string) => void
|
||||
}): CloudOfflineService {
|
||||
@@ -122,6 +123,8 @@ export function installCloudOfflineService(deps: {
|
||||
memo = null
|
||||
}
|
||||
|
||||
const cloudReads = createCloudReadMemo(deps.readCloudSnapshot)
|
||||
|
||||
const broadcast = (channel: string, payload: unknown): void => {
|
||||
for (const window of deps.windows()) {
|
||||
if (!window.isDestroyed()) {
|
||||
@@ -252,6 +255,7 @@ export function installCloudOfflineService(deps: {
|
||||
}
|
||||
})
|
||||
setCloudOfflineReset(() => {
|
||||
cloudReads.clear()
|
||||
void cache.clear()
|
||||
queue.clear()
|
||||
})
|
||||
@@ -274,9 +278,7 @@ export function installCloudOfflineService(deps: {
|
||||
async (_event, args: { workspaceId: string }): Promise<CloudOfflineSnapshot | null> => {
|
||||
invalidate()
|
||||
const info = runtimes().byWorkspace.get(args.workspaceId)
|
||||
return info
|
||||
? await buildOfflineSnapshot(cache, info.environmentId, args.workspaceId, info.asleep)
|
||||
: null
|
||||
return info ? await cloudReads.snapshot(cache, info, args.workspaceId) : null
|
||||
}
|
||||
)
|
||||
ipcMain.handle(
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { ReadSnapshot } from '../../shared/cloud-workspaces/read-snapshot'
|
||||
import type { CloudOfflineSnapshot } from '../../shared/hosted-sandbox/cloud-workspace-offline-api'
|
||||
import { mergeCloudReadSnapshot } from './cloud-offline-snapshot-merge'
|
||||
|
||||
const local: CloudOfflineSnapshot = {
|
||||
workspaceId: 'w',
|
||||
asleep: true,
|
||||
capturedAt: 1_000,
|
||||
git: {
|
||||
branch: 'old',
|
||||
head: 'aaa',
|
||||
changes: [{ path: 'a.ts', status: 'modified', area: 'unstaged' }],
|
||||
changeCount: 1,
|
||||
commits: [],
|
||||
at: 1_000
|
||||
},
|
||||
terminals: [{ handle: 'h', title: null, lines: ['x'], at: 1_000 }],
|
||||
chats: [
|
||||
{ sessionId: 's1', at: 1_000, messages: [{ itemId: 'a', role: 'user', text: 'hi', at: 1 }] },
|
||||
{ sessionId: 's9', at: 900, messages: [{ itemId: 'z', role: 'user', text: 'kept', at: 1 }] }
|
||||
],
|
||||
source: 'device'
|
||||
}
|
||||
|
||||
function remote(capturedAt: number): ReadSnapshot {
|
||||
return {
|
||||
v: 1,
|
||||
workspaceId: 'sbx',
|
||||
snapshotId: 'snap',
|
||||
capturedAt,
|
||||
reason: 'sleep',
|
||||
git: {
|
||||
branch: 'new',
|
||||
head: 'bbb',
|
||||
changes: [{ path: 'b.ts', status: 'added', area: 'untracked', added: 5, removed: 0 }],
|
||||
changeCount: 1,
|
||||
added: 5,
|
||||
removed: 0,
|
||||
commits: []
|
||||
},
|
||||
pr: {
|
||||
number: 7,
|
||||
title: 'PR',
|
||||
state: 'open',
|
||||
url: 'https://github.com/a/b/pull/7',
|
||||
checksStatus: 'success',
|
||||
checksSummary: null
|
||||
},
|
||||
sessions: [
|
||||
{
|
||||
sessionId: 's1',
|
||||
agent: 'claude',
|
||||
title: 'T',
|
||||
status: 'idle',
|
||||
turnOutcome: 'done',
|
||||
updatedAt: null,
|
||||
messages: [{ itemId: 'b', role: 'assistant', text: 'newer', at: 2 }],
|
||||
truncated: false
|
||||
},
|
||||
{
|
||||
sessionId: 's2',
|
||||
agent: 'codex',
|
||||
title: null,
|
||||
status: 'working',
|
||||
turnOutcome: null,
|
||||
updatedAt: null,
|
||||
messages: [{ itemId: 'c', role: 'user', text: 'only in cloud', at: 2 }],
|
||||
truncated: false
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
describe('mergeCloudReadSnapshot', () => {
|
||||
it('takes newer cloud sections, keeps terminals and chats the snapshot lacks', () => {
|
||||
const merged = mergeCloudReadSnapshot(local, remote(2_000))
|
||||
expect(merged.git).toMatchObject({ branch: 'new', at: 2_000, added: 5 })
|
||||
expect(merged.git?.changes[0]).toMatchObject({ path: 'b.ts', added: 5 })
|
||||
expect(merged.terminals).toEqual(local.terminals)
|
||||
expect(merged.chats.map((chat) => chat.sessionId)).toEqual(['s1', 's2', 's9'])
|
||||
expect(merged.chats[0]).toMatchObject({ agent: 'claude', title: 'T' })
|
||||
expect(merged.chats[0]!.messages[0]!.text).toBe('newer')
|
||||
expect(merged.pr?.number).toBe(7)
|
||||
expect(merged.capturedAt).toBe(2_000)
|
||||
expect(merged.source).toBe('mixed')
|
||||
})
|
||||
|
||||
it('keeps the local copy where it is newer, but adds what only the cloud has', () => {
|
||||
const merged = mergeCloudReadSnapshot(local, remote(500))
|
||||
expect(merged.git?.branch).toBe('old')
|
||||
expect(merged.chats.find((chat) => chat.sessionId === 's1')!.messages[0]!.text).toBe('hi')
|
||||
expect(merged.chats.some((chat) => chat.sessionId === 's2')).toBe(true)
|
||||
expect(merged.pr?.number).toBe(7)
|
||||
expect(merged.capturedAt).toBe(1_000)
|
||||
})
|
||||
|
||||
it('fills an empty local cache entirely from the cloud', () => {
|
||||
const empty: CloudOfflineSnapshot = {
|
||||
workspaceId: 'w',
|
||||
asleep: true,
|
||||
capturedAt: null,
|
||||
git: null,
|
||||
terminals: [],
|
||||
chats: []
|
||||
}
|
||||
const merged = mergeCloudReadSnapshot(empty, remote(2_000))
|
||||
expect(merged.capturedAt).toBe(2_000)
|
||||
expect(merged.source).toBe('cloud')
|
||||
expect(merged.git?.branch).toBe('new')
|
||||
expect(merged.chats).toHaveLength(2)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,62 @@
|
||||
// Folds a sleeping workspace's sealed read snapshot (Orca Cloud) into this computer's cached copy.
|
||||
import type { ReadSnapshot } from '../../shared/cloud-workspaces/read-snapshot'
|
||||
import type { CloudOfflineSnapshot } from '../../shared/hosted-sandbox/cloud-workspace-offline-api'
|
||||
|
||||
const MAX_CHANGES = 300
|
||||
|
||||
/**
|
||||
* Folds the workspace's own sealed sleep snapshot into this computer's cached copy: each section
|
||||
* (git, each chat) comes from whichever is newer, so the view is never older than either. The cache
|
||||
* keeps terminals (the snapshot has none); the PR only exists in the snapshot.
|
||||
*/
|
||||
export function mergeCloudReadSnapshot(
|
||||
local: CloudOfflineSnapshot,
|
||||
remote: ReadSnapshot
|
||||
): CloudOfflineSnapshot {
|
||||
const at = remote.capturedAt
|
||||
let fromCloud = false
|
||||
let git = local.git
|
||||
if (remote.git && (!local.git || at > local.git.at)) {
|
||||
fromCloud = true
|
||||
git = {
|
||||
branch: remote.git.branch,
|
||||
head: remote.git.head,
|
||||
changes: remote.git.changes.slice(0, MAX_CHANGES).map((change) => ({ ...change })),
|
||||
changeCount: remote.git.changeCount,
|
||||
commits: remote.git.commits.map((commit) => ({ ...commit })),
|
||||
at,
|
||||
added: remote.git.added,
|
||||
removed: remote.git.removed
|
||||
}
|
||||
}
|
||||
const chats = new Map(local.chats.map((chat) => [chat.sessionId, chat]))
|
||||
for (const session of remote.sessions) {
|
||||
const known = chats.get(session.sessionId)
|
||||
// A session the snapshot saw with no messages adds nothing a cached transcript lacks.
|
||||
if (session.messages.length === 0 && known) {
|
||||
continue
|
||||
}
|
||||
if (!known || at > known.at) {
|
||||
fromCloud = true
|
||||
chats.set(session.sessionId, {
|
||||
sessionId: session.sessionId,
|
||||
at,
|
||||
messages: session.messages.map((message) => ({ ...message })),
|
||||
agent: session.agent,
|
||||
title: session.title
|
||||
})
|
||||
}
|
||||
}
|
||||
const pr = remote.pr ? { ...remote.pr } : (local.pr ?? null)
|
||||
fromCloud ||= pr !== null && local.pr == null
|
||||
const hadLocal = local.capturedAt !== null
|
||||
const times = [local.capturedAt ?? 0, fromCloud ? at : 0].filter((time) => time > 0)
|
||||
return {
|
||||
...local,
|
||||
capturedAt: times.length > 0 ? Math.max(...times) : null,
|
||||
git,
|
||||
chats: [...chats.values()].sort((a, b) => b.at - a.at),
|
||||
pr,
|
||||
source: !fromCloud ? (local.source ?? 'device') : hadLocal ? 'mixed' : 'cloud'
|
||||
}
|
||||
}
|
||||
@@ -227,7 +227,8 @@ export async function buildOfflineSnapshot(
|
||||
capturedAt: times.length > 0 ? Math.max(...times) : null,
|
||||
git,
|
||||
terminals,
|
||||
chats
|
||||
chats,
|
||||
source: 'device'
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ import { createHostedSandboxDeviceEnroller } from './hosted-sandbox-device-enrol
|
||||
import { registerOrcaCloudDeviceEnroller } from '../runtime/rpc/methods/orca-cloud/orca-cloud-device-enrollment'
|
||||
import type { HostedSandboxControlPlaneClient } from './hosted-sandbox-control-plane-client'
|
||||
import { registerCloudRemoteDesktopHandlers } from '../ipc/cloud-remote-desktop'
|
||||
import { readCloudWorkspaceSnapshot } from '../ipc/cloud-workspaces'
|
||||
import {
|
||||
ORCA_CLOUD_RECIPE,
|
||||
createHostedSandboxRecipeClient,
|
||||
@@ -157,6 +158,11 @@ export function installHostedSandbox(repos?: OrcaCloudEnvironmentRepoSource): vo
|
||||
return found
|
||||
? (await client.workspaceStatus(found.sandboxId)).status.state === 'archived'
|
||||
: false
|
||||
},
|
||||
readCloudSnapshot: async (workspaceId) => {
|
||||
const found = findCloudRuntime(userDataPath, workspaceId)
|
||||
const read = found ? await readCloudWorkspaceSnapshot(found.sandboxId) : null
|
||||
return read?.state === 'ready' ? read.snapshot : null
|
||||
}
|
||||
})
|
||||
setCloudOfflineService(offline)
|
||||
|
||||
@@ -11,6 +11,13 @@ import {
|
||||
createCloudWorkspacesService,
|
||||
type CloudWorkspacesService
|
||||
} from '../cloud-workspaces/cloud-workspaces-service'
|
||||
import {
|
||||
getCloudReaderKeyStore,
|
||||
setCloudReaderKeyRevoker
|
||||
} from '../cloud-workspaces/cloud-reader-key-store'
|
||||
import type { ReaderKeyAccess } from '../cloud-workspaces/cloud-read-snapshot-reader'
|
||||
import { ensureActiveOrcaProfile } from '../orca-profiles/profile-index-store'
|
||||
import type { CloudReadSnapshotState } from '../../shared/cloud-workspaces/read-snapshot-state'
|
||||
|
||||
const Id = z.string().regex(/^sbx_[0-9a-f]{24}$/)
|
||||
const GrantId = z.string().regex(/^grt_[0-9a-f]{24}$/)
|
||||
@@ -60,8 +67,11 @@ function getService(): Promise<CloudWorkspacesService | null> {
|
||||
service = createCloudWorkspacesService({
|
||||
userDataPath,
|
||||
config,
|
||||
clientId: await clientIdFor(userDataPath)
|
||||
clientId: await clientIdFor(userDataPath),
|
||||
readerKey: profileReaderKey(userDataPath)
|
||||
})
|
||||
const started = service
|
||||
setCloudReaderKeyRevoker((timeoutMs) => started.revokeReaderKey(timeoutMs))
|
||||
return service
|
||||
})()
|
||||
servicePromise = starting
|
||||
@@ -74,6 +84,38 @@ function getService(): Promise<CloudWorkspacesService | null> {
|
||||
return starting
|
||||
}
|
||||
|
||||
/** The active Orca profile's reader key; registrations follow its signed-in user and account. */
|
||||
function profileReaderKey(userDataPath: string): ReaderKeyAccess {
|
||||
return {
|
||||
identity: () => {
|
||||
const active = ensureActiveOrcaProfile(userDataPath)
|
||||
const cloud = active.profile.cloud
|
||||
return cloud
|
||||
? JSON.stringify([active.profile.id, cloud.userId ?? null, cloud.activeOrgId ?? null])
|
||||
: null
|
||||
},
|
||||
load: () =>
|
||||
getCloudReaderKeyStore(userDataPath).load(ensureActiveOrcaProfile(userDataPath).profile.id),
|
||||
peek: () =>
|
||||
getCloudReaderKeyStore(userDataPath).peek(ensureActiveOrcaProfile(userDataPath).profile.id)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The owner's asleep view merges this in (main process). Null when it cannot be read (no control
|
||||
* plane, keychain, network); the view then keeps showing this computer's own copy.
|
||||
*/
|
||||
export async function readCloudWorkspaceSnapshot(
|
||||
sandboxId: string
|
||||
): Promise<CloudReadSnapshotState | null> {
|
||||
if (!Id.safeParse(sandboxId).success) {
|
||||
return null
|
||||
}
|
||||
const s = await getService().catch(() => null)
|
||||
const result = await s?.readSnapshot(sandboxId)
|
||||
return result?.ok ? result.value : null
|
||||
}
|
||||
|
||||
/** Stable per-install id for presence rows (one row per device, not per window). */
|
||||
async function clientIdFor(userDataPath: string): Promise<string> {
|
||||
const file = join(userDataPath, 'cloud-workspaces-client-id')
|
||||
@@ -187,6 +229,11 @@ export function registerCloudWorkspacesHandlers(): void {
|
||||
const s = await getService()
|
||||
return !s ? NOT_CONFIGURED : parsed.success ? s.openGrant(parsed.data.id) : INVALID
|
||||
})
|
||||
handle('cloudWorkspaces:readSnapshot', async (args) => {
|
||||
const parsed = z.object({ id: Id }).safeParse(args)
|
||||
const s = await getService()
|
||||
return !s ? NOT_CONFIGURED : parsed.success ? s.readSnapshot(parsed.data.id) : INVALID
|
||||
})
|
||||
handle('cloudWorkspaces:listGrants', async (args) => {
|
||||
const parsed = z.object({ id: Id }).safeParse(args)
|
||||
const s = await getService()
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { withClaudeAgentViewPlugin } from '../../../shared/claude-agent-view-launch'
|
||||
import { getConnectionExecutionHostId } from '../../../shared/execution-host'
|
||||
import { withAgentApiKeyLaunchEnv } from '../../agent-api-keys/agent-api-key-launch-env'
|
||||
import { withHostAgentApiKeyLaunchEnv } from '../../hosted-sandbox/cloud-desktop-keys'
|
||||
import { resolveStartupShell } from '../../../shared/agent-launch/startup/tui-agent-startup-shell'
|
||||
import { resolveLocalWindowsAgentStartupShell } from '../../../shared/windows-terminal-shell'
|
||||
import { getAppEnvironment } from '../../../shared/app-environment'
|
||||
@@ -156,11 +155,7 @@ export async function assemblePtySpawnLaunchOptions(input: PtySpawnLaunchOptions
|
||||
const env =
|
||||
input.preAdoptedStablePane || input.launchCommand === undefined
|
||||
? openCodeLaunch.env
|
||||
: await withAgentApiKeyLaunchEnv(
|
||||
openCodeLaunch.env,
|
||||
launchAgent,
|
||||
getConnectionExecutionHostId(connectionId)
|
||||
)
|
||||
: await withHostAgentApiKeyLaunchEnv(openCodeLaunch.env, launchAgent, connectionId)
|
||||
const pluginDir = !connectionId ? env?.ORCA_CLAUDE_AGENT_VIEW_PLUGIN_DIR : undefined
|
||||
const launchCommand =
|
||||
pluginDir && openCodeLaunch.command
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
vi.mock('../../workspace-ports/workspace-port-block-registry', () => ({
|
||||
getWorkspacePortBlockForWorktreeId: async (worktreeId: string) =>
|
||||
worktreeId.endsWith('/a') ? { base: 21000, count: 10 } : { base: 21010, count: 10 }
|
||||
}))
|
||||
|
||||
const { stampWorkspacePortEnv, stampPtySpawnPaneEnv } = await import('./spawn-pane-env')
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs()
|
||||
})
|
||||
|
||||
describe('workspace port env', () => {
|
||||
it('gives each workspace its own block even when the host process has ORCA_PORT (VM launcher)', async () => {
|
||||
vi.stubEnv('ORCA_PORT', '3000')
|
||||
const a: Record<string, string> = { ORCA_PORT: '3000', CONDUCTOR_PORT: '3000' }
|
||||
const b: Record<string, string> = { ORCA_PORT: '3000', CONDUCTOR_PORT: '3000' }
|
||||
await stampWorkspacePortEnv(a, 'repo::/w/a')
|
||||
await stampWorkspacePortEnv(b, 'repo::/w/b')
|
||||
expect(a).toEqual({ ORCA_PORT: '21000', ORCA_PORT_COUNT: '10', CONDUCTOR_PORT: '21000' })
|
||||
expect(b).toEqual({ ORCA_PORT: '21010', ORCA_PORT_COUNT: '10', CONDUCTOR_PORT: '21010' })
|
||||
})
|
||||
|
||||
it('scrubs an inherited block from a spawn that names no pane', () => {
|
||||
const env: Record<string, string> = {
|
||||
ORCA_PORT: '3000',
|
||||
ORCA_PORT_COUNT: '10',
|
||||
CONDUCTOR_PORT: '3000'
|
||||
}
|
||||
stampPtySpawnPaneEnv(env, { pane: null, jcodeRuntimeDir: undefined })
|
||||
expect(env.ORCA_PORT).toBeUndefined()
|
||||
expect(env.CONDUCTOR_PORT).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -95,6 +95,8 @@ export async function stampWorkspacePortEnv(
|
||||
return
|
||||
}
|
||||
try {
|
||||
// Always the workspace's own block: a host env's ORCA_PORT (a VM launcher sets one) would make
|
||||
// every workspace on that host share it.
|
||||
const block = await getWorkspacePortBlockForWorktreeId(worktreeId)
|
||||
if (block) {
|
||||
Object.assign(env, buildWorkspacePortEnv(block))
|
||||
|
||||
@@ -157,7 +157,7 @@ export class AuthCallbackForward {
|
||||
ok: false,
|
||||
code: busy ? 'port_busy' : 'listen_failed',
|
||||
message: busy
|
||||
? `Port ${this.request.port} is busy on this computer.`
|
||||
? `Port ${this.request.port} is in use on this computer.`
|
||||
: 'Orca could not listen for the sign-in on this computer.'
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ import { getRuntimeEnvironmentStatus } from './runtime-environment-status-probe'
|
||||
import { noteRuntimeEnvironmentConnectRequested } from './runtime-environment-pairing-refusal-registry'
|
||||
import { publicRuntimeEnvironmentWithHostKey } from './runtime-environment-host-key'
|
||||
import { withWslOrcadAccountEnv } from '../../wsl/orcad/wsl-orcad-account-env'
|
||||
import { withAgentApiKeyRuntimeEnv } from '../../agent-api-keys/agent-api-key-runtime-call'
|
||||
import { withHostAgentApiKeyEnv } from '../../hosted-sandbox/cloud-desktop-keys'
|
||||
import { clearSshCredentialDeclinedForEnvironment } from '../../ssh/authentication/ssh-credential-decline'
|
||||
import {
|
||||
disconnectManagedHostOfEnvironmentForUser,
|
||||
@@ -287,7 +287,7 @@ function registerPassiveCallHandler(
|
||||
getUserDataPath(),
|
||||
environment.id,
|
||||
args.method,
|
||||
await withAgentApiKeyRuntimeEnv(environment.id, args.method, accounts.params, () =>
|
||||
await withHostAgentApiKeyEnv(environment.id, args.method, accounts.params, () =>
|
||||
callRuntimeEnvironment(getUserDataPath(), environment.id, 'status.get', undefined)
|
||||
),
|
||||
args.timeoutMs,
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
import { createHash, randomBytes } from 'node:crypto'
|
||||
import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record'
|
||||
import {
|
||||
AGENT_SESSION_CHECKPOINT_PREVIEW_PATHS,
|
||||
AGENT_SESSION_CHECKPOINT_UNDO_ID,
|
||||
agentSessionCheckpointPartialMessage,
|
||||
agentSessionCheckpointRefusalMessage,
|
||||
@@ -157,6 +158,9 @@ export function createAgentSessionCheckpoints(deps: AgentSessionCheckpointsDeps)
|
||||
return {
|
||||
available: true,
|
||||
changedFiles: changes.length,
|
||||
paths: [...new Set(changes.map((change) => change.path))]
|
||||
.sort()
|
||||
.slice(0, AGENT_SESSION_CHECKPOINT_PREVIEW_PATHS),
|
||||
headMoved,
|
||||
createdAt: found.checkpoint.createdAt,
|
||||
busy:
|
||||
|
||||
+6
-1
@@ -180,7 +180,12 @@ describe('rewind with file restore', () => {
|
||||
expect(await git('stash', 'list')).toBe('')
|
||||
|
||||
const preview = await hostAgentSessionCheckpoints(host).preview(HOST_TEST_SESSION, second)
|
||||
expect(preview).toMatchObject({ available: true, changedFiles: 3, headMoved: false })
|
||||
expect(preview).toMatchObject({
|
||||
available: true,
|
||||
changedFiles: 3,
|
||||
paths: ['app.ts', 'feature.ts', 'refactor/util.ts'],
|
||||
headMoved: false
|
||||
})
|
||||
const restored = await hostAgentSessionCheckpoints(host).restore(HOST_TEST_SESSION, second)
|
||||
expect(restored.changedFiles).toBe(3)
|
||||
expect(await read('app.ts')).toBe('v1\n')
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import { resetCloudOfflineData } from '../hosted-sandbox/cloud-offline-reset'
|
||||
import {
|
||||
clearCloudReaderKey,
|
||||
revokeCloudReaderKeyBestEffort
|
||||
} from '../cloud-workspaces/cloud-reader-key-store'
|
||||
import type {
|
||||
ConnectCurrentOrcaProfileResult,
|
||||
CreateCloudLinkedOrcaProfileArgs,
|
||||
@@ -157,6 +161,11 @@ export async function signOutCurrentOrcaProfile(
|
||||
const active = ensureActiveOrcaProfile(userDataPath)
|
||||
const configState = getOrcaCloudAuthConfig()
|
||||
const session = readCloudSession(active.profile.id, userDataPath)
|
||||
if (session.status === 'found') {
|
||||
// While the session still mints tokens: revoke this device's reader key server-side so no
|
||||
// later sleep seals to it. Bounded (a couple of seconds) and never fails the sign-out.
|
||||
await revokeCloudReaderKeyBestEffort()
|
||||
}
|
||||
// Fence before network I/O so in-flight refreshes cannot save after sign-out.
|
||||
invalidateCloudSessionChanges(active.profile.id, userDataPath)
|
||||
if (!isOrcaCloudDevAuthEnabled() && configState.configured && session.status === 'found') {
|
||||
@@ -175,6 +184,8 @@ export async function signOutCurrentOrcaProfile(
|
||||
const list = unlinkOrcaProfileFromCloud(active.profile.id, userDataPath)
|
||||
// Cached Orca Cloud transcripts and queued prompts belong to the signed-out account.
|
||||
resetCloudOfflineData()
|
||||
// The next account signed in on this profile gets its own reader key.
|
||||
await clearCloudReaderKey(active.profile.id, userDataPath)
|
||||
try {
|
||||
clearRelayRegionPreferenceCache(userDataPath)
|
||||
} catch {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user