@devries-cameron20 / composio-1 / commits / 9d7cf5aca
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

feat(cli-keyring): add @composio/cli-keyring package (#3201)

## Summary - Cross-platform OS credential storage package for the Composio CLI, structurally modeled on [keyring-rs](https://github.com/open-source-cooperative/keyring-rs) - **macOS FFI backend**: direct `SecItemCopyMatching` via `bun:ffi` — **~1.4ms median reads** (vs 22ms subprocess). Writes delegate to `/usr/bin/security -A` for reliable allow-any ACL - **macOS subprocess fallback**: `/usr/bin/security` for Node/test environments - **Linux backend**: `secret-tool` subprocess with keyring-rs-compatible attribute keys (`{service, username, target}`) - All pointers as `bigint` (`FFIType.u64`) to handle CoreFoundation tagged pointers above `2^53` - `b64:` prefix encoding for cross-backend binary safety - 11-variant `KeyringError` discriminated union matching `keyring-core`'s error model - Effect.ts integration via `@composio/cli-keyring/effect` subpath export (optional peer dep) - `dangerouslySaveApiKeyInUserConfig` escape hatch designed for the CLI migration PR (next in stack) ## Benchmark (100 iterations, Apple Silicon) | operation | subprocess | FFI | speedup | |---|---|---|---| | `getPassword` p50 | 19.95ms | **1.14ms** | **18×** | | `getPassword` p99 | 88.72ms | **7.39ms** | **12×** | ## Test plan - [x] 16 unit tests (errors, entry, shared encoding) — Node vitest - [x] 4 E2E tests against real macOS keychain — gated on `COMPOSIO_KEYRING_E2E=1` - [x] 6 FFI-specific tests — gated on `typeof Bun !== 'undefined'` + E2E flag - [x] `publint` + `attw` clean - [x] `bun build --compile` produces working standalone binary with FFI reads 🤖 Generated with [Claude Code](https://claude.com/claude-code) **Stack: 1/2** — next PR: `cli/keyring-migration` (wires this into the CLI) --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

Rahul Tarak committed Apr 13, 2026 at 23:55 UTC 9d7cf5aca27a57a25080ae82d164fece0031f64a
28 files changed +2904 -15
pnpm-lock.yaml
+95 -15
@@ -709,16 +709,16 @@ importers:
709 version: link:../../packages/providers/llamaindex
710 '@llamaindex/openai':
711 specifier: ^0.4.20
712 - version: 0.4.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(ws@8.20.0)(zod@4.3.6)
712 + version: 0.4.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(ws@8.20.0)(zod@3.25.76)
713 '@llamaindex/workflow':
714 specifier: ^1.1.24
715 - version: 1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(zod@4.3.6)
715 + version: 1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(zod@3.25.76)
716 dotenv:
717 specifier: ^16.4.1
718 version: 16.6.1
719 llamaindex:
720 specifier: ^0.12.0
721 - version: 0.12.1(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@4.3.6)
721 + version: 0.12.1(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@3.25.76)
722 devDependencies:
723 '@types/bun':
724 specifier: ^1.2.9
@@ -1171,6 +1171,27 @@ importers:
1171 specifier: 'catalog:'
1172 version: 3.2.4(@types/node@24.10.13)(@vitest/ui@3.2.4)(tsx@4.21.0)(yaml@2.8.2)
1173
1174 + ts/packages/cli-keyring:
1175 + devDependencies:
1176 + '@types/node':
1177 + specifier: ^24.0.1
1178 + version: 24.10.13
1179 + bun-types:
1180 + specifier: ^1.3.11
1181 + version: 1.3.11
1182 + effect:
1183 + specifier: 'catalog:'
1184 + version: 3.19.18
1185 + tsdown:
1186 + specifier: 'catalog:'
1187 + version: 0.18.4(@arethetypeswrong/core@0.18.2)(@typescript/native-preview@7.0.0-dev.20260403.1)(publint@0.3.17)(typescript@5.9.3)
1188 + typescript:
1189 + specifier: 'catalog:'
1190 + version: 5.9.3
1191 + vitest:
1192 + specifier: 'catalog:'
1193 + version: 3.2.4(@types/node@24.10.13)(@vitest/ui@3.2.4)(tsx@4.21.0)(yaml@2.8.2)
1194 +
1195 ts/packages/core:
1196 dependencies:
1197 '@composio/client':
@@ -1348,7 +1369,7 @@ importers:
1369 dependencies:
1370 llamaindex:
1371 specifier: ^0.12.0
1351 - version: 0.12.1(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@4.3.6)
1372 + version: 0.12.1(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@4.3.6)
1373 devDependencies:
1374 '@composio/core':
1375 specifier: workspace:*
@@ -4085,6 +4106,9 @@ packages:
4106 buffer@5.7.1:
4107 resolution: {integrity: sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==}
4108
4109 + bun-types@1.3.11:
4110 + resolution: {integrity: sha512-1KGPpoxQWl9f6wcZh57LvrPIInQMn2TQ7jsgxqpRzg+l0QPOFvJVH7HmvHo/AiPgwXy+/Thf6Ov3EdVn1vOabg==}
4111 +
4112 bun-types@1.3.9:
4113 resolution: {integrity: sha512-+UBWWOakIP4Tswh0Bt0QD0alpTY8cb5hvgiYeWCMet9YukHbzuruIEeXC2D7nMJPB12kbh8C7XJykSexEqGKJg==}
4114
@@ -7971,26 +7995,43 @@ snapshots:
7995 tree-sitter: 0.22.4
7996 web-tree-sitter: 0.24.7
7997
7974 - '@llamaindex/openai@0.4.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(ws@8.20.0)(zod@4.3.6)':
7998 + '@llamaindex/openai@0.4.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(ws@8.20.0)(zod@3.25.76)':
7999 dependencies:
8000 '@llamaindex/core': 0.6.22
8001 '@llamaindex/env': 0.1.30
7978 - openai: 5.23.2(ws@8.20.0)(zod@4.3.6)
8002 + openai: 5.23.2(ws@8.20.0)(zod@3.25.76)
8003 transitivePeerDependencies:
8004 - ws
8005 - zod
8006
7983 - '@llamaindex/workflow-core@1.3.3(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(zod@4.3.6)':
8007 + '@llamaindex/workflow-core@1.3.3(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(zod@3.25.76)':
8008 optionalDependencies:
7985 - '@modelcontextprotocol/sdk': 1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6)
8009 + '@modelcontextprotocol/sdk': 1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76)
8010 hono: 4.11.9
8011 + zod: 3.25.76
8012 +
8013 + '@llamaindex/workflow-core@1.3.3(zod@4.3.6)':
8014 + optionalDependencies:
8015 zod: 4.3.6
8016
7989 - '@llamaindex/workflow@1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(zod@4.3.6)':
8017 + '@llamaindex/workflow@1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(zod@3.25.76)':
8018 + dependencies:
8019 + '@llamaindex/core': 0.6.22
8020 + '@llamaindex/env': 0.1.30
8021 + '@llamaindex/workflow-core': 1.3.3(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(zod@3.25.76)
8022 + transitivePeerDependencies:
8023 + - '@modelcontextprotocol/sdk'
8024 + - hono
8025 + - next
8026 + - p-retry
8027 + - rxjs
8028 + - zod
8029 +
8030 + '@llamaindex/workflow@1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(zod@4.3.6)':
8031 dependencies:
8032 '@llamaindex/core': 0.6.22
8033 '@llamaindex/env': 0.1.30
7993 - '@llamaindex/workflow-core': 1.3.3(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(zod@4.3.6)
8034 + '@llamaindex/workflow-core': 1.3.3(zod@4.3.6)
8035 transitivePeerDependencies:
8036 - '@modelcontextprotocol/sdk'
8037 - hono
@@ -9008,6 +9049,14 @@ snapshots:
9049 optionalDependencies:
9050 vite: 7.3.1(@types/node@22.19.11)(tsx@4.21.0)(yaml@2.8.2)
9051
9052 + '@vitest/mocker@3.2.4(vite@7.3.1(@types/node@24.10.13)(tsx@4.21.0)(yaml@2.8.2))':
9053 + dependencies:
9054 + '@vitest/spy': 3.2.4
9055 + estree-walker: 3.0.3
9056 + magic-string: 0.30.21
9057 + optionalDependencies:
9058 + vite: 7.3.1(@types/node@24.10.13)(tsx@4.21.0)(yaml@2.8.2)
9059 +
9060 '@vitest/pretty-format@3.2.4':
9061 dependencies:
9062 tinyrainbow: 2.0.0
@@ -9037,7 +9086,7 @@ snapshots:
9086 sirv: 3.0.2
9087 tinyglobby: 0.2.15
9088 tinyrainbow: 2.0.0
9040 - vitest: 3.2.4(@types/node@22.19.11)(@vitest/ui@3.2.4)(tsx@4.21.0)(yaml@2.8.2)
9089 + vitest: 3.2.4(@types/node@24.10.13)(@vitest/ui@3.2.4)(tsx@4.21.0)(yaml@2.8.2)
9090
9091 '@vitest/utils@3.2.4':
9092 dependencies:
@@ -9274,9 +9323,13 @@ snapshots:
9323 base64-js: 1.5.1
9324 ieee754: 1.2.1
9325
9326 + bun-types@1.3.11:
9327 + dependencies:
9328 + '@types/node': 24.10.13
9329 +
9330 bun-types@1.3.9:
9331 dependencies:
9279 - '@types/node': 22.19.11
9332 + '@types/node': 24.10.13
9333
9334 bundle-name@4.1.0:
9335 dependencies:
@@ -10483,12 +10536,34 @@ snapshots:
10536 rfdc: 1.4.1
10537 wrap-ansi: 9.0.2
10538
10486 - llamaindex@0.12.1(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@4.3.6):
10539 + llamaindex@0.12.1(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@3.25.76):
10540 + dependencies:
10541 + '@llamaindex/core': 0.6.22
10542 + '@llamaindex/env': 0.1.30
10543 + '@llamaindex/node-parser': 2.0.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)
10544 + '@llamaindex/workflow': 1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@3.25.76))(hono@4.11.9)(zod@3.25.76)
10545 + '@types/lodash': 4.17.23
10546 + '@types/node': 24.10.13
10547 + lodash: 4.17.23
10548 + magic-bytes.js: 1.13.0
10549 + transitivePeerDependencies:
10550 + - '@huggingface/transformers'
10551 + - '@modelcontextprotocol/sdk'
10552 + - gpt-tokenizer
10553 + - hono
10554 + - next
10555 + - p-retry
10556 + - rxjs
10557 + - tree-sitter
10558 + - web-tree-sitter
10559 + - zod
10560 +
10561 + llamaindex@0.12.1(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)(zod@4.3.6):
10562 dependencies:
10563 '@llamaindex/core': 0.6.22
10564 '@llamaindex/env': 0.1.30
10565 '@llamaindex/node-parser': 2.0.22(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(tree-sitter@0.22.4)(web-tree-sitter@0.24.7)
10491 - '@llamaindex/workflow': 1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(@modelcontextprotocol/sdk@1.26.0(@cfworker/json-schema@4.1.1)(zod@4.3.6))(hono@4.11.9)(zod@4.3.6)
10566 + '@llamaindex/workflow': 1.1.24(@llamaindex/core@0.6.22)(@llamaindex/env@0.1.30)(zod@4.3.6)
10567 '@types/lodash': 4.17.23
10568 '@types/node': 24.10.13
10569 lodash: 4.17.23
@@ -10772,6 +10847,11 @@ snapshots:
10847 is-inside-container: 1.0.0
10848 wsl-utils: 0.1.0
10849
10850 + openai@5.23.2(ws@8.20.0)(zod@3.25.76):
10851 + optionalDependencies:
10852 + ws: 8.20.0
10853 + zod: 3.25.76
10854 +
10855 openai@5.23.2(ws@8.20.0)(zod@4.3.6):
10856 optionalDependencies:
10857 ws: 8.20.0
@@ -11870,7 +11950,7 @@ snapshots:
11950 dependencies:
11951 '@types/chai': 5.2.3
11952 '@vitest/expect': 3.2.4
11873 - '@vitest/mocker': 3.2.4(vite@7.3.1(@types/node@22.19.11)(tsx@4.21.0)(yaml@2.8.2))
11953 + '@vitest/mocker': 3.2.4(vite@7.3.1(@types/node@24.10.13)(tsx@4.21.0)(yaml@2.8.2))
11954 '@vitest/pretty-format': 3.2.4
11955 '@vitest/runner': 3.2.4
11956 '@vitest/snapshot': 3.2.4
pnpm-workspace.yaml
+1
@@ -7,6 +7,7 @@ packages:
7 - ts/e2e-tests/runtimes/cloudflare/*
8 - ts/examples/*
9 - ts/packages/cli
10 + - ts/packages/cli-keyring
11 - ts/packages/core
12 - ts/packages/json-schema-to-zod
13 - ts/packages/providers/*
ts/packages/cli-keyring/README.md new
+232
@@ -0,0 +1,232 @@
1 +# @composio/cli-keyring
2 +
3 +Cross-platform OS credential storage for the Composio CLI.
4 +
5 +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.
6 +
7 +## Why this exists
8 +
9 +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.
10 +
11 +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.
12 +
13 +## Architecture
14 +
15 +```
16 +src/
17 +├── core/ # keyring-rs keyring-core port
18 +│ ├── entry.ts # Entry class — (service, user, modifiers)
19 +│ ├── errors.ts # KeyringError, 11-variant discriminated union
20 +│ ├── persistence.ts # CredentialPersistence enum
21 +│ └── store.ts # CredentialStore interface + default-store registry
22 +└── stores/ # per-platform backends
23 + ├── macos-security.ts # runtime picker (Bun → FFI, Node → subprocess)
24 + ├── macos-security-ffi.ts # direct Security.framework via bun:ffi (fast path)
25 + ├── macos-security-subprocess.ts# /usr/bin/security subprocess fallback
26 + ├── linux-secret-tool.ts # secret-tool subprocess
27 + ├── unsupported.ts # Windows / BSD / … — throws NoStorageAccess
28 + └── shared.ts # subprocess helpers + base64 on-disk encoding
29 +```
30 +
31 +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.
32 +
33 +## Backends and runtime dispatch
34 +
35 +| platform | runtime | backend | read latency |
36 +| ----------- | ------- | ------------------------------------ | ------------ |
37 +| macOS | Bun | `SecItem*` via `bun:ffi` | **~1.4ms** |
38 +| macOS | Node | `/usr/bin/security` subprocess | ~22ms |
39 +| Linux | both | `secret-tool` subprocess (libsecret) | ~15–40ms |
40 +| Windows/BSD | both | throws `NoStorageAccess` | — |
41 +
42 +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.
43 +
44 +## Performance
45 +
46 +Measured 100 iterations on an Apple Silicon Mac with a warm login keychain:
47 +
48 +| operation | subprocess | FFI (bun:ffi) | speedup |
49 +| ------------------ | ---------- | ------------- | ------- |
50 +| `getPassword` mean | 22.25ms | **1.46ms** | **15×** |
51 +| `getPassword` p50 | 19.95ms | **1.14ms** | **18×** |
52 +| `getPassword` p99 | 88.72ms | **7.39ms** | **12×** |
53 +| `setPassword` mean | 26.61ms | **16.18ms** | 1.6× |
54 +
55 +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.
56 +
57 +## Security model
58 +
59 +### Tagged pointers
60 +
61 +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.
62 +
63 +### ACL story (macOS)
64 +
65 +Keychain items have an **Access Control List** — a per-item permission record that lists which binaries can read the item without a GUI prompt.
66 +
67 +| ACL populated with | upgrade-stable? | gates agents? |
68 +| ------------------------------------------ | --------------------------- | ------------- |
69 +| `[/usr/bin/security]` (subprocess default) | yes | no |
70 +| `[composio (ad-hoc signed)]` | **no — breaks every build** | yes |
71 +| `[composio (Developer ID signed)]` | yes | **yes** |
72 +| **allow-any** (current FFI choice) | yes | no |
73 +
74 +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.
75 +
76 +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.
77 +
78 +### Linux
79 +
80 +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.
81 +
82 +## On-disk encoding
83 +
84 +Both backends base64-encode every secret before handing it to the OS and prefix the encoded string with `b64:`. Reasons:
85 +
86 +- `security -w` takes the password on argv and cannot carry binary bytes (NUL bytes truncate; newlines break parsing).
87 +- `secret-tool store` reads one line from stdin via `g_io_channel_read_line`, which can't carry NUL bytes or embedded newlines.
88 +- 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.
89 +
90 +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.
91 +
92 +## Linux attribute conventions (keyring-rs interop)
93 +
94 +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.
95 +
96 +## Usage
97 +
98 +```ts
99 +import { Entry, createDefaultStore, setDefaultStore } from '@composio/cli-keyring';
100 +
101 +// One-time process startup:
102 +setDefaultStore(await createDefaultStore());
103 +
104 +// Anywhere:
105 +const entry = new Entry('com.composio.cli', 'default');
106 +await entry.setPassword(apiKey);
107 +const stored = await entry.getPassword();
108 +await entry.deleteCredential();
109 +```
110 +
111 +With Effect.ts:
112 +
113 +```ts
114 +import { Effect, Layer } from 'effect';
115 +import { KeyringService, KeyringLive } from '@composio/cli-keyring/effect';
116 +
117 +const program = Effect.gen(function* () {
118 + const keyring = yield* KeyringService;
119 + yield* keyring.setPassword('com.composio.cli', 'default', apiKey);
120 +});
121 +
122 +program.pipe(Effect.provide(KeyringLive));
123 +```
124 +
125 +## Error handling
126 +
127 +Every operation throws `KeyringError` with a discriminated `details` field. Pattern-match on the kind, don't catch generically:
128 +
129 +```ts
130 +try {
131 + const key = await entry.getPassword();
132 +} catch (err) {
133 + if (err instanceof KeyringError) {
134 + switch (err.kind) {
135 + case 'NoEntry':
136 + /* user not logged in yet */ break;
137 + case 'NoStorageAccess':
138 + /* keyring unavailable — fall back */ break;
139 + case 'BadEncoding':
140 + /* stored bytes aren't valid UTF-8 */ break;
141 + // ...
142 + }
143 + }
144 +}
145 +```
146 +
147 +Full variant list (mirroring `keyring-core/src/error.rs`): `PlatformFailure`, `NoStorageAccess`, `NoEntry`, `BadEncoding`, `BadDataFormat`, `BadStoreFormat`, `TooLong`, `Invalid`, `Ambiguous`, `NoDefaultStore`, `NotSupportedByStore`.
148 +
149 +## Integration plan (Composio CLI migration)
150 +
151 +Tracked in a follow-up PR stacked on top of this one. Summary of the intended `ComposioUserContextLive` behavior:
152 +
153 +### Caching (Option A: in-process memoization, no cross-process cache)
154 +
155 +- `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).
156 +- 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.
157 +- **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.
158 +- **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.
159 +
160 +### Fallback chain
161 +
162 +```
163 +login(apiKey):
164 + if config.dangerouslySaveApiKeyInUserConfig === true:
165 + → write apiKey to user_data.json.api_key (plaintext; skip keyring entirely)
166 + else:
167 + try keyring.setPassword(apiKey)
168 + success: write user_data.json with api_key = null
169 + NoStorageAccess: fall back to user_data.json.api_key + one-time warning
170 +
171 +init (read):
172 + read user_data.json
173 + if config.dangerouslySaveApiKeyInUserConfig === true:
174 + → use user_data.json.api_key directly, never touch keyring
175 + else:
176 + try keyring.getPassword()
177 + success: use it
178 + NoEntry:
179 + if user_data.json.api_key is set (legacy):
180 + → use it, migrate to keyring, rewrite user_data.json with api_key = null
181 + else:
182 + → user is logged out
183 + NoStorageAccess:
184 + → fall back to user_data.json.api_key with a one-time warning
185 +
186 +logout:
187 + best-effort keyring.deleteCredential() (swallow NoEntry / NoStorageAccess)
188 + rewrite user_data.json with api_key = null
189 +```
190 +
191 +### The `dangerouslySaveApiKeyInUserConfig` escape hatch
192 +
193 +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.
194 +
195 +```json
196 +{
197 + "experimental_features": {},
198 + "dangerously_save_api_key_in_user_config": true
199 +}
200 +```
201 +
202 +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`.
203 +
204 +**Why it exists**:
205 +
206 +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`.
207 +2. **Docker / devcontainers / CI** — same story; ephemeral environments where the keyring is either absent or actively harmful.
208 +3. **Power users who audit their config** — explicit opt-in with a name that makes the risk legible in `cat config.json`.
209 +
210 +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.
211 +
212 +## Known limitations
213 +
214 +- **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.
215 +- **Linux has no per-binary ACL at any layer** of the stack. Best achievable on Linux today is the `secret-tool` Bash-prompt gate.
216 +- **`getAttributes` / `updateAttributes` / `search`** from keyring-rs's API surface are not implemented; they throw `NotSupportedByStore`. Add later if a caller needs them.
217 +- **macOS non-`User` keychain domains** (System, Common, Dynamic) are not supported; modifier throws `NotSupportedByStore`.
218 +
219 +## Running the tests
220 +
221 +```bash
222 +# Unit tests (Node, no keychain access)
223 +pnpm test
224 +
225 +# E2E against the real macOS keychain via subprocess backend (Node)
226 +COMPOSIO_KEYRING_E2E=1 pnpm test
227 +
228 +# E2E against the real macOS keychain via FFI backend (Bun)
229 +COMPOSIO_KEYRING_E2E=1 bun --bun x vitest run test/ffi.test.ts
230 +```
231 +
232 +The E2E suites use UUID-suffixed service names so parallel runs and leftover entries from crashed runs never collide with real credentials.
ts/packages/cli-keyring/eslint.config.mjs new
+3
@@ -0,0 +1,3 @@
1 +module.exports = {
2 + extends: ['../../.eslintrc.cjs'],
3 +};
ts/packages/cli-keyring/package.json new
+90
@@ -0,0 +1,90 @@
1 +{
2 + "name": "@composio/cli-keyring",
3 + "version": "0.1.0",
4 + "description": "Cross-platform OS credential store access for the Composio CLI (macOS Keychain, Linux Secret Service).",
5 + "main": "src/index.ts",
6 + "private": true,
7 + "type": "module",
8 + "repository": {
9 + "type": "git",
10 + "url": "https://github.com/ComposioHQ/composio.git",
11 + "directory": "ts/packages/cli-keyring"
12 + },
13 + "publishConfig": {
14 + "access": "public",
15 + "main": "dist/index.mjs",
16 + "types": "dist/index.d.mts"
17 + },
18 + "exports": {
19 + ".": {
20 + "import": {
21 + "types": "./dist/index.d.mts",
22 + "default": "./dist/index.mjs"
23 + },
24 + "require": {
25 + "types": "./dist/index.d.cts",
26 + "default": "./dist/index.cjs"
27 + },
28 + "default": {
29 + "types": "./dist/index.d.cts",
30 + "default": "./dist/index.cjs"
31 + }
32 + },
33 + "./effect": {
34 + "import": {
35 + "types": "./dist/effect.d.mts",
36 + "default": "./dist/effect.mjs"
37 + },
38 + "require": {
39 + "types": "./dist/effect.d.cts",
40 + "default": "./dist/effect.cjs"
41 + },
42 + "default": {
43 + "types": "./dist/effect.d.cts",
44 + "default": "./dist/effect.cjs"
45 + }
46 + }
47 + },
48 + "files": [
49 + "README.md",
50 + "dist"
51 + ],
52 + "scripts": {
53 + "clean": "git clean -xdf node_modules",
54 + "build": "pnpm exec tsdown",
55 + "test": "vitest run",
56 + "typecheck:src": "pnpm exec tsgo --noEmit -p ./tsconfig.src.json",
57 + "typecheck:test": "pnpm exec tsgo --noEmit -p ./tsconfig.test.json",
58 + "typecheck": "pnpm run typecheck:src && pnpm run typecheck:test",
59 + "typecheck:src:tsc": "tsc --noEmit -p ./tsconfig.src.json",
60 + "typecheck:test:tsc": "tsc --noEmit -p ./tsconfig.test.json",
61 + "typecheck:tsc": "pnpm run typecheck:src:tsc && pnpm run typecheck:test:tsc"
62 + },
63 + "keywords": [
64 + "composio",
65 + "keyring",
66 + "keychain",
67 + "credential",
68 + "secret-service",
69 + "libsecret"
70 + ],
71 + "author": "Composio",
72 + "license": "ISC",
73 + "packageManager": "pnpm@10.28.0",
74 + "devDependencies": {
75 + "@types/node": "^24.0.1",
76 + "bun-types": "^1.3.11",
77 + "effect": "catalog:",
78 + "tsdown": "catalog:",
79 + "typescript": "catalog:",
80 + "vitest": "catalog:"
81 + },
82 + "peerDependencies": {
83 + "effect": ">=3.17.0"
84 + },
85 + "peerDependenciesMeta": {
86 + "effect": {
87 + "optional": true
88 + }
89 + }
90 +}
ts/packages/cli-keyring/src/core/entry.ts new
+106
@@ -0,0 +1,106 @@
1 +/**
2 + * `Entry` — the specifier-based credential handle users interact with.
3 + *
4 + * Mirrors `keyring_core::api::Entry` / `CredentialApi`. An `Entry` is
5 + * just a `(service, user, modifiers)` triple that routes calls through
6 + * the process-global default store. There is no long-lived handle to
7 + * the underlying credential — every call is a round-trip to the OS.
8 + */
9 +
10 +import { KeyringError } from './errors';
11 +import { type CredentialStore, type EntryModifiers, getDefaultStore } from './store';
12 +
13 +const textEncoder = new TextEncoder();
14 +const textDecoder = new TextDecoder('utf-8', { fatal: true });
15 +
16 +/**
17 + * Identifies a credential by `service` + `user`, with optional
18 + * per-store modifiers (keychain domain, Secret Service collection,
19 + * custom label).
20 + *
21 + * Both `service` and `user` must be non-empty — empty strings act as
22 + * wildcards in Keychain Services and would silently delete other
23 + * credentials. This mirrors keyring-rs's `Invalid` check on the macOS
24 + * backend and we enforce it uniformly so behavior doesn't diverge by
25 + * platform.
26 + */
27 +export class Entry {
28 + readonly service: string;
29 + readonly user: string;
30 + readonly modifiers: EntryModifiers;
31 +
32 + /**
33 + * Override the store just for this entry (e.g. tests). When `null`,
34 + * the process-global default store is resolved on every call so that
35 + * `setDefaultStore` / `unsetDefaultStore` take effect immediately.
36 + */
37 + private readonly overrideStore: CredentialStore | null;
38 +
39 + constructor(
40 + service: string,
41 + user: string,
42 + modifiers: EntryModifiers = {},
43 + overrideStore: CredentialStore | null = null
44 + ) {
45 + if (service.length === 0) {
46 + throw new KeyringError({
47 + kind: 'Invalid',
48 + param: 'service',
49 + reason: 'service must be a non-empty string',
50 + });
51 + }
52 + if (user.length === 0) {
53 + throw new KeyringError({
54 + kind: 'Invalid',
55 + param: 'user',
56 + reason: 'user must be a non-empty string',
57 + });
58 + }
59 + this.service = service;
60 + this.user = user;
61 + this.modifiers = modifiers;
62 + this.overrideStore = overrideStore;
63 + }
64 +
65 + /**
66 + * Store `password` as UTF-8 bytes under this entry's specifier.
67 + * Overwrites any existing value.
68 + */
69 + async setPassword(password: string): Promise<void> {
70 + await this.setSecret(textEncoder.encode(password));
71 + }
72 +
73 + /**
74 + * Fetch the stored value and decode it as UTF-8. Throws
75 + * `KeyringError({ kind: 'NoEntry' })` if nothing was stored, or
76 + * `KeyringError({ kind: 'BadEncoding', bytes })` if the stored bytes
77 + * aren't valid UTF-8 — matching keyring-rs's `Error::BadEncoding`.
78 + */
79 + async getPassword(): Promise<string> {
80 + const bytes = await this.getSecret();
81 + try {
82 + return textDecoder.decode(bytes);
83 + } catch {
84 + throw new KeyringError({ kind: 'BadEncoding', bytes });
85 + }
86 + }
87 +
88 + /** Store raw bytes. */
89 + async setSecret(secret: Uint8Array): Promise<void> {
90 + await this.resolveStore().setSecret(this.service, this.user, secret, this.modifiers);
91 + }
92 +
93 + /** Fetch raw bytes. Throws `NoEntry` if nothing matches. */
94 + async getSecret(): Promise<Uint8Array> {
95 + return this.resolveStore().getSecret(this.service, this.user, this.modifiers);
96 + }
97 +
98 + /** Delete the credential. Throws `NoEntry` if it didn't exist. */
99 + async deleteCredential(): Promise<void> {
100 + await this.resolveStore().deleteCredential(this.service, this.user, this.modifiers);
101 + }
102 +
103 + private resolveStore(): CredentialStore {
104 + return this.overrideStore ?? getDefaultStore();
105 + }
106 +}
ts/packages/cli-keyring/src/core/errors.ts new
+128
@@ -0,0 +1,128 @@
1 +/**
2 + * Error model for `@composio/cli-keyring`.
3 + *
4 + * Mirrors the 11-variant enum from `keyring-core/src/error.rs` in
5 + * https://github.com/open-source-cooperative/keyring-core so that this
6 + * package can act as a structural TypeScript port of keyring-rs for the
7 + * backends we care about (macOS Keychain via `security`, Linux Secret
8 + * Service via `secret-tool`).
9 + */
10 +
11 +import type { Entry } from './entry';
12 +
13 +/**
14 + * Discriminated union of every error condition a `CredentialStore` may
15 + * surface. Prefer pattern-matching on `kind` rather than catching
16 + * `KeyringError` generically so handlers remain explicit about what they
17 + * tolerate (`NoEntry` on first login, for example).
18 + */
19 +export type KeyringErrorDetails =
20 + /** The underlying store returned an unexpected runtime failure. */
21 + | { readonly kind: 'PlatformFailure'; readonly cause: unknown }
22 + /**
23 + * The store is present but inaccessible: keychain locked, D-Bus
24 + * session missing, user declined an unlock prompt, `secret-tool`
25 + * not installed, etc. Callers should treat this as "try a fallback
26 + * or warn the user" rather than "retry".
27 + */
28 + | { readonly kind: 'NoStorageAccess'; readonly cause: unknown }
29 + /** No credential exists for the (service, user) specifier. */
30 + | { readonly kind: 'NoEntry' }
31 + /** Retrieved bytes were not valid UTF-8 (only raised by `getPassword`). */
32 + | { readonly kind: 'BadEncoding'; readonly bytes: Uint8Array }
33 + /** Retrieved bytes didn't match the store's expected blob format. */
34 + | { readonly kind: 'BadDataFormat'; readonly bytes: Uint8Array; readonly cause: unknown }
35 + /** Store metadata itself is corrupted. */
36 + | { readonly kind: 'BadStoreFormat'; readonly detail: string }
37 + /** An attribute value exceeded the platform length limit. */
38 + | { readonly kind: 'TooLong'; readonly attr: string; readonly limit: number }
39 + /**
40 + * A parameter violated a store-specific rule — e.g. an empty `service`
41 + * or `user` on macOS (empty strings act as wildcards in Keychain
42 + * Services and must be rejected locally before we spawn).
43 + */
44 + | { readonly kind: 'Invalid'; readonly param: string; readonly reason: string }
45 + /**
46 + * Multiple credentials matched the (service, user) specifier. Only
47 + * possible on Secret Service; generic-password items on macOS are
48 + * unique per (service, account, keychain).
49 + */
50 + | { readonly kind: 'Ambiguous'; readonly matches: readonly Entry[] }
51 + /** No process-global default store has been registered. */
52 + | { readonly kind: 'NoDefaultStore' }
53 + /** The active store does not implement the requested operation. */
54 + | { readonly kind: 'NotSupportedByStore'; readonly operation: string };
55 +
56 +export type KeyringErrorKind = KeyringErrorDetails['kind'];
57 +
58 +/**
59 + * The single error type thrown by every operation on `Entry` or a
60 + * `CredentialStore`. `details` carries the variant-specific payload;
61 + * the base `message` is derived for human logs but callers should
62 + * branch on `details.kind`.
63 + */
64 +export class KeyringError extends Error {
65 + readonly details: KeyringErrorDetails;
66 +
67 + constructor(details: KeyringErrorDetails) {
68 + super(KeyringError.formatMessage(details));
69 + this.name = 'KeyringError';
70 + this.details = details;
71 + // Preserve the original cause chain for PlatformFailure / NoStorageAccess
72 + // so `console.error(err)` prints the underlying reason.
73 + if ('cause' in details && details.cause !== undefined) {
74 + (this as { cause?: unknown }).cause = details.cause;
75 + }
76 + }
77 +
78 + get kind(): KeyringErrorKind {
79 + return this.details.kind;
80 + }
81 +
82 + /**
83 + * Convenience predicate — avoids `err instanceof KeyringError && err.kind === 'NoEntry'`
84 + * at every call site.
85 + */
86 + is<K extends KeyringErrorKind>(
87 + kind: K
88 + ): this is KeyringError & { readonly details: Extract<KeyringErrorDetails, { kind: K }> } {
89 + return this.details.kind === kind;
90 + }
91 +
92 + private static formatMessage(d: KeyringErrorDetails): string {
93 + switch (d.kind) {
94 + case 'NoEntry':
95 + return 'No matching credential was found in the store.';
96 + case 'NoDefaultStore':
97 + return 'No default keyring store has been registered for this process.';
98 + case 'PlatformFailure':
99 + return `Keyring store failure: ${describe(d.cause)}`;
100 + case 'NoStorageAccess':
101 + return `Keyring store is unavailable: ${describe(d.cause)}`;
102 + case 'BadEncoding':
103 + return `Stored credential is not valid UTF-8 (${d.bytes.byteLength} bytes).`;
104 + case 'BadDataFormat':
105 + return `Stored credential is malformed: ${describe(d.cause)}`;
106 + case 'BadStoreFormat':
107 + return `Credential store metadata is corrupted: ${d.detail}`;
108 + case 'TooLong':
109 + return `Attribute "${d.attr}" exceeds the platform limit of ${d.limit} bytes.`;
110 + case 'Invalid':
111 + return `Invalid parameter "${d.param}": ${d.reason}`;
112 + case 'Ambiguous':
113 + return `Credential specifier matched ${d.matches.length} items; expected exactly one.`;
114 + case 'NotSupportedByStore':
115 + return `Operation "${d.operation}" is not supported by the active keyring store.`;
116 + }
117 + }
118 +}
119 +
120 +function describe(cause: unknown): string {
121 + if (cause instanceof Error) return cause.message;
122 + if (typeof cause === 'string') return cause;
123 + try {
124 + return JSON.stringify(cause);
125 + } catch {
126 + return String(cause);
127 + }
128 +}
ts/packages/cli-keyring/src/core/persistence.ts new
+25
@@ -0,0 +1,25 @@
1 +/**
2 + * Lifetime of credentials held by a store.
3 + *
4 + * Mirrors `keyring_core::api::CredentialPersistence`. Clients can query
5 + * `store.persistence()` to warn users when credentials will be lost on
6 + * logout (e.g. keyutils) vs. persisted to disk (macOS Keychain, Secret
7 + * Service).
8 + */
9 +export const CredentialPersistence = {
10 + /** Credentials exist only for the lifetime of an `Entry` handle. */
11 + EntryOnly: 'EntryOnly',
12 + /** Credentials are wiped when the process exits. */
13 + ProcessOnly: 'ProcessOnly',
14 + /** Credentials persist until the user logs out of the session. */
15 + UntilLogout: 'UntilLogout',
16 + /** Credentials persist until the machine is rebooted. */
17 + UntilReboot: 'UntilReboot',
18 + /** Credentials persist until explicitly deleted. */
19 + UntilDelete: 'UntilDelete',
20 + /** Persistence characteristics are unknown. */
21 + Unspecified: 'Unspecified',
22 +} as const;
23 +
24 +export type CredentialPersistence =
25 + (typeof CredentialPersistence)[keyof typeof CredentialPersistence];
ts/packages/cli-keyring/src/core/store.ts new
+107
@@ -0,0 +1,107 @@
1 +/**
2 + * Store contract and process-global registry.
3 + *
4 + * Mirrors `keyring_core::api::CredentialStoreApi` + the
5 + * `set_default_store` / `get_default_store` / `unset_default_store`
6 + * helpers from `keyring_core::lib`. Tests can swap the default store
7 + * with an in-memory mock via `setDefaultStore`.
8 + */
9 +
10 +import type { CredentialPersistence } from './persistence';
11 +import { KeyringError } from './errors';
12 +
13 +/**
14 + * Optional per-entry modifiers supported by this package. Not every
15 + * store honors every modifier:
16 + *
17 + * - `label` — human-readable label shown in Keychain Access / seahorse.
18 + * If omitted, stores default to `keyring:{user}@{service}`
19 + * to match the label format keyring-rs produces.
20 + * - `collection` — Secret Service collection name (Linux only).
21 + * Defaults to `"default"`, matching keyring-rs's `target`
22 + * attribute convention.
23 + * - `keychain` — macOS keychain domain (`User` | `System` | `Common` |
24 + * `Dynamic`). Defaults to `User` (the login keychain).
25 + */
26 +export interface EntryModifiers {
27 + readonly label?: string;
28 + readonly collection?: string;
29 + readonly keychain?: 'User' | 'System' | 'Common' | 'Dynamic';
30 +}
31 +
32 +/**
33 + * The low-level operations a backend must implement. `Entry` is a thin
34 + * specifier wrapper that routes every call through the active store.
35 + *
36 + * All operations are async because both supported backends are
37 + * subprocess-based (`/usr/bin/security`, `secret-tool`). Throwing
38 + * `KeyringError` with a precise `kind` is required — callers need to
39 + * distinguish `NoEntry` from `NoStorageAccess` at minimum.
40 + */
41 +export interface CredentialStore {
42 + /** Short identifier shown in error messages and logs. */
43 + readonly id: string;
44 + /** Vendor / platform description. */
45 + readonly vendor: string;
46 +
47 + /** Lifetime characteristics of credentials stored by this backend. */
48 + persistence(): CredentialPersistence;
49 +
50 + /**
51 + * Store `secret` under `(service, user)`. Overwrites any existing
52 + * value for the same specifier.
53 + */
54 + setSecret(
55 + service: string,
56 + user: string,
57 + secret: Uint8Array,
58 + modifiers: EntryModifiers
59 + ): Promise<void>;
60 +
61 + /**
62 + * Fetch the raw bytes previously stored via `setSecret`. Must throw
63 + * `KeyringError({ kind: 'NoEntry' })` if nothing matches.
64 + */
65 + getSecret(service: string, user: string, modifiers: EntryModifiers): Promise<Uint8Array>;
66 +
67 + /**
68 + * Remove the credential identified by `(service, user)`. Throws
69 + * `NoEntry` if it didn't exist.
70 + */
71 + deleteCredential(service: string, user: string, modifiers: EntryModifiers): Promise<void>;
72 +}
73 +
74 +// -----------------------------------------------------------------------------
75 +// Process-global default store registry
76 +// -----------------------------------------------------------------------------
77 +
78 +let defaultStore: CredentialStore | null = null;
79 +
80 +/**
81 + * Register the store that `new Entry(service, user)` should dispatch to.
82 + * The CLI calls this once at startup; tests call it to inject a mock.
83 + */
84 +export function setDefaultStore(store: CredentialStore): void {
85 + defaultStore = store;
86 +}
87 +
88 +/** Clear the registered store — mostly useful for test teardown. */
89 +export function unsetDefaultStore(): void {
90 + defaultStore = null;
91 +}
92 +
93 +/**
94 + * Return the active default store or throw `NoDefaultStore` if none is
95 + * registered. Callers that want a non-throwing check should use
96 + * `hasDefaultStore()` instead.
97 + */
98 +export function getDefaultStore(): CredentialStore {
99 + if (defaultStore === null) {
100 + throw new KeyringError({ kind: 'NoDefaultStore' });
101 + }
102 + return defaultStore;
103 +}
104 +
105 +export function hasDefaultStore(): boolean {
106 + return defaultStore !== null;
107 +}
ts/packages/cli-keyring/src/effect.ts new
+183
@@ -0,0 +1,183 @@
1 +/**
2 + * Effect.ts integration for `@composio/cli-keyring`.
3 + *
4 + * The core package is intentionally Promise-based so Node and Bun
5 + * consumers can use it without pulling in Effect. This entry point
6 + * wraps `Entry` in an Effect service so the Composio CLI (which is
7 + * built on Effect) can access the keyring through its normal layer
8 + * composition:
9 + *
10 + * ```ts
11 + * import { Effect, Layer } from 'effect';
12 + * import { KeyringService, KeyringLive } from '@composio/cli-keyring/effect';
13 + *
14 + * const program = Effect.gen(function* () {
15 + * const keyring = yield* KeyringService;
16 + * yield* keyring.setPassword('com.composio.cli', 'default', apiKey);
17 + * });
18 + *
19 + * program.pipe(Effect.provide(KeyringLive));
20 + * ```
21 + *
22 + * This module has a peer dependency on `effect`. Consumers that don't
23 + * use Effect should import from `@composio/cli-keyring` directly and
24 + * never touch this file.
25 + */
26 +
27 +import { Context, Effect, Layer } from 'effect';
28 +import { Entry } from './core/entry';
29 +import type { KeyringError } from './core/errors';
30 +import { createDefaultStore, type MacOSBackend } from './index';
31 +import { type CredentialStore, type EntryModifiers, setDefaultStore } from './core/store';
32 +
33 +/**
34 + * Service shape exposed to Effect consumers. Every method returns
35 + * `Effect.Effect<T, KeyringError>` — callers branch on
36 + * `Effect.catchTag`-style error handling by matching on
37 + * `error.details.kind`.
38 + */
39 +export interface KeyringServiceShape {
40 + /** Store a UTF-8 password under (service, user). */
41 + readonly setPassword: (
42 + service: string,
43 + user: string,
44 + password: string,
45 + modifiers?: EntryModifiers
46 + ) => Effect.Effect<void, KeyringError>;
47 +
48 + /** Fetch a UTF-8 password; fails with `NoEntry` if missing. */
49 + readonly getPassword: (
50 + service: string,
51 + user: string,
52 + modifiers?: EntryModifiers
53 + ) => Effect.Effect<string, KeyringError>;
54 +
55 + /** Store raw bytes under (service, user). */
56 + readonly setSecret: (
57 + service: string,
58 + user: string,
59 + secret: Uint8Array,
60 + modifiers?: EntryModifiers
61 + ) => Effect.Effect<void, KeyringError>;
62 +
63 + /** Fetch raw bytes; fails with `NoEntry` if missing. */
64 + readonly getSecret: (
65 + service: string,
66 + user: string,
67 + modifiers?: EntryModifiers
68 + ) => Effect.Effect<Uint8Array, KeyringError>;
69 +
70 + /** Delete the credential; fails with `NoEntry` if missing. */
71 + readonly deleteCredential: (
72 + service: string,
73 + user: string,
74 + modifiers?: EntryModifiers
75 + ) => Effect.Effect<void, KeyringError>;
76 +
77 + /**
78 + * Probe whether the backing store is currently usable. Catches
79 + * `NoStorageAccess` to return `false` — useful for deciding whether
80 + * to offer keyring-backed login or fall back to on-disk config.
81 + */
82 + readonly isAvailable: Effect.Effect<boolean>;
83 +}
84 +
85 +/**
86 + * Context tag. Resolve with `yield* KeyringService` inside an
87 + * `Effect.gen` block.
88 + */
89 +export class KeyringService extends Context.Tag('composio/cli-keyring/KeyringService')<
90 + KeyringService,
91 + KeyringServiceShape
92 +>() {}
93 +
94 +/**
95 + * Build a `KeyringServiceShape` from a concrete `CredentialStore`.
96 + * Factored out so tests can swap in an in-memory mock without going
97 + * through `setDefaultStore`.
98 + */
99 +export function makeKeyringService(store: CredentialStore): KeyringServiceShape {
100 + const entryFor = (service: string, user: string, modifiers?: EntryModifiers): Entry =>
101 + new Entry(service, user, modifiers ?? {}, store);
102 +
103 + const unsafe = <T>(op: () => Promise<T>): Effect.Effect<T, KeyringError> =>
104 + Effect.tryPromise({
105 + try: op,
106 + // Store operations already throw KeyringError, so we preserve
107 + // the error verbatim. The `as KeyringError` cast is safe
108 + // because every path into this helper comes from an `Entry`
109 + // method or the underlying store, both of which only throw
110 + // KeyringError.
111 + catch: err => err as KeyringError,
112 + });
113 +
114 + return {
115 + setPassword: (service, user, password, modifiers) =>
116 + unsafe(() => entryFor(service, user, modifiers).setPassword(password)),
117 + getPassword: (service, user, modifiers) =>
118 + unsafe(() => entryFor(service, user, modifiers).getPassword()),
119 + setSecret: (service, user, secret, modifiers) =>
120 + unsafe(() => entryFor(service, user, modifiers).setSecret(secret)),
121 + getSecret: (service, user, modifiers) =>
122 + unsafe(() => entryFor(service, user, modifiers).getSecret()),
123 + deleteCredential: (service, user, modifiers) =>
124 + unsafe(() => entryFor(service, user, modifiers).deleteCredential()),
125 + isAvailable: Effect.gen(function* () {
126 + // Probe with a non-existent specifier — we expect NoEntry if
127 + // the store is healthy, NoStorageAccess if it isn't.
128 + const probeService = '__composio_cli_keyring_probe__';
129 + const probeUser = '__probe__';
130 + const probe = unsafe(() => new Entry(probeService, probeUser, {}, store).getSecret());
131 + return yield* probe.pipe(
132 + Effect.match({
133 + onSuccess: () => true,
134 + onFailure: err => err.details.kind === 'NoEntry',
135 + })
136 + );
137 + }),
138 + };
139 +}
140 +
141 +/**
142 + * Live layer that instantiates the platform store on effect-build and
143 + * registers it as the process-global default (so non-Effect callers
144 + * in the same process also see it). Provide this once at startup:
145 + *
146 + * ```ts
147 + * BunRuntime.runMain(program.pipe(Effect.provide(KeyringLive)));
148 + * ```
149 + *
150 + * The layer uses `Layer.effect` rather than `Layer.sync` because the
151 + * macOS FFI backend is dynamically imported — it must stay out of the
152 + * Node bundle so `bun:ffi` doesn't crash at module load. The extra
153 + * layer-build cost is a one-shot `import()` per process.
154 + */
155 +export const KeyringLive: Layer.Layer<KeyringService> = Layer.effect(
156 + KeyringService,
157 + Effect.promise(async () => {
158 + const store = await createDefaultStore();
159 + setDefaultStore(store);
160 + return makeKeyringService(store);
161 + })
162 +);
163 +
164 +/**
165 + * Build a `KeyringLive` layer with an explicit macOS backend choice.
166 + * Use this instead of `KeyringLive` when the CLI lets the user pick
167 + * between `subprocess` (safe default) and `ffi` (experimental,
168 + * requires Developer ID signing). The `backend` parameter is
169 + * ignored on Linux and other platforms.
170 + */
171 +export const KeyringLiveWithBackend = (macOSBackend: MacOSBackend): Layer.Layer<KeyringService> =>
172 + Layer.effect(
173 + KeyringService,
174 + Effect.promise(async () => {
175 + const store = await createDefaultStore({ macOSBackend });
176 + setDefaultStore(store);
177 + return makeKeyringService(store);
178 + })
179 + );
180 +
181 +/** Layer built from an explicit store — used by tests. */
182 +export const KeyringLayer = (store: CredentialStore): Layer.Layer<KeyringService> =>
183 + Layer.succeed(KeyringService, makeKeyringService(store));
ts/packages/cli-keyring/src/index.ts new
+95
@@ -0,0 +1,95 @@
1 +/**
2 + * `@composio/cli-keyring` — cross-platform OS credential storage for
3 + * the Composio CLI. Structurally modeled after
4 + * [keyring-rs](https://github.com/open-source-cooperative/keyring-rs)
5 + * but implemented as a thin shell over OS primitives so we own every
6 + * byte of the execution surface and never depend on a third-party
7 + * native module.
8 + *
9 + * Backends:
10 + * - **macOS (Bun runtime)**: direct Security.framework calls via
11 + * `bun:ffi`. ~1ms reads, no subprocess overhead, ACL = allow-any
12 + * (upgrade-stable; identical threat model to the subprocess
13 + * backend until the CLI is Developer ID-signed).
14 + * - **macOS (Node runtime / fallback)**: `/usr/bin/security`
15 + * subprocess. Same semantics, ~25ms reads.
16 + * - **Linux**: `secret-tool` subprocess against the freedesktop
17 + * Secret Service API, with keyring-rs-compatible attribute names.
18 + *
19 + * Typical usage:
20 + *
21 + * ```ts
22 + * import { Entry, setDefaultStore, createDefaultStore } from '@composio/cli-keyring';
23 + *
24 + * setDefaultStore(await createDefaultStore());
25 + *
26 + * const entry = new Entry('com.composio.cli', 'default');
27 + * await entry.setPassword(apiKey);
28 + * const stored = await entry.getPassword();
29 + * await entry.deleteCredential();
30 + * ```
31 + */
32 +
33 +export { Entry } from './core/entry';
34 +export { KeyringError, type KeyringErrorDetails, type KeyringErrorKind } from './core/errors';
35 +export { CredentialPersistence } from './core/persistence';
36 +export {
37 + type CredentialStore,
38 + type EntryModifiers,
39 + setDefaultStore,
40 + unsetDefaultStore,
41 + getDefaultStore,
42 + hasDefaultStore,
43 +} from './core/store';
44 +
45 +import type { CredentialStore } from './core/store';
46 +import { createMacOSStore, createMacOSStoreSync, type MacOSBackend } from './stores/macos-security';
47 +import { LinuxSecretToolStore } from './stores/linux-secret-tool';
48 +import { UnsupportedPlatformStore } from './stores/unsupported';
49 +
50 +/**
51 + * Instantiate the native store for the current platform (async). On
52 + * macOS under Bun this resolves to the fast FFI backend; under Node
53 + * (typically tests or tools that import this package without Bun) it
54 + * falls back to the `/usr/bin/security` subprocess backend. On Linux
55 + * it always returns the `secret-tool` subprocess backend. Unsupported
56 + * platforms return a store whose operations throw `NoStorageAccess`.
57 + *
58 + * Call this once at process startup, pass the result to
59 + * `setDefaultStore`, and use `new Entry(service, user)` everywhere.
60 + */
61 +export async function createDefaultStore(
62 + options: { macOSBackend?: MacOSBackend } = {}
63 +): Promise<CredentialStore> {
64 + switch (process.platform) {
65 + case 'darwin':
66 + return await createMacOSStore(options.macOSBackend ?? 'auto');
67 + case 'linux':
68 + return new LinuxSecretToolStore();
69 + default:
70 + return new UnsupportedPlatformStore(process.platform);
71 + }
72 +}
73 +
74 +/**
75 + * Synchronous fallback that never returns the FFI macOS backend —
76 + * useful for callers that can't await at construction time (e.g. the
77 + * Effect.ts `Layer.sync` variant) and are willing to accept the
78 + * subprocess overhead. The async `createDefaultStore()` is strongly
79 + * preferred in the CLI's hot path.
80 + */
81 +export function createDefaultStoreSync(): CredentialStore {
82 + switch (process.platform) {
83 + case 'darwin':
84 + return createMacOSStoreSync();
85 + case 'linux':
86 + return new LinuxSecretToolStore();
87 + default:
88 + return new UnsupportedPlatformStore(process.platform);
89 + }
90 +}
91 +
92 +export { createMacOSStore, createMacOSStoreSync, type MacOSBackend } from './stores/macos-security';
93 +export { MacOSSecuritySubprocessStore } from './stores/macos-security-subprocess';
94 +export { LinuxSecretToolStore } from './stores/linux-secret-tool';
95 +export { UnsupportedPlatformStore } from './stores/unsupported';
ts/packages/cli-keyring/src/stores/linux-secret-tool.ts new
+259
@@ -0,0 +1,259 @@
1 +/**
2 + * Linux Secret Service store backed by the `secret-tool` CLI.
3 + *
4 + * This is a structural port of the `dbus-secret-service-keyring-store`
5 + * crate from keyring-rs. The Rust version speaks the
6 + * `org.freedesktop.Secret.Service` D-Bus protocol directly via the
7 + * `dbus-secret-service` crate; we invoke `secret-tool`, a one-line
8 + * wrapper shipped in the `libsecret-tools` (Debian/Ubuntu) or
9 + * `libsecret` (Fedora/Arch) package that exposes the exact same
10 + * Secret Service operations. Using the CLI keeps the execution surface
11 + * auditable and lets us stay off FFI entirely.
12 + *
13 + * Attribute naming follows keyring-rs for interop with any other
14 + * keyring-rs-based tool the user might run on the same system:
15 + *
16 + * service → the application / service name
17 + * username → the user / account
18 + * target → the Secret Service collection (default: "default")
19 + *
20 + * Labels default to `keyring:{user}@{service}`, matching
21 + * `dbus-secret-service-keyring-store`'s default label format.
22 + */
23 +
24 +import { existsSync } from 'node:fs';
25 +import type { CredentialStore, EntryModifiers } from '../core/store';
26 +import { CredentialPersistence } from '../core/persistence';
27 +import { KeyringError } from '../core/errors';
28 +import {
29 + bytesToUtf8,
30 + decodeSecret,
31 + encodeSecret,
32 + runCommand,
33 + utf8ToBytes,
34 + type SpawnResult,
35 +} from './shared';
36 +
37 +const SECRET_TOOL_BIN = 'secret-tool';
38 +
39 +function validateSpecifier(service: string, user: string): void {
40 + if (service.includes('\0')) {
41 + throw new KeyringError({
42 + kind: 'Invalid',
43 + param: 'service',
44 + reason: 'service must not contain NUL bytes',
45 + });
46 + }
47 + if (user.includes('\0')) {
48 + throw new KeyringError({
49 + kind: 'Invalid',
50 + param: 'user',
51 + reason: 'user must not contain NUL bytes',
52 + });
53 + }
54 +}
55 +
56 +function attributeArgs(
57 + service: string,
58 + user: string,
59 + modifiers: EntryModifiers
60 +): readonly string[] {
61 + // Match keyring-rs's attribute keys exactly so credentials stored by
62 + // this package are readable by any Rust tool using keyring-rs (and
63 + // vice-versa) on the same session.
64 + return ['service', service, 'username', user, 'target', modifiers.collection ?? 'default'];
65 +}
66 +
67 +/**
68 + * Classify a spawn error into a KeyringError. We can't rely on `code`
69 + * alone because `secret-tool` returns `1` for almost every failure;
70 + * stderr text is the main signal.
71 + */
72 +function classifyFailure(result: SpawnResult, operation: string): KeyringError {
73 + const stderr = bytesToUtf8(result.stderr).trim();
74 +
75 + // D-Bus errors that mean "the session bus or the secret daemon is
76 + // unreachable" — headless systems, containers, or SSH without a
77 + // running keyring. Treat as NoStorageAccess so callers can fall back
78 + // to on-disk config.
79 + if (
80 + stderr.includes('org.freedesktop.DBus.Error.ServiceUnknown') ||
81 + stderr.includes('org.freedesktop.DBus.Error.NoReply') ||
82 + stderr.includes('Cannot autolaunch D-Bus without X11') ||
83 + stderr.includes('Cannot spawn a message bus') ||
84 + stderr.includes('No such interface') ||
85 + stderr.includes('secret_service_get_sync')
86 + ) {
87 + return new KeyringError({
88 + kind: 'NoStorageAccess',
89 + cause: new Error(stderr || `${operation} failed: D-Bus Secret Service unreachable`),
90 + });
91 + }
92 +
93 + // "The collection does not exist" / "Prompt was dismissed" usually
94 + // means the user cancelled an unlock prompt.
95 + if (stderr.includes('dismissed') || stderr.includes('does not exist')) {
96 + return new KeyringError({
97 + kind: 'NoStorageAccess',
98 + cause: new Error(stderr),
99 + });
100 + }
101 +
102 + return new KeyringError({
103 + kind: 'PlatformFailure',
104 + cause: new Error(stderr || `${operation} failed with exit ${result.code}`),
105 + });
106 +}
107 +
108 +function missingDBus(): boolean {
109 + // `secret-tool` requires a session bus. When SSHing without bus
110 + // forwarding, neither var is set. We fail fast with a clear message
111 + // instead of letting the user wait for `dbus-daemon --session` to
112 + // time out.
113 + return (
114 + process.env.DBUS_SESSION_BUS_ADDRESS === undefined &&
115 + !existsSync(`/run/user/${process.getuid?.() ?? -1}/bus`)
116 + );
117 +}
118 +
119 +export class LinuxSecretToolStore implements CredentialStore {
120 + readonly id = 'linux-secret-tool';
121 + readonly vendor = 'freedesktop.org Secret Service (via secret-tool)';
122 +
123 + persistence(): CredentialPersistence {
124 + return CredentialPersistence.UntilDelete;
125 + }
126 +
127 + async setSecret(
128 + service: string,
129 + user: string,
130 + secret: Uint8Array,
131 + modifiers: EntryModifiers
132 + ): Promise<void> {
133 + validateSpecifier(service, user);
134 + if (missingDBus()) {
135 + throw new KeyringError({
136 + kind: 'NoStorageAccess',
137 + cause: new Error(
138 + 'D-Bus session bus not available — no DBUS_SESSION_BUS_ADDRESS and no /run/user/<uid>/bus'
139 + ),
140 + });
141 + }
142 +
143 + const encoded = encodeSecret(secret);
144 + const label = modifiers.label ?? defaultLabel(service, user);
145 + const args = ['store', '--label', label, ...attributeArgs(service, user, modifiers)];
146 +
147 + // `secret-tool store` reads the password from stdin (one line,
148 + // terminated by LF). encodeSecret returns ASCII base64 with our
149 + // `b64:` prefix, so it's always a single printable line.
150 + let result: SpawnResult;
151 + try {
152 + result = await runCommand({
153 + command: SECRET_TOOL_BIN,
154 + args,
155 + stdin: utf8ToBytes(encoded + '\n'),
156 + });
157 + } catch (err) {
158 + throw this.spawnErrorToKeyringError(err);
159 + }
160 +
161 + if (result.code === 0) return;
162 + throw classifyFailure(result, 'secret-tool store');
163 + }
164 +
165 + async getSecret(service: string, user: string, modifiers: EntryModifiers): Promise<Uint8Array> {
166 + validateSpecifier(service, user);
167 + if (missingDBus()) {
168 + throw new KeyringError({
169 + kind: 'NoStorageAccess',
170 + cause: new Error(
171 + 'D-Bus session bus not available — no DBUS_SESSION_BUS_ADDRESS and no /run/user/<uid>/bus'
172 + ),
173 + });
174 + }
175 +
176 + const args = ['lookup', ...attributeArgs(service, user, modifiers)];
177 +
178 + let result: SpawnResult;
179 + try {
180 + result = await runCommand({ command: SECRET_TOOL_BIN, args });
181 + } catch (err) {
182 + throw this.spawnErrorToKeyringError(err);
183 + }
184 +
185 + if (result.code === 0) {
186 + const stdout = bytesToUtf8(result.stdout);
187 + // `secret-tool lookup` prints the password without a trailing
188 + // newline when found, and prints nothing (exit 0) when not found.
189 + if (stdout.length === 0) {
190 + throw new KeyringError({ kind: 'NoEntry' });
191 + }
192 + try {
193 + return decodeSecret(stdout);
194 + } catch (err) {
195 + throw new KeyringError({
196 + kind: 'BadDataFormat',
197 + bytes: new Uint8Array(result.stdout),
198 + cause: err,
199 + });
200 + }
201 + }
202 +
203 + // Exit 1 can mean many things — stderr is the real signal.
204 + throw classifyFailure(result, 'secret-tool lookup');
205 + }
206 +
207 + async deleteCredential(service: string, user: string, modifiers: EntryModifiers): Promise<void> {
208 + validateSpecifier(service, user);
209 + if (missingDBus()) {
210 + throw new KeyringError({
211 + kind: 'NoStorageAccess',
212 + cause: new Error(
213 + 'D-Bus session bus not available — no DBUS_SESSION_BUS_ADDRESS and no /run/user/<uid>/bus'
214 + ),
215 + });
216 + }
217 +
218 + // `secret-tool clear` returns exit 0 regardless of whether any
219 + // entry matched, so we probe with `lookup` first to preserve the
220 + // NoEntry semantics the rest of the package relies on.
221 + await this.getSecret(service, user, modifiers); // throws NoEntry if missing
222 +
223 + const args = ['clear', ...attributeArgs(service, user, modifiers)];
224 + let result: SpawnResult;
225 + try {
226 + result = await runCommand({ command: SECRET_TOOL_BIN, args });
227 + } catch (err) {
228 + throw this.spawnErrorToKeyringError(err);
229 + }
230 + if (result.code === 0) return;
231 + throw classifyFailure(result, 'secret-tool clear');
232 + }
233 +
234 + private spawnErrorToKeyringError(err: unknown): KeyringError {
235 + // ENOENT from child_process means `secret-tool` isn't on PATH.
236 + // Surface a helpful install hint rather than the raw errno.
237 + if (
238 + typeof err === 'object' &&
239 + err !== null &&
240 + 'code' in err &&
241 + (err as { code?: string }).code === 'ENOENT'
242 + ) {
243 + return new KeyringError({
244 + kind: 'NoStorageAccess',
245 + cause: new Error(
246 + 'secret-tool not found. Install it with: ' +
247 + 'apt install libsecret-tools (Debian/Ubuntu) / ' +
248 + 'dnf install libsecret (Fedora) / ' +
249 + 'pacman -S libsecret (Arch)'
250 + ),
251 + });
252 + }
253 + return new KeyringError({ kind: 'NoStorageAccess', cause: err });
254 + }
255 +}
256 +
257 +function defaultLabel(service: string, user: string): string {
258 + return `keyring:${user}@${service}`;
259 +}
ts/packages/cli-keyring/src/stores/macos-security-ffi.ts new
+606
@@ -0,0 +1,606 @@
1 +/**
2 + * macOS Keychain store backed by direct Security.framework calls via
3 + * `bun:ffi`. Structurally this is a TypeScript port of the relevant
4 + * subset of keyring-rs's `apple-native-keyring-store` crate — which
5 + * itself delegates to the `security-framework` Rust crate — but we
6 + * skip the Rust layer and call the C ABI directly from Bun.
7 + *
8 + * Why FFI instead of the subprocess `/usr/bin/security` CLI?
9 + *
10 + * - **Performance.** A subprocess fork/exec round-trip is ~25ms
11 + * median and ~150ms p99 on a warm Mac. A direct `SecItemCopyMatching`
12 + * call is sub-millisecond. For hot-path commands (`composio execute`,
13 + * `composio run`) this is a 25× improvement per invocation with
14 + * effectively zero tail.
15 + * - **Upgrade-stable ACL.** The item's access control is built with
16 + * `SecAccessCreate` + the "allow-any" pattern (empty trusted apps
17 + * list, no-prompt selector — mirrors what `security -A` produces),
18 + * so the ACL does not depend on the composio binary's code
19 + * signature. `composio upgrade` never triggers a keychain dialog.
20 + *
21 + * The allow-any ACL matches the threat model of the subprocess
22 + * implementation exactly: silent exfil via a plaintext file becomes
23 + * visible exfil via the Bash tool prompt ("claude wants to run
24 + * /usr/bin/security find-generic-password …"), but the OS does not
25 + * gate reads to our binary specifically. Upgrading this to a
26 + * per-binary ACL requires the `composio` binary to be signed with a
27 + * stable Developer ID certificate so the ACL's designated
28 + * requirement can survive self-update — that is a separate
29 + * operational PR, not handled here. When it lands, the
30 + * `buildAllowAnyAccess` call in `setSecret` is replaced with a
31 + * single call to a new `buildComposioOnlyAccess` builder that
32 + * constructs a `SecAccessRef` with the composio binary in the
33 + * trusted list. The rest of the module is unchanged.
34 + *
35 + * Pointer representation: every CoreFoundation / Security
36 + * reference is carried as `bigint`, never `number`. Reason: short
37 + * `CFString` values and other small CF types are represented as
38 + * **tagged pointers** in CoreFoundation — the string data is packed
39 + * directly into pointer bits with the high bits set as tag
40 + * markers, producing addresses above 2^53. JavaScript's `number`
41 + * type loses precision above that threshold, so a tagged pointer
42 + * received as `number` cannot be passed back to another FFI call
43 + * intact. Declaring every pointer arg/return as `FFIType.u64`
44 + * preserves full 64-bit fidelity via `BigInt`.
45 + *
46 + * This module must not be imported from Node — it depends on
47 + * `bun:ffi`. The platform picker in `macos-security.ts` is
48 + * responsible for loading this file only when `typeof Bun !==
49 + * 'undefined'`.
50 + */
51 +
52 +import { dlopen, FFIType, ptr, toArrayBuffer } from 'bun:ffi';
53 +import type { CredentialStore, EntryModifiers } from '../core/store';
54 +import { CredentialPersistence } from '../core/persistence';
55 +import { KeyringError } from '../core/errors';
56 +import { bytesToUtf8, decodeSecret, encodeSecret, runCommand } from './shared';
57 +
58 +const textEncoder = new TextEncoder();
59 +const textDecoder = new TextDecoder('utf-8');
60 +const SECURITY_BIN = '/usr/bin/security';
61 +
62 +/** Encode a JS string as a NUL-terminated UTF-8 byte array (for dlopen/dlsym). */
63 +function cstr(s: string): Uint8Array {
64 + return textEncoder.encode(s + '\0');
65 +}
66 +
67 +// -----------------------------------------------------------------------------
68 +// Low-level dlopen / dlsym (used to resolve `kSec*` / `kCF*` extern const
69 +// data symbols that `bun:ffi`'s normal dlopen surface doesn't expose).
70 +// -----------------------------------------------------------------------------
71 +
72 +const LIBSYSTEM = '/usr/lib/libSystem.B.dylib';
73 +const SECURITY_FRAMEWORK = '/System/Library/Frameworks/Security.framework/Security';
74 +const CORE_FOUNDATION = '/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation';
75 +
76 +const RTLD_NOW = 0x2;
77 +
78 +const libSystem = dlopen(LIBSYSTEM, {
79 + dlopen: { args: [FFIType.ptr, FFIType.i32], returns: FFIType.u64 },
80 + dlsym: { args: [FFIType.u64, FFIType.ptr], returns: FFIType.u64 },
81 +});
82 +
83 +function dlopenRaw(path: string): bigint {
84 + const handle = libSystem.symbols.dlopen(cstr(path), RTLD_NOW);
85 + if (handle === 0n) {
86 + throw new KeyringError({
87 + kind: 'PlatformFailure',
88 + cause: new Error(`dlopen(${path}) failed`),
89 + });
90 + }
91 + return handle;
92 +}
93 +
94 +/**
95 + * Resolve an extern const CFTypeRef data symbol: `dlsym` returns the
96 + * address of the storage slot (i.e. a pointer-to-pointer); we
97 + * dereference one level via `read.ptr` to get the actual CFTypeRef
98 + * value stored there. The symbol is stable for the process lifetime,
99 + * so caching the resolved BigInt is safe.
100 + */
101 +function dlsymCFConstant(handle: bigint, name: string): bigint {
102 + const addr = libSystem.symbols.dlsym(handle, cstr(name));
103 + if (addr === 0n) {
104 + throw new KeyringError({
105 + kind: 'PlatformFailure',
106 + cause: new Error(`dlsym(${name}) failed`),
107 + });
108 + }
109 + // read.ptr wants a number address — the storage address from dlsym
110 + // is a real heap address (never tagged), so it fits in a number.
111 + // The VALUE we read back, however, may be a tagged pointer, so we
112 + // must capture it as BigInt. `read.ptr` on bun returns number;
113 + // instead we use a small helper that reads 8 bytes into a BigInt.
114 + return read64(Number(addr));
115 +}
116 +
117 +/**
118 + * Read a 64-bit little-endian value from a process address and
119 + * return it as BigInt. Used to dereference data-symbol slots (which
120 + * live at plain heap addresses) without precision loss on the
121 + * stored value.
122 + */
123 +function read64(address: number): bigint {
124 + // `toArrayBuffer(ptr, offset, length)` wraps a raw pointer as an
125 + // ArrayBuffer view without copying. We use it for read-only access
126 + // to an 8-byte window, then pull the BigInt out via DataView.
127 + const ab = toArrayBuffer(address as unknown as never, 0, 8);
128 + return new DataView(ab).getBigUint64(0, true);
129 +}
130 +
131 +const securityHandle = dlopenRaw(SECURITY_FRAMEWORK);
132 +const coreFoundationHandle = dlopenRaw(CORE_FOUNDATION);
133 +
134 +// -----------------------------------------------------------------------------
135 +// Function bindings (CoreFoundation + Security.framework)
136 +// -----------------------------------------------------------------------------
137 +
138 +const cf = dlopen(CORE_FOUNDATION, {
139 + CFStringCreateWithBytes: {
140 + // allocator, bytes, length, encoding, isExternalRepresentation
141 + args: [FFIType.u64, FFIType.ptr, FFIType.i64, FFIType.u32, FFIType.bool],
142 + returns: FFIType.u64,
143 + },
144 + CFStringGetCString: {
145 + args: [FFIType.u64, FFIType.ptr, FFIType.i64, FFIType.u32],
146 + returns: FFIType.bool,
147 + },
148 + CFDataCreate: {
149 + args: [FFIType.u64, FFIType.ptr, FFIType.i64],
150 + returns: FFIType.u64,
151 + },
152 + CFDataGetBytePtr: {
153 + args: [FFIType.u64],
154 + returns: FFIType.u64,
155 + },
156 + CFDataGetLength: {
157 + args: [FFIType.u64],
158 + returns: FFIType.i64,
159 + },
160 + CFDictionaryCreateMutable: {
161 + args: [FFIType.u64, FFIType.i64, FFIType.u64, FFIType.u64],
162 + returns: FFIType.u64,
163 + },
164 + CFDictionaryAddValue: {
165 + args: [FFIType.u64, FFIType.u64, FFIType.u64],
166 + returns: FFIType.void,
167 + },
168 + CFArrayGetCount: {
169 + args: [FFIType.u64],
170 + returns: FFIType.i64,
171 + },
172 + CFArrayGetValueAtIndex: {
173 + args: [FFIType.u64, FFIType.i64],
174 + returns: FFIType.u64,
175 + },
176 + CFRelease: {
177 + args: [FFIType.u64],
178 + returns: FFIType.void,
179 + },
180 + CFGetTypeID: {
181 + args: [FFIType.u64],
182 + returns: FFIType.u64,
183 + },
184 +});
185 +
186 +const sec = dlopen(SECURITY_FRAMEWORK, {
187 + SecItemAdd: {
188 + args: [FFIType.u64, FFIType.u64],
189 + returns: FFIType.i32,
190 + },
191 + SecItemCopyMatching: {
192 + args: [FFIType.u64, FFIType.u64],
193 + returns: FFIType.i32,
194 + },
195 + SecItemUpdate: {
196 + args: [FFIType.u64, FFIType.u64],
197 + returns: FFIType.i32,
198 + },
199 + SecItemDelete: {
200 + args: [FFIType.u64],
201 + returns: FFIType.i32,
202 + },
203 + SecCopyErrorMessageString: {
204 + args: [FFIType.i32, FFIType.u64],
205 + returns: FFIType.u64,
206 + },
207 +});
208 +
209 +// -----------------------------------------------------------------------------
210 +// Constant resolution
211 +// -----------------------------------------------------------------------------
212 +
213 +/** Resolved extern CFTypeRef constants (stable for process lifetime). */
214 +const K = {
215 + kSecClass: dlsymCFConstant(securityHandle, 'kSecClass'),
216 + kSecClassGenericPassword: dlsymCFConstant(securityHandle, 'kSecClassGenericPassword'),
217 + kSecAttrService: dlsymCFConstant(securityHandle, 'kSecAttrService'),
218 + kSecAttrAccount: dlsymCFConstant(securityHandle, 'kSecAttrAccount'),
219 + kSecValueData: dlsymCFConstant(securityHandle, 'kSecValueData'),
220 + kSecReturnData: dlsymCFConstant(securityHandle, 'kSecReturnData'),
221 + kSecMatchLimit: dlsymCFConstant(securityHandle, 'kSecMatchLimit'),
222 + kSecMatchLimitOne: dlsymCFConstant(securityHandle, 'kSecMatchLimitOne'),
223 + kCFBooleanTrue: dlsymCFConstant(coreFoundationHandle, 'kCFBooleanTrue'),
224 + kCFTypeDictionaryKeyCallBacks: BigInt(
225 + addressOfSymbol(coreFoundationHandle, 'kCFTypeDictionaryKeyCallBacks')
226 + ),
227 + kCFTypeDictionaryValueCallBacks: BigInt(
228 + addressOfSymbol(coreFoundationHandle, 'kCFTypeDictionaryValueCallBacks')
229 + ),
230 +} as const;
231 +
232 +/**
233 + * Return the *address* of a named data symbol (not its dereferenced
234 + * value). Used for the `kCFType*CallBacks` structs, which are
235 + * structs in static data rather than pointers — the function wants a
236 + * pointer TO the struct, not a pointer read out of the symbol slot.
237 + */
238 +function addressOfSymbol(handle: bigint, name: string): bigint {
239 + const addr = libSystem.symbols.dlsym(handle, cstr(name));
240 + if (addr === 0n) {
241 + throw new KeyringError({
242 + kind: 'PlatformFailure',
243 + cause: new Error(`dlsym(${name}) failed`),
244 + });
245 + }
246 + return addr;
247 +}
248 +
249 +/** UTF-8 encoding constant for CFString. */
250 +const kCFStringEncodingUTF8 = 0x08000100;
251 +
252 +// -----------------------------------------------------------------------------
253 +// OSStatus mapping
254 +// -----------------------------------------------------------------------------
255 +
256 +const errSecSuccess = 0;
257 +const errSecItemNotFound = -25300;
258 +const errSecAuthFailed = -25293;
259 +const errSecNotAvailable = -25291;
260 +const errSecReadOnly = -25292;
261 +const errSecNoSuchKeychain = -25294;
262 +const errSecInvalidKeychain = -25295;
263 +const errSecWrPerm = -61;
264 +
265 +const NO_STORAGE_ACCESS_STATUSES = new Set([
266 + errSecNotAvailable,
267 + errSecReadOnly,
268 + errSecNoSuchKeychain,
269 + errSecInvalidKeychain,
270 + errSecAuthFailed,
271 + errSecWrPerm,
272 +]);
273 +
274 +/**
275 + * Convert an OSStatus into a KeyringError. Uses
276 + * `SecCopyErrorMessageString` to pull the human-readable description
277 + * out of the Security framework.
278 + */
279 +function osStatusToError(status: number, operation: string): KeyringError {
280 + if (status === errSecItemNotFound) {
281 + return new KeyringError({ kind: 'NoEntry' });
282 + }
283 + const message = osStatusMessage(status) ?? `${operation} failed with OSStatus ${status}`;
284 + if (NO_STORAGE_ACCESS_STATUSES.has(status)) {
285 + return new KeyringError({
286 + kind: 'NoStorageAccess',
287 + cause: new Error(message),
288 + });
289 + }
290 + return new KeyringError({
291 + kind: 'PlatformFailure',
292 + cause: new Error(`${operation}: ${message}`),
293 + });
294 +}
295 +
296 +function osStatusMessage(status: number): string | null {
297 + const cfString = sec.symbols.SecCopyErrorMessageString(status, 0n);
298 + if (cfString === 0n) return null;
299 + try {
300 + return cfStringToJs(cfString);
301 + } finally {
302 + cf.symbols.CFRelease(cfString);
303 + }
304 +}
305 +
306 +// -----------------------------------------------------------------------------
307 +// CoreFoundation helpers
308 +// -----------------------------------------------------------------------------
309 +
310 +/**
311 + * A "retain pool" that releases every CF object pushed into it when
312 + * `release()` runs. Used to guarantee cleanup across the (potentially
313 + * many) CF allocations each store operation performs.
314 + */
315 +class CFPool {
316 + private readonly refs: bigint[] = [];
317 +
318 + /** Push a CFTypeRef into the pool and return it unchanged for chaining. */
319 + retain(ref: bigint): bigint {
320 + if (ref !== 0n) this.refs.push(ref);
321 + return ref;
322 + }
323 +
324 + release(): void {
325 + // Release in reverse order of allocation to match object graph.
326 + for (let i = this.refs.length - 1; i >= 0; i--) {
327 + cf.symbols.CFRelease(this.refs[i]!);
328 + }
329 + this.refs.length = 0;
330 + }
331 +}
332 +
333 +/** Create a CFString from a JS string (UTF-8 bytes). Throws on allocation failure. */
334 +function cfStringFromJs(pool: CFPool, s: string): bigint {
335 + const bytes = textEncoder.encode(s);
336 + const ref = cf.symbols.CFStringCreateWithBytes(
337 + 0n, // kCFAllocatorDefault
338 + bytes,
339 + BigInt(bytes.byteLength),
340 + kCFStringEncodingUTF8,
341 + false
342 + );
343 + if (ref === 0n) {
344 + throw new KeyringError({
345 + kind: 'PlatformFailure',
346 + cause: new Error('CFStringCreateWithBytes returned NULL'),
347 + });
348 + }
349 + return pool.retain(ref);
350 +}
351 +
352 +/** Read a CFString into a JS UTF-8 string. Only used for error messages. */
353 +function cfStringToJs(cfString: bigint): string {
354 + const buf = new Uint8Array(4096);
355 + const ok = cf.symbols.CFStringGetCString(
356 + cfString,
357 + buf,
358 + BigInt(buf.byteLength),
359 + kCFStringEncodingUTF8
360 + );
361 + if (!ok) return '<unrepresentable>';
362 + const end = buf.indexOf(0);
363 + return textDecoder.decode(buf.subarray(0, end === -1 ? buf.byteLength : end));
364 +}
365 +
366 +/** Extract raw bytes from a CFData. */
367 +function cfDataToBytes(cfData: bigint): Uint8Array {
368 + const length = Number(cf.symbols.CFDataGetLength(cfData));
369 + if (length === 0) return new Uint8Array();
370 + const bytePtr = cf.symbols.CFDataGetBytePtr(cfData);
371 + if (bytePtr === 0n) {
372 + throw new KeyringError({
373 + kind: 'PlatformFailure',
374 + cause: new Error('CFDataGetBytePtr returned NULL'),
375 + });
376 + }
377 + // CFData storage is a real heap pointer (never tagged), so the
378 + // BigInt value fits in JS safe integer range and we can hand it to
379 + // toArrayBuffer via Number. Copy into JS-owned memory so we don't
380 + // retain the CFData longer than necessary.
381 + const view = new Uint8Array(toArrayBuffer(Number(bytePtr) as unknown as never, 0, length));
382 + return new Uint8Array(view);
383 +}
384 +
385 +/** Build a mutable CFDictionary. */
386 +function cfMutableDict(pool: CFPool): bigint {
387 + const dict = cf.symbols.CFDictionaryCreateMutable(
388 + 0n,
389 + 0n,
390 + K.kCFTypeDictionaryKeyCallBacks,
391 + K.kCFTypeDictionaryValueCallBacks
392 + );
393 + if (dict === 0n) {
394 + throw new KeyringError({
395 + kind: 'PlatformFailure',
396 + cause: new Error('CFDictionaryCreateMutable returned NULL'),
397 + });
398 + }
399 + return pool.retain(dict);
400 +}
401 +
402 +function cfDictSet(dict: bigint, key: bigint, value: bigint): void {
403 + cf.symbols.CFDictionaryAddValue(dict, key, value);
404 +}
405 +
406 +// -----------------------------------------------------------------------------
407 +// Store implementation
408 +// -----------------------------------------------------------------------------
409 +
410 +function validateSpecifier(service: string, user: string): void {
411 + if (service.length === 0) {
412 + throw new KeyringError({
413 + kind: 'Invalid',
414 + param: 'service',
415 + reason: 'service must be a non-empty string',
416 + });
417 + }
418 + if (user.length === 0) {
419 + throw new KeyringError({
420 + kind: 'Invalid',
421 + param: 'user',
422 + reason: 'user must be a non-empty string',
423 + });
424 + }
425 + if (service.includes('\0') || user.includes('\0')) {
426 + throw new KeyringError({
427 + kind: 'Invalid',
428 + param: service.includes('\0') ? 'service' : 'user',
429 + reason: 'must not contain NUL bytes',
430 + });
431 + }
432 +}
433 +
434 +function defaultLabel(service: string, user: string): string {
435 + return `keyring:${user}@${service}`;
436 +}
437 +
438 +export class MacOSSecurityFFIStore implements CredentialStore {
439 + readonly id = 'macos-security-ffi';
440 + readonly vendor = 'Apple Security.framework (via bun:ffi SecItem*)';
441 +
442 + persistence(): CredentialPersistence {
443 + return CredentialPersistence.UntilDelete;
444 + }
445 +
446 + async setSecret(
447 + service: string,
448 + user: string,
449 + secret: Uint8Array,
450 + modifiers: EntryModifiers
451 + ): Promise<void> {
452 + validateSpecifier(service, user);
453 + if (modifiers.keychain !== undefined && modifiers.keychain !== 'User') {
454 + throw new KeyringError({
455 + kind: 'NotSupportedByStore',
456 + operation: `macos keychain domain "${modifiers.keychain}"`,
457 + });
458 + }
459 +
460 + // Writes delegate to `/usr/bin/security add-generic-password -A`
461 + // (subprocess) because that is the ONLY path that reliably produces
462 + // a genuine allow-any ACL. The Security.framework APIs
463 + // (SecAccessCreate + SecACLSetSimpleContents with NULL
464 + // applicationList + zero selector) should theoretically produce the
465 + // same result, but in practice the items they produce still trigger
466 + // the macOS trust dialog ("X wants to access key Y") when read
467 + // from a different binary. Apple's `security` CLI uses internal
468 + // codepaths that bypass this limitation.
469 + //
470 + // The write happens once per login/migration — its ~25ms cost is
471 + // irrelevant relative to the network round-trip that follows. The
472 + // hot path (reads on every `composio execute`) stays on FFI at
473 + // ~1ms via SecItemCopyMatching.
474 + const encoded = encodeSecret(secret);
475 + const label = modifiers.label ?? defaultLabel(service, user);
476 +
477 + // Delete-then-add pattern instead of `-U` (update-if-exists).
478 + //
479 + // `-U` updates the password but PRESERVES the old ACL. If the
480 + // entry was previously created by the FFI ACL builder (which
481 + // produces per-binary ACLs — see the long comment block above),
482 + // the old broken ACL survives the `-U` update and the allow-any
483 + // flag from `-A` is silently ignored. Deleting first guarantees
484 + // the new `add-generic-password -A` creates a fresh entry with
485 + // a genuine allow-any ACL.
486 + //
487 + // The delete is best-effort — if the entry doesn't exist yet
488 + // (first login), the delete fails with errSecItemNotFound (exit
489 + // 44) and we proceed to the add.
490 + try {
491 + await runCommand({
492 + command: SECURITY_BIN,
493 + args: ['delete-generic-password', '-a', user, '-s', service],
494 + });
495 + } catch {
496 + // Spawn failure is fine — entry may not exist.
497 + }
498 +
499 + // `-A` = allow any application to read without prompting
500 + // `-l` = human-readable label (shown in Keychain Access)
501 + // `-w` = password value (on argv — brief `ps` visibility,
502 + // documented in the package README)
503 + const args = [
504 + 'add-generic-password',
505 + '-A',
506 + '-a',
507 + user,
508 + '-s',
509 + service,
510 + '-l',
511 + label,
512 + '-w',
513 + encoded,
514 + ];
515 +
516 + let result;
517 + try {
518 + result = await runCommand({ command: SECURITY_BIN, args });
519 + } catch (err) {
520 + throw new KeyringError({ kind: 'NoStorageAccess', cause: err });
521 + }
522 +
523 + if (result.code === 0) return;
524 +
525 + const stderr = bytesToUtf8(result.stderr).trim();
526 + throw new KeyringError({
527 + kind: 'PlatformFailure',
528 + cause: new Error(stderr || `security add-generic-password failed with exit ${result.code}`),
529 + });
530 + }
531 +
532 + async getSecret(service: string, user: string, modifiers: EntryModifiers): Promise<Uint8Array> {
533 + validateSpecifier(service, user);
534 + if (modifiers.keychain !== undefined && modifiers.keychain !== 'User') {
535 + throw new KeyringError({
536 + kind: 'NotSupportedByStore',
537 + operation: `macos keychain domain "${modifiers.keychain}"`,
538 + });
539 + }
540 +
541 + const pool = new CFPool();
542 + try {
543 + const query = cfMutableDict(pool);
544 + cfDictSet(query, K.kSecClass, K.kSecClassGenericPassword);
545 + cfDictSet(query, K.kSecAttrService, cfStringFromJs(pool, service));
546 + cfDictSet(query, K.kSecAttrAccount, cfStringFromJs(pool, user));
547 + cfDictSet(query, K.kSecReturnData, K.kCFBooleanTrue);
548 + cfDictSet(query, K.kSecMatchLimit, K.kSecMatchLimitOne);
549 +
550 + // SecItemCopyMatching writes a CFTypeRef (here: CFDataRef because
551 + // kSecReturnData=true, kSecMatchLimit=One) into the 8-byte slot.
552 + const resultOut = new Uint8Array(8);
553 + const status = sec.symbols.SecItemCopyMatching(query, BigInt(ptr(resultOut)));
554 + if (status !== errSecSuccess) {
555 + throw osStatusToError(status, 'SecItemCopyMatching');
556 + }
557 + const cfData = new DataView(resultOut.buffer).getBigUint64(0, true);
558 + if (cfData === 0n) {
559 + throw new KeyringError({ kind: 'NoEntry' });
560 + }
561 + try {
562 + const encoded = cfDataToBytes(cfData);
563 + // Legacy-item compatibility: if this entry was written by a
564 + // pre-base64 version of the FFI backend, the bytes won't have
565 + // the `b64:` prefix. `decodeSecret` throws in that case; we
566 + // fall back to returning the raw bytes so one-time reads of
567 + // old entries still work (the next setPassword call
568 + // rewrites them in the canonical format).
569 + try {
570 + return decodeSecret(bytesToUtf8(encoded));
571 + } catch {
572 + return encoded;
573 + }
574 + } finally {
575 + cf.symbols.CFRelease(cfData);
576 + }
577 + } finally {
578 + pool.release();
579 + }
580 + }
581 +
582 + async deleteCredential(service: string, user: string, modifiers: EntryModifiers): Promise<void> {
583 + validateSpecifier(service, user);
584 + if (modifiers.keychain !== undefined && modifiers.keychain !== 'User') {
585 + throw new KeyringError({
586 + kind: 'NotSupportedByStore',
587 + operation: `macos keychain domain "${modifiers.keychain}"`,
588 + });
589 + }
590 +
591 + const pool = new CFPool();
592 + try {
593 + const query = cfMutableDict(pool);
594 + cfDictSet(query, K.kSecClass, K.kSecClassGenericPassword);
595 + cfDictSet(query, K.kSecAttrService, cfStringFromJs(pool, service));
596 + cfDictSet(query, K.kSecAttrAccount, cfStringFromJs(pool, user));
597 +
598 + const status = sec.symbols.SecItemDelete(query);
599 + if (status !== errSecSuccess) {
600 + throw osStatusToError(status, 'SecItemDelete');
601 + }
602 + } finally {
603 + pool.release();
604 + }
605 + }
606 +}
ts/packages/cli-keyring/src/stores/macos-security-subprocess.ts new
+243
@@ -0,0 +1,243 @@
1 +/**
2 + * macOS Keychain store backed by the `/usr/bin/security` CLI.
3 + *
4 + * This is a structural port of the `apple-native-keyring-store` crate
5 + * from keyring-rs. The Rust version calls Security.framework via
6 + * `security-framework::os::macos::passwords::{find,set}_generic_password`;
7 + * we shell out to `/usr/bin/security`'s `add-generic-password`,
8 + * `find-generic-password`, and `delete-generic-password` subcommands
9 + * because they are 1:1 wrappers over the same Security.framework APIs,
10 + * ship with every macOS, and give us a trivially auditable execution
11 + * surface vs. FFI.
12 + *
13 + * Exit-code mapping is taken from `decode_error` in
14 + * `apple-native-keyring-store/src/keychain.rs`:
15 + *
16 + * errSecItemNotFound (-25300) → NoEntry
17 + * errSecNotAvailable (-25291) → NoStorageAccess
18 + * errSecReadOnly (-25292) → NoStorageAccess
19 + * errSecNoSuchKeychain (-25294) → NoStorageAccess
20 + * errSecInvalidKeychain (-25295) → NoStorageAccess
21 + * errSecAuthFailed (-25293) → NoStorageAccess
22 + * everything else → PlatformFailure
23 + *
24 + * The `security` CLI translates OSStatus values to its own exit codes
25 + * (typically the low byte of the OSStatus), which is why we see exit
26 + * 44 for item-not-found instead of -25300.
27 + */
28 +
29 +import type { CredentialStore, EntryModifiers } from '../core/store';
30 +import { CredentialPersistence } from '../core/persistence';
31 +import { KeyringError } from '../core/errors';
32 +import { bytesToUtf8, decodeSecret, encodeSecret, runCommand, type SpawnResult } from './shared';
33 +
34 +const SECURITY_BIN = '/usr/bin/security';
35 +
36 +/** `security` CLI exit code for `errSecItemNotFound`. */
37 +const EXIT_ITEM_NOT_FOUND = 44;
38 +/** `security` CLI exit code for `errSecDuplicateItem`. */
39 +const EXIT_DUPLICATE_ITEM = 45;
40 +/**
41 + * Exit codes that translate to `NoStorageAccess`. These correspond to
42 + * the OSStatus values keyring-rs's `decode_error` maps to the same
43 + * variant — keychain locked, read-only mount, missing/invalid keychain
44 + * domain, or auth failure when the user cancels an unlock prompt.
45 + */
46 +const EXIT_NO_STORAGE_ACCESS = new Set([36, 37, 50, 51, 45401]);
47 +
48 +/** Map the `keychain` modifier onto the `-A`/-domain flags of `security`. */
49 +function domainFlag(domain: EntryModifiers['keychain']): readonly string[] {
50 + // The `security` CLI picks the login keychain by default, which is
51 + // the `User` domain. The other domains require the -A / --keychain
52 + // flag with a specific path; surface them as NotSupportedByStore for
53 + // v0 so we don't silently write to the wrong place.
54 + if (domain === undefined || domain === 'User') {
55 + return [];
56 + }
57 + throw new KeyringError({
58 + kind: 'NotSupportedByStore',
59 + operation: `macos keychain domain "${domain}"`,
60 + });
61 +}
62 +
63 +function validateSpecifier(service: string, user: string): void {
64 + // Empty service or user would become wildcards in Keychain Services
65 + // — keyring-rs throws `Error::Invalid` here and we match that.
66 + if (service.includes('\0')) {
67 + throw new KeyringError({
68 + kind: 'Invalid',
69 + param: 'service',
70 + reason: 'service must not contain NUL bytes',
71 + });
72 + }
73 + if (user.includes('\0')) {
74 + throw new KeyringError({
75 + kind: 'Invalid',
76 + param: 'user',
77 + reason: 'user must not contain NUL bytes',
78 + });
79 + }
80 +}
81 +
82 +function classifyExitCode(result: SpawnResult, operation: string): KeyringError {
83 + const code = result.code;
84 + const stderr = bytesToUtf8(result.stderr).trim();
85 + if (code === EXIT_ITEM_NOT_FOUND) {
86 + return new KeyringError({ kind: 'NoEntry' });
87 + }
88 + if (code !== null && EXIT_NO_STORAGE_ACCESS.has(code)) {
89 + return new KeyringError({
90 + kind: 'NoStorageAccess',
91 + cause: new Error(stderr || `security ${operation} failed with exit ${code}`),
92 + });
93 + }
94 + return new KeyringError({
95 + kind: 'PlatformFailure',
96 + cause: new Error(stderr || `security ${operation} failed with exit ${code}`),
97 + });
98 +}
99 +
100 +export class MacOSSecuritySubprocessStore implements CredentialStore {
101 + readonly id = 'macos-security-subprocess';
102 + readonly vendor = 'Apple Security.framework (via /usr/bin/security)';
103 +
104 + persistence(): CredentialPersistence {
105 + return CredentialPersistence.UntilDelete;
106 + }
107 +
108 + async setSecret(
109 + service: string,
110 + user: string,
111 + secret: Uint8Array,
112 + modifiers: EntryModifiers
113 + ): Promise<void> {
114 + validateSpecifier(service, user);
115 + const encoded = encodeSecret(secret);
116 + const label = modifiers.label ?? defaultLabel(service, user);
117 + const domainArgs = domainFlag(modifiers.keychain);
118 +
119 + // Delete-then-add pattern instead of `-U`: the `-U` flag updates
120 + // the password of an existing entry but PRESERVES the old ACL.
121 + // If a previous composio version wrote this entry with a
122 + // per-binary ACL (e.g. the FFI ACL builder in an earlier beta),
123 + // `-U` would leave that ACL in place and our `-A` flag would be
124 + // silently ignored. Deleting first guarantees a fresh allow-any
125 + // ACL on the next add.
126 + //
127 + // The delete is best-effort — if no entry exists yet (first
128 + // login / clean install), `security` exits with 44 (itemNotFound)
129 + // and we proceed to the add.
130 + try {
131 + await runCommand({
132 + command: SECURITY_BIN,
133 + args: ['delete-generic-password', '-a', user, '-s', service, ...domainArgs],
134 + });
135 + } catch {
136 + // Spawn failure (e.g. /usr/bin/security missing) — the add
137 + // below will hit the same failure and surface it properly.
138 + }
139 +
140 + // -A: allow ANY application to read this item without prompting
141 + // (produces a genuine allow-any ACL — the only configuration
142 + // that works reliably for reads from an ad-hoc signed
143 + // composio binary via /usr/bin/security).
144 + // -l: human-readable label (shown in Keychain Access).
145 + //
146 + // Password leak risk: `-w <value>` puts the secret on argv, so it
147 + // is briefly visible in `ps` output. This matches the behavior of
148 + // every OTHER tool that shells out to `security` (git credential
149 + // osxkeychain, 1Password CLI, etc.). Callers that can't tolerate
150 + // this are expected to fall back to the on-disk `~/.composio/`
151 + // user config — the CLI already owns that code path.
152 + const args = [
153 + 'add-generic-password',
154 + '-A',
155 + '-a',
156 + user,
157 + '-s',
158 + service,
159 + '-l',
160 + label,
161 + '-w',
162 + encoded,
163 + ...domainArgs,
164 + ];
165 +
166 + let result: SpawnResult;
167 + try {
168 + result = await runCommand({ command: SECURITY_BIN, args });
169 + } catch (err) {
170 + throw new KeyringError({ kind: 'NoStorageAccess', cause: err });
171 + }
172 +
173 + if (result.code === 0) return;
174 +
175 + if (result.code === EXIT_DUPLICATE_ITEM) {
176 + throw new KeyringError({
177 + kind: 'PlatformFailure',
178 + cause: new Error(
179 + 'security add-generic-password: delete-then-add produced duplicate. ' +
180 + 'The existing item may have an ACL that blocks deletion — ' +
181 + 'run `security delete-generic-password -s com.composio.cli -a default` manually.'
182 + ),
183 + });
184 + }
185 + throw classifyExitCode(result, 'add-generic-password');
186 + }
187 +
188 + async getSecret(service: string, user: string, modifiers: EntryModifiers): Promise<Uint8Array> {
189 + validateSpecifier(service, user);
190 + const domainArgs = domainFlag(modifiers.keychain);
191 +
192 + // -w prints the password to stdout and nothing else. Without -w,
193 + // `security` dumps the item's attributes in a human-readable form
194 + // that's painful to parse.
195 + const args = ['find-generic-password', '-a', user, '-s', service, '-w', ...domainArgs];
196 +
197 + let result: SpawnResult;
198 + try {
199 + result = await runCommand({ command: SECURITY_BIN, args });
200 + } catch (err) {
201 + throw new KeyringError({ kind: 'NoStorageAccess', cause: err });
202 + }
203 +
204 + if (result.code !== 0) {
205 + throw classifyExitCode(result, 'find-generic-password');
206 + }
207 +
208 + // `security -w` prints the value followed by \n. Strip exactly one
209 + // trailing newline — the base64 alphabet does not contain \n, so
210 + // any remaining whitespace would be a malformed blob.
211 + const stdout = bytesToUtf8(result.stdout).replace(/\n$/, '');
212 + try {
213 + return decodeSecret(stdout);
214 + } catch (err) {
215 + throw new KeyringError({
216 + kind: 'BadDataFormat',
217 + bytes: new Uint8Array(result.stdout),
218 + cause: err,
219 + });
220 + }
221 + }
222 +
223 + async deleteCredential(service: string, user: string, modifiers: EntryModifiers): Promise<void> {
224 + validateSpecifier(service, user);
225 + const domainArgs = domainFlag(modifiers.keychain);
226 + const args = ['delete-generic-password', '-a', user, '-s', service, ...domainArgs];
227 +
228 + let result: SpawnResult;
229 + try {
230 + result = await runCommand({ command: SECURITY_BIN, args });
231 + } catch (err) {
232 + throw new KeyringError({ kind: 'NoStorageAccess', cause: err });
233 + }
234 +
235 + if (result.code === 0) return;
236 + throw classifyExitCode(result, 'delete-generic-password');
237 + }
238 +}
239 +
240 +/** Default label matches the format keyring-rs generates on Linux (`keyring:{user}@{service}`). */
241 +function defaultLabel(service: string, user: string): string {
242 + return `keyring:${user}@${service}`;
243 +}
ts/packages/cli-keyring/src/stores/macos-security.ts new
+62
@@ -0,0 +1,62 @@
1 +/**
2 + * macOS backend picker.
3 + *
4 + * The production CLI runs on Bun, so the FFI backend is the default
5 + * there — it's ~25× faster per read than the subprocess backend and
6 + * has no p99 tail. In Node environments (tests, dev tools that import
7 + * this package without Bun), `bun:ffi` is not available; we fall back
8 + * to the subprocess backend, which shells out to `/usr/bin/security`.
9 + *
10 + * Both backends expose the same `CredentialStore` interface so the
11 + * rest of the package is agnostic about which one is active.
12 + */
13 +
14 +import type { CredentialStore } from '../core/store';
15 +import { MacOSSecuritySubprocessStore } from './macos-security-subprocess';
16 +
17 +/**
18 + * Backend selector for `createMacOSStore`.
19 + *
20 + * - `"auto"` / `"subprocess"`: shell out to `/usr/bin/security` for
21 + * every operation. ~25ms per call, no ACL dialogs, works with
22 + * unsigned / ad-hoc signed callers. Safe default.
23 + * - `"ffi"`: call Security.framework directly via `bun:ffi`. ~1ms
24 + * per read, but currently triggers a macOS trust dialog when the
25 + * calling binary is not signed with a stable Developer ID.
26 + * Experimental — opt-in only. Falls back to subprocess when
27 + * `bun:ffi` is unavailable (Node runtime).
28 + */
29 +export type MacOSBackend = 'auto' | 'subprocess' | 'ffi';
30 +
31 +const isBun = typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined';
32 +
33 +/**
34 + * Resolve the appropriate macOS store for the current runtime.
35 + *
36 + * Defaults to `"auto"` which picks the subprocess backend — the only
37 + * path that reliably avoids macOS keychain trust dialogs for ad-hoc
38 + * signed binaries. Callers can opt into `"ffi"` for the ~25× perf win
39 + * if and only if the calling binary is signed with a stable Developer
40 + * ID certificate (dialogs appear otherwise).
41 + */
42 +export async function createMacOSStore(backend: MacOSBackend = 'auto'): Promise<CredentialStore> {
43 + if (backend === 'ffi' && isBun) {
44 + const mod = await import('./macos-security-ffi');
45 + return new mod.MacOSSecurityFFIStore();
46 + }
47 + return new MacOSSecuritySubprocessStore();
48 +}
49 +
50 +/**
51 + * Synchronous variant — returns the subprocess backend unconditionally.
52 + * Callers that cannot await (e.g. `createDefaultStore()` used by the
53 + * CLI's synchronous Effect layer construction) can use this at the
54 + * cost of giving up the FFI opt-in.
55 + */
56 +export function createMacOSStoreSync(): CredentialStore {
57 + return new MacOSSecuritySubprocessStore();
58 +}
59 +
60 +// Re-export both concrete stores for callers that want to wire a
61 +// specific one by hand (tests, benchmarks, diagnostics).
62 +export { MacOSSecuritySubprocessStore } from './macos-security-subprocess';
ts/packages/cli-keyring/src/stores/shared.ts new
+166
@@ -0,0 +1,166 @@
1 +/**
2 + * Subprocess plumbing shared by the macOS and Linux stores.
3 + *
4 + * Both stores shell out to OS-provided CLIs (`/usr/bin/security` and
5 + * `secret-tool`) via `node:child_process`. Keeping the spawn helper
6 + * here means the backends only have to deal with argv construction
7 + * and exit-code mapping — not stream buffering.
8 + */
9 +
10 +import { spawn, type SpawnOptionsWithoutStdio } from 'node:child_process';
11 +
12 +const textEncoder = new TextEncoder();
13 +const textDecoder = new TextDecoder('utf-8');
14 +
15 +export interface SpawnResult {
16 + readonly code: number | null;
17 + readonly signal: NodeJS.Signals | null;
18 + readonly stdout: Uint8Array;
19 + readonly stderr: Uint8Array;
20 +}
21 +
22 +export interface SpawnInput {
23 + readonly command: string;
24 + readonly args: readonly string[];
25 + /**
26 + * Raw bytes to write to stdin before closing it. Used by the Linux
27 + * store to pipe passwords into `secret-tool store` without putting
28 + * them on argv.
29 + */
30 + readonly stdin?: Uint8Array;
31 + readonly env?: NodeJS.ProcessEnv;
32 +}
33 +
34 +/**
35 + * Concatenate an array of Uint8Arrays without going through Buffer.
36 + */
37 +function concatBytes(chunks: readonly Uint8Array[]): Uint8Array {
38 + let total = 0;
39 + for (const chunk of chunks) total += chunk.byteLength;
40 + const out = new Uint8Array(total);
41 + let offset = 0;
42 + for (const chunk of chunks) {
43 + out.set(chunk, offset);
44 + offset += chunk.byteLength;
45 + }
46 + return out;
47 +}
48 +
49 +/**
50 + * Spawn a subprocess and return all output buffered. Resolves once
51 + * the process exits; never rejects — errors from failed spawns (e.g.
52 + * ENOENT when `secret-tool` isn't installed) surface as a rejected
53 + * promise with the original `Error`, which callers convert into a
54 + * `KeyringError({ kind: 'NoStorageAccess' })` or similar.
55 + */
56 +export function runCommand(input: SpawnInput): Promise<SpawnResult> {
57 + return new Promise((resolve, reject) => {
58 + const options: SpawnOptionsWithoutStdio = {
59 + stdio: ['pipe', 'pipe', 'pipe'],
60 + env: input.env,
61 + };
62 + let child;
63 + try {
64 + child = spawn(input.command, [...input.args], options);
65 + } catch (err) {
66 + reject(err);
67 + return;
68 + }
69 +
70 + const stdoutChunks: Uint8Array[] = [];
71 + const stderrChunks: Uint8Array[] = [];
72 +
73 + child.stdout.on('data', (chunk: Uint8Array) => stdoutChunks.push(chunk));
74 + child.stderr.on('data', (chunk: Uint8Array) => stderrChunks.push(chunk));
75 +
76 + child.once('error', err => reject(err));
77 + child.once('close', (code, signal) => {
78 + resolve({
79 + code,
80 + signal,
81 + stdout: concatBytes(stdoutChunks),
82 + stderr: concatBytes(stderrChunks),
83 + });
84 + });
85 +
86 + if (input.stdin !== undefined) {
87 + child.stdin.end(input.stdin);
88 + } else {
89 + child.stdin.end();
90 + }
91 + });
92 +}
93 +
94 +/** Decode a byte slice as UTF-8. */
95 +export function bytesToUtf8(bytes: Uint8Array): string {
96 + return textDecoder.decode(bytes);
97 +}
98 +
99 +/** Encode a JS string as UTF-8 bytes. */
100 +export function utf8ToBytes(s: string): Uint8Array {
101 + return textEncoder.encode(s);
102 +}
103 +
104 +/**
105 + * Universal on-disk encoding for stored secrets. We base64-encode
106 + * every secret before handing it to `security` / `secret-tool` because:
107 + *
108 + * 1. `security -w` takes the password on argv and cannot carry binary
109 + * bytes (NUL bytes truncate; newlines break parsing).
110 + * 2. `secret-tool store` reads one line from stdin via
111 + * `g_io_channel_read_line`, which can't carry NUL bytes or embedded
112 + * newlines either.
113 + *
114 + * The tradeoff is that credentials written by this package are NOT
115 + * readable by other tools that share the same keychain namespace —
116 + * they'll see `<base64 blob>` instead of the original value. For the
117 + * CLI's use case (our own API key) that's fine, and the prefix tag
118 + * keeps us honest about what we're doing.
119 + */
120 +const STORAGE_PREFIX = 'b64:';
121 +
122 +/**
123 + * Encode bytes to base64 via `btoa` on a binary latin-1 string —
124 + * avoids `Buffer` and works in every runtime that provides the HTML5
125 + * `btoa` global (Node 16+, Bun, browsers).
126 + */
127 +function bytesToBase64(bytes: Uint8Array): string {
128 + let binary = '';
129 + for (let i = 0; i < bytes.byteLength; i++) {
130 + binary += String.fromCharCode(bytes[i]!);
131 + }
132 + return btoa(binary);
133 +}
134 +
135 +function base64ToBytes(b64: string): Uint8Array {
136 + const binary = atob(b64);
137 + const bytes = new Uint8Array(binary.length);
138 + for (let i = 0; i < binary.length; i++) {
139 + bytes[i] = binary.charCodeAt(i);
140 + }
141 + return bytes;
142 +}
143 +
144 +/** Encode raw bytes into the on-disk format. */
145 +export function encodeSecret(secret: Uint8Array): string {
146 + return STORAGE_PREFIX + bytesToBase64(secret);
147 +}
148 +
149 +/**
150 + * Decode the on-disk format back into raw bytes. Throws a plain
151 + * `Error` on malformed input; callers wrap it in
152 + * `KeyringError({ kind: 'BadDataFormat' })`.
153 + */
154 +export function decodeSecret(stored: string): Uint8Array {
155 + const trimmed = stored.replace(/\n$/, '');
156 + if (!trimmed.startsWith(STORAGE_PREFIX)) {
157 + throw new Error(`expected keyring value to start with "${STORAGE_PREFIX}" prefix`);
158 + }
159 + const encoded = trimmed.slice(STORAGE_PREFIX.length);
160 + // Strict validation — `atob` is lenient and malformed blobs would
161 + // silently decode to truncated garbage otherwise.
162 + if (!/^[A-Za-z0-9+/]*={0,2}$/.test(encoded)) {
163 + throw new Error('keyring value contains non-base64 characters');
164 + }
165 + return base64ToBytes(encoded);
166 +}
ts/packages/cli-keyring/src/stores/unsupported.ts new
+44
@@ -0,0 +1,44 @@
1 +/**
2 + * Fallback store used on unsupported platforms (Windows, BSDs, …).
3 + *
4 + * Every operation throws `KeyringError({ kind: 'NoStorageAccess' })`
5 + * so the CLI can fall back to the legacy on-disk config without the
6 + * platform check leaking into caller code.
7 + */
8 +
9 +import type { CredentialStore } from '../core/store';
10 +import { CredentialPersistence } from '../core/persistence';
11 +import { KeyringError } from '../core/errors';
12 +
13 +export class UnsupportedPlatformStore implements CredentialStore {
14 + readonly id = 'unsupported';
15 + readonly vendor: string;
16 +
17 + constructor(platform: string) {
18 + this.vendor = `unsupported platform (${platform})`;
19 + }
20 +
21 + persistence(): CredentialPersistence {
22 + return CredentialPersistence.Unspecified;
23 + }
24 +
25 + async setSecret(): Promise<void> {
26 + throw this.unavailable();
27 + }
28 + async getSecret(): Promise<never> {
29 + throw this.unavailable();
30 + }
31 + async deleteCredential(): Promise<void> {
32 + throw this.unavailable();
33 + }
34 +
35 + private unavailable(): KeyringError {
36 + return new KeyringError({
37 + kind: 'NoStorageAccess',
38 + cause: new Error(
39 + `@composio/cli-keyring does not yet support ${this.vendor}. ` +
40 + 'Only macOS (Keychain via /usr/bin/security) and Linux (Secret Service via secret-tool) are implemented.'
41 + ),
42 + });
43 + }
44 +}
ts/packages/cli-keyring/test/e2e.test.ts new
+67
@@ -0,0 +1,67 @@
1 +/**
2 + * Real-keystore roundtrip test.
3 + *
4 + * Gated behind `COMPOSIO_KEYRING_E2E=1` so CI and the default
5 + * `pnpm test` run don't touch the user's keychain. Run locally with:
6 + *
7 + * COMPOSIO_KEYRING_E2E=1 pnpm --filter @composio/cli-keyring test
8 + *
9 + * Each test uses a UUID-suffixed service name so parallel runs (and
10 + * leftover entries from crashed runs) never collide with the user's
11 + * real credentials.
12 + */
13 +
14 +import { describe, it, expect, afterAll, beforeAll } from 'vitest';
15 +import { randomUUID } from 'node:crypto';
16 +import { Entry } from '../src/core/entry';
17 +import { KeyringError } from '../src/core/errors';
18 +import { createDefaultStore, setDefaultStore } from '../src/index';
19 +
20 +const enabled = process.env.COMPOSIO_KEYRING_E2E === '1';
21 +const suite = enabled ? describe : describe.skip;
22 +
23 +suite('e2e: real OS keystore', () => {
24 + beforeAll(async () => {
25 + setDefaultStore(await createDefaultStore());
26 + });
27 +
28 + const service = `com.composio.cli.test.${randomUUID()}`;
29 + const user = 'default';
30 + const entry = new Entry(service, user);
31 +
32 + afterAll(async () => {
33 + try {
34 + await entry.deleteCredential();
35 + } catch (err) {
36 + if (!(err instanceof KeyringError) || err.kind !== 'NoEntry') {
37 + throw err;
38 + }
39 + }
40 + });
41 +
42 + it('roundtrips a password', async () => {
43 + const password = `test-${randomUUID()}`;
44 + await entry.setPassword(password);
45 + expect(await entry.getPassword()).toBe(password);
46 + });
47 +
48 + it('overwrites on repeated setPassword', async () => {
49 + await entry.setPassword('first');
50 + await entry.setPassword('second');
51 + expect(await entry.getPassword()).toBe('second');
52 + });
53 +
54 + it('delete then get throws NoEntry', async () => {
55 + await entry.setPassword('x');
56 + await entry.deleteCredential();
57 + await expect(entry.getPassword()).rejects.toSatisfy(
58 + (err: unknown) => err instanceof KeyringError && err.kind === 'NoEntry'
59 + );
60 + });
61 +
62 + it('roundtrips binary bytes', async () => {
63 + const bytes = new Uint8Array([0, 1, 2, 3, 255, 254, 253]);
64 + await entry.setSecret(bytes);
65 + expect(Array.from(await entry.getSecret())).toEqual(Array.from(bytes));
66 + });
67 +});
ts/packages/cli-keyring/test/entry.test.ts new
+131
@@ -0,0 +1,131 @@
1 +import { describe, it, expect, beforeEach, afterEach } from 'vitest';
2 +import { Entry } from '../src/core/entry';
3 +import { KeyringError } from '../src/core/errors';
4 +import {
5 + type CredentialStore,
6 + setDefaultStore,
7 + unsetDefaultStore,
8 + hasDefaultStore,
9 + getDefaultStore,
10 +} from '../src/core/store';
11 +import { CredentialPersistence } from '../src/core/persistence';
12 +
13 +/**
14 + * In-memory store used by every unit test. Lets us exercise Entry's
15 + * routing and validation logic without shelling out to a real keystore.
16 + */
17 +class MemoryStore implements CredentialStore {
18 + readonly id = 'memory';
19 + readonly vendor = 'test in-memory';
20 + private readonly items = new Map<string, Uint8Array>();
21 +
22 + persistence() {
23 + return CredentialPersistence.ProcessOnly;
24 + }
25 +
26 + private key(service: string, user: string) {
27 + return `${service}\0${user}`;
28 + }
29 +
30 + async setSecret(service: string, user: string, secret: Uint8Array) {
31 + this.items.set(this.key(service, user), new Uint8Array(secret));
32 + }
33 +
34 + async getSecret(service: string, user: string) {
35 + const v = this.items.get(this.key(service, user));
36 + if (v === undefined) throw new KeyringError({ kind: 'NoEntry' });
37 + return v;
38 + }
39 +
40 + async deleteCredential(service: string, user: string) {
41 + if (!this.items.delete(this.key(service, user))) {
42 + throw new KeyringError({ kind: 'NoEntry' });
43 + }
44 + }
45 +}
46 +
47 +describe('Entry', () => {
48 + let store: MemoryStore;
49 +
50 + beforeEach(() => {
51 + store = new MemoryStore();
52 + setDefaultStore(store);
53 + });
54 +
55 + afterEach(() => {
56 + unsetDefaultStore();
57 + });
58 +
59 + it('rejects empty service', () => {
60 + expect(() => new Entry('', 'user')).toThrowError(KeyringError);
61 + try {
62 + new Entry('', 'user');
63 + } catch (err) {
64 + expect(err).toBeInstanceOf(KeyringError);
65 + expect((err as KeyringError).kind).toBe('Invalid');
66 + }
67 + });
68 +
69 + it('rejects empty user', () => {
70 + expect(() => new Entry('svc', '')).toThrowError(KeyringError);
71 + });
72 +
73 + it('roundtrips a UTF-8 password', async () => {
74 + const entry = new Entry('com.composio.cli', 'default');
75 + await entry.setPassword('hunter2-😀');
76 + expect(await entry.getPassword()).toBe('hunter2-😀');
77 + });
78 +
79 + it('throws NoEntry when reading a missing credential', async () => {
80 + const entry = new Entry('com.composio.cli', 'nobody');
81 + await expect(entry.getPassword()).rejects.toSatisfy(
82 + (err: unknown) => err instanceof KeyringError && err.kind === 'NoEntry'
83 + );
84 + });
85 +
86 + it('throws BadEncoding when stored bytes are not valid UTF-8', async () => {
87 + const entry = new Entry('com.composio.cli', 'binaryuser');
88 + await entry.setSecret(new Uint8Array([0xff, 0xfe, 0xfd]));
89 + await expect(entry.getPassword()).rejects.toSatisfy(
90 + (err: unknown) => err instanceof KeyringError && err.kind === 'BadEncoding'
91 + );
92 + });
93 +
94 + it('roundtrips raw binary bytes', async () => {
95 + const entry = new Entry('com.composio.cli', 'binaryuser');
96 + const bytes = new Uint8Array([0, 1, 2, 3, 4, 255]);
97 + await entry.setSecret(bytes);
98 + const got = await entry.getSecret();
99 + expect(Array.from(got)).toEqual(Array.from(bytes));
100 + });
101 +
102 + it('deleteCredential removes the entry and future reads throw NoEntry', async () => {
103 + const entry = new Entry('com.composio.cli', 'default');
104 + await entry.setPassword('secret');
105 + await entry.deleteCredential();
106 + await expect(entry.getPassword()).rejects.toSatisfy(
107 + (err: unknown) => err instanceof KeyringError && err.kind === 'NoEntry'
108 + );
109 + });
110 +
111 + it('overrides the default store via constructor argument', async () => {
112 + const other = new MemoryStore();
113 + const entry = new Entry('svc', 'user', {}, other);
114 + await entry.setPassword('x');
115 + // Default store should still be empty.
116 + await expect(new Entry('svc', 'user').getPassword()).rejects.toSatisfy(
117 + (err: unknown) => err instanceof KeyringError && err.kind === 'NoEntry'
118 + );
119 + expect(await entry.getPassword()).toBe('x');
120 + });
121 +
122 + it('throws NoDefaultStore when no store is registered', async () => {
123 + unsetDefaultStore();
124 + expect(hasDefaultStore()).toBe(false);
125 + expect(() => getDefaultStore()).toThrowError(KeyringError);
126 + const entry = new Entry('svc', 'user');
127 + await expect(entry.getPassword()).rejects.toSatisfy(
128 + (err: unknown) => err instanceof KeyringError && err.kind === 'NoDefaultStore'
129 + );
130 + });
131 +});
ts/packages/cli-keyring/test/errors.test.ts new
+42
@@ -0,0 +1,42 @@
1 +import { describe, it, expect } from 'vitest';
2 +import { KeyringError } from '../src/core/errors';
3 +
4 +describe('KeyringError', () => {
5 + it('exposes kind via getter and .is() predicate', () => {
6 + const err = new KeyringError({ kind: 'NoEntry' });
7 + expect(err.kind).toBe('NoEntry');
8 + expect(err.is('NoEntry')).toBe(true);
9 + expect(err.is('PlatformFailure')).toBe(false);
10 + });
11 +
12 + it('preserves the underlying cause chain for PlatformFailure', () => {
13 + const inner = new Error('boom');
14 + const err = new KeyringError({ kind: 'PlatformFailure', cause: inner });
15 + expect((err as { cause?: unknown }).cause).toBe(inner);
16 + expect(err.message).toContain('boom');
17 + });
18 +
19 + it('formats a readable message for every variant', () => {
20 + const cases: KeyringError[] = [
21 + new KeyringError({ kind: 'NoEntry' }),
22 + new KeyringError({ kind: 'NoDefaultStore' }),
23 + new KeyringError({ kind: 'PlatformFailure', cause: new Error('x') }),
24 + new KeyringError({ kind: 'NoStorageAccess', cause: 'locked' }),
25 + new KeyringError({ kind: 'BadEncoding', bytes: new Uint8Array([0xff, 0xfe]) }),
26 + new KeyringError({
27 + kind: 'BadDataFormat',
28 + bytes: new Uint8Array(),
29 + cause: new Error('nope'),
30 + }),
31 + new KeyringError({ kind: 'BadStoreFormat', detail: 'corrupt' }),
32 + new KeyringError({ kind: 'TooLong', attr: 'service', limit: 1024 }),
33 + new KeyringError({ kind: 'Invalid', param: 'user', reason: 'empty' }),
34 + new KeyringError({ kind: 'Ambiguous', matches: [] }),
35 + new KeyringError({ kind: 'NotSupportedByStore', operation: 'updateAttributes' }),
36 + ];
37 + for (const err of cases) {
38 + expect(err.message.length).toBeGreaterThan(0);
39 + expect(err.name).toBe('KeyringError');
40 + }
41 + });
42 +});
ts/packages/cli-keyring/test/ffi.test.ts new
+113
@@ -0,0 +1,113 @@
1 +/**
2 + * FFI-backend roundtrip test — exercises the real `bun:ffi`
3 + * `SecItem*` path against the live macOS keychain.
4 + *
5 + * Gated twice: the test only runs when
6 + *
7 + * - we are in Bun (`globalThis.Bun !== undefined`), AND
8 + * - `COMPOSIO_KEYRING_E2E=1` is set in the env.
9 + *
10 + * The first gate keeps the file inert when vitest runs under Node
11 + * (where importing `bun:ffi` would crash at module load). The second
12 + * keeps CI and the default `pnpm test` run from touching the user's
13 + * real keychain.
14 + *
15 + * Run locally with:
16 + *
17 + * COMPOSIO_KEYRING_E2E=1 bun --bun x vitest run test/ffi.test.ts
18 + */
19 +
20 +import { describe, it, expect, beforeAll, afterAll } from 'vitest';
21 +import { randomUUID } from 'node:crypto';
22 +import { Entry } from '../src/core/entry';
23 +import { KeyringError } from '../src/core/errors';
24 +import { setDefaultStore, unsetDefaultStore } from '../src/core/store';
25 +import type { CredentialStore } from '../src/core/store';
26 +
27 +const underBun = typeof (globalThis as { Bun?: unknown }).Bun !== 'undefined';
28 +const enabled = underBun && process.env.COMPOSIO_KEYRING_E2E === '1';
29 +const suite = enabled ? describe : describe.skip;
30 +
31 +suite('ffi: MacOSSecurityFFIStore roundtrip', () => {
32 + let store: CredentialStore;
33 +
34 + beforeAll(async () => {
35 + // Import dynamically — never touch this module from Node.
36 + const mod = await import('../src/stores/macos-security-ffi');
37 + store = new mod.MacOSSecurityFFIStore();
38 + setDefaultStore(store);
39 + });
40 +
41 + afterAll(() => {
42 + unsetDefaultStore();
43 + });
44 +
45 + it('reports the expected id and vendor', () => {
46 + expect(store.id).toBe('macos-security-ffi');
47 + expect(store.vendor).toContain('bun:ffi');
48 + });
49 +
50 + it('roundtrips a password', async () => {
51 + const entry = new Entry(`com.composio.cli.ffi.${randomUUID()}`, 'default');
52 + try {
53 + const password = `ffi-${randomUUID()}`;
54 + await entry.setPassword(password);
55 + expect(await entry.getPassword()).toBe(password);
56 + } finally {
57 + try {
58 + await entry.deleteCredential();
59 + } catch {
60 + /* best-effort cleanup */
61 + }
62 + }
63 + });
64 +
65 + it('overwrites on repeated setPassword without duplicate error', async () => {
66 + const entry = new Entry(`com.composio.cli.ffi.${randomUUID()}`, 'default');
67 + try {
68 + await entry.setPassword('first');
69 + await entry.setPassword('second');
70 + await entry.setPassword('third');
71 + expect(await entry.getPassword()).toBe('third');
72 + } finally {
73 + try {
74 + await entry.deleteCredential();
75 + } catch {
76 + /* best-effort cleanup */
77 + }
78 + }
79 + });
80 +
81 + it('throws NoEntry for a missing credential', async () => {
82 + const entry = new Entry(`com.composio.cli.ffi.nonexistent.${randomUUID()}`, 'default');
83 + await expect(entry.getPassword()).rejects.toSatisfy(
84 + (err: unknown) => err instanceof KeyringError && err.kind === 'NoEntry'
85 + );
86 + });
87 +
88 + it('roundtrips arbitrary binary bytes', async () => {
89 + const entry = new Entry(`com.composio.cli.ffi.bin.${randomUUID()}`, 'default');
90 + try {
91 + const bytes = new Uint8Array(256);
92 + for (let i = 0; i < 256; i++) bytes[i] = i;
93 + await entry.setSecret(bytes);
94 + const got = await entry.getSecret();
95 + expect(Array.from(got)).toEqual(Array.from(bytes));
96 + } finally {
97 + try {
98 + await entry.deleteCredential();
99 + } catch {
100 + /* best-effort cleanup */
101 + }
102 + }
103 + });
104 +
105 + it('delete then read throws NoEntry', async () => {
106 + const entry = new Entry(`com.composio.cli.ffi.del.${randomUUID()}`, 'default');
107 + await entry.setPassword('x');
108 + await entry.deleteCredential();
109 + await expect(entry.getPassword()).rejects.toSatisfy(
110 + (err: unknown) => err instanceof KeyringError && err.kind === 'NoEntry'
111 + );
112 + });
113 +});
ts/packages/cli-keyring/test/shared.test.ts new
+36
@@ -0,0 +1,36 @@
1 +import { describe, it, expect } from 'vitest';
2 +import { encodeSecret, decodeSecret } from '../src/stores/shared';
3 +
4 +describe('shared encoding', () => {
5 + it('roundtrips arbitrary bytes through base64 with the b64: prefix', () => {
6 + const inputs: Uint8Array[] = [
7 + new Uint8Array(),
8 + new Uint8Array([0]),
9 + new Uint8Array([1, 2, 3, 4, 5]),
10 + new Uint8Array([0xff, 0xfe, 0xfd]),
11 + new Uint8Array(Buffer.from('plain string', 'utf8')),
12 + new Uint8Array(Buffer.from('password with spaces\nand newline', 'utf8')),
13 + // 1 KiB of pseudo-random data
14 + crypto.getRandomValues(new Uint8Array(1024)),
15 + ];
16 + for (const bytes of inputs) {
17 + const encoded = encodeSecret(bytes);
18 + expect(encoded.startsWith('b64:')).toBe(true);
19 + const decoded = decodeSecret(encoded);
20 + expect(Array.from(decoded)).toEqual(Array.from(bytes));
21 + }
22 + });
23 +
24 + it('tolerates a trailing newline from CLI stdout', () => {
25 + const encoded = encodeSecret(new Uint8Array([1, 2, 3]));
26 + expect(Array.from(decodeSecret(encoded + '\n'))).toEqual([1, 2, 3]);
27 + });
28 +
29 + it('rejects blobs without the b64: prefix', () => {
30 + expect(() => decodeSecret('no-prefix-here')).toThrowError();
31 + });
32 +
33 + it('rejects blobs with non-base64 characters after the prefix', () => {
34 + expect(() => decodeSecret('b64:!!!not-base64!!!')).toThrowError();
35 + });
36 +});
ts/packages/cli-keyring/tsconfig.json new
+8
@@ -0,0 +1,8 @@
1 +{
2 + "$schema": "https://json.schemastore.org/tsconfig",
3 + "extends": "./tsconfig.options.json",
4 + "compilerOptions": {
5 + "rootDir": "."
6 + },
7 + "include": ["src/**/*", "test/**/*", "package.json"]
8 +}
ts/packages/cli-keyring/tsconfig.options.json new
+23
@@ -0,0 +1,23 @@
1 +{
2 + "$schema": "https://json.schemastore.org/tsconfig",
3 + "compilerOptions": {
4 + "target": "es2022",
5 + "module": "es2022",
6 + "lib": ["es2022"],
7 + "declaration": true,
8 + "outDir": "./dist",
9 + "rootDir": ".",
10 + "strict": true,
11 + "esModuleInterop": true,
12 + "moduleResolution": "bundler",
13 + "skipLibCheck": true,
14 + "resolveJsonModule": true,
15 + "pretty": true,
16 + "noImplicitReturns": true,
17 + "noFallthroughCasesInSwitch": true,
18 + "noUnusedLocals": false,
19 + "noUnusedParameters": false,
20 + "types": ["node", "bun-types"]
21 + },
22 + "exclude": ["node_modules", "**/dist"]
23 +}
ts/packages/cli-keyring/tsconfig.src.json new
+10
@@ -0,0 +1,10 @@
1 +{
2 + "$schema": "https://json.schemastore.org/tsconfig",
3 + "extends": "./tsconfig.options.json",
4 + "compilerOptions": {
5 + "outDir": "./dist",
6 + "rootDir": "."
7 + },
8 + "include": ["src/**/*", "package.json"],
9 + "exclude": ["node_modules", "../../../node_modules", "**/dist"]
10 +}
ts/packages/cli-keyring/tsconfig.test.json new
+9
@@ -0,0 +1,9 @@
1 +{
2 + "$schema": "https://json.schemastore.org/tsconfig",
3 + "extends": "./tsconfig.options.json",
4 + "compilerOptions": {
5 + "rootDir": "."
6 + },
7 + "include": ["src/**/*", "test/**/*", "package.json"],
8 + "exclude": ["node_modules", "../../../node_modules", "**/dist"]
9 +}
ts/packages/cli-keyring/tsdown.config.ts new
+13
@@ -0,0 +1,13 @@
1 +import { defineConfig } from 'tsdown';
2 +import { baseConfig } from '../../../tsdown.config.base';
3 +
4 +export default defineConfig({
5 + ...baseConfig,
6 + entry: ['src/index.ts', 'src/effect.ts'],
7 + tsconfig: 'tsconfig.src.json',
8 + // bun:ffi is a Bun built-in; in the Node/CJS output it must remain
9 + // an unresolved import so Node never tries to load the FFI backend
10 + // chunk at startup. The runtime branch in stores/macos-security.ts
11 + // guards `isBun` before reaching the dynamic import.
12 + external: [...baseConfig.external, /^bun:/],
13 +});
ts/packages/cli-keyring/vitest.config.ts new
+7
@@ -0,0 +1,7 @@
1 +import { defineConfig } from 'vitest/config';
2 +
3 +export default defineConfig({
4 + test: {
5 + exclude: ['**/node_modules/**', '**/dist/**'],
6 + },
7 +});