11
import { setupCacheDir } from 'src/effects/setup-cache-dir';
12
import * as constants from 'src/constants';
13
import { APP_CONFIG } from 'src/config';
14
+import {
15
+ backendMismatch,
16
+ resolveBackend,
17
+ type BackendMismatch,
18
+ type StoredBackend,
19
+} from 'src/config/backend';
20
import { KeyringService, KeyringLiveWithBackend } from '@composio/cli-keyring/effect';
21
import type { KeyringServiceShape } from '@composio/cli-keyring/effect';
22
import { KeyringError, type MacOSBackend } from '@composio/cli-keyring';
154
export class ComposioUserContext extends Context.Service<
155
ComposioUserContext,
156
{
157
+ /** The stored user data, with `baseURL` and `webURL` resolved by `resolveBackend`. */
158
readonly data: UserDataWithDefaults;
159
+ /** Set when an env var sends the stored login's key to a backend other than its issuer. */
160
+ readonly backendMismatch: Option.Option<BackendMismatch>;
161
isLoggedIn: () => boolean;
162
logout: Effect.Effect<void, Schema.SchemaError | PlatformError.PlatformError, never>;
163
+ /**
164
+ * Stores a login and records the backend that issued its key: by default the backend this
165
+ * run resolved (the one the caller verified the key against), or with `issuer:
166
+ * 'environment'` the backend the env vars select, ignoring any earlier stored login, for a
167
+ * key no stored backend issued (an agent identity from agents.composio.dev).
168
+ */
169
login: (
170
apiKey: string,
171
orgId?: string,
157
- testUserId?: string
172
+ testUserId?: string,
173
+ options?: LoginOptions
174
) => Effect.Effect<void, Schema.SchemaError | PlatformError.PlatformError, never>;
175
+ /** Changes stored fields. The login's backend is only ever recorded by `login`. */
176
update: (
160
- data: UserData
177
+ data: Partial<Omit<UserData, 'baseURL' | 'webURL'>>
178
) => Effect.Effect<void, Schema.SchemaError | PlatformError.PlatformError, never>;
179
}
180
>()('ComposioUserData') {}
181
182
+export interface LoginOptions {
183
+ /** Which backend issued the key; `'resolved'` when absent. */
184
+ readonly issuer?: 'resolved' | 'environment';
185
+}
186
+
187
export const rawComposioUserContextLive = Layer.effect(
188
ComposioUserContext,
189
Effect.gen(function* () {
190
const fs = yield* FileSystem.FileSystem;
191
const path = yield* Path.Path;
192
const apiKey = Option.fromNullishOr(yield* APP_CONFIG.USER_API_KEY);
171
- const baseURL = yield* APP_CONFIG.BASE_URL;
172
- const webURL = yield* APP_CONFIG.WEB_URL;
193
+ const envBackend = yield* APP_CONFIG.BACKEND;
194
const cliConfig = yield* ComposioCliUserConfig;
195
const keyring = yield* KeyringService;
196
201
const useLegacyStorage =
202
cliConfig.data.security === 'auto' || cliConfig.data.security === 'json';
203
const kDeps: KeyringDeps = { keyring, useLegacyStorage };
204
+ // Whether the API key must stay in user_data.json: always for the legacy storage, and in
205
+ // the keychain modes while the keyring could not take it.
206
+ let keepApiKeyInFile = useLegacyStorage;
207
208
const cacheDir = yield* setupCacheDir;
209
const jsonUserConfigPath = path.join(cacheDir, constants.USER_CONFIG_FILE_NAME);
210
211
+ // The stored login's key (user_data.json or the keyring). `userData.apiKey` is the key
212
+ // requests use, COMPOSIO_USER_API_KEY first; only this one is ever written back, so an
213
+ // update made while that variable is set cannot pair its key with the stored backend.
214
+ let storedApiKey: Option.Option<string> = Option.none();
215
+
216
+ // `baseURL` and `webURL` hold what is stored: the backend the stored login was issued by.
217
let userData = UserData.make({
218
apiKey,
189
- baseURL: Option.some(baseURL),
190
- webURL: Option.some(webURL),
219
+ baseURL: Option.none(),
220
+ webURL: Option.none(),
221
orgId: Option.none(),
222
projectId: Option.none(),
223
testUserId: Option.none(),
224
});
225
226
+ // The backend the stored login was issued by. A key from COMPOSIO_USER_API_KEY is not
227
+ // the stored login's, and a recorded backend without a stored key is no login.
228
+ const storedLogin = (): Option.Option<StoredBackend> =>
229
+ Option.isSome(apiKey) || Option.isNone(storedApiKey)
230
+ ? Option.none()
231
+ : Option.map(userData.baseURL, baseURL => ({ baseURL, webURL: userData.webURL }));
232
+ const currentBackend = () => resolveBackend(envBackend, storedLogin());
233
+
234
const writeJson = (snapshot: UserData) =>
235
Effect.gen(function* () {
198
- const onDisk: UserData = useLegacyStorage
199
- ? snapshot
200
- : { ...snapshot, apiKey: Option.none() };
236
+ const onDisk: UserData = {
237
+ ...snapshot,
238
+ apiKey: keepApiKeyInFile ? storedApiKey : Option.none(),
239
+ };
240
const encoded = yield* userDataToJSON(onDisk);
202
- const normalized = yield* normalizeEncodedUserData(encoded, !useLegacyStorage);
241
+ const normalized = yield* normalizeEncodedUserData(encoded, !keepApiKeyInFile);
242
yield* Effect.logDebug('Saving user data:', redactSensitiveLogValue(onDisk));
243
yield* atomicWritePrivateFileString({
244
fs,
249
250
const logout = Effect.gen(function* () {
251
yield* deleteKeyring(kDeps);
252
+ storedApiKey = Option.none();
253
const cleared: UserData = {
254
apiKey: Option.none(),
255
baseURL: Option.none(),
216
- webURL: Option.some(webURL),
256
+ webURL: Option.none(),
257
orgId: Option.none(),
258
projectId: Option.none(),
259
testUserId: Option.none(),
262
yield* writeJson(cleared);
263
});
264
225
- const login = (apiKey: string, orgId?: string, testUserId?: string) =>
265
+ const login = (apiKey: string, orgId?: string, testUserId?: string, options?: LoginOptions) =>
266
Effect.gen(function* () {
267
+ const backend =
268
+ options?.issuer === 'environment'
269
+ ? resolveBackend(envBackend, Option.none())
270
+ : currentBackend();
271
const keyringOk = yield* writeKeyring(kDeps, apiKey);
272
+ // Keyring write failed (NoStorageAccess / headless Linux): keep api_key in the JSON
273
+ // so it survives across process restarts.
274
+ keepApiKeyInFile = useLegacyStorage || !keyringOk;
275
+ storedApiKey = Option.some(apiKey);
276
const next: UserData = {
277
...userData,
278
apiKey: Option.some(apiKey),
231
- baseURL: Option.some(baseURL),
232
- webURL: Option.some(webURL),
279
+ baseURL: Option.some(backend.baseURL),
280
+ webURL: Option.some(backend.webURL),
281
orgId: Option.fromNullishOr(orgId),
282
projectId: userData.projectId,
283
testUserId: Option.fromNullishOr(testUserId),
284
};
285
userData = next;
238
-
239
- if (keyringOk) {
240
- // Keyring has the key — writeJson will strip api_key from
241
- // disk automatically (useLegacyStorage is false).
242
- yield* writeJson(next);
243
- } else {
244
- // Keyring write failed (NoStorageAccess / headless Linux).
245
- // Force api_key into the JSON so it survives across
246
- // process restarts. We bypass writeJson's strip logic by
247
- // temporarily writing with the legacy-storage codepath.
248
- const onDisk = yield* userDataToJSON(next);
249
- const normalized = yield* normalizeEncodedUserData(onDisk, false);
250
- yield* Effect.logDebug(
251
- 'Saving user data (keyring fallback):',
252
- redactSensitiveLogValue(next)
253
- );
254
- yield* atomicWritePrivateFileString({
255
- fs,
256
- target: jsonUserConfigPath,
257
- contents: normalized,
258
- });
259
- }
286
+ yield* writeJson(next);
287
});
288
262
- const update = (data: Partial<UserData>) =>
289
+ const update = (data: Partial<Omit<UserData, 'baseURL' | 'webURL'>>) =>
290
Effect.gen(function* () {
264
- const nextUserData = { ...userData, ...data } satisfies UserData;
291
+ const nextUserData = {
292
+ ...userData,
293
+ ...data,
294
+ baseURL: userData.baseURL,
295
+ webURL: userData.webURL,
296
+ } satisfies UserData;
297
userData = nextUserData;
298
yield* writeJson(nextUserData);
299
yield* Effect.logDebug('User data updated:', redactSensitiveLogValue(userData));
305
const userDataJson = yield* fs.readFileString(jsonUserConfigPath, 'utf8');
306
const parsedUserData = (yield* userDataFromJSON(userDataJson)) satisfies UserData;
307
yield* Effect.logDebug('User data (parsed):', redactSensitiveLogValue(parsedUserData));
308
+ storedApiKey = parsedUserData.apiKey;
309
310
const overriddenUserData = {
311
...userData,
312
...parsedUserData,
313
apiKey: apiKey.pipe(Option.orElse(() => parsedUserData.apiKey)),
281
- baseURL: Option.some(baseURL),
282
- webURL: Option.some(webURL),
314
orgId: parsedUserData.orgId,
315
projectId: parsedUserData.projectId,
316
testUserId: parsedUserData.testUserId,
317
} satisfies UserData;
318
319
yield* Effect.logDebug(
289
- 'User data (overridden from env vars):',
320
+ 'User data (API key overridden from env vars):',
321
redactSensitiveLogValue(overriddenUserData)
322
);
323
userData = overriddenUserData;
348
const fromKeyring = yield* readKeyring(kDeps);
349
350
if (Option.isSome(fromKeyring)) {
351
+ storedApiKey = fromKeyring;
352
userData = { ...userData, apiKey: fromKeyring };
353
if (Option.isSome(plaintextOnDisk)) {
354
yield* Effect.logDebug('Clearing stale plaintext api_key from user_data.json');
357
} else if (Option.isSome(plaintextOnDisk)) {
358
yield* Effect.logDebug('Migrating legacy api_key from user_data.json to the OS keyring');
359
const migrated = yield* writeKeyring(kDeps, plaintextOnDisk.value);
360
+ keepApiKeyInFile = !migrated;
361
if (migrated) {
362
yield* Effect.logInfo('Composio API key migrated from user_data.json to the OS keyring');
363
yield* writeJson(userData);
369
370
const snapshot = (): UserDataWithDefaults => ({
371
...userData,
339
- baseURL: Option.getOrElse(userData.baseURL, () => baseURL),
340
- webURL: Option.getOrElse(userData.webURL, () => webURL),
372
+ ...currentBackend(),
373
orgId: userData.orgId,
374
projectId: userData.projectId,
375
testUserId: userData.testUserId,
379
get data() {
380
return snapshot();
381
},
382
+ get backendMismatch() {
383
+ return backendMismatch(envBackend, storedLogin());
384
+ },
385
isLoggedIn,
386
update,
387
login,