Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
fix(cli): harden client-side analytics identity and event hygiene
Kshitij Jhunjhunwalaf043061952a9
diff --git a/ts/packages/cli/src/analytics/dispatch.ts b/ts/packages/cli/src/analytics/dispatch.tsindex dcf82b8b0..b04f6c54e 100644--- a/ts/packages/cli/src/analytics/dispatch.ts+++ b/ts/packages/cli/src/analytics/dispatch.ts@@ -158,6 +158,7 @@ const getAnalyticsPaths = Effect.gen(function* () {analyticsDir,analyticsStatePath: path.join(analyticsDir, ANALYTICS_STATE_FILE_NAME),userConfigPath: path.join(analyticsDir, constants.USER_CONFIG_FILE_NAME),+ cliConfigPath: path.join(analyticsDir, constants.CLI_CONFIG_FILE_NAME),consumerShortTermCachePath: path.join(cacheDir, CONSUMER_SHORT_TERM_CACHE_FILE_NAME),};});@@ -174,6 +175,7 @@ type AnalyticsState = {readonly apollo_user_id?: string;readonly aliased_apollo_user_id?: string;readonly api_key_fingerprint?: string;+ readonly stitch_attempted_at?: string;readonly created_at?: string;};@@ -184,6 +186,19 @@ const readAnalyticsState = Effect.gen(function* () {return yield* readOptionalJson<AnalyticsState>(paths.analyticsStatePath);});+// Concurrent CLI processes write this file; temp-file + rename keeps each+// write atomic so readers never observe partial JSON.+const writeAnalyticsStateFile = (contents: string) =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const paths = yield* getAnalyticsPaths;+ const temporaryPath = `${paths.analyticsStatePath}.${crypto.randomUUID().slice(0, 8)}.tmp`;+ yield* fs.writeFileString(temporaryPath, contents);+ yield* fs+ .rename(temporaryPath, paths.analyticsStatePath)+ .pipe(Effect.tapError(() => fs.remove(temporaryPath).pipe(Effect.ignore)));+ });+const getOrCreateInstallId = Effect.gen(function* () {const fs = yield* FileSystem.FileSystem;const paths = yield* getAnalyticsPaths;@@ -204,7 +219,7 @@ const getOrCreateInstallId = Effect.gen(function* () {install_id: installId,created_at: createdAt,});- yield* fs.writeFileString(paths.analyticsStatePath, contents);+ yield* writeAnalyticsStateFile(contents);return installId;}).pipe(Effect.catchAll(() => makeInstallId));@@ -224,7 +239,7 @@ const mergeAnalyticsState = (installId: string, patch: Partial<AnalyticsState>)created_at: state?.created_at ?? DateTime.formatIso(yield* DateTime.now),...patch,});- yield* fs.writeFileString(paths.analyticsStatePath, contents);+ yield* writeAnalyticsStateFile(contents);}).pipe(Effect.catchAll(() => Effect.void));const readUserConfig = Effect.gen(function* () {@@ -259,19 +274,31 @@ const getApiKeyFingerprint = Effect.map(getUserApiKey, apiKey =>apiKey ? fingerprintApiKey(apiKey) : null);+// The keychain* security modes strip the api key from user_data.json, so no+// fingerprint is computable here; a parseable user config in one of those+// modes is the signal that the persisted identity still belongs to a login.+const keyringBackedLoginPresent = Effect.gen(function* () {+ const paths = yield* getAnalyticsPaths;+ const cliConfig = yield* readOptionalJson<{ security?: unknown }>(paths.cliConfigPath);+ if (cliConfig?.security !== 'keychain' && cliConfig?.security !== 'keychain-subprocess') {+ return false;+ }+ return (yield* readUserConfig) !== undefined;+});+const getDistinctId = (installId: string) =>Effect.gen(function* () {const state = yield* readAnalyticsState;const apolloUserId = state?.apollo_user_id;const fingerprint = yield* getApiKeyFingerprint;- if (- typeof apolloUserId === 'string' &&- apolloUserId.length > 0 &&- fingerprint !== null &&- fingerprint === state?.api_key_fingerprint- ) {- return apolloUserId;+ if (typeof apolloUserId === 'string' && apolloUserId.length > 0) {+ if (fingerprint !== null && fingerprint === state?.api_key_fingerprint) {+ return apolloUserId;+ }+ if (fingerprint === null && (yield* keyringBackedLoginPresent)) {+ return apolloUserId;+ }}if (typeof state?.aliased_apollo_user_id !== 'string') {@@ -280,6 +307,54 @@ const getDistinctId = (installId: string) =>return fingerprint !== null ? `user_${fingerprint}` : `anon_${installId}`;});+// The direct-to-PostHog path bypasses Apollo's server-side sanitizer, so+// secret-shaped tokens are redacted client-side before any envelope leaves.+const REDACTED_VALUE = '[redacted]';+const KNOWN_SECRET_PATTERNS: ReadonlyArray<RegExp> = [+ /\buak_[A-Za-z0-9_-]+/gu,+ /\bak_[A-Za-z0-9_-]+/gu,+ /\bphc_[A-Za-z0-9]+/gu,+ /\bsk-[A-Za-z0-9_-]+/gu,+ /\bghp_[A-Za-z0-9]+/gu,+ /\bBearer\s+[A-Za-z0-9._~+/=-]+/gu,+];++// Mixed-case-plus-digit tokens of api-key length; single-case tokens+// (uuids, hex ids, tool slugs) stay untouched.+const isHighEntropyToken = (token: string): boolean =>+ token.length >= 24 &&+ /^[A-Za-z0-9+/=_-]+$/u.test(token) &&+ /[a-z]/u.test(token) &&+ /[A-Z]/u.test(token) &&+ /[0-9]/u.test(token);++const scrubSecretsFromString = (value: string): string =>+ KNOWN_SECRET_PATTERNS.reduce(+ (scrubbed, pattern) => scrubbed.replace(pattern, REDACTED_VALUE),+ value+ )+ .split(/(\s+)/u)+ .map(part => (isHighEntropyToken(part) ? REDACTED_VALUE : part))+ .join('');++const scrubSecrets = (value: unknown): unknown => {+ if (typeof value === 'string') {+ return scrubSecretsFromString(value);+ }+ if (Array.isArray(value)) {+ return value.map(scrubSecrets);+ }+ if (value !== null && typeof value === 'object') {+ return Object.fromEntries(+ Object.entries(value as Record<string, unknown>).map(([key, entry]) => [+ key,+ scrubSecrets(entry),+ ])+ );+ }+ return value;+};+const cwdHash = (cwd: string): string => djb2Hash(cwd).toString(36);export const getCurrentCwdSessionId = (cwd = process.cwd()) =>@@ -553,10 +628,10 @@ export const trackCliEventEffect = (event: TrackEvent) =>const distinctId = yield* getDistinctId(installId);const orgId = yield* getOrgId;const sentAt = DateTime.formatIso(yield* DateTime.now);- const properties = {+ const properties = scrubSecrets({...(enrichedEvent.properties ?? {}),...(orgId ? { org_id: orgId } : {}),- };+ }) as Record<string, unknown>;const envelope: AnalyticsEnvelope = {event: enrichedEvent.name,...(Object.keys(properties).length > 0 ? { properties } : {}),@@ -605,8 +680,27 @@ export const linkApolloIdentityForAnalytics = (apolloUserId: string, apiKey?: streturn;}- const state = yield* readAnalyticsState;- const installId = yield* getOrCreateInstallId;+ let state = yield* readAnalyticsState;+ let installId = yield* getOrCreateInstallId;++ // A second user on this machine must not merge into the previous user's+ // PostHog person: rotate to a fresh install_id before linking.+ const previousIdentity = state?.apollo_user_id ?? state?.aliased_apollo_user_id;+ const identityChanged =+ typeof previousIdentity === 'string' &&+ previousIdentity.length > 0 &&+ previousIdentity !== resolved;+ if (identityChanged) {+ installId = yield* makeInstallId;+ yield* mergeAnalyticsState(installId, {+ install_id: installId,+ apollo_user_id: undefined,+ aliased_apollo_user_id: undefined,+ api_key_fingerprint: undefined,+ });+ state = yield* readAnalyticsState;+ }+const fingerprint =typeof apiKey === 'string' && apiKey.length > 0? fingerprintApiKey(apiKey)@@ -626,6 +720,55 @@ export const linkApolloIdentityForAnalytics = (apolloUserId: string, apiKey?: st}}).pipe(Effect.catchAllCause(() => Effect.void));+const STITCH_ATTEMPT_INTERVAL_MS = 24 * 60 * 60 * 1000;+const STITCH_SESSION_INFO_TIMEOUT = '1500 millis';++type AnalyticsSessionInfoFetcher = (params: {+ baseURL: string;+ userApiKey: string;+}) => Effect.Effect<{ readonly org_member: { readonly id: string } }, unknown>;++// Repairs a missing/stale persisted identity for already-logged-in installs+// (e.g. keyring-stored keys that predate identity stitching). The session-info+// fetcher is injected because composio-clients already imports this module.+export const ensureAnalyticsIdentity = (params: {+ apiKey: string;+ baseURL: string;+ fetchSessionInfo: AnalyticsSessionInfoFetcher;+}) =>+ Effect.gen(function* () {+ if ((yield* analyticsDisabled) || params.apiKey.trim().length === 0) {+ return;+ }++ const state = yield* readAnalyticsState;+ const fingerprint = fingerprintApiKey(params.apiKey);+ const identityLinked =+ typeof state?.apollo_user_id === 'string' &&+ state.apollo_user_id.length > 0 &&+ state.api_key_fingerprint === fingerprint;+ if (identityLinked) {+ return;+ }++ const lastAttemptMs = Date.parse(state?.stitch_attempted_at ?? '');+ const nowMs = yield* Clock.currentTimeMillis;+ if (Number.isFinite(lastAttemptMs) && nowMs - lastAttemptMs < STITCH_ATTEMPT_INTERVAL_MS) {+ return;+ }++ // Persisted before the network attempt so failures cannot retry-storm.+ const installId = yield* getOrCreateInstallId;+ yield* mergeAnalyticsState(installId, {+ stitch_attempted_at: DateTime.formatIso(yield* DateTime.now),+ });++ const info = yield* params+ .fetchSessionInfo({ baseURL: params.baseURL, userApiKey: params.apiKey })+ .pipe(Effect.timeout(STITCH_SESSION_INFO_TIMEOUT));+ yield* linkApolloIdentityForAnalytics(info.org_member.id, params.apiKey);+ }).pipe(Effect.catchAllCause(() => Effect.void));+export const clearApolloIdentityForAnalytics = Effect.gen(function* () {const state = yield* readAnalyticsState;if (!state?.install_id || !state.apollo_user_id) {diff --git a/ts/packages/cli/src/cli-main.ts b/ts/packages/cli/src/cli-main.tsindex 68d86d95f..d3929af40 100644--- a/ts/packages/cli/src/cli-main.ts+++ b/ts/packages/cli/src/cli-main.ts@@ -1,5 +1,5 @@import process from 'node:process';-import { Cause, Effect, Exit, Layer, Logger } from 'effect';+import { Cause, Effect, Exit, Layer, Logger, Option } from 'effect';import { captureErrors, prettyPrintFromCapturedErrors } from 'effect-errors/index';import { CliConfig, HelpDoc, ValidationError } from '@effect/cli';import { FetchHttpClient } from '@effect/platform';@@ -15,13 +15,17 @@ import {ComposioClientSingleton,ComposioSessionRepository,ComposioToolkitsRepository,+ getSessionInfoByUserApiKey,} from 'src/services/composio-clients';import { ComposioToolkitsRepositoryCached } from 'src/services/composio-clients-cached';import { NodeOs } from 'src/services/node-os';import { NodeProcess } from 'src/services/node-process';import { JsPackageManagerDetector } from 'src/services/js-package-manager-detector';import { ComposioCliUserConfigLive, ComposioCliUserConfig } from 'src/services/cli-user-config';-import { ComposioUserContextLive as _ComposioUserContextLive } from 'src/services/user-context';+import {+ ComposioUserContext,+ ComposioUserContextLive as _ComposioUserContextLive,+} from 'src/services/user-context';import { UpgradeBinary } from 'src/services/upgrade-binary';import { TerminalUI, TerminalUILive } from 'src/services/terminal-ui';import { TriggersRealtime } from 'src/services/triggers-realtime';@@ -37,7 +41,7 @@ import {getPrimaryLifecycleInvokedEvent,getPrimaryLifecycleSucceededEvent,} from 'src/analytics/events';-import { trackCliEventEffect } from 'src/analytics/dispatch';+import { ensureAnalyticsIdentity, trackCliEventEffect } from 'src/analytics/dispatch';import { mapOnlyComposioOverrideError } from 'src/services/composio-error-overrides';import { SetupSkillInstaller } from 'src/services/setup-skill-installer';import { SetupCommandError } from 'src/services/setup';@@ -144,6 +148,19 @@ const runWithArgs = Effect.flatMap(runWithConfig, run => run(process.argv)) saticonst runWithTelemetry = Effect.gen(function* () {const ui = yield* TerminalUI;const terminal = yield* ui.capabilities;++ // Stitch the analytics identity for installs whose credential (env or+ // keyring) resolved without ever passing through a login-time link.+ const userContext = yield* ComposioUserContext;+ const resolvedApiKey = Option.getOrUndefined(userContext.data.apiKey);+ if (resolvedApiKey) {+ yield* ensureAnalyticsIdentity({+ apiKey: resolvedApiKey,+ baseURL: userContext.data.baseURL,+ fetchSessionInfo: getSessionInfoByUserApiKey,+ });+ }+const commandTelemetryContext = createCliCommandTelemetryContext(process.argv,constants.APP_VERSION,diff --git a/ts/packages/cli/test/src/analytics.dispatch.test.ts b/ts/packages/cli/test/src/analytics.dispatch.test.tsindex 2a4073e28..de8d8b869 100644--- a/ts/packages/cli/test/src/analytics.dispatch.test.ts+++ b/ts/packages/cli/test/src/analytics.dispatch.test.ts@@ -7,6 +7,7 @@ import * as tempy from 'tempy';import {clearApolloIdentityForAnalytics,emitPostHogAlias,+ ensureAnalyticsIdentity,getCurrentCwdSessionId,linkApolloIdentityForAnalytics,readApiBaseUrl,@@ -774,7 +775,7 @@ describe('CLI analytics dispatch', () => {}).pipe(Effect.provide(makePlatformLayer(home)));});- it.effect('never re-aliases one install onto a second Apollo user', () => {+ it.effect('rotates to a fresh install_id when a second Apollo user links', () => {const home = tempy.temporaryDirectory();const scriptPath = `${home}/composio.ts`;enableTelemetry();@@ -782,15 +783,216 @@ describe('CLI analytics dispatch', () => {return Effect.gen(function* () {const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;yield* fs.writeFileString(scriptPath, '');yield* linkApolloIdentityForAnalytics('om_first_user');expect(childProcessMocks.spawn).toHaveBeenCalledTimes(1);+ const firstArgs = childProcessMocks.spawn.mock.calls[0]![1] as string[];+ const firstPayload = decodeWorkerPayload<{ installId: string }>(firstArgs[2]!);- // Logout, then log in as a different user on the same device.+ // Logout, then log in as a different user on the same device: the+ // second user is aliased to a fresh install_id, never the one already+ // merged into the first user's PostHog person.yield* clearApolloIdentityForAnalytics;yield* linkApolloIdentityForAnalytics('om_second_user');+ expect(childProcessMocks.spawn).toHaveBeenCalledTimes(2);+ const secondArgs = childProcessMocks.spawn.mock.calls[1]![1] as string[];+ const secondPayload = decodeWorkerPayload<{+ event: string;+ distinctId: string;+ installId: string;+ properties: { alias: string };+ }>(secondArgs[2]!);+ expect(secondPayload.event).toBe('$create_alias');+ expect(secondPayload.distinctId).toBe('om_second_user');+ expect(secondPayload.installId).not.toBe(firstPayload.installId);+ expect(secondPayload.properties.alias).toBe(secondPayload.installId);++ const persisted = JSON.parse(+ yield* fs.readFileString(path.join(home, '.composio', 'analytics.json'), 'utf8')+ ) as { install_id: string; apollo_user_id: string; aliased_apollo_user_id: string };+ expect(persisted.install_id).toBe(secondPayload.installId);+ expect(persisted.apollo_user_id).toBe('om_second_user');+ expect(persisted.aliased_apollo_user_id).toBe('om_second_user');+ }).pipe(Effect.provide(makePlatformLayer(home)));+ });++ it.effect('trusts the persisted identity when the api key lives in the OS keyring', () => {+ const home = tempy.temporaryDirectory();+ const scriptPath = `${home}/composio.ts`;+ // No env key and no plaintext api_key on disk -> no fingerprint.+ enableTelemetry('');+ process.argv[1] = scriptPath;++ return Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ yield* fs.writeFileString(scriptPath, '');+ const composioDir = path.join(home, '.composio');+ yield* fs.makeDirectory(composioDir, { recursive: true });+ yield* fs.writeFileString(+ path.join(composioDir, 'config.json'),+ JSON.stringify({ security: 'keychain-subprocess' })+ );+ yield* fs.writeFileString(+ path.join(composioDir, USER_CONFIG_FILE_NAME),+ JSON.stringify({ base_url: 'https://backend.example.test', org_id: 'org_keychain' })+ );+ yield* fs.writeFileString(+ path.join(composioDir, 'analytics.json'),+ JSON.stringify({+ install_id: 'install_keychain',+ apollo_user_id: 'om_keychain_user',+ aliased_apollo_user_id: 'om_keychain_user',+ api_key_fingerprint: 'abc.5',+ })+ );++ yield* trackCliEventEffect({ name: 'producer_event' });++ const args = childProcessMocks.spawn.mock.calls[0]![1] as string[];+ const payload = decodeWorkerPayload<{ distinctId: string }>(args[2]!);+ expect(payload.distinctId).toBe('om_keychain_user');+ }).pipe(Effect.provide(makePlatformLayer(home)));+ });++ it.effect('does not trust a fingerprint-less identity outside keychain modes', () => {+ const home = tempy.temporaryDirectory();+ const scriptPath = `${home}/composio.ts`;+ enableTelemetry('');+ process.argv[1] = scriptPath;++ return Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ yield* fs.writeFileString(scriptPath, '');+ const composioDir = path.join(home, '.composio');+ yield* fs.makeDirectory(composioDir, { recursive: true });+ yield* fs.writeFileString(+ path.join(composioDir, 'config.json'),+ JSON.stringify({ security: 'json' })+ );+ yield* fs.writeFileString(+ path.join(composioDir, USER_CONFIG_FILE_NAME),+ JSON.stringify({ org_id: 'org_json' })+ );+ yield* fs.writeFileString(+ path.join(composioDir, 'analytics.json'),+ JSON.stringify({+ install_id: 'install_json',+ apollo_user_id: 'om_json_user',+ aliased_apollo_user_id: 'om_json_user',+ api_key_fingerprint: 'abc.5',+ })+ );++ yield* trackCliEventEffect({ name: 'producer_event' });++ const args = childProcessMocks.spawn.mock.calls[0]![1] as string[];+ const payload = decodeWorkerPayload<{ distinctId: string }>(args[2]!);+ expect(payload.distinctId).toBe('anon_install_json');+ }).pipe(Effect.provide(makePlatformLayer(home)));+ });++ it.effect('redacts secret-shaped tokens from event properties', () => {+ const home = tempy.temporaryDirectory();+ const scriptPath = `${home}/composio.ts`;+ enableTelemetry();+ process.argv[1] = scriptPath;++ return Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ yield* fs.writeFileString(scriptPath, '');++ yield* trackCliEventEffect({+ name: CLI_ANALYTICS_EVENTS.CLI_COMMAND_FAILED,+ properties: {+ error_message: 'Auth failed for uak_AbC123xyz_secret via Bearer eyJhbGciOi.Jt0ken',+ nested: { tokens: ['ghp_ABCdef1234567890'] },+ duration_ms: 42,+ },+ });++ const args = childProcessMocks.spawn.mock.calls[0]![1] as string[];+ const payload = decodeWorkerPayload<{+ properties: {+ error_message: string;+ nested: { tokens: string[] };+ duration_ms: number;+ };+ }>(args[2]!);+ expect(payload.properties.error_message).toBe('Auth failed for [redacted] via [redacted]');+ expect(payload.properties.nested.tokens).toEqual(['[redacted]']);+ expect(payload.properties.duration_ms).toBe(42);+ }).pipe(Effect.provide(makePlatformLayer(home)));+ });++ it.effect('bootstrap stitch links a missing identity through session info', () => {+ const home = tempy.temporaryDirectory();+ const scriptPath = `${home}/composio.ts`;+ enableTelemetry('uak_stitch');+ process.argv[1] = scriptPath;+ const fetchSessionInfo = vi.fn(() => Effect.succeed({ org_member: { id: 'om_stitched' } }));++ return Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ yield* fs.writeFileString(scriptPath, '');++ yield* ensureAnalyticsIdentity({+ apiKey: 'uak_stitch',+ baseURL: 'https://backend.example.test',+ fetchSessionInfo,+ });++ expect(fetchSessionInfo).toHaveBeenCalledTimes(1);expect(childProcessMocks.spawn).toHaveBeenCalledTimes(1);+ const args = childProcessMocks.spawn.mock.calls[0]![1] as string[];+ const payload = decodeWorkerPayload<{ event: string; distinctId: string }>(args[2]!);+ expect(payload.event).toBe('$create_alias');+ expect(payload.distinctId).toBe('om_stitched');++ // Once linked under this credential, later runs make no network attempt.+ yield* ensureAnalyticsIdentity({+ apiKey: 'uak_stitch',+ baseURL: 'https://backend.example.test',+ fetchSessionInfo,+ });+ expect(fetchSessionInfo).toHaveBeenCalledTimes(1);+ }).pipe(Effect.provide(makePlatformLayer(home)));+ });++ it.effect('bootstrap stitch attempts at most once per day after a failure', () => {+ const home = tempy.temporaryDirectory();+ const scriptPath = `${home}/composio.ts`;+ enableTelemetry('uak_stitch');+ process.argv[1] = scriptPath;+ const fetchSessionInfo = vi.fn(() => Effect.fail(new Error('offline')));++ return Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ yield* fs.writeFileString(scriptPath, '');++ yield* ensureAnalyticsIdentity({+ apiKey: 'uak_stitch',+ baseURL: 'https://backend.example.test',+ fetchSessionInfo,+ });+ expect(fetchSessionInfo).toHaveBeenCalledTimes(1);++ const persisted = JSON.parse(+ yield* fs.readFileString(path.join(home, '.composio', 'analytics.json'), 'utf8')+ ) as { stitch_attempted_at?: string };+ expect(typeof persisted.stitch_attempted_at).toBe('string');++ // Identity is still unlinked, but the attempt is throttled for 24h.+ yield* ensureAnalyticsIdentity({+ apiKey: 'uak_stitch',+ baseURL: 'https://backend.example.test',+ fetchSessionInfo,+ });+ expect(fetchSessionInfo).toHaveBeenCalledTimes(1);}).pipe(Effect.provide(makePlatformLayer(home)));});});