Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
Mirrored from https://github.com/Camo67/composio.git
Synced Nov 21, 18:30 UTC
fix(cli): keep analytics identity in sync with auth
Kshitij Jhunjhunwala committed
Jul 29, 2026 at 19:04 UTC
d00a3b5576ef9b1fe35406fe8e51371fa1f74d73
7 files changed
+229
-12
ts/packages/cli/src/analytics/dispatch.ts
+7
-3
@@ -129,6 +129,8 @@ const postHogEnabled = Effect.gen(function* () {
129
return projectKey.length > 0;
130
});
131
132
+export const analyticsIdentityLinkingEnabled = postHogEnabled;
133
+
134
const jsonFromString = Schema.parseJson();
135
const prettyJsonFromString = Schema.parseJson({ space: 2 });
136
const decodeJson = Schema.decodeUnknown(jsonFromString);
@@ -376,15 +378,17 @@ const getApiKeyFingerprint = Effect.flatMap(getUserApiKey, apiKey =>
378
);
379
380
// The keychain* security modes strip the api key from user_data.json, so no
379
-// fingerprint is computable here; a parseable user config in one of those
380
-// modes is the signal that the persisted identity still belongs to a login.
381
+// fingerprint is computable here. A persisted org is the durable login signal:
382
+// logout keeps the file but clears org_id, so a stale analytics identity can
383
+// never survive a failed best-effort state cleanup.
384
const keyringBackedLoginPresent = Effect.gen(function* () {
385
const paths = yield* getAnalyticsPaths;
386
const cliConfig = yield* readOptionalJson<{ security?: unknown }>(paths.cliConfigPath);
387
if (cliConfig?.security !== 'keychain' && cliConfig?.security !== 'keychain-subprocess') {
388
return false;
389
}
387
- return (yield* readUserConfig) !== undefined;
390
+ const userConfig = yield* readUserConfig;
391
+ return typeof userConfig?.org_id === 'string' && userConfig.org_id.trim().length > 0;
392
});
393
394
const getDistinctId = (installId: string) =>
ts/packages/cli/src/commands/login.cmd.ts
+40
-4
@@ -14,11 +14,11 @@ import { ComposioUserContext } from 'src/services/user-context';
14
import { TerminalUI } from 'src/services/terminal-ui';
15
import { commandHintStep } from 'src/services/command-hints';
16
import { runOrgSelection } from 'src/effects/select-org-project';
17
+import { linkAnalyticsIdentityForOrg } from 'src/effects/link-analytics-identity';
18
import { setupCacheDir } from 'src/effects/setup-cache-dir';
19
import { primeConsumerConnectedToolkitsCacheInBackground } from 'src/services/consumer-short-term-cache';
20
import { inferSkillReleaseChannel, installSkillSafe } from 'src/effects/install-skill';
21
import { handleAgentAuthError } from 'src/effects/handle-agent-auth-error';
21
-import { linkApolloIdentityForAnalytics } from 'src/analytics/dispatch';
22
import { APP_VERSION } from 'src/constants';
23
import {
24
ensureAgentSignupAllowed,
@@ -352,7 +352,15 @@ const directLogin = (params: { userApiKey: string; org?: string }) =>
352
: Option.getOrUndefined(ctx.data.testUserId);
353
354
yield* ctx.login(params.userApiKey, selectedOrg.id, testUserId);
355
- yield* linkApolloIdentityForAnalytics(sessionInfo.org_member.id, params.userApiKey);
355
+ yield* linkAnalyticsIdentityForOrg({
356
+ apiKey: params.userApiKey,
357
+ baseURL: ctx.data.baseURL,
358
+ orgId: selectedOrg.id,
359
+ knownIdentity: {
360
+ orgId: sessionInfo.project.org.id,
361
+ orgMemberId: sessionInfo.org_member.id,
362
+ },
363
+ });
364
yield* primeConsumerConnectedToolkitsCacheInBackground({
365
orgId: selectedOrg.id,
366
});
@@ -382,6 +390,8 @@ const storeCredentials = (params: {
390
skipHints?: boolean;
391
/** When true, skip JSON output (emitted later after org picker with final selection). */
392
skipOutput?: boolean;
393
+ /** When true, wait to link analytics until the org picker has made its final selection. */
394
+ deferAnalyticsIdentity?: boolean;
395
}) =>
396
Effect.gen(function* () {
397
const ctx = yield* ComposioUserContext;
@@ -395,6 +405,7 @@ const storeCredentials = (params: {
405
orgMemberId,
406
skipHints = false,
407
skipOutput = false,
408
+ deferAnalyticsIdentity = false,
409
} = params;
410
411
// Call session/info to enrich the login with org/project metadata.
@@ -437,8 +448,13 @@ const storeCredentials = (params: {
448
yield* ctx.login(uakApiKey, orgId, testUserId);
449
// Linked only after the credential persists, so stitching cannot outlive a failed login.
450
const linkedOrgMemberId = sessionInfo?.org_member.id ?? orgMemberId;
440
- if (linkedOrgMemberId) {
441
- yield* linkApolloIdentityForAnalytics(linkedOrgMemberId, uakApiKey);
451
+ if (linkedOrgMemberId && !deferAnalyticsIdentity) {
452
+ yield* linkAnalyticsIdentityForOrg({
453
+ apiKey: uakApiKey,
454
+ baseURL,
455
+ orgId,
456
+ knownIdentity: { orgId, orgMemberId: linkedOrgMemberId },
457
+ });
458
}
459
yield* primeConsumerConnectedToolkitsCacheInBackground({
460
orgId,
@@ -559,6 +575,7 @@ const loginWithKey = (params: {
575
orgMemberId: uakSessionInfo.org_member.id,
576
skipHints: willRunPicker,
577
skipOutput: true,
578
+ deferAnalyticsIdentity: willRunPicker,
579
});
580
581
if (willRunPicker) {
@@ -588,6 +605,15 @@ const loginWithKey = (params: {
605
}
606
const finalOrgId = result?.id ?? xOrgId;
607
const finalOrgName = result?.name ?? uakSessionInfo.project.org.name ?? '';
608
+ yield* linkAnalyticsIdentityForOrg({
609
+ apiKey: uakApiKey,
610
+ baseURL: ctx.data.baseURL,
611
+ orgId: finalOrgId,
612
+ knownIdentity: {
613
+ orgId: uakSessionInfo.project.org.id,
614
+ orgMemberId: uakSessionInfo.org_member.id,
615
+ },
616
+ });
617
yield* emitLoginComplete({
618
email: linkedSession.account.email ?? undefined,
619
orgId: finalOrgId,
@@ -754,6 +780,7 @@ export const browserLogin = (params: {
780
orgMemberId: uakSessionInfo.org_member.id,
781
skipHints: willRunPicker,
782
skipOutput: willRunPicker,
783
+ deferAnalyticsIdentity: willRunPicker,
784
});
785
786
if (willRunPicker) {
@@ -783,6 +810,15 @@ export const browserLogin = (params: {
810
}
811
const finalOrgId = result?.id ?? xOrgId;
812
const finalOrgName = result?.name ?? uakSessionInfo.project.org.name ?? '';
813
+ yield* linkAnalyticsIdentityForOrg({
814
+ apiKey: uakApiKey,
815
+ baseURL: ctx.data.baseURL,
816
+ orgId: finalOrgId,
817
+ knownIdentity: {
818
+ orgId: uakSessionInfo.project.org.id,
819
+ orgMemberId: uakSessionInfo.org_member.id,
820
+ },
821
+ });
822
yield* emitLoginComplete({
823
email: linkedSession.account.email ?? undefined,
824
orgId: finalOrgId,
ts/packages/cli/src/commands/orgs/commands/orgs.switch.cmd.ts
+6
@@ -2,6 +2,7 @@ import { Command, Options } from '@effect/cli';
2
import { Effect, Option } from 'effect';
3
import { requireAuth } from 'src/effects/require-auth';
4
import { runOrgSelection } from 'src/effects/select-org-project';
5
+import { linkAnalyticsIdentityForOrg } from 'src/effects/link-analytics-identity';
6
import { TerminalUI } from 'src/services/terminal-ui';
7
import { ComposioUserContext } from 'src/services/user-context';
8
@@ -49,6 +50,11 @@ export const orgsCmd$Switch = Command.make('switch', { orgId, limit }, ({ orgId,
50
}
51
52
yield* ctx.login(apiKey, result.id, Option.getOrUndefined(ctx.data.testUserId));
53
+ yield* linkAnalyticsIdentityForOrg({
54
+ apiKey,
55
+ baseURL: ctx.data.baseURL,
56
+ orgId: result.id,
57
+ });
58
59
yield* ui.log.success(`Updated current org to "${result.name}".`);
60
yield* ui.output(
ts/packages/cli/src/effects/link-analytics-identity.ts
new
+43
@@ -0,0 +1,43 @@
1
+import { Effect } from 'effect';
2
+import {
3
+ analyticsIdentityLinkingEnabled,
4
+ linkApolloIdentityForAnalytics,
5
+} from 'src/analytics/dispatch';
6
+import { getSessionInfoByUserApiKey } from 'src/services/composio-clients';
7
+
8
+type KnownOrgIdentity = {
9
+ readonly orgId: string;
10
+ readonly orgMemberId: string;
11
+};
12
+
13
+export const linkAnalyticsIdentityForOrg = (params: {
14
+ readonly apiKey: string;
15
+ readonly baseURL: string;
16
+ readonly orgId: string;
17
+ readonly knownIdentity?: KnownOrgIdentity;
18
+}) =>
19
+ Effect.gen(function* () {
20
+ const knownIdentity =
21
+ params.knownIdentity?.orgId === params.orgId ? params.knownIdentity : undefined;
22
+ if (!knownIdentity && !(yield* analyticsIdentityLinkingEnabled)) {
23
+ return;
24
+ }
25
+ const orgMemberId = knownIdentity
26
+ ? knownIdentity.orgMemberId
27
+ : yield* getSessionInfoByUserApiKey({
28
+ baseURL: params.baseURL,
29
+ userApiKey: params.apiKey,
30
+ orgId: params.orgId,
31
+ }).pipe(
32
+ Effect.map(sessionInfo => sessionInfo.org_member.id),
33
+ Effect.catchAll(error =>
34
+ Effect.logDebug('Failed to resolve analytics identity for selected org:', error).pipe(
35
+ Effect.as(undefined)
36
+ )
37
+ )
38
+ );
39
+
40
+ if (orgMemberId) {
41
+ yield* linkApolloIdentityForAnalytics(orgMemberId, params.apiKey);
42
+ }
43
+ });
ts/packages/cli/test/src/analytics.dispatch.test.ts
+49
@@ -1068,6 +1068,55 @@ describe('CLI analytics dispatch', () => {
1068
}).pipe(Effect.provide(makePlatformLayer(home)));
1069
});
1070
1071
+ it.effect('does not reuse a stale keychain identity when logout loses the state lock', () => {
1072
+ const home = tempy.temporaryDirectory();
1073
+ const scriptPath = `${home}/composio.ts`;
1074
+ enableTelemetry('');
1075
+ vi.stubEnv('COMPOSIO_CACHE_DIR', `${home}/.composio`);
1076
+ process.argv[1] = scriptPath;
1077
+
1078
+ return Effect.gen(function* () {
1079
+ const fs = yield* FileSystem.FileSystem;
1080
+ const path = yield* Path.Path;
1081
+ yield* fs.writeFileString(scriptPath, '');
1082
+ const composioDir = path.join(home, '.composio');
1083
+ yield* fs.makeDirectory(composioDir, { recursive: true });
1084
+ yield* fs.writeFileString(
1085
+ path.join(composioDir, 'config.json'),
1086
+ JSON.stringify({ security: 'keychain-subprocess' })
1087
+ );
1088
+ // Logout persists an empty credential record but intentionally keeps
1089
+ // user_data.json in place.
1090
+ yield* fs.writeFileString(
1091
+ path.join(composioDir, USER_CONFIG_FILE_NAME),
1092
+ JSON.stringify({ base_url: 'https://backend.example.test' })
1093
+ );
1094
+ yield* fs.writeFileString(
1095
+ path.join(composioDir, 'analytics.json'),
1096
+ JSON.stringify({
1097
+ install_id: 'install_keychain_logout',
1098
+ apollo_user_id: 'om_logged_out_keychain_user',
1099
+ aliased_apollo_user_id: 'om_logged_out_keychain_user',
1100
+ })
1101
+ );
1102
+ const lockPath = path.join(composioDir, 'analytics.json.lock');
1103
+ yield* fs.writeFileString(lockPath, 'other-process');
1104
+
1105
+ // The clear is best-effort and times out while another process owns
1106
+ // the lock, leaving the old identity on disk.
1107
+ yield* clearApolloIdentityForAnalytics;
1108
+ yield* fs.remove(lockPath);
1109
+ childProcessMocks.spawn.mockClear();
1110
+
1111
+ yield* trackCliEventEffect({ name: 'producer_event' });
1112
+
1113
+ const args = childProcessMocks.spawn.mock.calls[0]![1] as string[];
1114
+ const payload = decodeWorkerPayload<{ distinctId: string; installId: string }>(args[2]!);
1115
+ expect(payload.distinctId).not.toBe('om_logged_out_keychain_user');
1116
+ expect(payload.distinctId).toBe(`anon_${payload.installId}`);
1117
+ }).pipe(Effect.provide(makePlatformLayer(home)));
1118
+ });
1119
+
1120
it.effect('does not trust a fingerprint-less identity outside keychain modes', () => {
1121
const home = tempy.temporaryDirectory();
1122
const scriptPath = `${home}/composio.ts`;
ts/packages/cli/test/src/commands/login.cmd.test.ts
+12
-5
@@ -28,6 +28,7 @@ vi.mock('src/analytics/dispatch', async importOriginal => {
28
const { ComposioUserContext } = await import('src/services/user-context');
29
return {
30
...actual,
31
+ analyticsIdentityLinkingEnabled: Effect.succeed(true),
32
linkApolloIdentityForAnalytics: ((apolloUserId: string) =>
33
Effect.map(ComposioUserContext, ctx => {
34
analyticsMocks.linkCalls.push({ apolloUserId, loggedInAtLinkTime: ctx.isLoggedIn() });
@@ -340,19 +341,24 @@ describe('CLI: composio login', () => {
341
const url = requestUrl(requestInput);
342
343
if (url.includes('/api/v3/auth/session/info')) {
344
+ const selectedOrgId = new Headers(init?.headers).get('x-org-id');
345
return mockFetchResponse({
346
project: {
347
name: 'Default Project',
348
id: 'project_id_default',
347
- org_id: 'org_default',
349
+ org_id: selectedOrgId ?? 'org_default',
350
nano_id: 'project_default',
351
email: 'project@example.com',
352
created_at: '2026-01-01T00:00:00.000Z',
353
updated_at: '2026-01-01T00:00:00.000Z',
352
- org: { id: 'org_default', name: 'Example Org', plan: 'enterprise' },
354
+ org: {
355
+ id: selectedOrgId ?? 'org_default',
356
+ name: selectedOrgId ? 'Selected Org' : 'Example Org',
357
+ plan: 'enterprise',
358
+ },
359
},
360
org_member: {
355
- id: 'member_123',
361
+ id: selectedOrgId ? 'member_selected' : 'member_default',
362
user_id: 'user_123',
363
email: 'cli@example.com',
364
name: 'CLI User',
@@ -408,9 +414,10 @@ describe('CLI: composio login', () => {
414
expect(output).toContain('Logged in as cli@example.com in "Selected Org"');
415
416
// The analytics identity is linked exactly once, and only after the
411
- // credential was stored via ctx.login.
417
+ // credential was stored via ctx.login, using the selected org's
418
+ // membership rather than the API key's home-org membership.
419
expect(analyticsMocks.linkCalls).toEqual([
413
- { apolloUserId: 'member_123', loggedInAtLinkTime: true },
420
+ { apolloUserId: 'member_selected', loggedInAtLinkTime: true },
421
]);
422
})
423
);
ts/packages/cli/test/src/commands/orgs.switch.cmd.test.ts
new
+72
@@ -0,0 +1,72 @@
1
+import { describe, expect, layer } from '@effect/vitest';
2
+import { ConfigProvider, Effect } from 'effect';
3
+import { afterEach, vi } from 'vitest';
4
+import { extendConfigProvider } from 'src/services/config';
5
+import { cli, TestLive } from 'test/__utils__';
6
+
7
+const analyticsMocks = vi.hoisted(() => ({
8
+ linkCalls: [] as string[],
9
+}));
10
+
11
+vi.mock('src/analytics/dispatch', async importOriginal => {
12
+ const actual = await importOriginal<typeof import('src/analytics/dispatch')>();
13
+ const { Effect } = await import('effect');
14
+ return {
15
+ ...actual,
16
+ analyticsIdentityLinkingEnabled: Effect.succeed(true),
17
+ linkApolloIdentityForAnalytics: ((apolloUserId: string) =>
18
+ Effect.sync(() => {
19
+ analyticsMocks.linkCalls.push(apolloUserId);
20
+ })) as unknown as typeof actual.linkApolloIdentityForAnalytics,
21
+ };
22
+});
23
+
24
+describe('CLI: composio orgs switch', () => {
25
+ afterEach(() => {
26
+ vi.restoreAllMocks();
27
+ analyticsMocks.linkCalls.length = 0;
28
+ });
29
+
30
+ const testConfigProvider = ConfigProvider.fromMap(
31
+ new Map([['COMPOSIO_USER_API_KEY', 'uak_switch_test']])
32
+ ).pipe(extendConfigProvider);
33
+
34
+ layer(TestLive({ baseConfigProvider: testConfigProvider }))(it => {
35
+ it.scoped('[Then] links analytics to the selected org membership', () =>
36
+ Effect.gen(function* () {
37
+ vi.spyOn(globalThis, 'fetch').mockImplementation(
38
+ async (_requestInput: RequestInfo | URL, init?: RequestInit) => {
39
+ expect(new Headers(init?.headers).get('x-org-id')).toBe('org_selected');
40
+ return new Response(
41
+ JSON.stringify({
42
+ project: {
43
+ name: 'Selected Project',
44
+ id: 'project_selected',
45
+ org_id: 'org_selected',
46
+ nano_id: 'project_selected',
47
+ email: 'project@example.com',
48
+ created_at: '2026-01-01T00:00:00.000Z',
49
+ updated_at: '2026-01-01T00:00:00.000Z',
50
+ org: { id: 'org_selected', name: 'Selected Org', plan: 'enterprise' },
51
+ },
52
+ org_member: {
53
+ id: 'member_selected',
54
+ user_id: 'user_123',
55
+ email: 'cli@example.com',
56
+ name: 'CLI User',
57
+ role: 'admin',
58
+ },
59
+ api_key: null,
60
+ }),
61
+ { status: 200, headers: { 'Content-Type': 'application/json' } }
62
+ );
63
+ }
64
+ );
65
+
66
+ yield* cli(['orgs', 'switch', '--org-id', 'org_selected']);
67
+
68
+ expect(analyticsMocks.linkCalls).toEqual(['member_selected']);
69
+ })
70
+ );
71
+ });
72
+});