From 0dd726f6d15459c5b2d67da0161394fc22cdb79e Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Mon, 30 Nov 2026 01:05:03 -0800 Subject: [PATCH] feat: lend vault secrets to agents with per-request approval - @decryption/agent: local socket broker (0600 unix socket / named pipe), strict newline-JSON protocol, in-memory time-limited grants - dcrypt agent status|run: injects approved secrets into one command's environment; never prints them - dcrypt-vault: agent_access table, agent_reveal_field (refuses items not shared with agents, audits the caller), actor column on audit_log; existing vaults are upgraded on open - desktop: Agents screen (on/off, shared items, active grants, activity), per-item "Agents may use this" switch, native approval prompt (deny / once / 1 hour) with Touch ID; grants cleared on lock --- README.md | 10 +- apps/desktop/__tests__/agent-prompt.test.ts | 45 +++ apps/desktop/package.json | 1 + apps/desktop/src/main/agent-service.ts | 200 +++++++++++++ apps/desktop/src/main/index.ts | 18 +- apps/desktop/src/main/ipc.ts | 26 +- apps/desktop/src/main/vault-service.ts | 13 + apps/desktop/src/preload/index.ts | 17 ++ apps/desktop/src/renderer/src/App.tsx | 6 +- .../renderer/src/components/ItemDetail.tsx | 27 ++ apps/desktop/src/renderer/src/lib/ipc.ts | 1 + .../src/renderer/src/screens/AgentsScreen.tsx | 265 ++++++++++++++++++ apps/desktop/src/shared/agent-prompt.ts | 43 +++ apps/desktop/src/shared/api.ts | 41 +++ packages/agent/README.md | 88 ++++++ packages/agent/__tests__/broker.test.ts | 186 ++++++++++++ packages/agent/__tests__/protocol.test.ts | 53 ++++ packages/agent/__tests__/transport.test.ts | 88 ++++++ packages/agent/jest.config.js | 18 ++ packages/agent/package.json | 44 +++ packages/agent/src/broker.ts | 215 ++++++++++++++ packages/agent/src/grants.ts | 96 +++++++ packages/agent/src/index.ts | 5 + packages/agent/src/protocol.ts | 152 ++++++++++ packages/agent/src/socket-path.ts | 14 + packages/agent/src/transport.ts | 180 ++++++++++++ packages/agent/tsconfig.esm.json | 9 + packages/agent/tsconfig.json | 16 ++ packages/cli/README.md | 26 ++ packages/cli/__tests__/agent.test.ts | 156 +++++++++++ packages/cli/package.json | 1 + packages/cli/src/commands.ts | 3 + packages/cli/src/commands/agent.ts | 146 ++++++++++ packages/cli/src/index.ts | 2 + packages/vault/__tests__/vault.test.ts | 52 ++++ packages/vault/src/types.ts | 2 + packages/vault/src/vault.ts | 81 +++++- .../dcrypt-vault/__tests__/basic.test.ts | 53 ++++ .../schemas/dcrypt_vault/agent_access.sql | 70 +++++ pgpm-modules/dcrypt-vault/pgpm.plan | 1 + .../schemas/dcrypt_vault/agent_access.sql | 9 + .../schemas/dcrypt_vault/agent_access.sql | 9 + pnpm-lock.yaml | 19 +- 43 files changed, 2496 insertions(+), 11 deletions(-) create mode 100644 apps/desktop/__tests__/agent-prompt.test.ts create mode 100644 apps/desktop/src/main/agent-service.ts create mode 100644 apps/desktop/src/renderer/src/screens/AgentsScreen.tsx create mode 100644 apps/desktop/src/shared/agent-prompt.ts create mode 100644 packages/agent/README.md create mode 100644 packages/agent/__tests__/broker.test.ts create mode 100644 packages/agent/__tests__/protocol.test.ts create mode 100644 packages/agent/__tests__/transport.test.ts create mode 100644 packages/agent/jest.config.js create mode 100644 packages/agent/package.json create mode 100644 packages/agent/src/broker.ts create mode 100644 packages/agent/src/grants.ts create mode 100644 packages/agent/src/index.ts create mode 100644 packages/agent/src/protocol.ts create mode 100644 packages/agent/src/socket-path.ts create mode 100644 packages/agent/src/transport.ts create mode 100644 packages/agent/tsconfig.esm.json create mode 100644 packages/agent/tsconfig.json create mode 100644 packages/cli/__tests__/agent.test.ts create mode 100644 packages/cli/src/commands/agent.ts create mode 100644 pgpm-modules/dcrypt-vault/deploy/schemas/dcrypt_vault/agent_access.sql create mode 100644 pgpm-modules/dcrypt-vault/revert/schemas/dcrypt_vault/agent_access.sql create mode 100644 pgpm-modules/dcrypt-vault/verify/schemas/dcrypt_vault/agent_access.sql diff --git a/README.md b/README.md index 6a76896..6ec95f7 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,7 @@ libraries, install the scoped packages below, e.g. `npm install @decryption/core | **@decryption/keys** | [![npm](https://img.shields.io/npm/v/@decryption/keys.svg)](https://www.npmjs.com/package/@decryption/keys) | [GitHub](./packages/keys) | X25519 identities, recipient strings, files encrypted to recipients | | **@decryption/secrets** | [![npm](https://img.shields.io/npm/v/@decryption/secrets.svg)](https://www.npmjs.com/package/@decryption/secrets) | [GitHub](./packages/secrets) | Team secrets file format, rekeying and `.env` export | | **@decryption/accounts** | [![npm](https://img.shields.io/npm/v/@decryption/accounts.svg)](https://www.npmjs.com/package/@decryption/accounts) | [GitHub](./packages/accounts) | Constructive accounts and API keys, held in the local vault | +| **@decryption/agent** | [![npm](https://img.shields.io/npm/v/@decryption/agent.svg)](https://www.npmjs.com/package/@decryption/agent) | [GitHub](./packages/agent) | Lend vault secrets to local agents for one command, approved in the desktop app | | **@decryption/webauthn** | [![npm](https://img.shields.io/npm/v/@decryption/webauthn.svg)](https://www.npmjs.com/package/@decryption/webauthn) | [GitHub](./packages/webauthn) | A software WebAuthn authenticator: passkeys kept in the vault | | **@decryption/cli** | [![npm](https://img.shields.io/npm/v/@decryption/cli.svg)](https://www.npmjs.com/package/@decryption/cli) | [GitHub](./packages/cli) | The `dcrypt` command-line interface | | **decryption** | [![npm](https://img.shields.io/npm/v/decryption.svg)](https://www.npmjs.com/package/decryption) | [GitHub](./packages/decryption) | Short install name for the CLI: `npm install -g decryption` | @@ -81,6 +82,10 @@ dcrypt secrets run -- pnpm dev # inject secrets without writing a .env dcrypt account signin me@example.com --endpoint https://auth.example.com/graphql dcrypt account key create ci --expires-days 30 # secret lands in the vault, not a .env + +dcrypt agent run --secret GITHUB_TOKEN=GitHub -- gh pr list + # an agent borrows one secret for one command; + # you approve it in the desktop app ``` ## Security model @@ -99,6 +104,9 @@ dcrypt account key create ci --expires-days 30 # secret lands in the vault, no bundle changes nothing. A bundle does not authenticate its author; that is git's job. - Team secrets use X25519 per-recipient wrapping (age/sops-shaped), so adding or removing a teammate never requires resharing a passphrase. Shamir is reserved for break-glass recovery. +- Agents never get the master password. With agent access turned on in the desktop app, a local + socket (`~/.dcrypt/run/agent.sock`, this user only) lends opted-in items to one command at a time, + after you approve; locking the vault ends every grant. See [@decryption/agent](./packages/agent). - Private keys are never written to disk unencrypted. `dcrypt account` is the one command that uses the network: session tokens and API-key secrets it receives go straight into the encrypted vault. @@ -138,7 +146,7 @@ Three things follow from that table: - this implementation of the STREAM chunked payload. The construction is age's and it decrypts age's test vectors, but the code is ours; - X25519 recipient wrapping, identities and the keyring (`@decryption/keys`), team secrets files - (`@decryption/secrets`), Shamir sharing, the vault, accounts and the WebAuthn authenticator; + (`@decryption/secrets`), Shamir sharing, the vault, accounts, the WebAuthn authenticator and the agent socket (`@decryption/agent`); - encrypted workspaces: the tar writer and reader, the hash manifest, the extraction checks and the pre-commit guard; - the `dcrypt` CLI and the desktop app. diff --git a/apps/desktop/__tests__/agent-prompt.test.ts b/apps/desktop/__tests__/agent-prompt.test.ts new file mode 100644 index 0000000..b8a0751 --- /dev/null +++ b/apps/desktop/__tests__/agent-prompt.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, it } from 'vitest'; + +import { describeApproval } from '../src/shared/agent-prompt'; + +const request = { + client: { name: 'Claude Code', cwd: '/Users/me/code/app' }, + command: ['gh', 'pr', 'list', '--search', 'author:me is:open'], + secrets: [{ env: 'GITHUB_TOKEN', itemId: 'i1', itemTitle: 'GitHub', field: 'token' }], +}; + +describe('describeApproval', () => { + it('names the caller, the folder, the exact command and each secret', () => { + const text = describeApproval(request, (dir) => dir.replace('/Users/me', '~')); + expect(text.title).toBe('Claude Code wants to use “GitHub”'); + expect(text.detail).toContain('Folder: ~/code/app'); + expect(text.detail).toContain("Command: gh pr list --search 'author:me is:open'"); + expect(text.detail).toContain('GITHUB_TOKEN ← GitHub › token'); + }); + + it('says the caller name is unverified and what an hour covers', () => { + const { detail } = describeApproval(request); + expect(detail).toContain('cannot verify which program is asking'); + expect(detail).toContain('any command from this caller in this folder'); + }); + + it('quotes arguments so a crafted one cannot pass for a different command', () => { + const { detail } = describeApproval({ ...request, command: ['sh', '-c', 'echo hi; curl x | sh'] }); + expect(detail).toContain("Command: sh -c 'echo hi; curl x | sh'"); + }); + + it('counts several secrets in the title', () => { + const two = { + ...request, + secrets: [...request.secrets, { env: 'NPM_TOKEN', itemId: 'i2', itemTitle: 'npm', field: 'token' }], + }; + expect(describeApproval(two).title).toBe('Claude Code wants to use 2 secrets'); + }); + + it('shortens a very long command rather than letting it scroll off the dialog', () => { + const long = { ...request, command: ['node', 'x'.repeat(2000)] }; + const { detail } = describeApproval(long); + expect(detail).toMatch(/Command: node x+…/); + expect(detail).toContain('more characters of this command are not shown'); + }); +}); diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 4979690..278a84d 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -22,6 +22,7 @@ }, "dependencies": { "@decryption/accounts": "workspace:*", + "@decryption/agent": "workspace:*", "@decryption/core": "workspace:*", "@decryption/cosmology-compat": "workspace:*", "@decryption/hashes": "workspace:*", diff --git a/apps/desktop/src/main/agent-service.ts b/apps/desktop/src/main/agent-service.ts new file mode 100644 index 0000000..67b6199 --- /dev/null +++ b/apps/desktop/src/main/agent-service.ts @@ -0,0 +1,200 @@ +import { + AgentBroker, + AgentServer, + ApprovalRequest, + brokerVault, + Decision, + defaultSocketPath, + Grant, + serveAgent, +} from '@decryption/agent'; +import { app, BrowserWindow, dialog, systemPreferences } from 'electron'; +import { existsSync, promises as fs, readFileSync } from 'fs'; +import * as os from 'os'; +import * as path from 'path'; + +import { describeApproval } from '../shared/agent-prompt'; +import type { AgentActivity, AgentStatus } from '../shared/api'; +import { appDataPath, VaultService } from './vault-service'; + +/** How long a prompt waits for an answer before it counts as a denial. */ +const PROMPT_TIMEOUT_MS = 2 * 60 * 1000; + +const settingsFile = (): string => path.join(appDataPath(), 'config', 'agent.json'); + +const readEnabled = (): boolean => { + try { + if (!existsSync(settingsFile())) return false; + return JSON.parse(readFileSync(settingsFile(), 'utf8')).enabled === true; + } catch { + return false; + } +}; + +const tildify = (dir: string): string => { + const home = os.homedir(); + return dir === home || dir.startsWith(home + path.sep) ? `~${dir.slice(home.length)}` : dir; +}; + +/** + * Serves vault secrets to local agents through `@decryption/agent`, while this + * app holds the unlocked vault. Off until the person turns it on; every + * request is approved here; locking the vault clears every grant. + */ +export class AgentService { + private server: AgentServer | null = null; + private error: string | null = null; + private readonly broker: AgentBroker; + private enabled = readEnabled(); + + constructor( + private readonly vaults: VaultService, + private readonly window: () => BrowserWindow | null, + private readonly changed: () => void + ) { + const vault = brokerVault(() => { + try { + return vaults.current(); + } catch { + return null; + } + }); + this.broker = new AgentBroker({ + vault: { + ...vault, + // each release writes an audit row: persist it like any other edit + reveal: async (itemId, field, actor) => { + const value = await vault.reveal(itemId, field, actor); + vaults.scheduleSave(); + this.changed(); + return value; + }, + }, + approve: (request) => this.approve(request), + }); + this.broker.grants.onChange(() => this.changed()); + vaults.onLock(() => this.broker.grants.clear()); + } + + async start(): Promise { + if (this.enabled) await this.listen(); + } + + async stop(): Promise { + this.broker.grants.clear(); + const server = this.server; + this.server = null; + await server?.close(); + } + + status(): AgentStatus { + return { + enabled: this.enabled, + serving: this.server !== null, + socketPath: defaultSocketPath(), + error: this.error, + unlocked: this.vaults.status().unlocked, + }; + } + + async setEnabled(enabled: boolean): Promise { + this.enabled = enabled; + await fs.mkdir(path.dirname(settingsFile()), { recursive: true }); + await fs.writeFile(settingsFile(), JSON.stringify({ enabled }), { mode: 0o600 }); + if (enabled) await this.listen(); + else await this.stop(); + this.changed(); + return this.status(); + } + + grants(): Grant[] { + return this.broker.grants.list(); + } + + revoke(id: string): void { + this.broker.grants.revoke(id); + } + + revokeAll(): void { + this.broker.grants.clear(); + } + + /** An item stopped being shared: its grants go with it. */ + forgetItem(itemId: string): void { + this.broker.grants.revokeItem(itemId); + } + + /** Agent-related audit entries, newest first, with item titles attached. */ + async activity(limit = 100): Promise { + const vault = this.vaults.current(); + const [log, items, trashed] = await Promise.all([ + vault.auditLog(), + vault.listItems(), + vault.listItems({ trashed: true }), + ]); + const titles = new Map([...items, ...trashed].map((item) => [item.id, item.title])); + return log + .filter((entry) => entry.action.startsWith('agent_')) + .slice(0, limit) + .map((entry) => ({ ...entry, itemTitle: entry.itemId ? (titles.get(entry.itemId) ?? null) : null })); + } + + private async listen(): Promise { + if (this.server) return; + try { + this.server = await serveAgent({ + socketPath: defaultSocketPath(), + handle: (request) => this.broker.handle(request), + }); + this.error = null; + } catch (error) { + this.error = error instanceof Error ? error.message : String(error); + } + } + + /** + * Ask in a native dialog, in front of everything. Touch ID, where there is + * one, has to confirm an "allow": a click can be synthesized by any program + * that drives the screen — an agent with computer use included — a finger + * cannot. + */ + private async approve(request: ApprovalRequest): Promise { + const window = this.window(); + if (!window || window.isDestroyed()) return 'deny'; + if (window.isMinimized()) window.restore(); + window.show(); + app.focus({ steal: true }); + + const text = describeApproval(request, tildify); + const abort = new AbortController(); + const timer = setTimeout(() => abort.abort(), PROMPT_TIMEOUT_MS); + let response: number; + try { + ({ response } = await dialog.showMessageBox(window, { + type: 'warning', + title: 'Agent request', + message: text.title, + detail: text.detail, + buttons: ['Deny', 'Allow once', 'Allow for 1 hour'], + defaultId: 0, + cancelId: 0, + noLink: true, + signal: abort.signal, + })); + } catch { + return 'deny'; + } finally { + clearTimeout(timer); + } + if (abort.signal.aborted || response === 0) return 'deny'; + + if (process.platform === 'darwin' && systemPreferences.canPromptTouchID()) { + try { + await systemPreferences.promptTouchID(`let ${request.client.name} use ${text.what}`); + } catch { + return 'deny'; + } + } + return response === 2 ? 'grant' : 'once'; + } +} diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts index 1a854b5..33d1c3e 100644 --- a/apps/desktop/src/main/index.ts +++ b/apps/desktop/src/main/index.ts @@ -2,6 +2,7 @@ import { app, BrowserWindow, ipcMain, nativeImage, nativeTheme, powerMonitor, se import * as path from 'path'; import { CHANNELS } from '../shared/api'; +import { AgentService } from './agent-service'; import { registerIpc } from './ipc'; import { buildMenu } from './menu'; import { VaultService } from './vault-service'; @@ -14,6 +15,18 @@ const APP_ICON = nativeImage.createFromPath( const service = new VaultService(); +let mainWindow: BrowserWindow | null = null; + +const agents = new AgentService( + service, + () => mainWindow, + () => { + if (mainWindow && !mainWindow.isDestroyed()) { + mainWindow.webContents.send(CHANNELS.agentsChangedEvent); + } + } +); + /** Minutes of user idle time before the vault locks itself. */ const AUTO_LOCK_MINUTES = 10; @@ -74,7 +87,6 @@ const createWindow = (): BrowserWindow => { return window; }; -let mainWindow: BrowserWindow | null = null; let idleTimer: NodeJS.Timeout | null = null; const watchIdle = (): void => { @@ -108,7 +120,8 @@ app.whenReady().then(() => { } }); - registerIpc(service); + registerIpc(service, agents); + void agents.start(); buildMenu(service, () => mainWindow, () => { if (mainWindow && !mainWindow.isDestroyed()) { mainWindow.webContents.send(CHANNELS.lockedEvent); @@ -135,5 +148,6 @@ app.on('window-all-closed', () => { app.on('before-quit', () => { if (idleTimer) clearInterval(idleTimer); + void agents.stop(); void service.lock(); }); diff --git a/apps/desktop/src/main/ipc.ts b/apps/desktop/src/main/ipc.ts index 5b03037..24fd20c 100644 --- a/apps/desktop/src/main/ipc.ts +++ b/apps/desktop/src/main/ipc.ts @@ -17,6 +17,7 @@ import { StepUpProof, } from '../shared/api'; import { parseOtpauthUri } from '../shared/otpauth'; +import type { AgentService } from './agent-service'; import { backupVault, restoreVault } from './backup'; import { biometricStatus, enrol, forget as forgetUnlockKey, unlockSecret } from './biometric'; import { lookupBrandIcons } from './brand-icons'; @@ -29,7 +30,7 @@ const WORD_COUNTS: WordCount[] = [12, 15, 18, 21, 24]; * Registers every IPC handler. Handlers validate their inputs; nothing here * trusts the renderer. */ -export const registerIpc = (service: VaultService): void => { +export const registerIpc = (service: VaultService, agents: AgentService): void => { const handle = ( channel: string, handler: (...args: never[]) => unknown @@ -308,6 +309,29 @@ export const registerIpc = (service: VaultService): void => { // ─── audit ─── handle(CHANNELS.auditLog, (itemId?: string) => service.current().auditLog(itemId)); + // ─── agents ─── + // The renderer manages sharing and grants; it can never answer a request or + // read what was released. Approval happens in a native dialog in main. + handle(CHANNELS.agentsStatus, () => agents.status()); + handle(CHANNELS.agentsSetEnabled, (enabled: boolean) => agents.setEnabled(enabled === true)); + handle(CHANNELS.agentsShared, async () => { + const vault = service.current(); + const shared = new Set(await vault.agentAccessItemIds()); + return (await vault.listItems()).filter((item) => shared.has(item.id)); + }); + handle(CHANNELS.agentsIsShared, async (itemId: string) => + (await service.current().agentAccessItemIds()).includes(assertString(itemId)) + ); + handle(CHANNELS.agentsSetShared, async (itemId: string, shared: boolean) => { + await service.current().setAgentAccess(assertString(itemId), shared === true); + if (shared !== true) agents.forgetItem(itemId); + service.scheduleSave(); + }); + handle(CHANNELS.agentsGrants, () => agents.grants()); + handle(CHANNELS.agentsRevoke, (grantId: string) => agents.revoke(assertString(grantId))); + handle(CHANNELS.agentsRevokeAll, () => agents.revokeAll()); + handle(CHANNELS.agentsActivity, () => agents.activity()); + // ─── crypto workbench (stateless, works while locked) ─── handle(CHANNELS.wbCreateWallet, (networks: string[], words: number) => { const wordCount = WORD_COUNTS.includes(words as WordCount) ? (words as WordCount) : 24; diff --git a/apps/desktop/src/main/vault-service.ts b/apps/desktop/src/main/vault-service.ts index 37f7804..863da99 100644 --- a/apps/desktop/src/main/vault-service.ts +++ b/apps/desktop/src/main/vault-service.ts @@ -41,6 +41,17 @@ export class VaultService { private saveTimer: NodeJS.Timeout | null = null; /** In-flight lock, so an unlock racing a pending flush waits for it. */ private locking: Promise | null = null; + private lockListeners = new Set<() => void>(); + + /** Called whenever the vault closes, however it closed. */ + onLock(listener: () => void): () => void { + this.lockListeners.add(listener); + return () => this.lockListeners.delete(listener); + } + + private notifyLocked(): void { + for (const listener of this.lockListeners) listener(); + } status(): VaultStatus { const file = vaultFilePath(); @@ -70,6 +81,7 @@ export class VaultService { if (!this.vault) return; const vault = this.vault; this.vault = null; + this.notifyLocked(); this.locking = vault.lock().finally(() => { this.locking = null; }); @@ -106,6 +118,7 @@ export class VaultService { // drop the database without persisting it: the file is about to go const vault = this.vault; this.vault = null; + this.notifyLocked(); await this.locking; if (vault) await vault.discard(); await fs.rm(appDataPath(), { recursive: true, force: true }); diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.ts index ce1ec12..ecf7383 100644 --- a/apps/desktop/src/preload/index.ts +++ b/apps/desktop/src/preload/index.ts @@ -7,6 +7,7 @@ const invoke = (channel: string, ...args: unknown[]): Promise => const api: DcryptApi & { onLocked(listener: () => void): () => void; + onAgentsChanged(listener: () => void): () => void; onSystemThemeChange(listener: (dark: boolean) => void): () => void; } = { vault: { @@ -77,6 +78,17 @@ const api: DcryptApi & { audit: { log: (itemId) => invoke(CHANNELS.auditLog, itemId), }, + agents: { + status: () => invoke(CHANNELS.agentsStatus), + setEnabled: (enabled) => invoke(CHANNELS.agentsSetEnabled, enabled), + shared: () => invoke(CHANNELS.agentsShared), + isShared: (itemId) => invoke(CHANNELS.agentsIsShared, itemId), + setShared: (itemId, shared) => invoke(CHANNELS.agentsSetShared, itemId, shared), + grants: () => invoke(CHANNELS.agentsGrants), + revoke: (grantId) => invoke(CHANNELS.agentsRevoke, grantId), + revokeAll: () => invoke(CHANNELS.agentsRevokeAll), + activity: () => invoke(CHANNELS.agentsActivity), + }, workbench: { createWallet: (networks, words) => invoke(CHANNELS.wbCreateWallet, networks, words), deriveAccounts: (mnemonic, networks) => invoke(CHANNELS.wbDeriveAccounts, mnemonic, networks), @@ -112,6 +124,11 @@ const api: DcryptApi & { ipcRenderer.on(CHANNELS.themeSystemChanged, wrapped); return () => ipcRenderer.removeListener(CHANNELS.themeSystemChanged, wrapped); }, + onAgentsChanged: (listener) => { + const wrapped = () => listener(); + ipcRenderer.on(CHANNELS.agentsChangedEvent, wrapped); + return () => ipcRenderer.removeListener(CHANNELS.agentsChangedEvent, wrapped); + }, onLocked: (listener) => { const wrapped = () => listener(); ipcRenderer.on(CHANNELS.lockedEvent, wrapped); diff --git a/apps/desktop/src/renderer/src/App.tsx b/apps/desktop/src/renderer/src/App.tsx index e2e3f28..285632c 100644 --- a/apps/desktop/src/renderer/src/App.tsx +++ b/apps/desktop/src/renderer/src/App.tsx @@ -2,6 +2,7 @@ import { Button } from '@constructive-io/ui/button'; import { Separator } from '@constructive-io/ui/separator'; import { Toaster } from '@constructive-io/ui/sonner'; import { + Bot, KeyRound, Lock, Settings, @@ -16,13 +17,14 @@ import { DoorState, VaultDoors } from './components/VaultDoors'; import { dcrypt } from './lib/ipc'; import { ThemeProvider, useThemeMode } from './lib/theme-context'; import { AccountsScreen } from './screens/AccountsScreen'; +import { AgentsScreen } from './screens/AgentsScreen'; import { SettingsScreen } from './screens/SettingsScreen'; import { ToolsScreen } from './screens/ToolsScreen'; import { TotpScreen } from './screens/TotpScreen'; import { UnlockScreen } from './screens/UnlockScreen'; import { VaultScreen } from './screens/VaultScreen'; -type Tab = 'vault' | 'codes' | 'accounts' | 'tools' | 'settings'; +type Tab = 'vault' | 'codes' | 'accounts' | 'agents' | 'tools' | 'settings'; /** `opening`/`closing` are the door transitions; the vault is mounted for all but `locked`. */ type Phase = 'locked' | 'opening' | 'unlocked' | 'closing'; @@ -31,6 +33,7 @@ const NAV: { id: Tab; label: string; icon: typeof KeyRound }[] = [ { id: 'vault', label: 'Vault', icon: KeyRound }, { id: 'codes', label: 'Codes', icon: Timer }, { id: 'accounts', label: 'Accounts', icon: UserRound }, + { id: 'agents', label: 'Agents', icon: Bot }, { id: 'tools', label: 'Tools', icon: Wrench }, { id: 'settings', label: 'Settings', icon: Settings }, ]; @@ -114,6 +117,7 @@ const AppContent = () => { {tab === 'vault' && } {tab === 'codes' && } {tab === 'accounts' && } + {tab === 'agents' && } {tab === 'tools' && } {tab === 'settings' && ( setPhase('closing')} /> diff --git a/apps/desktop/src/renderer/src/components/ItemDetail.tsx b/apps/desktop/src/renderer/src/components/ItemDetail.tsx index db40069..0756f1b 100644 --- a/apps/desktop/src/renderer/src/components/ItemDetail.tsx +++ b/apps/desktop/src/renderer/src/components/ItemDetail.tsx @@ -13,6 +13,7 @@ import { Button } from '@constructive-io/ui/button'; import { Input } from '@constructive-io/ui/input'; import { Progress } from '@constructive-io/ui/progress'; import { Separator } from '@constructive-io/ui/separator'; +import { Switch } from '@constructive-io/ui/switch'; import { Check, Copy, Eye, EyeOff, Pencil, Plus, Star, Trash2, X } from 'lucide-react'; import { useCallback, useEffect, useState } from 'react'; import { toast } from 'sonner'; @@ -59,6 +60,7 @@ export const ItemDetail = ({ const [title, setTitle] = useState(null); const [removing, setRemoving] = useState(null); const icons = useBrandIcons([item.title]); + const [agentShared, setAgentShared] = useState(false); const refresh = useCallback(async () => { setRevealed({}); @@ -66,6 +68,7 @@ export const ItemDetail = ({ setLoaded({ itemId: item.id, fields: await dcrypt.fields.list(item.id) }); setUrls(await dcrypt.organize.urls(item.id)); setTags(await dcrypt.organize.tags(item.id)); + setAgentShared(await dcrypt.agents.isShared(item.id)); }, [item.id]); useEffect(() => { @@ -168,6 +171,16 @@ export const ItemDetail = ({ onChanged(); }; + const toggleAgentShared = async (shared: boolean) => { + await dcrypt.agents.setShared(item.id, shared); + setAgentShared(shared); + toast.success( + shared + ? `Agents may now ask for “${item.title}”. You still approve each request.` + : `Agents can no longer ask for “${item.title}”` + ); + }; + const trash = async () => { await dcrypt.items.trash(item.id); toast.success(`Moved "${item.title}" to trash`); @@ -234,6 +247,20 @@ export const ItemDetail = ({ + + {totp && ( diff --git a/apps/desktop/src/renderer/src/lib/ipc.ts b/apps/desktop/src/renderer/src/lib/ipc.ts index 7396da2..d2b22c1 100644 --- a/apps/desktop/src/renderer/src/lib/ipc.ts +++ b/apps/desktop/src/renderer/src/lib/ipc.ts @@ -2,6 +2,7 @@ import type { DcryptApi } from '../../../shared/api'; export type RendererApi = DcryptApi & { onLocked(listener: () => void): () => void; + onAgentsChanged(listener: () => void): () => void; onSystemThemeChange(listener: (dark: boolean) => void): () => void; }; diff --git a/apps/desktop/src/renderer/src/screens/AgentsScreen.tsx b/apps/desktop/src/renderer/src/screens/AgentsScreen.tsx new file mode 100644 index 0000000..0c7c814 --- /dev/null +++ b/apps/desktop/src/renderer/src/screens/AgentsScreen.tsx @@ -0,0 +1,265 @@ +import { Badge } from '@constructive-io/ui/badge'; +import { Button } from '@constructive-io/ui/button'; +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from '@constructive-io/ui/card'; +import { Switch } from '@constructive-io/ui/switch'; +import { Copy } from 'lucide-react'; +import { useCallback, useEffect, useState } from 'react'; +import { toast } from 'sonner'; + +import type { AgentActivity, AgentStatus, Grant, VaultItem } from '../../../shared/api'; +import { dcrypt } from '../lib/ipc'; + +const EXAMPLE = 'dcrypt agent run --secret GITHUB_TOKEN=GitHub -- gh pr list'; + +const minutesLeft = (expiresAt: number): string => { + const minutes = Math.max(0, Math.ceil((expiresAt - Date.now()) / 60_000)); + return minutes <= 1 ? 'under a minute left' : `${minutes} min left`; +}; + +const when = (iso: string): string => { + const date = new Date(iso); + const sameDay = date.toDateString() === new Date().toDateString(); + return sameDay + ? date.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }) + : date.toLocaleString([], { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }); +}; + +const copyText = (text: string): void => { + void dcrypt.clipboard.copy(text).then(() => toast.success('Copied')); +}; + +export const AgentsScreen = () => { + const [status, setStatus] = useState(null); + const [shared, setShared] = useState([]); + const [grants, setGrants] = useState([]); + const [activity, setActivity] = useState([]); + const [busy, setBusy] = useState(false); + const [, setTick] = useState(0); + + const refresh = useCallback(async () => { + try { + const [s, items, g, a] = await Promise.all([ + dcrypt.agents.status(), + dcrypt.agents.shared(), + dcrypt.agents.grants(), + dcrypt.agents.activity(), + ]); + setStatus(s); + setShared(items); + setGrants(g); + setActivity(a); + } catch (err) { + toast.error(err instanceof Error ? err.message : String(err)); + } + }, []); + + useEffect(() => { + void refresh(); + const stop = dcrypt.onAgentsChanged(() => void refresh()); + // keep the countdowns honest, and drop grants as they expire + const timer = setInterval(() => { + setTick((n) => n + 1); + void dcrypt.agents.grants().then(setGrants); + }, 30_000); + return () => { + stop(); + clearInterval(timer); + }; + }, [refresh]); + + const toggle = async (enabled: boolean) => { + setBusy(true); + try { + const next = await dcrypt.agents.setEnabled(enabled); + setStatus(next); + if (next.error) toast.error(next.error); + } catch (err) { + toast.error(err instanceof Error ? err.message : String(err)); + } finally { + setBusy(false); + } + }; + + const unshare = async (item: VaultItem) => { + await dcrypt.agents.setShared(item.id, false); + toast.success(`Agents can no longer ask for “${item.title}”`); + await refresh(); + }; + + const stateLine = !status + ? '' + : !status.enabled + ? 'Off. No program can ask for anything.' + : status.error + ? `Could not start: ${status.error}` + : status.serving + ? 'On. Agents can ask; you approve each request.' + : 'Starting…'; + + return ( +
+

Agents

+ + + +
+
+ Agent access + + Let coding agents and scripts on this computer borrow a secret for one command, + without ever seeing your master password. You choose which items they may ask for, + and you approve every request here. + +
+ void toggle(checked)} + aria-label="Agent access" + /> +
+
+ + {stateLine} +

+ Locking the vault, or quitting dcrypt, cuts every agent off at once. +

+
+
+ + + + How an agent asks + + The secret goes into that command’s environment only. It is never printed, and never + written to disk. + + + +
+ {EXAMPLE} + +
+

+ Use Title#field when an item has several secret fields. + Read the command in each request before you allow it: a command that prints its + environment would show the value to the agent. +

+
+
+ + + + Shared items + + The only items an agent can ask for. Everything else stays invisible to them — they + cannot even tell it exists. + + + + {shared.length === 0 ? ( +

+ Nothing is shared. Open an item in the Vault and turn on “Agents may use this”. +

+ ) : ( + shared.map((item) => ( +
+
+ {item.title} + {item.kind.replace('_', ' ')} +
+ +
+ )) + )} +
+
+ + + +
+
+ Allowed for now + + Requests you allowed for an hour. Each covers one caller, in one folder, for one + secret. + +
+ {grants.length > 0 && ( + + )} +
+
+ + {grants.length === 0 ? ( +

Nothing. Every request will ask you first.

+ ) : ( + grants.map((grant) => ( +
+
+ + {grant.client} · {grant.itemTitle} › {grant.field} + + {grant.cwd} +
+
+ {minutesLeft(grant.expiresAt)} + +
+
+ )) + )} +
+
+ + + + Activity + + Every secret an agent was given, and every change to what is shared. Callers name + themselves, so treat the name as a label rather than proof. + + + + {activity.length === 0 ? ( +

No agent activity yet.

+ ) : ( + activity.map((entry) => ( +
+ {when(entry.occurredAt)} + + {entry.action === 'agent_reveal' ? ( + <> + {entry.actor ?? 'An agent'} used{' '} + {entry.itemTitle ?? 'a deleted item'} + {entry.fieldName ? ` › ${entry.fieldName}` : ''} + + ) : ( + <> + You {entry.action === 'agent_share' ? 'shared' : 'stopped sharing'}{' '} + {entry.itemTitle ?? 'a deleted item'} with agents + + )} + +
+ )) + )} +
+
+
+ ); +}; diff --git a/apps/desktop/src/shared/agent-prompt.ts b/apps/desktop/src/shared/agent-prompt.ts new file mode 100644 index 0000000..6782f38 --- /dev/null +++ b/apps/desktop/src/shared/agent-prompt.ts @@ -0,0 +1,43 @@ +import type { ApprovalRequest } from '@decryption/agent'; + +/** Quote one argument the way a shell would need it, for display only. */ +const shellQuote = (part: string): string => + /^[A-Za-z0-9_./:=@%+-]+$/.test(part) ? part : `'${part.replace(/'/g, `'\\''`)}'`; + +const MAX_COMMAND = 400; + +/** + * The words of an approval prompt. Kept free of Electron so it can be tested: + * what the person reads here is the whole basis of their decision. + */ +export const describeApproval = ( + request: ApprovalRequest, + shortenPath: (dir: string) => string = (dir) => dir +): { title: string; detail: string; what: string } => { + const count = request.secrets.length; + const what = count === 1 ? `“${request.secrets[0].itemTitle}”` : `${count} secrets`; + const full = request.command.map(shellQuote).join(' '); + const hidden = Math.max(0, full.length - MAX_COMMAND); + const command = hidden ? `${full.slice(0, MAX_COMMAND)}…` : full; + const lines = request.secrets.map( + (secret) => ` ${secret.env} ← ${secret.itemTitle} › ${secret.field}` + ); + return { + what, + title: `${request.client.name} wants to use ${what}`, + detail: [ + `Folder: ${shortenPath(request.client.cwd)}`, + `Command: ${command}`, + ...(hidden + ? [`⚠ ${hidden} more characters of this command are not shown. If you cannot see all of it, deny.`] + : []), + '', + ...lines, + '', + 'The values go into this command’s environment only. A command that prints its environment can still show them.', + '', + `The name “${request.client.name}” is what the caller says it is: dcrypt cannot verify which program is asking.`, + '“Allow for 1 hour” covers any command from this caller in this folder, until the vault locks.', + ].join('\n'), + }; +}; diff --git a/apps/desktop/src/shared/api.ts b/apps/desktop/src/shared/api.ts index 331149d..46126d2 100644 --- a/apps/desktop/src/shared/api.ts +++ b/apps/desktop/src/shared/api.ts @@ -4,6 +4,7 @@ import type { PrincipalRecord, StepUpProof, } from '@decryption/accounts'; +import type { Grant } from '@decryption/agent'; import type { AuditEntry, FieldPurpose, @@ -19,6 +20,7 @@ export type { ApiKeyRecord, AuditEntry, FieldPurpose, + Grant, ItemKind, PrincipalRecord, StepUpProof, @@ -109,6 +111,22 @@ export interface CreatePrincipalRequest { bypassStepUp?: boolean; } +/** Whether this app is lending secrets to local agents right now. */ +export interface AgentStatus { + /** The person's setting: off until they turn it on. */ + enabled: boolean; + /** Whether the socket is actually up; false with an error when it could not start. */ + serving: boolean; + socketPath: string; + error: string | null; + unlocked: boolean; +} + +/** An agent-related audit entry, with the item's title where it still exists. */ +export interface AgentActivity extends AuditEntry { + itemTitle: string | null; +} + /** What a rebuild carried across, so the UI can show it was not a no-op. */ export interface RebuildReport { tables: number; @@ -210,6 +228,19 @@ export interface DcryptApi { audit: { log(itemId?: string): Promise; }; + agents: { + status(): Promise; + setEnabled(enabled: boolean): Promise; + /** Items agents may ask for. */ + shared(): Promise; + isShared(itemId: string): Promise; + setShared(itemId: string, shared: boolean): Promise; + /** Live "allow for 1 hour" grants. */ + grants(): Promise; + revoke(grantId: string): Promise; + revokeAll(): Promise; + activity(): Promise; + }; workbench: { createWallet(networks: string[], words: number): Promise; deriveAccounts(mnemonic: string, networks: string[]): Promise; @@ -296,6 +327,16 @@ export const CHANNELS = { accountsLinkTotp: 'accounts:link-totp', accountsUnlinkTotp: 'accounts:unlink-totp', auditLog: 'audit:log', + agentsStatus: 'agents:status', + agentsSetEnabled: 'agents:set-enabled', + agentsShared: 'agents:shared', + agentsIsShared: 'agents:is-shared', + agentsSetShared: 'agents:set-shared', + agentsGrants: 'agents:grants', + agentsRevoke: 'agents:revoke', + agentsRevokeAll: 'agents:revoke-all', + agentsActivity: 'agents:activity', + agentsChangedEvent: 'agents:changed-event', wbCreateWallet: 'workbench:create-wallet', wbDeriveAccounts: 'workbench:derive-accounts', wbEncryptText: 'workbench:encrypt-text', diff --git a/packages/agent/README.md b/packages/agent/README.md new file mode 100644 index 0000000..08f71d6 --- /dev/null +++ b/packages/agent/README.md @@ -0,0 +1,88 @@ +# @decryption/agent + +

+ +

+ +

+ + + + + MIT license + + +

+ +Lend secrets from a dcrypt vault to local agents — coding agents, scripts, a harness — without giving +them the master password. Whatever holds the unlocked vault (the dcrypt desktop app) serves a local +socket; a caller asks for named secrets for one command; the person approves in the app, once or for +an hour; the values go into that command's environment and nowhere else. + +The same idea as `ssh-agent`: the key stays with its owner, and callers get a narrow, revocable use of it. + +## Installation + +```bash +npm install @decryption/agent +``` + +Most people want the command instead: `dcrypt agent run` in `@decryption/cli`. + +## Usage + +```bash +dcrypt agent status +dcrypt agent run --secret GITHUB_TOKEN=GitHub -- gh pr list +dcrypt agent run --secret PGPASSWORD="Staging DB#password" -- psql -h db.internal +``` + +Serving, from the process that holds the vault: + +```ts +import { AgentBroker, brokerVault, defaultSocketPath, serveAgent } from '@decryption/agent'; + +const broker = new AgentBroker({ + vault: brokerVault(() => currentVaultOrNull()), + approve: async (request) => askThePerson(request), // 'deny' | 'once' | 'grant' +}); +const server = await serveAgent({ socketPath: defaultSocketPath(), handle: (r) => broker.handle(r) }); +``` + +## What protects what + +- **Nothing is shared by default.** An item is reachable only after its owner opts it in + (`vault.setAgentAccess`). The check is in SQL (`dcrypt_vault.agent_reveal_field`), so no caller + can skip it, and items are looked up among shared ones only: a caller cannot learn whether an + unshared item exists. +- **A person approves.** Every request is shown with the caller, its folder, the command and each + secret it wants. "Allow once" releases the values for that request; "allow for an hour" remembers + that caller, folder, item and field until it expires. Grants live in memory: locking the vault or + quitting the app ends every one. +- **Only this user can connect.** The socket is `~/.dcrypt/run/agent.sock`, in a 0700 directory, + chmod 0600. On Windows it is a named pipe scoped by user name (not yet tested there). +- **Every release is audited** with the caller's label. +- **The master password never crosses the socket**, and the protocol has no way to list, export or + write anything. + +## What it does not protect + +- **The caller's name is self-reported.** dcrypt cannot tell which program is on the other end of the + socket; any process running as you can connect and call itself anything. The approval prompt says so. +- **A command can print its own environment.** The values never reach the agent through dcrypt, but + `env` or `echo $TOKEN` would show them, and anything an agent reads can end up in its transcript. + Read the command before approving it, and prefer scoped, short-lived credentials for agents. +- **Allow for an hour is not tied to the command.** It covers any command from that caller and folder. + +## Protocol + +One request per connection, one newline-terminated JSON object each way: + +```json +{"v":1,"op":"env","client":{"name":"Claude Code","cwd":"/work/app"},"command":["gh","pr","list"],"secrets":[{"env":"GITHUB_TOKEN","item":"GitHub"}]} +{"ok":true,"op":"env","env":{"GITHUB_TOKEN":"…"}} +``` + +`{"v":1,"op":"status"}` answers whether the vault is unlocked. Errors are +`{"ok":false,"code":"locked"|"denied"|"not_found"|"ambiguous"|"busy"|"bad_request"|"internal","message":"…"}`. + diff --git a/packages/agent/__tests__/broker.test.ts b/packages/agent/__tests__/broker.test.ts new file mode 100644 index 0000000..584b4e7 --- /dev/null +++ b/packages/agent/__tests__/broker.test.ts @@ -0,0 +1,186 @@ +import { AgentBroker, AgentRequest, ApprovalRequest, BrokerVault, Decision, GrantStore } from '../src'; + +interface FakeItem { + id: string; + title: string; + kind: string; + shared: boolean; + fields: Record; +} + +const makeVault = (items: FakeItem[]) => { + const reveals: { itemId: string; field: string; actor: string }[] = []; + let unlocked = true; + const vault: BrokerVault = { + isUnlocked: () => unlocked, + sharedItems: async () => items.filter((item) => item.shared), + listFields: async (itemId) => + Object.entries(items.find((item) => item.id === itemId)!.fields).map(([name, f]) => ({ + name, + concealed: f.concealed, + })), + reveal: async (itemId, field, actor) => { + const item = items.find((candidate) => candidate.id === itemId)!; + if (!item.shared) throw new Error('not shared with agents'); + reveals.push({ itemId, field, actor }); + return item.fields[field].value; + }, + }; + return { vault, reveals, lock: () => (unlocked = false) }; +}; + +const items = (): FakeItem[] => [ + { id: 'i1', title: 'GitHub', kind: 'api_key', shared: true, fields: { token: { value: 'ghp_1', concealed: true } } }, + { + id: 'i2', + title: 'Database', + kind: 'login', + shared: true, + fields: { + username: { value: 'app', concealed: false }, + password: { value: 'pw', concealed: true }, + host: { value: 'secret-host', concealed: true }, + }, + }, + { id: 'i3', title: 'Bank', kind: 'login', shared: false, fields: { password: { value: 'nope', concealed: true } } }, +]; + +const request = (secrets: { env: string; item: string; field?: string }[], cwd = '/work/app'): AgentRequest => ({ + v: 1, + op: 'env', + client: { name: 'Claude Code', cwd }, + command: ['gh', 'pr', 'list'], + secrets, +}); + +const setup = (decision: Decision | (() => Promise) = 'once') => { + const fake = makeVault(items()); + let now = 1_000_000; + const asked: ApprovalRequest[] = []; + const broker = new AgentBroker({ + vault: fake.vault, + grants: new GrantStore(() => now), + approve: async (req) => { + asked.push(req); + return typeof decision === 'function' ? decision() : decision; + }, + }); + return { ...fake, broker, asked, advance: (ms: number) => (now += ms) }; +}; + +describe('AgentBroker', () => { + it('reports status without touching any secret', async () => { + const { broker, reveals } = setup(); + expect(await broker.handle({ v: 1, op: 'status' })).toEqual({ ok: true, op: 'status', unlocked: true }); + expect(reveals).toEqual([]); + }); + + it('asks, then releases only what was requested, and audits the caller', async () => { + const { broker, asked, reveals } = setup('once'); + const response = await broker.handle(request([{ env: 'GITHUB_TOKEN', item: 'github' }])); + expect(response).toEqual({ ok: true, op: 'env', env: { GITHUB_TOKEN: 'ghp_1' } }); + expect(asked).toHaveLength(1); + expect(asked[0].secrets).toEqual([{ env: 'GITHUB_TOKEN', itemId: 'i1', itemTitle: 'GitHub', field: 'token' }]); + expect(reveals).toEqual([{ itemId: 'i1', field: 'token', actor: 'Claude Code in /work/app' }]); + }); + + it('releases nothing when declined', async () => { + const { broker, reveals } = setup('deny'); + expect(await broker.handle(request([{ env: 'T', item: 'GitHub' }]))).toMatchObject({ ok: false, code: 'denied' }); + expect(reveals).toEqual([]); + }); + + it('treats a failed or crashed prompt as a denial', async () => { + const { broker, reveals } = setup(() => Promise.reject(new Error('window gone'))); + expect(await broker.handle(request([{ env: 'T', item: 'GitHub' }]))).toMatchObject({ ok: false, code: 'denied' }); + expect(reveals).toEqual([]); + }); + + it('does not reveal whether an unshared item exists', async () => { + const { broker, asked } = setup('once'); + const unshared = await broker.handle(request([{ env: 'P', item: 'Bank' }])); + const missing = await broker.handle(request([{ env: 'P', item: 'Nothing' }])); + expect(unshared).toMatchObject({ ok: false, code: 'not_found' }); + expect((unshared as { message: string }).message).toBe( + (missing as { message: string }).message.replace('Nothing', 'Bank') + ); + expect(asked).toEqual([]); + }); + + it('refuses to guess between several secret fields', async () => { + const { broker, asked } = setup('once'); + expect(await broker.handle(request([{ env: 'P', item: 'Database' }]))).toMatchObject({ + ok: false, + code: 'ambiguous', + }); + expect(asked).toEqual([]); + expect(await broker.handle(request([{ env: 'P', item: 'Database', field: 'password' }]))).toMatchObject({ + ok: true, + env: { P: 'pw' }, + }); + }); + + it('remembers a grant for the same caller, folder, item and field only, until it expires', async () => { + const { broker, asked, advance } = setup('grant'); + await broker.handle(request([{ env: 'T', item: 'GitHub' }])); + await broker.handle(request([{ env: 'OTHER_NAME', item: 'GitHub' }])); + expect(asked).toHaveLength(1); + + await broker.handle(request([{ env: 'T', item: 'GitHub' }], '/elsewhere')); + expect(asked).toHaveLength(2); + + advance(60 * 60 * 1000 + 1); + await broker.handle(request([{ env: 'T', item: 'GitHub' }])); + expect(asked).toHaveLength(3); + }); + + it('asks again when any one requested secret is not covered by a grant', async () => { + const { broker, asked } = setup('grant'); + await broker.handle(request([{ env: 'T', item: 'GitHub' }])); + await broker.handle(request([{ env: 'T', item: 'GitHub' }, { env: 'P', item: 'Database', field: 'password' }])); + expect(asked).toHaveLength(2); + }); + + it('refuses when locked, including a lock that lands while the prompt is open', async () => { + let fake: ReturnType; + const { broker, reveals, lock } = (() => { + const s = setup(async () => { + fake.lock(); + return 'once'; + }); + fake = s; + return s; + })(); + expect(await broker.handle(request([{ env: 'T', item: 'GitHub' }]))).toMatchObject({ ok: false, code: 'locked' }); + expect(reveals).toEqual([]); + lock(); + expect(await broker.handle(request([{ env: 'T', item: 'GitHub' }]))).toMatchObject({ ok: false, code: 'locked' }); + }); + + it('shows one prompt at a time and refuses a flood', async () => { + const pending: ((d: Decision) => void)[] = []; + let open = 0; + let maxOpen = 0; + const { broker } = setup( + () => + new Promise((resolve) => { + open++; + maxOpen = Math.max(maxOpen, open); + pending.push((d) => { + open--; + resolve(d); + }); + }) + ); + const results = Array.from({ length: 6 }, () => broker.handle(request([{ env: 'T', item: 'GitHub' }]))); + const busy = await Promise.race([results[4], results[5]]); + expect(busy).toMatchObject({ ok: false, code: 'busy' }); + for (let i = 0; i < 4; i++) { + await new Promise((r) => setImmediate(r)); + pending.shift()!('once'); + } + const settled = await Promise.all(results); + expect(settled.filter((r) => r.ok)).toHaveLength(4); + expect(maxOpen).toBe(1); + }); +}); diff --git a/packages/agent/__tests__/protocol.test.ts b/packages/agent/__tests__/protocol.test.ts new file mode 100644 index 0000000..470072b --- /dev/null +++ b/packages/agent/__tests__/protocol.test.ts @@ -0,0 +1,53 @@ +import { AgentProtocolError, parseRequest, parseSecretSpec } from '../src'; + +const env = (overrides: Record = {}) => + JSON.stringify({ + v: 1, + op: 'env', + client: { name: 'Claude Code', cwd: '/work/app' }, + command: ['gh', 'pr', 'list'], + secrets: [{ env: 'GITHUB_TOKEN', item: 'GitHub' }], + ...overrides, + }); + +describe('parseRequest', () => { + it('accepts a status request', () => { + expect(parseRequest('{"v":1,"op":"status"}')).toEqual({ v: 1, op: 'status' }); + }); + + it('accepts a well-formed env request', () => { + expect(parseRequest(env())).toMatchObject({ + op: 'env', + client: { name: 'Claude Code', cwd: '/work/app' }, + secrets: [{ env: 'GITHUB_TOKEN', item: 'GitHub' }], + }); + }); + + it.each([ + ['not JSON', 'nope'], + ['a newer protocol', JSON.stringify({ v: 2, op: 'status' })], + ['an unknown op', JSON.stringify({ v: 1, op: 'dump' })], + ['no secrets', env({ secrets: [] })], + ['no command', env({ command: [] })], + ['a bad env name', env({ secrets: [{ env: '1BAD', item: 'x' }] })], + ['an env name twice', env({ secrets: [{ env: 'A', item: 'x' }, { env: 'A', item: 'y' }] })], + ['control characters that could redraw the prompt', env({ client: { name: 'ok\u001b[2J', cwd: '/' } })], + ['a non-string command part', env({ command: ['gh', 3] })], + ])('rejects %s', (_label, raw) => { + expect(() => parseRequest(raw)).toThrow(AgentProtocolError); + }); +}); + +describe('parseSecretSpec', () => { + it('reads ENV=item', () => { + expect(parseSecretSpec('GITHUB_TOKEN=GitHub')).toEqual({ env: 'GITHUB_TOKEN', item: 'GitHub' }); + }); + + it('reads ENV=item#field, splitting at the last #', () => { + expect(parseSecretSpec('T=Team #2#token')).toEqual({ env: 'T', item: 'Team #2', field: 'token' }); + }); + + it.each(['GitHub', '=GitHub', 'T=', 'T=GitHub#'])('rejects %s', (spec) => { + expect(() => parseSecretSpec(spec)).toThrow(AgentProtocolError); + }); +}); diff --git a/packages/agent/__tests__/transport.test.ts b/packages/agent/__tests__/transport.test.ts new file mode 100644 index 0000000..a076c7c --- /dev/null +++ b/packages/agent/__tests__/transport.test.ts @@ -0,0 +1,88 @@ +import { spawn } from 'child_process'; +import { promises as fs } from 'fs'; +import * as net from 'net'; +import * as os from 'os'; +import * as path from 'path'; + +import { AgentAlreadyServingError, AgentUnavailableError, askAgent, serveAgent } from '../src'; + +let dir: string; +let socketPath: string; + +beforeEach(async () => { + dir = await fs.mkdtemp(path.join(os.tmpdir(), 'dca-')); + socketPath = path.join(dir, 'run', 'agent.sock'); +}); + +afterEach(async () => { + await fs.rm(dir, { recursive: true, force: true }); +}); + +const unix = process.platform === 'win32' ? it.skip : it; + +describe('serveAgent / askAgent', () => { + it('round-trips a request', async () => { + const server = await serveAgent({ + socketPath, + handle: async () => ({ ok: true, op: 'status', unlocked: true }), + }); + try { + expect(await askAgent({ v: 1, op: 'status' }, { socketPath })).toEqual({ ok: true, op: 'status', unlocked: true }); + } finally { + await server.close(); + } + }); + + unix('keeps the socket private to this user', async () => { + const server = await serveAgent({ socketPath, handle: async () => ({ ok: true, op: 'status', unlocked: false }) }); + try { + expect((await fs.stat(path.dirname(socketPath))).mode & 0o777).toBe(0o700); + expect((await fs.stat(socketPath)).mode & 0o777).toBe(0o600); + } finally { + await server.close(); + } + }); + + it('answers a malformed request with bad_request and never calls the handler', async () => { + const handle = jest.fn(); + const server = await serveAgent({ socketPath, handle }); + try { + const reply = await new Promise((resolve) => { + const socket = net.connect(socketPath, () => socket.write('{"v":1,"op":"dump"}\n')); + let data = ''; + socket.on('data', (chunk) => (data += chunk)); + socket.on('end', () => resolve(data)); + }); + expect(JSON.parse(reply)).toMatchObject({ ok: false, code: 'bad_request' }); + expect(handle).not.toHaveBeenCalled(); + } finally { + await server.close(); + } + }); + + it('says plainly when nothing is serving', async () => { + await expect(askAgent({ v: 1, op: 'status' }, { socketPath })).rejects.toBeInstanceOf(AgentUnavailableError); + }); + + unix('replaces a stale socket but refuses to take over a live one', async () => { + const first = await serveAgent({ socketPath, handle: async () => ({ ok: true, op: 'status', unlocked: true }) }); + await expect( + serveAgent({ socketPath, handle: async () => ({ ok: true, op: 'status', unlocked: true }) }) + ).rejects.toBeInstanceOf(AgentAlreadyServingError); + await first.close(); + + // a crash leaves the file behind with nobody listening: kill a listener outright + const child = spawn(process.execPath, [ + '-e', + `require('net').createServer().listen(${JSON.stringify(socketPath)}, () => process.stdout.write('up'))`, + ]); + await new Promise((resolve) => child.stdout.once('data', () => resolve())); + child.kill('SIGKILL'); + await new Promise((resolve) => child.once('exit', resolve)); + expect((await fs.lstat(socketPath)).isSocket()).toBe(true); + + const second = await serveAgent({ socketPath, handle: async () => ({ ok: true, op: 'status', unlocked: false }) }); + expect(await askAgent({ v: 1, op: 'status' }, { socketPath })).toMatchObject({ unlocked: false }); + await second.close(); + }); +}); diff --git a/packages/agent/jest.config.js b/packages/agent/jest.config.js new file mode 100644 index 0000000..f4c0ce0 --- /dev/null +++ b/packages/agent/jest.config.js @@ -0,0 +1,18 @@ +/** @type {import('ts-jest').JestConfigWithTsJest} */ +module.exports = { + preset: 'ts-jest', + testEnvironment: 'node', + transform: { + '^.+\\.tsx?$': [ + 'ts-jest', + { + babelConfig: false, + tsconfig: 'tsconfig.json', + }, + ], + }, + transformIgnorePatterns: [`/node_modules/*`], + testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$', + moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'], + modulePathIgnorePatterns: ['dist/*'], +}; diff --git a/packages/agent/package.json b/packages/agent/package.json new file mode 100644 index 0000000..205fb02 --- /dev/null +++ b/packages/agent/package.json @@ -0,0 +1,44 @@ +{ + "name": "@decryption/agent", + "version": "0.0.1", + "description": "Lend vault secrets to local agents without the master password: a local socket, per-item opt-in, approval and time-boxed grants", + "author": "Constructive ", + "main": "index.js", + "module": "esm/index.js", + "types": "index.d.ts", + "homepage": "https://github.com/constructive-io/decryption", + "license": "MIT", + "publishConfig": { + "access": "public", + "directory": "dist" + }, + "repository": { + "type": "git", + "url": "https://github.com/constructive-io/decryption" + }, + "bugs": { + "url": "https://github.com/constructive-io/decryption/issues" + }, + "scripts": { + "copy": "makage assets", + "clean": "makage clean", + "prepublishOnly": "npm run build", + "build": "makage build", + "lint": "eslint . --fix", + "test": "NODE_OPTIONS=--experimental-vm-modules jest", + "test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch" + }, + "keywords": [ + "agent", + "secrets", + "vault", + "ssh-agent", + "local-first" + ], + "dependencies": { + "appstash": "^0.7.0" + }, + "devDependencies": { + "makage": "0.3.0" + } +} diff --git a/packages/agent/src/broker.ts b/packages/agent/src/broker.ts new file mode 100644 index 0000000..be39f3a --- /dev/null +++ b/packages/agent/src/broker.ts @@ -0,0 +1,215 @@ +import { GrantStore } from './grants'; +import { AgentRequest, AgentResponse, ClientInfo } from './protocol'; + +/** What the broker needs from a vault; @decryption/vault's Vault adapts to it. */ +export interface BrokerVault { + isUnlocked(): boolean; + /** Items opted in to agent access (never trashed ones). */ + sharedItems(): Promise; + listFields(itemId: string): Promise<{ name: string; concealed: boolean }[]>; + /** Must enforce the opt-in itself and audit `actor`. */ + reveal(itemId: string, field: string, actor: string): Promise; +} + +export interface BrokerItem { + id: string; + title: string; + kind: string; +} + +export interface ApprovalSecret { + env: string; + itemId: string; + itemTitle: string; + field: string; +} + +export interface ApprovalRequest { + client: ClientInfo; + command: string[]; + secrets: ApprovalSecret[]; +} + +/** "once" releases the values for this request only; "grant" also remembers it. */ +export type Decision = 'deny' | 'once' | 'grant'; + +export interface BrokerOptions { + vault: BrokerVault; + /** Ask the person. Resolve 'deny' on timeout or when no one can be asked. */ + approve(request: ApprovalRequest): Promise; + grants?: GrantStore; + /** How long a "grant" decision lasts. Default one hour. */ + grantMs?: number; + /** Requests allowed to wait behind an open prompt before new ones are refused. */ + maxQueued?: number; +} + +const HOUR = 60 * 60 * 1000; + +class BrokerError extends Error { + constructor( + readonly code: Extract['code'], + message: string + ) { + super(message); + } +} + +/** The label stored in the audit log for a caller. */ +export const actorLabel = (client: ClientInfo): string => `${client.name} in ${client.cwd}`.slice(0, 300); + +/** + * Decides what an agent request gets. Items are looked up among shared items + * only, so a caller cannot even learn whether an unshared item exists; values + * are released only after the person approves or a live grant covers every + * requested secret; and prompts are shown one at a time. + */ +export class AgentBroker { + readonly grants: GrantStore; + private readonly grantMs: number; + private readonly maxQueued: number; + private queue: Promise = Promise.resolve(); + private queued = 0; + + constructor(private readonly options: BrokerOptions) { + this.grants = options.grants ?? new GrantStore(); + this.grantMs = options.grantMs ?? HOUR; + this.maxQueued = options.maxQueued ?? 4; + } + + async handle(request: AgentRequest): Promise { + try { + if (request.op === 'status') { + return { ok: true, op: 'status', unlocked: this.options.vault.isUnlocked() }; + } + return { ok: true, op: 'env', env: await this.env(request) }; + } catch (error) { + if (error instanceof BrokerError) return { ok: false, code: error.code, message: error.message }; + return { ok: false, code: 'internal', message: error instanceof Error ? error.message : String(error) }; + } + } + + private async env(request: Extract): Promise> { + const { vault } = this.options; + if (!vault.isUnlocked()) throw new BrokerError('locked', 'the vault is locked: unlock it in the dcrypt app'); + + const shared = await vault.sharedItems(); + const resolved: ApprovalSecret[] = []; + for (const secret of request.secrets) { + const item = pickItem(shared, secret.item); + const field = await pickField(vault, item, secret.field); + resolved.push({ env: secret.env, itemId: item.id, itemTitle: item.title, field }); + } + + const scope = (secret: ApprovalSecret) => ({ + client: request.client.name, + cwd: request.client.cwd, + itemId: secret.itemId, + itemTitle: secret.itemTitle, + field: secret.field, + }); + + if (!resolved.every((secret) => this.grants.covers(scope(secret)))) { + const decision = await this.ask({ client: request.client, command: request.command, secrets: resolved }); + if (decision === 'deny') throw new BrokerError('denied', 'the request was declined in the dcrypt app'); + if (decision === 'grant') { + for (const secret of resolved) this.grants.add(scope(secret), this.grantMs); + } + } + + // the vault may have locked while the prompt was open + if (!vault.isUnlocked()) throw new BrokerError('locked', 'the vault was locked before the request finished'); + const actor = actorLabel(request.client); + const env: Record = {}; + for (const secret of resolved) { + env[secret.env] = await vault.reveal(secret.itemId, secret.field, actor); + } + return env; + } + + /** One prompt at a time; a flood of requests is refused rather than queued forever. */ + private ask(request: ApprovalRequest): Promise { + if (this.queued >= this.maxQueued) { + return Promise.reject(new BrokerError('busy', 'too many requests are waiting for approval')); + } + this.queued++; + const run = this.queue.then(() => this.options.approve(request)); + this.queue = run.catch((): void => undefined).finally(() => { + this.queued--; + }); + return run.catch((): Decision => 'deny'); + } +} + +const pickItem = (shared: BrokerItem[], ref: string): BrokerItem => { + const byId = shared.find((item) => item.id === ref); + if (byId) return byId; + const exact = shared.filter((item) => item.title === ref); + const matches = exact.length ? exact : shared.filter((item) => item.title.toLowerCase() === ref.toLowerCase()); + if (matches.length === 1) return matches[0]; + if (matches.length > 1) { + throw new BrokerError('ambiguous', `several shared items are called "${ref}": use the item id instead`); + } + throw new BrokerError( + 'not_found', + `no item shared with agents is called "${ref}". In the dcrypt app, open the item and turn on "Agents may use this".` + ); +}; + +/** + * The named field, or the item's one concealed field. Several concealed fields + * and no name is refused rather than guessed: handing over the wrong secret is + * worse than asking the caller to be specific. + */ +const pickField = async (vault: BrokerVault, item: BrokerItem, name?: string): Promise => { + const fields = await vault.listFields(item.id); + if (name !== undefined) { + if (!fields.some((field) => field.name === name)) { + throw new BrokerError('not_found', `"${item.title}" has no field "${name}"`); + } + return name; + } + const concealed = fields.filter((field) => field.concealed); + if (concealed.length === 1) return concealed[0].name; + if (concealed.length === 0 && fields.length === 1) return fields[0].name; + if (fields.length === 0) throw new BrokerError('not_found', `"${item.title}" has no fields`); + const names = (concealed.length ? concealed : fields).map((field) => field.name).join(', '); + throw new BrokerError('ambiguous', `"${item.title}" has several fields (${names}): name one as ${item.title}#`); +}; + +/** + * The parts of `@decryption/vault`'s Vault the broker uses, typed structurally + * so this package does not depend on the vault (and its database) to serve it. + */ +export interface VaultLike { + readonly isLocked: boolean; + listItems(): Promise; + agentAccessItemIds(): Promise; + listFields(itemId: string): Promise<{ name: string; concealed: boolean }[]>; + revealFieldForAgent(itemId: string, name: string, actor: string): Promise; +} + +/** + * Adapt a vault for the broker. `current` is asked on every call, so the broker + * follows the app as it locks and unlocks and never holds a vault itself. + */ +export const brokerVault = (current: () => VaultLike | null): BrokerVault => { + const open = (): VaultLike => { + const vault = current(); + if (!vault || vault.isLocked) throw new Error('vault is locked'); + return vault; + }; + return { + isUnlocked: () => { + const vault = current(); + return Boolean(vault && !vault.isLocked); + }, + sharedItems: async () => { + const vault = open(); + const shared = new Set(await vault.agentAccessItemIds()); + return (await vault.listItems()).filter((item) => shared.has(item.id)); + }, + listFields: (itemId) => open().listFields(itemId), + reveal: (itemId, field, actor) => open().revealFieldForAgent(itemId, field, actor), + }; +}; diff --git a/packages/agent/src/grants.ts b/packages/agent/src/grants.ts new file mode 100644 index 0000000..dc6a6e2 --- /dev/null +++ b/packages/agent/src/grants.ts @@ -0,0 +1,96 @@ +/** + * Time-boxed permissions handed out by "allow for an hour". Held in memory + * only: locking the vault or quitting the app clears every one of them, so no + * grant can outlive the session that approved it. + */ + +export interface Grant { + id: string; + /** The caller's self-description at approval time. */ + client: string; + cwd: string; + itemId: string; + itemTitle: string; + field: string; + grantedAt: number; + expiresAt: number; +} + +export type GrantInput = Omit; + +let counter = 0; +const nextId = (): string => `g${Date.now().toString(36)}${(counter++).toString(36)}`; + +export class GrantStore { + private grants = new Map(); + private listeners = new Set<() => void>(); + + constructor(private readonly now: () => number = Date.now) {} + + add(input: GrantInput, durationMs: number): Grant { + // replace rather than stack: a second approval extends, never duplicates + for (const grant of this.grants.values()) { + if (sameScope(grant, input)) this.grants.delete(grant.id); + } + const at = this.now(); + const grant: Grant = { ...input, id: nextId(), grantedAt: at, expiresAt: at + durationMs }; + this.grants.set(grant.id, grant); + this.emit(); + return grant; + } + + /** Whether a live grant covers exactly this caller, folder, item and field. */ + covers(scope: GrantInput): boolean { + return this.list().some((grant) => sameScope(grant, scope)); + } + + /** Live grants, soonest to expire first; expired ones are dropped. */ + list(): Grant[] { + const at = this.now(); + let pruned = false; + for (const [id, grant] of this.grants) { + if (grant.expiresAt <= at) { + this.grants.delete(id); + pruned = true; + } + } + if (pruned) this.emit(); + return [...this.grants.values()].sort((a, b) => a.expiresAt - b.expiresAt); + } + + revoke(id: string): boolean { + const removed = this.grants.delete(id); + if (removed) this.emit(); + return removed; + } + + /** Drop grants for one item, e.g. when it stops being shared. */ + revokeItem(itemId: string): void { + let removed = false; + for (const [id, grant] of this.grants) { + if (grant.itemId === itemId) { + this.grants.delete(id); + removed = true; + } + } + if (removed) this.emit(); + } + + clear(): void { + if (this.grants.size === 0) return; + this.grants.clear(); + this.emit(); + } + + onChange(listener: () => void): () => void { + this.listeners.add(listener); + return () => this.listeners.delete(listener); + } + + private emit(): void { + for (const listener of this.listeners) listener(); + } +} + +const sameScope = (a: GrantInput, b: GrantInput): boolean => + a.client === b.client && a.cwd === b.cwd && a.itemId === b.itemId && a.field === b.field; diff --git a/packages/agent/src/index.ts b/packages/agent/src/index.ts new file mode 100644 index 0000000..cbe71c2 --- /dev/null +++ b/packages/agent/src/index.ts @@ -0,0 +1,5 @@ +export * from './broker'; +export * from './grants'; +export * from './protocol'; +export * from './socket-path'; +export * from './transport'; diff --git a/packages/agent/src/protocol.ts b/packages/agent/src/protocol.ts new file mode 100644 index 0000000..32b644b --- /dev/null +++ b/packages/agent/src/protocol.ts @@ -0,0 +1,152 @@ +/** + * The wire format between `dcrypt agent` and whatever holds the unlocked vault + * (the desktop app). One request per connection, one newline-terminated JSON + * object each way. Every field is validated on the serving side: the socket is + * reachable by any process running as this user, so nothing it sends is trusted. + */ + +export const PROTOCOL_VERSION = 1; + +/** Largest request a server will read, in bytes. */ +export const MAX_REQUEST_BYTES = 64 * 1024; + +/** How the caller describes itself. Self-reported: a label, never proof. */ +export interface ClientInfo { + /** e.g. "Claude Code", "Codex", "a terminal". */ + name: string; + /** Working directory the request was made from. */ + cwd: string; + pid?: number; +} + +/** One secret to put into the child's environment. */ +export interface SecretRequest { + /** Environment variable name. */ + env: string; + /** Item id or title. */ + item: string; + /** Field name; omitted means "the item's one secret field". */ + field?: string; +} + +export type AgentRequest = + | { v: typeof PROTOCOL_VERSION; op: 'status' } + | { + v: typeof PROTOCOL_VERSION; + op: 'env'; + client: ClientInfo; + /** The command the values are for, shown to the person approving. */ + command: string[]; + secrets: SecretRequest[]; + }; + +export type AgentErrorCode = + | 'bad_request' + | 'locked' + | 'denied' + | 'not_found' + | 'ambiguous' + | 'busy' + | 'internal'; + +export type AgentResponse = + | { ok: true; op: 'status'; unlocked: boolean } + | { ok: true; op: 'env'; env: Record } + | { ok: false; code: AgentErrorCode; message: string }; + +export class AgentProtocolError extends Error { + constructor(message: string) { + super(message); + this.name = 'AgentProtocolError'; + } +} + +const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/; +const MAX_SECRETS = 32; +const MAX_COMMAND_PARTS = 256; +const MAX_STRING = 4096; + +const isRecord = (value: unknown): value is Record => + typeof value === 'object' && value !== null && !Array.isArray(value); + +const boundedString = (value: unknown, what: string, allowEmpty = false): string => { + if (typeof value !== 'string') throw new AgentProtocolError(`${what} must be a string`); + if (!allowEmpty && value.length === 0) throw new AgentProtocolError(`${what} is empty`); + if (value.length > MAX_STRING) throw new AgentProtocolError(`${what} is too long`); + // control characters would let a caller redraw the approval prompt + // eslint-disable-next-line no-control-regex + if (/[\u0000-\u0008\u000b-\u001f\u007f]/.test(value)) { + throw new AgentProtocolError(`${what} contains control characters`); + } + return value; +}; + +/** Parse and validate one request; throws AgentProtocolError on anything off. */ +export const parseRequest = (raw: string): AgentRequest => { + let data: unknown; + try { + data = JSON.parse(raw); + } catch { + throw new AgentProtocolError('request is not JSON'); + } + if (!isRecord(data)) throw new AgentProtocolError('request must be an object'); + if (data.v !== PROTOCOL_VERSION) { + throw new AgentProtocolError(`unsupported protocol version ${String(data.v)}`); + } + if (data.op === 'status') return { v: PROTOCOL_VERSION, op: 'status' }; + if (data.op !== 'env') throw new AgentProtocolError(`unknown op ${String(data.op)}`); + + if (!isRecord(data.client)) throw new AgentProtocolError('client is required'); + const client: ClientInfo = { + name: boundedString(data.client.name, 'client.name').slice(0, 80), + cwd: boundedString(data.client.cwd, 'client.cwd'), + }; + if (data.client.pid !== undefined) { + if (!Number.isInteger(data.client.pid)) throw new AgentProtocolError('client.pid must be an integer'); + client.pid = data.client.pid as number; + } + + if (!Array.isArray(data.command) || data.command.length === 0) { + throw new AgentProtocolError('command is required'); + } + if (data.command.length > MAX_COMMAND_PARTS) throw new AgentProtocolError('command is too long'); + const command = data.command.map((part, index) => + boundedString(part, `command[${index}]`, index > 0) + ); + + if (!Array.isArray(data.secrets) || data.secrets.length === 0) { + throw new AgentProtocolError('at least one secret is required'); + } + if (data.secrets.length > MAX_SECRETS) throw new AgentProtocolError('too many secrets'); + const seen = new Set(); + const secrets = data.secrets.map((entry, index): SecretRequest => { + if (!isRecord(entry)) throw new AgentProtocolError(`secrets[${index}] must be an object`); + const env = boundedString(entry.env, `secrets[${index}].env`); + if (!ENV_NAME.test(env)) throw new AgentProtocolError(`"${env}" is not an environment variable name`); + if (seen.has(env)) throw new AgentProtocolError(`${env} is requested twice`); + seen.add(env); + const secret: SecretRequest = { env, item: boundedString(entry.item, `secrets[${index}].item`) }; + if (entry.field !== undefined) secret.field = boundedString(entry.field, `secrets[${index}].field`); + return secret; + }); + + return { v: PROTOCOL_VERSION, op: 'env', client, command, secrets }; +}; + +/** + * Parse `ENV=item` or `ENV=item#field`, the command-line form. The field is + * split at the last `#`, so a title containing `#` needs its field named too — + * or the item's id instead of its title. + */ +export const parseSecretSpec = (spec: string): SecretRequest => { + const eq = spec.indexOf('='); + if (eq <= 0) throw new AgentProtocolError(`"${spec}" should look like ENV=item or ENV=item#field`); + const env = spec.slice(0, eq); + const ref = spec.slice(eq + 1); + const hash = ref.lastIndexOf('#'); + const item = hash > 0 ? ref.slice(0, hash) : ref; + const field = hash > 0 ? ref.slice(hash + 1) : undefined; + if (!item) throw new AgentProtocolError(`"${spec}" names no item`); + if (field === '') throw new AgentProtocolError(`"${spec}" has an empty field after #`); + return field ? { env, item, field } : { env, item }; +}; diff --git a/packages/agent/src/socket-path.ts b/packages/agent/src/socket-path.ts new file mode 100644 index 0000000..32aebab --- /dev/null +++ b/packages/agent/src/socket-path.ts @@ -0,0 +1,14 @@ +import { appstash } from 'appstash'; +import * as os from 'os'; +import * as path from 'path'; + +/** + * Where the agent socket lives: `~/.dcrypt/run/agent.sock`, in a directory only + * this user can enter. On Windows, a named pipe scoped by user name. + */ +export const defaultSocketPath = (): string => { + if (process.platform === 'win32') { + return `\\\\.\\pipe\\dcrypt-agent-${os.userInfo().username}`; + } + return path.join(appstash('dcrypt').root, 'run', 'agent.sock'); +}; diff --git a/packages/agent/src/transport.ts b/packages/agent/src/transport.ts new file mode 100644 index 0000000..9ba6323 --- /dev/null +++ b/packages/agent/src/transport.ts @@ -0,0 +1,180 @@ +import { promises as fs } from 'fs'; +import * as net from 'net'; +import * as path from 'path'; + +import { + AgentProtocolError, + AgentRequest, + AgentResponse, + MAX_REQUEST_BYTES, + parseRequest, +} from './protocol'; + +/** Nothing is serving on the socket: the app is not running, or agent access is off. */ +export class AgentUnavailableError extends Error { + constructor(readonly socketPath: string) { + super('the dcrypt app is not serving agents: open it and turn on agent access in its Agents screen'); + this.name = 'AgentUnavailableError'; + } +} + +/** Another process is already serving on this socket. */ +export class AgentAlreadyServingError extends Error { + constructor(readonly socketPath: string) { + super(`another dcrypt is already serving agents at ${socketPath}`); + this.name = 'AgentAlreadyServingError'; + } +} + +export interface AgentServer { + readonly socketPath: string; + close(): Promise; +} + +export interface ServeOptions { + socketPath: string; + handle(request: AgentRequest): Promise; + /** How long a client may take to send its request. Default 10s. */ + requestTimeoutMs?: number; +} + +const isWindowsPipe = (socketPath: string): boolean => socketPath.startsWith('\\\\.\\pipe\\'); + +const canConnect = (socketPath: string): Promise => + new Promise((resolve) => { + const probe = net.connect(socketPath); + probe.once('connect', () => { + probe.destroy(); + resolve(true); + }); + probe.once('error', () => resolve(false)); + }); + +/** + * Serve agent requests on a Unix socket (or Windows named pipe). The socket's + * directory is created 0700 and the socket chmod 0600, so only this user's + * processes can connect; a stale socket from a crashed app is replaced, a live + * one is refused. + */ +export const serveAgent = async (options: ServeOptions): Promise => { + const { socketPath, handle, requestTimeoutMs = 10_000 } = options; + + if (!isWindowsPipe(socketPath)) { + const dir = path.dirname(socketPath); + await fs.mkdir(dir, { recursive: true, mode: 0o700 }); + await fs.chmod(dir, 0o700); + const existing = await fs.lstat(socketPath).catch((): null => null); + if (existing) { + if (!existing.isSocket()) throw new Error(`${socketPath} exists and is not a socket`); + if (await canConnect(socketPath)) throw new AgentAlreadyServingError(socketPath); + await fs.unlink(socketPath); + } + } + + const server = net.createServer((socket) => { + let buffer = ''; + let done = false; + socket.setEncoding('utf8'); + socket.setTimeout(requestTimeoutMs, () => socket.destroy()); + + const reply = (response: AgentResponse): void => { + if (!socket.destroyed) socket.end(`${JSON.stringify(response)}\n`); + }; + + socket.on('data', (chunk: string) => { + if (done) return; + buffer += chunk; + if (buffer.length > MAX_REQUEST_BYTES) { + done = true; + reply({ ok: false, code: 'bad_request', message: 'request too large' }); + return; + } + const newline = buffer.indexOf('\n'); + if (newline === -1) return; + done = true; + // the request is in: waiting on a person to approve has no deadline here + socket.setTimeout(0); + let request: AgentRequest; + try { + request = parseRequest(buffer.slice(0, newline)); + } catch (error) { + const message = error instanceof AgentProtocolError ? error.message : 'bad request'; + reply({ ok: false, code: 'bad_request', message }); + return; + } + handle(request).then(reply, (error: unknown) => + reply({ ok: false, code: 'internal', message: error instanceof Error ? error.message : String(error) }) + ); + }); + socket.on('error', () => socket.destroy()); + }); + + await new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(socketPath, () => { + server.off('error', reject); + resolve(); + }); + }); + if (!isWindowsPipe(socketPath)) await fs.chmod(socketPath, 0o600); + + return { + socketPath, + close: () => + new Promise((resolve) => { + server.close(() => resolve()); + }), + }; +}; + +export interface AskOptions { + socketPath: string; + /** Overall deadline, approval included. Default 3 minutes. */ + timeoutMs?: number; +} + +/** Send one request and wait for its response. */ +export const askAgent = (request: AgentRequest, options: AskOptions): Promise => { + const { socketPath, timeoutMs = 180_000 } = options; + return new Promise((resolve, reject) => { + const socket = net.connect(socketPath); + let buffer = ''; + let settled = false; + const finish = (fn: () => void): void => { + if (settled) return; + settled = true; + clearTimeout(timer); + socket.destroy(); + fn(); + }; + const timer = setTimeout( + () => finish(() => reject(new Error('timed out waiting for the dcrypt app to answer'))), + timeoutMs + ); + socket.setEncoding('utf8'); + socket.once('connect', () => socket.write(`${JSON.stringify(request)}\n`)); + socket.on('data', (chunk: string) => { + buffer += chunk; + const newline = buffer.indexOf('\n'); + if (newline === -1) return; + const line = buffer.slice(0, newline); + finish(() => { + try { + resolve(JSON.parse(line) as AgentResponse); + } catch { + reject(new Error('the dcrypt app sent a response that is not JSON')); + } + }); + }); + socket.on('error', (error: NodeJS.ErrnoException) => + finish(() => + reject( + error.code === 'ENOENT' || error.code === 'ECONNREFUSED' + ? new AgentUnavailableError(socketPath) + : error + ) + ) + ); + socket.on('end', () => finish(() => reject(new Error('the dcrypt app closed the connection without answering')))); + }); +}; diff --git a/packages/agent/tsconfig.esm.json b/packages/agent/tsconfig.esm.json new file mode 100644 index 0000000..800d750 --- /dev/null +++ b/packages/agent/tsconfig.esm.json @@ -0,0 +1,9 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "dist/esm", + "module": "es2022", + "rootDir": "src/", + "declaration": false + } +} diff --git a/packages/agent/tsconfig.json b/packages/agent/tsconfig.json new file mode 100644 index 0000000..ef02482 --- /dev/null +++ b/packages/agent/tsconfig.json @@ -0,0 +1,16 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src/" + }, + "include": [ + "src/**/*.ts" + ], + "exclude": [ + "dist", + "node_modules", + "**/*.spec.*", + "**/*.test.*" + ] +} diff --git a/packages/cli/README.md b/packages/cli/README.md index 6bfb868..9822fc5 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -38,6 +38,7 @@ dcrypt --help | `dcrypt wallet create\|address\|validate` | BIP39 mnemonics and offline address derivation | | `dcrypt keys generate\|show\|verify` | Your X25519 identity, stored encrypted | | `dcrypt secrets …` | Team secrets files, `.env` generation, recipient management | +| `dcrypt agent status\|run` | Lend vault secrets to one command, approved in the desktop app | | `dcrypt keychain set\|get\|del\|list` | Named local secrets, always encrypted | | `dcrypt shamir split\|combine` | Authenticated Shamir shares | | `dcrypt salt generate\|encrypt\|decrypt` | Two-layer encryption (data under a salt, salt under your passphrase) | @@ -250,6 +251,29 @@ to establish and what an extraction is verified against. - `dcrypt keychain` has no plaintext mode. The old cosmology CLI stored the *plaintext* when you passed `--encrypted`; that bug is not reproduced here. +## Lending secrets to agents + +Coding agents and scripts should not hold your master password. Instead, with the desktop app open, +unlocked and agent access turned on (its Agents screen), an agent asks for named secrets for one +command: + +```bash +dcrypt agent run --secret GITHUB_TOKEN=GitHub -- gh pr list +dcrypt agent run --secret PGPASSWORD="Staging DB#password" -- psql -h db.internal +``` + +- Only items you have marked "Agents may use this" can be asked for. Other items are invisible: the + agent cannot even learn that they exist. +- The app shows who is asking, from which folder, the exact command and each secret. You choose + Deny, Allow once, or Allow for 1 hour; on a Mac with Touch ID, allowing also needs your finger. +- The values go into that command's environment only. A command that prints its environment can + still show them, so read the command before allowing it. +- The caller's name is self-reported, and allowing for an hour covers any command from that caller + in that folder. Locking the vault or quitting the app ends every grant at once. + +Exit codes: 4 when the app is not serving (or no shared item matches), 2 when the vault is locked, +5 when you deny; otherwise the command's own exit code. + ## Non-interactive use Every prompt has a flag, so the CLI works in CI. `dcrypt` only prompts on a terminal: when stdin is a @@ -296,6 +320,8 @@ Add `--json` for machine-readable output, and check exit codes: ```text ~/.dcrypt/ config/identity.json X25519 identity, encrypted under your passphrase + config/agent.json whether the desktop app serves agents (no secrets) + run/agent.sock the desktop app's agent socket, while it serves (this user only) data/keychain.json named secrets, each encrypted data/vaults/.json team secrets files ``` diff --git a/packages/cli/__tests__/agent.test.ts b/packages/cli/__tests__/agent.test.ts new file mode 100644 index 0000000..9369353 --- /dev/null +++ b/packages/cli/__tests__/agent.test.ts @@ -0,0 +1,156 @@ +import { AgentBroker, AgentServer, brokerVault, Decision, defaultSocketPath, serveAgent } from '@decryption/agent'; +import { defaultModulePath, Vault } from '@decryption/vault'; +import { mkdtempSync, readFileSync, writeFileSync } from 'fs'; +import { Inquirerer, parseArgv } from 'inquirerer'; +import { tmpdir } from 'os'; +import { join } from 'path'; + +import { dispatch, EXIT } from '../src'; +import { clientName } from '../src/commands/agent'; + +jest.setTimeout(300000); + +let home: string; +let work: string; +let out: string[]; +let errors: string[]; +let vault: Vault | null; +let server: AgentServer | null; +let decisions: Decision[]; +let asked: number; + +const run = async (args: string[]): Promise => { + const argv = parseArgv(['node', 'dcrypt', ...args], { '--': true, string: ['secret', 'as'] }); + const prompter = new Inquirerer({ noTty: true, useDefaults: true }); + try { + return await dispatch(argv, prompter); + } finally { + prompter.close(); + } +}; + +const stdout = (): string => out.join('').trim(); +const stderr = (): string => errors.join('').trim(); + +/** A child that records the variable it was given, so the test sees what the command saw. */ +const recorder = (name: string): { args: string[]; read(): string } => { + const script = join(work, 'record.js'); + const target = join(work, `${name}.out`); + writeFileSync(script, `require('fs').writeFileSync(process.argv[2], process.env[process.argv[3]] ?? '')`); + return { args: [process.execPath, script, target, name], read: () => readFileSync(target, 'utf8') }; +}; + +const serve = async (): Promise => { + const broker = new AgentBroker({ + vault: brokerVault(() => vault), + approve: async () => { + asked++; + return decisions.shift() ?? 'deny'; + }, + }); + server = await serveAgent({ socketPath: defaultSocketPath(), handle: (request) => broker.handle(request) }); +}; + +beforeEach(async () => { + home = mkdtempSync(join(tmpdir(), 'dca-home-')); + work = mkdtempSync(join(tmpdir(), 'dca-work-')); + process.env.APPSTASH_BASE_DIR = home; + out = []; + errors = []; + decisions = []; + asked = 0; + server = null; + vault = await Vault.open({ + file: join(home, 'vault.dcrypt'), + passphrase: 'a strong master password', + modulePath: defaultModulePath(), + kdf: { t: 1, m: 8192, p: 1 }, + }); + jest.spyOn(process.stdout, 'write').mockImplementation((chunk) => { + out.push(String(chunk)); + return true; + }); + jest.spyOn(process.stderr, 'write').mockImplementation((chunk) => { + errors.push(String(chunk)); + return true; + }); +}); + +afterEach(async () => { + jest.restoreAllMocks(); + await server?.close(); + await vault?.discard(); + delete process.env.APPSTASH_BASE_DIR; +}); + +const sharedToken = async (title = 'GitHub', value = 'ghp_from_vault'): Promise => { + const item = await vault!.createItem('api_key', title); + await vault!.setField(item.id, 'token', 'token', value); + await vault!.setAgentAccess(item.id, true); + return item.id; +}; + +describe('dcrypt agent', () => { + it('says when nothing is serving', async () => { + expect(await run(['agent', 'status'])).toBe(0); + expect(stdout()).toContain('not serving'); + expect(await run(['agent', 'run', '--secret', 'T=GitHub', '--', 'true'])).toBe(EXIT.notFound); + expect(stderr()).toContain('not serving agents'); + }); + + it('runs a command with an approved secret in its environment, and prints no value', async () => { + await sharedToken(); + await serve(); + decisions = ['once']; + const child = recorder('GITHUB_TOKEN'); + expect(await run(['agent', 'run', '--secret', 'GITHUB_TOKEN=GitHub', '--', ...child.args])).toBe(0); + expect(child.read()).toBe('ghp_from_vault'); + expect(stdout() + stderr()).not.toContain('ghp_from_vault'); + const log = await vault!.auditLog(); + expect(log[0]).toMatchObject({ action: 'agent_reveal', actor: expect.stringContaining(process.cwd()) }); + }); + + it('runs nothing when the request is declined', async () => { + await sharedToken(); + await serve(); + decisions = ['deny']; + const child = recorder('GITHUB_TOKEN'); + expect(await run(['agent', 'run', '--secret', 'GITHUB_TOKEN=GitHub', '--', ...child.args])).toBe(EXIT.permission); + expect(() => child.read()).toThrow(); + }); + + it('cannot reach an item that is not shared, and never asks about it', async () => { + const item = await vault!.createItem('login', 'Bank'); + await vault!.setField(item.id, 'password', 'password', 'hunter2'); + await serve(); + decisions = ['once']; + expect(await run(['agent', 'run', '--secret', 'P=Bank', '--', 'true'])).toBe(EXIT.notFound); + expect(asked).toBe(0); + }); + + it('stops serving secrets the moment the vault locks', async () => { + await sharedToken(); + await serve(); + expect(await run(['agent', 'status'])).toBe(0); + expect(stdout()).toContain('serving, unlocked'); + await vault!.lock(); + out = []; + expect(await run(['agent', 'status'])).toBe(0); + expect(stdout()).toContain('vault is locked'); + expect(await run(['agent', 'run', '--secret', 'T=GitHub', '--', 'true'])).toBe(EXIT.auth); + expect(asked).toBe(0); + }); + + it('passes the command exit code through', async () => { + await sharedToken(); + await serve(); + decisions = ['once']; + expect(await run(['agent', 'run', '--secret', 'T=GitHub', '--', process.execPath, '-e', 'process.exit(7)'])).toBe(7); + }); + + it('labels the caller from --as, or from a known agent environment', () => { + expect(clientName({ _: [], as: 'deploy bot' })).toBe('deploy bot'); + expect(clientName({ _: [] }, { CLAUDECODE: '1' })).toBe('Claude Code'); + expect(clientName({ _: [] }, {})).toBe('dcrypt agent'); + }); +}); diff --git a/packages/cli/package.json b/packages/cli/package.json index 98789fb..84199ce 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -39,6 +39,7 @@ ], "dependencies": { "@decryption/accounts": "workspace:*", + "@decryption/agent": "workspace:*", "@decryption/base": "workspace:*", "@decryption/core": "workspace:*", "@decryption/cosmology-compat": "workspace:*", diff --git a/packages/cli/src/commands.ts b/packages/cli/src/commands.ts index de87229..3f762ae 100644 --- a/packages/cli/src/commands.ts +++ b/packages/cli/src/commands.ts @@ -2,6 +2,7 @@ import { CommandHandler, getPackageJson, Inquirerer } from 'inquirerer'; import { ParsedArgs } from 'minimist'; import { accountCommand } from './commands/account'; +import { agentCommand } from './commands/agent'; import { cosmologyCommand } from './commands/cosmology'; import { doctorCommand } from './commands/doctor'; import { decryptCommand, encryptCommand } from './commands/encrypt'; @@ -38,6 +39,7 @@ Commands: secrets Team secrets files (.env generation, recipients, rekeying) vault The local encrypted vault, shared with the desktop app account Constructive accounts and API keys, stored in the vault + agent Lend vault secrets to a command, approved in the desktop app passkey Passkeys held in the vault; dcrypt signs for the site keychain Store named secrets locally, always encrypted shamir Split and recombine a secret into authenticated shares @@ -72,6 +74,7 @@ export const createCommandMap = (): Record => ({ secrets: secretsCommand, vault: vaultCommand, account: accountCommand, + agent: agentCommand, passkey: passkeyCommand, keychain: keychainCommand, shamir: shamirCommand, diff --git a/packages/cli/src/commands/agent.ts b/packages/cli/src/commands/agent.ts new file mode 100644 index 0000000..43614f2 --- /dev/null +++ b/packages/cli/src/commands/agent.ts @@ -0,0 +1,146 @@ +import { + AgentResponse, + AgentUnavailableError, + askAgent, + defaultSocketPath, + parseSecretSpec, + PROTOCOL_VERSION, + SecretRequest, +} from '@decryption/agent'; +import { spawnSync } from 'child_process'; +import { Inquirerer } from 'inquirerer'; +import { ParsedArgs } from 'minimist'; + +import { runSubcommand } from '../utils/dispatch'; +import { CliError, EXIT } from '../utils/errors'; +import { emit } from '../utils/io'; + +export const agentUsage = ` +Agent Command: + + dcrypt agent [OPTIONS] + + Lend secrets from the vault to a command, through the dcrypt desktop app, + without the master password. The app must be open and unlocked, agent access + must be on, and each item must be shared with agents. You approve every + request in the app, once or for an hour. + +Subcommands: + status Whether the app is serving agents, and if it is unlocked + run -- Run a command with secrets in its environment + +Options: + --secret ENV=item Put an item's secret in ENV (repeatable) + --secret ENV=item#field Name the field when the item has several + --as How to describe the caller in the approval prompt + --json Machine-readable output (status) + --help, -h Show this help message + +The values go into the command's environment only. They are never printed, +and never written to disk. A command that prints its environment can still +show them, so read the command before you approve it. + +Examples: + dcrypt agent status + dcrypt agent run --secret GITHUB_TOKEN=GitHub -- gh pr list + dcrypt agent run --secret PGPASSWORD="Staging DB#password" -- psql -h db.internal +`; + +/** How the caller is labelled in the prompt and the audit log: self-reported. */ +export const clientName = (argv: ParsedArgs, env: NodeJS.ProcessEnv = process.env): string => { + if (typeof argv.as === 'string' && argv.as.trim()) return argv.as.trim(); + if (env.CLAUDECODE === '1') return 'Claude Code'; + if (env.CODEX_SANDBOX || env.CODEX_SANDBOX_NETWORK_DISABLED) return 'Codex'; + return 'dcrypt agent'; +}; + +const failure = (response: Extract): CliError => { + const code = + response.code === 'locked' + ? EXIT.auth + : response.code === 'denied' + ? EXIT.permission + : response.code === 'not_found' + ? EXIT.notFound + : EXIT.usage; + return new CliError(response.message, code); +}; + +const ask: typeof askAgent = async (request, options) => { + try { + return await askAgent(request, options); + } catch (error) { + if (error instanceof AgentUnavailableError) throw new CliError(error.message, EXIT.notFound); + throw error; + } +}; + +const status = async (argv: ParsedArgs): Promise => { + const socketPath = defaultSocketPath(); + let unlocked: boolean | null = null; + try { + const response = await askAgent({ v: PROTOCOL_VERSION, op: 'status' }, { socketPath, timeoutMs: 5000 }); + if (response.ok === false) throw failure(response); + if (response.op === 'status') unlocked = response.unlocked; + } catch (error) { + if (!(error instanceof AgentUnavailableError)) throw error; + } + const serving = unlocked !== null; + emit(argv, { serving, unlocked: Boolean(unlocked), socket: socketPath }, () => + !serving + ? 'not serving: open the dcrypt app and turn on agent access in its Agents screen' + : unlocked + ? 'serving, unlocked' + : 'serving, but the vault is locked: unlock it in the dcrypt app' + ); +}; + +const specs = (argv: ParsedArgs): SecretRequest[] => { + const raw = argv.secret; + const list = Array.isArray(raw) ? raw : raw === undefined ? [] : [raw]; + if (list.length === 0) throw new CliError('name at least one secret: --secret ENV=item'); + return list.map((spec) => { + if (typeof spec !== 'string') throw new CliError('--secret takes ENV=item'); + try { + return parseSecretSpec(spec); + } catch (error) { + throw new CliError(error instanceof Error ? error.message : String(error)); + } + }); +}; + +const run = async (argv: ParsedArgs): Promise => { + const command = argv['--'] as string[] | undefined; + if (!command || command.length === 0) { + throw new CliError('nothing to run: put the command after `--`'); + } + const secrets = specs(argv); + const response = await ask( + { + v: PROTOCOL_VERSION, + op: 'env', + client: { name: clientName(argv), cwd: process.cwd(), pid: process.pid }, + command, + secrets, + }, + { socketPath: defaultSocketPath() } + ); + if (response.ok === false) throw failure(response); + if (response.op !== 'env') throw new CliError('the dcrypt app answered a different question'); + + const [bin, ...args] = command; + const result = spawnSync(bin, args, { + stdio: 'inherit', + env: { ...process.env, ...response.env }, + }); + if (result.error) throw new CliError(`failed to run ${bin}: ${result.error.message}`); + if (result.status !== 0) throw new CliError(`${bin} exited with ${result.status ?? result.signal}`, result.status ?? 1); +}; + +export const agentCommand = async (argv: ParsedArgs, prompter: Inquirerer): Promise => { + await runSubcommand(argv, prompter, { + name: 'agent', + usage: agentUsage, + handlers: { status, run }, + }); +}; diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index e133740..75ee238 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -31,6 +31,8 @@ export const options: Partial = { 'recipient', 'recipients-file', 'workspace', + 'secret', + 'as', ], // declared so that a flag never takes the positional after it as its value: // `dcrypt encrypt --binary "some text"`, `dcrypt decrypt-workspace --force finance` diff --git a/packages/vault/__tests__/vault.test.ts b/packages/vault/__tests__/vault.test.ts index 002120d..9717a69 100644 --- a/packages/vault/__tests__/vault.test.ts +++ b/packages/vault/__tests__/vault.test.ts @@ -192,4 +192,56 @@ describe('Vault', () => { expect(log.map((entry) => entry.action)).toEqual(['reveal', 'set']); await vault.lock(); }); + + it('reveals only opted-in items to agents, and audits who asked', async () => { + const file = path.join(dir, 'agents.dcrypt'); + const vault = await Vault.open({ file, passphrase: PASSPHRASE, modulePath: MODULE_PATH, kdf: FAST }); + const item = await vault.createItem('api_key', 'GitHub token'); + await vault.setField(item.id, 'token', 'token', 'ghp_example'); + + await expect(vault.revealFieldForAgent(item.id, 'token', 'Claude Code')).rejects.toThrow( + /not shared with agents/ + ); + + await vault.setAgentAccess(item.id, true); + expect(await vault.agentAccessItemIds()).toEqual([item.id]); + expect(await vault.revealFieldForAgent(item.id, 'token', 'Claude Code')).toBe('ghp_example'); + const log = await vault.auditLog(item.id); + expect(log[0]).toMatchObject({ action: 'agent_reveal', actor: 'Claude Code', fieldName: 'token' }); + + await vault.trashItem(item.id); + expect(await vault.agentAccessItemIds()).toEqual([]); + await vault.restoreItem(item.id); + + await vault.setAgentAccess(item.id, false); + await expect(vault.revealFieldForAgent(item.id, 'token', 'Claude Code')).rejects.toThrow( + /not shared with agents/ + ); + await vault.lock(); + }); + + it('upgrades a vault that predates agent access, and keeps it across a rebuild', async () => { + const file = path.join(dir, 'old.dcrypt'); + const old = await Vault.open({ file, passphrase: PASSPHRASE, modulePath: MODULE_PATH, kdf: FAST }); + const item = await old.createItem('api_key', 'Old token'); + await old.setField(item.id, 'token', 'token', 'tok-old'); + // make the snapshot look like one written before the change existed + const db = (old as unknown as { db: { exec(sql: string): Promise } }).db; + await db.exec(` + DROP FUNCTION dcrypt_vault.agent_reveal_field(uuid, text, text, text); + ALTER TABLE dcrypt_vault.audit_log DROP COLUMN actor; + DROP TABLE dcrypt_vault.agent_access; + `); + await old.lock(); + + const vault = await Vault.open({ file, passphrase: PASSPHRASE, modulePath: MODULE_PATH, kdf: FAST }); + await vault.setAgentAccess(item.id, true); + expect(await vault.revealFieldForAgent(item.id, 'token', 'Codex')).toBe('tok-old'); + + await vault.rebuild(MODULE_PATH); + expect(await vault.agentAccessItemIds()).toEqual([item.id]); + const log = await vault.auditLog(item.id); + expect(log.find((entry) => entry.action === 'agent_reveal')?.actor).toBe('Codex'); + await vault.lock(); + }); }); diff --git a/packages/vault/src/types.ts b/packages/vault/src/types.ts index da9323a..6b014e1 100644 --- a/packages/vault/src/types.ts +++ b/packages/vault/src/types.ts @@ -56,6 +56,8 @@ export interface AuditEntry { itemId: string | null; fieldName: string | null; action: string; + /** Who asked, as the caller described itself; null when it was the owner. */ + actor: string | null; occurredAt: string; } diff --git a/packages/vault/src/vault.ts b/packages/vault/src/vault.ts index 8d07272..bc48c55 100644 --- a/packages/vault/src/vault.ts +++ b/packages/vault/src/vault.ts @@ -121,7 +121,7 @@ export class Vault { ); } - await Vault.ensureSchema(db); + await Vault.ensureSchema(db, modulePath); const salt = await Vault.readDbKeySalt(db); const dbKey = deriveDbKey(passphrase, salt); @@ -170,8 +170,19 @@ export class Vault { * `deploy/schemas/dcrypt_vault/account_types.sql`, which is what a fresh * deploy and a rebuild run. */ - private static async ensureSchema(db: PGlite): Promise { + private static async ensureSchema(db: PGlite, modulePath: string): Promise { for (const statement of ADDED_ENUM_VALUES) await db.query(statement); + // later changes are written to be re-runnable, so the module's own deploy + // script is the single source of truth for upgrading an older snapshot + for (const change of ADDED_CHANGES) { + const present = await db.query<{ found: string | null }>( + 'SELECT to_regclass($1)::text AS found', + [change.probe] + ); + if (present.rows[0]?.found) continue; + const script = path.join(modulePath, 'deploy', `${change.name}.sql`); + await db.exec(await fs.readFile(script, 'utf8')); + } } /** @@ -487,6 +498,54 @@ export class Vault { return result.rows.map((row) => row.url); } + // ─── agent access ───────────────────────────────────────────────────────── + + /** + * Opt an item in to (or out of) being requested by local agents. Nothing is + * reachable by an agent until this is set; the check is enforced in SQL by + * `dcrypt_vault.agent_reveal_field`, not by callers. + */ + async setAgentAccess(itemId: string, allowed: boolean): Promise { + if (allowed) { + await this.database.query( + 'INSERT INTO dcrypt_vault.agent_access (item_id) VALUES ($1) ON CONFLICT DO NOTHING', + [itemId] + ); + } else { + await this.database.query('DELETE FROM dcrypt_vault.agent_access WHERE item_id = $1', [ + itemId, + ]); + } + await this.database.query( + 'INSERT INTO dcrypt_vault.audit_log (item_id, action) VALUES ($1, $2)', + [itemId, allowed ? 'agent_share' : 'agent_unshare'] + ); + } + + /** Ids of every item agents may ask for, trashed items excluded. */ + async agentAccessItemIds(): Promise { + const result = await this.database.query<{ item_id: string }>( + `SELECT a.item_id FROM dcrypt_vault.agent_access a + JOIN dcrypt_vault.items i ON i.id = a.item_id + WHERE i.deleted_at IS NULL + ORDER BY a.granted_at` + ); + return result.rows.map((row) => row.item_id); + } + + /** + * Reveal one field for an agent. Throws unless the item is opted in, and + * records `actor` in the audit log — the caller's own description of itself, + * which the vault cannot verify, so it is kept as a label and nothing more. + */ + async revealFieldForAgent(itemId: string, name: string, actor: string): Promise { + const result = await this.database.query<{ v: string }>( + 'SELECT dcrypt_vault.agent_reveal_field($1, $2, $3, $4) AS v', + [itemId, name, this.dbKey, actor] + ); + return result.rows[0].v; + } + // ─── audit ──────────────────────────────────────────────────────────────── async auditLog(itemId?: string): Promise { @@ -496,9 +555,10 @@ export class Vault { item_id: string | null; field_name: string | null; action: string; + actor: string | null; occurred_at: string; }>( - 'SELECT * FROM dcrypt_vault.audit_log WHERE item_id = $1 ORDER BY occurred_at DESC', + 'SELECT * FROM dcrypt_vault.audit_log WHERE item_id = $1 ORDER BY occurred_at DESC, id DESC', [itemId] ) : await this.database.query<{ @@ -506,13 +566,15 @@ export class Vault { item_id: string | null; field_name: string | null; action: string; + actor: string | null; occurred_at: string; - }>('SELECT * FROM dcrypt_vault.audit_log ORDER BY occurred_at DESC'); + }>('SELECT * FROM dcrypt_vault.audit_log ORDER BY occurred_at DESC, id DESC'); return result.rows.map((row) => ({ id: row.id, itemId: row.item_id, fieldName: row.field_name, action: row.action, + actor: row.actor ?? null, occurredAt: row.occurred_at, })); } @@ -557,6 +619,14 @@ const ADDED_ENUM_VALUES: readonly string[] = [ "ALTER TYPE dcrypt_vault.field_purpose ADD VALUE IF NOT EXISTS 'token'", ]; +/** + * pgpm changes added after vaults already existed, each re-runnable, with a + * relation whose presence proves the change was applied. See ensureSchema. + */ +const ADDED_CHANGES: readonly { name: string; probe: string }[] = [ + { name: 'schemas/dcrypt_vault/agent_access', probe: 'dcrypt_vault.agent_access' }, +]; + interface CopySpec { table: string; columns: string[]; @@ -614,9 +684,10 @@ const COPY_ORDER: CopySpec[] = [ { table: 'tags', columns: ['id', 'name'], onConflict: '(name) DO NOTHING' }, { table: 'item_tags', columns: ['item_id', 'tag_id'], onConflict: 'DO NOTHING' }, { table: 'urls', columns: ['id', 'item_id', 'url'], onConflict: 'DO NOTHING' }, + { table: 'agent_access', columns: ['item_id', 'granted_at'], onConflict: 'DO NOTHING' }, { table: 'audit_log', - columns: ['id', 'item_id', 'field_name', 'action', 'occurred_at'], + columns: ['id', 'item_id', 'field_name', 'action', 'actor', 'occurred_at'], }, ]; diff --git a/pgpm-modules/dcrypt-vault/__tests__/basic.test.ts b/pgpm-modules/dcrypt-vault/__tests__/basic.test.ts index e2e41f0..057a173 100644 --- a/pgpm-modules/dcrypt-vault/__tests__/basic.test.ts +++ b/pgpm-modules/dcrypt-vault/__tests__/basic.test.ts @@ -46,6 +46,7 @@ describe('schema', () => { WHERE table_schema = 'dcrypt_vault' ORDER BY table_name` ); expect(result.rows.map((r: { table_name: string }) => r.table_name)).toEqual([ + 'agent_access', 'audit_log', 'fields', 'folders', @@ -261,3 +262,55 @@ describe('housekeeping', () => { expect(fields.rows).toHaveLength(0); }); }); + +describe('agent access', () => { + const setSecret = async (itemId: string): Promise => { + await pg.query("SELECT dcrypt_vault.set_field($1, 'token', 'token', 'tok-123', $2, true)", [ + itemId, + KEY, + ]); + }; + + it('refuses an item that was never opted in', async () => { + const id = await createItem('api_key', 'GitHub'); + await setSecret(id); + await expect( + pg.query("SELECT dcrypt_vault.agent_reveal_field($1, 'token', $2, 'Claude Code')", [id, KEY]) + ).rejects.toThrow(/not shared with agents/); + }); + + it('reveals an opted-in item and audits who asked', async () => { + const id = await createItem('api_key', 'GitHub'); + await setSecret(id); + await pg.query('INSERT INTO dcrypt_vault.agent_access (item_id) VALUES ($1)', [id]); + const result = await pg.query<{ v: string }>( + "SELECT dcrypt_vault.agent_reveal_field($1, 'token', $2, 'Claude Code') AS v", + [id, KEY] + ); + expect(result.rows[0].v).toBe('tok-123'); + const audit = await pg.query<{ action: string; actor: string | null }>( + "SELECT action, actor FROM dcrypt_vault.audit_log WHERE item_id = $1 AND action = 'agent_reveal'", + [id] + ); + expect(audit.rows).toEqual([{ action: 'agent_reveal', actor: 'Claude Code' }]); + }); + + it('refuses a trashed item even when it was opted in', async () => { + const id = await createItem('api_key', 'GitHub'); + await setSecret(id); + await pg.query('INSERT INTO dcrypt_vault.agent_access (item_id) VALUES ($1)', [id]); + await pg.query('UPDATE dcrypt_vault.items SET deleted_at = now() WHERE id = $1', [id]); + await expect( + pg.query("SELECT dcrypt_vault.agent_reveal_field($1, 'token', $2, 'Claude Code')", [id, KEY]) + ).rejects.toThrow(/not shared with agents/); + }); + + it('refuses an anonymous caller', async () => { + const id = await createItem('api_key', 'GitHub'); + await setSecret(id); + await pg.query('INSERT INTO dcrypt_vault.agent_access (item_id) VALUES ($1)', [id]); + await expect( + pg.query("SELECT dcrypt_vault.agent_reveal_field($1, 'token', $2, '')", [id, KEY]) + ).rejects.toThrow(/must name who is asking/); + }); +}); diff --git a/pgpm-modules/dcrypt-vault/deploy/schemas/dcrypt_vault/agent_access.sql b/pgpm-modules/dcrypt-vault/deploy/schemas/dcrypt_vault/agent_access.sql new file mode 100644 index 0000000..49a2726 --- /dev/null +++ b/pgpm-modules/dcrypt-vault/deploy/schemas/dcrypt_vault/agent_access.sql @@ -0,0 +1,70 @@ +-- Deploy schemas/dcrypt_vault/agent_access to pg +-- requires: schemas/dcrypt_vault/procedures/reveal_field + +-- Which items a local agent may ask for, and a reveal path that enforces it. +-- +-- An item is never reachable by an agent until its owner opts it in, and the +-- check lives here rather than in the caller, so no code path that reveals a +-- value for an agent can skip it. Every agent reveal is audited with who asked. +-- +-- Written to be re-runnable: a vault is deployed once and later opens restore +-- its snapshot, so @decryption/vault runs this same file against vaults that +-- predate it. + +BEGIN; + +CREATE TABLE IF NOT EXISTS dcrypt_vault.agent_access ( + item_id uuid PRIMARY KEY REFERENCES dcrypt_vault.items (id) ON DELETE CASCADE, + granted_at timestamptz NOT NULL DEFAULT now() +); + +COMMENT ON TABLE dcrypt_vault.agent_access IS 'Items the owner has opted in to being requested by local agents; absent means never'; + +ALTER TABLE dcrypt_vault.audit_log ADD COLUMN IF NOT EXISTS actor text; + +COMMENT ON COLUMN dcrypt_vault.audit_log.actor IS 'Who asked, as the caller described itself; null for the owner'; + +CREATE OR REPLACE FUNCTION dcrypt_vault.agent_reveal_field( + in_item_id uuid, + in_name text, + in_key text, + in_actor text +) RETURNS text +AS $$ +DECLARE + result text; +BEGIN + IF in_actor IS NULL OR length(in_actor) = 0 THEN + RAISE EXCEPTION 'an agent reveal must name who is asking'; + END IF; + + IF NOT EXISTS ( + SELECT 1 + FROM dcrypt_vault.agent_access a + JOIN dcrypt_vault.items i ON i.id = a.item_id + WHERE a.item_id = in_item_id AND i.deleted_at IS NULL + ) THEN + RAISE EXCEPTION 'item % is not shared with agents', in_item_id + USING ERRCODE = 'insufficient_privilege'; + END IF; + + SELECT pgp_sym_decrypt(f.value_enc, in_key) + INTO result + FROM dcrypt_vault.fields f + WHERE f.item_id = in_item_id AND f.name = in_name; + + IF result IS NULL THEN + RAISE EXCEPTION 'field "%" not found on item %', in_name, in_item_id; + END IF; + + INSERT INTO dcrypt_vault.audit_log (item_id, field_name, action, actor) + VALUES (in_item_id, in_name, 'agent_reveal', in_actor); + + RETURN result; +END; +$$ +LANGUAGE plpgsql VOLATILE; + +COMMENT ON FUNCTION dcrypt_vault.agent_reveal_field IS 'Decrypt one field for a local agent: refuses unless the item is opted in, and audits who asked'; + +COMMIT; diff --git a/pgpm-modules/dcrypt-vault/pgpm.plan b/pgpm-modules/dcrypt-vault/pgpm.plan index 73df4e5..1daa017 100644 --- a/pgpm-modules/dcrypt-vault/pgpm.plan +++ b/pgpm-modules/dcrypt-vault/pgpm.plan @@ -21,3 +21,4 @@ schemas/dcrypt_vault/procedures/totp_code [schemas/dcrypt_vault/procedures/revea schemas/dcrypt_vault/procedures/search_items [schemas/dcrypt_vault/tables/urls schemas/dcrypt_vault/tables/item_tags] 2026-07-26T00:00:15Z Dan Lynch # add schemas/dcrypt_vault/procedures/search_items schemas/dcrypt_vault/account_types [schemas/dcrypt_vault/types] 2026-07-26T00:00:16Z Dan Lynch # add schemas/dcrypt_vault/account_types schemas/dcrypt_vault/passkey_types [schemas/dcrypt_vault/account_types] 2026-07-26T00:00:17Z Dan Lynch # add schemas/dcrypt_vault/passkey_types +schemas/dcrypt_vault/agent_access [schemas/dcrypt_vault/procedures/reveal_field schemas/dcrypt_vault/tables/audit_log] 2026-11-29T00:00:00Z Dan Lynch # add schemas/dcrypt_vault/agent_access diff --git a/pgpm-modules/dcrypt-vault/revert/schemas/dcrypt_vault/agent_access.sql b/pgpm-modules/dcrypt-vault/revert/schemas/dcrypt_vault/agent_access.sql new file mode 100644 index 0000000..a84ec20 --- /dev/null +++ b/pgpm-modules/dcrypt-vault/revert/schemas/dcrypt_vault/agent_access.sql @@ -0,0 +1,9 @@ +-- Revert schemas/dcrypt_vault/agent_access from pg + +BEGIN; + +DROP FUNCTION dcrypt_vault.agent_reveal_field(uuid, text, text, text); +ALTER TABLE dcrypt_vault.audit_log DROP COLUMN actor; +DROP TABLE dcrypt_vault.agent_access; + +COMMIT; diff --git a/pgpm-modules/dcrypt-vault/verify/schemas/dcrypt_vault/agent_access.sql b/pgpm-modules/dcrypt-vault/verify/schemas/dcrypt_vault/agent_access.sql new file mode 100644 index 0000000..f3e0d9e --- /dev/null +++ b/pgpm-modules/dcrypt-vault/verify/schemas/dcrypt_vault/agent_access.sql @@ -0,0 +1,9 @@ +-- Verify schemas/dcrypt_vault/agent_access on pg + +BEGIN; + +SELECT item_id, granted_at FROM dcrypt_vault.agent_access WHERE false; +SELECT actor FROM dcrypt_vault.audit_log WHERE false; +SELECT pg_catalog.has_function_privilege('dcrypt_vault.agent_reveal_field(uuid, text, text, text)', 'execute'); + +ROLLBACK; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e48152d..e09786c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -79,6 +79,9 @@ importers: "@decryption/accounts": specifier: workspace:* version: link:../../packages/accounts/dist + "@decryption/agent": + specifier: workspace:* + version: link:../../packages/agent/dist "@decryption/core": specifier: workspace:* version: link:../../packages/core/dist @@ -212,6 +215,17 @@ importers: version: 0.3.0 publishDirectory: dist + packages/agent: + dependencies: + appstash: + specifier: ^0.7.0 + version: 0.7.0 + devDependencies: + makage: + specifier: 0.3.0 + version: 0.3.0 + publishDirectory: dist + packages/base: devDependencies: "@decryption/hashes": @@ -265,6 +279,9 @@ importers: "@decryption/accounts": specifier: workspace:* version: link:../accounts/dist + "@decryption/agent": + specifier: workspace:* + version: link:../agent/dist "@decryption/base": specifier: workspace:* version: link:../base/dist @@ -17609,7 +17626,7 @@ snapshots: array-differ: 3.0.0 array-union: 2.1.0 arrify: 2.0.1 - minimatch: 3.0.5 + minimatch: 3.1.5 mute-stream@0.0.8: {}