feat(agent-api-keys): save Agent API keys to the Orca account and import from this Mac (A5/D12)

While signed in to Orca with Orca Cloud, saving an Agent API key also writes it to the
personal Cloud secret of the same variable through /v1/secrets. The sealed vault stays the
cache and the source for non-Cloud launches; host scope stays local. Only every-host keys the
egress proxy swaps are written. A main-side ledger (names only, per account) tracks what this
computer wrote, and only those copies can be removed from the account, after confirmation.

Import from this Mac: main scans OpenCode's auth.json, ~/.gemini/.env and the login shell env;
the renderer sees names, sources and last fours only, and main re-reads values on import.
OAuth sign-ins are listed, never read.
This commit is contained in:
Neil
2026-11-10 06:46:50 -08:00
parent 0606c25105
commit 0df70ebdf7
26 changed files with 2638 additions and 142 deletions
@@ -0,0 +1,40 @@
// Who the desktop writes personal Cloud secrets as. Set up by the Cloud secrets handlers, which own
// the control-plane client; until then (or in builds without Orca Cloud) keys stay on this computer.
import { app } from 'electron'
import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent'
import type { CloudSecretsClient } from '../cloud-secrets/cloud-secrets-client'
import { getOrcaCloudAvailability } from '../hosted-sandbox/hosted-sandbox-install'
import { getOrcaProfileIndexGeneration } from '../orca-profiles/profile-index-generation'
import { ensureActiveOrcaProfile } from '../orca-profiles/profile-index-store'
import type { AgentApiKeyCloudConnection } from './agent-api-key-cloud-sync'
let client: CloudSecretsClient | null = null
let recorder: ((agent: TuiAgent, envName: string) => Promise<void>) | null = null
/** Lets the vault note a key the cloud workspace setup saved to the Orca account. */
export function setAgentApiKeyCloudRecorder(
next: ((agent: TuiAgent, envName: string) => Promise<void>) | null
): void {
recorder = next
}
export async function recordAgentApiKeyCloudWrite(agent: TuiAgent, envName: string): Promise<void> {
await recorder?.(agent, envName).catch(() => undefined)
}
export function setAgentApiKeyCloudClient(next: CloudSecretsClient | null): void {
client = next
}
/** The signed-in Orca account with Orca Cloud, or null: signed out, no capability, or offline. */
export async function agentApiKeyCloudConnection(): Promise<AgentApiKeyCloudConnection | null> {
const current = client
const generation = getOrcaProfileIndexGeneration()
if (!current || (await getOrcaCloudAvailability()) !== 'offered') {
return null
}
const accountId = ensureActiveOrcaProfile(app.getPath('userData')).profile.cloud?.userId
// Every sign-in, sign-out and account or team switch rewrites the profile index.
const isCurrent = (): boolean => getOrcaProfileIndexGeneration() === generation
return accountId && isCurrent() ? { accountId, client: current, isCurrent } : null
}
@@ -0,0 +1,96 @@
// IPC for the Orca account side of Agent API keys: save one existing key there, and "Import from
// this Mac". Nothing here returns a value; scans answer with names, sources and last fours.
import { ipcMain } from 'electron'
import type {
AgentApiKeyRemoveRequest,
AgentApiKeysImportResult,
AgentApiKeysScanResult
} from '../../shared/agent-api-keys/agent-api-key-cloud'
import type { AgentApiKeysMutationResult } from '../../shared/agent-api-keys/agent-api-key-catalog'
import { resolveLoginShellEnvironment } from '../startup/login-shell-environment'
import type { AgentApiKeyCloudSync } from './agent-api-key-cloud-sync'
import { importLocalAgentKeys, parseImportNames, scanSummary } from './agent-api-key-import'
import { mutate, stateOf } from './agent-api-key-state'
import type { AgentApiKeyStore } from './agent-api-key-store'
import { readLocalAgentCredentials, type LocalAgentCredentials } from './local-agent-credentials'
const CHANNELS = [
'agentApiKeys:saveToAccount',
'agentApiKeys:scanThisComputer',
'agentApiKeys:importFromThisComputer'
] as const
/** `remove` takes a bare id (keep the account copy) or `{ id, fromAccount }`. */
export function removeRequestOf(raw: unknown): AgentApiKeyRemoveRequest | null {
if (typeof raw === 'string') {
return { id: raw, fromAccount: false }
}
if (
typeof raw === 'object' &&
raw !== null &&
'id' in raw &&
typeof raw.id === 'string' &&
'fromAccount' in raw &&
typeof raw.fromAccount === 'boolean'
) {
return { id: raw.id, fromAccount: raw.fromAccount }
}
return null
}
/** What an agent started from a terminal here would see: the login shell's env over Orca's own. */
async function readThisComputer(): Promise<LocalAgentCredentials> {
let shellEnv: NodeJS.ProcessEnv = {}
try {
shellEnv = await resolveLoginShellEnvironment()
} catch {
// No login shell (or it timed out): Orca's own env and the agents' files still count.
}
return await readLocalAgentCredentials({ env: { ...process.env, ...shellEnv } })
}
export function registerAgentApiKeyCloudHandlers({
store,
cloud,
serial,
read = readThisComputer
}: {
store: AgentApiKeyStore
cloud: AgentApiKeyCloudSync
serial: <T>(run: () => Promise<T>) => Promise<T>
read?: () => Promise<LocalAgentCredentials>
}): void {
for (const channel of CHANNELS) {
ipcMain.removeHandler(channel)
}
// One explicit click: writes a key that is only on this computer to the Orca account.
ipcMain.handle(
'agentApiKeys:saveToAccount',
(_event, id: unknown): Promise<AgentApiKeysMutationResult> =>
serial(() =>
mutate(store, cloud, async () => {
const key =
typeof id === 'string' ? (await store.list()).find((entry) => entry.id === id) : null
return key ? cloud.push(key, { replace: true }) : { kind: 'failed', error: 'not_found' }
})
)
)
ipcMain.handle('agentApiKeys:scanThisComputer', async (): Promise<AgentApiKeysScanResult> =>
scanSummary(await read(), await store.list())
)
ipcMain.handle(
'agentApiKeys:importFromThisComputer',
async (_event, raw: unknown): Promise<AgentApiKeysImportResult> => {
const names = parseImportNames(raw)
// Read outside the queue: a slow shell or file must not hold up saves and removals.
const found = names ? await read() : null
return serial(async () => {
const result =
names && found
? await importLocalAgentKeys({ names, found, store, push: (key) => cloud.push(key) })
: { imported: [], failed: [], cloudFailed: [] }
return { ...result, state: await stateOf(store, cloud) }
})
}
)
}
@@ -0,0 +1,260 @@
import { mkdtemp, readFile, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { AgentApiKeySummary } from '../../shared/agent-api-keys/agent-api-key-catalog'
import type { CloudSecretView } from '../../shared/cloud-secrets/cloud-secrets-wire'
import { EnvironmentProviderError } from '../environment-providers/environment-provider-driver'
import { AgentApiKeyCloudSync, type AgentApiKeyCloudConnection } from './agent-api-key-cloud-sync'
const VALUE = 'sk-ant-api03-cloud-sync-secret-9fQ2'
let root: string
function key(overrides: Partial<AgentApiKeySummary> = {}): AgentApiKeySummary {
return {
id: 'k1',
agent: 'claude',
envName: 'ANTHROPIC_API_KEY',
hostScope: { kind: 'all' },
hint: '9fQ2',
updatedAt: 1,
...overrides
}
}
function setup(accountId: string | null = 'user-a', vault: AgentApiKeySummary[] = []) {
const view: CloudSecretView = {
scope: 'personal',
name: 'ANTHROPIC_API_KEY',
kind: 'agent_key',
hint: '9fQ2',
updatedAt: 1,
updatedBy: 'user-a'
}
const client = {
put: vi.fn(async () => view),
remove: vi.fn(async (_target: { scope: 'personal' }, _name: string) => {})
}
let generation = 0
const connect = (id: string): AgentApiKeyCloudConnection => {
const at = generation
return { accountId: id, client, isCurrent: () => generation === at }
}
let current: AgentApiKeyCloudConnection | null = accountId ? connect(accountId) : null
const sync = new AgentApiKeyCloudSync({
ledgerPath: join(root, 'ledger.json'),
connection: async () => current,
valueOf: async () => VALUE,
listKeys: async () => vault,
now: () => 100
})
return {
client,
sync,
signInAs: (id: string | null) => {
generation++
current = id ? connect(id) : null
}
}
}
beforeEach(async () => {
root = await mkdtemp(join(tmpdir(), 'orca-agent-key-cloud-'))
})
afterEach(async () => {
await rm(root, { recursive: true, force: true })
})
describe('AgentApiKeyCloudSync', () => {
it('writes a saved key to the personal secret of the same name and records only its name', async () => {
const { client, sync } = setup()
expect(await sync.push(key())).toEqual({ kind: 'synced' })
expect(client.put).toHaveBeenCalledWith({ scope: 'personal' }, 'ANTHROPIC_API_KEY', VALUE)
const ledger = await readFile(join(root, 'ledger.json'), 'utf8')
expect(ledger).not.toContain(VALUE)
expect(ledger).not.toContain('9fQ2')
expect(await sync.state([key()])).toEqual({ signedIn: true, synced: ['k1'], managed: ['k1'] })
})
it('stays local-only when signed out', async () => {
const { client, sync } = setup(null)
expect(await sync.push(key())).toEqual({ kind: 'skipped' })
expect(client.put).not.toHaveBeenCalled()
expect(await sync.state([key()])).toEqual({ signedIn: false, synced: [], managed: [] })
})
it('skips host-scoped keys and refuses names the proxy cannot swap', async () => {
const { client, sync } = setup()
expect(await sync.push(key({ hostScope: { kind: 'hosts', hostIds: ['local'] } }))).toEqual({
kind: 'skipped'
})
expect(await sync.push(key({ envName: 'AWS_BEARER_TOKEN_BEDROCK' }))).toEqual({
kind: 'failed',
error: 'not_swappable',
keyId: 'k1'
})
expect(client.put).not.toHaveBeenCalled()
})
it('reports a failed write as a code, never the value, and logs only the code', async () => {
const { client, sync } = setup()
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
client.put.mockRejectedValueOnce(
new EnvironmentProviderError('unavailable', `upstream echoed ${VALUE}`)
)
const outcome = await sync.push(key())
expect(outcome).toEqual({ kind: 'failed', error: 'unavailable', keyId: 'k1' })
expect(JSON.stringify(outcome)).not.toContain(VALUE)
expect(JSON.stringify(warn.mock.calls)).not.toContain(VALUE)
expect(await sync.state([key()])).toEqual({ signedIn: true, synced: [], managed: [] })
warn.mockRestore()
})
it('treats an edited key whose write failed as not synced, but still managed', async () => {
const { client, sync } = setup()
await sync.push(key())
client.put.mockRejectedValueOnce(new EnvironmentProviderError('timeout', 'slow'))
const edited = key({ updatedAt: 2, hint: 'zzzz' })
await sync.push(edited)
expect(await sync.state([edited])).toEqual({ signedIn: true, synced: [], managed: ['k1'] })
})
it('keeps one ledger per Orca account', async () => {
const { sync, signInAs } = setup()
await sync.push(key())
signInAs('user-b')
expect(await sync.state([key()])).toEqual({ signedIn: true, synced: [], managed: [] })
})
it('removes the account copy only for a key this computer wrote, and only when asked', async () => {
const { client, sync } = setup()
await sync.push(key())
// Another vault key with the same variable never wrote it: refused, nothing removed.
expect(await sync.beforeRemove(key({ id: 'other' }), true)).toEqual({
ok: false,
error: 'not_found'
})
expect(client.remove).not.toHaveBeenCalled()
const removal = await sync.beforeRemove(key(), true)
expect(removal).toMatchObject({ ok: true, removedFromAccount: true })
expect(client.remove).toHaveBeenCalledWith({ scope: 'personal' }, 'ANTHROPIC_API_KEY')
// The ledger forgets only once the vault has removed the key.
expect(await sync.state([key()])).toMatchObject({ managed: ['k1'] })
if (removal.ok) {
await removal.forget()
}
expect(await sync.state([key()])).toEqual({ signedIn: true, synced: [], managed: [] })
})
it('leaves the account copy when the user keeps it, and stops managing it', async () => {
const { client, sync } = setup()
await sync.push(key())
const removal = await sync.beforeRemove(key(), false)
expect(removal).toMatchObject({ ok: true, removedFromAccount: false })
expect(client.remove).not.toHaveBeenCalled()
if (removal.ok) {
await removal.forget()
}
expect(await sync.state([key()])).toEqual({ signedIn: true, synced: [], managed: [] })
})
it('never removes a secret it has no ledger entry for (e.g. one created on the web)', async () => {
const { client, sync } = setup()
expect(await sync.beforeRemove(key(), true)).toEqual({ ok: false, error: 'not_found' })
expect(client.remove).not.toHaveBeenCalled()
})
it('aborts the removal when the account delete fails, but treats not_found as done', async () => {
const { client, sync } = setup()
vi.spyOn(console, 'warn').mockImplementation(() => {})
await sync.push(key())
client.remove.mockRejectedValueOnce(new EnvironmentProviderError('unavailable', 'down'))
expect(await sync.beforeRemove(key(), true)).toEqual({ ok: false, error: 'unavailable' })
expect(await sync.state([key()])).toMatchObject({ managed: ['k1'] })
client.remove.mockRejectedValueOnce(new EnvironmentProviderError('not_found', 'gone'))
expect(await sync.beforeRemove(key(), true)).toMatchObject({
ok: true,
removedFromAccount: true
})
vi.mocked(console.warn).mockRestore()
})
it('refuses an account delete while signed out', async () => {
const { sync } = setup(null)
expect(await sync.beforeRemove(key(), true)).toEqual({ ok: false, error: 'unauthorized' })
expect(await sync.beforeRemove(key(), false)).toMatchObject({
ok: true,
removedFromAccount: false
})
})
it('does not overwrite another saved key’s account copy unless asked to replace it', async () => {
const codex = key({ id: 'codex', agent: 'codex', envName: 'OPENAI_API_KEY' })
const opencode = key({ id: 'opencode', agent: 'opencode', envName: 'OPENAI_API_KEY' })
const { client, sync } = setup('user-a', [codex, opencode])
await sync.push(codex)
expect(await sync.push(opencode)).toEqual({
kind: 'failed',
error: 'desktop_key_conflict',
keyId: 'opencode'
})
expect(client.put).toHaveBeenCalledTimes(1)
expect(await sync.push(opencode, { replace: true })).toEqual({ kind: 'synced' })
expect(await sync.state([codex, opencode])).toEqual({
signedIn: true,
synced: ['opencode'],
managed: ['opencode']
})
})
it('keeps tracking an account copy after a rename or narrower scope, and removes every copy', async () => {
const { client, sync } = setup()
await sync.push(key())
const renamed = key({ envName: 'OPENAI_API_KEY', updatedAt: 2 })
await sync.push(renamed)
const scoped = key({
envName: 'OPENAI_API_KEY',
hostScope: { kind: 'hosts', hostIds: ['local'] },
updatedAt: 3
})
expect(await sync.push(scoped)).toEqual({ kind: 'skipped' })
expect(await sync.state([scoped])).toEqual({ signedIn: true, synced: [], managed: ['k1'] })
expect(await sync.beforeRemove(scoped, true)).toMatchObject({ ok: true })
expect(client.remove.mock.calls.map(([, name]) => name).sort()).toEqual([
'ANTHROPIC_API_KEY',
'OPENAI_API_KEY'
])
})
it('does not claim a write that raced an account switch', async () => {
const { client, sync, signInAs } = setup()
vi.spyOn(console, 'warn').mockImplementation(() => {})
client.put.mockImplementationOnce(async () => {
signInAs('user-b')
return {
scope: 'personal',
name: 'ANTHROPIC_API_KEY',
kind: 'agent_key',
hint: null,
updatedAt: 1,
updatedBy: 'user-b'
}
})
expect(await sync.push(key())).toEqual({ kind: 'failed', error: 'unauthorized', keyId: 'k1' })
signInAs('user-a')
expect(await sync.state([key()])).toEqual({ signedIn: true, synced: [], managed: [] })
vi.mocked(console.warn).mockRestore()
})
it('records a write made by the cloud workspace setup', async () => {
const { sync } = setup()
await sync.record(key())
expect(await sync.state([key()])).toEqual({ signedIn: true, synced: ['k1'], managed: ['k1'] })
await sync.record(key({ id: 'b', envName: 'AWS_BEARER_TOKEN_BEDROCK' }))
expect(await sync.state([key({ id: 'b', envName: 'AWS_BEARER_TOKEN_BEDROCK' })])).toMatchObject(
{
managed: []
}
)
})
})
@@ -0,0 +1,300 @@
// D12: while signed in to Orca, a saved Agent API key is also written to the user's personal Cloud
// secret of the same variable. Cloud secrets are write-only, so this is one way (desktop → account),
// and a key removed here leaves the account copy alone unless this computer wrote it and the user
// confirms. The ledger records which variables this computer wrote, per account; it holds no values.
import { readFile } from 'node:fs/promises'
import { writeSecureFile } from '../../shared/secure-storage/secure-file'
import type { AgentApiKeySummary } from '../../shared/agent-api-keys/agent-api-key-catalog'
import {
agentApiKeyCloudEligible,
type AgentApiKeyCloudOutcome,
type AgentApiKeysCloudState
} from '../../shared/agent-api-keys/agent-api-key-cloud'
import { cloudSecretValueError } from '../../shared/cloud-secrets/cloud-secret-rules'
import type { CloudSecretsErrorCode } from '../../shared/cloud-secrets/cloud-secrets-wire'
import {
cloudSecretsFailureCode,
type CloudSecretsClient
} from '../cloud-secrets/cloud-secrets-client'
/** The signed-in account that can hold personal Cloud secrets, or null (signed out, no Cloud). */
export type AgentApiKeyCloudConnection = {
accountId: string
client: Pick<CloudSecretsClient, 'put' | 'remove'>
/** False once the user signs in, out or switches account or team after this was read. */
isCurrent: () => boolean
}
type LedgerEntry = {
/** The vault key whose value was written. */
keyId: string
/** That key's `updatedAt` when it was written, so a later edit that failed to sync isn't "synced". */
keyUpdatedAt: number
syncedAt: number
}
type LedgerFile = {
version: 1
/** accountId → variable → what this computer wrote there. */
accounts: Record<string, Record<string, LedgerEntry>>
}
const MAX_LEDGER_BYTES = 256 * 1024
const PERSONAL = { scope: 'personal' } as const
function isEntry(value: unknown): value is LedgerEntry {
return (
typeof value === 'object' &&
value !== null &&
'keyId' in value &&
'keyUpdatedAt' in value &&
'syncedAt' in value &&
typeof value.keyId === 'string' &&
typeof value.keyUpdatedAt === 'number' &&
typeof value.syncedAt === 'number'
)
}
function parseLedger(text: string): LedgerFile {
const ledger: LedgerFile = { version: 1, accounts: {} }
if (text.length > MAX_LEDGER_BYTES) {
return ledger
}
let parsed: unknown
try {
parsed = JSON.parse(text)
} catch {
return ledger
}
if (
typeof parsed !== 'object' ||
parsed === null ||
!('version' in parsed) ||
parsed.version !== 1 ||
!('accounts' in parsed) ||
typeof parsed.accounts !== 'object' ||
parsed.accounts === null
) {
return ledger
}
for (const [accountId, names] of Object.entries(parsed.accounts)) {
if (typeof names !== 'object' || names === null) {
continue
}
const kept: Record<string, LedgerEntry> = {}
for (const [name, entry] of Object.entries(names)) {
if (isEntry(entry)) {
kept[name] = entry
}
}
ledger.accounts[accountId] = kept
}
return ledger
}
export type AgentApiKeyCloudSyncOptions = {
ledgerPath: string
/** Null when signed out of Orca or Orca Cloud isn't offered: keys then stay on this computer. */
connection: () => Promise<AgentApiKeyCloudConnection | null>
/** Unseals one vault key for a single write. */
valueOf: (keyId: string) => Promise<string | null>
/** The vault's keys now, to tell whether another key owns a variable's account copy. */
listKeys: () => Promise<AgentApiKeySummary[]>
now?: () => number
}
/** The variables `keyId` wrote to the account (more than one after a rename). */
function namesWrittenBy(names: Record<string, LedgerEntry>, keyId: string): string[] {
return Object.entries(names)
.filter(([, entry]) => entry.keyId === keyId)
.map(([name]) => name)
}
export class AgentApiKeyCloudSync {
private cached: LedgerFile | null = null
constructor(private readonly options: AgentApiKeyCloudSyncOptions) {}
private now(): number {
return this.options.now?.() ?? Date.now()
}
private async ledger(): Promise<LedgerFile> {
if (this.cached) {
return this.cached
}
let text = ''
try {
text = await readFile(this.options.ledgerPath, 'utf8')
} catch {
// Missing or unreadable: nothing was synced from here that we can prove, so remove nothing.
}
return (this.cached = parseLedger(text))
}
private async setNames(accountId: string, names: Record<string, LedgerEntry>): Promise<void> {
const ledger = await this.ledger()
const next: LedgerFile = { ...ledger, accounts: { ...ledger.accounts, [accountId]: names } }
writeSecureFile(this.options.ledgerPath, JSON.stringify(next, null, 2))
this.cached = next
}
private async connection(): Promise<AgentApiKeyCloudConnection | null> {
try {
return await this.options.connection()
} catch {
return null
}
}
async state(keys: readonly AgentApiKeySummary[]): Promise<AgentApiKeysCloudState> {
const connection = await this.connection()
if (!connection) {
return { signedIn: false, synced: [], managed: [] }
}
const names = (await this.ledger()).accounts[connection.accountId] ?? {}
const managed = keys.filter((key) => namesWrittenBy(names, key.id).length > 0)
return {
signedIn: true,
managed: managed.map((key) => key.id),
synced: managed
.filter((key) => {
const entry = names[key.envName]
return (
agentApiKeyCloudEligible(key) &&
entry?.keyId === key.id &&
entry.keyUpdatedAt === key.updatedAt
)
})
.map((key) => key.id)
}
}
/**
* Writes one vault key to the personal Cloud secret of its variable. Skips (no error) when signed
* out or when the key is scoped to some hosts; a variable the proxy can't swap is refused, because
* the workspace would hold it in full. When another vault key (another agent's) wrote that
* variable, only an explicit `replace` overwrites it.
*/
async push(
key: AgentApiKeySummary,
{ replace = false }: { replace?: boolean } = {}
): Promise<AgentApiKeyCloudOutcome> {
const connection = await this.connection()
if (!connection || key.hostScope.kind !== 'all') {
return { kind: 'skipped' }
}
const failed = (error: CloudSecretsErrorCode): AgentApiKeyCloudOutcome => ({
kind: 'failed',
error,
keyId: key.id
})
if (!agentApiKeyCloudEligible(key)) {
return failed('not_swappable')
}
const owner = (await this.ledger()).accounts[connection.accountId]?.[key.envName]?.keyId
if (
!replace &&
owner !== undefined &&
owner !== key.id &&
(await this.options.listKeys()).some((other) => other.id === owner)
) {
return failed('desktop_key_conflict')
}
const value = await this.options.valueOf(key.id)
if (!value) {
return failed('not_found')
}
const valueError = cloudSecretValueError(key.envName, value)
if (valueError) {
return failed(valueError)
}
try {
await connection.client.put(PERSONAL, key.envName, value)
} catch (error) {
return failed(logged('save', cloudSecretsFailureCode(error)))
}
// A sign-in or account switch mid-write: the token may have been another account's, so this
// computer can't claim the variable (and must never later delete it on that claim).
if (!connection.isCurrent()) {
return failed(logged('save', 'unauthorized'))
}
const names = { ...(await this.ledger()).accounts[connection.accountId] }
names[key.envName] = { keyId: key.id, keyUpdatedAt: key.updatedAt, syncedAt: this.now() }
await this.setNames(connection.accountId, names)
return { kind: 'synced' }
}
/** Records a write of `key` made elsewhere (the cloud workspace setup's "Save to your Orca account"). */
async record(key: AgentApiKeySummary): Promise<void> {
const connection = await this.connection()
if (!connection || !agentApiKeyCloudEligible(key)) {
return
}
const names = { ...(await this.ledger()).accounts[connection.accountId] }
names[key.envName] = { keyId: key.id, keyUpdatedAt: key.updatedAt, syncedAt: this.now() }
await this.setNames(connection.accountId, names)
}
/**
* Before the vault removes `key`: with `fromAccount`, deletes every account copy this computer
* wrote from this key (its current and any earlier variable). Returns an error code to abort the
* removal (nothing changed), or the variables to forget once the vault has removed the key.
*/
async beforeRemove(
key: AgentApiKeySummary,
fromAccount: boolean
): Promise<
| { ok: true; removedFromAccount: boolean; forget: () => Promise<void> }
| { ok: false; error: CloudSecretsErrorCode }
> {
const connection = await this.connection()
if (!connection) {
return fromAccount
? { ok: false, error: 'unauthorized' }
: { ok: true, removedFromAccount: false, forget: async () => {} }
}
const written = namesWrittenBy(
(await this.ledger()).accounts[connection.accountId] ?? {},
key.id
)
if (fromAccount && written.length === 0) {
// Nothing this computer wrote: never delete a secret the user made elsewhere.
return { ok: false, error: 'not_found' }
}
if (fromAccount) {
for (const name of written) {
if (!connection.isCurrent()) {
return { ok: false, error: logged('remove', 'unauthorized') }
}
try {
await connection.client.remove(PERSONAL, name)
} catch (error) {
const code = cloudSecretsFailureCode(error)
// Already gone from the account is what the user asked for.
if (code !== 'not_found') {
return { ok: false, error: logged('remove', code) }
}
}
}
}
return {
ok: true,
removedFromAccount: fromAccount,
// Removed, or the user chose to keep it there: either way this computer stops managing it.
forget: async () => {
const { [connection.accountId]: names = {} } = (await this.ledger()).accounts
const rest = Object.fromEntries(
Object.entries(names).filter(([, entry]) => entry.keyId !== key.id)
)
await this.setNames(connection.accountId, rest)
}
}
}
}
function logged(action: string, code: CloudSecretsErrorCode): CloudSecretsErrorCode {
// Codes only: a message or body could quote the value.
console.warn(`[agent-api-keys] could not ${action} in the Orca account: ${code}`)
return code
}
@@ -0,0 +1,157 @@
import { describe, expect, it, vi } from 'vitest'
import type {
AgentApiKeySaveRequest,
AgentApiKeySummary
} from '../../shared/agent-api-keys/agent-api-key-catalog'
import { CLOUD_SWAPPED_CREDENTIALS } from '../../shared/cloud-secrets/cloud-secret-rules'
import { importLocalAgentKeys, parseImportNames, scanSummary } from './agent-api-key-import'
import { AgentApiKeyError } from './agent-api-key-store'
import { SWAPPABLE_AGENT_KEY_NAMES, type LocalAgentCredentials } from './local-agent-credentials'
const OPENAI = 'sk-proj-import-secret-value-a1B2'
const GATEWAY = 'vck_import_secret_value_gw90'
const GEMINI = 'AIzaSy-import-secret-value-Zk19'
const FOUND: LocalAgentCredentials = {
keys: [
{ name: 'OPENAI_API_KEY', value: OPENAI, source: 'shell-env' },
{ name: 'AI_GATEWAY_API_KEY', value: GATEWAY, source: 'opencode-auth' },
{ name: 'GEMINI_API_KEY', value: GEMINI, source: 'gemini-env-file' }
],
signIns: [{ agent: 'opencode', provider: 'anthropic' }]
}
function summary(request: AgentApiKeySaveRequest, id: string): AgentApiKeySummary {
return {
id,
agent: request.agent,
envName: request.envName,
hostScope: request.hostScope,
hint: request.value?.slice(-4) ?? '',
updatedAt: 1
}
}
describe('scanSummary', () => {
it('gives the renderer names, sources and last fours, never a value', () => {
const saved = [
summary({ agent: 'gemini', envName: 'GEMINI_API_KEY', hostScope: { kind: 'all' } }, 'g')
]
const result = scanSummary(FOUND, saved)
expect(result).toEqual({
keys: [
{
name: 'OPENAI_API_KEY',
agent: 'codex',
source: 'shell-env',
hint: 'a1B2',
alreadySaved: false
},
{
name: 'AI_GATEWAY_API_KEY',
agent: 'opencode',
source: 'opencode-auth',
hint: 'gw90',
alreadySaved: false
},
{
name: 'GEMINI_API_KEY',
agent: 'gemini',
source: 'gemini-env-file',
hint: 'Zk19',
alreadySaved: true
}
],
signIns: [{ agent: 'opencode', provider: 'anthropic' }]
})
const wire = JSON.stringify(result)
for (const value of [OPENAI, GATEWAY, GEMINI]) {
expect(wire).not.toContain(value)
expect(wire).not.toContain(value.slice(0, -4))
}
})
it('only offers names the egress proxy swaps', () => {
for (const name of SWAPPABLE_AGENT_KEY_NAMES) {
expect(CLOUD_SWAPPED_CREDENTIALS).toContain(name)
}
})
})
describe('parseImportNames', () => {
it('accepts known swappable names only', () => {
expect(parseImportNames(['OPENAI_API_KEY', 'OPENAI_API_KEY'])).toEqual(['OPENAI_API_KEY'])
expect(parseImportNames(['PATH'])).toBeNull()
expect(parseImportNames('OPENAI_API_KEY')).toBeNull()
expect(parseImportNames([])).toBeNull()
})
})
describe('importLocalAgentKeys', () => {
it('saves chosen keys for every host, pushes each to the account, and skips saved ones', async () => {
const saved: AgentApiKeySummary[] = [
summary({ agent: 'gemini', envName: 'GEMINI_API_KEY', hostScope: { kind: 'all' } }, 'g')
]
const store = {
list: async () => saved,
save: vi.fn(async (request: AgentApiKeySaveRequest) => {
const next = summary(request, `id-${saved.length}`)
saved.push(next)
return next
})
}
const push = vi.fn(async (key: AgentApiKeySummary) =>
key.envName === 'AI_GATEWAY_API_KEY'
? ({ kind: 'failed', error: 'unavailable', keyId: key.id } as const)
: ({ kind: 'synced' } as const)
)
const result = await importLocalAgentKeys({
names: ['OPENAI_API_KEY', 'AI_GATEWAY_API_KEY', 'GEMINI_API_KEY'],
found: FOUND,
store,
push
})
expect(store.save).toHaveBeenCalledWith({
agent: 'codex',
envName: 'OPENAI_API_KEY',
value: OPENAI,
hostScope: { kind: 'all' }
})
expect(result).toEqual({
imported: ['OPENAI_API_KEY', 'AI_GATEWAY_API_KEY'],
failed: [
{ name: 'GEMINI_API_KEY', error: 'Already saved. Edit the saved key to change it.' }
],
cloudFailed: [{ name: 'AI_GATEWAY_API_KEY', error: 'unavailable' }]
})
expect(push).toHaveBeenCalledTimes(2)
})
it('reports vault errors with Orca copy only, and a name no longer found', async () => {
const store = {
list: async () => [],
save: vi.fn(async () => {
throw new Error(`boom ${OPENAI}`)
})
}
const result = await importLocalAgentKeys({
names: ['OPENAI_API_KEY', 'CURSOR_API_KEY'],
found: FOUND,
store,
push: async () => ({ kind: 'synced' })
})
expect(result.failed).toEqual([
{ name: 'OPENAI_API_KEY', error: 'Orca could not save the key.' },
{ name: 'CURSOR_API_KEY', error: 'Orca no longer finds this key on this computer.' }
])
expect(JSON.stringify(result)).not.toContain(OPENAI)
store.save.mockRejectedValueOnce(new AgentApiKeyError('Keys are a single line.'))
const again = await importLocalAgentKeys({
names: ['OPENAI_API_KEY'],
found: FOUND,
store,
push: async () => ({ kind: 'synced' })
})
expect(again.failed).toEqual([{ name: 'OPENAI_API_KEY', error: 'Keys are a single line.' }])
})
})
@@ -0,0 +1,133 @@
// "Import from this Mac": main finds agent keys this computer already uses; the renderer only ever
// sees names, where each was found and the last four characters. Values are re-read here at import
// time and go straight into the sealed vault (and the Orca account when signed in).
import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent'
import {
MAX_AGENT_API_KEY_IMPORT,
type AgentApiKeyCloudOutcome,
type AgentApiKeysImportResult,
type AgentApiKeysScanResult
} from '../../shared/agent-api-keys/agent-api-key-cloud'
import type { AgentApiKeySummary } from '../../shared/agent-api-keys/agent-api-key-catalog'
import { AgentApiKeyError, type AgentApiKeyStore } from './agent-api-key-store'
import {
SWAPPABLE_AGENT_KEY_NAMES,
type LocalAgentCredentials,
type LocalAgentKey,
type SwappableAgentKeyName
} from './local-agent-credentials'
/** The vault agent an imported key belongs to: the tool whose file held it, else the CLI that reads it. */
const AGENT_BY_NAME: Record<SwappableAgentKeyName, TuiAgent> = {
ANTHROPIC_API_KEY: 'claude',
OPENAI_API_KEY: 'codex',
GEMINI_API_KEY: 'gemini',
GOOGLE_GENERATIVE_AI_API_KEY: 'opencode',
CURSOR_API_KEY: 'cursor',
AI_GATEWAY_API_KEY: 'opencode'
}
export function importAgentFor(key: Pick<LocalAgentKey, 'name' | 'source'>): TuiAgent {
if (key.source === 'opencode-auth') {
return 'opencode'
}
if (key.source === 'gemini-env-file') {
return 'gemini'
}
return AGENT_BY_NAME[key.name]
}
function alreadySaved(keys: readonly AgentApiKeySummary[], agent: TuiAgent, name: string): boolean {
return keys.some((key) => key.agent === agent && key.envName === name)
}
/** What the renderer may see of a scan: no value, no part of one beyond the last four. */
export function scanSummary(
found: LocalAgentCredentials,
saved: readonly AgentApiKeySummary[]
): AgentApiKeysScanResult {
return {
keys: found.keys.map((key) => {
const agent = importAgentFor(key)
return {
name: key.name,
agent,
source: key.source,
hint: key.value.slice(-4),
alreadySaved: alreadySaved(saved, agent, key.name)
}
}),
signIns: found.signIns.map(({ agent, provider }) => ({ agent, provider }))
}
}
export function parseImportNames(raw: unknown): SwappableAgentKeyName[] | null {
if (!Array.isArray(raw) || raw.length === 0 || raw.length > MAX_AGENT_API_KEY_IMPORT) {
return null
}
const names = new Set<SwappableAgentKeyName>()
for (const name of raw) {
const known = SWAPPABLE_AGENT_KEY_NAMES.find((candidate) => candidate === name)
if (!known) {
return null
}
names.add(known)
}
return [...names]
}
/**
* Saves the chosen names from a fresh scan. A name the vault already holds for that agent is left
* alone (the user edits it instead), so an import never overwrites a key silently.
*/
export async function importLocalAgentKeys(input: {
names: readonly SwappableAgentKeyName[]
found: LocalAgentCredentials
store: Pick<AgentApiKeyStore, 'list' | 'save'>
push: (key: AgentApiKeySummary) => Promise<AgentApiKeyCloudOutcome>
}): Promise<Omit<AgentApiKeysImportResult, 'state'>> {
const result: Omit<AgentApiKeysImportResult, 'state'> = {
imported: [],
failed: [],
cloudFailed: []
}
for (const name of input.names) {
const key = input.found.keys.find((entry) => entry.name === name)
if (!key) {
result.failed.push({
name,
error: 'Orca no longer finds this key on this computer.'
})
continue
}
const agent = importAgentFor(key)
if (alreadySaved(await input.store.list(), agent, name)) {
result.failed.push({
name,
error: 'Already saved. Edit the saved key to change it.'
})
continue
}
let saved: AgentApiKeySummary
try {
saved = await input.store.save({
agent,
envName: name,
value: key.value,
hostScope: { kind: 'all' }
})
} catch (error) {
result.failed.push({
name,
error: error instanceof AgentApiKeyError ? error.message : 'Orca could not save the key.'
})
continue
}
result.imported.push(name)
const cloud = await input.push(saved)
if (cloud.kind === 'failed') {
result.cloudFailed.push({ name, error: cloud.error })
}
}
return result
}
+57 -30
View File
@@ -1,51 +1,78 @@
import { ipcMain } from 'electron'
import { join } from 'node:path'
import type {
AgentApiKeySaveRequest,
AgentApiKeysMutationResult,
AgentApiKeysState
import {
selectAgentApiKeys,
type AgentApiKeySaveRequest
} from '../../shared/agent-api-keys/agent-api-key-catalog'
import { AgentApiKeyError, AgentApiKeyStore } from './agent-api-key-store'
import { toRuntimeExecutionHostId } from '../../shared/execution-host'
import { AgentApiKeyStore } from './agent-api-key-store'
import { mutate, stateOf } from './agent-api-key-state'
import { installAgentApiKeyLaunchEnvResolver } from './agent-api-key-launch-env'
import { AgentApiKeyCloudSync } from './agent-api-key-cloud-sync'
import {
agentApiKeyCloudConnection,
setAgentApiKeyCloudRecorder
} from './agent-api-key-cloud-connection'
import { registerAgentApiKeyCloudHandlers, removeRequestOf } from './agent-api-key-cloud-ipc'
/** A host id no host-scoped key names, as in desktopKeyValueForCloud. */
const ANY_CLOUD_HOST = toRuntimeExecutionHostId('orca-cloud')
const CHANNELS = ['agentApiKeys:list', 'agentApiKeys:save', 'agentApiKeys:remove'] as const
async function stateOf(store: AgentApiKeyStore): Promise<AgentApiKeysState> {
return { keys: await store.list(), protection: store.protection() }
}
async function mutate(
store: AgentApiKeyStore,
run: () => Promise<unknown>
): Promise<AgentApiKeysMutationResult> {
try {
await run()
return { ok: true, state: await stateOf(store) }
} catch (error) {
// Only our own messages reach the renderer: anything else could quote a value.
const message =
error instanceof AgentApiKeyError ? error.message : 'Orca could not save the key.'
return { ok: false, error: message, state: await stateOf(store) }
}
}
/** Values only ever travel renderer → main here; nothing returns them. */
export function registerAgentApiKeyHandlers(userDataPath: string): AgentApiKeyStore {
const store = new AgentApiKeyStore(join(userDataPath, 'agent-api-keys.json'))
const cloud = new AgentApiKeyCloudSync({
ledgerPath: join(userDataPath, 'agent-api-keys-cloud-ledger.json'),
connection: agentApiKeyCloudConnection,
valueOf: (id) => store.valueOf(id),
listKeys: () => store.list()
})
// Saves, removals and imports touch the vault and the ledger; one at a time keeps them in step.
let queue: Promise<unknown> = Promise.resolve()
const serial = <T>(run: () => Promise<T>): Promise<T> => {
const next = queue.then(run, run)
queue = next.catch(() => undefined)
return next
}
installAgentApiKeyLaunchEnvResolver((agent, hostId) => store.launchEnv(agent, hostId))
for (const channel of CHANNELS) {
ipcMain.removeHandler(channel)
}
ipcMain.handle('agentApiKeys:list', () => stateOf(store))
ipcMain.handle('agentApiKeys:list', () => stateOf(store, cloud))
ipcMain.handle('agentApiKeys:save', (_event, request: AgentApiKeySaveRequest) =>
mutate(store, () => store.save(request))
serial(() => mutate(store, cloud, async () => cloud.push(await store.save(request))))
)
ipcMain.handle('agentApiKeys:remove', (_event, id: unknown) =>
mutate(store, async () => {
if (typeof id === 'string') {
await store.remove(id)
ipcMain.handle('agentApiKeys:remove', (_event, raw: unknown) =>
serial(() =>
mutate(store, cloud, async () => {
const request = removeRequestOf(raw)
const key = request ? (await store.list()).find((entry) => entry.id === request.id) : null
if (!request || !key) {
return
}
const account = await cloud.beforeRemove(key, request.fromAccount)
if (!account.ok) {
return { kind: 'failed', error: account.error }
}
await store.remove(key.id)
await account.forget()
return account.removedFromAccount ? { kind: 'removed' } : { kind: 'skipped' }
})
)
)
// The key desktopKeyValueForCloud picks: this agent's every-host key for the variable.
setAgentApiKeyCloudRecorder((agent, envName) =>
serial(async () => {
const key = selectAgentApiKeys(await store.list(), agent, ANY_CLOUD_HOST).find(
(entry) => entry.envName === envName
)
if (key) {
await cloud.record(key)
}
})
)
registerAgentApiKeyCloudHandlers({ store, cloud, serial })
return store
}
@@ -0,0 +1,39 @@
import type {
AgentApiKeysMutationResult,
AgentApiKeysState
} from '../../shared/agent-api-keys/agent-api-key-catalog'
import type { AgentApiKeyCloudOutcome } from '../../shared/agent-api-keys/agent-api-key-cloud'
import type { AgentApiKeyCloudSync } from './agent-api-key-cloud-sync'
import { AgentApiKeyError, type AgentApiKeyStore } from './agent-api-key-store'
export async function stateOf(
store: AgentApiKeyStore,
cloud: AgentApiKeyCloudSync
): Promise<AgentApiKeysState> {
const keys = await store.list()
return {
keys,
protection: store.protection(),
cloud: await cloud.state(keys)
}
}
export async function mutate(
store: AgentApiKeyStore,
cloud: AgentApiKeyCloudSync,
run: () => Promise<AgentApiKeyCloudOutcome | void>
): Promise<AgentApiKeysMutationResult> {
try {
const outcome = await run()
return {
ok: true,
state: await stateOf(store, cloud),
...(outcome ? { cloud: outcome } : {})
}
} catch (error) {
// Only our own messages reach the renderer: anything else could quote a value.
const message =
error instanceof AgentApiKeyError ? error.message : 'Orca could not save the key.'
return { ok: false, error: message, state: await stateOf(store, cloud) }
}
}
@@ -204,6 +204,22 @@ export class AgentApiKeyStore {
}
}
/** Main only: one key's value, unsealed for a single write to the user's Orca account. */
async valueOf(id: string): Promise<string | null> {
const key = ((await this.read())?.keys ?? []).find((entry) => entry.id === id)
const store = getSecretStore()
if (!key || !store.isEncryptionAvailable()) {
return null
}
try {
const value = store.decryptString(Buffer.from(key.ciphertext, 'base64'))
registerRedactedSecretValue(value)
return value
} catch {
return null
}
}
/** The env one launch of `agent` on `hostId` gets. Keys that fail to unseal are skipped, never sent half-read. */
async launchEnv(agent: TuiAgent, hostId: ExecutionHostId): Promise<Record<string, string>> {
const keys = (await this.read())?.keys ?? []
@@ -0,0 +1,118 @@
import { describe, expect, it } from 'vitest'
import { readLocalAgentCredentials } from './local-agent-credentials'
const HOME = '/home/u'
function files(map: Record<string, string>) {
return {
readText: async (path: string) => map[path] ?? null,
exists: async (path: string) => path in map
}
}
describe('readLocalAgentCredentials', () => {
it('offers OpenCode API keys under the env names the egress proxy swaps, and lists OAuth sign-ins without copying them', async () => {
const auth = JSON.stringify({
anthropic: {
type: 'oauth',
refresh: 'rt-secret',
access: 'at-secret',
expires: 1
},
openai: { type: 'api', key: 'sk-proj-openai-1234' },
google: { type: 'api', key: 'AIzaSy-google-5678' },
vercel: { type: 'api', key: 'vck_gateway_9012' },
openrouter: { type: 'api', key: 'sk-or-not-swapped' },
'github-copilot': {
type: 'oauth',
refresh: 'gho_x',
access: 'y',
expires: 2
}
})
const found = await readLocalAgentCredentials({
home: HOME,
env: {},
...files({ '/home/u/.local/share/opencode/auth.json': auth })
})
expect(found.keys).toEqual([
{
name: 'OPENAI_API_KEY',
value: 'sk-proj-openai-1234',
source: 'opencode-auth'
},
{
name: 'GOOGLE_GENERATIVE_AI_API_KEY',
value: 'AIzaSy-google-5678',
source: 'opencode-auth'
},
{
name: 'AI_GATEWAY_API_KEY',
value: 'vck_gateway_9012',
source: 'opencode-auth'
}
])
expect(found.signIns).toEqual([
{ agent: 'opencode', provider: 'anthropic' },
{ agent: 'opencode', provider: 'github-copilot' }
])
expect(JSON.stringify(found)).not.toMatch(/rt-secret|at-secret|gho_x|sk-or-not-swapped/)
})
it('reads Gemini keys from ~/.gemini/.env and Cursor/Gemini keys from the shell env; first source wins', async () => {
const found = await readLocalAgentCredentials({
home: HOME,
env: {
GEMINI_API_KEY: 'AIzaSy-shell-0000',
CURSOR_API_KEY: 'key_cursor_shell_1',
ANTHROPIC_API_KEY: ' '
},
...files({
'/home/u/.gemini/.env': 'export GEMINI_API_KEY="AIzaSy-file-1111"\nOTHER=x\n',
'/home/u/.gemini/oauth_creds.json': '{}'
})
})
expect(found.keys).toEqual([
{
name: 'GEMINI_API_KEY',
value: 'AIzaSy-file-1111',
source: 'gemini-env-file'
},
{
name: 'CURSOR_API_KEY',
value: 'key_cursor_shell_1',
source: 'shell-env'
}
])
expect(found.signIns).toEqual([{ agent: 'gemini', provider: 'google' }])
})
it('ignores unreadable files and honours XDG_DATA_HOME', async () => {
expect(
await readLocalAgentCredentials({
home: HOME,
env: {},
...files({
'/home/u/.local/share/opencode/auth.json': '{not json'
})
})
).toEqual({ keys: [], signIns: [] })
const auth = JSON.stringify({
anthropic: { type: 'api', key: 'sk-ant-api03-xdg' }
})
expect(
(
await readLocalAgentCredentials({
home: HOME,
env: { XDG_DATA_HOME: '/data' },
...files({ '/data/opencode/auth.json': auth })
})
).keys
).toEqual([
{
name: 'ANTHROPIC_API_KEY',
value: 'sk-ant-api03-xdg',
source: 'opencode-auth'
}
])
})
})
@@ -0,0 +1,162 @@
// What this computer already uses to sign agents in, so an Orca Cloud workspace can start with the
// same credentials. API keys are offered for the cloud secret store, where the egress proxy swaps
// them in (the VM only ever holds a placeholder). OAuth/subscription sign-ins are never copied:
// they can't be swapped, and the user signs in once on the workspace instead.
import { constants } from 'node:fs'
import { access, open, stat, type FileHandle } from 'node:fs/promises'
import { homedir } from 'node:os'
import { join } from 'node:path'
import { parseDotenvPaste } from '../../shared/cloud-secrets/dotenv-paste'
/** Names the egress proxy swaps (cloud/apps/sandbox-control/src/provider-env.ts), per agent that reads them. */
export const SWAPPABLE_AGENT_KEY_NAMES = [
'ANTHROPIC_API_KEY',
'OPENAI_API_KEY',
'GEMINI_API_KEY',
'GOOGLE_GENERATIVE_AI_API_KEY',
'CURSOR_API_KEY',
'AI_GATEWAY_API_KEY'
] as const
export type SwappableAgentKeyName = (typeof SWAPPABLE_AGENT_KEY_NAMES)[number]
/** OpenCode auth.json provider id -> the env name OpenCode also reads for that provider. */
const OPENCODE_PROVIDER_ENV: Record<string, SwappableAgentKeyName> = {
anthropic: 'ANTHROPIC_API_KEY',
openai: 'OPENAI_API_KEY',
google: 'GOOGLE_GENERATIVE_AI_API_KEY',
vercel: 'AI_GATEWAY_API_KEY'
}
export type LocalAgentKey = {
name: SwappableAgentKeyName
value: string
/** Where it was found, for the confirmation copy (never the value). */
source: 'opencode-auth' | 'gemini-env-file' | 'shell-env'
}
/** A sign-in that stays on this computer; the user signs in on the workspace instead. */
export type LocalAgentSignIn = {
agent: 'opencode' | 'gemini'
/** Provider (OpenCode) or method (Gemini) the sign-in is for. */
provider: string
}
export type LocalAgentCredentials = {
keys: LocalAgentKey[]
signIns: LocalAgentSignIn[]
}
type Sources = {
home: string
env: Readonly<Record<string, string | undefined>>
readText: (path: string) => Promise<string | null>
/** Sign-in files are only checked for, never read. */
exists: (path: string) => Promise<boolean>
}
/** Agent credential files are small; anything bigger isn't one. */
const MAX_FILE_BYTES = 256 * 1024
async function defaultExists(path: string): Promise<boolean> {
try {
await access(path)
return true
} catch {
return false
}
}
/** A regular file under the cap, read without blocking on a FIFO or following it into a device. */
async function defaultReadText(path: string): Promise<string | null> {
let handle: FileHandle | null = null
try {
const info = await stat(path)
if (!info.isFile() || info.size > MAX_FILE_BYTES) {
return null
}
handle = await open(path, constants.O_RDONLY | constants.O_NONBLOCK)
const opened = await handle.stat()
if (!opened.isFile() || opened.size > MAX_FILE_BYTES) {
return null
}
return await handle.readFile('utf8')
} catch {
return null
} finally {
await handle?.close().catch(() => undefined)
}
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function usable(value: unknown): value is string {
return (
typeof value === 'string' &&
value.trim().length >= 8 &&
value.length <= 16 * 1024 &&
!/\s/.test(value.trim())
)
}
/**
* First source wins per name: OpenCode's own auth file, then Gemini's ~/.gemini/.env, then the login
* shell's env (what an agent started from a terminal here would see).
*/
export async function readLocalAgentCredentials(
sources: Partial<Sources> = {}
): Promise<LocalAgentCredentials> {
const home = sources.home ?? homedir()
const env = sources.env ?? process.env
const readText = sources.readText ?? defaultReadText
const exists = sources.exists ?? defaultExists
const keys = new Map<SwappableAgentKeyName, LocalAgentKey>()
const signIns: LocalAgentSignIn[] = []
const offer = (name: SwappableAgentKeyName, value: unknown, source: LocalAgentKey['source']) => {
if (!keys.has(name) && usable(value)) {
keys.set(name, { name, value: value.trim(), source })
}
}
const dataHome = env.XDG_DATA_HOME || join(home, '.local', 'share')
const opencode = await readText(join(dataHome, 'opencode', 'auth.json'))
if (opencode) {
let parsed: unknown = null
try {
parsed = JSON.parse(opencode)
} catch {
// A file OpenCode can't read either; nothing to offer.
}
if (isRecord(parsed)) {
for (const [provider, entry] of Object.entries(parsed)) {
if (!isRecord(entry)) {
continue
}
const name = OPENCODE_PROVIDER_ENV[provider]
if (entry.type === 'api' && name) {
offer(name, entry.key, 'opencode-auth')
} else if (entry.type === 'oauth' || entry.type === 'wellknown') {
signIns.push({ agent: 'opencode', provider })
}
}
}
}
const geminiEnv = await readText(join(home, '.gemini', '.env'))
if (geminiEnv) {
for (const entry of parseDotenvPaste(geminiEnv)) {
if (entry.name === 'GEMINI_API_KEY' || entry.name === 'GOOGLE_GENERATIVE_AI_API_KEY') {
offer(entry.name, entry.value, 'gemini-env-file')
}
}
}
if (await exists(join(home, '.gemini', 'oauth_creds.json'))) {
signIns.push({ agent: 'gemini', provider: 'google' })
}
for (const name of SWAPPABLE_AGENT_KEY_NAMES) {
offer(name, env[name], 'shell-env')
}
return { keys: [...keys.values()], signIns }
}
+12 -1
View File
@@ -29,6 +29,10 @@ import {
createCloudSecretsClient,
type CloudSecretsClient
} from './cloud-secrets-client'
import {
recordAgentApiKeyCloudWrite,
setAgentApiKeyCloudClient
} from '../agent-api-keys/agent-api-key-cloud-connection'
const Repo = z.string().trim().min(3).max(256)
const Target = z.object({ scope: z.enum(CLOUD_SECRET_SCOPES), repo: Repo.optional() })
@@ -113,6 +117,8 @@ export function registerCloudSecretsHandlers(userDataPath: string): void {
getAccessToken: config.getAccessToken
})
: null
// Agent API keys saved while signed in are written to personal secrets through the same client.
setAgentApiKeyCloudClient(client)
for (const channel of CHANNELS) {
ipcMain.removeHandler(channel)
}
@@ -177,7 +183,12 @@ export function registerCloudSecretsHandlers(userDataPath: string): void {
if (valueError) {
return { ok: false, error: valueError }
}
return attempt(client, (c) => c.put({ scope: 'personal' }, envName, value))
const result = await attempt(client, (c) => c.put({ scope: 'personal' }, envName, value))
if (result.ok) {
// So Settings › Agent API keys shows it as saved in the Orca account.
await recordAgentApiKeyCloudWrite(agent, envName)
}
return result
})
ipcMain.handle('cloudSecrets:refreshEnv', (_event, raw: unknown) => {
const request = RefreshRequest.safeParse(raw)
+17 -2
View File
@@ -4,16 +4,31 @@ import type {
AgentApiKeysMutationResult,
AgentApiKeysState
} from '../../shared/agent-api-keys/agent-api-key-catalog'
import type {
AgentApiKeyRemoveRequest,
AgentApiKeysImportResult,
AgentApiKeysScanResult
} from '../../shared/agent-api-keys/agent-api-key-cloud'
/** Desktop only. Values go in; nothing comes back but names, scopes and hints. */
export type AgentApiKeysApi = {
list: () => Promise<AgentApiKeysState>
save: (request: AgentApiKeySaveRequest) => Promise<AgentApiKeysMutationResult>
remove: (id: string) => Promise<AgentApiKeysMutationResult>
/** A bare id keeps any copy in the Orca account. */
remove: (request: string | AgentApiKeyRemoveRequest) => Promise<AgentApiKeysMutationResult>
/** Writes a key that is only on this computer to the Orca account. */
saveToAccount?: (id: string) => Promise<AgentApiKeysMutationResult>
/** Keys this computer already uses: names, sources and last fours only. */
scanThisComputer?: () => Promise<AgentApiKeysScanResult>
importFromThisComputer?: (names: string[]) => Promise<AgentApiKeysImportResult>
}
export const agentApiKeysApi: AgentApiKeysApi = {
list: () => ipcRenderer.invoke('agentApiKeys:list'),
save: (request) => ipcRenderer.invoke('agentApiKeys:save', request),
remove: (id) => ipcRenderer.invoke('agentApiKeys:remove', id)
remove: (request) => ipcRenderer.invoke('agentApiKeys:remove', request),
saveToAccount: (id) => ipcRenderer.invoke('agentApiKeys:saveToAccount', id),
scanThisComputer: () => ipcRenderer.invoke('agentApiKeys:scanThisComputer'),
importFromThisComputer: (names) =>
ipcRenderer.invoke('agentApiKeys:importFromThisComputer', names)
}
@@ -0,0 +1,195 @@
import { useState } from 'react'
import { Cloud, HardDrive, Loader2 } from 'lucide-react'
import type { AgentApiKeyCloudRowState } from '../../../../../shared/agent-api-keys/agent-api-key-cloud'
import type { CloudSecretsErrorCode } from '../../../../../shared/cloud-secrets/cloud-secrets-wire'
import { useTranslate } from '@/i18n/use-translate'
import { Button } from '../../ui/button'
import { InlineError } from '../../ui/inline-error'
import { cloudSecretsErrorCopy } from '../cloud-secrets/cloud-secrets-copy'
/** Where a key lives, under its row: the Orca account (with this computer as a cache) or here only. */
export function AgentApiKeyCloudLine({
envName,
state,
canSave,
failure,
onSaveToAccount
}: {
envName: string
state: AgentApiKeyCloudRowState
/** Every host and a variable the proxy swaps. */
canSave: boolean
failure: CloudSecretsErrorCode | undefined
onSaveToAccount: () => Promise<CloudSecretsErrorCode | null>
}): React.JSX.Element | null {
const t = useTranslate()
const [saving, setSaving] = useState(false)
if (state === 'none') {
return null
}
const save = async (): Promise<void> => {
if (saving) {
return
}
setSaving(true)
await onSaveToAccount()
setSaving(false)
}
return (
<div className="space-y-1 pl-[22px]">
<div className="flex min-h-6 items-center gap-2 text-xs text-muted-foreground">
{state === 'synced' ? (
<>
<Cloud aria-hidden className="size-3.5 shrink-0" />
<span>
{t(
'agentApiKeys.cloud.synced',
'Saved in your Orca account · cached on this computer'
)}
</span>
</>
) : (
<>
<HardDrive aria-hidden className="size-3.5 shrink-0" />
<span className="min-w-0 flex-1">
{state === 'not-swappable'
? t(
'agentApiKeys.cloud.notSwappable',
'Only on this computer · not used in Orca Cloud'
)
: state === 'stale'
? t(
'agentApiKeys.cloud.stale',
'Your Orca account has an earlier copy · cloud workspaces still use it'
)
: t('agentApiKeys.cloud.local', 'Only on this computer')}
</span>
{canSave && (state === 'local' || state === 'stale') ? (
<Button
type="button"
variant="outline"
size="xs"
className="shrink-0 aria-disabled:pointer-events-none"
aria-disabled={saving || undefined}
aria-busy={saving || undefined}
aria-label={t(
'agentApiKeys.cloud.saveLabel',
'Save {{name}} to your Orca account',
{
name: envName
}
)}
onClick={() => void save()}
>
{saving ? <Loader2 className="motion-safe:animate-spin" /> : null}
{t('agentApiKeys.cloud.save', 'Save to your Orca account')}
</Button>
) : null}
</>
)}
</div>
{failure && (state === 'local' || state === 'stale') ? (
<InlineError
layout="line"
title={t(
'agentApiKeys.cloud.saveFailed',
'Saved on this computer, but not in your Orca account.'
)}
detail={
// The generic transport copy says "Nothing was changed", which isn't true here.
failure === 'unavailable' || failure === 'timeout' || failure === 'unknown'
? t('agentApiKeys.cloud.saveFailedRetry', 'Couldn’t reach Orca Cloud. Try again.')
: cloudSecretsErrorCopy(failure, t)
}
/>
) : null}
</div>
)
}
/** Removing a key this computer saved to the Orca account asks what happens to that copy. */
export function AgentApiKeyRemoveFromAccountConfirm({
envName,
onCancel,
onRemove
}: {
envName: string
onCancel: () => void
onRemove: (fromAccount: boolean) => void
}): React.JSX.Element {
const t = useTranslate()
return (
<div
role="group"
aria-label={t('agentApiKeys.remove.confirmLabel', 'Remove {{name}}', {
name: envName
})}
className="ml-[22px] space-y-2 rounded-md border border-border bg-muted/40 px-3 py-2 text-xs"
>
<p className="text-foreground">
{t(
'agentApiKeys.remove.fromAccountQuestion',
'Also remove it from your Orca account? Cloud workspaces will stop using it.'
)}
</p>
<div className="flex flex-wrap items-center justify-end gap-1.5">
<Button variant="ghost" size="xs" onClick={onCancel}>
{t('auto.components.settings.agentApiKeys.keep', 'Keep')}
</Button>
<Button variant="outline" size="xs" onClick={() => onRemove(false)}>
{t('agentApiKeys.remove.thisComputerOnly', 'Remove from this computer only')}
</Button>
<Button variant="destructive-chip" size="xs" onClick={() => onRemove(true)}>
{t('agentApiKeys.remove.both', 'Remove from both')}
</Button>
</div>
</div>
)
}
export type AgentApiKeysNoticeState =
| { kind: 'kept'; envName: string }
| { kind: 'imported'; count: number }
| null
/** One line above the list: the last removal or import, or what failed. */
export function AgentApiKeysNotice({
failure,
notice
}: {
failure: string | null
notice: AgentApiKeysNoticeState
}): React.JSX.Element | null {
const t = useTranslate()
if (failure) {
return <InlineError density="compact" title={failure} />
}
if (notice?.kind === 'kept') {
return (
<InlineError
tone="neutral"
density="compact"
title={t(
'agentApiKeys.remove.kept',
'Removed from this computer. {{name}} is still in your Orca account.',
{ name: notice.envName }
)}
detail={t('agentApiKeys.remove.keptDetail', 'Manage it in Settings › Cloud secrets.')}
/>
)
}
if (notice?.kind === 'imported') {
return (
<InlineError
tone="neutral"
density="compact"
title={
notice.count === 1
? t('agentApiKeys.import.doneOne', 'Imported 1 key.')
: t('agentApiKeys.import.done', 'Imported {{count}} keys.', { count: notice.count })
}
/>
)
}
return null
}
@@ -0,0 +1,237 @@
import { useState } from 'react'
import { KeyRound, Loader2, LogIn } from 'lucide-react'
import type { AgentApiKeysImportResult } from '../../../../../shared/agent-api-keys/agent-api-key-cloud'
import { AgentIcon } from '@/components/agent/icons/AgentIcon'
import { getAgentLabel } from '@/lib/agent-catalog/agent-catalog'
import { useTranslate } from '@/i18n/use-translate'
import { Button } from '../../ui/button'
import { Checkbox } from '../../ui/checkbox'
import { InlineError } from '../../ui/inline-error'
import { Skeleton } from '../../ui/skeleton'
import type { AgentApiKeysModel } from './use-agent-api-keys'
import {
defaultImportSelection,
importOutcome,
importSourceLabel,
isMacPlatform,
signInProviderLabel,
type ImportScanState
} from './agent-api-keys-import'
/**
* Keys this computer already uses, by name only: main holds the values and re-reads them on import.
* Sign-ins are listed so the user knows they weren't copied.
*/
/** The import panel's state: closed (null), scanning, failed or ready, and the import itself. */
export function useAgentApiKeysImport(
model: Pick<AgentApiKeysModel, 'scanThisComputer' | 'importFromThisComputer'>,
initial: ImportScanState | null,
onDone: (outcome: ReturnType<typeof importOutcome>) => void
): {
scan: ImportScanState | null
start: () => void
close: () => void
run: (names: string[]) => Promise<AgentApiKeysImportResult | null>
} {
const t = useTranslate()
const [scan, setScan] = useState<ImportScanState | null>(initial)
const start = (): void => {
const scanThisComputer = model.scanThisComputer
if (!scanThisComputer) {
return
}
setScan({ kind: 'scanning' })
scanThisComputer().then(
(found) => setScan((current) => (current ? { kind: 'ready', scan: found } : current)),
() => setScan((current) => (current ? { kind: 'failed' } : current))
)
}
const run = async (names: string[]): Promise<AgentApiKeysImportResult | null> => {
const result = (await model.importFromThisComputer?.(names)) ?? null
if (result) {
onDone(importOutcome(result, t))
setScan(null)
}
return result
}
return { scan, start, close: () => setScan(null), run }
}
export function AgentApiKeysImportPanel({
scan,
signedIn,
onRetry,
onImport,
onClose
}: {
scan: ImportScanState
signedIn: boolean
onRetry: () => void
onImport: (names: string[]) => Promise<AgentApiKeysImportResult | null>
onClose: () => void
}): React.JSX.Element {
const t = useTranslate()
const place = isMacPlatform()
? t('agentApiKeys.import.thisMac', 'this Mac')
: t('agentApiKeys.import.thisComputer', 'this computer')
const [selected, setSelected] = useState<string[] | null>(null)
const [importing, setImporting] = useState(false)
const [failed, setFailed] = useState(false)
const chosen = selected ?? (scan.kind === 'ready' ? defaultImportSelection(scan.scan) : [])
const run = async (): Promise<void> => {
if (importing || chosen.length === 0) {
return
}
setImporting(true)
setFailed(false)
const result = await onImport(chosen)
setImporting(false)
if (!result) {
setFailed(true)
}
}
return (
<section
aria-labelledby="agent-api-keys-import-title"
className="space-y-3 rounded-xl border border-border bg-card/50 px-5 py-4 shadow-xs"
>
<div className="space-y-1">
<h4 id="agent-api-keys-import-title" className="text-sm font-medium">
{t('agentApiKeys.import.title', 'Keys found on {{place}}', { place })}
</h4>
<p className="text-xs text-muted-foreground">
{signedIn
? t(
'agentApiKeys.import.detailSignedIn',
'Orca shows names only. Imported keys are sealed on this computer, used on every host, and saved in your Orca account.'
)
: t(
'agentApiKeys.import.detailSignedOut',
'Orca shows names only. Imported keys are sealed on this computer and used on every host.'
)}
</p>
</div>
{scan.kind === 'scanning' ? (
<div aria-busy="true" className="space-y-2">
<span className="sr-only">{t('agentApiKeys.import.scanning', 'Looking for keys…')}</span>
<Skeleton className="h-7 w-full" />
<Skeleton className="h-7 w-4/5" />
</div>
) : scan.kind === 'failed' ? (
<InlineError
density="compact"
title={t('agentApiKeys.import.scanFailed', 'Couldn’t look for keys on {{place}}.', {
place
})}
retryLabel={t('agentApiKeys.import.retry', 'Try again')}
onRetry={onRetry}
/>
) : (
<>
{scan.scan.keys.length === 0 ? (
<p className="text-xs text-muted-foreground">
{t(
'agentApiKeys.import.empty',
'No agent API keys found in your shell environment, OpenCode or ~/.gemini/.env.'
)}
</p>
) : (
<ul className="space-y-0.5">
{scan.scan.keys.map((key) => {
const id = `agent-api-key-import-${key.name}`
const checked = chosen.includes(key.name)
return (
<li
key={key.name}
className="flex items-center gap-3 rounded-md px-2 py-1.5 hover:bg-accent/40"
>
<Checkbox
id={id}
checked={checked}
disabled={key.alreadySaved || importing}
onCheckedChange={(next) =>
setSelected(
next === true
? [...chosen, key.name]
: chosen.filter((name) => name !== key.name)
)
}
/>
<AgentIcon agent={key.agent} size={14} />
<label htmlFor={id} className="flex min-w-0 flex-1 items-center gap-3">
<code className="w-52 shrink-0 truncate font-mono text-xs">{key.name}</code>
<span className="w-16 shrink-0 font-mono text-xs text-muted-foreground">
••••{key.hint}
</span>
<span className="min-w-0 flex-1 truncate text-xs text-muted-foreground">
{key.alreadySaved
? t('agentApiKeys.import.alreadySaved', 'Already saved for {{agent}}', {
agent: getAgentLabel(key.agent)
})
: `${getAgentLabel(key.agent)} · ${importSourceLabel(key.source, t)}`}
</span>
</label>
</li>
)
})}
</ul>
)}
{scan.scan.signIns.length > 0 ? (
<ul className="space-y-1 border-t border-border pt-3">
{scan.scan.signIns.map((signIn) => (
<li
key={`${signIn.agent}:${signIn.provider}`}
className="flex items-center gap-3 px-2 text-xs text-muted-foreground"
>
<LogIn aria-hidden className="size-3.5 shrink-0" />
<span className="min-w-0 flex-1">
{t(
'agentApiKeys.import.signIn',
'{{agent}} is signed in with {{provider}}. Sign in once in Settings › Agent accounts.',
{
agent: getAgentLabel(signIn.agent),
provider: signInProviderLabel(signIn)
}
)}
</span>
</li>
))}
</ul>
) : null}
</>
)}
{failed ? (
<InlineError
density="compact"
title={t('agentApiKeys.import.failed', 'Couldn’t import. Nothing was changed.')}
/>
) : null}
<div className="flex items-center justify-end gap-2">
<Button variant="ghost" size="sm" onClick={onClose}>
{t('agentApiKeys.import.cancel', 'Cancel')}
</Button>
{scan.kind === 'ready' && scan.scan.keys.length > 0 ? (
<Button
size="sm"
disabled={chosen.length === 0}
aria-disabled={importing || undefined}
aria-busy={importing || undefined}
onClick={() => void run()}
>
{importing ? <Loader2 className="motion-safe:animate-spin" /> : <KeyRound />}
{chosen.length === 1
? t('agentApiKeys.import.submitOne', 'Import 1 key')
: t('agentApiKeys.import.submit', 'Import {{count}} keys', {
count: chosen.length
})}
</Button>
) : null}
</div>
</section>
)
}
@@ -1,5 +1,6 @@
import { defineFixture } from '../../../component-fixtures/component-fixture'
import type { AgentApiKeysState } from '../../../../../shared/agent-api-keys/agent-api-key-catalog'
import type { AgentApiKeysScanResult } from '../../../../../shared/agent-api-keys/agent-api-key-cloud'
import { AgentApiKeysPane } from './AgentApiKeysPane'
import type { AgentApiKeyHostChoice } from './AgentApiKeyEditor'
import type { AgentApiKeysModel } from './use-agent-api-keys'
@@ -11,8 +12,19 @@ const HOSTS: AgentApiKeyHostChoice[] = [
{ id: 'runtime:build-box', label: 'build-box' }
]
function model(state: AgentApiKeysState): AgentApiKeysModel {
return { state, save: async () => null, remove: async () => null }
function model(
state: AgentApiKeysState,
extra: Partial<AgentApiKeysModel> = {}
): AgentApiKeysModel {
return {
state,
save: async () => null,
remove: async () => null,
saveToAccount: async () => null,
scanThisComputer: async () => ({ keys: [], signIns: [] }),
importFromThisComputer: async () => null,
...extra
}
}
const SAVED: AgentApiKeysState = {
@@ -95,3 +107,143 @@ export const keychainUnavailable = defineFixture({
/>
)
})
// D12: keys saved while signed in to Orca also live in the Orca account.
const CLOUD_KEYS: AgentApiKeysState['keys'] = [
{
id: 'synced',
agent: 'claude',
envName: 'ANTHROPIC_API_KEY',
hostScope: { kind: 'all' },
hint: '9fQ2',
updatedAt: 2
},
{
id: 'bedrock',
agent: 'claude',
envName: 'AWS_BEARER_TOKEN_BEDROCK',
hostScope: { kind: 'all' },
hint: 'x7Lm',
updatedAt: 1
},
{
id: 'local',
agent: 'codex',
envName: 'OPENAI_API_KEY',
hostScope: { kind: 'all' },
hint: 'Q0aa',
updatedAt: 3
},
{
id: 'scoped',
agent: 'gemini',
envName: 'GEMINI_API_KEY',
hostScope: { kind: 'hosts', hostIds: ['ssh:devbox'] },
hint: 'Zk19',
updatedAt: 4
}
]
const SIGNED_IN: AgentApiKeysState = {
protection: { available: true },
keys: CLOUD_KEYS,
cloud: { signedIn: true, synced: ['synced'], managed: ['synced'] }
}
/** One key synced, one the proxy can't swap, one only here, one scoped to a host. */
export const cloudSynced = defineFixture({
width: 720,
render: () => <AgentApiKeysPane model={model(SIGNED_IN)} hosts={HOSTS} />
})
/** The account write failed after a local save: the key reads as only on this computer. */
export const cloudLocalOnly = defineFixture({
width: 720,
render: () => (
<AgentApiKeysPane
model={model(SIGNED_IN, { cloudFailures: { local: 'unavailable' } })}
hosts={HOSTS}
/>
)
})
/** Signed out: every key reads as it always has. */
export const cloudSignedOut = defineFixture({
width: 720,
render: () => (
<AgentApiKeysPane
model={model({ ...SIGNED_IN, cloud: { signedIn: false, synced: [], managed: [] } })}
hosts={HOSTS}
/>
)
})
const SCAN: AgentApiKeysScanResult = {
keys: [
{
name: 'OPENAI_API_KEY',
agent: 'codex',
source: 'shell-env',
hint: 'a1B2',
alreadySaved: false
},
{
name: 'AI_GATEWAY_API_KEY',
agent: 'opencode',
source: 'opencode-auth',
hint: 'gw90',
alreadySaved: false
},
{
name: 'GEMINI_API_KEY',
agent: 'gemini',
source: 'gemini-env-file',
hint: 'Zk19',
alreadySaved: true
}
],
signIns: [{ agent: 'opencode', provider: 'anthropic' }]
}
export const importList = defineFixture({
width: 720,
render: () => (
<AgentApiKeysPane
model={model(SIGNED_IN)}
hosts={HOSTS}
initialImport={{ kind: 'ready', scan: SCAN }}
/>
)
})
export const importEmpty = defineFixture({
width: 720,
render: () => (
<AgentApiKeysPane
model={model({ keys: [], protection: { available: true } })}
hosts={HOSTS}
initialImport={{ kind: 'ready', scan: { keys: [], signIns: [] } }}
/>
)
})
export const importScanning = defineFixture({
width: 720,
render: () => (
<AgentApiKeysPane model={model(SIGNED_IN)} hosts={HOSTS} initialImport={{ kind: 'scanning' }} />
)
})
/** An edit that didn't reach the account: the account still holds the earlier value. */
export const cloudStale = defineFixture({
width: 720,
render: () => (
<AgentApiKeysPane
model={model(
{ ...SIGNED_IN, cloud: { signedIn: true, synced: [], managed: ['synced'] } },
{ cloudFailures: { synced: 'timeout' } }
)}
hosts={HOSTS}
/>
)
})
@@ -1,11 +1,27 @@
import { useMemo, useState } from 'react'
import { ChevronDown, KeyRound, Pencil, Plus, ShieldAlert, ShieldCheck, Trash2 } from 'lucide-react'
import {
ChevronDown,
Download,
KeyRound,
Pencil,
Plus,
ShieldAlert,
ShieldCheck,
Trash2
} from 'lucide-react'
import type { TuiAgent } from '../../../../../shared/agent-launch/catalog/tui-agent'
import {
FEATURED_API_KEY_AGENTS,
isAgentApiKeyAgent,
type AgentApiKeySummary
} from '../../../../../shared/agent-api-keys/agent-api-key-catalog'
import {
agentApiKeyCloudEligible,
agentApiKeyCloudRowState,
agentApiKeyRemoveAsksAboutAccount,
type AgentApiKeysCloudState
} from '../../../../../shared/agent-api-keys/agent-api-key-cloud'
import type { CloudSecretsErrorCode } from '../../../../../shared/cloud-secrets/cloud-secrets-wire'
import { AgentIcon } from '@/components/agent/icons/AgentIcon'
import { getAgentCatalog, getAgentLabel } from '@/lib/agent-catalog/agent-catalog'
import { useTranslate, type Translate } from '@/i18n/use-translate'
@@ -20,6 +36,14 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '../../ui/tooltip'
import { SettingsGroup } from '../section-layout/SettingsGroup'
import { AgentApiKeyEditor, type AgentApiKeyHostChoice } from './AgentApiKeyEditor'
import type { AgentApiKeysModel } from './use-agent-api-keys'
import {
AgentApiKeyCloudLine,
AgentApiKeyRemoveFromAccountConfirm,
AgentApiKeysNotice,
type AgentApiKeysNoticeState
} from './AgentApiKeyCloudLine'
import { AgentApiKeysImportPanel, useAgentApiKeysImport } from './AgentApiKeysImportPanel'
import { isMacPlatform, type ImportScanState } from './agent-api-keys-import'
type Editing = { agent: TuiAgent; keyId: string | null } | null
@@ -43,73 +67,97 @@ function KeyLine({
apiKey,
hosts,
canEdit,
cloud,
cloudFailure,
onEdit,
onRemove
onRemove,
onSaveToAccount
}: {
apiKey: AgentApiKeySummary
hosts: readonly AgentApiKeyHostChoice[]
canEdit: boolean
cloud: AgentApiKeysCloudState | undefined
cloudFailure: CloudSecretsErrorCode | undefined
onEdit: () => void
onRemove: () => Promise<void>
onRemove: (fromAccount: boolean) => Promise<void>
onSaveToAccount: () => Promise<CloudSecretsErrorCode | null>
}): React.JSX.Element {
const t = useTranslate()
const [confirming, setConfirming] = useState(false)
const asksAboutAccount = agentApiKeyRemoveAsksAboutAccount(apiKey, cloud)
return (
<li className="group flex items-center gap-3 rounded-md px-2 py-1.5 hover:bg-accent/40">
<KeyRound className="size-3.5 shrink-0 text-muted-foreground" />
<code className="w-52 shrink-0 truncate font-mono text-xs">{apiKey.envName}</code>
<span className="w-16 shrink-0 font-mono text-xs text-muted-foreground">
••••{apiKey.hint}
</span>
<span className="min-w-0 flex-1 truncate text-xs text-muted-foreground">
{scopeLabel(apiKey, hosts, t)}
</span>
<div className="flex shrink-0 items-center gap-0.5">
{confirming ? (
<>
<Button variant="ghost" size="xs" onClick={() => setConfirming(false)}>
{t('auto.components.settings.agentApiKeys.keep', 'Keep')}
</Button>
<Button variant="destructive-chip" size="xs" onClick={() => void onRemove()}>
{t('auto.components.settings.agentApiKeys.confirmRemove', 'Remove key')}
</Button>
</>
) : (
<>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon-xs"
disabled={!canEdit}
onClick={onEdit}
aria-label={t('auto.components.settings.agentApiKeys.edit', 'Edit key')}
>
<Pencil />
</Button>
</TooltipTrigger>
<TooltipContent>
{t('auto.components.settings.agentApiKeys.edit', 'Edit key')}
</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon-xs"
onClick={() => setConfirming(true)}
aria-label={t('auto.components.settings.agentApiKeys.remove', 'Remove key')}
>
<Trash2 />
</Button>
</TooltipTrigger>
<TooltipContent>
{t('auto.components.settings.agentApiKeys.remove', 'Remove key')}
</TooltipContent>
</Tooltip>
</>
)}
<li className="group space-y-1 rounded-md px-2 py-1.5 hover:bg-accent/40">
<div className="flex items-center gap-3">
<KeyRound className="size-3.5 shrink-0 text-muted-foreground" />
<code className="w-52 shrink-0 truncate font-mono text-xs">{apiKey.envName}</code>
<span className="w-16 shrink-0 font-mono text-xs text-muted-foreground">
••••{apiKey.hint}
</span>
<span className="min-w-0 flex-1 truncate text-xs text-muted-foreground">
{scopeLabel(apiKey, hosts, t)}
</span>
<div className="flex shrink-0 items-center gap-0.5">
{confirming && asksAboutAccount ? null : confirming ? (
<>
<Button variant="ghost" size="xs" onClick={() => setConfirming(false)}>
{t('auto.components.settings.agentApiKeys.keep', 'Keep')}
</Button>
<Button variant="destructive-chip" size="xs" onClick={() => void onRemove(false)}>
{t('auto.components.settings.agentApiKeys.confirmRemove', 'Remove key')}
</Button>
</>
) : (
<>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon-xs"
disabled={!canEdit}
onClick={onEdit}
aria-label={t('auto.components.settings.agentApiKeys.edit', 'Edit key')}
>
<Pencil />
</Button>
</TooltipTrigger>
<TooltipContent>
{t('auto.components.settings.agentApiKeys.edit', 'Edit key')}
</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon-xs"
onClick={() => setConfirming(true)}
aria-label={t('auto.components.settings.agentApiKeys.remove', 'Remove key')}
>
<Trash2 />
</Button>
</TooltipTrigger>
<TooltipContent>
{t('auto.components.settings.agentApiKeys.remove', 'Remove key')}
</TooltipContent>
</Tooltip>
</>
)}
</div>
</div>
{confirming && asksAboutAccount ? (
<AgentApiKeyRemoveFromAccountConfirm
envName={apiKey.envName}
onCancel={() => setConfirming(false)}
onRemove={(fromAccount) => void onRemove(fromAccount)}
/>
) : (
<AgentApiKeyCloudLine
envName={apiKey.envName}
state={agentApiKeyCloudRowState(apiKey, cloud)}
canSave={agentApiKeyCloudEligible(apiKey)}
failure={cloudFailure}
onSaveToAccount={onSaveToAccount}
/>
)}
</li>
)
}
@@ -117,15 +165,35 @@ function KeyLine({
export function AgentApiKeysPane({
model,
hosts,
initiallyEditing = null
initiallyEditing = null,
initialImport = null
}: {
model: AgentApiKeysModel
hosts: readonly AgentApiKeyHostChoice[]
/** Lets the in-pane sign-in card open straight into "add a key for this agent". */
initiallyEditing?: Editing
/** Fixtures: open "Import from this Mac" in a given state. */
initialImport?: ImportScanState | null
}): React.JSX.Element {
const t = useTranslate()
const [editing, setEditing] = useState<Editing>(initiallyEditing)
const [notice, setNotice] = useState<AgentApiKeysNoticeState>(null)
const [failure, setFailure] = useState<string | null>(null)
const cloud = model.state?.cloud
const signedIn = cloud?.signedIn === true
const importer = useAgentApiKeysImport(model, initialImport, (outcome) => {
setFailure(outcome.failure)
setNotice(outcome.imported > 0 ? { kind: 'imported', count: outcome.imported } : null)
})
const removeKey = async (apiKey: AgentApiKeySummary, fromAccount: boolean): Promise<void> => {
const asked = agentApiKeyRemoveAsksAboutAccount(apiKey, cloud)
setNotice(null)
const error = await model.remove(apiKey.id, fromAccount)
setFailure(error)
if (!error && asked && !fromAccount) {
setNotice({ kind: 'kept', envName: apiKey.envName })
}
}
const [extraAgents, setExtraAgents] = useState<TuiAgent[]>(
initiallyEditing ? [initiallyEditing.agent] : []
)
@@ -177,6 +245,8 @@ export function AgentApiKeysPane({
</div>
) : null}
<AgentApiKeysNotice failure={failure} notice={notice} />
<SettingsGroup bodyClassName="px-0">
{agents.map((agent) => {
const agentKeys = keys.filter((key) => key.agent === agent)
@@ -233,10 +303,13 @@ export function AgentApiKeysPane({
apiKey={apiKey}
hosts={hosts}
canEdit={canEdit}
cloud={cloud}
cloudFailure={model.cloudFailures?.[apiKey.id]}
onEdit={() => setEditing({ agent, keyId: apiKey.id })}
onRemove={async () => {
await model.remove(apiKey.id)
}}
onRemove={(fromAccount) => removeKey(apiKey, fromAccount)}
onSaveToAccount={() =>
model.saveToAccount?.(apiKey.id) ?? Promise.resolve('not_configured')
}
/>
)
)}
@@ -263,34 +336,54 @@ export function AgentApiKeysPane({
})}
</SettingsGroup>
{otherAgents.length > 0 ? (
<DropdownMenu>
<DropdownMenuTrigger asChild disabled={!canEdit}>
<Button variant="outline" size="sm">
<Plus />
{t(
'auto.components.settings.agentApiKeys.anotherAgent',
'Add a key for another agent'
)}
<ChevronDown className="text-muted-foreground" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="max-h-72">
{otherAgents.map((agent) => (
<DropdownMenuItem
key={agent}
onSelect={() => {
setExtraAgents((current) => [...current, agent])
setEditing({ agent, keyId: null })
}}
>
<AgentIcon agent={agent} size={14} />
{getAgentLabel(agent)}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
{importer.scan ? (
<AgentApiKeysImportPanel
scan={importer.scan}
signedIn={signedIn}
onRetry={importer.start}
onClose={importer.close}
onImport={importer.run}
/>
) : null}
<div className="flex flex-wrap items-center gap-2">
{model.scanThisComputer && !importer.scan ? (
<Button variant="outline" size="sm" disabled={!canEdit} onClick={importer.start}>
<Download />
{isMacPlatform()
? t('agentApiKeys.import.open', 'Import from this Mac')
: t('agentApiKeys.import.openComputer', 'Import from this computer')}
</Button>
) : null}
{otherAgents.length > 0 ? (
<DropdownMenu>
<DropdownMenuTrigger asChild disabled={!canEdit}>
<Button variant="outline" size="sm">
<Plus />
{t(
'auto.components.settings.agentApiKeys.anotherAgent',
'Add a key for another agent'
)}
<ChevronDown className="text-muted-foreground" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="max-h-72">
{otherAgents.map((agent) => (
<DropdownMenuItem
key={agent}
onSelect={() => {
setExtraAgents((current) => [...current, agent])
setEditing({ agent, keyId: null })
}}
>
<AgentIcon agent={agent} size={14} />
{getAgentLabel(agent)}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
) : null}
</div>
</div>
)
}
@@ -0,0 +1,40 @@
import { describe, expect, it } from 'vitest'
import { defaultImportSelection, isMacPlatform, signInProviderLabel } from './agent-api-keys-import'
describe('agent API key import helpers', () => {
it('checks every found key the vault does not already hold', () => {
expect(
defaultImportSelection({
keys: [
{
name: 'OPENAI_API_KEY',
agent: 'codex',
source: 'shell-env',
hint: 'a1B2',
alreadySaved: false
},
{
name: 'GEMINI_API_KEY',
agent: 'gemini',
source: 'gemini-env-file',
hint: 'Zk19',
alreadySaved: true
}
],
signIns: []
})
).toEqual(['OPENAI_API_KEY'])
})
it('says "this Mac" only on macOS', () => {
expect(isMacPlatform('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)')).toBe(true)
expect(isMacPlatform('Mozilla/5.0 (Windows NT 10.0; Win64; x64)')).toBe(false)
})
it('labels known sign-in providers', () => {
expect(signInProviderLabel({ agent: 'opencode', provider: 'github-copilot' })).toBe(
'GitHub Copilot'
)
expect(signInProviderLabel({ agent: 'opencode', provider: 'xai' })).toBe('xai')
})
})
@@ -0,0 +1,65 @@
import type {
AgentApiKeysImportResult,
AgentApiKeysScanResult,
LocalAgentKeySource,
LocalAgentSignInFound
} from '../../../../../shared/agent-api-keys/agent-api-key-cloud'
import type { Translate } from '@/i18n/use-translate'
export type ImportScanState =
| { kind: 'scanning' }
| { kind: 'failed' }
| { kind: 'ready'; scan: AgentApiKeysScanResult }
/** Every key found that the vault doesn't already hold starts checked. */
export function defaultImportSelection(scan: AgentApiKeysScanResult): string[] {
return scan.keys.filter((key) => !key.alreadySaved).map((key) => key.name)
}
/** "this Mac" on macOS, "this computer" elsewhere. */
export function isMacPlatform(userAgent: string = globalThis.navigator?.userAgent ?? ''): boolean {
return /Mac/i.test(userAgent)
}
export function importSourceLabel(source: LocalAgentKeySource, t: Translate): string {
switch (source) {
case 'opencode-auth':
return t('agentApiKeys.import.source.opencode', 'OpenCode sign-in file')
case 'gemini-env-file':
return t('agentApiKeys.import.source.geminiEnv', '~/.gemini/.env')
case 'shell-env':
return t('agentApiKeys.import.source.shell', 'Shell environment')
}
}
const PROVIDER_LABELS: Record<string, string> = {
anthropic: 'Anthropic',
openai: 'OpenAI',
google: 'Google',
'github-copilot': 'GitHub Copilot'
}
export function signInProviderLabel(signIn: LocalAgentSignInFound): string {
return PROVIDER_LABELS[signIn.provider] ?? signIn.provider
}
/** What to tell the user after an import: how many landed, and every name that didn't fully. */
export function importOutcome(
result: Pick<AgentApiKeysImportResult, 'imported' | 'failed' | 'cloudFailed'>,
t: Translate
): { imported: number; failure: string | null } {
const problems = [
...result.failed.map((entry) => `${entry.name}: ${entry.error}`),
...result.cloudFailed.map((entry) =>
t(
'agentApiKeys.import.cloudFailed',
'{{name}} is saved on this computer, but not in your Orca account.',
{ name: entry.name }
)
)
]
return {
imported: result.imported.length,
failure: problems.length > 0 ? problems.join(' ') : null
}
}
@@ -4,6 +4,12 @@ import type {
AgentApiKeysMutationResult,
AgentApiKeysState
} from '../../../../../shared/agent-api-keys/agent-api-key-catalog'
import type {
AgentApiKeyCloudOutcome,
AgentApiKeysImportResult,
AgentApiKeysScanResult
} from '../../../../../shared/agent-api-keys/agent-api-key-cloud'
import type { CloudSecretsErrorCode } from '../../../../../shared/cloud-secrets/cloud-secrets-wire'
import type { PreloadApi } from '../../../../../preload/api-types'
export type AgentApiKeysApi = NonNullable<PreloadApi['agentApiKeys']>
@@ -11,12 +17,21 @@ export type AgentApiKeysApi = NonNullable<PreloadApi['agentApiKeys']>
export type AgentApiKeysModel = {
state: AgentApiKeysState | null
save: (request: AgentApiKeySaveRequest) => Promise<string | null>
remove: (id: string) => Promise<string | null>
/** `fromAccount` also deletes the copy this computer saved to the Orca account. */
remove: (id: string, fromAccount?: boolean) => Promise<string | null>
/** Why the last write of a key to the Orca account failed, by key id. */
cloudFailures?: Readonly<Record<string, CloudSecretsErrorCode>>
saveToAccount?: (id: string) => Promise<CloudSecretsErrorCode | null>
scanThisComputer?: () => Promise<AgentApiKeysScanResult>
importFromThisComputer?: (names: string[]) => Promise<AgentApiKeysImportResult | null>
}
const DESKTOP_ONLY = 'Keys are managed in the desktop app.'
/** Values are sent once on save and never read back. Returns the user-facing error, or null. */
export function useAgentApiKeys(api: AgentApiKeysApi | undefined): AgentApiKeysModel {
const [state, setState] = useState<AgentApiKeysState | null>(null)
const [cloudFailures, setCloudFailures] = useState<Record<string, CloudSecretsErrorCode>>({})
useEffect(() => {
if (!api) {
@@ -33,7 +48,10 @@ export function useAgentApiKeys(api: AgentApiKeysApi | undefined): AgentApiKeysM
if (!cancelled) {
setState({
keys: [],
protection: { available: false, reason: 'Orca could not read the saved keys.' }
protection: {
available: false,
reason: 'Orca could not read the saved keys.'
}
})
}
}
@@ -43,28 +61,102 @@ export function useAgentApiKeys(api: AgentApiKeysApi | undefined): AgentApiKeysM
}
}, [api])
const apply = useCallback(async (run: () => Promise<AgentApiKeysMutationResult>) => {
try {
const result = await run()
setState(result.state)
return result.ok ? null : result.error
} catch {
return 'Orca could not save the key.'
const noteCloud = useCallback((outcome: AgentApiKeyCloudOutcome | undefined) => {
if (outcome?.kind === 'failed' && outcome.keyId) {
const { keyId, error } = outcome
setCloudFailures((current) => ({ ...current, [keyId]: error }))
}
}, [])
const apply = useCallback(
async (
run: () => Promise<AgentApiKeysMutationResult>,
clearFailureFor?: string
): Promise<AgentApiKeysMutationResult | null> => {
try {
const result = await run()
setState(result.state)
if (clearFailureFor) {
setCloudFailures(({ [clearFailureFor]: _cleared, ...rest }) => rest)
}
noteCloud(result.cloud)
return result
} catch {
return null
}
},
[noteCloud]
)
const save = useCallback(
(request: AgentApiKeySaveRequest) =>
api
? apply(() => api.save(request))
: Promise.resolve('Keys are managed in the desktop app.'),
async (request: AgentApiKeySaveRequest) => {
if (!api) {
return DESKTOP_ONLY
}
const result = await apply(() => api.save(request), request.id)
return !result ? 'Orca could not save the key.' : result.ok ? null : result.error
},
[api, apply]
)
const remove = useCallback(
(id: string) =>
api ? apply(() => api.remove(id)) : Promise.resolve('Keys are managed in the desktop app.'),
async (id: string, fromAccount = false) => {
if (!api) {
return DESKTOP_ONLY
}
const result = await apply(() => api.remove(fromAccount ? { id, fromAccount } : id))
if (!result) {
return 'Orca could not remove the key.'
}
if (result.ok && result.cloud?.kind === 'failed') {
return 'Couldn’t remove it from your Orca account. Nothing was changed.'
}
return result.ok ? null : result.error
},
[api, apply]
)
const saveToAccount = useCallback(
async (id: string): Promise<CloudSecretsErrorCode | null> => {
if (!api?.saveToAccount) {
return 'not_configured'
}
const saveToAccountApi = api.saveToAccount
const result = await apply(() => saveToAccountApi(id), id)
if (!result) {
return 'unknown'
}
return result.cloud?.kind === 'failed' ? result.cloud.error : null
},
[api, apply]
)
const scanThisComputer = useCallback(async (): Promise<AgentApiKeysScanResult> => {
if (!api?.scanThisComputer) {
return { keys: [], signIns: [] }
}
return api.scanThisComputer()
}, [api])
const importFromThisComputer = useCallback(
async (names: string[]): Promise<AgentApiKeysImportResult | null> => {
if (!api?.importFromThisComputer) {
return null
}
try {
const result = await api.importFromThisComputer(names)
setState(result.state)
return result
} catch {
return null
}
},
[api]
)
return { state, save, remove }
return {
state,
save,
remove,
cloudFailures,
saveToAccount,
scanThisComputer: api?.scanThisComputer ? scanThisComputer : undefined,
importFromThisComputer
}
}
@@ -37,6 +37,11 @@ export function cloudSecretsErrorCopy(
'cloudSecrets.error.notSwappable',
'A workspace would get this key in full, so Orca doesn’t save it from here. Add it in Cloud secrets if you accept that.'
)
case 'desktop_key_conflict':
return t(
'cloudSecrets.error.desktopKeyConflict',
'Another agent’s key is saved in your Orca account under this name. Save this one to replace it.'
)
case 'invalid_name':
return t(
'cloudSecrets.error.invalidName',
+49 -1
View File
@@ -26936,7 +26936,8 @@
"unterminatedQuote": "The closing quote is missing.",
"overridden": "Set again further down; the later line is used.",
"unknown": "Something went wrong in Orca Cloud. Nothing was changed. Try again.",
"notSwappable": "A workspace would get this key in full, so Orca doesn’t save it from here. Add it in Cloud secrets if you accept that."
"notSwappable": "A workspace would get this key in full, so Orca doesn’t save it from here. Add it in Cloud secrets if you accept that.",
"desktopKeyConflict": "Another agent’s key is saved in your Orca account under this name. Save this one to replace it."
},
"vm": {
"badge": "Stored on workspace",
@@ -27156,5 +27157,52 @@
"showOutputTooltip": "Show {{name}} output",
"shortcutRestarts": "{{shortcut}} restarts it",
"menuRunning": "Run actions, {{count}} running"
},
"agentApiKeys": {
"cloud": {
"synced": "Saved in your Orca account · cached on this computer",
"notSwappable": "Only on this computer · not used in Orca Cloud",
"local": "Only on this computer",
"saveLabel": "Save {{name}} to your Orca account",
"save": "Save to your Orca account",
"saveFailed": "Saved on this computer, but not in your Orca account.",
"stale": "Your Orca account has an earlier copy · cloud workspaces still use it",
"saveFailedRetry": "Couldn’t reach Orca Cloud. Try again."
},
"remove": {
"confirmLabel": "Remove {{name}}",
"fromAccountQuestion": "Also remove it from your Orca account? Cloud workspaces will stop using it.",
"thisComputerOnly": "Remove from this computer only",
"both": "Remove from both",
"kept": "Removed from this computer. {{name}} is still in your Orca account.",
"keptDetail": "Manage it in Settings › Cloud secrets."
},
"import": {
"title": "Keys found on {{place}}",
"detailSignedIn": "Orca shows names only. Imported keys are sealed on this computer, used on every host, and saved in your Orca account.",
"detailSignedOut": "Orca shows names only. Imported keys are sealed on this computer and used on every host.",
"scanning": "Looking for keys…",
"scanFailed": "Couldn’t look for keys on {{place}}.",
"retry": "Try again",
"empty": "No agent API keys found in your shell environment, OpenCode or ~/.gemini/.env.",
"alreadySaved": "Already saved for {{agent}}",
"signIn": "{{agent}} is signed in with {{provider}}. Sign in once in Settings › Agent accounts.",
"failed": "Couldn’t import. Nothing was changed.",
"cancel": "Cancel",
"submitOne": "Import 1 key",
"submit": "Import {{count}} keys",
"thisMac": "this Mac",
"thisComputer": "this computer",
"doneOne": "Imported 1 key.",
"done": "Imported {{count}} keys.",
"cloudFailed": "{{name}} is saved on this computer, but not in your Orca account.",
"open": "Import from this Mac",
"openComputer": "Import from this computer",
"source": {
"opencode": "OpenCode sign-in file",
"geminiEnv": "~/.gemini/.env",
"shell": "Shell environment"
}
}
}
}
@@ -1,6 +1,7 @@
import type { TuiAgent } from '../agent-launch/catalog/tui-agent'
import { isTuiAgent } from '../agent-launch/catalog/tui-agent-config'
import type { ExecutionHostId } from '../execution-host'
import type { AgentApiKeyCloudOutcome, AgentApiKeysCloudState } from './agent-api-key-cloud'
/** Where a stored key is injected. `hosts` lists execution host ids (`local`, `ssh:…`, `runtime:…`). */
export type AgentApiKeyHostScope = { kind: 'all' } | { kind: 'hosts'; hostIds: ExecutionHostId[] }
@@ -21,11 +22,13 @@ export type AgentApiKeyProtection = { available: true } | { available: false; re
export type AgentApiKeysState = {
keys: AgentApiKeySummary[]
protection: AgentApiKeyProtection
/** Desktop with Orca Cloud: which keys are also in the user's Orca account. */
cloud?: AgentApiKeysCloudState
}
export type AgentApiKeysMutationResult =
| { ok: true; state: AgentApiKeysState }
| { ok: false; error: string; state: AgentApiKeysState }
| { ok: true; state: AgentApiKeysState; cloud?: AgentApiKeyCloudOutcome }
| { ok: false; error: string; state: AgentApiKeysState; cloud?: AgentApiKeyCloudOutcome }
export type AgentApiKeySaveRequest = {
/** Present when editing; an edit without `value` keeps the stored value. */
@@ -0,0 +1,75 @@
import { describe, expect, it } from 'vitest'
import {
agentApiKeyCloudEligible,
agentApiKeyCloudRowState,
agentApiKeyRemoveAsksAboutAccount,
type AgentApiKeysCloudState
} from './agent-api-key-cloud'
const ALL = { kind: 'all' } as const
const signedIn: AgentApiKeysCloudState = { signedIn: true, synced: ['a'], managed: ['a', 'b'] }
describe('agentApiKeyCloudRowState', () => {
it('reads as today when signed out or when the key is scoped to some hosts', () => {
expect(
agentApiKeyCloudRowState({ id: 'a', envName: 'ANTHROPIC_API_KEY', hostScope: ALL }, undefined)
).toBe('none')
expect(
agentApiKeyCloudRowState(
{ id: 'a', envName: 'ANTHROPIC_API_KEY', hostScope: ALL },
{ signedIn: false, synced: ['a'], managed: ['a'] }
)
).toBe('none')
expect(
agentApiKeyCloudRowState(
{ id: 'c', envName: 'ANTHROPIC_API_KEY', hostScope: { kind: 'hosts', hostIds: ['local'] } },
signedIn
)
).toBe('none')
})
it('names a key whose account copy is out of date as stale, whatever its scope now', () => {
expect(
agentApiKeyCloudRowState(
{ id: 'b', envName: 'OPENAI_API_KEY', hostScope: { kind: 'hosts', hostIds: ['local'] } },
signedIn
)
).toBe('stale')
})
it('names synced, local and not-swappable keys', () => {
expect(
agentApiKeyCloudRowState({ id: 'a', envName: 'ANTHROPIC_API_KEY', hostScope: ALL }, signedIn)
).toBe('synced')
expect(
agentApiKeyCloudRowState({ id: 'd', envName: 'OPENAI_API_KEY', hostScope: ALL }, signedIn)
).toBe('local')
expect(
agentApiKeyCloudRowState(
{ id: 'c', envName: 'AWS_BEARER_TOKEN_BEDROCK', hostScope: ALL },
signedIn
)
).toBe('not-swappable')
})
it('only offers account removal for keys this computer wrote, while signed in', () => {
expect(agentApiKeyRemoveAsksAboutAccount({ id: 'b' }, signedIn)).toBe(true)
expect(agentApiKeyRemoveAsksAboutAccount({ id: 'c' }, signedIn)).toBe(false)
expect(agentApiKeyRemoveAsksAboutAccount({ id: 'a' }, { ...signedIn, signedIn: false })).toBe(
false
)
})
it('is eligible only for every-host keys the proxy swaps', () => {
expect(agentApiKeyCloudEligible({ envName: 'GEMINI_API_KEY', hostScope: ALL })).toBe(true)
expect(agentApiKeyCloudEligible({ envName: 'AWS_BEARER_TOKEN_BEDROCK', hostScope: ALL })).toBe(
false
)
expect(
agentApiKeyCloudEligible({
envName: 'GEMINI_API_KEY',
hostScope: { kind: 'hosts', hostIds: ['local'] }
})
).toBe(false)
})
})
@@ -0,0 +1,115 @@
// Agent API keys and the user's Orca account (D12). While signed in, a saved key is also written to
// the personal Cloud secret of the same variable, and this computer's vault stays the sealed cache
// that non-Cloud launches read. Cloud secrets are write-only, so the sync is one way: desktop → account.
import type { TuiAgent } from '../agent-launch/catalog/tui-agent'
import type { CloudSecretsErrorCode } from '../cloud-secrets/cloud-secrets-wire'
import { cloudSecretSwapped } from '../cloud-secrets/cloud-secret-rules'
import type { AgentApiKeySummary, AgentApiKeysState } from './agent-api-key-catalog'
export type AgentApiKeysCloudState = {
/** Signed in to an Orca account that has Orca Cloud; otherwise keys stay on this computer only. */
signedIn: boolean
/** Keys whose current value this computer saved to the Orca account. */
synced: string[]
/**
* Keys whose variable this computer wrote to the Orca account (possibly an older value). Only these
* may be removed from the account, and only after the user confirms.
*/
managed: string[]
}
/**
* What happened in the Orca account. Codes only: never a value. After a save, `failed` means the key
* is saved on this computer only; after a removal it means nothing was removed. `removed` means a
* removal also deleted the account copy; `skipped` means the account wasn't touched.
*/
export type AgentApiKeyCloudOutcome =
| { kind: 'synced' }
| { kind: 'removed' }
| { kind: 'skipped' }
| { kind: 'failed'; error: CloudSecretsErrorCode; keyId?: string }
export type AgentApiKeyRemoveRequest = {
id: string
/** Also delete the personal Cloud secret. Honoured only for a key in `managed`. */
fromAccount: boolean
}
/**
* How a row describes the key:
* - `synced`: "Saved in your Orca account · cached on this computer".
* - `stale`: this computer saved it to the Orca account earlier, but the account holds an older value
* or variable (an edit that didn't reach the account, a rename, or a narrower host scope).
* - `local`: signed in, the key could be used in Orca Cloud but is only on this computer.
* - `not-swappable`: the egress proxy can't stand in for it, so it is never sent to Orca Cloud.
* - `none`: signed out, or a key scoped to some hosts; the row reads as it always has.
*/
export type AgentApiKeyCloudRowState = 'synced' | 'stale' | 'local' | 'not-swappable' | 'none'
/** A key the desktop may write to the Orca account: every host, and a variable the proxy swaps. */
export function agentApiKeyCloudEligible(
key: Pick<AgentApiKeySummary, 'envName' | 'hostScope'>
): boolean {
return key.hostScope.kind === 'all' && cloudSecretSwapped(key.envName)
}
export function agentApiKeyCloudRowState(
key: Pick<AgentApiKeySummary, 'id' | 'envName' | 'hostScope'>,
cloud: AgentApiKeysCloudState | undefined
): AgentApiKeyCloudRowState {
if (!cloud?.signedIn) {
return 'none'
}
if (cloud.synced.includes(key.id)) {
return 'synced'
}
if (cloud.managed.includes(key.id)) {
return 'stale'
}
if (key.hostScope.kind !== 'all') {
return 'none'
}
return cloudSecretSwapped(key.envName) ? 'local' : 'not-swappable'
}
/** Whether removing this key should ask about the copy in the Orca account. */
export function agentApiKeyRemoveAsksAboutAccount(
key: Pick<AgentApiKeySummary, 'id'>,
cloud: AgentApiKeysCloudState | undefined
): boolean {
return cloud?.signedIn === true && cloud.managed.includes(key.id)
}
export type LocalAgentKeySource = 'opencode-auth' | 'gemini-env-file' | 'shell-env'
/** One key "Import from this Mac" found. Names, source and last four only: the value stays in main. */
export type LocalAgentKeyFound = {
name: string
agent: TuiAgent
source: LocalAgentKeySource
hint: string
/** The vault already has a key for this agent and variable; import skips it. */
alreadySaved: boolean
}
/** A subscription sign-in found on this computer. Its tokens are never read. */
export type LocalAgentSignInFound = {
agent: 'opencode' | 'gemini'
provider: string
}
export type AgentApiKeysScanResult = {
keys: LocalAgentKeyFound[]
signIns: LocalAgentSignInFound[]
}
export type AgentApiKeysImportResult = {
state: AgentApiKeysState
imported: string[]
/** Not saved on this computer; `error` is Orca's own copy, never a value. */
failed: { name: string; error: string }[]
/** Saved on this computer, but not to the Orca account. */
cloudFailed: { name: string; error: CloudSecretsErrorCode }[]
}
export const MAX_AGENT_API_KEY_IMPORT = 16
@@ -88,6 +88,8 @@ export type CloudSecretsErrorCode =
| 'not_found'
/** Desktop only: a key the workspace would get in full (no egress stand-in), so not saved from here. */
| 'not_swappable'
/** Desktop only: another saved key wrote this variable to the Orca account; replacing it takes a click. */
| 'desktop_key_conflict'
| 'unavailable'
| 'timeout'
| 'not_configured'