Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
feat(cli-keyring): add @composio/cli-keyring package (#3201)
Rahul Tarak9d7cf5aca27a
diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 2a71236ea..9b0d32901 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -709,16 +709,16 @@ importers:version: link:../../packages/providers/llamaindex'@llamaindex/openai':specifier: ^0.4.20- version: 0.4.22(@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])+ version: 0.4.22(@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])'@llamaindex/workflow':specifier: ^1.1.24- version: 1.1.24(@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])+ version: 1.1.24(@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])dotenv:specifier: ^16.4.1version: 16.6.1llamaindex:specifier: ^0.12.0- version: 0.12.1(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])+ version: 0.12.1(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])devDependencies:'@types/bun':specifier: ^1.2.9@@ -1171,6 +1171,27 @@ importers:specifier: 'catalog:'version: 3.2.4(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])+ ts/packages/cli-keyring:+ devDependencies:+ '@types/node':+ specifier: ^24.0.1+ version: 24.10.13+ bun-types:+ specifier: ^1.3.11+ version: 1.3.11+ effect:+ specifier: 'catalog:'+ version: 3.19.18+ tsdown:+ specifier: 'catalog:'+ version: 0.18.4(@arethetypeswrong/[email protected])(@typescript/[email protected])([email protected])([email protected])+ typescript:+ specifier: 'catalog:'+ version: 5.9.3+ vitest:+ specifier: 'catalog:'+ version: 3.2.4(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])+ts/packages/core:dependencies:'@composio/client':@@ -1348,7 +1369,7 @@ importers:dependencies:llamaindex:specifier: ^0.12.0- version: 0.12.1(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])devDependencies:'@composio/core':specifier: workspace:*@@ -4085,6 +4106,9 @@ packages:resolution: {integrity: sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==}+ resolution: {integrity: sha512-1KGPpoxQWl9f6wcZh57LvrPIInQMn2TQ7jsgxqpRzg+l0QPOFvJVH7HmvHo/AiPgwXy+/Thf6Ov3EdVn1vOabg==}+resolution: {integrity: sha512-+UBWWOakIP4Tswh0Bt0QD0alpTY8cb5hvgiYeWCMet9YukHbzuruIEeXC2D7nMJPB12kbh8C7XJykSexEqGKJg==}@@ -7971,26 +7995,43 @@ snapshots:tree-sitter: 0.22.4web-tree-sitter: 0.24.7- '@llamaindex/[email protected](@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])':+ '@llamaindex/[email protected](@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])':dependencies:'@llamaindex/core': 0.6.22'@llamaindex/env': 0.1.30- openai: 5.23.2([email protected])([email protected])+ openai: 5.23.2([email protected])([email protected])transitivePeerDependencies:- ws- zod- '@llamaindex/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])':+ '@llamaindex/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])':optionalDependencies:- '@modelcontextprotocol/sdk': 1.26.0(@cfworker/[email protected])([email protected])+ '@modelcontextprotocol/sdk': 1.26.0(@cfworker/[email protected])([email protected])hono: 4.11.9+ zod: 3.25.76++ '@llamaindex/[email protected]([email protected])':+ optionalDependencies:zod: 4.3.6- '@llamaindex/[email protected](@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])':+ '@llamaindex/[email protected](@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])':+ dependencies:+ '@llamaindex/core': 0.6.22+ '@llamaindex/env': 0.1.30+ '@llamaindex/workflow-core': 1.3.3(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])+ transitivePeerDependencies:+ - '@modelcontextprotocol/sdk'+ - hono+ - next+ - p-retry+ - rxjs+ - zod++ '@llamaindex/[email protected](@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])':dependencies:'@llamaindex/core': 0.6.22'@llamaindex/env': 0.1.30- '@llamaindex/workflow-core': 1.3.3(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])+ '@llamaindex/workflow-core': 1.3.3([email protected])transitivePeerDependencies:- '@modelcontextprotocol/sdk'- hono@@ -9008,6 +9049,14 @@ snapshots:optionalDependencies:+ '@vitest/[email protected]([email protected](@types/[email protected])([email protected])([email protected]))':+ dependencies:+ '@vitest/spy': 3.2.4+ estree-walker: 3.0.3+ magic-string: 0.30.21+ optionalDependencies:+'@vitest/[email protected]':dependencies:tinyrainbow: 2.0.0@@ -9037,7 +9086,7 @@ snapshots:sirv: 3.0.2tinyglobby: 0.2.15tinyrainbow: 2.0.0- vitest: 3.2.4(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])+ vitest: 3.2.4(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])'@vitest/[email protected]':dependencies:@@ -9274,9 +9323,13 @@ snapshots:base64-js: 1.5.1ieee754: 1.2.1+ dependencies:+ '@types/node': 24.10.13+dependencies:- '@types/node': 22.19.11+ '@types/node': 24.10.13dependencies:@@ -10483,12 +10536,34 @@ snapshots:rfdc: 1.4.1wrap-ansi: 9.0.2- [email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected]):+ [email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected]):+ dependencies:+ '@llamaindex/core': 0.6.22+ '@llamaindex/env': 0.1.30+ '@llamaindex/node-parser': 2.0.22(@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])+ '@llamaindex/workflow': 1.1.24(@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])+ '@types/lodash': 4.17.23+ '@types/node': 24.10.13+ lodash: 4.17.23+ magic-bytes.js: 1.13.0+ transitivePeerDependencies:+ - '@huggingface/transformers'+ - '@modelcontextprotocol/sdk'+ - gpt-tokenizer+ - hono+ - next+ - p-retry+ - rxjs+ - tree-sitter+ - web-tree-sitter+ - zod+dependencies:'@llamaindex/core': 0.6.22'@llamaindex/env': 0.1.30'@llamaindex/node-parser': 2.0.22(@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])- '@llamaindex/workflow': 1.1.24(@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])+ '@llamaindex/workflow': 1.1.24(@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])'@types/lodash': 4.17.23'@types/node': 24.10.13lodash: 4.17.23@@ -10772,6 +10847,11 @@ snapshots:is-inside-container: 1.0.0wsl-utils: 0.1.0+ optionalDependencies:+ ws: 8.20.0+ zod: 3.25.76+optionalDependencies:ws: 8.20.0@@ -11870,7 +11950,7 @@ snapshots:dependencies:'@types/chai': 5.2.3'@vitest/expect': 3.2.4- '@vitest/mocker': 3.2.4([email protected](@types/[email protected])([email protected])([email protected]))+ '@vitest/mocker': 3.2.4([email protected](@types/[email protected])([email protected])([email protected]))'@vitest/pretty-format': 3.2.4'@vitest/runner': 3.2.4'@vitest/snapshot': 3.2.4diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 4fe238b7e..a61b67a02 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -7,6 +7,7 @@ packages:- ts/e2e-tests/runtimes/cloudflare/*- ts/examples/*- ts/packages/cli+ - ts/packages/cli-keyring- ts/packages/core- ts/packages/json-schema-to-zod- ts/packages/providers/*diff --git a/ts/packages/cli-keyring/README.md b/ts/packages/cli-keyring/README.mdnew file mode 100644index 000000000..f9427a120--- /dev/null+++ b/ts/packages/cli-keyring/README.md@@ -0,0 +1,232 @@+# @composio/cli-keyring++Cross-platform OS credential storage for the Composio CLI.++Structurally modeled on [keyring-rs](https://github.com/open-source-cooperative/keyring-rs) (the `keyring-core` + per-platform store-crate split), but implemented as a thin shell over OS primitives so we own every byte of the execution surface and never depend on a third-party native module.++## Why this exists++Before: `~/.composio/user_data.json` held the Composio API key as a plaintext string. Any agent (Claude Code, etc.) with file-read permission could silently `Read` the file and exfiltrate the key in a single, unobservable tool call — then use it to take actions on the Composio platform.++After: the API key lives in the OS credential store (macOS Keychain / Linux Secret Service). Reading it requires either (a) an in-process call to Security.framework / D-Bus — which only the composio binary makes, and which agents cannot invoke from their own processes — or (b) shelling out to `/usr/bin/security` / `secret-tool`, which is a visible Bash tool call the user can deny. **Silent exfil becomes visible exfil**: the gate is the agent's shell-permission prompt, not a filesystem read that leaves no trace.++## Architecture++```+src/+├── core/ # keyring-rs keyring-core port+│ ├── entry.ts # Entry class — (service, user, modifiers)+│ ├── errors.ts # KeyringError, 11-variant discriminated union+│ ├── persistence.ts # CredentialPersistence enum+│ └── store.ts # CredentialStore interface + default-store registry+└── stores/ # per-platform backends+ ├── macos-security.ts # runtime picker (Bun → FFI, Node → subprocess)+ ├── macos-security-ffi.ts # direct Security.framework via bun:ffi (fast path)+ ├── macos-security-subprocess.ts# /usr/bin/security subprocess fallback+ ├── linux-secret-tool.ts # secret-tool subprocess+ ├── unsupported.ts # Windows / BSD / … — throws NoStorageAccess+ └── shared.ts # subprocess helpers + base64 on-disk encoding+```++The core is intentionally Promise-based and depends on neither Effect nor any other framework. Effect-based callers (the Composio CLI) import `@composio/cli-keyring/effect` for a `KeyringService` layer.++## Backends and runtime dispatch++| platform | runtime | backend | read latency |+| ----------- | ------- | ------------------------------------ | ------------ |+| macOS | Bun | `SecItem*` via `bun:ffi` | **~1.4ms** |+| macOS | Node | `/usr/bin/security` subprocess | ~22ms |+| Linux | both | `secret-tool` subprocess (libsecret) | ~15–40ms |+| Windows/BSD | both | throws `NoStorageAccess` | — |++The Composio CLI ships as a compiled Bun binary, so production reads always hit the FFI path. Node is the fallback for vitest-under-Node, dev tools, and anyone importing the package outside the CLI's runtime.++## Performance++Measured 100 iterations on an Apple Silicon Mac with a warm login keychain:++| operation | subprocess | FFI (bun:ffi) | speedup |+| ------------------ | ---------- | ------------- | ------- |+| `getPassword` mean | 22.25ms | **1.46ms** | **15×** |+| `getPassword` p50 | 19.95ms | **1.14ms** | **18×** |+| `getPassword` p99 | 88.72ms | **7.39ms** | **12×** |+| `setPassword` mean | 26.61ms | **16.18ms** | 1.6× |++For reference, the legacy plaintext read was `fs.readFileSync` + `JSON.parse` at ~0.01ms. The CLI's `ComposioUserContext` resolves the key **exactly once per process** (in-memory closure cache), so most commands pay ~1.4ms startup overhead over the plaintext baseline — well below perception, and amortized to zero for commands that do any network I/O.++## Security model++### Tagged pointers++CoreFoundation uses tagged pointers — short `CFString` and other small types pack their data directly into the pointer bits, producing values above 2^53 that cannot round-trip through JavaScript `number`. Every CF/Sec FFI type in this package is declared as `FFIType.u64` and trafficked as `bigint` to preserve full 64-bit fidelity. See the doc block at the top of `macos-security-ffi.ts` for details.++### ACL story (macOS)++Keychain items have an **Access Control List** — a per-item permission record that lists which binaries can read the item without a GUI prompt.++| ACL populated with | upgrade-stable? | gates agents? |+| ------------------------------------------ | --------------------------- | ------------- |+| `[/usr/bin/security]` (subprocess default) | yes | no |+| `[composio (ad-hoc signed)]` | **no — breaks every build** | yes |+| `[composio (Developer ID signed)]` | yes | **yes** |+| **allow-any** (current FFI choice) | yes | no |++The composio CLI is currently ad-hoc signed (`Signature=adhoc`), so a per-binary ACL would invalidate the Keychain entry on every `composio upgrade` and trigger a user dialog. To avoid that, the FFI backend builds an **allow-any** ACL (the Security.framework equivalent of `security add-generic-password -A`): `SecAccessCreate` → `SecAccessCopyACLList` → `SecACLSetSimpleContents` with `applicationList=NULL` and `selector={version=0x0101, flags=0}`. The ACL is upgrade-stable because no binary identity is recorded.++This yields the same threat model as the subprocess backend: silent file exfil becomes visible shell-tool exfil, but the OS doesn't gate reads to our binary specifically. **Upgrading to per-binary ACLs requires the composio CLI to be signed with a stable Developer ID** — that's a separate operational change (Apple Developer Program cert, notarization, CI signing step). When it lands, `buildAllowAnyAccess` gets replaced with a `buildComposioOnlyAccess` variant in a single file; no public-API churn.++### Linux++The freedesktop Secret Service API has no per-binary ACL concept at all. Any process with the same UID can read any unlocked item from the session's default collection, with zero prompting. FFI into `libsecret` would give no additional threat-model protection over the `secret-tool` subprocess — just complexity. Subprocess is the correct choice on Linux.++## On-disk encoding++Both backends base64-encode every secret before handing it to the OS and prefix the encoded string with `b64:`. Reasons:++- `security -w` takes the password on argv and cannot carry binary bytes (NUL bytes truncate; newlines break parsing).+- `secret-tool store` reads one line from stdin via `g_io_channel_read_line`, which can't carry NUL bytes or embedded newlines.+- The FFI backend stores binary-safe `CFData` directly, but encoding consistently across backends means items written by the subprocess/Node path are readable by the FFI/Bun path and vice versa.++Downside: credentials written by this package are not readable as raw bytes by other keyring-rs consumers sharing the same keychain namespace (they'd see `b64:<base64>` instead of the original value). For the CLI's API-key use case this is irrelevant — only `@composio/cli-keyring` reads them.++## Linux attribute conventions (keyring-rs interop)++When `secret-tool` creates an item, the attribute keys match keyring-rs exactly: `{service, username, target}` with `target` naming the Secret Service collection (default `"default"`). Label defaults to `keyring:{user}@{service}`. This means any other Rust tool using keyring-rs on the same system can _discover_ our items (same attribute keys, interoperable lookups), even though the stored value is our `b64:`-prefixed format.++## Usage++```ts+import { Entry, createDefaultStore, setDefaultStore } from '@composio/cli-keyring';++// One-time process startup:+setDefaultStore(await createDefaultStore());++// Anywhere:+const entry = new Entry('com.composio.cli', 'default');+await entry.setPassword(apiKey);+const stored = await entry.getPassword();+await entry.deleteCredential();+```++With Effect.ts:++```ts+import { Effect, Layer } from 'effect';+import { KeyringService, KeyringLive } from '@composio/cli-keyring/effect';++const program = Effect.gen(function* () {+ const keyring = yield* KeyringService;+ yield* keyring.setPassword('com.composio.cli', 'default', apiKey);+});++program.pipe(Effect.provide(KeyringLive));+```++## Error handling++Every operation throws `KeyringError` with a discriminated `details` field. Pattern-match on the kind, don't catch generically:++```ts+try {+ const key = await entry.getPassword();+} catch (err) {+ if (err instanceof KeyringError) {+ switch (err.kind) {+ case 'NoEntry':+ /* user not logged in yet */ break;+ case 'NoStorageAccess':+ /* keyring unavailable — fall back */ break;+ case 'BadEncoding':+ /* stored bytes aren't valid UTF-8 */ break;+ // ...+ }+ }+}+```++Full variant list (mirroring `keyring-core/src/error.rs`): `PlatformFailure`, `NoStorageAccess`, `NoEntry`, `BadEncoding`, `BadDataFormat`, `BadStoreFormat`, `TooLong`, `Invalid`, `Ambiguous`, `NoDefaultStore`, `NotSupportedByStore`.++## Integration plan (Composio CLI migration)++Tracked in a follow-up PR stacked on top of this one. Summary of the intended `ComposioUserContextLive` behavior:++### Caching (Option A: in-process memoization, no cross-process cache)++- `ComposioUserContext` resolves the API key once at layer-build time via `entry.getPassword()` and holds it in a closure variable for the remainder of the process (piggybacks on the existing `userData` single-resolve pattern — no new cache layer).+- For short-lived commands this is ~1.4ms extra startup. For the `composio execute` / `composio run` hot path it's free after the first lookup.+- **No cross-process daemon**: FFI at ~1.4ms per cold process is cheap enough that tight scripting (`composio execute` in a shell loop) stays under 140ms of keychain overhead across 100 invocations.+- **Agent threat model**: a JavaScript closure inside the composio process is unreachable to other processes on the system without `ptrace`. The key never lands in an env var, never writes to a tempfile, never hits disk.++### Fallback chain++```+login(apiKey):+ if config.dangerouslySaveApiKeyInUserConfig === true:+ → write apiKey to user_data.json.api_key (plaintext; skip keyring entirely)+ else:+ try keyring.setPassword(apiKey)+ success: write user_data.json with api_key = null+ NoStorageAccess: fall back to user_data.json.api_key + one-time warning++init (read):+ read user_data.json+ if config.dangerouslySaveApiKeyInUserConfig === true:+ → use user_data.json.api_key directly, never touch keyring+ else:+ try keyring.getPassword()+ success: use it+ NoEntry:+ if user_data.json.api_key is set (legacy):+ → use it, migrate to keyring, rewrite user_data.json with api_key = null+ else:+ → user is logged out+ NoStorageAccess:+ → fall back to user_data.json.api_key with a one-time warning++logout:+ best-effort keyring.deleteCredential() (swallow NoEntry / NoStorageAccess)+ rewrite user_data.json with api_key = null+```++### The `dangerouslySaveApiKeyInUserConfig` escape hatch++Lives in `CliUserConfig` (`~/.composio/config.json`), alongside existing `experimentalFeatures` / `artifactDirectory` / `experimentalSubagent`. **Opt-in, not a CLI flag, not advertised in `--help`** — users who need it edit `config.json` themselves.++```json+{+ "experimental_features": {},+ "dangerously_save_api_key_in_user_config": true+}+```++Snake-case on disk (`dangerously_save_api_key_in_user_config`), camelCase in the TypeScript schema. The name follows React's `dangerouslySetInnerHTML` precedent: explicit about the risk, defaults to `false`.++**Why it exists**:++1. **Headless Linux** — no D-Bus session, `secret-tool` unavailable or unreliable in containers/CI/SSH-without-forwarding. Users who can't get the keyring working should have a clean opt-out rather than fighting `DBUS_SESSION_BUS_ADDRESS`.+2. **Docker / devcontainers / CI** — same story; ephemeral environments where the keyring is either absent or actively harmful.+3. **Power users who audit their config** — explicit opt-in with a name that makes the risk legible in `cat config.json`.++The `@composio/cli-keyring` package itself has no knowledge of this flag. The CLI's `ComposioUserContextLive` checks the flag at layer-build time and skips the keyring entirely when set. Package-CLI separation stays clean.++## Known limitations++- **macOS ACL is allow-any until Developer ID signing lands.** Subprocess-equivalent threat model: silent exfil → visible shell-tool exfil, but not per-binary gating. See the "ACL story" section above for the path to fix this.+- **Linux has no per-binary ACL at any layer** of the stack. Best achievable on Linux today is the `secret-tool` Bash-prompt gate.+- **`getAttributes` / `updateAttributes` / `search`** from keyring-rs's API surface are not implemented; they throw `NotSupportedByStore`. Add later if a caller needs them.+- **macOS non-`User` keychain domains** (System, Common, Dynamic) are not supported; modifier throws `NotSupportedByStore`.++## Running the tests++```bash+# Unit tests (Node, no keychain access)+pnpm test++# E2E against the real macOS keychain via subprocess backend (Node)+COMPOSIO_KEYRING_E2E=1 pnpm test++# E2E against the real macOS keychain via FFI backend (Bun)+COMPOSIO_KEYRING_E2E=1 bun --bun x vitest run test/ffi.test.ts+```++The E2E suites use UUID-suffixed service names so parallel runs and leftover entries from crashed runs never collide with real credentials.diff --git a/ts/packages/cli-keyring/eslint.config.mjs b/ts/packages/cli-keyring/eslint.config.mjsnew file mode 100644index 000000000..165e7042e--- /dev/null+++ b/ts/packages/cli-keyring/eslint.config.mjs@@ -0,0 +1,3 @@+module.exports = {+ extends: ['../../.eslintrc.cjs'],+};diff --git a/ts/packages/cli-keyring/package.json b/ts/packages/cli-keyring/package.jsonnew file mode 100644index 000000000..88fb13592--- /dev/null+++ b/ts/packages/cli-keyring/package.json@@ -0,0 +1,90 @@+{+ "name": "@composio/cli-keyring",+ "version": "0.1.0",+ "description": "Cross-platform OS credential store access for the Composio CLI (macOS Keychain, Linux Secret Service).",+ "main": "src/index.ts",+ "private": true,+ "type": "module",+ "repository": {+ "type": "git",+ "url": "https://github.com/ComposioHQ/composio.git",+ "directory": "ts/packages/cli-keyring"+ },+ "publishConfig": {+ "access": "public",+ "main": "dist/index.mjs",+ "types": "dist/index.d.mts"+ },+ "exports": {+ ".": {+ "import": {+ "types": "./dist/index.d.mts",+ "default": "./dist/index.mjs"+ },+ "require": {+ "types": "./dist/index.d.cts",+ "default": "./dist/index.cjs"+ },+ "default": {+ "types": "./dist/index.d.cts",+ "default": "./dist/index.cjs"+ }+ },+ "./effect": {+ "import": {+ "types": "./dist/effect.d.mts",+ "default": "./dist/effect.mjs"+ },+ "require": {+ "types": "./dist/effect.d.cts",+ "default": "./dist/effect.cjs"+ },+ "default": {+ "types": "./dist/effect.d.cts",+ "default": "./dist/effect.cjs"+ }+ }+ },+ "files": [+ "README.md",+ "dist"+ ],+ "scripts": {+ "clean": "git clean -xdf node_modules",+ "build": "pnpm exec tsdown",+ "test": "vitest run",+ "typecheck:src": "pnpm exec tsgo --noEmit -p ./tsconfig.src.json",+ "typecheck:test": "pnpm exec tsgo --noEmit -p ./tsconfig.test.json",+ "typecheck": "pnpm run typecheck:src && pnpm run typecheck:test",+ "typecheck:src:tsc": "tsc --noEmit -p ./tsconfig.src.json",+ "typecheck:test:tsc": "tsc --noEmit -p ./tsconfig.test.json",+ "typecheck:tsc": "pnpm run typecheck:src:tsc && pnpm run typecheck:test:tsc"+ },+ "keywords": [+ "composio",+ "keyring",+ "keychain",+ "credential",+ "secret-service",+ "libsecret"+ ],+ "author": "Composio",+ "license": "ISC",+ "packageManager": "[email protected]",+ "devDependencies": {+ "@types/node": "^24.0.1",+ "bun-types": "^1.3.11",+ "effect": "catalog:",+ "tsdown": "catalog:",+ "typescript": "catalog:",+ "vitest": "catalog:"+ },+ "peerDependencies": {+ "effect": ">=3.17.0"+ },+ "peerDependenciesMeta": {+ "effect": {+ "optional": true+ }+ }+}diff --git a/ts/packages/cli-keyring/src/core/entry.ts b/ts/packages/cli-keyring/src/core/entry.tsnew file mode 100644index 000000000..9fab9aa53--- /dev/null+++ b/ts/packages/cli-keyring/src/core/entry.ts@@ -0,0 +1,106 @@+/**+ * `Entry` — the specifier-based credential handle users interact with.+ *+ * Mirrors `keyring_core::api::Entry` / `CredentialApi`. An `Entry` is+ * just a `(service, user, modifiers)` triple that routes calls through+ * the process-global default store. There is no long-lived handle to+ * the underlying credential — every call is a round-trip to the OS.+ */++import { KeyringError } from './errors';+import { type CredentialStore, type EntryModifiers, getDefaultStore } from './store';++const textEncoder = new TextEncoder();+const textDecoder = new TextDecoder('utf-8', { fatal: true });++/**+ * Identifies a credential by `service` + `user`, with optional+ * per-store modifiers (keychain domain, Secret Service collection,+ * custom label).+ *+ * Both `service` and `user` must be non-empty — empty strings act as+ * wildcards in Keychain Services and would silently delete other+ * credentials. This mirrors keyring-rs's `Invalid` check on the macOS+ * backend and we enforce it uniformly so behavior doesn't diverge by+ * platform.+ */+export class Entry {+ readonly service: string;+ readonly user: string;+ readonly modifiers: EntryModifiers;++ /**+ * Override the store just for this entry (e.g. tests). When `null`,+ * the process-global default store is resolved on every call so that+ * `setDefaultStore` / `unsetDefaultStore` take effect immediately.+ */+ private readonly overrideStore: CredentialStore | null;++ constructor(+ service: string,+ user: string,+ modifiers: EntryModifiers = {},+ overrideStore: CredentialStore | null = null+ ) {+ if (service.length === 0) {+ throw new KeyringError({+ kind: 'Invalid',+ param: 'service',+ reason: 'service must be a non-empty string',+ });+ }+ if (user.length === 0) {+ throw new KeyringError({+ kind: 'Invalid',+ param: 'user',+ reason: 'user must be a non-empty string',+ });+ }+ this.service = service;+ this.user = user;+ this.modifiers = modifiers;+ this.overrideStore = overrideStore;+ }++ /**+ * Store `password` as UTF-8 bytes under this entry's specifier.+ * Overwrites any existing value.+ */+ async setPassword(password: string): Promise<void> {+ await this.setSecret(textEncoder.encode(password));+ }++ /**+ * Fetch the stored value and decode it as UTF-8. Throws+ * `KeyringError({ kind: 'NoEntry' })` if nothing was stored, or+ * `KeyringError({ kind: 'BadEncoding', bytes })` if the stored bytes+ * aren't valid UTF-8 — matching keyring-rs's `Error::BadEncoding`.+ */+ async getPassword(): Promise<string> {+ const bytes = await this.getSecret();+ try {+ return textDecoder.decode(bytes);+ } catch {+ throw new KeyringError({ kind: 'BadEncoding', bytes });+ }+ }++ /** Store raw bytes. */+ async setSecret(secret: Uint8Array): Promise<void> {+ await this.resolveStore().setSecret(this.service, this.user, secret, this.modifiers);+ }++ /** Fetch raw bytes. Throws `NoEntry` if nothing matches. */+ async getSecret(): Promise<Uint8Array> {+ return this.resolveStore().getSecret(this.service, this.user, this.modifiers);+ }++ /** Delete the credential. Throws `NoEntry` if it didn't exist. */+ async deleteCredential(): Promise<void> {+ await this.resolveStore().deleteCredential(this.service, this.user, this.modifiers);+ }++ private resolveStore(): CredentialStore {+ return this.overrideStore ?? getDefaultStore();+ }+}diff --git a/ts/packages/cli-keyring/src/core/errors.ts b/ts/packages/cli-keyring/src/core/errors.tsnew file mode 100644index 000000000..8f1230beb--- /dev/null+++ b/ts/packages/cli-keyring/src/core/errors.ts@@ -0,0 +1,128 @@+/**+ * Error model for `@composio/cli-keyring`.+ *+ * Mirrors the 11-variant enum from `keyring-core/src/error.rs` in+ * https://github.com/open-source-cooperative/keyring-core so that this+ * package can act as a structural TypeScript port of keyring-rs for the+ * backends we care about (macOS Keychain via `security`, Linux Secret+ * Service via `secret-tool`).+ */++import type { Entry } from './entry';++/**+ * Discriminated union of every error condition a `CredentialStore` may+ * surface. Prefer pattern-matching on `kind` rather than catching+ * `KeyringError` generically so handlers remain explicit about what they+ * tolerate (`NoEntry` on first login, for example).+ */+export type KeyringErrorDetails =+ /** The underlying store returned an unexpected runtime failure. */+ | { readonly kind: 'PlatformFailure'; readonly cause: unknown }+ /**+ * The store is present but inaccessible: keychain locked, D-Bus+ * session missing, user declined an unlock prompt, `secret-tool`+ * not installed, etc. Callers should treat this as "try a fallback+ * or warn the user" rather than "retry".+ */+ | { readonly kind: 'NoStorageAccess'; readonly cause: unknown }+ /** No credential exists for the (service, user) specifier. */+ | { readonly kind: 'NoEntry' }+ /** Retrieved bytes were not valid UTF-8 (only raised by `getPassword`). */+ | { readonly kind: 'BadEncoding'; readonly bytes: Uint8Array }+ /** Retrieved bytes didn't match the store's expected blob format. */+ | { readonly kind: 'BadDataFormat'; readonly bytes: Uint8Array; readonly cause: unknown }+ /** Store metadata itself is corrupted. */+ | { readonly kind: 'BadStoreFormat'; readonly detail: string }+ /** An attribute value exceeded the platform length limit. */+ | { readonly kind: 'TooLong'; readonly attr: string; readonly limit: number }+ /**+ * A parameter violated a store-specific rule — e.g. an empty `service`+ * or `user` on macOS (empty strings act as wildcards in Keychain+ * Services and must be rejected locally before we spawn).+ */+ | { readonly kind: 'Invalid'; readonly param: string; readonly reason: string }+ /**+ * Multiple credentials matched the (service, user) specifier. Only+ * possible on Secret Service; generic-password items on macOS are+ * unique per (service, account, keychain).+ */+ | { readonly kind: 'Ambiguous'; readonly matches: readonly Entry[] }+ /** No process-global default store has been registered. */+ | { readonly kind: 'NoDefaultStore' }+ /** The active store does not implement the requested operation. */+ | { readonly kind: 'NotSupportedByStore'; readonly operation: string };++export type KeyringErrorKind = KeyringErrorDetails['kind'];++/**+ * The single error type thrown by every operation on `Entry` or a+ * `CredentialStore`. `details` carries the variant-specific payload;+ * the base `message` is derived for human logs but callers should+ * branch on `details.kind`.+ */+export class KeyringError extends Error {+ readonly details: KeyringErrorDetails;++ constructor(details: KeyringErrorDetails) {+ super(KeyringError.formatMessage(details));+ this.name = 'KeyringError';+ this.details = details;+ // Preserve the original cause chain for PlatformFailure / NoStorageAccess+ // so `console.error(err)` prints the underlying reason.+ if ('cause' in details && details.cause !== undefined) {+ (this as { cause?: unknown }).cause = details.cause;+ }+ }++ get kind(): KeyringErrorKind {+ return this.details.kind;+ }++ /**+ * Convenience predicate — avoids `err instanceof KeyringError && err.kind === 'NoEntry'`+ * at every call site.+ */+ is<K extends KeyringErrorKind>(+ kind: K+ ): this is KeyringError & { readonly details: Extract<KeyringErrorDetails, { kind: K }> } {+ return this.details.kind === kind;+ }++ private static formatMessage(d: KeyringErrorDetails): string {+ switch (d.kind) {+ case 'NoEntry':+ return 'No matching credential was found in the store.';+ case 'NoDefaultStore':+ return 'No default keyring store has been registered for this process.';+ case 'PlatformFailure':+ return `Keyring store failure: ${describe(d.cause)}`;+ case 'NoStorageAccess':+ return `Keyring store is unavailable: ${describe(d.cause)}`;+ case 'BadEncoding':+ return `Stored credential is not valid UTF-8 (${d.bytes.byteLength} bytes).`;+ case 'BadDataFormat':+ return `Stored credential is malformed: ${describe(d.cause)}`;+ case 'BadStoreFormat':+ return `Credential store metadata is corrupted: ${d.detail}`;+ case 'TooLong':+ return `Attribute "${d.attr}" exceeds the platform limit of ${d.limit} bytes.`;+ case 'Invalid':+ return `Invalid parameter "${d.param}": ${d.reason}`;+ case 'Ambiguous':+ return `Credential specifier matched ${d.matches.length} items; expected exactly one.`;+ case 'NotSupportedByStore':+ return `Operation "${d.operation}" is not supported by the active keyring store.`;+ }+ }+}++function describe(cause: unknown): string {+ if (cause instanceof Error) return cause.message;+ if (typeof cause === 'string') return cause;+ try {+ return JSON.stringify(cause);+ } catch {+ return String(cause);+ }+}diff --git a/ts/packages/cli-keyring/src/core/persistence.ts b/ts/packages/cli-keyring/src/core/persistence.tsnew file mode 100644index 000000000..d37aa93fd--- /dev/null+++ b/ts/packages/cli-keyring/src/core/persistence.ts@@ -0,0 +1,25 @@+/**+ * Lifetime of credentials held by a store.+ *+ * Mirrors `keyring_core::api::CredentialPersistence`. Clients can query+ * `store.persistence()` to warn users when credentials will be lost on+ * logout (e.g. keyutils) vs. persisted to disk (macOS Keychain, Secret+ * Service).+ */+export const CredentialPersistence = {+ /** Credentials exist only for the lifetime of an `Entry` handle. */+ EntryOnly: 'EntryOnly',+ /** Credentials are wiped when the process exits. */+ ProcessOnly: 'ProcessOnly',+ /** Credentials persist until the user logs out of the session. */+ UntilLogout: 'UntilLogout',+ /** Credentials persist until the machine is rebooted. */+ UntilReboot: 'UntilReboot',+ /** Credentials persist until explicitly deleted. */+ UntilDelete: 'UntilDelete',+ /** Persistence characteristics are unknown. */+ Unspecified: 'Unspecified',+} as const;++export type CredentialPersistence =+ (typeof CredentialPersistence)[keyof typeof CredentialPersistence];diff --git a/ts/packages/cli-keyring/src/core/store.ts b/ts/packages/cli-keyring/src/core/store.tsnew file mode 100644index 000000000..c709bc752--- /dev/null+++ b/ts/packages/cli-keyring/src/core/store.ts@@ -0,0 +1,107 @@+/**+ * Store contract and process-global registry.+ *+ * Mirrors `keyring_core::api::CredentialStoreApi` + the+ * `set_default_store` / `get_default_store` / `unset_default_store`+ * helpers from `keyring_core::lib`. Tests can swap the default store+ * with an in-memory mock via `setDefaultStore`.+ */++import type { CredentialPersistence } from './persistence';+import { KeyringError } from './errors';++/**+ * Optional per-entry modifiers supported by this package. Not every+ * store honors every modifier:+ *+ * - `label` — human-readable label shown in Keychain Access / seahorse.+ * If omitted, stores default to `keyring:{user}@{service}`+ * to match the label format keyring-rs produces.+ * - `collection` — Secret Service collection name (Linux only).+ * Defaults to `"default"`, matching keyring-rs's `target`+ * attribute convention.+ * - `keychain` — macOS keychain domain (`User` | `System` | `Common` |+ * `Dynamic`). Defaults to `User` (the login keychain).+ */+export interface EntryModifiers {+ readonly label?: string;+ readonly collection?: string;+ readonly keychain?: 'User' | 'System' | 'Common' | 'Dynamic';+}++/**+ * The low-level operations a backend must implement. `Entry` is a thin+ * specifier wrapper that routes every call through the active store.+ *+ * All operations are async because both supported backends are+ * subprocess-based (`/usr/bin/security`, `secret-tool`). Throwing+ * `KeyringError` with a precise `kind` is required — callers need to+ * distinguish `NoEntry` from `NoStorageAccess` at minimum.+ */+export interface CredentialStore {+ /** Short identifier shown in error messages and logs. */+ readonly id: string;+ /** Vendor / platform description. */+ readonly vendor: string;++ /** Lifetime characteristics of credentials stored by this backend. */+ persistence(): CredentialPersistence;++ /**+ * Store `secret` under `(service, user)`. Overwrites any existing+ * value for the same specifier.+ */+ setSecret(+ service: string,+ user: string,+ secret: Uint8Array,+ modifiers: EntryModifiers+ ): Promise<void>;++ /**+ * Fetch the raw bytes previously stored via `setSecret`. Must throw+ * `KeyringError({ kind: 'NoEntry' })` if nothing matches.+ */+ getSecret(service: string, user: string, modifiers: EntryModifiers): Promise<Uint8Array>;++ /**+ * Remove the credential identified by `(service, user)`. Throws+ * `NoEntry` if it didn't exist.+ */+ deleteCredential(service: string, user: string, modifiers: EntryModifiers): Promise<void>;+}++// -----------------------------------------------------------------------------+// Process-global default store registry+// -----------------------------------------------------------------------------++let defaultStore: CredentialStore | null = null;++/**+ * Register the store that `new Entry(service, user)` should dispatch to.+ * The CLI calls this once at startup; tests call it to inject a mock.+ */+export function setDefaultStore(store: CredentialStore): void {+ defaultStore = store;+}++/** Clear the registered store — mostly useful for test teardown. */+export function unsetDefaultStore(): void {+ defaultStore = null;+}++/**+ * Return the active default store or throw `NoDefaultStore` if none is+ * registered. Callers that want a non-throwing check should use+ * `hasDefaultStore()` instead.+ */+export function getDefaultStore(): CredentialStore {+ if (defaultStore === null) {+ throw new KeyringError({ kind: 'NoDefaultStore' });+ }+ return defaultStore;+}++export function hasDefaultStore(): boolean {+ return defaultStore !== null;+}diff --git a/ts/packages/cli-keyring/src/effect.ts b/ts/packages/cli-keyring/src/effect.tsnew file mode 100644index 000000000..d3676cc9f--- /dev/null+++ b/ts/packages/cli-keyring/src/effect.ts@@ -0,0 +1,183 @@+/**+ * Effect.ts integration for `@composio/cli-keyring`.+ *+ * The core package is intentionally Promise-based so Node and Bun+ * consumers can use it without pulling in Effect. This entry point+ * wraps `Entry` in an Effect service so the Composio CLI (which is+ * built on Effect) can access the keyring through its normal layer+ * composition:+ *+ * ```ts+ * import { Effect, Layer } from 'effect';+ * import { KeyringService, KeyringLive } from '@composio/cli-keyring/effect';+ *+ * const program = Effect.gen(function* () {+ * const keyring = yield* KeyringService;+ * yield* keyring.setPassword('com.composio.cli', 'default', apiKey);+ * });+ *+ * program.pipe(Effect.provide(KeyringLive));+ * ```+ *+ * This module has a peer dependency on `effect`. Consumers that don't+ * use Effect should import from `@composio/cli-keyring` directly and+ * never touch this file.+ */++import { Context, Effect, Layer } from 'effect';+import { Entry } from './core/entry';+import type { KeyringError } from './core/errors';+import { createDefaultStore, type MacOSBackend } from './index';+import { type CredentialStore, type EntryModifiers, setDefaultStore } from './core/store';++/**+ * Service shape exposed to Effect consumers. Every method returns+ * `Effect.Effect<T, KeyringError>` — callers branch on+ * `Effect.catchTag`-style error handling by matching on+ * `error.details.kind`.+ */+export interface KeyringServiceShape {+ /** Store a UTF-8 password under (service, user). */+ readonly setPassword: (+ service: string,+ user: string,+ password: string,+ modifiers?: EntryModifiers+ ) => Effect.Effect<void, KeyringError>;++ /** Fetch a UTF-8 password; fails with `NoEntry` if missing. */+ readonly getPassword: (+ service: string,+ user: string,+ modifiers?: EntryModifiers+ ) => Effect.Effect<string, KeyringError>;++ /** Store raw bytes under (service, user). */+ readonly setSecret: (+ service: string,+ user: string,+ secret: Uint8Array,+ modifiers?: EntryModifiers+ ) => Effect.Effect<void, KeyringError>;++ /** Fetch raw bytes; fails with `NoEntry` if missing. */+ readonly getSecret: (+ service: string,+ user: string,+ modifiers?: EntryModifiers+ ) => Effect.Effect<Uint8Array, KeyringError>;++ /** Delete the credential; fails with `NoEntry` if missing. */+ readonly deleteCredential: (+ service: string,+ user: string,+ modifiers?: EntryModifiers+ ) => Effect.Effect<void, KeyringError>;++ /**+ * Probe whether the backing store is currently usable. Catches+ * `NoStorageAccess` to return `false` — useful for deciding whether+ * to offer keyring-backed login or fall back to on-disk config.+ */+ readonly isAvailable: Effect.Effect<boolean>;+}++/**+ * Context tag. Resolve with `yield* KeyringService` inside an+ * `Effect.gen` block.+ */+export class KeyringService extends Context.Tag('composio/cli-keyring/KeyringService')<+ KeyringService,+ KeyringServiceShape+>() {}++/**+ * Build a `KeyringServiceShape` from a concrete `CredentialStore`.+ * Factored out so tests can swap in an in-memory mock without going+ * through `setDefaultStore`.+ */+export function makeKeyringService(store: CredentialStore): KeyringServiceShape {+ const entryFor = (service: string, user: string, modifiers?: EntryModifiers): Entry =>+ new Entry(service, user, modifiers ?? {}, store);++ const unsafe = <T>(op: () => Promise<T>): Effect.Effect<T, KeyringError> =>+ Effect.tryPromise({+ try: op,+ // Store operations already throw KeyringError, so we preserve+ // the error verbatim. The `as KeyringError` cast is safe+ // because every path into this helper comes from an `Entry`+ // method or the underlying store, both of which only throw+ // KeyringError.+ catch: err => err as KeyringError,+ });++ return {+ setPassword: (service, user, password, modifiers) =>+ unsafe(() => entryFor(service, user, modifiers).setPassword(password)),+ getPassword: (service, user, modifiers) =>+ unsafe(() => entryFor(service, user, modifiers).getPassword()),+ setSecret: (service, user, secret, modifiers) =>+ unsafe(() => entryFor(service, user, modifiers).setSecret(secret)),+ getSecret: (service, user, modifiers) =>+ unsafe(() => entryFor(service, user, modifiers).getSecret()),+ deleteCredential: (service, user, modifiers) =>+ unsafe(() => entryFor(service, user, modifiers).deleteCredential()),+ isAvailable: Effect.gen(function* () {+ // Probe with a non-existent specifier — we expect NoEntry if+ // the store is healthy, NoStorageAccess if it isn't.+ const probeService = '__composio_cli_keyring_probe__';+ const probeUser = '__probe__';+ const probe = unsafe(() => new Entry(probeService, probeUser, {}, store).getSecret());+ return yield* probe.pipe(+ Effect.match({+ onSuccess: () => true,+ onFailure: err => err.details.kind === 'NoEntry',+ })+ );+ }),+ };+}++/**+ * Live layer that instantiates the platform store on effect-build and+ * registers it as the process-global default (so non-Effect callers+ * in the same process also see it). Provide this once at startup:+ *+ * ```ts+ * BunRuntime.runMain(program.pipe(Effect.provide(KeyringLive)));+ * ```+ *+ * The layer uses `Layer.effect` rather than `Layer.sync` because the+ * macOS FFI backend is dynamically imported — it must stay out of the+ * Node bundle so `bun:ffi` doesn't crash at module load. The extra+ * layer-build cost is a one-shot `import()` per process.+ */+export const KeyringLive: Layer.Layer<KeyringService> = Layer.effect(+ KeyringService,+ Effect.promise(async () => {+ const store = await createDefaultStore();+ setDefaultStore(store);+ return makeKeyringService(store);+ })+);++/**+ * Build a `KeyringLive` layer with an explicit macOS backend choice.+ * Use this instead of `KeyringLive` when the CLI lets the user pick+ * between `subprocess` (safe default) and `ffi` (experimental,+ * requires Developer ID signing). The `backend` parameter is+ * ignored on Linux and other platforms.+ */+export const KeyringLiveWithBackend = (macOSBackend: MacOSBackend): Layer.Layer<KeyringService> =>+ Layer.effect(+ KeyringService,+ Effect.promise(async () => {+ const store = await createDefaultStore({ macOSBackend });+ setDefaultStore(store);+ return makeKeyringService(store);+ })+ );++/** Layer built from an explicit store — used by tests. */+export const KeyringLayer = (store: CredentialStore): Layer.Layer<KeyringService> =>+ Layer.succeed(KeyringService, makeKeyringService(store));diff --git a/ts/packages/cli-keyring/src/index.ts b/ts/packages/cli-keyring/src/index.tsnew file mode 100644index 000000000..a6524192e--- /dev/null+++ b/ts/packages/cli-keyring/src/index.ts@@ -0,0 +1,95 @@+/**+ * `@composio/cli-keyring` — cross-platform OS credential storage for+ * the Composio CLI. Structurally modeled after+ * [keyring-rs](https://github.com/open-source-cooperative/keyring-rs)+ * but implemented as a thin shell over OS primitives so we own every+ * byte of the execution surface and never depend on a third-party+ * native module.+ *+ * Backends:+ * - **macOS (Bun runtime)**: direct Security.framework calls via+ * `bun:ffi`. ~1ms reads, no subprocess overhead, ACL = allow-any+ * (upgrade-stable; identical threat model to the subprocess+ * backend until the CLI is Developer ID-signed).+ * - **macOS (Node runtime / fallback)**: `/usr/bin/security`+ * subprocess. Same semantics, ~25ms reads.+ * - **Linux**: `secret-tool` subprocess against the freedesktop+ * Secret Service API, with keyring-rs-compatible attribute names.+ *+ * Typical usage:+ *+ * ```ts+ * import { Entry, setDefaultStore, createDefaultStore } from '@composio/cli-keyring';+ *+ * setDefaultStore(await createDefaultStore());+ *+ * const entry = new Entry('com.composio.cli', 'default');+ * await entry.setPassword(apiKey);+ * const stored = await entry.getPassword();+ * await entry.deleteCredential();+ * ```+ */++export { Entry } from './core/entry';+export { KeyringError, type KeyringErrorDetails, type KeyringErrorKind } from './core/errors';+export { CredentialPersistence } from './core/persistence';+export {+ type CredentialStore,+ type EntryModifiers,+ setDefaultStore,+ unsetDefaultStore,+ getDefaultStore,+ hasDefaultStore,+} from './core/store';++import type { CredentialStore } from './core/store';+import { createMacOSStore, createMacOSStoreSync, type MacOSBackend } from './stores/macos-security';+import { LinuxSecretToolStore } from './stores/linux-secret-tool';+import { UnsupportedPlatformStore } from './stores/unsupported';++/**+ * Instantiate the native store for the current platform (async). On+ * macOS under Bun this resolves to the fast FFI backend; under Node+ * (typically tests or tools that import this package without Bun) it+ * falls back to the `/usr/bin/security` subprocess backend. On Linux+ * it always returns the `secret-tool` subprocess backend. Unsupported+ * platforms return a store whose operations throw `NoStorageAccess`.+ *+ * Call this once at process startup, pass the result to+ * `setDefaultStore`, and use `new Entry(service, user)` everywhere.+ */+export async function createDefaultStore(+ options: { macOSBackend?: MacOSBackend } = {}+): Promise<CredentialStore> {+ switch (process.platform) {+ case 'darwin':+ return await createMacOSStore(options.macOSBackend ?? 'auto');+ case 'linux':+ return new LinuxSecretToolStore();+ default:+ return new UnsupportedPlatformStore(process.platform);+ }+}++/**+ * Synchronous fallback that never returns the FFI macOS backend —+ * useful for callers that can't await at construction time (e.g. the+ * Effect.ts `Layer.sync` variant) and are willing to accept the+ * subprocess overhead. The async `createDefaultStore()` is strongly+ * preferred in the CLI's hot path.+ */+export function createDefaultStoreSync(): CredentialStore {+ switch (process.platform) {+ case 'darwin':+ return createMacOSStoreSync();+ case 'linux':+ return new LinuxSecretToolStore();+ default:+ return new UnsupportedPlatformStore(process.platform);+ }+}++export { createMacOSStore, createMacOSStoreSync, type MacOSBackend } from './stores/macos-security';+export { MacOSSecuritySubprocessStore } from './stores/macos-security-subprocess';+export { LinuxSecretToolStore } from './stores/linux-secret-tool';+export { UnsupportedPlatformStore } from './stores/unsupported';diff --git a/ts/packages/cli-keyring/src/stores/linux-secret-tool.ts b/ts/packages/cli-keyring/src/stores/linux-secret-tool.tsnew file mode 100644index 000000000..99898d2cc--- /dev/null+++ b/ts/packages/cli-keyring/src/stores/linux-secret-tool.ts@@ -0,0 +1,259 @@+/**+ * Linux Secret Service store backed by the `secret-tool` CLI.+ *+ * This is a structural port of the `dbus-secret-service-keyring-store`+ * crate from keyring-rs. The Rust version speaks the+ * `org.freedesktop.Secret.Service` D-Bus protocol directly via the+ * `dbus-secret-service` crate; we invoke `secret-tool`, a one-line+ * wrapper shipped in the `libsecret-tools` (Debian/Ubuntu) or+ * `libsecret` (Fedora/Arch) package that exposes the exact same+ * Secret Service operations. Using the CLI keeps the execution surface+ * auditable and lets us stay off FFI entirely.+ *+ * Attribute naming follows keyring-rs for interop with any other+ * keyring-rs-based tool the user might run on the same system:+ *+ * service → the application / service name+ * username → the user / account+ * target → the Secret Service collection (default: "default")+ *+ * Labels default to `keyring:{user}@{service}`, matching+ * `dbus-secret-service-keyring-store`'s default label format.+ */++import { existsSync } from 'node:fs';+import type { CredentialStore, EntryModifiers } from '../core/store';+import { CredentialPersistence } from '../core/persistence';+import { KeyringError } from '../core/errors';+import {+ bytesToUtf8,+ decodeSecret,+ encodeSecret,+ runCommand,+ utf8ToBytes,+ type SpawnResult,+} from './shared';++const SECRET_TOOL_BIN = 'secret-tool';++function validateSpecifier(service: string, user: string): void {+ if (service.includes('\0')) {+ throw new KeyringError({+ kind: 'Invalid',+ param: 'service',+ reason: 'service must not contain NUL bytes',+ });+ }+ if (user.includes('\0')) {+ throw new KeyringError({+ kind: 'Invalid',+ param: 'user',+ reason: 'user must not contain NUL bytes',+ });+ }+}++function attributeArgs(+ service: string,+ user: string,+ modifiers: EntryModifiers+): readonly string[] {+ // Match keyring-rs's attribute keys exactly so credentials stored by+ // this package are readable by any Rust tool using keyring-rs (and+ // vice-versa) on the same session.+ return ['service', service, 'username', user, 'target', modifiers.collection ?? 'default'];+}++/**+ * Classify a spawn error into a KeyringError. We can't rely on `code`+ * alone because `secret-tool` returns `1` for almost every failure;+ * stderr text is the main signal.+ */+function classifyFailure(result: SpawnResult, operation: string): KeyringError {+ const stderr = bytesToUtf8(result.stderr).trim();++ // D-Bus errors that mean "the session bus or the secret daemon is+ // unreachable" — headless systems, containers, or SSH without a+ // running keyring. Treat as NoStorageAccess so callers can fall back+ // to on-disk config.+ if (+ stderr.includes('org.freedesktop.DBus.Error.ServiceUnknown') ||+ stderr.includes('org.freedesktop.DBus.Error.NoReply') ||+ stderr.includes('Cannot autolaunch D-Bus without X11') ||+ stderr.includes('Cannot spawn a message bus') ||+ stderr.includes('No such interface') ||+ stderr.includes('secret_service_get_sync')+ ) {+ return new KeyringError({+ kind: 'NoStorageAccess',+ cause: new Error(stderr || `${operation} failed: D-Bus Secret Service unreachable`),+ });+ }++ // "The collection does not exist" / "Prompt was dismissed" usually+ // means the user cancelled an unlock prompt.+ if (stderr.includes('dismissed') || stderr.includes('does not exist')) {+ return new KeyringError({+ kind: 'NoStorageAccess',+ cause: new Error(stderr),+ });+ }++ return new KeyringError({+ kind: 'PlatformFailure',+ cause: new Error(stderr || `${operation} failed with exit ${result.code}`),+ });+}++function missingDBus(): boolean {+ // `secret-tool` requires a session bus. When SSHing without bus+ // forwarding, neither var is set. We fail fast with a clear message+ // instead of letting the user wait for `dbus-daemon --session` to+ // time out.+ return (+ process.env.DBUS_SESSION_BUS_ADDRESS === undefined &&+ !existsSync(`/run/user/${process.getuid?.() ?? -1}/bus`)+ );+}++export class LinuxSecretToolStore implements CredentialStore {+ readonly id = 'linux-secret-tool';+ readonly vendor = 'freedesktop.org Secret Service (via secret-tool)';++ persistence(): CredentialPersistence {+ return CredentialPersistence.UntilDelete;+ }++ async setSecret(+ service: string,+ user: string,+ secret: Uint8Array,+ modifiers: EntryModifiers+ ): Promise<void> {+ validateSpecifier(service, user);+ if (missingDBus()) {+ throw new KeyringError({+ kind: 'NoStorageAccess',+ cause: new Error(+ 'D-Bus session bus not available — no DBUS_SESSION_BUS_ADDRESS and no /run/user/<uid>/bus'+ ),+ });+ }++ const encoded = encodeSecret(secret);+ const label = modifiers.label ?? defaultLabel(service, user);+ const args = ['store', '--label', label, ...attributeArgs(service, user, modifiers)];++ // `secret-tool store` reads the password from stdin (one line,+ // terminated by LF). encodeSecret returns ASCII base64 with our+ // `b64:` prefix, so it's always a single printable line.+ let result: SpawnResult;+ try {+ result = await runCommand({+ command: SECRET_TOOL_BIN,+ args,+ stdin: utf8ToBytes(encoded + '\n'),+ });+ } catch (err) {+ throw this.spawnErrorToKeyringError(err);+ }++ if (result.code === 0) return;+ throw classifyFailure(result, 'secret-tool store');+ }++ async getSecret(service: string, user: string, modifiers: EntryModifiers): Promise<Uint8Array> {+ validateSpecifier(service, user);+ if (missingDBus()) {+ throw new KeyringError({+ kind: 'NoStorageAccess',+ cause: new Error(+ 'D-Bus session bus not available — no DBUS_SESSION_BUS_ADDRESS and no /run/user/<uid>/bus'+ ),+ });+ }++ const args = ['lookup', ...attributeArgs(service, user, modifiers)];++ let result: SpawnResult;+ try {+ result = await runCommand({ command: SECRET_TOOL_BIN, args });+ } catch (err) {+ throw this.spawnErrorToKeyringError(err);+ }++ if (result.code === 0) {+ const stdout = bytesToUtf8(result.stdout);+ // `secret-tool lookup` prints the password without a trailing+ // newline when found, and prints nothing (exit 0) when not found.+ if (stdout.length === 0) {+ throw new KeyringError({ kind: 'NoEntry' });+ }+ try {+ return decodeSecret(stdout);+ } catch (err) {+ throw new KeyringError({+ kind: 'BadDataFormat',+ bytes: new Uint8Array(result.stdout),+ cause: err,+ });+ }+ }++ // Exit 1 can mean many things — stderr is the real signal.+ throw classifyFailure(result, 'secret-tool lookup');+ }++ async deleteCredential(service: string, user: string, modifiers: EntryModifiers): Promise<void> {+ validateSpecifier(service, user);+ if (missingDBus()) {+ throw new KeyringError({+ kind: 'NoStorageAccess',+ cause: new Error(+ 'D-Bus session bus not available — no DBUS_SESSION_BUS_ADDRESS and no /run/user/<uid>/bus'+ ),+ });+ }++ // `secret-tool clear` returns exit 0 regardless of whether any+ // entry matched, so we probe with `lookup` first to preserve the+ // NoEntry semantics the rest of the package relies on.+ await this.getSecret(service, user, modifiers); // throws NoEntry if missing++ const args = ['clear', ...attributeArgs(service, user, modifiers)];+ let result: SpawnResult;+ try {+ result = await runCommand({ command: SECRET_TOOL_BIN, args });+ } catch (err) {+ throw this.spawnErrorToKeyringError(err);+ }+ if (result.code === 0) return;+ throw classifyFailure(result, 'secret-tool clear');+ }++ private spawnErrorToKeyringError(err: unknown): KeyringError {+ // ENOENT from child_process means `secret-tool` isn't on PATH.+ // Surface a helpful install hint rather than the raw errno.+ if (+ typeof err === 'object' &&+ err !== null &&+ 'code' in err &&+ (err as { code?: string }).code === 'ENOENT'+ ) {+ return new KeyringError({+ kind: 'NoStorageAccess',+ cause: new Error(+ 'secret-tool not found. Install it with: ' ++ 'apt install libsecret-tools (Debian/Ubuntu) / ' ++ 'dnf install libsecret (Fedora) / ' ++ 'pacman -S libsecret (Arch)'+ ),+ });+ }+ return new KeyringError({ kind: 'NoStorageAccess', cause: err });+ }+}++function defaultLabel(service: string, user: string): string {+ return `keyring:${user}@${service}`;+}diff --git a/ts/packages/cli-keyring/src/stores/macos-security-ffi.ts b/ts/packages/cli-keyring/src/stores/macos-security-ffi.tsnew file mode 100644index 000000000..358b8dcf5--- /dev/null+++ b/ts/packages/cli-keyring/src/stores/macos-security-ffi.ts@@ -0,0 +1,606 @@+/**+ * macOS Keychain store backed by direct Security.framework calls via+ * `bun:ffi`. Structurally this is a TypeScript port of the relevant+ * subset of keyring-rs's `apple-native-keyring-store` crate — which+ * itself delegates to the `security-framework` Rust crate — but we+ * skip the Rust layer and call the C ABI directly from Bun.+ *+ * Why FFI instead of the subprocess `/usr/bin/security` CLI?+ *+ * - **Performance.** A subprocess fork/exec round-trip is ~25ms+ * median and ~150ms p99 on a warm Mac. A direct `SecItemCopyMatching`+ * call is sub-millisecond. For hot-path commands (`composio execute`,+ * `composio run`) this is a 25× improvement per invocation with+ * effectively zero tail.+ * - **Upgrade-stable ACL.** The item's access control is built with+ * `SecAccessCreate` + the "allow-any" pattern (empty trusted apps+ * list, no-prompt selector — mirrors what `security -A` produces),+ * so the ACL does not depend on the composio binary's code+ * signature. `composio upgrade` never triggers a keychain dialog.+ *+ * The allow-any ACL matches the threat model of the subprocess+ * implementation exactly: silent exfil via a plaintext file becomes+ * visible exfil via the Bash tool prompt ("claude wants to run+ * /usr/bin/security find-generic-password …"), but the OS does not+ * gate reads to our binary specifically. Upgrading this to a+ * per-binary ACL requires the `composio` binary to be signed with a+ * stable Developer ID certificate so the ACL's designated+ * requirement can survive self-update — that is a separate+ * operational PR, not handled here. When it lands, the+ * `buildAllowAnyAccess` call in `setSecret` is replaced with a+ * single call to a new `buildComposioOnlyAccess` builder that+ * constructs a `SecAccessRef` with the composio binary in the+ * trusted list. The rest of the module is unchanged.+ *+ * Pointer representation: every CoreFoundation / Security+ * reference is carried as `bigint`, never `number`. Reason: short+ * `CFString` values and other small CF types are represented as+ * **tagged pointers** in CoreFoundation — the string data is packed+ * directly into pointer bits with the high bits set as tag+ * markers, producing addresses above 2^53. JavaScript's `number`+ * type loses precision above that threshold, so a tagged pointer+ * received as `number` cannot be passed back to another FFI call+ * intact. Declaring every pointer arg/return as `FFIType.u64`+ * preserves full 64-bit fidelity via `BigInt`.+ *+ * This module must not be imported from Node — it depends on+ * `bun:ffi`. The platform picker in `macos-security.ts` is+ * responsible for loading this file only when `typeof Bun !==+ * 'undefined'`.+ */++import { dlopen, FFIType, ptr, toArrayBuffer } from 'bun:ffi';+import type { CredentialStore, EntryModifiers } from '../core/store';+import { CredentialPersistence } from '../core/persistence';+import { KeyringError } from '../core/errors';+import { bytesToUtf8, decodeSecret, encodeSecret, runCommand } from './shared';++const textEncoder = new TextEncoder();+const textDecoder = new TextDecoder('utf-8');+const SECURITY_BIN = '/usr/bin/security';++/** Encode a JS string as a NUL-terminated UTF-8 byte array (for dlopen/dlsym). */+function cstr(s: string): Uint8Array {+ return textEncoder.encode(s + '\0');+}++// -----------------------------------------------------------------------------+// Low-level dlopen / dlsym (used to resolve `kSec*` / `kCF*` extern const+// data symbols that `bun:ffi`'s normal dlopen surface doesn't expose).+// -----------------------------------------------------------------------------++const LIBSYSTEM = '/usr/lib/libSystem.B.dylib';+const SECURITY_FRAMEWORK = '/System/Library/Frameworks/Security.framework/Security';+const CORE_FOUNDATION = '/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation';++const RTLD_NOW = 0x2;++const libSystem = dlopen(LIBSYSTEM, {+ dlopen: { args: [FFIType.ptr, FFIType.i32], returns: FFIType.u64 },+ dlsym: { args: [FFIType.u64, FFIType.ptr], returns: FFIType.u64 },+});++function dlopenRaw(path: string): bigint {+ const handle = libSystem.symbols.dlopen(cstr(path), RTLD_NOW);+ if (handle === 0n) {+ throw new KeyringError({+ kind: 'PlatformFailure',+ cause: new Error(`dlopen(${path}) failed`),+ });+ }+ return handle;+}++/**+ * Resolve an extern const CFTypeRef data symbol: `dlsym` returns the+ * address of the storage slot (i.e. a pointer-to-pointer); we+ * dereference one level via `read.ptr` to get the actual CFTypeRef+ * value stored there. The symbol is stable for the process lifetime,+ * so caching the resolved BigInt is safe.+ */+function dlsymCFConstant(handle: bigint, name: string): bigint {+ const addr = libSystem.symbols.dlsym(handle, cstr(name));+ if (addr === 0n) {+ throw new KeyringError({+ kind: 'PlatformFailure',+ cause: new Error(`dlsym(${name}) failed`),+ });+ }+ // read.ptr wants a number address — the storage address from dlsym+ // is a real heap address (never tagged), so it fits in a number.+ // The VALUE we read back, however, may be a tagged pointer, so we+ // must capture it as BigInt. `read.ptr` on bun returns number;+ // instead we use a small helper that reads 8 bytes into a BigInt.+ return read64(Number(addr));+}++/**+ * Read a 64-bit little-endian value from a process address and+ * return it as BigInt. Used to dereference data-symbol slots (which+ * live at plain heap addresses) without precision loss on the+ * stored value.+ */+function read64(address: number): bigint {+ // `toArrayBuffer(ptr, offset, length)` wraps a raw pointer as an+ // ArrayBuffer view without copying. We use it for read-only access+ // to an 8-byte window, then pull the BigInt out via DataView.+ const ab = toArrayBuffer(address as unknown as never, 0, 8);+ return new DataView(ab).getBigUint64(0, true);+}++const securityHandle = dlopenRaw(SECURITY_FRAMEWORK);+const coreFoundationHandle = dlopenRaw(CORE_FOUNDATION);++// -----------------------------------------------------------------------------+// Function bindings (CoreFoundation + Security.framework)+// -----------------------------------------------------------------------------++const cf = dlopen(CORE_FOUNDATION, {+ CFStringCreateWithBytes: {+ // allocator, bytes, length, encoding, isExternalRepresentation+ args: [FFIType.u64, FFIType.ptr, FFIType.i64, FFIType.u32, FFIType.bool],+ returns: FFIType.u64,+ },+ CFStringGetCString: {+ args: [FFIType.u64, FFIType.ptr, FFIType.i64, FFIType.u32],+ returns: FFIType.bool,+ },+ CFDataCreate: {+ args: [FFIType.u64, FFIType.ptr, FFIType.i64],+ returns: FFIType.u64,+ },+ CFDataGetBytePtr: {+ args: [FFIType.u64],+ returns: FFIType.u64,+ },+ CFDataGetLength: {+ args: [FFIType.u64],+ returns: FFIType.i64,+ },+ CFDictionaryCreateMutable: {+ args: [FFIType.u64, FFIType.i64, FFIType.u64, FFIType.u64],+ returns: FFIType.u64,+ },+ CFDictionaryAddValue: {+ args: [FFIType.u64, FFIType.u64, FFIType.u64],+ returns: FFIType.void,+ },+ CFArrayGetCount: {+ args: [FFIType.u64],+ returns: FFIType.i64,+ },+ CFArrayGetValueAtIndex: {+ args: [FFIType.u64, FFIType.i64],+ returns: FFIType.u64,+ },+ CFRelease: {+ args: [FFIType.u64],+ returns: FFIType.void,+ },+ CFGetTypeID: {+ args: [FFIType.u64],+ returns: FFIType.u64,+ },+});++const sec = dlopen(SECURITY_FRAMEWORK, {+ SecItemAdd: {+ args: [FFIType.u64, FFIType.u64],+ returns: FFIType.i32,+ },+ SecItemCopyMatching: {+ args: [FFIType.u64, FFIType.u64],+ returns: FFIType.i32,+ },+ SecItemUpdate: {+ args: [FFIType.u64, FFIType.u64],+ returns: FFIType.i32,+ },+ SecItemDelete: {+ args: [FFIType.u64],+ returns: FFIType.i32,+ },+ SecCopyErrorMessageString: {+ args: [FFIType.i32, FFIType.u64],+ returns: FFIType.u64,+ },+});++// -----------------------------------------------------------------------------+// Constant resolution+// -----------------------------------------------------------------------------++/** Resolved extern CFTypeRef constants (stable for process lifetime). */+const K = {+ kSecClass: dlsymCFConstant(securityHandle, 'kSecClass'),+ kSecClassGenericPassword: dlsymCFConstant(securityHandle, 'kSecClassGenericPassword'),+ kSecAttrService: dlsymCFConstant(securityHandle, 'kSecAttrService'),+ kSecAttrAccount: dlsymCFConstant(securityHandle, 'kSecAttrAccount'),+ kSecValueData: dlsymCFConstant(securityHandle, 'kSecValueData'),+ kSecReturnData: dlsymCFConstant(securityHandle, 'kSecReturnData'),+ kSecMatchLimit: dlsymCFConstant(securityHandle, 'kSecMatchLimit'),+ kSecMatchLimitOne: dlsymCFConstant(securityHandle, 'kSecMatchLimitOne'),+ kCFBooleanTrue: dlsymCFConstant(coreFoundationHandle, 'kCFBooleanTrue'),+ kCFTypeDictionaryKeyCallBacks: BigInt(+ addressOfSymbol(coreFoundationHandle, 'kCFTypeDictionaryKeyCallBacks')+ ),+ kCFTypeDictionaryValueCallBacks: BigInt(+ addressOfSymbol(coreFoundationHandle, 'kCFTypeDictionaryValueCallBacks')+ ),+} as const;++/**+ * Return the *address* of a named data symbol (not its dereferenced+ * value). Used for the `kCFType*CallBacks` structs, which are+ * structs in static data rather than pointers — the function wants a+ * pointer TO the struct, not a pointer read out of the symbol slot.+ */+function addressOfSymbol(handle: bigint, name: string): bigint {+ const addr = libSystem.symbols.dlsym(handle, cstr(name));+ if (addr === 0n) {+ throw new KeyringError({+ kind: 'PlatformFailure',+ cause: new Error(`dlsym(${name}) failed`),+ });+ }+ return addr;+}++/** UTF-8 encoding constant for CFString. */+const kCFStringEncodingUTF8 = 0x08000100;++// -----------------------------------------------------------------------------+// OSStatus mapping+// -----------------------------------------------------------------------------++const errSecSuccess = 0;+const errSecItemNotFound = -25300;+const errSecAuthFailed = -25293;+const errSecNotAvailable = -25291;+const errSecReadOnly = -25292;+const errSecNoSuchKeychain = -25294;+const errSecInvalidKeychain = -25295;+const errSecWrPerm = -61;++const NO_STORAGE_ACCESS_STATUSES = new Set([+ errSecNotAvailable,+ errSecReadOnly,+ errSecNoSuchKeychain,+ errSecInvalidKeychain,+ errSecAuthFailed,+ errSecWrPerm,+]);++/**+ * Convert an OSStatus into a KeyringError. Uses+ * `SecCopyErrorMessageString` to pull the human-readable description+ * out of the Security framework.+ */+function osStatusToError(status: number, operation: string): KeyringError {+ if (status === errSecItemNotFound) {+ return new KeyringError({ kind: 'NoEntry' });+ }+ const message = osStatusMessage(status) ?? `${operation} failed with OSStatus ${status}`;+ if (NO_STORAGE_ACCESS_STATUSES.has(status)) {+ return new KeyringError({+ kind: 'NoStorageAccess',+ cause: new Error(message),+ });+ }+ return new KeyringError({+ kind: 'PlatformFailure',+ cause: new Error(`${operation}: ${message}`),+ });+}++function osStatusMessage(status: number): string | null {+ const cfString = sec.symbols.SecCopyErrorMessageString(status, 0n);+ if (cfString === 0n) return null;+ try {+ return cfStringToJs(cfString);+ } finally {+ cf.symbols.CFRelease(cfString);+ }+}++// -----------------------------------------------------------------------------+// CoreFoundation helpers+// -----------------------------------------------------------------------------++/**+ * A "retain pool" that releases every CF object pushed into it when+ * `release()` runs. Used to guarantee cleanup across the (potentially+ * many) CF allocations each store operation performs.+ */+class CFPool {+ private readonly refs: bigint[] = [];++ /** Push a CFTypeRef into the pool and return it unchanged for chaining. */+ retain(ref: bigint): bigint {+ if (ref !== 0n) this.refs.push(ref);+ return ref;+ }++ release(): void {+ // Release in reverse order of allocation to match object graph.+ for (let i = this.refs.length - 1; i >= 0; i--) {+ cf.symbols.CFRelease(this.refs[i]!);+ }+ this.refs.length = 0;+ }+}++/** Create a CFString from a JS string (UTF-8 bytes). Throws on allocation failure. */+function cfStringFromJs(pool: CFPool, s: string): bigint {+ const bytes = textEncoder.encode(s);+ const ref = cf.symbols.CFStringCreateWithBytes(+ 0n, // kCFAllocatorDefault+ bytes,+ BigInt(bytes.byteLength),+ kCFStringEncodingUTF8,+ false+ );+ if (ref === 0n) {+ throw new KeyringError({+ kind: 'PlatformFailure',+ cause: new Error('CFStringCreateWithBytes returned NULL'),+ });+ }+ return pool.retain(ref);+}++/** Read a CFString into a JS UTF-8 string. Only used for error messages. */+function cfStringToJs(cfString: bigint): string {+ const buf = new Uint8Array(4096);+ const ok = cf.symbols.CFStringGetCString(+ cfString,+ buf,+ BigInt(buf.byteLength),+ kCFStringEncodingUTF8+ );+ if (!ok) return '<unrepresentable>';+ const end = buf.indexOf(0);+ return textDecoder.decode(buf.subarray(0, end === -1 ? buf.byteLength : end));+}++/** Extract raw bytes from a CFData. */+function cfDataToBytes(cfData: bigint): Uint8Array {+ const length = Number(cf.symbols.CFDataGetLength(cfData));+ if (length === 0) return new Uint8Array();+ const bytePtr = cf.symbols.CFDataGetBytePtr(cfData);+ if (bytePtr === 0n) {+ throw new KeyringError({+ kind: 'PlatformFailure',+ cause: new Error('CFDataGetBytePtr returned NULL'),+ });+ }+ // CFData storage is a real heap pointer (never tagged), so the+ // BigInt value fits in JS safe integer range and we can hand it to+ // toArrayBuffer via Number. Copy into JS-owned memory so we don't+ // retain the CFData longer than necessary.+ const view = new Uint8Array(toArrayBuffer(Number(bytePtr) as unknown as never, 0, length));+ return new Uint8Array(view);+}++/** Build a mutable CFDictionary. */+function cfMutableDict(pool: CFPool): bigint {+ const dict = cf.symbols.CFDictionaryCreateMutable(+ 0n,+ 0n,+ K.kCFTypeDictionaryKeyCallBacks,+ K.kCFTypeDictionaryValueCallBacks+ );+ if (dict === 0n) {+ throw new KeyringError({+ kind: 'PlatformFailure',+ cause: new Error('CFDictionaryCreateMutable returned NULL'),+ });+ }+ return pool.retain(dict);+}++function cfDictSet(dict: bigint, key: bigint, value: bigint): void {+ cf.symbols.CFDictionaryAddValue(dict, key, value);+}++// -----------------------------------------------------------------------------+// Store implementation+// -----------------------------------------------------------------------------++function validateSpecifier(service: string, user: string): void {+ if (service.length === 0) {+ throw new KeyringError({+ kind: 'Invalid',+ param: 'service',+ reason: 'service must be a non-empty string',+ });+ }+ if (user.length === 0) {+ throw new KeyringError({+ kind: 'Invalid',+ param: 'user',+ reason: 'user must be a non-empty string',+ });+ }+ if (service.includes('\0') || user.includes('\0')) {+ throw new KeyringError({+ kind: 'Invalid',+ param: service.includes('\0') ? 'service' : 'user',+ reason: 'must not contain NUL bytes',+ });+ }+}++function defaultLabel(service: string, user: string): string {+ return `keyring:${user}@${service}`;+}++export class MacOSSecurityFFIStore implements CredentialStore {+ readonly id = 'macos-security-ffi';+ readonly vendor = 'Apple Security.framework (via bun:ffi SecItem*)';++ persistence(): CredentialPersistence {+ return CredentialPersistence.UntilDelete;+ }++ async setSecret(+ service: string,+ user: string,+ secret: Uint8Array,+ modifiers: EntryModifiers+ ): Promise<void> {+ validateSpecifier(service, user);+ if (modifiers.keychain !== undefined && modifiers.keychain !== 'User') {+ throw new KeyringError({+ kind: 'NotSupportedByStore',+ operation: `macos keychain domain "${modifiers.keychain}"`,+ });+ }++ // Writes delegate to `/usr/bin/security add-generic-password -A`+ // (subprocess) because that is the ONLY path that reliably produces+ // a genuine allow-any ACL. The Security.framework APIs+ // (SecAccessCreate + SecACLSetSimpleContents with NULL+ // applicationList + zero selector) should theoretically produce the+ // same result, but in practice the items they produce still trigger+ // the macOS trust dialog ("X wants to access key Y") when read+ // from a different binary. Apple's `security` CLI uses internal+ // codepaths that bypass this limitation.+ //+ // The write happens once per login/migration — its ~25ms cost is+ // irrelevant relative to the network round-trip that follows. The+ // hot path (reads on every `composio execute`) stays on FFI at+ // ~1ms via SecItemCopyMatching.+ const encoded = encodeSecret(secret);+ const label = modifiers.label ?? defaultLabel(service, user);++ // Delete-then-add pattern instead of `-U` (update-if-exists).+ //+ // `-U` updates the password but PRESERVES the old ACL. If the+ // entry was previously created by the FFI ACL builder (which+ // produces per-binary ACLs — see the long comment block above),+ // the old broken ACL survives the `-U` update and the allow-any+ // flag from `-A` is silently ignored. Deleting first guarantees+ // the new `add-generic-password -A` creates a fresh entry with+ // a genuine allow-any ACL.+ //+ // The delete is best-effort — if the entry doesn't exist yet+ // (first login), the delete fails with errSecItemNotFound (exit+ // 44) and we proceed to the add.+ try {+ await runCommand({+ command: SECURITY_BIN,+ args: ['delete-generic-password', '-a', user, '-s', service],+ });+ } catch {+ // Spawn failure is fine — entry may not exist.+ }++ // `-A` = allow any application to read without prompting+ // `-l` = human-readable label (shown in Keychain Access)+ // `-w` = password value (on argv — brief `ps` visibility,+ // documented in the package README)+ const args = [+ 'add-generic-password',+ '-A',+ '-a',+ user,+ '-s',+ service,+ '-l',+ label,+ '-w',+ encoded,+ ];++ let result;+ try {+ result = await runCommand({ command: SECURITY_BIN, args });+ } catch (err) {+ throw new KeyringError({ kind: 'NoStorageAccess', cause: err });+ }++ if (result.code === 0) return;++ const stderr = bytesToUtf8(result.stderr).trim();+ throw new KeyringError({+ kind: 'PlatformFailure',+ cause: new Error(stderr || `security add-generic-password failed with exit ${result.code}`),+ });+ }++ async getSecret(service: string, user: string, modifiers: EntryModifiers): Promise<Uint8Array> {+ validateSpecifier(service, user);+ if (modifiers.keychain !== undefined && modifiers.keychain !== 'User') {+ throw new KeyringError({+ kind: 'NotSupportedByStore',+ operation: `macos keychain domain "${modifiers.keychain}"`,+ });+ }++ const pool = new CFPool();+ try {+ const query = cfMutableDict(pool);+ cfDictSet(query, K.kSecClass, K.kSecClassGenericPassword);+ cfDictSet(query, K.kSecAttrService, cfStringFromJs(pool, service));+ cfDictSet(query, K.kSecAttrAccount, cfStringFromJs(pool, user));+ cfDictSet(query, K.kSecReturnData, K.kCFBooleanTrue);+ cfDictSet(query, K.kSecMatchLimit, K.kSecMatchLimitOne);++ // SecItemCopyMatching writes a CFTypeRef (here: CFDataRef because+ // kSecReturnData=true, kSecMatchLimit=One) into the 8-byte slot.+ const resultOut = new Uint8Array(8);+ const status = sec.symbols.SecItemCopyMatching(query, BigInt(ptr(resultOut)));+ if (status !== errSecSuccess) {+ throw osStatusToError(status, 'SecItemCopyMatching');+ }+ const cfData = new DataView(resultOut.buffer).getBigUint64(0, true);+ if (cfData === 0n) {+ throw new KeyringError({ kind: 'NoEntry' });+ }+ try {+ const encoded = cfDataToBytes(cfData);+ // Legacy-item compatibility: if this entry was written by a+ // pre-base64 version of the FFI backend, the bytes won't have+ // the `b64:` prefix. `decodeSecret` throws in that case; we+ // fall back to returning the raw bytes so one-time reads of+ // old entries still work (the next setPassword call+ // rewrites them in the canonical format).+ try {+ return decodeSecret(bytesToUtf8(encoded));+ } catch {+ return encoded;+ }+ } finally {+ cf.symbols.CFRelease(cfData);+ }+ } finally {+ pool.release();+ }+ }++ async deleteCredential(service: string, user: string, modifiers: EntryModifiers): Promise<void> {+ validateSpecifier(service, user);+ if (modifiers.keychain !== undefined && modifiers.keychain !== 'User') {+ throw new KeyringError({+ kind: 'NotSupportedByStore',+ operation: `macos keychain domain "${modifiers.keychain}"`,+ });+ }++ const pool = new CFPool();+ try {+ const query = cfMutableDict(pool);+ cfDictSet(query, K.kSecClass, K.kSecClassGenericPassword);+ cfDictSet(query, K.kSecAttrService, cfStringFromJs(pool, service));+ cfDictSet(query, K.kSecAttrAccount, cfStringFromJs(pool, user));++ const status = sec.symbols.SecItemDelete(query);+ if (status !== errSecSuccess) {+ throw osStatusToError(status, 'SecItemDelete');+ }+ } finally {+ pool.release();+ }+ }+}diff --git a/ts/packages/cli-keyring/src/stores/macos-security-subprocess.ts b/ts/packages/cli-keyring/src/stores/macos-security-subprocess.tsnew file mode 100644index 000000000..4d452846f--- /dev/null+++ b/ts/packages/cli-keyring/src/stores/macos-security-subprocess.ts@@ -0,0 +1,243 @@+/**+ * macOS Keychain store backed by the `/usr/bin/security` CLI.+ *+ * This is a structural port of the `apple-native-keyring-store` crate+ * from keyring-rs. The Rust version calls Security.framework via+ * `security-framework::os::macos::passwords::{find,set}_generic_password`;+ * we shell out to `/usr/bin/security`'s `add-generic-password`,+ * `find-generic-password`, and `delete-generic-password` subcommands+ * because they are 1:1 wrappers over the same Security.framework APIs,+ * ship with every macOS, and give us a trivially auditable execution+ * surface vs. FFI.+ *+ * Exit-code mapping is taken from `decode_error` in+ * `apple-native-keyring-store/src/keychain.rs`:+ *+ * errSecItemNotFound (-25300) → NoEntry+ * errSecNotAvailable (-25291) → NoStorageAccess+ * errSecReadOnly (-25292) → NoStorageAccess+ * errSecNoSuchKeychain (-25294) → NoStorageAccess+ * errSecInvalidKeychain (-25295) → NoStorageAccess+ * errSecAuthFailed (-25293) → NoStorageAccess+ * everything else → PlatformFailure+ *+ * The `security` CLI translates OSStatus values to its own exit codes+ * (typically the low byte of the OSStatus), which is why we see exit+ * 44 for item-not-found instead of -25300.+ */++import type { CredentialStore, EntryModifiers } from '../core/store';+import { CredentialPersistence } from '../core/persistence';+import { KeyringError } from '../core/errors';+import { bytesToUtf8, decodeSecret, encodeSecret, runCommand, type SpawnResult } from './shared';++const SECURITY_BIN = '/usr/bin/security';++/** `security` CLI exit code for `errSecItemNotFound`. */+const EXIT_ITEM_NOT_FOUND = 44;+/** `security` CLI exit code for `errSecDuplicateItem`. */+const EXIT_DUPLICATE_ITEM = 45;+/**+ * Exit codes that translate to `NoStorageAccess`. These correspond to+ * the OSStatus values keyring-rs's `decode_error` maps to the same+ * variant — keychain locked, read-only mount, missing/invalid keychain+ * domain, or auth failure when the user cancels an unlock prompt.+ */+const EXIT_NO_STORAGE_ACCESS = new Set([36, 37, 50, 51, 45401]);++/** Map the `keychain` modifier onto the `-A`/-domain flags of `security`. */+function domainFlag(domain: EntryModifiers['keychain']): readonly string[] {+ // The `security` CLI picks the login keychain by default, which is+ // the `User` domain. The other domains require the -A / --keychain+ // flag with a specific path; surface them as NotSupportedByStore for+ // v0 so we don't silently write to the wrong place.+ if (domain === undefined || domain === 'User') {+ return [];+ }+ throw new KeyringError({+ kind: 'NotSupportedByStore',+ operation: `macos keychain domain "${domain}"`,+ });+}++function validateSpecifier(service: string, user: string): void {+ // Empty service or user would become wildcards in Keychain Services+ // — keyring-rs throws `Error::Invalid` here and we match that.+ if (service.includes('\0')) {+ throw new KeyringError({+ kind: 'Invalid',+ param: 'service',+ reason: 'service must not contain NUL bytes',+ });+ }+ if (user.includes('\0')) {+ throw new KeyringError({+ kind: 'Invalid',+ param: 'user',+ reason: 'user must not contain NUL bytes',+ });+ }+}++function classifyExitCode(result: SpawnResult, operation: string): KeyringError {+ const code = result.code;+ const stderr = bytesToUtf8(result.stderr).trim();+ if (code === EXIT_ITEM_NOT_FOUND) {+ return new KeyringError({ kind: 'NoEntry' });+ }+ if (code !== null && EXIT_NO_STORAGE_ACCESS.has(code)) {+ return new KeyringError({+ kind: 'NoStorageAccess',+ cause: new Error(stderr || `security ${operation} failed with exit ${code}`),+ });+ }+ return new KeyringError({+ kind: 'PlatformFailure',+ cause: new Error(stderr || `security ${operation} failed with exit ${code}`),+ });+}++export class MacOSSecuritySubprocessStore implements CredentialStore {+ readonly id = 'macos-security-subprocess';+ readonly vendor = 'Apple Security.framework (via /usr/bin/security)';++ persistence(): CredentialPersistence {+ return CredentialPersistence.UntilDelete;+ }++ async setSecret(+ service: string,+ user: string,+ secret: Uint8Array,+ modifiers: EntryModifiers+ ): Promise<void> {+ validateSpecifier(service, user);+ const encoded = encodeSecret(secret);+ const label = modifiers.label ?? defaultLabel(service, user);+ const domainArgs = domainFlag(modifiers.keychain);++ // Delete-then-add pattern instead of `-U`: the `-U` flag updates+ // the password of an existing entry but PRESERVES the old ACL.+ // If a previous composio version wrote this entry with a+ // per-binary ACL (e.g. the FFI ACL builder in an earlier beta),+ // `-U` would leave that ACL in place and our `-A` flag would be+ // silently ignored. Deleting first guarantees a fresh allow-any+ // ACL on the next add.+ //+ // The delete is best-effort — if no entry exists yet (first+ // login / clean install), `security` exits with 44 (itemNotFound)+ // and we proceed to the add.+ try {+ await runCommand({+ command: SECURITY_BIN,+ args: ['delete-generic-password', '-a', user, '-s', service, ...domainArgs],+ });+ } catch {+ // Spawn failure (e.g. /usr/bin/security missing) — the add+ // below will hit the same failure and surface it properly.+ }++ // -A: allow ANY application to read this item without prompting+ // (produces a genuine allow-any ACL — the only configuration+ // that works reliably for reads from an ad-hoc signed+ // composio binary via /usr/bin/security).+ // -l: human-readable label (shown in Keychain Access).+ //+ // Password leak risk: `-w <value>` puts the secret on argv, so it+ // is briefly visible in `ps` output. This matches the behavior of+ // every OTHER tool that shells out to `security` (git credential+ // osxkeychain, 1Password CLI, etc.). Callers that can't tolerate+ // this are expected to fall back to the on-disk `~/.composio/`+ // user config — the CLI already owns that code path.+ const args = [+ 'add-generic-password',+ '-A',+ '-a',+ user,+ '-s',+ service,+ '-l',+ label,+ '-w',+ encoded,+ ...domainArgs,+ ];++ let result: SpawnResult;+ try {+ result = await runCommand({ command: SECURITY_BIN, args });+ } catch (err) {+ throw new KeyringError({ kind: 'NoStorageAccess', cause: err });+ }++ if (result.code === 0) return;++ if (result.code === EXIT_DUPLICATE_ITEM) {+ throw new KeyringError({+ kind: 'PlatformFailure',+ cause: new Error(+ 'security add-generic-password: delete-then-add produced duplicate. ' ++ 'The existing item may have an ACL that blocks deletion — ' ++ 'run `security delete-generic-password -s com.composio.cli -a default` manually.'+ ),+ });+ }+ throw classifyExitCode(result, 'add-generic-password');+ }++ async getSecret(service: string, user: string, modifiers: EntryModifiers): Promise<Uint8Array> {+ validateSpecifier(service, user);+ const domainArgs = domainFlag(modifiers.keychain);++ // -w prints the password to stdout and nothing else. Without -w,+ // `security` dumps the item's attributes in a human-readable form+ // that's painful to parse.+ const args = ['find-generic-password', '-a', user, '-s', service, '-w', ...domainArgs];++ let result: SpawnResult;+ try {+ result = await runCommand({ command: SECURITY_BIN, args });+ } catch (err) {+ throw new KeyringError({ kind: 'NoStorageAccess', cause: err });+ }++ if (result.code !== 0) {+ throw classifyExitCode(result, 'find-generic-password');+ }++ // `security -w` prints the value followed by \n. Strip exactly one+ // trailing newline — the base64 alphabet does not contain \n, so+ // any remaining whitespace would be a malformed blob.+ const stdout = bytesToUtf8(result.stdout).replace(/\n$/, '');+ try {+ return decodeSecret(stdout);+ } catch (err) {+ throw new KeyringError({+ kind: 'BadDataFormat',+ bytes: new Uint8Array(result.stdout),+ cause: err,+ });+ }+ }++ async deleteCredential(service: string, user: string, modifiers: EntryModifiers): Promise<void> {+ validateSpecifier(service, user);+ const domainArgs = domainFlag(modifiers.keychain);+ const args = ['delete-generic-password', '-a', user, '-s', service, ...domainArgs];++ let result: SpawnResult;+ try {+ result = await runCommand({ command: SECURITY_BIN, args });+ } catch (err) {+ throw new KeyringError({ kind: 'NoStorageAccess', cause: err });+ }++ if (result.code === 0) return;+ throw classifyExitCode(result, 'delete-generic-password');+ }+}++/** Default label matches the format keyring-rs generates on Linux (`keyring:{user}@{service}`). */+function defaultLabel(service: string, user: string): string {+ return `keyring:${user}@${service}`;+}diff --git a/ts/packages/cli-keyring/src/stores/macos-security.ts b/ts/packages/cli-keyring/src/stores/macos-security.tsnew file mode 100644index 000000000..856bf55fc--- /dev/null+++ b/ts/packages/cli-keyring/src/stores/macos-security.ts@@ -0,0 +1,62 @@+/**+ * macOS backend picker.+ *+ * The production CLI runs on Bun, so the FFI backend is the default+ * there — it's ~25× faster per read than the subprocess backend and+ * has no p99 tail. In Node environments (tests, dev tools that import+ * this package without Bun), `bun:ffi` is not available; we fall back+ * to the subprocess backend, which shells out to `/usr/bin/security`.+ *+ * Both backends expose the same `CredentialStore` interface so the+ * rest of the package is agnostic about which one is active.+ */++import type { CredentialStore } from '../core/store';+import { MacOSSecuritySubprocessStore } from './macos-security-subprocess';++/**+ * Backend selector for `createMacOSStore`.+ *+ * - `"auto"` / `"subprocess"`: shell out to `/usr/bin/security` for+ * every operation. ~25ms per call, no ACL dialogs, works with+ * unsigned / ad-hoc signed callers. Safe default.+ * - `"ffi"`: call Security.framework directly via `bun:ffi`. ~1ms+ * per read, but currently triggers a macOS trust dialog when the+ * calling binary is not signed with a stable Developer ID.+ * Experimental — opt-in only. Falls back to subprocess when+ * `bun:ffi` is unavailable (Node runtime).+ */+export type MacOSBackend = 'auto' | 'subprocess' | 'ffi';++const isBun = typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined';++/**+ * Resolve the appropriate macOS store for the current runtime.+ *+ * Defaults to `"auto"` which picks the subprocess backend — the only+ * path that reliably avoids macOS keychain trust dialogs for ad-hoc+ * signed binaries. Callers can opt into `"ffi"` for the ~25× perf win+ * if and only if the calling binary is signed with a stable Developer+ * ID certificate (dialogs appear otherwise).+ */+export async function createMacOSStore(backend: MacOSBackend = 'auto'): Promise<CredentialStore> {+ if (backend === 'ffi' && isBun) {+ const mod = await import('./macos-security-ffi');+ return new mod.MacOSSecurityFFIStore();+ }+ return new MacOSSecuritySubprocessStore();+}++/**+ * Synchronous variant — returns the subprocess backend unconditionally.+ * Callers that cannot await (e.g. `createDefaultStore()` used by the+ * CLI's synchronous Effect layer construction) can use this at the+ * cost of giving up the FFI opt-in.+ */+export function createMacOSStoreSync(): CredentialStore {+ return new MacOSSecuritySubprocessStore();+}++// Re-export both concrete stores for callers that want to wire a+// specific one by hand (tests, benchmarks, diagnostics).+export { MacOSSecuritySubprocessStore } from './macos-security-subprocess';diff --git a/ts/packages/cli-keyring/src/stores/shared.ts b/ts/packages/cli-keyring/src/stores/shared.tsnew file mode 100644index 000000000..58a6ff0d8--- /dev/null+++ b/ts/packages/cli-keyring/src/stores/shared.ts@@ -0,0 +1,166 @@+/**+ * Subprocess plumbing shared by the macOS and Linux stores.+ *+ * Both stores shell out to OS-provided CLIs (`/usr/bin/security` and+ * `secret-tool`) via `node:child_process`. Keeping the spawn helper+ * here means the backends only have to deal with argv construction+ * and exit-code mapping — not stream buffering.+ */++import { spawn, type SpawnOptionsWithoutStdio } from 'node:child_process';++const textEncoder = new TextEncoder();+const textDecoder = new TextDecoder('utf-8');++export interface SpawnResult {+ readonly code: number | null;+ readonly signal: NodeJS.Signals | null;+ readonly stdout: Uint8Array;+ readonly stderr: Uint8Array;+}++export interface SpawnInput {+ readonly command: string;+ readonly args: readonly string[];+ /**+ * Raw bytes to write to stdin before closing it. Used by the Linux+ * store to pipe passwords into `secret-tool store` without putting+ * them on argv.+ */+ readonly stdin?: Uint8Array;+ readonly env?: NodeJS.ProcessEnv;+}++/**+ * Concatenate an array of Uint8Arrays without going through Buffer.+ */+function concatBytes(chunks: readonly Uint8Array[]): Uint8Array {+ let total = 0;+ for (const chunk of chunks) total += chunk.byteLength;+ const out = new Uint8Array(total);+ let offset = 0;+ for (const chunk of chunks) {+ out.set(chunk, offset);+ offset += chunk.byteLength;+ }+ return out;+}++/**+ * Spawn a subprocess and return all output buffered. Resolves once+ * the process exits; never rejects — errors from failed spawns (e.g.+ * ENOENT when `secret-tool` isn't installed) surface as a rejected+ * promise with the original `Error`, which callers convert into a+ * `KeyringError({ kind: 'NoStorageAccess' })` or similar.+ */+export function runCommand(input: SpawnInput): Promise<SpawnResult> {+ return new Promise((resolve, reject) => {+ const options: SpawnOptionsWithoutStdio = {+ stdio: ['pipe', 'pipe', 'pipe'],+ env: input.env,+ };+ let child;+ try {+ child = spawn(input.command, [...input.args], options);+ } catch (err) {+ reject(err);+ return;+ }++ const stdoutChunks: Uint8Array[] = [];+ const stderrChunks: Uint8Array[] = [];++ child.stdout.on('data', (chunk: Uint8Array) => stdoutChunks.push(chunk));+ child.stderr.on('data', (chunk: Uint8Array) => stderrChunks.push(chunk));++ child.once('error', err => reject(err));+ child.once('close', (code, signal) => {+ resolve({+ code,+ signal,+ stdout: concatBytes(stdoutChunks),+ stderr: concatBytes(stderrChunks),+ });+ });++ if (input.stdin !== undefined) {+ child.stdin.end(input.stdin);+ } else {+ child.stdin.end();+ }+ });+}++/** Decode a byte slice as UTF-8. */+export function bytesToUtf8(bytes: Uint8Array): string {+ return textDecoder.decode(bytes);+}++/** Encode a JS string as UTF-8 bytes. */+export function utf8ToBytes(s: string): Uint8Array {+ return textEncoder.encode(s);+}++/**+ * Universal on-disk encoding for stored secrets. We base64-encode+ * every secret before handing it to `security` / `secret-tool` because:+ *+ * 1. `security -w` takes the password on argv and cannot carry binary+ * bytes (NUL bytes truncate; newlines break parsing).+ * 2. `secret-tool store` reads one line from stdin via+ * `g_io_channel_read_line`, which can't carry NUL bytes or embedded+ * newlines either.+ *+ * The tradeoff is that credentials written by this package are NOT+ * readable by other tools that share the same keychain namespace —+ * they'll see `<base64 blob>` instead of the original value. For the+ * CLI's use case (our own API key) that's fine, and the prefix tag+ * keeps us honest about what we're doing.+ */+const STORAGE_PREFIX = 'b64:';++/**+ * Encode bytes to base64 via `btoa` on a binary latin-1 string —+ * avoids `Buffer` and works in every runtime that provides the HTML5+ * `btoa` global (Node 16+, Bun, browsers).+ */+function bytesToBase64(bytes: Uint8Array): string {+ let binary = '';+ for (let i = 0; i < bytes.byteLength; i++) {+ binary += String.fromCharCode(bytes[i]!);+ }+ return btoa(binary);+}++function base64ToBytes(b64: string): Uint8Array {+ const binary = atob(b64);+ const bytes = new Uint8Array(binary.length);+ for (let i = 0; i < binary.length; i++) {+ bytes[i] = binary.charCodeAt(i);+ }+ return bytes;+}++/** Encode raw bytes into the on-disk format. */+export function encodeSecret(secret: Uint8Array): string {+ return STORAGE_PREFIX + bytesToBase64(secret);+}++/**+ * Decode the on-disk format back into raw bytes. Throws a plain+ * `Error` on malformed input; callers wrap it in+ * `KeyringError({ kind: 'BadDataFormat' })`.+ */+export function decodeSecret(stored: string): Uint8Array {+ const trimmed = stored.replace(/\n$/, '');+ if (!trimmed.startsWith(STORAGE_PREFIX)) {+ throw new Error(`expected keyring value to start with "${STORAGE_PREFIX}" prefix`);+ }+ const encoded = trimmed.slice(STORAGE_PREFIX.length);+ // Strict validation — `atob` is lenient and malformed blobs would+ // silently decode to truncated garbage otherwise.+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(encoded)) {+ throw new Error('keyring value contains non-base64 characters');+ }+ return base64ToBytes(encoded);+}diff --git a/ts/packages/cli-keyring/src/stores/unsupported.ts b/ts/packages/cli-keyring/src/stores/unsupported.tsnew file mode 100644index 000000000..f7b20e418--- /dev/null+++ b/ts/packages/cli-keyring/src/stores/unsupported.ts@@ -0,0 +1,44 @@+/**+ * Fallback store used on unsupported platforms (Windows, BSDs, …).+ *+ * Every operation throws `KeyringError({ kind: 'NoStorageAccess' })`+ * so the CLI can fall back to the legacy on-disk config without the+ * platform check leaking into caller code.+ */++import type { CredentialStore } from '../core/store';+import { CredentialPersistence } from '../core/persistence';+import { KeyringError } from '../core/errors';++export class UnsupportedPlatformStore implements CredentialStore {+ readonly id = 'unsupported';+ readonly vendor: string;++ constructor(platform: string) {+ this.vendor = `unsupported platform (${platform})`;+ }++ persistence(): CredentialPersistence {+ return CredentialPersistence.Unspecified;+ }++ async setSecret(): Promise<void> {+ throw this.unavailable();+ }+ async getSecret(): Promise<never> {+ throw this.unavailable();+ }+ async deleteCredential(): Promise<void> {+ throw this.unavailable();+ }++ private unavailable(): KeyringError {+ return new KeyringError({+ kind: 'NoStorageAccess',+ cause: new Error(+ `@composio/cli-keyring does not yet support ${this.vendor}. ` ++ 'Only macOS (Keychain via /usr/bin/security) and Linux (Secret Service via secret-tool) are implemented.'+ ),+ });+ }+}diff --git a/ts/packages/cli-keyring/test/e2e.test.ts b/ts/packages/cli-keyring/test/e2e.test.tsnew file mode 100644index 000000000..d834728d8--- /dev/null+++ b/ts/packages/cli-keyring/test/e2e.test.ts@@ -0,0 +1,67 @@+/**+ * Real-keystore roundtrip test.+ *+ * Gated behind `COMPOSIO_KEYRING_E2E=1` so CI and the default+ * `pnpm test` run don't touch the user's keychain. Run locally with:+ *+ * COMPOSIO_KEYRING_E2E=1 pnpm --filter @composio/cli-keyring test+ *+ * Each test uses a UUID-suffixed service name so parallel runs (and+ * leftover entries from crashed runs) never collide with the user's+ * real credentials.+ */++import { describe, it, expect, afterAll, beforeAll } from 'vitest';+import { randomUUID } from 'node:crypto';+import { Entry } from '../src/core/entry';+import { KeyringError } from '../src/core/errors';+import { createDefaultStore, setDefaultStore } from '../src/index';++const enabled = process.env.COMPOSIO_KEYRING_E2E === '1';+const suite = enabled ? describe : describe.skip;++suite('e2e: real OS keystore', () => {+ beforeAll(async () => {+ setDefaultStore(await createDefaultStore());+ });++ const service = `com.composio.cli.test.${randomUUID()}`;+ const user = 'default';+ const entry = new Entry(service, user);++ afterAll(async () => {+ try {+ await entry.deleteCredential();+ } catch (err) {+ if (!(err instanceof KeyringError) || err.kind !== 'NoEntry') {+ throw err;+ }+ }+ });++ it('roundtrips a password', async () => {+ const password = `test-${randomUUID()}`;+ await entry.setPassword(password);+ expect(await entry.getPassword()).toBe(password);+ });++ it('overwrites on repeated setPassword', async () => {+ await entry.setPassword('first');+ await entry.setPassword('second');+ expect(await entry.getPassword()).toBe('second');+ });++ it('delete then get throws NoEntry', async () => {+ await entry.setPassword('x');+ await entry.deleteCredential();+ await expect(entry.getPassword()).rejects.toSatisfy(+ (err: unknown) => err instanceof KeyringError && err.kind === 'NoEntry'+ );+ });++ it('roundtrips binary bytes', async () => {+ const bytes = new Uint8Array([0, 1, 2, 3, 255, 254, 253]);+ await entry.setSecret(bytes);+ expect(Array.from(await entry.getSecret())).toEqual(Array.from(bytes));+ });+});diff --git a/ts/packages/cli-keyring/test/entry.test.ts b/ts/packages/cli-keyring/test/entry.test.tsnew file mode 100644index 000000000..2fa1cecb0--- /dev/null+++ b/ts/packages/cli-keyring/test/entry.test.ts@@ -0,0 +1,131 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { Entry } from '../src/core/entry';+import { KeyringError } from '../src/core/errors';+import {+ type CredentialStore,+ setDefaultStore,+ unsetDefaultStore,+ hasDefaultStore,+ getDefaultStore,+} from '../src/core/store';+import { CredentialPersistence } from '../src/core/persistence';++/**+ * In-memory store used by every unit test. Lets us exercise Entry's+ * routing and validation logic without shelling out to a real keystore.+ */+class MemoryStore implements CredentialStore {+ readonly id = 'memory';+ readonly vendor = 'test in-memory';+ private readonly items = new Map<string, Uint8Array>();++ persistence() {+ return CredentialPersistence.ProcessOnly;+ }++ private key(service: string, user: string) {+ return `${service}\0${user}`;+ }++ async setSecret(service: string, user: string, secret: Uint8Array) {+ this.items.set(this.key(service, user), new Uint8Array(secret));+ }++ async getSecret(service: string, user: string) {+ const v = this.items.get(this.key(service, user));+ if (v === undefined) throw new KeyringError({ kind: 'NoEntry' });+ return v;+ }++ async deleteCredential(service: string, user: string) {+ if (!this.items.delete(this.key(service, user))) {+ throw new KeyringError({ kind: 'NoEntry' });+ }+ }+}++describe('Entry', () => {+ let store: MemoryStore;++ beforeEach(() => {+ store = new MemoryStore();+ setDefaultStore(store);+ });++ afterEach(() => {+ unsetDefaultStore();+ });++ it('rejects empty service', () => {+ expect(() => new Entry('', 'user')).toThrowError(KeyringError);+ try {+ new Entry('', 'user');+ } catch (err) {+ expect(err).toBeInstanceOf(KeyringError);+ expect((err as KeyringError).kind).toBe('Invalid');+ }+ });++ it('rejects empty user', () => {+ expect(() => new Entry('svc', '')).toThrowError(KeyringError);+ });++ it('roundtrips a UTF-8 password', async () => {+ const entry = new Entry('com.composio.cli', 'default');+ await entry.setPassword('hunter2-😀');+ expect(await entry.getPassword()).toBe('hunter2-😀');+ });++ it('throws NoEntry when reading a missing credential', async () => {+ const entry = new Entry('com.composio.cli', 'nobody');+ await expect(entry.getPassword()).rejects.toSatisfy(+ (err: unknown) => err instanceof KeyringError && err.kind === 'NoEntry'+ );+ });++ it('throws BadEncoding when stored bytes are not valid UTF-8', async () => {+ const entry = new Entry('com.composio.cli', 'binaryuser');+ await entry.setSecret(new Uint8Array([0xff, 0xfe, 0xfd]));+ await expect(entry.getPassword()).rejects.toSatisfy(+ (err: unknown) => err instanceof KeyringError && err.kind === 'BadEncoding'+ );+ });++ it('roundtrips raw binary bytes', async () => {+ const entry = new Entry('com.composio.cli', 'binaryuser');+ const bytes = new Uint8Array([0, 1, 2, 3, 4, 255]);+ await entry.setSecret(bytes);+ const got = await entry.getSecret();+ expect(Array.from(got)).toEqual(Array.from(bytes));+ });++ it('deleteCredential removes the entry and future reads throw NoEntry', async () => {+ const entry = new Entry('com.composio.cli', 'default');+ await entry.setPassword('secret');+ await entry.deleteCredential();+ await expect(entry.getPassword()).rejects.toSatisfy(+ (err: unknown) => err instanceof KeyringError && err.kind === 'NoEntry'+ );+ });++ it('overrides the default store via constructor argument', async () => {+ const other = new MemoryStore();+ const entry = new Entry('svc', 'user', {}, other);+ await entry.setPassword('x');+ // Default store should still be empty.+ await expect(new Entry('svc', 'user').getPassword()).rejects.toSatisfy(+ (err: unknown) => err instanceof KeyringError && err.kind === 'NoEntry'+ );+ expect(await entry.getPassword()).toBe('x');+ });++ it('throws NoDefaultStore when no store is registered', async () => {+ unsetDefaultStore();+ expect(hasDefaultStore()).toBe(false);+ expect(() => getDefaultStore()).toThrowError(KeyringError);+ const entry = new Entry('svc', 'user');+ await expect(entry.getPassword()).rejects.toSatisfy(+ (err: unknown) => err instanceof KeyringError && err.kind === 'NoDefaultStore'+ );+ });+});diff --git a/ts/packages/cli-keyring/test/errors.test.ts b/ts/packages/cli-keyring/test/errors.test.tsnew file mode 100644index 000000000..72d24b75c--- /dev/null+++ b/ts/packages/cli-keyring/test/errors.test.ts@@ -0,0 +1,42 @@+import { describe, it, expect } from 'vitest';+import { KeyringError } from '../src/core/errors';++describe('KeyringError', () => {+ it('exposes kind via getter and .is() predicate', () => {+ const err = new KeyringError({ kind: 'NoEntry' });+ expect(err.kind).toBe('NoEntry');+ expect(err.is('NoEntry')).toBe(true);+ expect(err.is('PlatformFailure')).toBe(false);+ });++ it('preserves the underlying cause chain for PlatformFailure', () => {+ const inner = new Error('boom');+ const err = new KeyringError({ kind: 'PlatformFailure', cause: inner });+ expect((err as { cause?: unknown }).cause).toBe(inner);+ expect(err.message).toContain('boom');+ });++ it('formats a readable message for every variant', () => {+ const cases: KeyringError[] = [+ new KeyringError({ kind: 'NoEntry' }),+ new KeyringError({ kind: 'NoDefaultStore' }),+ new KeyringError({ kind: 'PlatformFailure', cause: new Error('x') }),+ new KeyringError({ kind: 'NoStorageAccess', cause: 'locked' }),+ new KeyringError({ kind: 'BadEncoding', bytes: new Uint8Array([0xff, 0xfe]) }),+ new KeyringError({+ kind: 'BadDataFormat',+ bytes: new Uint8Array(),+ cause: new Error('nope'),+ }),+ new KeyringError({ kind: 'BadStoreFormat', detail: 'corrupt' }),+ new KeyringError({ kind: 'TooLong', attr: 'service', limit: 1024 }),+ new KeyringError({ kind: 'Invalid', param: 'user', reason: 'empty' }),+ new KeyringError({ kind: 'Ambiguous', matches: [] }),+ new KeyringError({ kind: 'NotSupportedByStore', operation: 'updateAttributes' }),+ ];+ for (const err of cases) {+ expect(err.message.length).toBeGreaterThan(0);+ expect(err.name).toBe('KeyringError');+ }+ });+});diff --git a/ts/packages/cli-keyring/test/ffi.test.ts b/ts/packages/cli-keyring/test/ffi.test.tsnew file mode 100644index 000000000..d12794059--- /dev/null+++ b/ts/packages/cli-keyring/test/ffi.test.ts@@ -0,0 +1,113 @@+/**+ * FFI-backend roundtrip test — exercises the real `bun:ffi`+ * `SecItem*` path against the live macOS keychain.+ *+ * Gated twice: the test only runs when+ *+ * - we are in Bun (`globalThis.Bun !== undefined`), AND+ * - `COMPOSIO_KEYRING_E2E=1` is set in the env.+ *+ * The first gate keeps the file inert when vitest runs under Node+ * (where importing `bun:ffi` would crash at module load). The second+ * keeps CI and the default `pnpm test` run from touching the user's+ * real keychain.+ *+ * Run locally with:+ *+ * COMPOSIO_KEYRING_E2E=1 bun --bun x vitest run test/ffi.test.ts+ */++import { describe, it, expect, beforeAll, afterAll } from 'vitest';+import { randomUUID } from 'node:crypto';+import { Entry } from '../src/core/entry';+import { KeyringError } from '../src/core/errors';+import { setDefaultStore, unsetDefaultStore } from '../src/core/store';+import type { CredentialStore } from '../src/core/store';++const underBun = typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined';+const enabled = underBun && process.env.COMPOSIO_KEYRING_E2E === '1';+const suite = enabled ? describe : describe.skip;++suite('ffi: MacOSSecurityFFIStore roundtrip', () => {+ let store: CredentialStore;++ beforeAll(async () => {+ // Import dynamically — never touch this module from Node.+ const mod = await import('../src/stores/macos-security-ffi');+ store = new mod.MacOSSecurityFFIStore();+ setDefaultStore(store);+ });++ afterAll(() => {+ unsetDefaultStore();+ });++ it('reports the expected id and vendor', () => {+ expect(store.id).toBe('macos-security-ffi');+ expect(store.vendor).toContain('bun:ffi');+ });++ it('roundtrips a password', async () => {+ const entry = new Entry(`com.composio.cli.ffi.${randomUUID()}`, 'default');+ try {+ const password = `ffi-${randomUUID()}`;+ await entry.setPassword(password);+ expect(await entry.getPassword()).toBe(password);+ } finally {+ try {+ await entry.deleteCredential();+ } catch {+ /* best-effort cleanup */+ }+ }+ });++ it('overwrites on repeated setPassword without duplicate error', async () => {+ const entry = new Entry(`com.composio.cli.ffi.${randomUUID()}`, 'default');+ try {+ await entry.setPassword('first');+ await entry.setPassword('second');+ await entry.setPassword('third');+ expect(await entry.getPassword()).toBe('third');+ } finally {+ try {+ await entry.deleteCredential();+ } catch {+ /* best-effort cleanup */+ }+ }+ });++ it('throws NoEntry for a missing credential', async () => {+ const entry = new Entry(`com.composio.cli.ffi.nonexistent.${randomUUID()}`, 'default');+ await expect(entry.getPassword()).rejects.toSatisfy(+ (err: unknown) => err instanceof KeyringError && err.kind === 'NoEntry'+ );+ });++ it('roundtrips arbitrary binary bytes', async () => {+ const entry = new Entry(`com.composio.cli.ffi.bin.${randomUUID()}`, 'default');+ try {+ const bytes = new Uint8Array(256);+ for (let i = 0; i < 256; i++) bytes[i] = i;+ await entry.setSecret(bytes);+ const got = await entry.getSecret();+ expect(Array.from(got)).toEqual(Array.from(bytes));+ } finally {+ try {+ await entry.deleteCredential();+ } catch {+ /* best-effort cleanup */+ }+ }+ });++ it('delete then read throws NoEntry', async () => {+ const entry = new Entry(`com.composio.cli.ffi.del.${randomUUID()}`, 'default');+ await entry.setPassword('x');+ await entry.deleteCredential();+ await expect(entry.getPassword()).rejects.toSatisfy(+ (err: unknown) => err instanceof KeyringError && err.kind === 'NoEntry'+ );+ });+});diff --git a/ts/packages/cli-keyring/test/shared.test.ts b/ts/packages/cli-keyring/test/shared.test.tsnew file mode 100644index 000000000..361785377--- /dev/null+++ b/ts/packages/cli-keyring/test/shared.test.ts@@ -0,0 +1,36 @@+import { describe, it, expect } from 'vitest';+import { encodeSecret, decodeSecret } from '../src/stores/shared';++describe('shared encoding', () => {+ it('roundtrips arbitrary bytes through base64 with the b64: prefix', () => {+ const inputs: Uint8Array[] = [+ new Uint8Array(),+ new Uint8Array([0]),+ new Uint8Array([1, 2, 3, 4, 5]),+ new Uint8Array([0xff, 0xfe, 0xfd]),+ new Uint8Array(Buffer.from('plain string', 'utf8')),+ new Uint8Array(Buffer.from('password with spaces\nand newline', 'utf8')),+ // 1 KiB of pseudo-random data+ crypto.getRandomValues(new Uint8Array(1024)),+ ];+ for (const bytes of inputs) {+ const encoded = encodeSecret(bytes);+ expect(encoded.startsWith('b64:')).toBe(true);+ const decoded = decodeSecret(encoded);+ expect(Array.from(decoded)).toEqual(Array.from(bytes));+ }+ });++ it('tolerates a trailing newline from CLI stdout', () => {+ const encoded = encodeSecret(new Uint8Array([1, 2, 3]));+ expect(Array.from(decodeSecret(encoded + '\n'))).toEqual([1, 2, 3]);+ });++ it('rejects blobs without the b64: prefix', () => {+ expect(() => decodeSecret('no-prefix-here')).toThrowError();+ });++ it('rejects blobs with non-base64 characters after the prefix', () => {+ expect(() => decodeSecret('b64:!!!not-base64!!!')).toThrowError();+ });+});diff --git a/ts/packages/cli-keyring/tsconfig.json b/ts/packages/cli-keyring/tsconfig.jsonnew file mode 100644index 000000000..92abc2696--- /dev/null+++ b/ts/packages/cli-keyring/tsconfig.json@@ -0,0 +1,8 @@+{+ "$schema": "https://json.schemastore.org/tsconfig",+ "extends": "./tsconfig.options.json",+ "compilerOptions": {+ "rootDir": "."+ },+ "include": ["src/**/*", "test/**/*", "package.json"]+}diff --git a/ts/packages/cli-keyring/tsconfig.options.json b/ts/packages/cli-keyring/tsconfig.options.jsonnew file mode 100644index 000000000..bf41cb9a7--- /dev/null+++ b/ts/packages/cli-keyring/tsconfig.options.json@@ -0,0 +1,23 @@+{+ "$schema": "https://json.schemastore.org/tsconfig",+ "compilerOptions": {+ "target": "es2022",+ "module": "es2022",+ "lib": ["es2022"],+ "declaration": true,+ "outDir": "./dist",+ "rootDir": ".",+ "strict": true,+ "esModuleInterop": true,+ "moduleResolution": "bundler",+ "skipLibCheck": true,+ "resolveJsonModule": true,+ "pretty": true,+ "noImplicitReturns": true,+ "noFallthroughCasesInSwitch": true,+ "noUnusedLocals": false,+ "noUnusedParameters": false,+ "types": ["node", "bun-types"]+ },+ "exclude": ["node_modules", "**/dist"]+}diff --git a/ts/packages/cli-keyring/tsconfig.src.json b/ts/packages/cli-keyring/tsconfig.src.jsonnew file mode 100644index 000000000..dee0c0af3--- /dev/null+++ b/ts/packages/cli-keyring/tsconfig.src.json@@ -0,0 +1,10 @@+{+ "$schema": "https://json.schemastore.org/tsconfig",+ "extends": "./tsconfig.options.json",+ "compilerOptions": {+ "outDir": "./dist",+ "rootDir": "."+ },+ "include": ["src/**/*", "package.json"],+ "exclude": ["node_modules", "../../../node_modules", "**/dist"]+}diff --git a/ts/packages/cli-keyring/tsconfig.test.json b/ts/packages/cli-keyring/tsconfig.test.jsonnew file mode 100644index 000000000..972d895b7--- /dev/null+++ b/ts/packages/cli-keyring/tsconfig.test.json@@ -0,0 +1,9 @@+{+ "$schema": "https://json.schemastore.org/tsconfig",+ "extends": "./tsconfig.options.json",+ "compilerOptions": {+ "rootDir": "."+ },+ "include": ["src/**/*", "test/**/*", "package.json"],+ "exclude": ["node_modules", "../../../node_modules", "**/dist"]+}diff --git a/ts/packages/cli-keyring/tsdown.config.ts b/ts/packages/cli-keyring/tsdown.config.tsnew file mode 100644index 000000000..42109e243--- /dev/null+++ b/ts/packages/cli-keyring/tsdown.config.ts@@ -0,0 +1,13 @@+import { defineConfig } from 'tsdown';+import { baseConfig } from '../../../tsdown.config.base';++export default defineConfig({+ ...baseConfig,+ entry: ['src/index.ts', 'src/effect.ts'],+ tsconfig: 'tsconfig.src.json',+ // bun:ffi is a Bun built-in; in the Node/CJS output it must remain+ // an unresolved import so Node never tries to load the FFI backend+ // chunk at startup. The runtime branch in stores/macos-security.ts+ // guards `isBun` before reaching the dynamic import.+ external: [...baseConfig.external, /^bun:/],+});diff --git a/ts/packages/cli-keyring/vitest.config.ts b/ts/packages/cli-keyring/vitest.config.tsnew file mode 100644index 000000000..297ba2b49--- /dev/null+++ b/ts/packages/cli-keyring/vitest.config.ts@@ -0,0 +1,7 @@+import { defineConfig } from 'vitest/config';++export default defineConfig({+ test: {+ exclude: ['**/node_modules/**', '**/dist/**'],+ },+});