Skip to content

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): migrate API key storage from plaintext to OS keyring (#3202)

Rahul Tarak08eccb85de3d
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 9b0d32901..c484a5770 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -709,16 +709,16 @@ importers:
version: link:../../packages/providers/llamaindex
'@llamaindex/openai':
specifier: ^0.4.20
- version: 0.4.22(@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])
+ version: 0.4.22(@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])
'@llamaindex/workflow':
specifier: ^1.1.24
- version: 1.1.24(@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])
+ version: 1.1.24(@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])
dotenv:
specifier: ^16.4.1
version: 16.6.1
llamaindex:
specifier: ^0.12.0
devDependencies:
'@types/bun':
specifier: ^1.2.9
@@ -1058,6 +1058,9 @@ importers:
'@clack/prompts':
specifier: 'catalog:'
version: 1.0.1
+ '@composio/cli-keyring':
+ specifier: workspace:*
+ version: link:../cli-keyring
'@composio/client':
specifier: 'catalog:'
version: 0.1.0-alpha.66
@@ -1369,7 +1372,7 @@ importers:
dependencies:
llamaindex:
specifier: ^0.12.0
devDependencies:
'@composio/core':
specifier: workspace:*
@@ -7995,43 +7998,26 @@ snapshots:
tree-sitter: 0.22.4
web-tree-sitter: 0.24.7
dependencies:
'@llamaindex/core': 0.6.22
'@llamaindex/env': 0.1.30
transitivePeerDependencies:
- ws
- zod
optionalDependencies:
- '@modelcontextprotocol/sdk': 1.26.0(@cfworker/[email protected])([email protected])
+ '@modelcontextprotocol/sdk': 1.26.0(@cfworker/[email protected])([email protected])
hono: 4.11.9
- zod: 3.25.76
-
- optionalDependencies:
zod: 4.3.6
- dependencies:
- '@llamaindex/core': 0.6.22
- '@llamaindex/env': 0.1.30
- '@llamaindex/workflow-core': 1.3.3(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])
- transitivePeerDependencies:
- - '@modelcontextprotocol/sdk'
- - hono
- - next
- - p-retry
- - rxjs
- - zod
-
dependencies:
'@llamaindex/core': 0.6.22
'@llamaindex/env': 0.1.30
- '@llamaindex/workflow-core': 1.3.3([email protected])
+ '@llamaindex/workflow-core': 1.3.3(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])
transitivePeerDependencies:
- '@modelcontextprotocol/sdk'
- hono
@@ -9049,14 +9035,6 @@ snapshots:
optionalDependencies:
- dependencies:
- '@vitest/spy': 3.2.4
- estree-walker: 3.0.3
- magic-string: 0.30.21
- optionalDependencies:
-
'@vitest/[email protected]':
dependencies:
tinyrainbow: 2.0.0
@@ -9086,7 +9064,7 @@ snapshots:
sirv: 3.0.2
tinyglobby: 0.2.15
tinyrainbow: 2.0.0
'@vitest/[email protected]':
dependencies:
@@ -10536,34 +10514,12 @@ snapshots:
rfdc: 1.4.1
wrap-ansi: 9.0.2
dependencies:
'@llamaindex/core': 0.6.22
'@llamaindex/env': 0.1.30
'@llamaindex/node-parser': 2.0.22(@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])
- '@llamaindex/workflow': 1.1.24(@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])
- '@types/lodash': 4.17.23
- '@types/node': 24.10.13
- lodash: 4.17.23
- magic-bytes.js: 1.13.0
- transitivePeerDependencies:
- - '@huggingface/transformers'
- - '@modelcontextprotocol/sdk'
- - gpt-tokenizer
- - hono
- - next
- - p-retry
- - rxjs
- - tree-sitter
- - web-tree-sitter
- - zod
-
- dependencies:
- '@llamaindex/core': 0.6.22
- '@llamaindex/env': 0.1.30
- '@llamaindex/node-parser': 2.0.22(@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])([email protected])
- '@llamaindex/workflow': 1.1.24(@llamaindex/[email protected])(@llamaindex/[email protected])([email protected])
+ '@llamaindex/workflow': 1.1.24(@llamaindex/[email protected])(@llamaindex/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected])([email protected])
'@types/lodash': 4.17.23
'@types/node': 24.10.13
lodash: 4.17.23
@@ -10847,11 +10803,6 @@ snapshots:
is-inside-container: 1.0.0
wsl-utils: 0.1.0
- optionalDependencies:
- ws: 8.20.0
- zod: 3.25.76
-
optionalDependencies:
ws: 8.20.0
@@ -11950,7 +11901,7 @@ snapshots:
dependencies:
'@types/chai': 5.2.3
'@vitest/expect': 3.2.4
'@vitest/pretty-format': 3.2.4
'@vitest/runner': 3.2.4
'@vitest/snapshot': 3.2.4
diff --git a/ts/packages/cli/package.json b/ts/packages/cli/package.json
index 87fb36b00..155a5a7f6 100644
--- a/ts/packages/cli/package.json
+++ b/ts/packages/cli/package.json
@@ -77,6 +77,7 @@
"@zed-industries/codex-acp": "^0.10.0",
"@clack/core": "catalog:",
"@clack/prompts": "catalog:",
+ "@composio/cli-keyring": "workspace:*",
"@composio/client": "catalog:",
"@composio/core": "workspace:*",
"@composio/json-schema-to-zod": "workspace:*",
diff --git a/ts/packages/cli/src/models/cli-user-config.ts b/ts/packages/cli/src/models/cli-user-config.ts
index 0a6a1ffcf..34fc9039a 100644
--- a/ts/packages/cli/src/models/cli-user-config.ts
+++ b/ts/packages/cli/src/models/cli-user-config.ts
@@ -5,6 +5,32 @@ import { JSONTransformSchema } from './utils/json-transform-schema';
export const ExperimentalSubagentTarget = Schema.Literal('auto', 'claude', 'codex');
export type ExperimentalSubagentTarget = Schema.Schema.Type<typeof ExperimentalSubagentTarget>;
+/**
+ * Where the CLI stores the Composio API key.
+ *
+ * - `"auto"` (default): plaintext `user_data.json`. Backwards-
+ * compatible with every prior CLI release — upgrading does not
+ * change where the key is stored, and no migration or keychain
+ * access is attempted. Lets users harden security explicitly by
+ * picking one of the keyring options below.
+ * - `"json"`: explicit opt-in to plaintext `user_data.json`. Pins
+ * the behavior so a future default change won't affect configs
+ * that set this value.
+ * - `"keychain-subprocess"`: store the API key in the OS credential
+ * store via `/usr/bin/security` (macOS) or `secret-tool` (Linux).
+ * Adds ~25ms to startup (memoized for the process). No macOS
+ * dialogs — `/usr/bin/security` is Apple-signed and trusted.
+ * Opt-in hardening for users who want the key out of plaintext.
+ * - `"keychain"` (experimental): direct Security.framework FFI
+ * (~1ms reads). Currently triggers a macOS keychain trust dialog
+ * on unsigned / ad-hoc signed binaries — avoid unless the
+ * composio binary is signed with a stable Developer ID
+ * certificate. Linux is identical to `"keychain-subprocess"`
+ * (there's no FFI backend for libsecret).
+ */
+export const SecurityBackend = Schema.Literal('auto', 'json', 'keychain-subprocess', 'keychain');
+export type SecurityBackend = Schema.Schema.Type<typeof SecurityBackend>;
+
export const ExperimentalFeatures = Schema.Record({
key: Schema.String,
value: Schema.Boolean,
@@ -43,6 +69,15 @@ export const CliUserConfig = Schema.Struct({
null
)
).pipe(Schema.fromKey('experimental_subagent')),
+ /**
+ * Where the CLI stores the Composio API key. See the
+ * `SecurityBackend` type above for semantics. Default: `"auto"`
+ * (plaintext `user_data.json`, same as every prior CLI release —
+ * no behavior change on upgrade).
+ */
+ security: Schema.optionalWith(SecurityBackend, {
+ default: () => 'auto' as const,
+ }),
}).annotations({
identifier: 'CliUserConfig',
description: 'Named user configuration storage for the Composio CLI',
diff --git a/ts/packages/cli/src/services/cli-user-config.ts b/ts/packages/cli/src/services/cli-user-config.ts
index c7ac10e7c..ef624e8b4 100644
--- a/ts/packages/cli/src/services/cli-user-config.ts
+++ b/ts/packages/cli/src/services/cli-user-config.ts
@@ -22,6 +22,13 @@ export type CliUserConfigResolved = {
readonly experimentalFeatures: Readonly<Record<string, boolean>>;
readonly artifactDirectory: string | undefined;
readonly experimentalSubagentTarget: 'auto' | 'claude' | 'codex';
+ /**
+ * Where the CLI stores the Composio API key. See the
+ * `SecurityBackend` type in `src/models/cli-user-config.ts`.
+ * Default: `"auto"` (plaintext `user_data.json`, backwards-compatible
+ * with every prior CLI release).
+ */
+ readonly security: 'auto' | 'json' | 'keychain-subprocess' | 'keychain';
};
const detectReleaseChannel = (version: string): CliReleaseChannel =>
@@ -58,6 +65,7 @@ const resolveConfig = (raw: CliUserConfig, channel: CliReleaseChannel): CliUserC
onNone: () => 'auto',
onSome: value => value.target,
}),
+ security: raw.security,
});
export const ComposioCliUserConfigLive = Layer.effect(
@@ -77,6 +85,7 @@ export const ComposioCliUserConfigLive = Layer.effect(
experimentalFeatures: {},
artifactDirectory: Option.none(),
experimentalSubagent: Option.none(),
+ security: 'auto',
});
const normalizeRawConfigJson = (value: unknown): unknown => {
@@ -144,6 +153,7 @@ export const ComposioCliUserConfigLive = Layer.effect(
experimentalFeatures: {},
artifactDirectory: Option.none(),
experimentalSubagent: Option.none(),
+ security: 'auto',
})
)
)
diff --git a/ts/packages/cli/src/services/user-context.ts b/ts/packages/cli/src/services/user-context.ts
index 506dbf77f..23f87fded 100644
--- a/ts/packages/cli/src/services/user-context.ts
+++ b/ts/packages/cli/src/services/user-context.ts
@@ -12,49 +12,159 @@ import * as constants from 'src/constants';
import type { PlatformError } from '@effect/platform/Error';
import type { ParseError } from 'effect/ParseResult';
import { APP_CONFIG } from 'src/effects/app-config';
+import { KeyringService, KeyringLiveWithBackend } from '@composio/cli-keyring/effect';
+import type { KeyringServiceShape } from '@composio/cli-keyring/effect';
+import { KeyringError, type MacOSBackend } from '@composio/cli-keyring';
+import { ComposioCliUserConfig, ComposioCliUserConfigLive } from 'src/services/cli-user-config';
+
+/**
+ * Keyring specifier for the Composio API key. `service` is a reverse
+ * DNS identifier shared by every composio CLI install; `user` is a
+ * single fixed slot because the API key is user-scoped (one per
+ * logged-in account, independent of which org/project the user is
+ * currently working in).
+ */
+const KEYRING_SERVICE = 'com.composio.cli';
+const KEYRING_USER = 'default';
+
+// -----------------------------------------------------------------------------
+// Keyring helpers — extracted from the generator so it stays within
+// the max-lines-per-function lint limit. Each helper takes its deps
+// as parameters rather than closing over the generator's locals.
+// -----------------------------------------------------------------------------
+
+type KeyringDeps = {
+ keyring: KeyringServiceShape;
+ useLegacyStorage: boolean;
+};
+
+/**
+ * Write `password` into the OS keyring. Returns `true` on success,
+ * `false` on `NoStorageAccess` or unexpected errors so the caller
+ * can fall back to plaintext. Never propagates — the CLI always
+ * prefers "keep working with plaintext fallback" over "crash".
+ */
+const writeKeyring = (deps: KeyringDeps, password: string) =>
+ Effect.gen(function* () {
+ if (deps.useLegacyStorage) return false;
+ return yield* deps.keyring.setPassword(KEYRING_SERVICE, KEYRING_USER, password).pipe(
+ Effect.map(() => true),
+ Effect.catchAll(err =>
+ Effect.gen(function* () {
+ if (err instanceof KeyringError && err.kind === 'NoStorageAccess') {
+ yield* Effect.logDebug(
+ 'OS keyring unavailable, storing api_key in user_data.json as plaintext. ' +
+ `Reason: ${err.message}`
+ );
+ } else {
+ yield* Effect.logDebug(
+ 'Unexpected keyring error while writing api_key, falling back to plaintext: ' +
+ (err instanceof Error ? err.message : String(err))
+ );
+ }
+ return false;
+ })
+ )
+ );
+ });
+
+/**
+ * Read the API key from the OS keyring. Returns `Option.some(value)`
+ * if found, `Option.none()` on NoEntry or any failure (with warning
+ * logged). The caller falls back to plaintext on `none`.
+ */
+const readKeyring = (deps: KeyringDeps) =>
+ Effect.gen(function* () {
+ if (deps.useLegacyStorage) return Option.none<string>();
+ return yield* deps.keyring.getPassword(KEYRING_SERVICE, KEYRING_USER).pipe(
+ Effect.map(Option.some),
+ Effect.catchAll(err =>
+ Effect.gen(function* () {
+ if (err instanceof KeyringError && err.kind === 'NoEntry') {
+ yield* Effect.logDebug('No keyring entry found for Composio API key');
+ } else if (err instanceof KeyringError && err.kind === 'NoStorageAccess') {
+ // Expected normal path on headless Linux / containers /
+ // CI — log at debug to avoid polluting stdout on every
+ // CLI invocation. Only the first write attempt would
+ // warn loudly (see `writeKeyring`).
+ yield* Effect.logDebug(
+ 'OS keyring unavailable, falling back to user_data.json. ' + `Reason: ${err.message}`
+ );
+ } else {
+ yield* Effect.logDebug(
+ 'Unexpected keyring error while reading api_key, falling back to plaintext: ' +
+ (err instanceof Error ? err.message : String(err))
+ );
+ }
+ return Option.none<string>();
+ })
+ )
+ );
+ });
+
+/**
+ * Best-effort keyring delete. Swallows `NoEntry` (idempotent) and
+ * `NoStorageAccess` (logout should not fail because the keyring is
+ * unreachable).
+ */
+const deleteKeyring = (deps: KeyringDeps) =>
+ Effect.gen(function* () {
+ if (deps.useLegacyStorage) return;
+ yield* deps.keyring.deleteCredential(KEYRING_SERVICE, KEYRING_USER).pipe(
+ Effect.catchAll(err =>
+ Effect.gen(function* () {
+ if (
+ err instanceof KeyringError &&
+ (err.kind === 'NoEntry' || err.kind === 'NoStorageAccess')
+ ) {
+ yield* Effect.logDebug(`Keyring delete skipped: ${err.kind}`);
+ } else {
+ yield* Effect.logWarning(
+ 'Keyring delete failed: ' + (err instanceof Error ? err.message : String(err))
+ );
+ }
+ })
+ )
+ );
+ });
+
+// -----------------------------------------------------------------------------
+// Service definition
+// -----------------------------------------------------------------------------
export class ComposioUserContext extends Context.Tag('ComposioUserData')<
ComposioUserContext,
{
readonly data: UserDataWithDefaults;
-
- /**
- * Returns `true` if the user is logged in, i.e., has a valid Composio API key.
- */
isLoggedIn: () => boolean;
-
- /**
- * Logs out the user by clearing the API key and any other sensitive data.
- */
logout: Effect.Effect<void, ParseError | PlatformError, never>;
-
- /**
- * Logs in the user by setting the API key, and optionally org ID.
- */
login: (
apiKey: string,
orgId?: string,
testUserId?: string
) => Effect.Effect<void, ParseError | PlatformError, never>;
-
- /**
- * Saves the user data to a persistent store, e.g., file or database.
- */
update: (data: UserData) => Effect.Effect<void, ParseError | PlatformError, never>;
}
>() {}
-export const ComposioUserContextLive = Layer.effect(
+export const rawComposioUserContextLive = Layer.effect(
ComposioUserContext,
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const apiKey = yield* APP_CONFIG['USER_API_KEY'];
const baseURL = yield* APP_CONFIG['BASE_URL'];
const webURL = yield* APP_CONFIG['WEB_URL'];
+ const cliConfig = yield* ComposioCliUserConfig;
+ const keyring = yield* KeyringService;
+
+ // `security: "auto"` and `"json"` both keep the API key in
+ // plaintext `user_data.json` (the legacy path — same behavior
+ // as every prior CLI release). `"keychain-subprocess"` and
+ // `"keychain"` opt into the OS credential store.
+ const useLegacyStorage =
+ cliConfig.data.security === 'auto' || cliConfig.data.security === 'json';
+ const kDeps: KeyringDeps = { keyring, useLegacyStorage };
- /**
- * Ensure the cache directory exists before reading/writing user data.
- */
const cacheDir = yield* setupCacheDir;
const jsonUserConfigPath = path.join(cacheDir, constants.USER_CONFIG_FILE_NAME);
@@ -67,54 +177,82 @@ export const ComposioUserContextLive = Layer.effect(
testUserId: Option.none(),
});
+ const writeJson = (snapshot: UserData) =>
+ Effect.gen(function* () {
+ const onDisk: UserData = useLegacyStorage
+ ? snapshot
+ : { ...snapshot, apiKey: Option.none() };
+ const encoded = yield* userDataToJSON(onDisk);
+ const normalized = JSON.stringify(
+ (() => {
+ const parsed = JSON.parse(encoded) as Record<string, unknown>;
+ if (parsed.project_id === null) delete parsed.project_id;
+ if (!useLegacyStorage && parsed.api_key === null) delete parsed.api_key;
+ return parsed;
+ })()
+ );
+ yield* Effect.logDebug('Saving user data:', normalized);
+ yield* fs.writeFileString(jsonUserConfigPath, normalized);
+ });
+
const logout = Effect.gen(function* () {
- yield* update({
+ yield* deleteKeyring(kDeps);
+ const cleared: UserData = {
apiKey: Option.none(),
baseURL: Option.none(),
webURL: Option.some(webURL),
orgId: Option.none(),
projectId: Option.none(),
testUserId: Option.none(),
- });
+ };
+ userData = cleared;
+ yield* writeJson(cleared);
});
const login = (apiKey: string, orgId?: string, testUserId?: string) =>
Effect.gen(function* () {
- yield* update({
+ const keyringOk = yield* writeKeyring(kDeps, apiKey);
+ const next: UserData = {
+ ...userData,
apiKey: Option.some(apiKey),
baseURL: Option.some(baseURL),
webURL: Option.some(webURL),
orgId: Option.fromNullable(orgId),
- projectId: Option.none(),
+ projectId: userData.projectId,
testUserId: Option.fromNullable(testUserId),
- });
+ };
+ userData = next;
+
+ if (keyringOk) {
+ // Keyring has the key — writeJson will strip api_key from
+ // disk automatically (useLegacyStorage is false).
+ yield* writeJson(next);
+ } else {
+ // Keyring write failed (NoStorageAccess / headless Linux).
+ // Force api_key into the JSON so it survives across
+ // process restarts. We bypass writeJson's strip logic by
+ // temporarily writing with the legacy-storage codepath.
+ const onDisk = yield* userDataToJSON(next);
+ const normalized = JSON.stringify(
+ (() => {
+ const parsed = JSON.parse(onDisk) as Record<string, unknown>;
+ if (parsed.project_id === null) delete parsed.project_id;
+ return parsed;
+ })()
+ );
+ yield* Effect.logDebug('Saving user data (keyring fallback):', normalized);
+ yield* fs.writeFileString(jsonUserConfigPath, normalized);
+ }
});
- /**
- * Saves the user data to a JSON file.
- */
const update = (data: Partial<UserData>) =>
Effect.gen(function* () {
const nextUserData = { ...userData, ...data } satisfies UserData;
- const encodedUserData = yield* userDataToJSON(nextUserData);
- const normalizedUserDataJson = JSON.stringify(
- (() => {
- const parsed = JSON.parse(encodedUserData) as Record<string, unknown>;
- if (parsed.project_id === null) {
- delete parsed.project_id;
- }
- return parsed;
- })()
- );
- yield* Effect.logDebug('Saving user data:', normalizedUserDataJson);
- yield* fs.writeFileString(jsonUserConfigPath, normalizedUserDataJson);
userData = nextUserData;
+ yield* writeJson(nextUserData);
yield* Effect.logDebug('User data updated:', userData);
});
- /**
- * Loads the user data from a JSON file.
- */
const load = Effect.gen(function* () {
yield* Effect.logDebug('Loading user data from', jsonUserConfigPath);
const userDataJson = yield* fs.readFileString(jsonUserConfigPath, 'utf8');
@@ -134,7 +272,6 @@ export const ComposioUserContextLive = Layer.effect(
} satisfies UserData;
yield* Effect.logDebug('User data (overridden from env vars):', overriddenUserData);
-
userData = overriddenUserData;
return userData;
});
@@ -148,28 +285,51 @@ export const ComposioUserContextLive = Layer.effect(
'Failed to load user data file (empty or corrupted), resetting to defaults:',
error
);
- yield* update(userData);
+ yield* writeJson(userData);
})
)
);
} else {
yield* Effect.logDebug('User data file does not exist, creating a new one');
- yield* update(userData);
+ yield* writeJson(userData);
+ }
+
+ // Resolve API key: env var > keyring > legacy plaintext.
+ if (Option.isNone(apiKey) && !useLegacyStorage) {
+ const plaintextOnDisk = userData.apiKey;
+ const fromKeyring = yield* readKeyring(kDeps);
+
+ if (Option.isSome(fromKeyring)) {
+ userData = { ...userData, apiKey: fromKeyring };
+ if (Option.isSome(plaintextOnDisk)) {
+ yield* Effect.logDebug('Clearing stale plaintext api_key from user_data.json');
+ yield* writeJson(userData);
+ }
+ } else if (Option.isSome(plaintextOnDisk)) {
+ yield* Effect.logDebug('Migrating legacy api_key from user_data.json to the OS keyring');
+ const migrated = yield* writeKeyring(kDeps, plaintextOnDisk.value);
+ if (migrated) {
+ yield* Effect.logInfo('Composio API key migrated from user_data.json to the OS keyring');
+ yield* writeJson(userData);
+ }
+ }
}
const isLoggedIn = () => Option.isSome(userData.apiKey);
- const userDataWithDefaults = {
+ const snapshot = (): UserDataWithDefaults => ({
...userData,
baseURL: Option.getOrElse(userData.baseURL, () => baseURL),
webURL: Option.getOrElse(userData.webURL, () => webURL),
orgId: userData.orgId,
projectId: userData.projectId,
testUserId: userData.testUserId,
- };
+ });
return ComposioUserContext.of({
- data: userDataWithDefaults,
+ get data() {
+ return snapshot();
+ },
isLoggedIn,
update,
login,
@@ -177,3 +337,36 @@ export const ComposioUserContextLive = Layer.effect(
});
})
);
+
+/**
+ * Map the config's `security` field onto the cli-keyring package's
+ * `MacOSBackend` parameter.
+ *
+ * Only `"keychain"` opts into the FFI path. Everything else uses the
+ * subprocess backend — including `"auto"` and `"json"`, which never
+ * actually call the keyring (useLegacyStorage gates them off), but
+ * we still build a usable subprocess store so the layer wiring stays
+ * uniform.
+ */
+const resolveMacOSBackend = (
+ security: 'auto' | 'json' | 'keychain-subprocess' | 'keychain'
+): MacOSBackend => (security === 'keychain' ? 'ffi' : 'auto');
+
+/**
+ * Public layer that pre-provides the keyring and CLI-config deps,
+ * leaving only `FileSystem` as the external requirement. The keyring
+ * backend is chosen dynamically from the user's `config.json`
+ * `security` field — `"auto"` / `"keychain-subprocess"` select the
+ * subprocess path (default); `"keychain"` opts into the experimental
+ * FFI path (requires Developer ID-signed binary to avoid dialogs).
+ */
+export const ComposioUserContextLive = Layer.unwrapEffect(
+ Effect.gen(function* () {
+ const cliConfig = yield* ComposioCliUserConfig;
+ const backend = resolveMacOSBackend(cliConfig.data.security);
+ return Layer.provide(
+ rawComposioUserContextLive,
+ Layer.mergeAll(KeyringLiveWithBackend(backend), ComposioCliUserConfigLive)
+ );
+ }).pipe(Effect.provide(ComposioCliUserConfigLive))
+);
diff --git a/ts/packages/cli/test/__utils__/services/test-layer.ts b/ts/packages/cli/test/__utils__/services/test-layer.ts
index 1d59c5f25..aba4d85a4 100644
--- a/ts/packages/cli/test/__utils__/services/test-layer.ts
+++ b/ts/packages/cli/test/__utils__/services/test-layer.ts
@@ -816,6 +816,7 @@ export const TestLayer = (input?: TestLiveInput) =>
experimentalFeatures: input?.cliUserConfig?.experimentalFeatures ?? {},
artifactDirectory: Option.none(),
experimentalSubagent: Option.none(),
+ security: 'auto',
});
const ComposioCliUserConfigTest = Layer.succeed(
@@ -829,6 +830,7 @@ export const TestLayer = (input?: TestLiveInput) =>
experimentalFeatures: rawCliUserConfig.experimentalFeatures,
artifactDirectory: undefined,
experimentalSubagentTarget: 'auto' as const,
+ security: 'auto' as const,
};
},
get raw() {
diff --git a/ts/packages/cli/test/src/commands/login.cmd.test.ts b/ts/packages/cli/test/src/commands/login.cmd.test.ts
index 9efb705bd..0b4bcdc11 100644
--- a/ts/packages/cli/test/src/commands/login.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/login.cmd.test.ts
@@ -1,11 +1,12 @@
import { describe, expect, layer } from '@effect/vitest';
import { vi, afterEach } from 'vitest';
-import { Effect } from 'effect';
+import { Effect, Option } from 'effect';
import path from 'node:path';
import { FileSystem } from '@effect/platform';
import { cli, MockConsole, TestLive } from 'test/__utils__';
import * as constants from 'src/constants';
import { setupCacheDir } from 'src/effects/setup-cache-dir';
+import { ComposioUserContext } from 'src/services/user-context';
const mockFetchResponse = (body: unknown, status = 200) =>
new Response(JSON.stringify(body), {
@@ -103,9 +104,20 @@ describe('CLI: composio login', () => {
const userConfigPath = path.join(cacheDir, constants.USER_CONFIG_FILE_NAME);
const rawUserConfig = yield* fs.readFileString(userConfigPath, 'utf8');
const userConfig = JSON.parse(rawUserConfig) as Record<string, unknown>;
+ // Default `security: "auto"` keeps the API key in plaintext
+ // `user_data.json` for backwards compatibility — same as
+ // every prior CLI release. Users opt into keyring storage
+ // by setting `security: "keychain-subprocess"` (or
+ // `"keychain"` for the experimental FFI path) in
+ // `~/.composio/config.json`.
expect(userConfig.api_key).toBe('uak_direct_key');
expect(userConfig.org_id).toBe('org_selected');
+ // ComposioUserContext also exposes the resolved key in-memory
+ // for subsequent API calls in this process.
+ const ctx = yield* ComposioUserContext;
+ expect(Option.getOrUndefined(ctx.data.apiKey)).toBe('uak_direct_key');
+
const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
expect(output).toContain('Logged in as [email protected] in "Selected Org"');
})
diff --git a/ts/packages/cli/test/src/services/composio-client-singleton.test.ts b/ts/packages/cli/test/src/services/composio-client-singleton.test.ts
index 85a2c83a0..9a150dd67 100644
--- a/ts/packages/cli/test/src/services/composio-client-singleton.test.ts
+++ b/ts/packages/cli/test/src/services/composio-client-singleton.test.ts
@@ -1,6 +1,7 @@
-import { afterEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
import { BunFileSystem } from '@effect/platform-bun';
-import { ConfigProvider, Effect, Layer } from 'effect';
+import { ConfigProvider, Effect, Layer, Option } from 'effect';
+import { execSync } from 'node:child_process';
import * as tempy from 'tempy';
import { ComposioClientSingleton } from 'src/services/composio-clients';
import { defaultNodeOs, NodeOs } from 'src/services/node-os';
@@ -20,6 +21,22 @@ const okResponse = () =>
});
describe('ComposioClientSingleton headers', () => {
+ // Delete any real keychain entry so the subprocess keyring read
+ // inside ComposioUserContextLive (baked into
+ // ComposioClientSingleton.Default's dependencies) finds nothing
+ // and apiKey resolves to Option.none(). Without this, the test
+ // picks up real credentials and assertions on x-user-api-key fail.
+ beforeAll(() => {
+ try {
+ execSync(
+ '/usr/bin/security delete-generic-password -s com.composio.cli -a default 2>/dev/null',
+ { stdio: 'ignore' }
+ );
+ } catch {
+ // Entry may not exist — fine.
+ }
+ });
+
afterEach(() => {
vi.restoreAllMocks();
});
diff --git a/ts/packages/cli/test/src/services/user-context.test.ts b/ts/packages/cli/test/src/services/user-context.test.ts
index 50c6b8858..b2d96eb0f 100644
--- a/ts/packages/cli/test/src/services/user-context.test.ts
+++ b/ts/packages/cli/test/src/services/user-context.test.ts
@@ -4,12 +4,75 @@ import { FileSystem } from '@effect/platform';
import { BunFileSystem } from '@effect/platform-bun';
import { ConfigProvider, Effect, Layer, Option, Data } from 'effect';
import * as tempy from 'tempy';
-import { ComposioUserContext, ComposioUserContextLive } from 'src/services/user-context';
+import { ComposioUserContext, rawComposioUserContextLive } from 'src/services/user-context';
import { defaultNodeOs, NodeOs } from 'src/services/node-os';
import { UserData, UserDataWithDefaults, userDataToJSON } from 'src/models/user-data';
import { extendConfigProvider } from 'src/services/config';
+import { CliUserConfig } from 'src/models/cli-user-config';
+import { ComposioCliUserConfig } from 'src/services/cli-user-config';
+import { makeKeyringService, KeyringService } from '@composio/cli-keyring/effect';
+import {
+ type CredentialStore,
+ type EntryModifiers,
+ KeyringError,
+ CredentialPersistence,
+} from '@composio/cli-keyring';
import path from 'node:path';
+const InMemoryKeyringLayer = (() => {
+ const items = new Map<string, Uint8Array>();
+ const key = (s: string, u: string) => `${s}\0${u}`;
+ const store: CredentialStore = {
+ id: 'memory',
+ vendor: 'test',
+ persistence: () => CredentialPersistence.ProcessOnly,
+ async setSecret(s: string, u: string, secret: Uint8Array, _m: EntryModifiers) {
+ items.set(key(s, u), new Uint8Array(secret));
+ },
+ async getSecret(s: string, u: string, _m: EntryModifiers) {
+ const v = items.get(key(s, u));
+ if (!v) throw new KeyringError({ kind: 'NoEntry' });
+ return v;
+ },
+ async deleteCredential(s: string, u: string, _m: EntryModifiers) {
+ if (!items.delete(key(s, u))) throw new KeyringError({ kind: 'NoEntry' });
+ },
+ };
+ return Layer.succeed(KeyringService, makeKeyringService(store));
+})();
+
+const MockCliUserConfigLayer = Layer.succeed(
+ ComposioCliUserConfig,
+ ComposioCliUserConfig.of({
+ data: {
+ channel: 'beta',
+ developerModeEnabled: true,
+ developerDangerousCommandsEnabled: false,
+ experimentalFeatures: {},
+ artifactDirectory: undefined,
+ experimentalSubagentTarget: 'auto',
+ security: 'auto',
+ },
+ raw: CliUserConfig.make({
+ developer: { enabled: true, destructiveActions: false },
+ experimentalFeatures: {},
+ artifactDirectory: Option.none(),
+ experimentalSubagent: Option.none(),
+ security: 'auto',
+ }),
+ channel: 'beta',
+ isDevModeEnabled: () => true,
+ areDeveloperDangerousCommandsEnabled: () => false,
+ isExperimentalFeatureEnabled: () => true,
+ update: () => Effect.void,
+ })
+);
+
+const ComposioUserContextLive = Layer.provide(
+ rawComposioUserContextLive,
+ Layer.mergeAll(InMemoryKeyringLayer, MockCliUserConfigLayer)
+);
+
describe('ComposioUserContext', () => {
const withMapConfigProvider = (map: Map<string, string>) =>
Layer.setConfigProvider(extendConfigProvider(ConfigProvider.fromMap(map)));