From 1d2460734f0e36b572e53978c919e9fbac2ca779 Mon Sep 17 00:00:00 2001 From: hkonsti <45428767+hkonsti@users.noreply.github.com> Date: Sat, 21 Nov 2026 03:57:18 +0000 Subject: [PATCH 1/5] secrets in the vault: keys agents' sandbox commands use but never see A vault keeps secrets beside its entries: a name (an environment variable's), a value and a note. An agent sees a secret's name and note, never its value, which only the person reads, on the vault's page. Use secrets gives the named secrets to a sandbox command as environment variables (sandbox_exec {secrets}), and what the command writes back has each value shown as [secret NAME]; Save secrets adds, replaces and deletes them without reading any back. Both are off by default. --- packages/api/src/agent-side/tools.test.ts | 14 +- packages/api/src/agent-side/tools.ts | 18 +- packages/api/src/mcp/tools.ts | 27 ++- packages/api/src/native/sandbox/exec.test.ts | 20 ++ packages/api/src/native/sandbox/exec.ts | 20 +- .../src/native/sandbox/secret-values.test.ts | 46 ++++ .../api/src/native/sandbox/secret-values.ts | 52 +++++ packages/api/src/native/sandbox/secrets.ts | 36 ++++ packages/api/src/native/vault/connector.ts | 80 ++++++- packages/api/src/native/vault/integration.ts | 2 +- packages/db/src/vault.ts | 6 +- packages/integrations/src/catalog.ts | 64 +++++- packages/integrations/src/index.ts | 2 + packages/integrations/src/tools.test.ts | 5 + packages/integrations/src/types.ts | 3 + packages/web/src/components/vault-secrets.tsx | 196 ++++++++++++++++++ packages/web/src/loaders.ts | 7 +- .../web/src/pages/connection-page.test.tsx | 29 +++ packages/web/src/pages/connection-page.tsx | 9 + 19 files changed, 602 insertions(+), 34 deletions(-) create mode 100644 packages/api/src/native/sandbox/secret-values.test.ts create mode 100644 packages/api/src/native/sandbox/secret-values.ts create mode 100644 packages/api/src/native/sandbox/secrets.ts create mode 100644 packages/web/src/components/vault-secrets.tsx diff --git a/packages/api/src/agent-side/tools.test.ts b/packages/api/src/agent-side/tools.test.ts index fc898226..f386f7a5 100644 --- a/packages/api/src/agent-side/tools.test.ts +++ b/packages/api/src/agent-side/tools.test.ts @@ -320,6 +320,16 @@ describe('runAgentTool', () => { expect(getAgentTask).toHaveBeenCalledWith('org-1', 'agent-1', 'task-1'); }); + test('a secret is given without its value, which only the person reads', async () => { + const {runAgentTool} = await import('./tools'); + const secret = {id: 'secret-1', values: {name: 'API_KEY', value: 'sk-never-shown', note: 'For the reports'}, updatedAt: '2026-11-17T10:00:00.000Z'}; + connector.get.mockResolvedValueOnce(Ok(secret)); + connector.list.mockResolvedValueOnce(Ok({records: [secret], nextPage: null})); + + expect((await runAgentTool(caller, 'vault-1', 'secrets_get', {id: 'secret-1'})).unwrap()).toEqual({record: {...secret, values: {name: 'API_KEY', note: 'For the reports'}}}); + expect(JSON.stringify((await runAgentTool(caller, 'vault-1', 'secrets_list', {})).unwrap())).not.toContain('sk-never-shown'); + }); + test('a run for a task the agent does not have, or one finished already, is refused unlogged', async () => { const {runAgentTool} = await import('./tools'); getAgentTask.mockResolvedValue(Ok(null)); @@ -806,11 +816,13 @@ describe("an integration's own tools", () => { 'entries_create', 'entries_update', 'entries_delete', + 'secrets_list', + 'secrets_get', 'entries_count', 'entries_purge', ]); getAgentById.mockResolvedValue(Ok({...agent, grants: []})); - expect((await listAgentTools(signedIn, 'vault-1')).unwrap().map((tool) => tool.name)).toEqual(['entries_list', 'entries_get', 'entries_count']); + expect((await listAgentTools(signedIn, 'vault-1')).unwrap().map((tool) => tool.name)).toEqual(['entries_list', 'entries_get', 'secrets_list', 'secrets_get', 'entries_count']); }); test('run by the runner with the params as given, for the caller on the connection, and logged by name with them', async () => { diff --git a/packages/api/src/agent-side/tools.ts b/packages/api/src/agent-side/tools.ts index 69ffff0e..0dbb3b4a 100644 --- a/packages/api/src/agent-side/tools.ts +++ b/packages/api/src/agent-side/tools.ts @@ -484,6 +484,16 @@ function requireApplies(condition: Condition | undefined, record: DataRecord): R return Err(ApiErr.validationError(`Only for ${condition?.values.join(' or ')}`)); } +// A record as an agent is given it: without what is never given to one, as a vault's secret's +// value (`Field.secret`), which the person reads on the connection's page and a command uses by name. +function withoutSecrets(collection: Collection, record: DataRecord): DataRecord { + const hidden = collection.fields.filter((field) => field.secret).map((field) => field.key); + if (hidden.length === 0) { + return record; + } + return {...record, values: Object.fromEntries(Object.entries(record.values).filter(([key]) => !hidden.includes(key)))}; +} + // A list opened inside a record, in a nested collection, is logged with that record's title. function list(run: StoreRun, params: Record): Promise> { return Do(async ($) => { @@ -491,7 +501,7 @@ function list(run: StoreRun, params: Record): Promise withoutSecrets(run.target.collection, record))}; }); } @@ -499,7 +509,7 @@ function get(run: StoreRun, recordId: string): Promise { const record = $(await logFailure(run, await run.connector.get(run.target, recordId), null)); $(await log(run, 'allowed', recordTitle(run.target.collection, record.values))); - return {record}; + return {record: withoutSecrets(run.target.collection, record)}; }); } @@ -526,7 +536,7 @@ function create(run: StoreRun, params: Record): Promise): Promise connection.integrationId === VAULT_INTEGRATION_ID); + const uses = vaults.some((vault) => vault.actions.includes('useSecrets')); + const adds = vaults.some((vault) => vault.actions.includes('writeSecrets')); + if (!uses && !adds) { + return []; + } + return [ + [ + ...(uses + ? [ + 'A vault’s secrets (secrets_list), such as API keys, are given to a sandbox command as environment variables by name: sandbox_exec {secrets: ["NAME"]}. Their values are never shown to you.', + ] + : []), + ...(adds ? ['Keep a key you made with secrets_create {name, value, note}: it can’t be read back.'] : []), + ].join(' '), + ]; +} + const GITHUB_INTEGRATION_ID = 'github'; function runsCommands(connection: AgentConnection): boolean { @@ -201,8 +222,9 @@ export function pageInstructions(signedIn: SignedInAgent): Promise> { return Do(async ($) => { @@ -221,6 +243,7 @@ export function agentInstructions(signedIn: SignedInAgent, flow: string, folder? flow, lines.length > 0 ? `Connections:\n${lines.join('\n')}` : 'This login has no access yet: the person who made it has to give it some.', ...vaultInstructions(connections), + ...secretInstructions(connections), ...sandboxInstructions(connections), ...filesInstructions(connections, folder), ...chatInstructions(connections), diff --git a/packages/api/src/native/sandbox/exec.test.ts b/packages/api/src/native/sandbox/exec.test.ts index e241c33e..41656231 100644 --- a/packages/api/src/native/sandbox/exec.test.ts +++ b/packages/api/src/native/sandbox/exec.test.ts @@ -45,6 +45,10 @@ const wakeSandbox = mock(async () => Ok(sandbox)); mock.module('./machines', () => ({requireBackend, wakeSandbox})); +const secretsFor = mock(async (): Promise, ApiError>> => Ok([])); + +mock.module('./secrets', () => ({secretsFor})); + const signedIn = {agentId: 'agent-1', orgId: 'org-1', ownerUserId: 'user-1', providerId: 'claude', name: 'Claude', orgSlug: 'org-1', experiments: []}; const caller = {agent: signedIn, via: 'mcp' as const, taskId: 'task-1'}; const connection = {id: 'sandboxes-1'} as never; @@ -58,6 +62,7 @@ beforeEach(() => { mock.clearAllMocks(); sandbox.papVersion = 'v2'; exec.mockImplementation(async () => Ok(done)); + secretsFor.mockImplementation(async () => Ok([])); mockEnv.AUTH_SECRET = 'test-auth-secret'; mockEnv.APP_URL = 'https://app.example.com'; }); @@ -78,6 +83,21 @@ describe('runSandboxCommand', () => { expect(left).toBeLessThanOrEqual(91); }); + test('with secrets, the command is given each by its name, and what it writes shows each by its name', async () => { + secretsFor.mockImplementation(async () => Ok([{name: 'API_KEY', value: 'sk-test-123'}])); + exec.mockImplementation(async () => Ok({...done, stdout: 'key is sk-test-123\n'})); + const answer = (await run({secrets: ['API_KEY']})).unwrap(); + expect(exec.mock.calls.at(-1)?.[1].env).toEqual({API_KEY: 'sk-test-123'}); + expect(answer).toContain('key is [secret API_KEY]'); + expect(answer).not.toContain('sk-test-123'); + }); + + test('a secret no vault lets the agent use fails the call, and nothing is run', async () => { + secretsFor.mockImplementation(async () => Err(ApiErr.validationError('No vault lets you use its secrets'))); + expect((await run({secrets: ['API_KEY']})).isErr()).toBe(true); + expect(exec).not.toHaveBeenCalled(); + }); + test('without pap, no environment at all', async () => { await run({}); await run({pap: false}); diff --git a/packages/api/src/native/sandbox/exec.ts b/packages/api/src/native/sandbox/exec.ts index 29214a4e..554f6148 100644 --- a/packages/api/src/native/sandbox/exec.ts +++ b/packages/api/src/native/sandbox/exec.ts @@ -12,6 +12,8 @@ import type {NativeToolRunner} from '../tool'; import {holdForTask} from './lease'; import {requireBackend, wakeSandbox} from './machines'; import {ensurePap, withPapOnPath} from './pap'; +import {maskSecrets, secretEnv} from './secret-values'; +import {secretsFor} from './secrets'; /** * The console, `sandbox_exec`: a command run in a sandbox of the connection's for the caller's @@ -22,7 +24,9 @@ import {ensurePap, withPapOnPath} from './pap'; * the `pap` CLI on its PATH, installed first where it isn't this server's (pap.ts); without it, no * credential and nothing installed. The activity log has the command as the agent gave it. The * token is signed once the sandbox is woken and pap installed, so it lasts as long as the command - * may. + * may. With `secrets`, it is given the vaults' secrets named, as environment variables + * (secrets.ts), and what it writes back has their values shown by their names; the log has the + * names alone, as the agent gave them. */ const paramsSchema = z.object({ @@ -32,6 +36,7 @@ const paramsSchema = z.object({ cwd: z.string().optional(), timeout: z.number().positive().max(SANDBOX_EXEC_MAX_SECONDS).optional(), pap: z.boolean().optional(), + secrets: z.array(z.string().min(1)).max(50).optional(), }); // How much of each stream the model is given; the gate cuts the whole answer further. @@ -65,9 +70,12 @@ export const runSandboxCommand: NativeToolRunner = ({caller, connection, params} Do(async ($): Promise => { const parsed = parseSchema(paramsSchema, params); if (parsed.isErr()) { - return $(Err(ApiErr.validationError(`sandbox_exec takes sandbox, command, and stdin, cwd, timeout and pap where wanted: ${parsed.error.kind === 'parse_error' ? parsed.error.message : ''}`))); + return $( + Err(ApiErr.validationError(`sandbox_exec takes sandbox, command, and stdin, cwd, timeout, pap and secrets where wanted: ${parsed.error.kind === 'parse_error' ? parsed.error.message : ''}`)), + ); } - const {sandbox: sandboxId, command, stdin, cwd, timeout = SANDBOX_EXEC_DEFAULT_SECONDS, pap = false} = parsed.value; + const {sandbox: sandboxId, command, stdin, cwd, timeout = SANDBOX_EXEC_DEFAULT_SECONDS, pap = false, secrets: asked = []} = parsed.value; + const secrets = $(await secretsFor(caller, asked)); const config = pap ? $(requireCliTokenConfig()) : null; const bundle = pap ? $(await papBundle()) : null; const backend = $(await requireBackend()); @@ -78,8 +86,10 @@ export const runSandboxCommand: NativeToolRunner = ({caller, connection, params} $(await ensurePap(backend, running, bundle)); } const claims = {agentId: caller.agent.agentId, orgId: caller.agent.orgId, ownerUserId: caller.agent.ownerUserId, taskId: caller.taskId, sandboxId: running.id, connectionId: connection.id}; - const sent = config === null ? {command} : {command: withPapOnPath(command), env: cliCommandEnv(config, claims, timeout)}; + const given = secretEnv(secrets); + const plain = secrets.length === 0 ? {command} : {command, env: given}; + const sent = config === null ? plain : {command: withPapOnPath(command), env: {...given, ...cliCommandEnv(config, claims, timeout)}}; const output = $(await backend.exec(running.backendRef, {...sent, stdin, cwd, timeoutMs: Math.round(timeout * 1000)})); $(await touchSandbox(running.id)); - return describeOutput(output, timeout); + return describeOutput({...output, stdout: maskSecrets(output.stdout, secrets), stderr: maskSecrets(output.stderr, secrets)}, timeout); }); diff --git a/packages/api/src/native/sandbox/secret-values.test.ts b/packages/api/src/native/sandbox/secret-values.test.ts new file mode 100644 index 00000000..bda46ee7 --- /dev/null +++ b/packages/api/src/native/sandbox/secret-values.test.ts @@ -0,0 +1,46 @@ +import {describe, expect, test} from 'bun:test'; + +import {maskSecrets, pickSecret, secretEnv} from './secret-values'; + +const own = {id: 'vault-1', integrationId: 'vault', account: 'Acme', shared: false, actions: ['useSecrets'], name: null, signInNeeded: false}; +const work = {...own, id: 'vault-2', name: 'Work', shared: true}; + +describe('pickSecret', () => { + test('finds a name one vault has', () => { + const held = [{name: 'API_KEY', value: 'sk-one', vault: own}]; + expect(pickSecret(held, 'API_KEY').unwrap()).toEqual({name: 'API_KEY', value: 'sk-one'}); + }); + + test('asks which vault where two have the name, and takes one named by its name or id', () => { + const held = [ + {name: 'API_KEY', value: 'sk-one', vault: own}, + {name: 'API_KEY', value: 'sk-two', vault: work}, + ]; + expect(pickSecret(held, 'API_KEY').isErr()).toBe(true); + expect(pickSecret(held, 'Work/API_KEY').unwrap().value).toBe('sk-two'); + expect(pickSecret(held, 'vault-1/API_KEY').unwrap().value).toBe('sk-one'); + expect(pickSecret(held, 'Vault/API_KEY').unwrap().value).toBe('sk-one'); + }); + + test('a name no vault has is not found', () => { + expect(pickSecret([], 'MISSING').unwrapErr().kind).toBe('not_found'); + }); +}); + +describe('maskSecrets', () => { + test('shows each value as its name, the longer first', () => { + const secrets = [ + {name: 'SHORT', value: 'abcd'}, + {name: 'LONG', value: 'abcdefgh'}, + ]; + expect(maskSecrets('key=abcdefgh and abcd', secrets)).toBe('key=[secret LONG] and [secret SHORT]'); + }); + + test('leaves values too short to tell apart as they are', () => { + expect(maskSecrets('a b c', [{name: 'TINY', value: 'b'}])).toBe('a b c'); + }); +}); + +test('secretEnv gives each secret by its name', () => { + expect(secretEnv([{name: 'API_KEY', value: 'sk-one'}])).toEqual({API_KEY: 'sk-one'}); +}); diff --git a/packages/api/src/native/sandbox/secret-values.ts b/packages/api/src/native/sandbox/secret-values.ts new file mode 100644 index 00000000..63f3936d --- /dev/null +++ b/packages/api/src/native/sandbox/secret-values.ts @@ -0,0 +1,52 @@ +import {Err, Ok, type Result} from 'ts-results-es'; + +import {ApiErr, type ApiError} from '@proxy/utils'; +import type {AgentConnection} from '@proxy/contracts/agent-side'; + +/** + * Secrets as a sandbox command is given them (secrets.ts finds them): the one a name asks for, + * the environment they make, and what the command wrote with each value shown as its name. + */ + +/** A secret as a command is given it. */ +export type GivenSecret = {name: string; value: string}; + +/** A secret of a vault the agent may use the secrets of. */ +export type HeldSecret = GivenSecret & {vault: AgentConnection}; + +// Whether the vault is the one a name was asked for in: by its id, or by what it is called, the +// person's own being called Vault. +function vaultCalled(vault: AgentConnection, called: string): boolean { + return vault.id === called || vault.name === called || (vault.name === null && called.toLowerCase() === 'vault'); +} + +/** The secret a name asks for, among those held: the one vault that has it, or the one named, as Work/OPENAI_API_KEY. */ +export function pickSecret(held: HeldSecret[], asked: string): Result { + const slash = asked.lastIndexOf('/'); + const name = slash === -1 ? asked : asked.slice(slash + 1); + const vault = slash === -1 ? null : asked.slice(0, slash); + const found = held.filter((secret) => secret.name === name && (vault === null || vaultCalled(secret.vault, vault))); + if (found.length > 1) { + return Err(ApiErr.validationError(`${name} is in more than one vault: ask for it as ${found.map((secret) => `${secret.vault.id}/${name}`).join(' or ')}`)); + } + const [only] = found; + if (!only) { + return Err(ApiErr.notFound('secret', asked, 'secrets_list, in a vault you may use the secrets of, lists them.')); + } + return Ok({name: only.name, value: only.value}); +} + +// Values shorter than this are left as they are in what a command writes: a word that short is +// more likely to be anything else. +const MASKED_FROM = 4; + +/** What a command wrote, each secret's value in it shown as [secret NAME], the longest first, so one inside another is never half shown. */ +export function maskSecrets(text: string, secrets: GivenSecret[]): string { + const masked = secrets.filter((secret) => secret.value.length >= MASKED_FROM).toSorted((a, b) => b.value.length - a.value.length); + return masked.reduce((shown, secret) => shown.split(secret.value).join(`[secret ${secret.name}]`), text); +} + +/** The secrets as environment variables, by their names. */ +export function secretEnv(secrets: GivenSecret[]): Record { + return Object.fromEntries(secrets.map((secret) => [secret.name, secret.value])); +} diff --git a/packages/api/src/native/sandbox/secrets.ts b/packages/api/src/native/sandbox/secrets.ts new file mode 100644 index 00000000..3268f491 --- /dev/null +++ b/packages/api/src/native/sandbox/secrets.ts @@ -0,0 +1,36 @@ +import {Err, type Result} from 'ts-results-es'; + +import {ApiErr, type ApiError, Do} from '@proxy/utils'; +import {VAULT_INTEGRATION_ID} from '@proxy/integrations'; + +import type {TaskCaller} from '../../agent-side/tools'; +import {listSecrets} from '../vault/connector'; +import {type GivenSecret, type HeldSecret, pickSecret} from './secret-values'; + +/** + * The vaults' secrets a sandbox command is given, as environment variables, by the names the + * agent asked for: only from vaults it has Use secrets on. The command can do what it likes with + * what it is given, which the permission says; what it writes back has each value shown by its + * name (secret-values.ts), so a key printed as it is never reaches the model. + */ +export function secretsFor(caller: TaskCaller, asked: string[]): Promise> { + return Do(async ($) => { + if (asked.length === 0) { + return []; + } + // Read when asked for: the agent side runs every tool, this one among them, so importing it + // as this file loads would load the whole of it with any sandbox module. + const {listAgentConnections} = await import('../../agent-side/tools'); + const {connections} = $(await listAgentConnections(caller.agent)); + const vaults = connections.filter((connection) => connection.integrationId === VAULT_INTEGRATION_ID && connection.actions.includes('useSecrets')); + if (vaults.length === 0) { + return $(Err(ApiErr.validationError('No vault lets you use its secrets: the person turns on Use secrets for one on its page.'))); + } + const held: HeldSecret[] = []; + for (const vault of vaults) { + const secrets = $(await listSecrets(vault.id)); + held.push(...secrets.map((secret) => ({...secret, vault}))); + } + return [...new Set(asked)].map((name) => $(pickSecret(held, name))); + }); +} diff --git a/packages/api/src/native/vault/connector.ts b/packages/api/src/native/vault/connector.ts index 14cba62a..fa3e4bd6 100644 --- a/packages/api/src/native/vault/connector.ts +++ b/packages/api/src/native/vault/connector.ts @@ -2,17 +2,22 @@ import {Err, Ok, Result} from 'ts-results-es'; import {z} from 'zod'; import {ApiErr, type ApiError, Do, parseSchema, requirePresent} from '@proxy/utils'; -import {createVaultEntry, deleteVaultEntry, getVaultEntry, listVaultEntries, updateVaultEntry, type VaultEntryRow} from '@proxy/db/vault'; +import {SECRET_NAME_PATTERN, VAULT_SECRETS_COLLECTION_ID} from '@proxy/integrations'; +import {createVaultEntry, deleteVaultEntry, getVaultEntry, listVaultEntries, updateVaultEntry, type VaultCollection, type VaultEntryRow} from '@proxy/db/vault'; import {decryptSecret, encryptSecret} from '../../utils/secret-crypto'; import {requireFirstPage, type DataRecord, type RecordStore, type RecordTarget, type RecordValues} from '../../records/connector'; const storedValuesSchema = z.record(z.string(), z.string()); -function vaultCollection(target: RecordTarget) { +function vaultCollection(target: RecordTarget): VaultCollection { return {connectionId: target.connection.id, collectionId: target.collection.id}; } +function isSecrets(target: RecordTarget): boolean { + return target.collection.id === VAULT_SECRETS_COLLECTION_ID; +} + export function encryptValues(values: RecordValues): Result { return encryptSecret(JSON.stringify(values)); } @@ -25,8 +30,11 @@ export function decryptValues(stored: string): Result { }); } -// An entry without a type is Text, as its row shows it. -function withType(values: RecordValues): RecordValues { +// An entry without a type is Text, as its row shows it; a secret has none. +function withType(target: RecordTarget, values: RecordValues): RecordValues { + if (isSecrets(target)) { + return values; + } return {...values, type: values.type || 'Text'}; } @@ -42,16 +50,62 @@ function toRecord(row: VaultEntryRow): Result { return decryptValues(row.values).map((values) => ({id: row.id, values, updatedAt: row.updatedAt.toISOString()})); } -/** The vault lives in Personal Agent Proxy: each entry's title, type and content are stored as encrypted JSON. */ +function listRecords(collection: VaultCollection): Promise> { + return Do(async ($) => { + const rows = $(await listVaultEntries(collection)); + return rows.map((row) => $(toRecord(row))); + }); +} + +/** A vault's secrets, each by its name and value, as a sandbox command is given them (native/sandbox/secrets.ts). */ +export function listSecrets(connectionId: string): Promise, ApiError>> { + return Do(async ($) => { + const records = $(await listRecords({connectionId, collectionId: VAULT_SECRETS_COLLECTION_ID})); + return records.map((record) => ({name: record.values.name ?? '', value: record.values.value ?? ''})); + }); +} + +// A secret needs a name a command's environment can have, one no other secret of the vault has, +// and a value. `id` is the secret's own, where it is being changed. +function requireSecret(target: RecordTarget, values: RecordValues, id: string | null): Promise> { + return Do(async ($) => { + const name = (values.name ?? '').trim(); + if (!SECRET_NAME_PATTERN.test(name)) { + return $(Err(ApiErr.validationError('A secret’s name is an environment variable’s: letters, digits and _, not starting with a digit, as OPENAI_API_KEY'))); + } + if ((values.value ?? '') === '') { + return $(Err(ApiErr.validationError('A secret needs a value'))); + } + const others = $(await listRecords(vaultCollection(target))); + if (others.some((other) => other.id !== id && other.values.name === name)) { + return $(Err(ApiErr.conflict(`This vault has a secret called ${name} already`))); + } + return {name, value: values.value ?? '', note: values.note ?? ''}; + }); +} + +// What a write keeps: an entry with its type, or a secret as it has to be. +function written(target: RecordTarget, values: RecordValues, id: string | null): Promise> { + if (isSecrets(target)) { + return requireSecret(target, values, id); + } + return Promise.resolve(Ok(withType(target, values))); +} + +/** + * The vault lives in Personal Agent Proxy: each entry's title, type and content, and each secret's + * name, value and note, are stored as encrypted JSON. A search reads every field but those never + * given to an agent, a secret's value. + */ export const vaultConnector = { // Few enough to search in memory, after decrypting, and to list on one page. list: (target, query) => Do(async ($) => { $(requireFirstPage(query)); - const rows = $(await listVaultEntries(vaultCollection(target))); - const records = rows.map((row) => $(toRecord(row))); + const records = $(await listRecords(vaultCollection(target))); const search = query.search?.toLowerCase(); - const matching = search ? records.filter((record) => Object.values(record.values).some((value) => value.toLowerCase().includes(search))) : records; + const searched = target.collection.fields.filter((field) => !field.secret).map((field) => field.key); + const matching = search ? records.filter((record) => searched.some((key) => (record.values[key] ?? '').toLowerCase().includes(search))) : records; return {records: matching, nextPage: null}; }), get: (target, recordId) => @@ -61,13 +115,17 @@ export const vaultConnector = { }), create: (target, values) => Do(async ($) => { - $(requireWritten(values)); - const row = $(await createVaultEntry(vaultCollection(target), $(encryptValues(withType(values))))); + if (!isSecrets(target)) { + $(requireWritten(values)); + } + const kept = $(await written(target, values, null)); + const row = $(await createVaultEntry(vaultCollection(target), $(encryptValues(kept)))); return $(toRecord(row)); }), update: (target, recordId, values) => Do(async ($) => { - const row = $(await updateVaultEntry(vaultCollection(target), recordId, $(encryptValues(withType(values))))); + const kept = $(await written(target, values, recordId)); + const row = $(await updateVaultEntry(vaultCollection(target), recordId, $(encryptValues(kept)))); return $(toRecord(row)); }), remove: (target, recordId) => deleteVaultEntry(vaultCollection(target), recordId), diff --git a/packages/api/src/native/vault/integration.ts b/packages/api/src/native/vault/integration.ts index d74e7a6b..fd832a50 100644 --- a/packages/api/src/native/vault/integration.ts +++ b/packages/api/src/native/vault/integration.ts @@ -4,5 +4,5 @@ import type {ApiIntegration} from '../../connections/integration'; /** The vault, in Personal Agent Proxy itself: always there, never connected or disconnected. */ export const VAULT_INTEGRATION: ApiIntegration = { id: 'vault', - connectors: {entries: vaultConnector}, + connectors: {entries: vaultConnector, secrets: vaultConnector}, }; diff --git a/packages/db/src/vault.ts b/packages/db/src/vault.ts index e9aa4a2f..b370c199 100644 --- a/packages/db/src/vault.ts +++ b/packages/db/src/vault.ts @@ -78,14 +78,14 @@ export async function deleteVaultEntry( }); } -// A record from before the vault had one collection: an address, a payment card or a note, until -// the api turns it into an entry as it starts. +// A record from before the vault had its entries: an address, a payment card or a note, until the +// api turns it into an entry as it starts. A secret is the vault's own, as an entry is. export type OldVaultRecord = {id: string; collectionId: string; values: string}; export async function listOldVaultRecords(): Promise> { return wrapDb(() => db.vaultEntry.findMany({ - where: {collectionId: {not: 'entries'}}, + where: {collectionId: {notIn: ['entries', 'secrets']}}, select: {id: true, collectionId: true, values: true}, }), ); diff --git a/packages/integrations/src/catalog.ts b/packages/integrations/src/catalog.ts index abc6909f..c16dd0db 100644 --- a/packages/integrations/src/catalog.ts +++ b/packages/integrations/src/catalog.ts @@ -2063,6 +2063,12 @@ const plaid: Integration = { ], }; +/** The vault's secrets, beside its entries. */ +export const VAULT_SECRETS_COLLECTION_ID = 'secrets'; + +/** What a secret's name has to be: an environment variable's, as OPENAI_API_KEY. */ +export const SECRET_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/; + // What a vault entry's value is, so a row shows it as such and an agent knows what it holds. export const VAULT_ENTRY_TYPES = ['Text', 'Address', 'Phone number', 'Email', 'Link', 'Date']; @@ -2072,11 +2078,17 @@ export const VAULT_ENTRY_TYPES = ['Text', 'Address', 'Phone number', 'Email', 'L const vault: Integration = { id: VAULT_INTEGRATION_ID, name: 'Vault', - description: 'What agents should know, kept in Personal Agent Proxy', + description: + 'What agents should know, and the secrets they may use, kept in Personal Agent Proxy', native: true, - made: {one: 'vault', holds: 'entries'}, + made: {one: 'vault', holds: 'entries and secrets'}, actions: [ - {id: 'readEntries', label: 'Read entries', description: 'List and open entries', risk: 'low'}, + { + id: 'readEntries', + label: 'Read entries', + description: 'List and open entries, and see which secrets there are', + risk: 'low', + }, { id: 'writeEntries', label: 'Edit entries', @@ -2084,6 +2096,22 @@ const vault: Integration = { risk: 'medium', requires: 'readEntries', }, + { + id: 'writeSecrets', + label: 'Save secrets', + description: + 'Add, replace and delete secrets, such as a key it made, without reading any back', + risk: 'medium', + requires: 'readEntries', + }, + { + id: 'useSecrets', + label: 'Use secrets', + description: + 'Give secrets to sandbox commands as environment variables. A command can read what it is given and send it anywhere', + risk: 'high', + requires: 'readEntries', + }, ], collections: [ { @@ -2101,12 +2129,32 @@ const vault: Integration = { {key: 'content', label: 'Content', type: 'longtext'}, ], }, + // Secrets, such as API keys, by the environment variable a command is given each as: an + // agent sees a secret's name and note, never its value, which only the person reads, on the + // vault's page. Agents with Use secrets have them given to a sandbox command by name + // (native/sandbox/secrets.ts); with Save secrets, add, replace and delete them, as a key + // they made, without ever reading one back. + { + id: VAULT_SECRETS_COLLECTION_ID, + name: 'Secrets', + singular: 'secret', + titleField: 'name', + summaryField: 'note', + read: 'readEntries', + writes: {create: 'writeSecrets', update: 'writeSecrets', delete: 'writeSecrets'}, + searchHint: 'Matches the words in the name or the note, in any case.', + fields: [ + {key: 'name', label: 'Name', type: 'text'}, + {key: 'value', label: 'Value', type: 'text', secret: true}, + {key: 'note', label: 'Note', type: 'longtext'}, + ], + }, ], }; // What agents may do with a vault by default, a member's own and any they make: read it, and -// keep what they learn there, unless told otherwise. -export const VAULT_DEFAULT_ACTIONS: string[] = vault.actions.map((action) => action.id); +// keep what they learn there, unless told otherwise. Its secrets are the person's to hand out. +export const VAULT_DEFAULT_ACTIONS: string[] = ['readEntries', 'writeEntries']; export const SANDBOX_INTEGRATION_ID = 'sandbox'; @@ -2225,6 +2273,12 @@ const sandbox: Integration = { type: 'boolean', description: 'Lets the command use pap, to call your connections from code', }, + secrets: { + type: 'array', + items: {type: 'string'}, + description: + 'Vault secrets to give the command as environment variables, by name, as OPENAI_API_KEY, or as Vault name/NAME where two vaults have it. A value the command writes is shown as [secret NAME]', + }, }, required: ['sandbox', 'command'], }, diff --git a/packages/integrations/src/index.ts b/packages/integrations/src/index.ts index a87c3acd..196aa26b 100644 --- a/packages/integrations/src/index.ts +++ b/packages/integrations/src/index.ts @@ -16,9 +16,11 @@ export { SANDBOX_EXEC_DEFAULT_SECONDS, SANDBOX_EXEC_MAX_SECONDS, SANDBOX_INTEGRATION_ID, + SECRET_NAME_PATTERN, VAULT_DEFAULT_ACTIONS, VAULT_ENTRY_TYPES, VAULT_INTEGRATION_ID, + VAULT_SECRETS_COLLECTION_ID, } from './catalog'; export {allowedTools, findTool, integrationTools, toolName} from './tools'; export type { diff --git a/packages/integrations/src/tools.test.ts b/packages/integrations/src/tools.test.ts index c782e4bf..aeeb41ab 100644 --- a/packages/integrations/src/tools.test.ts +++ b/packages/integrations/src/tools.test.ts @@ -710,6 +710,11 @@ describe("an integration's own tools", () => { 'entries_create', 'entries_update', 'entries_delete', + 'secrets_list', + 'secrets_get', + 'secrets_create', + 'secrets_update', + 'secrets_delete', 'entries_count', 'entries_purge', ]); diff --git a/packages/integrations/src/types.ts b/packages/integrations/src/types.ts index 758d5d2d..2f45a62c 100644 --- a/packages/integrations/src/types.ts +++ b/packages/integrations/src/types.ts @@ -15,6 +15,9 @@ export type Field = { // The action writing it needs beyond the collection's write: creating or editing a record where // it holds anything, before the write or after it, as an event's guests need Invite guests. action?: string; + // Never given to an agent, as a vault's secret's value: the person reads it on the connection's + // page, and agents only use it where an action lets them. + secret?: true; }; // One thing an agent can be allowed to do with a connection, set on its own: Read, Archive, Send. diff --git a/packages/web/src/components/vault-secrets.tsx b/packages/web/src/components/vault-secrets.tsx new file mode 100644 index 00000000..a851cfd6 --- /dev/null +++ b/packages/web/src/components/vault-secrets.tsx @@ -0,0 +1,196 @@ +import type {DataRecord} from '@proxy/contracts/records'; +import {VAULT_SECRETS_COLLECTION_ID} from '@proxy/integrations'; +import {EyeIcon, EyeOffIcon, KeyRoundIcon} from 'lucide-react'; +import {useState} from 'react'; +import {createRecord, deleteRecord, updateRecord} from '@/client/records-client'; +import {AddButton} from '@/components/add-button'; +import {CopyButton} from '@/components/copy-button'; +import {IconButton} from '@/components/icon-button'; +import {EmptyRows, Row, RowHeader, RowList} from '@/components/row-list'; +import {useApply} from '@/hooks/use-apply'; +import {useOrgSlug} from '@/hooks/use-org'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from '@proxy/ui/components/dialog'; +import {Input} from '@proxy/ui/components/input'; +import {Label} from '@proxy/ui/components/label'; +import {PillButton} from '@proxy/ui/components/pill-button'; +import {Textarea} from '@proxy/ui/components/textarea'; + +const EMPTY = + 'No secrets yet. Add an API key or a token, and turn on Use secrets for the agents that may run commands with it.'; + +const HIDDEN = '••••••••••••'; + +const CELLS = { + note: 'hidden w-2/5 shrink-0 truncate text-muted-foreground md:block', + value: + 'flex w-56 shrink-0 items-center justify-end gap-1 font-mono text-xs text-muted-foreground', +}; + +// One secret's value, hidden until the person shows it, and copied either way. +function SecretValue({value}: {value: string}) { + const [shown, setShown] = useState(false); + return ( + <> + {shown ? value : HIDDEN} + setShown(!shown)}> + {shown ? : } + + + + ); +} + +// A secret written by the person: its name, its value and what it is for. +function SecretDialog({ + connectionId, + secret, + onClose, +}: { + connectionId: string; + secret: DataRecord | null; + onClose: () => void; +}) { + const org = useOrgSlug(); + const [name, setName] = useState(secret?.values.name ?? ''); + const [value, setValue] = useState(secret?.values.value ?? ''); + const [note, setNote] = useState(secret?.values.note ?? ''); + const [error, setError] = useState(null); + const apply = useApply(setError); + const values = {name: name.trim(), value, note}; + return ( + + + {secret ? secret.values.name : 'New secret'} + + Agents see its name and note, never its value. Those with Use secrets have it given to + their sandbox commands as an environment variable. + + +
+ + setName(event.target.value)} + /> +
+
+ + setValue(event.target.value)} + /> +
+
+ +