12
import type { PlatformError } from '@effect/platform/Error';
13
import type { ParseError } from 'effect/ParseResult';
14
import { APP_CONFIG } from 'src/effects/app-config';
15
+import { KeyringService, KeyringLiveWithBackend } from '@composio/cli-keyring/effect';
16
+import type { KeyringServiceShape } from '@composio/cli-keyring/effect';
17
+import { KeyringError, type MacOSBackend } from '@composio/cli-keyring';
18
+import { ComposioCliUserConfig, ComposioCliUserConfigLive } from 'src/services/cli-user-config';
19
+
20
+/**
21
+ * Keyring specifier for the Composio API key. `service` is a reverse
22
+ * DNS identifier shared by every composio CLI install; `user` is a
23
+ * single fixed slot because the API key is user-scoped (one per
24
+ * logged-in account, independent of which org/project the user is
25
+ * currently working in).
26
+ */
27
+const KEYRING_SERVICE = 'com.composio.cli';
28
+const KEYRING_USER = 'default';
29
+
30
+// -----------------------------------------------------------------------------
31
+// Keyring helpers — extracted from the generator so it stays within
32
+// the max-lines-per-function lint limit. Each helper takes its deps
33
+// as parameters rather than closing over the generator's locals.
34
+// -----------------------------------------------------------------------------
35
+
36
+type KeyringDeps = {
37
+ keyring: KeyringServiceShape;
38
+ useLegacyStorage: boolean;
39
+};
40
+
41
+/**
42
+ * Write `password` into the OS keyring. Returns `true` on success,
43
+ * `false` on `NoStorageAccess` or unexpected errors so the caller
44
+ * can fall back to plaintext. Never propagates — the CLI always
45
+ * prefers "keep working with plaintext fallback" over "crash".
46
+ */
47
+const writeKeyring = (deps: KeyringDeps, password: string) =>
48
+ Effect.gen(function* () {
49
+ if (deps.useLegacyStorage) return false;
50
+ return yield* deps.keyring.setPassword(KEYRING_SERVICE, KEYRING_USER, password).pipe(
51
+ Effect.map(() => true),
52
+ Effect.catchAll(err =>
53
+ Effect.gen(function* () {
54
+ if (err instanceof KeyringError && err.kind === 'NoStorageAccess') {
55
+ yield* Effect.logDebug(
56
+ 'OS keyring unavailable, storing api_key in user_data.json as plaintext. ' +
57
+ `Reason: ${err.message}`
58
+ );
59
+ } else {
60
+ yield* Effect.logDebug(
61
+ 'Unexpected keyring error while writing api_key, falling back to plaintext: ' +
62
+ (err instanceof Error ? err.message : String(err))
63
+ );
64
+ }
65
+ return false;
66
+ })
67
+ )
68
+ );
69
+ });
70
+
71
+/**
72
+ * Read the API key from the OS keyring. Returns `Option.some(value)`
73
+ * if found, `Option.none()` on NoEntry or any failure (with warning
74
+ * logged). The caller falls back to plaintext on `none`.
75
+ */
76
+const readKeyring = (deps: KeyringDeps) =>
77
+ Effect.gen(function* () {
78
+ if (deps.useLegacyStorage) return Option.none<string>();
79
+ return yield* deps.keyring.getPassword(KEYRING_SERVICE, KEYRING_USER).pipe(
80
+ Effect.map(Option.some),
81
+ Effect.catchAll(err =>
82
+ Effect.gen(function* () {
83
+ if (err instanceof KeyringError && err.kind === 'NoEntry') {
84
+ yield* Effect.logDebug('No keyring entry found for Composio API key');
85
+ } else if (err instanceof KeyringError && err.kind === 'NoStorageAccess') {
86
+ // Expected normal path on headless Linux / containers /
87
+ // CI — log at debug to avoid polluting stdout on every
88
+ // CLI invocation. Only the first write attempt would
89
+ // warn loudly (see `writeKeyring`).
90
+ yield* Effect.logDebug(
91
+ 'OS keyring unavailable, falling back to user_data.json. ' + `Reason: ${err.message}`
92
+ );
93
+ } else {
94
+ yield* Effect.logDebug(
95
+ 'Unexpected keyring error while reading api_key, falling back to plaintext: ' +
96
+ (err instanceof Error ? err.message : String(err))
97
+ );
98
+ }
99
+ return Option.none<string>();
100
+ })
101
+ )
102
+ );
103
+ });
104
+
105
+/**
106
+ * Best-effort keyring delete. Swallows `NoEntry` (idempotent) and
107
+ * `NoStorageAccess` (logout should not fail because the keyring is
108
+ * unreachable).
109
+ */
110
+const deleteKeyring = (deps: KeyringDeps) =>
111
+ Effect.gen(function* () {
112
+ if (deps.useLegacyStorage) return;
113
+ yield* deps.keyring.deleteCredential(KEYRING_SERVICE, KEYRING_USER).pipe(
114
+ Effect.catchAll(err =>
115
+ Effect.gen(function* () {
116
+ if (
117
+ err instanceof KeyringError &&
118
+ (err.kind === 'NoEntry' || err.kind === 'NoStorageAccess')
119
+ ) {
120
+ yield* Effect.logDebug(`Keyring delete skipped: ${err.kind}`);
121
+ } else {
122
+ yield* Effect.logWarning(
123
+ 'Keyring delete failed: ' + (err instanceof Error ? err.message : String(err))
124
+ );
125
+ }
126
+ })
127
+ )
128
+ );
129
+ });
130
+
131
+// -----------------------------------------------------------------------------
132
+// Service definition
133
+// -----------------------------------------------------------------------------
134
135
export class ComposioUserContext extends Context.Tag('ComposioUserData')<
136
ComposioUserContext,
137
{
138
readonly data: UserDataWithDefaults;
20
-
21
- /**
22
- * Returns `true` if the user is logged in, i.e., has a valid Composio API key.
23
- */
139
isLoggedIn: () => boolean;
25
-
26
- /**
27
- * Logs out the user by clearing the API key and any other sensitive data.
28
- */
140
logout: Effect.Effect<void, ParseError | PlatformError, never>;
30
-
31
- /**
32
- * Logs in the user by setting the API key, and optionally org ID.
33
- */
141
login: (
142
apiKey: string,
143
orgId?: string,
144
testUserId?: string
145
) => Effect.Effect<void, ParseError | PlatformError, never>;
39
-
40
- /**
41
- * Saves the user data to a persistent store, e.g., file or database.
42
- */
146
update: (data: UserData) => Effect.Effect<void, ParseError | PlatformError, never>;
147
}
148
>() {}
149
47
-export const ComposioUserContextLive = Layer.effect(
150
+export const rawComposioUserContextLive = Layer.effect(
151
ComposioUserContext,
152
Effect.gen(function* () {
153
const fs = yield* FileSystem.FileSystem;
154
const apiKey = yield* APP_CONFIG['USER_API_KEY'];
155
const baseURL = yield* APP_CONFIG['BASE_URL'];
156
const webURL = yield* APP_CONFIG['WEB_URL'];
157
+ const cliConfig = yield* ComposioCliUserConfig;
158
+ const keyring = yield* KeyringService;
159
+
160
+ // `security: "auto"` and `"json"` both keep the API key in
161
+ // plaintext `user_data.json` (the legacy path — same behavior
162
+ // as every prior CLI release). `"keychain-subprocess"` and
163
+ // `"keychain"` opt into the OS credential store.
164
+ const useLegacyStorage =
165
+ cliConfig.data.security === 'auto' || cliConfig.data.security === 'json';
166
+ const kDeps: KeyringDeps = { keyring, useLegacyStorage };
167
55
- /**
56
- * Ensure the cache directory exists before reading/writing user data.
57
- */
168
const cacheDir = yield* setupCacheDir;
169
const jsonUserConfigPath = path.join(cacheDir, constants.USER_CONFIG_FILE_NAME);
170
177
testUserId: Option.none(),
178
});
179
180
+ const writeJson = (snapshot: UserData) =>
181
+ Effect.gen(function* () {
182
+ const onDisk: UserData = useLegacyStorage
183
+ ? snapshot
184
+ : { ...snapshot, apiKey: Option.none() };
185
+ const encoded = yield* userDataToJSON(onDisk);
186
+ const normalized = JSON.stringify(
187
+ (() => {
188
+ const parsed = JSON.parse(encoded) as Record<string, unknown>;
189
+ if (parsed.project_id === null) delete parsed.project_id;
190
+ if (!useLegacyStorage && parsed.api_key === null) delete parsed.api_key;
191
+ return parsed;
192
+ })()
193
+ );
194
+ yield* Effect.logDebug('Saving user data:', normalized);
195
+ yield* fs.writeFileString(jsonUserConfigPath, normalized);
196
+ });
197
+
198
const logout = Effect.gen(function* () {
71
- yield* update({
199
+ yield* deleteKeyring(kDeps);
200
+ const cleared: UserData = {
201
apiKey: Option.none(),
202
baseURL: Option.none(),
203
webURL: Option.some(webURL),
204
orgId: Option.none(),
205
projectId: Option.none(),
206
testUserId: Option.none(),
78
- });
207
+ };
208
+ userData = cleared;
209
+ yield* writeJson(cleared);
210
});
211
212
const login = (apiKey: string, orgId?: string, testUserId?: string) =>
213
Effect.gen(function* () {
83
- yield* update({
214
+ const keyringOk = yield* writeKeyring(kDeps, apiKey);
215
+ const next: UserData = {
216
+ ...userData,
217
apiKey: Option.some(apiKey),
218
baseURL: Option.some(baseURL),
219
webURL: Option.some(webURL),
220
orgId: Option.fromNullable(orgId),
88
- projectId: Option.none(),
221
+ projectId: userData.projectId,
222
testUserId: Option.fromNullable(testUserId),
90
- });
223
+ };
224
+ userData = next;
225
+
226
+ if (keyringOk) {
227
+ // Keyring has the key — writeJson will strip api_key from
228
+ // disk automatically (useLegacyStorage is false).
229
+ yield* writeJson(next);
230
+ } else {
231
+ // Keyring write failed (NoStorageAccess / headless Linux).
232
+ // Force api_key into the JSON so it survives across
233
+ // process restarts. We bypass writeJson's strip logic by
234
+ // temporarily writing with the legacy-storage codepath.
235
+ const onDisk = yield* userDataToJSON(next);
236
+ const normalized = JSON.stringify(
237
+ (() => {
238
+ const parsed = JSON.parse(onDisk) as Record<string, unknown>;
239
+ if (parsed.project_id === null) delete parsed.project_id;
240
+ return parsed;
241
+ })()
242
+ );
243
+ yield* Effect.logDebug('Saving user data (keyring fallback):', normalized);
244
+ yield* fs.writeFileString(jsonUserConfigPath, normalized);
245
+ }
246
});
247
93
- /**
94
- * Saves the user data to a JSON file.
95
- */
248
const update = (data: Partial<UserData>) =>
249
Effect.gen(function* () {
250
const nextUserData = { ...userData, ...data } satisfies UserData;
99
- const encodedUserData = yield* userDataToJSON(nextUserData);
100
- const normalizedUserDataJson = JSON.stringify(
101
- (() => {
102
- const parsed = JSON.parse(encodedUserData) as Record<string, unknown>;
103
- if (parsed.project_id === null) {
104
- delete parsed.project_id;
105
- }
106
- return parsed;
107
- })()
108
- );
109
- yield* Effect.logDebug('Saving user data:', normalizedUserDataJson);
110
- yield* fs.writeFileString(jsonUserConfigPath, normalizedUserDataJson);
251
userData = nextUserData;
252
+ yield* writeJson(nextUserData);
253
yield* Effect.logDebug('User data updated:', userData);
254
});
255
115
- /**
116
- * Loads the user data from a JSON file.
117
- */
256
const load = Effect.gen(function* () {
257
yield* Effect.logDebug('Loading user data from', jsonUserConfigPath);
258
const userDataJson = yield* fs.readFileString(jsonUserConfigPath, 'utf8');
272
} satisfies UserData;
273
274
yield* Effect.logDebug('User data (overridden from env vars):', overriddenUserData);
137
-
275
userData = overriddenUserData;
276
return userData;
277
});
285
'Failed to load user data file (empty or corrupted), resetting to defaults:',
286
error
287
);
151
- yield* update(userData);
288
+ yield* writeJson(userData);
289
})
290
)
291
);
292
} else {
293
yield* Effect.logDebug('User data file does not exist, creating a new one');
157
- yield* update(userData);
294
+ yield* writeJson(userData);
295
+ }
296
+
297
+ // Resolve API key: env var > keyring > legacy plaintext.
298
+ if (Option.isNone(apiKey) && !useLegacyStorage) {
299
+ const plaintextOnDisk = userData.apiKey;
300
+ const fromKeyring = yield* readKeyring(kDeps);
301
+
302
+ if (Option.isSome(fromKeyring)) {
303
+ userData = { ...userData, apiKey: fromKeyring };
304
+ if (Option.isSome(plaintextOnDisk)) {
305
+ yield* Effect.logDebug('Clearing stale plaintext api_key from user_data.json');
306
+ yield* writeJson(userData);
307
+ }
308
+ } else if (Option.isSome(plaintextOnDisk)) {
309
+ yield* Effect.logDebug('Migrating legacy api_key from user_data.json to the OS keyring');
310
+ const migrated = yield* writeKeyring(kDeps, plaintextOnDisk.value);
311
+ if (migrated) {
312
+ yield* Effect.logInfo('Composio API key migrated from user_data.json to the OS keyring');
313
+ yield* writeJson(userData);
314
+ }
315
+ }
316
}
317
318
const isLoggedIn = () => Option.isSome(userData.apiKey);
319
162
- const userDataWithDefaults = {
320
+ const snapshot = (): UserDataWithDefaults => ({
321
...userData,
322
baseURL: Option.getOrElse(userData.baseURL, () => baseURL),
323
webURL: Option.getOrElse(userData.webURL, () => webURL),
324
orgId: userData.orgId,
325
projectId: userData.projectId,
326
testUserId: userData.testUserId,
169
- };
327
+ });
328
329
return ComposioUserContext.of({
172
- data: userDataWithDefaults,
330
+ get data() {
331
+ return snapshot();
332
+ },
333
isLoggedIn,
334
update,
335
login,
337
});
338
})
339
);
340
+
341
+/**
342
+ * Map the config's `security` field onto the cli-keyring package's
343
+ * `MacOSBackend` parameter.
344
+ *
345
+ * Only `"keychain"` opts into the FFI path. Everything else uses the
346
+ * subprocess backend — including `"auto"` and `"json"`, which never
347
+ * actually call the keyring (useLegacyStorage gates them off), but
348
+ * we still build a usable subprocess store so the layer wiring stays
349
+ * uniform.
350
+ */
351
+const resolveMacOSBackend = (
352
+ security: 'auto' | 'json' | 'keychain-subprocess' | 'keychain'
353
+): MacOSBackend => (security === 'keychain' ? 'ffi' : 'auto');
354
+
355
+/**
356
+ * Public layer that pre-provides the keyring and CLI-config deps,
357
+ * leaving only `FileSystem` as the external requirement. The keyring
358
+ * backend is chosen dynamically from the user's `config.json`
359
+ * `security` field — `"auto"` / `"keychain-subprocess"` select the
360
+ * subprocess path (default); `"keychain"` opts into the experimental
361
+ * FFI path (requires Developer ID-signed binary to avoid dialogs).
362
+ */
363
+export const ComposioUserContextLive = Layer.unwrapEffect(
364
+ Effect.gen(function* () {
365
+ const cliConfig = yield* ComposioCliUserConfig;
366
+ const backend = resolveMacOSBackend(cliConfig.data.security);
367
+ return Layer.provide(
368
+ rawComposioUserContextLive,
369
+ Layer.mergeAll(KeyringLiveWithBackend(backend), ComposioCliUserConfigLive)
370
+ );
371
+ }).pipe(Effect.provide(ComposioCliUserConfigLive))
372
+);