fix(cloud): local commands — security review fixes

- orcad: only the owner's desktop may attach/settle; devices paired through a grant are listed
  by orca-sandbox-grant and refused (forks keep their offer's origin id)
- desktop: per-workspace limits (3 waiting, 60/hour), always-allow runs one at a time and 30/hour,
  one banner per burst, refusal floods logged once a minute
- dialog: commands over 20 lines refused; long ones must be scrolled to the end; agent name muted;
  Turn off for this workspace; read delay counts from when a prompt reaches the front
- lookalike spaces and combining marks refused; settled events only close their own workspace's prompt
- executor reports soon after the shell exits even if an escaped process holds the pipes; hard stop
- audit log keeps 3 files, long commands stored as prefix + sha256
- rules expire after 30 days and are cleared when a shared workspace is allowed
This commit is contained in:
Neil
2026-11-10 20:11:56 -08:00
parent aab04d5d0a
commit 3f5f314efc
25 changed files with 564 additions and 125 deletions
File diff suppressed because one or more lines are too long
@@ -36,8 +36,9 @@ fi
offer="$(ORCA_USER_DATA_PATH="$DATA" timeout 30 "$node" "$cli" pair --json --rotate "${scope[@]}" \
--address "$ORCA_PUBLIC_WSS" 2>/dev/null)" || { echo 'pair failed' >&2; exit 1; }
# The offer goes to the sealer on stdin (never argv or disk); only the sealed form is printed.
# Granted devices are listed so orcad can keep owner-only features (local commands) from them.
printf '%s' "$offer" | ORCA_GRANT_ID="$ORCA_GRANT_ID" ORCA_GRANT_RECIPIENT_KEY="$ORCA_GRANT_RECIPIENT_KEY" \
"$node" -e '
ORCA_GRANT_LEDGER="$STATE/grant-devices" "$node" -e '
const crypto = require("node:crypto")
let input = ""
process.stdin.on("data", (c) => (input += c)).on("end", () => {
@@ -46,6 +47,7 @@ process.stdin.on("data", (c) => (input += c)).on("end", () => {
console.error("offer unavailable")
process.exit(1)
}
require("node:fs").appendFileSync(process.env.ORCA_GRANT_LEDGER, res.deviceId + "\n", { mode: 0o600 })
const recipient = Buffer.from(process.env.ORCA_GRANT_RECIPIENT_KEY, "base64")
if (recipient.length !== 32) { console.error("bad key length"); process.exit(2) }
const recipientKey = crypto.createPublicKey({ key: { kty: "OKP", crv: "X25519", x: recipient.toString("base64url") }, format: "jwk" })
@@ -148,6 +148,12 @@ export function explainLocalCommandError(error: unknown): unknown {
'The command contains control or invisible characters, which are never run. Use plain text.'
)
}
if (/too_many_lines/.test(error.message)) {
return new RuntimeClientError(
'invalid_argument',
'The command has more than 20 lines. Ask for something shorter, or a script the person can read.'
)
}
if (/cwd_not_absolute/.test(error.message)) {
return new RuntimeClientError(
'invalid_argument',
@@ -1,14 +1,18 @@
import { createHash } from 'node:crypto'
import { appendFileSync, chmodSync, readFileSync, renameSync, statSync } from 'node:fs'
import { join } from 'node:path'
import type { LocalCommandAuditEntry } from '../../shared/local-commands/local-command-desktop-types'
const MAX_BYTES = 2 * 1024 * 1024
const MAX_READ = 500
const KEPT_FILES = 3
/** Long commands keep their start plus a hash, so a few big entries can't flush the history. */
const MAX_COMMAND_CHARS = 1000
/**
* Append-only record of every request this computer saw and what happened to it: the command,
* folder, decision and exit status. Never the output (it can hold anything the command printed).
* One rotation keeps the previous file as .1.
* Rotates at 2 MB and keeps the two previous files (.1, .2).
*/
export class LocalCommandAuditLog {
private readonly path: string
@@ -20,7 +24,16 @@ export class LocalCommandAuditLog {
append(entry: LocalCommandAuditEntry): void {
try {
this.rotateIfFull()
appendFileSync(this.path, `${JSON.stringify(entry)}\n`, { encoding: 'utf8', mode: 0o600 })
const long = entry.command.length > MAX_COMMAND_CHARS
const stored: LocalCommandAuditEntry = long
? {
...entry,
command: entry.command.slice(0, MAX_COMMAND_CHARS),
commandLength: entry.command.length,
commandSha256: createHash('sha256').update(entry.command).digest('hex')
}
: entry
appendFileSync(this.path, `${JSON.stringify(stored)}\n`, { encoding: 'utf8', mode: 0o600 })
} catch (error) {
// The command itself already ran or was refused; a full disk must not crash the request.
console.warn('[local-commands] Could not write the audit log', error)
@@ -31,7 +44,11 @@ export class LocalCommandAuditLog {
recent(limit: number): LocalCommandAuditEntry[] {
const wanted = Math.max(1, Math.min(limit, MAX_READ))
const entries: LocalCommandAuditEntry[] = []
for (const file of [this.path, `${this.path}.1`]) {
const files = [
this.path,
...Array.from({ length: KEPT_FILES - 1 }, (_, i) => `${this.path}.${i + 1}`)
]
for (const file of files) {
let text: string
try {
text = readFileSync(file, 'utf8')
@@ -60,9 +77,17 @@ export class LocalCommandAuditLog {
} catch {
return
}
if (size >= MAX_BYTES) {
renameSync(this.path, `${this.path}.1`)
chmodSync(`${this.path}.1`, 0o600)
if (size < MAX_BYTES) {
return
}
for (let index = KEPT_FILES - 1; index >= 1; index -= 1) {
const from = index === 1 ? this.path : `${this.path}.${index - 1}`
try {
renameSync(from, `${this.path}.${index}`)
chmodSync(`${this.path}.${index}`, 0o600)
} catch {
// A gap in the rotation (first rotations) is fine.
}
}
}
}
@@ -20,7 +20,14 @@ afterEach(() => {
}
})
function setup(options: { policy?: LocalCommandWorkspacePolicy | null; enabled?: boolean } = {}) {
function setup(
options: {
policy?: LocalCommandWorkspacePolicy | null
enabled?: boolean
/** Runs stay in flight until release() is called. */
holdRuns?: boolean
} = {}
) {
const dir = mkdtempSync(join(tmpdir(), 'local-commands-'))
dirs.push(dir)
let clock = 10_000
@@ -34,6 +41,7 @@ function setup(options: { policy?: LocalCommandWorkspacePolicy | null; enabled?:
let prompts: LocalCommandPrompt[] = []
let onEvent: (event: unknown) => void = () => {}
const timers: (() => void)[] = []
const held: (() => void)[] = []
const bridge = createLocalCommandBridge({
settings,
audit,
@@ -56,6 +64,9 @@ function setup(options: { policy?: LocalCommandWorkspacePolicy | null; enabled?:
resolveCwd: async (cwd) => (cwd === '/missing' ? null : '/Users/me'),
execute: async ({ command, cwd }) => {
executed.push({ command, cwd })
if (options.holdRuns) {
await new Promise<void>((resolve) => held.push(resolve))
}
return {
exitCode: 0,
signal: null,
@@ -96,8 +107,25 @@ function setup(options: { policy?: LocalCommandWorkspacePolicy | null; enabled?:
expect(prompts.length + settled.length + executed.length).toBeGreaterThan(0)
})
}
// Sends a request with its own id and lets the bridge's async checks finish.
const send = async (id: string, overrides: Record<string, unknown> = {}): Promise<void> => {
onEvent({
type: 'requested',
requestId: id,
command: 'xcrun simctl list',
cwd: null,
timeoutSec: 60,
reason: null,
agent: null,
expiresInMs: 300_000,
...overrides
})
await new Promise((resolve) => setTimeout(resolve, 5))
}
return {
bridge,
send,
release: () => held.splice(0).forEach((resolve) => resolve()),
settings,
audit,
settled,
@@ -182,4 +210,24 @@ describe('local command bridge', () => {
})
expect(t.executed).toEqual([])
})
it('stops asking after three waiting prompts from one workspace', async () => {
const t = setup()
for (let index = 0; index < 5; index += 1) {
await t.send(`lc_flood${String(index).padStart(14, '0')}`)
}
expect(t.prompts()).toHaveLength(3)
expect(t.settled.filter((s) => s.outcome === 'declined')).toHaveLength(2)
expect(t.executed).toEqual([])
})
it('runs an always-allowed command one at a time and asks about the next one', async () => {
const t = setup({ holdRuns: true })
t.settings.addRule(SANDBOX, 'xcrun simctl list', '/Users/me', 1)
await t.send('lc_rule00000000000000001')
await t.send('lc_rule00000000000000002')
expect(t.executed).toHaveLength(1)
expect(t.prompts().map((p) => p.id)).toEqual(['lc_rule00000000000000002'])
t.release()
})
})
+60 -58
View File
@@ -16,17 +16,19 @@ import {
LocalCommandRequestedEventSchema,
LocalCommandSettledEventSchema,
displayText,
localCommandRefusal,
requestIdOf,
type LocalCommandWorkspacePolicy
requestIdOf
} from './local-command-request-checks'
import { createLocalCommandWorkspacePolicy } from './local-command-workspace-policy'
import { runApprovedLocalCommand, type RequestBase } from './local-command-run'
import {
LOCAL_COMMAND_DESKTOP_LIMITS,
createLocalCommandRequestLimits
} from './local-command-request-limits'
export type { LocalCloudWorkspaceRef, LocalCommandBridgeDeps } from './local-command-bridge-types'
/** A person can't have read a prompt this fresh: an allow that lands sooner is refused. */
export const LOCAL_COMMAND_MIN_DECISION_MS = 600
const POLICY_TTL_MS = 30_000
const HANDLED_LIMIT = 500
type PendingPrompt = {
@@ -52,10 +54,13 @@ export function createLocalCommandBridge(deps: LocalCommandBridgeDeps) {
const setTimer = deps.setTimer ?? defaultTimer
const log = deps.log ?? ((message: string) => console.info(`[local-commands] ${message}`))
const pending = new Map<string, PendingPrompt>()
// Request ids this computer already acted on; a replay after reconnect is never answered twice.
// Environment + request ids this computer already acted on; a replay is never answered twice.
const handled = new Set<string>()
const policyCache = new Map<string, { at: number; value: LocalCommandWorkspacePolicy | null }>()
const labels = new Map<string, string>()
const limits = createLocalCommandRequestLimits()
// The prompt in front and since when: a queued one gets its own read delay when it moves up.
let front: { id: string; since: number } | null = null
const policy = createLocalCommandWorkspacePolicy({ ...deps, now })
const { labelOf, policyOf, refusalOf } = policy
const attachments = createLocalCommandAttachments({
subscribe: deps.subscribe,
setTimer,
@@ -65,43 +70,30 @@ export function createLocalCommandBridge(deps: LocalCommandBridgeDeps) {
if (type === 'requested') {
void onRequested(environmentId, sandboxId, event)
} else if (type === 'settled') {
onSettled(event)
onSettled(environmentId, event)
}
}
})
const labelOf = (sandboxId: string): string => labels.get(sandboxId) ?? sandboxId
function audit(entry: Omit<LocalCommandAuditEntry, 'at' | 'workspaceLabel'>): void {
deps.audit.append({ at: now(), workspaceLabel: labelOf(entry.sandboxId), ...entry })
}
function publishPrompts(): void {
deps.publishPrompts([...pending.values()].map((p) => p.prompt))
const prompts = [...pending.values()].map((p) => p.prompt)
const firstId = prompts[0]?.id ?? null
if (firstId !== front?.id) {
front = firstId ? { id: firstId, since: now() } : null
}
deps.publishPrompts(prompts)
}
async function policyOf(
sandboxId: string,
fresh: boolean
): Promise<LocalCommandWorkspacePolicy | null> {
const cached = policyCache.get(sandboxId)
if (!fresh && cached && now() - cached.at < POLICY_TTL_MS) {
return cached.value
/** Refused without asking; a flood of refusals is logged once a minute. */
function refuse(environmentId: string, base: RequestBase, detail: string): void {
if (limits.shouldLogRefusal(base.sandboxId, now())) {
audit({ ...base, command: base.command.slice(0, 1000), outcome: 'refused', detail })
}
const value = await deps.readPolicy(sandboxId).catch(() => null)
policyCache.set(sandboxId, { at: now(), value })
if (value?.title) {
labels.set(sandboxId, value.title)
}
return value
}
async function refusalOf(sandboxId: string): Promise<string | null> {
const setting = deps.settings.workspace(sandboxId)
if (!deps.supported || !setting?.enabled) {
return localCommandRefusal(deps.supported, setting, null)
}
return localCommandRefusal(deps.supported, setting, await policyOf(sandboxId, true))
decline(environmentId, base.requestId, 'not_allowed')
}
async function settle(
@@ -122,17 +114,18 @@ export function createLocalCommandBridge(deps: LocalCommandBridgeDeps) {
async function onRequested(environmentId: string, sandboxId: string, raw: unknown) {
const requestId = requestIdOf(raw)
if (!requestId || handled.has(requestId) || pending.has(requestId)) {
const key = `${environmentId}\0${requestId}`
if (!requestId || handled.has(key) || pending.has(requestId)) {
return
}
handled.add(requestId)
handled.add(key)
if (handled.size > HANDLED_LIMIT) {
handled.delete(handled.values().next().value!)
}
const parsed = LocalCommandRequestedEventSchema.safeParse(raw)
if (!parsed.success) {
audit({ requestId, sandboxId, command: '', cwd: null, agent: null, outcome: 'refused' })
decline(environmentId, requestId, 'not_allowed')
const blank = { requestId, sandboxId, command: '', cwd: null, agent: null }
refuse(environmentId, blank, 'The request was malformed or had hidden characters.')
return
}
const event = parsed.data
@@ -143,25 +136,28 @@ export function createLocalCommandBridge(deps: LocalCommandBridgeDeps) {
cwd: event.cwd,
agent: displayText(event.agent, 64)
}
const waiting = [...pending.values()].filter((p) => p.prompt.sandboxId === sandboxId).length
if (
waiting >= LOCAL_COMMAND_DESKTOP_LIMITS.pendingPerWorkspace ||
!limits.admitRequest(sandboxId, now())
) {
refuse(environmentId, base, 'Too many requests from this workspace.')
return
}
const refusal = await refusalOf(sandboxId)
if (refusal) {
audit({ ...base, outcome: 'refused', detail: refusal })
decline(environmentId, requestId, 'not_allowed')
refuse(environmentId, base, refusal)
return
}
const cwd = await deps.resolveCwd(event.cwd)
if (!cwd) {
audit({ ...base, outcome: 'refused', detail: 'The folder does not exist on this computer.' })
if ((await settle(environmentId, { requestId, outcome: 'started' }))?.accepted) {
await settle(environmentId, {
requestId,
outcome: 'failed',
message: `The folder ${event.cwd ?? '~'} does not exist on the person's computer.`
})
}
refuse(environmentId, base, 'The folder does not exist on this computer.')
return
}
if (deps.settings.findRule(sandboxId, event.command, cwd)) {
if (
deps.settings.findRule(sandboxId, event.command, cwd, now()) &&
limits.admitAutoRun(sandboxId, now())
) {
await runApproved(environmentId, { ...base, cwd }, event.timeoutSec, 'auto-allowed')
return
}
@@ -173,7 +169,7 @@ export function createLocalCommandBridge(deps: LocalCommandBridgeDeps) {
id: requestId,
sandboxId,
workspaceLabel: labelOf(sandboxId),
shared: policyCache.get(sandboxId)?.value?.shared ?? false,
shared: policy.cached(sandboxId)?.shared ?? false,
command: event.command,
cwd,
timeoutSec: event.timeoutSec,
@@ -189,9 +185,13 @@ export function createLocalCommandBridge(deps: LocalCommandBridgeDeps) {
publishPrompts()
}
}, windowMs)
const firstWaiting = pending.size === 0
pending.set(requestId, { prompt, environmentId, shownAt: now(), timer })
publishPrompts()
deps.onPromptAdded?.(prompt)
// One banner per burst: further prompts queue behind the first.
if (firstWaiting) {
deps.onPromptAdded?.(prompt)
}
}
const runApproved = (
@@ -199,14 +199,16 @@ export function createLocalCommandBridge(deps: LocalCommandBridgeDeps) {
base: RequestBase & { cwd: string },
timeoutSec: number,
outcome: 'allowed-once' | 'always-allowed' | 'auto-allowed'
): Promise<void> =>
runApprovedLocalCommand(
): Promise<void> => {
limits.runStarted(base.sandboxId)
return runApprovedLocalCommand(
{ settle, execute: deps.execute, audit },
environmentId,
base,
timeoutSec,
outcome
)
).finally(() => limits.runEnded(base.sandboxId))
}
function closePrompt(id: string, entry: PendingPrompt): RequestBase & { cwd: string } {
entry.timer.cancel()
@@ -222,10 +224,11 @@ export function createLocalCommandBridge(deps: LocalCommandBridgeDeps) {
}
}
function onSettled(raw: unknown): void {
function onSettled(environmentId: string, raw: unknown): void {
const parsed = LocalCommandSettledEventSchema.safeParse(raw)
const entry = parsed.success ? pending.get(parsed.data.requestId) : undefined
if (!parsed.success || !entry) {
// Only the workspace that asked can close its own prompt.
if (!parsed.success || !entry || entry.environmentId !== environmentId) {
return
}
const base = closePrompt(parsed.data.requestId, entry)
@@ -240,9 +243,7 @@ export function createLocalCommandBridge(deps: LocalCommandBridgeDeps) {
const enabled = new Set(deps.supported ? deps.settings.enabledSandboxIds() : [])
const desired = new Map<string, string>()
for (const workspace of deps.listWorkspaces()) {
if (!labels.has(workspace.sandboxId)) {
labels.set(workspace.sandboxId, workspace.fallbackLabel)
}
policy.noteFallbackLabel(workspace.sandboxId, workspace.fallbackLabel)
if (enabled.has(workspace.sandboxId) && workspace.runtimeEnvironmentId) {
desired.set(workspace.sandboxId, workspace.runtimeEnvironmentId)
}
@@ -264,7 +265,8 @@ export function createLocalCommandBridge(deps: LocalCommandBridgeDeps) {
if (!entry) {
return { ok: false, error: 'not_found' }
}
if (decision !== 'deny' && now() - entry.shownAt < LOCAL_COMMAND_MIN_DECISION_MS) {
const visibleSince = front?.id === id ? front.since : now()
if (decision !== 'deny' && now() - visibleSince < LOCAL_COMMAND_MIN_DECISION_MS) {
return { ok: false, error: 'too_soon' }
}
const base = closePrompt(id, entry)
@@ -66,4 +66,16 @@ describe.skipIf(!localCommandsSupported())('local command executor', () => {
expect(await resolveLocalCommandCwd('~/nope', home)).toBeNull()
expect(await resolveLocalCommandCwd('relative/path', home)).toBeNull()
})
it('reports soon after the shell exits even if a detached process holds its output open', async () => {
const result = await executeLocalCommand({
command: `perl -MPOSIX -e 'setsid(); sleep 30' & echo done`,
cwd: tmpdir(),
timeoutSec: 20,
env: buildLocalCommandEnv(undefined)
})
expect(result.stdout).toBe('done\n')
expect(result.timedOut).toBe(false)
expect(result.durationMs).toBeLessThan(5_000)
})
})
@@ -8,6 +8,8 @@ import {
} from '../../shared/local-commands/local-command-contract'
const KILL_GRACE_MS = 3_000
/** After the shell exits, how long its output may keep draining before the result is reported. */
const RESULT_GRACE_MS = 1_000
const FALLBACK_PATH = '/usr/bin:/bin:/usr/sbin:/sbin'
/** Names copied from this app's own environment; nothing else is passed (no tokens, keys, sockets). */
const PASSTHROUGH = ['USER', 'LOGNAME', 'TMPDIR', 'LANG', 'LC_ALL', 'LC_CTYPE'] as const
@@ -153,23 +155,24 @@ export function executeLocalCommand(
running.add(child)
child.stdout?.on('data', (chunk: Buffer) => stdout.push(chunk))
child.stderr?.on('data', (chunk: Buffer) => stderr.push(chunk))
let killTimer: ReturnType<typeof setTimeout> | null = null
const timeout = setTimeout(() => {
timedOut = true
killGroup(child, 'SIGTERM')
killTimer = setTimeout(() => killGroup(child, 'SIGKILL'), KILL_GRACE_MS)
}, input.timeoutSec * 1000)
const finish = (exitCode: number | null, signal: NodeJS.Signals | null): void => {
clearTimeout(timeout)
if (killTimer) {
clearTimeout(killTimer)
const timers: ReturnType<typeof setTimeout>[] = []
let exit: { code: number | null; signal: NodeJS.Signals | null } | null = null
let settled = false
const finish = (): void => {
if (settled) {
return
}
settled = true
timers.forEach(clearTimeout)
running.delete(child)
// A command that exited may have left children in its group; they don't outlive the request.
// Children left in its group don't outlive the request, and a process that escaped the group
// can't hold the result open through an inherited pipe.
killGroup(child, 'SIGKILL')
child.stdout?.destroy()
child.stderr?.destroy()
resolve({
exitCode,
signal,
exitCode: exit?.code ?? null,
signal: exit?.signal ?? null,
timedOut,
durationMs: Date.now() - startedAt,
stdout: stdout.text(),
@@ -179,11 +182,37 @@ export function executeLocalCommand(
stderrBytes: stderr.bytes
})
}
timers.push(
setTimeout(() => {
timedOut = true
killGroup(child, 'SIGTERM')
timers.push(setTimeout(() => killGroup(child, 'SIGKILL'), KILL_GRACE_MS))
}, input.timeoutSec * 1000),
// Whatever holds the pipes, the result is reported shortly after the hard stop.
setTimeout(
() => {
timedOut = true
finish()
},
input.timeoutSec * 1000 + KILL_GRACE_MS + RESULT_GRACE_MS
)
)
child.once('error', (error) => {
clearTimeout(timeout)
running.delete(child)
reject(error)
if (!settled) {
settled = true
timers.forEach(clearTimeout)
running.delete(child)
reject(error)
}
})
child.once('exit', (code, signal) => {
exit = { code, signal }
// Let buffered output drain, then report even if a leftover process keeps the pipe open.
timers.push(setTimeout(finish, RESULT_GRACE_MS))
})
child.once('close', (code, signal) => {
exit ??= { code, signal }
finish()
})
child.once('close', finish)
})
}
@@ -0,0 +1,73 @@
const HOUR_MS = 60 * 60_000
/** This computer's own limits: a hostile workspace must not be able to flood the person or run a
* saved rule without bound, whatever the VM's broker claims to enforce. */
export const LOCAL_COMMAND_DESKTOP_LIMITS = {
pendingPerWorkspace: 3,
requestsPerHour: 60,
autoRunsPerHour: 30,
/** "Always allow" runs one at a time per workspace; a second one waits for the person. */
autoRunsConcurrent: 1,
/** A flood is logged once a minute, so it can't push real entries out of the audit log. */
refusalLogIntervalMs: 60_000
} as const
type WorkspaceCounters = {
requests: number[]
autoRuns: number[]
running: number
lastRefusalLoggedAt: number
}
export function createLocalCommandRequestLimits() {
const counters = new Map<string, WorkspaceCounters>()
const of = (sandboxId: string): WorkspaceCounters => {
let entry = counters.get(sandboxId)
if (!entry) {
entry = { requests: [], autoRuns: [], running: 0, lastRefusalLoggedAt: -Infinity }
counters.set(sandboxId, entry)
}
return entry
}
const recent = (times: number[], now: number): number[] => times.filter((t) => now - t < HOUR_MS)
return {
/** Counts the request; false when this workspace already asked too often this hour. */
admitRequest(sandboxId: string, now: number): boolean {
const entry = of(sandboxId)
entry.requests = recent(entry.requests, now)
if (entry.requests.length >= LOCAL_COMMAND_DESKTOP_LIMITS.requestsPerHour) {
return false
}
entry.requests.push(now)
return true
},
/** Whether a saved rule may run now without asking; counts it when it may. */
admitAutoRun(sandboxId: string, now: number): boolean {
const entry = of(sandboxId)
entry.autoRuns = recent(entry.autoRuns, now)
if (
entry.running >= LOCAL_COMMAND_DESKTOP_LIMITS.autoRunsConcurrent ||
entry.autoRuns.length >= LOCAL_COMMAND_DESKTOP_LIMITS.autoRunsPerHour
) {
return false
}
entry.autoRuns.push(now)
return true
},
runStarted(sandboxId: string): void {
of(sandboxId).running += 1
},
runEnded(sandboxId: string): void {
const entry = of(sandboxId)
entry.running = Math.max(0, entry.running - 1)
},
shouldLogRefusal(sandboxId: string, now: number): boolean {
const entry = of(sandboxId)
if (now - entry.lastRefusalLoggedAt < LOCAL_COMMAND_DESKTOP_LIMITS.refusalLogIntervalMs) {
return false
}
entry.lastRefusalLoggedAt = now
return true
}
}
}
@@ -76,7 +76,7 @@ export function createLocalCommandSettingsController(deps: LocalCommandSettingsC
return {
available: deps.supported,
workspaces,
rules: deps.settings.rules().map((rule) => ({
rules: deps.settings.rules(now()).map((rule) => ({
...rule,
workspaceLabel: deps.bridge.labelOf(rule.sandboxId)
}))
@@ -9,6 +9,8 @@ import {
} from '../../shared/local-commands/local-command-contract'
const MAX_RULES = 200
/** A saved approval lapses; the person sees the command again after this long. */
export const LOCAL_COMMAND_RULE_TTL_MS = 30 * 24 * 60 * 60_000
const SandboxId = z.string().regex(/^sbx_[0-9a-f]{24}$/)
const WorkspaceSettingSchema = z.object({
@@ -69,7 +71,12 @@ export class LocalCommandSettingsStore {
setEnabled(sandboxId: string, enabled: boolean, sharedAllowed: boolean, now: number): void {
const next = this.read()
if (enabled) {
const previous = next.workspaces[sandboxId]
next.workspaces[sandboxId] = { enabled, sharedAllowed, updatedAt: now }
// Rules approved while only the owner could prompt the agent don't carry over to a shared one.
if (sharedAllowed && !previous?.sharedAllowed) {
next.rules = next.rules.filter((rule) => rule.sandboxId !== sandboxId)
}
} else {
// Turning it off also forgets this workspace's "Always allow" rules: the next time it is on,
// every command is asked about again.
@@ -79,28 +86,32 @@ export class LocalCommandSettingsStore {
this.write(next)
}
rules(): LocalCommandRule[] {
return [...this.read().rules]
/** Rules still in force (expired ones are kept on disk until the next write drops them). */
rules(now: number): LocalCommandRule[] {
return this.read().rules.filter((rule) => now - rule.createdAt < LOCAL_COMMAND_RULE_TTL_MS)
}
/** Exact match only: same workspace, same characters, same resolved folder. */
findRule(sandboxId: string, command: string, cwd: string): LocalCommandRule | null {
/** Exact match only: same workspace, same characters, same resolved folder, not expired. */
findRule(sandboxId: string, command: string, cwd: string, now: number): LocalCommandRule | null {
return (
this.read().rules.find(
this.rules(now).find(
(rule) => rule.sandboxId === sandboxId && rule.command === command && rule.cwd === cwd
) ?? null
)
}
addRule(sandboxId: string, command: string, cwd: string, now: number): LocalCommandRule {
const existing = this.findRule(sandboxId, command, cwd)
const existing = this.findRule(sandboxId, command, cwd, now)
if (existing) {
return existing
}
const next = this.read()
const rule: LocalCommandRule = { id: randomUUID(), sandboxId, command, cwd, createdAt: now }
// Oldest first out at the cap; a forgotten rule only means one more prompt.
next.rules = [...next.rules, rule].slice(-MAX_RULES)
next.rules = [
...next.rules.filter((r) => now - r.createdAt < LOCAL_COMMAND_RULE_TTL_MS),
rule
].slice(-MAX_RULES)
this.write(next)
return rule
}
@@ -0,0 +1,55 @@
import {
localCommandRefusal,
type LocalCommandWorkspacePolicy
} from './local-command-request-checks'
import type { LocalCommandSettingsStore } from './local-command-settings-store'
const POLICY_TTL_MS = 30_000
/** Ownership and sharing per workspace (from the registry, cached briefly for display only), and
* the workspace names to show. Every decision re-reads the registry. */
export function createLocalCommandWorkspacePolicy(deps: {
settings: LocalCommandSettingsStore
supported: boolean
readPolicy: (sandboxId: string) => Promise<LocalCommandWorkspacePolicy | null>
now: () => number
}) {
const cache = new Map<string, { at: number; value: LocalCommandWorkspacePolicy | null }>()
const labels = new Map<string, string>()
async function policyOf(
sandboxId: string,
fresh: boolean
): Promise<LocalCommandWorkspacePolicy | null> {
const cached = cache.get(sandboxId)
if (!fresh && cached && deps.now() - cached.at < POLICY_TTL_MS) {
return cached.value
}
const value = await deps.readPolicy(sandboxId).catch(() => null)
cache.set(sandboxId, { at: deps.now(), value })
if (value?.title) {
labels.set(sandboxId, value.title)
}
return value
}
return {
policyOf,
/** The last registry answer, for display; null until one arrives. */
cached: (sandboxId: string) => cache.get(sandboxId)?.value ?? null,
labelOf: (sandboxId: string): string => labels.get(sandboxId) ?? sandboxId,
noteFallbackLabel(sandboxId: string, label: string): void {
if (!labels.has(sandboxId)) {
labels.set(sandboxId, label)
}
},
/** Why this computer won't take a request now; null when it may ask the person. */
async refusalOf(sandboxId: string): Promise<string | null> {
const setting = deps.settings.workspace(sandboxId)
if (!deps.supported || !setting?.enabled) {
return localCommandRefusal(deps.supported, setting, null)
}
return localCommandRefusal(deps.supported, setting, await policyOf(sandboxId, true))
}
}
}
@@ -0,0 +1,24 @@
import { readFileSync } from 'node:fs'
import { homedir } from 'node:os'
import { join } from 'node:path'
/** Written by /opt/orca/bin/orca-sandbox-grant: one device id per line for every offer minted for a
* teammate's (or any granted) device. The workspace owner's own desktop pairs from the VM's first
* offer and is never listed. */
export function grantDeviceLedgerPath(home = homedir()): string {
return join(home, '.orca-sandbox', 'grant-devices')
}
/** True when the device came from a grant. An unreadable ledger (other than missing) counts as yes. */
export function isGrantedDevice(
originDeviceId: string,
read: () => string = () => readFileSync(grantDeviceLedgerPath(), 'utf8')
): boolean {
let text: string
try {
text = read()
} catch (error) {
return (error as NodeJS.ErrnoException)?.code !== 'ENOENT'
}
return text.split('\n').some((line) => line.trim() === originDeviceId)
}
+2
View File
@@ -126,6 +126,8 @@ export type RpcContext = {
pairedDeviceId?: string
// Delegated phones use their parent desktop's workspaces.
pairedDeviceParentId?: string
// The pairing offer this device came from (a device-key fork keeps its offer's id).
pairedDeviceOriginId?: string
// Host-assigned transport identity; absent means the caller could not be established.
caller?: RpcCallerIdentity
// Only phones receive truncated payloads; undefined in-process callers remain unclipped.
@@ -13,6 +13,7 @@ export type RpcDispatchStreamingOptions = Pick<
| 'clientId'
| 'pairedDeviceId'
| 'pairedDeviceParentId'
| 'pairedDeviceOriginId'
| 'caller'
| 'clientKind'
| 'clientCapabilities'
@@ -65,6 +66,7 @@ export function rpcContextFromTransport(
clientId: options?.clientId,
pairedDeviceId: options?.pairedDeviceId,
pairedDeviceParentId: options?.pairedDeviceParentId,
pairedDeviceOriginId: options?.pairedDeviceOriginId,
caller: resolveRpcCallerIdentity(options),
clientKind: options?.clientKind,
clientCapabilities: options?.clientCapabilities,
@@ -0,0 +1,59 @@
import { describe, expect, it } from 'vitest'
import { LocalCommandBroker } from '../../../local-commands/local-command-broker'
import type { RpcContext } from '../../core'
import { createLocalCommandMethods } from './local-command-methods'
function methods(grantedDevices: string[]) {
const broker = new LocalCommandBroker()
const list = createLocalCommandMethods({
broker: () => broker,
enabled: () => true,
callerTerminal: () => null,
isGrantedDevice: (origin) => grantedDevices.includes(origin)
})
const byName = (name: string) => list.find((method) => method.name === name)!
return { broker, byName }
}
function desktop(deviceId: string, originId = deviceId): RpcContext {
return {
runtime: { registerSubscriptionCleanup: () => {} } as unknown as RpcContext['runtime'],
clientKind: 'runtime',
caller: { kind: 'paired-device', deviceId },
pairedDeviceId: deviceId,
pairedDeviceOriginId: originId,
connectionId: `conn-${deviceId}`
}
}
describe('local command RPC methods', () => {
it('refuses a device paired through a grant, even after it forked a key', async () => {
const { broker, byName } = methods(['grant-device'])
broker.attach('owner', 'owner-device', () => {})
const { requestId } = broker.request({ command: 'ls', cwd: null, reason: null, agent: null })
const settle = byName('localCommands.settle')
await expect(
Promise.resolve(
settle.handler(
{ requestId, outcome: 'started' } as never,
desktop('fork-1', 'grant-device')
)
)
).rejects.toThrow('local_command_forbidden')
expect(broker.status(requestId).status).toBe('pending')
})
it('refuses a phone and the agent CLI as a desktop', async () => {
const { broker, byName } = methods([])
broker.attach('owner', 'owner-device', () => {})
const { requestId } = broker.request({ command: 'ls', cwd: null, reason: null, agent: null })
const settle = byName('localCommands.settle')
const phone = { ...desktop('phone'), clientKind: 'mobile' as const }
const cli = { ...desktop('cli'), caller: { kind: 'local-cli' as const } }
for (const ctx of [phone, cli]) {
await expect(
Promise.resolve(settle.handler({ requestId, outcome: 'started' } as never, ctx))
).rejects.toThrow('local_command_forbidden')
}
})
})
@@ -18,6 +18,7 @@ import {
type LocalCommandBroker
} from '../../../local-commands/local-command-broker'
import { isCloudWorkspaceOrcad } from '../../../secrets/session-env-names'
import { isGrantedDevice } from '../../../local-commands/grant-device-ledger'
import { defineMethod, defineStreamingMethod, type RpcContext } from '../../core'
import { isAgentRpcCaller } from '../../rpc-caller-identity'
import { resolveSecretRequestCaller } from '../secrets/secret-requests'
@@ -28,21 +29,30 @@ export type LocalCommandMethodDeps = {
/** Only a cloud workspace's orcad relays; a desktop's own runtime refuses. */
enabled: () => boolean
callerTerminal: (ctx: RpcContext) => string | null
/** Devices paired through a grant (teammates, other computers) never take requests. */
isGrantedDevice: (originDeviceId: string) => boolean
}
const defaultDeps: LocalCommandMethodDeps = {
broker: getLocalCommandBroker,
enabled: () => isCloudWorkspaceOrcad(),
callerTerminal: verifiedCallerTerminalHandle
callerTerminal: verifiedCallerTerminalHandle,
isGrantedDevice: (originDeviceId) => isGrantedDevice(originDeviceId)
}
/** A paired desktop, proven by its socket: never the agent's CLI, never a phone. */
function requireDesktopDevice(ctx: RpcContext): { deviceId: string; connectionId: string } {
/** The owner's paired desktop, proven by its socket: never the agent's CLI, a phone, or a device
* paired through a grant (a teammate's computer must not see, claim or answer requests). */
function requireOwnerDesktop(
ctx: RpcContext,
deps: LocalCommandMethodDeps
): { deviceId: string; connectionId: string } {
if (
ctx.clientKind !== 'runtime' ||
ctx.caller?.kind !== 'paired-device' ||
!ctx.pairedDeviceId ||
!ctx.connectionId
!ctx.pairedDeviceOriginId ||
!ctx.connectionId ||
deps.isGrantedDevice(ctx.pairedDeviceOriginId)
) {
throw new LocalCommandError(LOCAL_COMMAND_ERRORS.forbidden)
}
@@ -99,7 +109,7 @@ export function createLocalCommandMethods(deps: LocalCommandMethodDeps = default
permission: 'workspace',
params: LocalCommandSettleParamsSchema,
handler: async (params, ctx): Promise<LocalCommandSettleResult> => {
const { deviceId } = requireDesktopDevice(ctx)
const { deviceId } = requireOwnerDesktop(ctx, deps)
return broker().settle(deviceId, params)
}
}),
@@ -108,7 +118,7 @@ export function createLocalCommandMethods(deps: LocalCommandMethodDeps = default
permission: 'workspace',
params: LocalCommandAttachParamsSchema,
handler: async (_params, ctx, emit) => {
const { deviceId, connectionId } = requireDesktopDevice(ctx)
const { deviceId, connectionId } = requireOwnerDesktop(ctx, deps)
const relay = broker()
await new Promise<void>((resolve) => {
const subscriptionId = `local-commands-${connectionId}-${++attachSeq}`
@@ -260,6 +260,7 @@ export class RuntimeRpcWebSocketDispatch extends RuntimeRpcMobileDevices {
clientId: principal.clientId,
pairedDeviceId: device.deviceId,
pairedDeviceParentId: device.parentDeviceId,
pairedDeviceOriginId: device.forkedFrom ?? device.deviceId,
// Diet only mobile payloads; retain full web/desktop replies.
clientKind: device.scope,
callerScope,
@@ -26,6 +26,7 @@ export const request = defineFixture({
ready
busy={false}
onDecide={() => {}}
onTurnOff={() => {}}
/>
</Dialog>
)
@@ -50,6 +51,7 @@ export const longSharedQueued = defineFixture({
ready
busy={false}
onDecide={() => {}}
onTurnOff={() => {}}
/>
</Dialog>
)
@@ -69,6 +71,7 @@ export const lookalikeCharacters = defineFixture({
ready={false}
busy={false}
onDecide={() => {}}
onTurnOff={() => {}}
/>
</Dialog>
)
@@ -64,7 +64,8 @@ export function LocalCommandApprovalDialogView({
waitingCount,
ready,
busy,
onDecide
onDecide,
onTurnOff
}: {
prompt: LocalCommandPrompt
/** Other requests queued behind this one. */
@@ -72,9 +73,28 @@ export function LocalCommandApprovalDialogView({
ready: boolean
busy: boolean
onDecide: (decision: LocalCommandDecision) => void
/** Denies this request and turns local commands off for the workspace. */
onTurnOff: () => void
}): React.JSX.Element {
const t = useTranslate()
const disabled = !ready || busy
// A long command must be scrolled to its end before it can be allowed: nothing stays out of view.
const [readToEnd, setReadToEnd] = useState(false)
const checkReadToEnd = useCallback((box: HTMLElement | null) => {
if (box && box.scrollTop + box.clientHeight >= box.scrollHeight - 2) {
setReadToEnd(true)
}
}, [])
// The dialog portal mounts after this component's first effect, so measure when the box attaches.
const commandRef = useCallback(
(box: HTMLPreElement | null) => {
if (box) {
requestAnimationFrame(() => checkReadToEnd(box))
}
},
[checkReadToEnd]
)
const disabled = !ready || busy || !readToEnd
const lineCount = prompt.command.split('\n').length
return (
<DialogContent
surface="security"
@@ -91,17 +111,11 @@ export function LocalCommandApprovalDialogView({
{t('localCommands.prompt.title', 'Run a command on this computer?')}
</DialogTitle>
<DialogDescription className="text-xs">
{prompt.agent
? t(
'localCommands.prompt.bodyAgent',
'{{agent}} in the cloud workspace {{workspace}} asks to run this command here. Allow it only if you understand what it does.',
{ agent: prompt.agent, workspace: prompt.workspaceLabel }
)
: t(
'localCommands.prompt.body',
'An agent in the cloud workspace {{workspace}} asks to run this command here. Allow it only if you understand what it does.',
{ workspace: prompt.workspaceLabel }
)}
{t(
'localCommands.prompt.body',
'An agent in the cloud workspace {{workspace}} asks to run this command here. Allow it only if you understand what it does.',
{ workspace: prompt.workspaceLabel }
)}
</DialogDescription>
</DialogHeader>
@@ -118,11 +132,19 @@ export function LocalCommandApprovalDialogView({
<div className="space-y-2 rounded-md border border-border/70 bg-muted/35 px-3 py-2">
<div>
<div className="mb-1 text-2xs font-medium uppercase tracking-wider text-muted-foreground">
{t('localCommands.prompt.commandLabel', 'Command')}
<div className="mb-1 flex items-baseline justify-between gap-2 text-2xs font-medium uppercase tracking-wider text-muted-foreground">
<span>{t('localCommands.prompt.commandLabel', 'Command')}</span>
{lineCount > 1 ? (
<span className="normal-case tracking-normal">
{t('localCommands.prompt.lines', '{{count}} lines', { count: lineCount })}
</span>
) : null}
</div>
<pre
className="max-h-48 overflow-auto whitespace-pre-wrap break-all font-mono text-xs text-foreground scrollbar-sleek"
ref={commandRef}
onScroll={(event) => checkReadToEnd(event.currentTarget)}
tabIndex={0}
className="max-h-48 overflow-auto whitespace-pre-wrap break-all font-mono text-xs text-foreground scrollbar-sleek focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-focus-ring"
data-testid="local-command-text"
>
<MarkedText text={prompt.command} />
@@ -156,7 +178,19 @@ export function LocalCommandApprovalDialogView({
</p>
) : null}
{!readToEnd ? (
<p className="text-xs text-foreground">
{t(
'localCommands.prompt.scrollToEnd',
'Scroll to the end of the command before you allow it.'
)}
</p>
) : null}
<p className="text-xs text-muted-foreground">
{prompt.agent
? `${t('localCommands.prompt.agent', 'From {{agent}}', { agent: prompt.agent })} · `
: null}
{timeoutLabel(prompt.timeoutSec, t)}
{' · '}
{t(
@@ -166,6 +200,15 @@ export function LocalCommandApprovalDialogView({
{waitingCount > 0
? ` · ${t('localCommands.prompt.waiting', '{{count}} more waiting', { count: waitingCount })}`
: null}
{' · '}
<button
type="button"
className="underline underline-offset-2 hover:text-foreground focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-focus-ring disabled:opacity-50"
disabled={busy}
onClick={onTurnOff}
>
{t('localCommands.prompt.turnOff', 'Turn off for this workspace')}
</button>
</p>
<DialogFooter>
@@ -253,6 +296,15 @@ export function LocalCommandApprovalDialogHost(): React.JSX.Element | null {
[currentId, ready]
)
const turnOff = useCallback(() => {
const api = window.api.localCommands
if (!api || !current) {
return
}
decide('deny')
void api.setEnabled({ sandboxId: current.sandboxId, enabled: false }).catch(() => {})
}, [current, decide])
if (!current) {
return null
}
@@ -272,6 +324,7 @@ export function LocalCommandApprovalDialogHost(): React.JSX.Element | null {
ready={ready}
busy={busy}
onDecide={decide}
onTurnOff={turnOff}
/>
</Dialog>
)
@@ -293,34 +293,41 @@ export function OrcaCloudLocalCommandsPane(): React.JSX.Element {
}
const enabling = !row.enabled
let allowShared = false
if (enabling && row.shared) {
allowShared = await confirm({
const confirmShared = (): Promise<boolean> =>
confirm({
title: t(
'localCommands.settings.sharedConfirmTitle',
'Allow commands from a shared workspace?'
),
description: t(
'localCommands.settings.sharedConfirmBody',
'Teammates can message the agent in {{workspace}}, so their messages can also lead to requests to run commands on this computer. You still approve every command.',
'Teammates can message the agent in {{workspace}}, so their messages can also lead to requests to run commands on this computer. You still approve each one, and commands you always allowed before are cleared.',
{ workspace: row.label }
),
confirmLabel: t('localCommands.settings.sharedConfirmAction', 'Turn on'),
surface: 'security',
initialFocus: 'cancel'
})
if (!allowShared) {
return
}
if (enabling && row.shared && !(allowShared = await confirmShared())) {
return
}
setPendingSandboxId(row.sandboxId)
setError(null)
try {
const result = await api.setEnabled({
let result = await api.setEnabled({
sandboxId: row.sandboxId,
enabled: enabling,
allowShared
})
if (!result.ok) {
// Sharing wasn't known when the row rendered: ask now, then try once more.
if (!result.ok && result.error === 'shared_needs_confirmation' && (await confirmShared())) {
result = await api.setEnabled({
sandboxId: row.sandboxId,
enabled: true,
allowShared: true
})
}
if (!result.ok && result.error !== 'shared_needs_confirmation') {
setError(
result.error === 'not_owner'
? t(
+4
View File
@@ -2319,10 +2319,14 @@
},
"localCommands": {
"prompt": {
"bodyAgent": "{{agent}} in the cloud workspace {{workspace}} asks to run this command here. Allow it only if you understand what it does.",
"timeoutMinutes_one": "Stops after {{count}} minute",
"timeoutMinutes_other": "Stops after {{count}} minutes",
"timeoutSeconds_one": "Stops after {{count}} second",
"timeoutSeconds_other": "Stops after {{count}} seconds"
},
"settings": {
"sharedConfirmBody": "Teammates can message the agent in {{workspace}}, so their messages can also lead to requests to run commands on this computer. You still approve every command."
}
},
"menu": {
+5 -1
View File
@@ -28083,7 +28083,11 @@
"waiting": "{{count}} more waiting",
"deny": "Deny",
"alwaysAllow": "Always allow this command",
"allowOnce": "Allow once"
"allowOnce": "Allow once",
"lines": "{{count}} lines",
"scrollToEnd": "Scroll to the end of the command before you allow it.",
"agent": "From {{agent}}",
"turnOff": "Turn off for this workspace"
},
"settings": {
"notOwner": "Only the workspace owner can turn this on.",
@@ -12,6 +12,8 @@ export const LOCAL_COMMANDS_ATTACH_METHOD = 'localCommands.attach'
export const LOCAL_COMMANDS_SETTLE_METHOD = 'localCommands.settle'
export const LOCAL_COMMAND_MAX_COMMAND_CHARS = 4000
/** More lines than a person reads in one prompt is refused rather than scrolled past. */
export const LOCAL_COMMAND_MAX_LINES = 20
export const LOCAL_COMMAND_MAX_CWD_CHARS = 1024
export const LOCAL_COMMAND_REASON_MAX = 200
export const LOCAL_COMMAND_DEFAULT_TIMEOUT_SEC = 120
@@ -28,10 +30,11 @@ export const LOCAL_COMMAND_MAX_PER_HOUR = 60
const RequestId = z.string().regex(/^lc_[A-Za-z0-9_-]{16,64}$/)
// Characters that can hide or reorder what a person reads: C0/C1 controls (tab and newline are
// shown as they are), bidi overrides and isolates, zero-width and invisible formatting, separators.
// shown as they are), bidi overrides and isolates, zero-width and invisible formatting, lookalike
// spaces, combining marks and separators.
const HIDDEN_CHARS =
// oxlint-disable-next-line no-control-regex, no-misleading-character-class -- SAFETY: matching control and invisible characters is the point.
/[\u0000-\u0008\u000B-\u001F\u007F-\u009F\u00AD\u061C\u115F\u1160\u180E\u200B-\u200F\u2028-\u202E\u2060-\u206F\u3164\uFE00-\uFE0F\uFEFF\uFFF9-\uFFFB]|\uDB40[\uDC00-\uDC7F]/
/[\u0000-\u0008\u000B-\u001F\u007F-\u00A0\u00AD\u0300-\u036F\u061C\u115F\u1160\u180E\u2000-\u200F\u2028-\u202F\u205F-\u206F\u3000\u3164\uFE00-\uFE0F\uFEFF\uFFF9-\uFFFB]|\uDB40[\uDC00-\uDC7F]/
/** True when the text holds a character that could make the shown command differ from the run one. */
export function hasHiddenCharacters(text: string): boolean {
@@ -63,6 +66,7 @@ export const LocalCommandText = z
.max(LOCAL_COMMAND_MAX_COMMAND_CHARS)
.refine((value) => value.trim().length > 0, 'empty_command')
.refine((value) => !hasHiddenCharacters(value), 'hidden_characters')
.refine((value) => value.split('\n').length <= LOCAL_COMMAND_MAX_LINES, 'too_many_lines')
/** Absolute, or ~ for the person's home folder. A single line. */
export const LocalCommandCwd = z
@@ -63,7 +63,10 @@ export type LocalCommandAuditEntry = {
requestId: string
sandboxId: string
workspaceLabel: string
/** The first 1,000 characters for a longer command; then the length and hash identify it. */
command: string
commandLength?: number
commandSha256?: string
cwd: string | null
agent: string | null
outcome: LocalCommandAuditOutcome