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..587e8dc1 100644 --- a/packages/api/src/agent-side/tools.ts +++ b/packages/api/src/agent-side/tools.ts @@ -440,9 +440,31 @@ function runParamsTool(target: RunTarget, tool: ServerTool | ApiTool, params: un }); } +// What a tool answers an agent, of whatever kind: never 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. Taken out here, once, so that no kind of tool answers with it. +async function execute(run: ToolRun, params: Record): Promise> { + return (await executeKind(run, params)).map((answer) => withoutSecrets(run.target.collection, answer)); +} + +function withoutSecrets(collection: Collection, answer: ToolResult): ToolResult { + const hidden = collection.fields.filter((field) => field.secret).map((field) => field.key); + if (hidden.length === 0) { + return answer; + } + const hide = (record: DataRecord): DataRecord => ({...record, values: Object.fromEntries(Object.entries(record.values).filter(([key]) => !hidden.includes(key)))}); + if ('records' in answer) { + return {...answer, records: answer.records.map(hide)}; + } + if ('record' in answer && answer.record !== null) { + return {record: hide(answer.record)}; + } + return answer; +} + // Only a command on values typed in runs on a collection that is only run; the catalog gives such // a collection no other tool, so a run of another on it is a tool it doesn't have. -function execute(run: ToolRun, params: Record): Promise> { +function executeKind(run: ToolRun, params: Record): Promise> { const {kind} = run.tool; if (kind === 'newCommand') { return newCommand(run, params); diff --git a/packages/api/src/mcp/tools.ts b/packages/api/src/mcp/tools.ts index 2270aeae..8497416c 100644 --- a/packages/api/src/mcp/tools.ts +++ b/packages/api/src/mcp/tools.ts @@ -124,6 +124,27 @@ function vaultInstructions(connections: AgentConnection[]): string[] { ]; } +// The vaults' secrets, where the agent may use or add them: that a sandbox command is given them +// by name, and that their values are never shown to it. +function secretInstructions(connections: AgentConnection[]): string[] { + const vaults = connections.filter((connection) => 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 kept from you: where a command prints one, it is shown as [secret NAME]. Don’t print them.', + ] + : []), + ...(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..d1c69b41 100644 --- a/packages/api/src/native/sandbox/exec.test.ts +++ b/packages/api/src/native/sandbox/exec.test.ts @@ -45,6 +45,11 @@ const wakeSandbox = mock(async () => Ok(sandbox)); mock.module('./machines', () => ({requireBackend, wakeSandbox})); +type Secret = {name: string; value: string}; +const secretsFor = mock(async (): Promise> => Ok({given: [], masked: []})); + +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 +63,7 @@ beforeEach(() => { mock.clearAllMocks(); sandbox.papVersion = 'v2'; exec.mockImplementation(async () => Ok(done)); + secretsFor.mockImplementation(async () => Ok({given: [], masked: []})); mockEnv.AUTH_SECRET = 'test-auth-secret'; mockEnv.APP_URL = 'https://app.example.com'; }); @@ -78,6 +84,31 @@ 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 () => { + const key = {name: 'API_KEY', value: 'sk-test-123'}; + secretsFor.mockImplementation(async () => Ok({given: [key], masked: [key]})); + 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('without secrets, the command is given none, and what it writes still shows each the agent may use by its name', async () => { + secretsFor.mockImplementation(async () => Ok({given: [], masked: [{name: 'API_KEY', value: 'sk-test-123'}]})); + exec.mockImplementation(async () => Ok({...done, stdout: 'API_KEY=sk-test-123\n'})); + const answer = (await run({command: 'cat env.txt'})).unwrap(); + expect(exec.mock.calls.at(-1)?.[1].env).toBeUndefined(); + expect(answer).toContain('API_KEY=[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..3198207d 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,10 @@ 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); what any command writes back has the values of every secret the agent may use + * shown by their names, so one isn't read by accident. The log has the names alone, as the agent + * gave them. */ const paramsSchema = z.object({ @@ -32,6 +37,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 +71,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 {given: secrets, masked} = $(await secretsFor(caller, asked)); const config = pap ? $(requireCliTokenConfig()) : null; const bundle = pap ? $(await papBundle()) : null; const backend = $(await requireBackend()); @@ -78,8 +87,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, masked), stderr: maskSecrets(output.stderr, masked)}, 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..e32c03fb --- /dev/null +++ b/packages/api/src/native/sandbox/secret-values.test.ts @@ -0,0 +1,59 @@ +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('never takes a name already shown for a value', () => { + const secrets = [ + {name: 'OPENAI_API_KEY', value: 'sk-long-key-123'}, + {name: 'PROVIDER', value: 'OPENAI'}, + ]; + expect(maskSecrets('sk-long-key-123 from OPENAI', secrets)).toBe('[secret OPENAI_API_KEY] from [secret PROVIDER]'); + }); + + test('finds a value as it is, whatever it has in it', () => { + const secrets = [{name: 'PASSWORD', value: 'a.b*c(d)[e]$/-'}]; + expect(maskSecrets('pw: a.b*c(d)[e]$/- and axbxc', secrets)).toBe('pw: [secret PASSWORD] and axbxc'); + }); + + 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..f6daaf99 --- /dev/null +++ b/packages/api/src/native/sandbox/secret-values.ts @@ -0,0 +1,66 @@ +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; + +// A value as a pattern matching it as it is, whatever it has in it. +function escaped(value: string): string { + return value.replace(/[\\^$.*+?()[\]{}|/-]/g, '\\$&'); +} + +/** + * What a command wrote, each secret's value in it shown as [secret NAME]: all in one pass, the + * longest first where values overlap, so one inside another is never half shown and a name already + * shown is never mistaken for a value. + */ +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); + if (masked.length === 0) { + return text; + } + const names = new Map(masked.map((secret) => [secret.value, secret.name])); + const pattern = new RegExp(masked.map((secret) => escaped(secret.value)).join('|'), 'g'); + return text.replace(pattern, (value) => `[secret ${names.get(value) ?? ''}]`); +} + +/** 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.test.ts b/packages/api/src/native/sandbox/secrets.test.ts new file mode 100644 index 00000000..b41f950f --- /dev/null +++ b/packages/api/src/native/sandbox/secrets.test.ts @@ -0,0 +1,69 @@ +import {beforeEach, describe, expect, mock, test} from 'bun:test'; +import {Ok} from 'ts-results-es'; + +const vault = (id: string, name: string | null, actions: string[]) => ({id, integrationId: 'vault', account: 'Acme', shared: false, actions, name, signInNeeded: false}); + +const listAgentConnections = mock(); +mock.module('../../agent-side/tools', () => ({listAgentConnections})); + +const held: Record> = { + 'vault-1': [ + {name: 'API_KEY', value: 'sk-one'}, + {name: 'DB_URL', value: 'postgres://db'}, + ], + 'vault-2': [ + {name: 'WORK_TOKEN', value: 'tok-two'}, + {name: 'DB_URL', value: 'postgres://work'}, + ], + 'vault-3': [{name: 'HIDDEN', value: 'never-used'}], +}; +const listSecrets = mock(async (id: string) => Ok(held[id] ?? [])); +mock.module('../vault/connector', () => ({listSecrets})); + +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'}; + +beforeEach(() => { + mock.clearAllMocks(); + listAgentConnections.mockResolvedValue( + Ok({ + agent: {id: 'agent-1', providerId: 'claude', name: 'Claude'}, + connections: [vault('vault-1', null, ['readEntries', 'useSecrets']), vault('vault-2', 'Work', ['readEntries', 'useSecrets']), vault('vault-3', 'Other', ['readEntries'])], + }), + ); +}); + +describe('secretsFor', () => { + test('gives the command those asked for, and masks every secret of each vault the agent may use the secrets of', async () => { + const {secretsFor} = await import('./secrets'); + const {given, masked} = (await secretsFor(caller, ['API_KEY'])).unwrap(); + + expect(given).toEqual([{name: 'API_KEY', value: 'sk-one'}]); + expect(masked.map((secret) => secret.name).sort()).toEqual(['API_KEY', 'DB_URL', 'DB_URL', 'WORK_TOKEN']); + expect(listSecrets).not.toHaveBeenCalledWith('vault-3'); + }); + + test('asked for none, gives none and still masks them', async () => { + const {secretsFor} = await import('./secrets'); + const {given, masked} = (await secretsFor(caller, [])).unwrap(); + + expect(given).toEqual([]); + expect(masked).toHaveLength(4); + }); + + test('with no vault whose secrets it may use, a command asking for none runs as it is, and one asking for some is refused', async () => { + listAgentConnections.mockResolvedValue(Ok({agent: {id: 'agent-1', providerId: 'claude', name: 'Claude'}, connections: [vault('vault-3', 'Other', ['readEntries'])]})); + const {secretsFor} = await import('./secrets'); + + expect((await secretsFor(caller, [])).unwrap()).toEqual({given: [], masked: []}); + expect((await secretsFor(caller, ['API_KEY'])).unwrapErr().kind).toBe('validation_error'); + expect(listSecrets).not.toHaveBeenCalled(); + }); + + test('refuses one name asked for from two vaults, since a command is given one variable of it', async () => { + const {secretsFor} = await import('./secrets'); + + expect((await secretsFor(caller, ['Vault/DB_URL', 'Work/DB_URL'])).unwrapErr().kind).toBe('validation_error'); + expect((await secretsFor(caller, ['Work/DB_URL'])).unwrap().given).toEqual([{name: 'DB_URL', value: 'postgres://work'}]); + }); +}); diff --git a/packages/api/src/native/sandbox/secrets.ts b/packages/api/src/native/sandbox/secrets.ts new file mode 100644 index 00000000..b19798f0 --- /dev/null +++ b/packages/api/src/native/sandbox/secrets.ts @@ -0,0 +1,44 @@ +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 secrets of a sandbox command: those it is given as environment variables, by the names the + * agent asked for, and those shown by their names wherever what it writes has their values, + * every secret of the vaults the agent may use the secrets of, asked for or not. + */ +export type CommandSecrets = {given: GivenSecret[]; masked: GivenSecret[]}; + +/** + * The vaults' secrets for a sandbox command, from the vaults the agent has Use secrets on. What a + * command is given it can read, and send anywhere, which the permission says: masking what it + * writes back (secret-values.ts) keeps a value out of the agent's answers by accident, as when a + * command prints its environment or a file one wrote before, not from an agent set on reading it. + * Masked on every call, since a value one command wrote to a file another may print. + */ +export function secretsFor(caller: TaskCaller, asked: string[]): Promise> { + return Do(async ($) => { + // 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 && asked.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 lists = await Promise.all(vaults.map(async (vault) => (await listSecrets(vault.id)).map((secrets) => secrets.map((secret): HeldSecret => ({...secret, vault}))))); + const held = lists.flatMap((list) => $(list)); + const given = [...new Set(asked)].map((name) => $(pickSecret(held, name))); + // Each is given as the environment variable of its name, which one command has only one of. + const twice = given.find((secret, index) => given.findIndex((other) => other.name === secret.name) !== index); + if (twice) { + return $(Err(ApiErr.validationError(`${twice.name} is asked for from more than one vault: a command is given one ${twice.name}, so ask for one of them`))); + } + return {given, masked: held.map(({name, value}) => ({name, value}))}; + }); +} diff --git a/packages/api/src/native/vault/connector.test.ts b/packages/api/src/native/vault/connector.test.ts index 1fea1ff2..9473d1cf 100644 --- a/packages/api/src/native/vault/connector.test.ts +++ b/packages/api/src/native/vault/connector.test.ts @@ -1,6 +1,7 @@ import {beforeEach, describe, expect, mock, test} from 'bun:test'; -import {Ok} from 'ts-results-es'; +import {Ok, type Result} from 'ts-results-es'; +import type {ApiError} from '@proxy/utils'; import {findCollection, findIntegration, type Collection} from '@proxy/integrations'; mock.module('../../utils/env', () => ({env: {ENCRYPTION_KEY: Buffer.alloc(32, 7).toString('base64')}})); @@ -126,3 +127,48 @@ describe('vaultConnector', () => { expect(result.unwrapErr().kind).toBe('internal_error'); }); }); + +describe('a vault’s secrets', () => { + function secrets(): Collection { + const integration = findIntegration('vault'); + const found = integration && findCollection(integration, 'secrets'); + if (!found) { + throw new Error('No secrets collection'); + } + return found; + } + + test('keep a value without the spaces and line breaks pasted around it, and refuse one that is only those', async () => { + const {vaultConnector} = await import('./connector'); + const kept = {...target, collection: secrets()}; + listVaultEntries.mockResolvedValue(Ok([])); + + const created = await vaultConnector.create(kept, {name: 'API_KEY', value: ' sk-test-123 \n', note: ''}); + expect(created.unwrap().values).toEqual({name: 'API_KEY', value: 'sk-test-123', note: ''}); + expect((await vaultConnector.create(kept, {name: 'API_KEY', value: ' \n', note: ''})).unwrapErr().kind).toBe('validation_error'); + }); + + test('refuse a name another secret of the vault has, as they are written, and let a secret keep its own', async () => { + const {vaultConnector, encryptValues} = await import('./connector'); + const kept = {...target, collection: secrets()}; + const others = [{id: 'rec-2', values: encryptValues({name: 'API_KEY', value: 'sk-other', note: ''}).unwrap(), updatedAt}]; + createVaultEntry.mockImplementation((_collection: unknown, values: string, check?: (rows: typeof others) => Result) => + Promise.resolve(check ? check(others).map(() => ({id: 'rec-1', values, updatedAt})) : Ok({id: 'rec-1', values, updatedAt})), + ); + + expect((await vaultConnector.create(kept, {name: 'API_KEY', value: 'sk-new', note: ''})).unwrapErr().kind).toBe('conflict'); + expect((await vaultConnector.create(kept, {name: 'OTHER_KEY', value: 'sk-new', note: ''})).isOk()).toBe(true); + }); + + test('are listed for a command without those that can’t be read', async () => { + const {listSecrets, encryptValues} = await import('./connector'); + listVaultEntries.mockResolvedValue( + Ok([ + {id: 'rec-1', values: encryptValues({name: 'API_KEY', value: 'sk-one', note: ''}).unwrap(), updatedAt}, + {id: 'rec-2', values: 'v1.not.encrypted.here', updatedAt}, + ]), + ); + + expect((await listSecrets('vault-1')).unwrap()).toEqual([{name: 'API_KEY', value: 'sk-one'}]); + }); +}); diff --git a/packages/api/src/native/vault/connector.ts b/packages/api/src/native/vault/connector.ts index 14cba62a..4d655697 100644 --- a/packages/api/src/native/vault/connector.ts +++ b/packages/api/src/native/vault/connector.ts @@ -2,17 +2,23 @@ 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 VaultEntriesCheck, type VaultEntryRow} from '@proxy/db/vault'; +import {log} from '../../observability/log'; 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)); } @@ -42,16 +48,86 @@ 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). One that can't be read is left out and logged rather than failing + * the rest: its value can't be given to a command, nor found in what one writes. + */ +export function listSecrets(connectionId: string): Promise, ApiError>> { + return Do(async ($) => { + const rows = $(await listVaultEntries({connectionId, collectionId: VAULT_SECRETS_COLLECTION_ID})); + return rows.flatMap((row) => { + const values = decryptValues(row.values); + if (values.isErr()) { + log.warn('A vault secret could not be read', {connectionId, recordId: row.id, errorKind: values.error.kind}); + return []; + } + return [{name: values.value.name ?? '', value: values.value.value ?? ''}]; + }); + }); +} + +// A secret needs a name a command's environment can have and a value, kept without the spaces and +// line breaks around it, which a paste brings along and a command's output may leave off, so that +// masking finds the value as printed (secret-values.ts). +function requireSecret(values: RecordValues): Result { + 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')); + } + const value = (values.value ?? '').trim(); + if (value === '') { + return Err(ApiErr.validationError('A secret needs a value')); + } + return Ok({name, value, note: values.note ?? ''}); +} + +// No other secret of the vault has the name: checked as the secret is written, with the vault's +// other writes of secrets held off (@proxy/db/vault), so two at once can't both take it. +function nameFree(name: string): VaultEntriesCheck { + return (others) => { + const taken = others.some((other) => decryptValues(other.values).mapOr(false, (values) => values.name === name)); + if (taken) { + return Err(ApiErr.conflict(`This vault has a secret called ${name} already`)); + } + return Ok(undefined); + }; +} + +// What a write keeps, and what it checks of the collection's others as it writes: an entry with +// its type, one new needing something written in it; or a secret as it has to be, its name the +// vault's only one. +function written(target: RecordTarget, values: RecordValues, isNew: boolean): Result<{kept: RecordValues; check?: VaultEntriesCheck}, ApiError> { + if (isSecrets(target)) { + return requireSecret(values).map((kept) => ({kept, check: nameFree(kept.name ?? '')})); + } + if (isNew) { + return requireWritten(values).map(() => ({kept: withType(values)})); + } + return Ok({kept: withType(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 +137,14 @@ export const vaultConnector = { }), create: (target, values) => Do(async ($) => { - $(requireWritten(values)); - const row = $(await createVaultEntry(vaultCollection(target), $(encryptValues(withType(values))))); + const {kept, check} = $(written(target, values, true)); + const row = $(await createVaultEntry(vaultCollection(target), $(encryptValues(kept)), check)); return $(toRecord(row)); }), update: (target, recordId, values) => Do(async ($) => { - const row = $(await updateVaultEntry(vaultCollection(target), recordId, $(encryptValues(withType(values))))); + const {kept, check} = $(written(target, values, false)); + const row = $(await updateVaultEntry(vaultCollection(target), recordId, $(encryptValues(kept)), check)); 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.test.ts b/packages/db/src/vault.test.ts new file mode 100644 index 00000000..aee50501 --- /dev/null +++ b/packages/db/src/vault.test.ts @@ -0,0 +1,103 @@ +import {afterAll, beforeAll, describe, expect, test} from 'bun:test'; +import {Err, Ok, type Result} from 'ts-results-es'; + +import {ApiErr, type ApiError} from '@proxy/utils'; + +import {db} from '.'; +import { + createVaultEntry, + listVaultEntries, + updateVaultEntry, + type VaultCollection, + type VaultEntriesCheck, +} from './vault'; + +// A vault's checked writes, against the local database: run with it up (`bun run dev`) and the +// environment loaded, `bun --env-file=../../.env test src/vault.test.ts` from this package. +// Without DATABASE_URL, as `bun run test` runs, there is nothing to run against, and this is +// skipped. Everything made here is one organization's, deleted at the end. The values stand for +// encrypted ones: this package never reads them, only a check does. +const databaseUrl = process.env.DATABASE_URL; + +function unwrap(result: Result): T { + if (result.isErr()) { + throw new Error(JSON.stringify(result.error)); + } + return result.value; +} + +// No other row holds the value, as the api checks a secret's name. +function valueFree(value: string): VaultEntriesCheck { + return (rows) => { + if (rows.some((row) => row.values === value)) { + return Err(ApiErr.conflict(`${value} is taken`)); + } + return Ok(undefined); + }; +} + +describe.skipIf(!databaseUrl)('vault, against the database', () => { + const stamp = `${Date.now()}-${process.pid}`; + let userId = ''; + let orgId = ''; + let collection: VaultCollection = {connectionId: '', collectionId: 'secrets'}; + + beforeAll(async () => { + const user = await db.user.create({ + data: {email: `vault-test-${stamp}@example.test`, name: 'Dana'}, + }); + userId = user.id; + const org = await db.organization.create({ + data: {name: 'Vault test', slug: `vault-test-${stamp}`, ownerUserId: userId}, + }); + orgId = org.id; + const connection = await db.connection.create({ + data: {orgId, integrationId: 'vault', ownerUserId: userId, account: 'Vault test'}, + }); + collection = {connectionId: connection.id, collectionId: 'secrets'}; + }); + + afterAll(async () => { + if (orgId !== '') { + await db.organization.delete({where: {id: orgId}}); + } + if (userId !== '') { + await db.user.delete({where: {id: userId}}); + } + }); + + test('checked writes at once are checked one after the other, so only one takes a value', async () => { + const results = await Promise.all( + Array.from({length: 5}, () => createVaultEntry(collection, 'API_KEY', valueFree('API_KEY'))), + ); + + expect(results.filter((result) => result.isOk())).toHaveLength(1); + expect( + results.filter((result) => result.isErr()).map((result) => result.unwrapErr().kind), + ).toEqual(['conflict', 'conflict', 'conflict', 'conflict']); + expect(unwrap(await listVaultEntries(collection))).toHaveLength(1); + }); + + test('an update is checked against the others alone, and a refused one changes nothing', async () => { + const own = unwrap(await createVaultEntry(collection, 'OWN_KEY', valueFree('OWN_KEY'))); + + expect( + unwrap(await updateVaultEntry(collection, own.id, 'OWN_KEY', valueFree('OWN_KEY'))).id, + ).toBe(own.id); + expect( + (await updateVaultEntry(collection, own.id, 'API_KEY', valueFree('API_KEY'))).unwrapErr() + .kind, + ).toBe('conflict'); + expect( + unwrap(await listVaultEntries(collection)) + .map((row) => row.values) + .sort(), + ).toEqual(['API_KEY', 'OWN_KEY']); + }); + + test('an update of an entry not in the collection is not found', async () => { + const result = await updateVaultEntry(collection, 'missing', 'X', valueFree('X')); + + expect(result.unwrapErr().kind).toBe('not_found'); + }); +}); diff --git a/packages/db/src/vault.ts b/packages/db/src/vault.ts index e9aa4a2f..65a638ba 100644 --- a/packages/db/src/vault.ts +++ b/packages/db/src/vault.ts @@ -1,6 +1,7 @@ +import type {Prisma} from '@prisma/client'; import {Err, type Result} from 'ts-results-es'; -import {ApiErr, type ApiError, Do, requirePresent, wrapDb} from '@proxy/utils'; +import {ApiErr, type ApiError, Do, wrapDb} from '@proxy/utils'; import {db} from '.'; @@ -33,12 +34,46 @@ export async function getVaultEntry( ); } +/** + * What a write checks of the collection's entries as they are when it writes: the others' rows, + * read with the collection's other checked writes held off until this one is done, so two at once + * never both pass. An error stops the write. + */ +export type VaultEntriesCheck = (rows: VaultEntryRow[]) => Result; + +type Tx = Prisma.TransactionClient; + +// Every checked write of the collection, one after the other: a lock on a key made of the +// collection, held until the transaction ends, as the collection has no row of its own to take. +async function checkEntries( + tx: Tx, + collection: VaultCollection, + check: VaultEntriesCheck, + recordId: string | null, +): Promise { + await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${`vault:${collection.connectionId}:${collection.collectionId}`}::text, 0))`; + const rows = await tx.vaultEntry.findMany({ + where: {...collection, ...(recordId === null ? {} : {id: {not: recordId}})}, + select: vaultEntrySelect, + }); + const checked = check(rows); + if (checked.isErr()) { + throw checked.error; + } +} + export async function createVaultEntry( collection: VaultCollection, values: string, + check?: VaultEntriesCheck, ): Promise> { return wrapDb(() => - db.vaultEntry.create({data: {...collection, values}, select: vaultEntrySelect}), + db.$transaction(async (tx) => { + if (check) { + await checkEntries(tx, collection, check, null); + } + return tx.vaultEntry.create({data: {...collection, values}, select: vaultEntrySelect}); + }), ); } @@ -47,20 +82,30 @@ export async function updateVaultEntry( collection: VaultCollection, recordId: string, values: string, + check?: VaultEntriesCheck, ): Promise> { - return Do(async ($) => { - const {count} = $( - await wrapDb(() => - db.vaultEntry.updateMany({where: {...collection, id: recordId}, data: {values}}), - ), - ); - if (count === 0) { - return $(Err(ApiErr.notFound('record', recordId))); - } - - const row = $(await getVaultEntry(collection, recordId)); - return $(requirePresent(row, ApiErr.notFound('record', recordId))); - }); + return wrapDb(() => + db.$transaction(async (tx) => { + if (check) { + await checkEntries(tx, collection, check, recordId); + } + const {count} = await tx.vaultEntry.updateMany({ + where: {...collection, id: recordId}, + data: {values}, + }); + if (count === 0) { + throw ApiErr.notFound('record', recordId); + } + const row = await tx.vaultEntry.findFirst({ + where: {...collection, id: recordId}, + select: vaultEntrySelect, + }); + if (!row) { + throw ApiErr.notFound('record', recordId); + } + return row; + }), + ); } /** Fails with not_found when the entry isn't in the collection. */ @@ -78,14 +123,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..594a6e14 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. Where any command prints a secret’s value, it 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/file-browser.tsx b/packages/web/src/components/file-browser.tsx index 53533e3a..58e345c8 100644 --- a/packages/web/src/components/file-browser.tsx +++ b/packages/web/src/components/file-browser.tsx @@ -24,6 +24,7 @@ import { UploadIcon, } from 'lucide-react'; import {Fragment, useEffect, useRef, useState, type DragEvent} from 'react'; +import {createPortal} from 'react-dom'; import {Link, useNavigate} from 'react-router'; import { createFolder, @@ -551,6 +552,8 @@ type Props = { place: DrivePlace; list: FileList | null; shown: FileDetail | null; + // Where its search and buttons go, on the page's row of tabs (page-tabs.tsx). + toolbar: HTMLElement | null; }; // The Files part of a drive's page, the first of its connection's tabs: the folder the person is @@ -559,7 +562,7 @@ type Props = { // dropping files on the list, and a new folder. A file opens over its folder with its versions, // and a file or a folder is renamed, moved into another folder, or put in the trash from its // row's menu. The trash is a list of its own, each thing in it taken out again. -export function FileBrowser({connectionId, place, list, shown}: Props) { +export function FileBrowser({connectionId, place, list, shown, toolbar}: Props) { const org = useOrgSlug(); const navigate = useNavigate(); const reload = useReload(); @@ -601,10 +604,16 @@ export function FileBrowser({connectionId, place, list, shown}: Props) { return (
-
- - {!trash && list !== null && ( - + {(trash || (list?.trail.length ?? 0) > 0) && ( +
+ +
+ )} + {toolbar !== null && + !trash && + list !== null && + createPortal( + @@ -619,9 +628,9 @@ export function FileBrowser({connectionId, place, list, shown}: Props) { > {uploading > 0 ? : } - +
, + toolbar, )} -
`, the first part's being the page's), drawn as the -// lists' own toggles are, the one shown filled in and the others their labels alone. +// lists' own toggles are, the one shown filled in and the others their labels alone. With +// `toolbar`, the row has room on its right for the shown part's own buttons, which it puts there +// (a portal into the element given back), as the Files put their search and upload. export function PageTabs({ tabs, chosen, label, + toolbar, }: { tabs: Array>; chosen: T | null; // What the tabs are of, for a screen reader: "Connection". label: string; + toolbar?: (element: HTMLElement | null) => void; +}) { + if (!toolbar) { + return ; + } + return ( +
+ +
+
+ ); +} + +function Tabs({ + tabs, + chosen, + label, +}: { + tabs: Array>; + chosen: T | null; + label: string; }) { return (