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

next
ts 259 lines 8.5 KB
Raw
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 }