@devries-cameron20 / composio-1 / commits / 021d65784
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

fix(cli): use the backend recorded at login (#5000)

This PR: - supersedes #4457 with a smaller fix - resolves the backend in one place (`resolveBackend` in `src/config/backend.ts`): `COMPOSIO_BASE_URL` or `COMPOSIO_ENVIRONMENT` when set, else the `base_url`/`web_url` the stored login recorded, else production; a key from `COMPOSIO_USER_API_KEY` keeps the env-selected backend - records the backend only in `ctx.login(...)`: `update` can no longer change it, `orgs switch` updates the org instead of re-logging in, and `logout` forgets it - warns once on stderr, before any request, when an env var sends the stored key to a backend other than the one that issued it - maps the backend's `UserApiKey_Unauthorized` rejection (in `handleClientApiError` and `cli-main.ts`) to ``composio logout && <COMPOSIO_ENVIRONMENT=staging | COMPOSIO_BASE_URL=…> composio login``, or to replacing `COMPOSIO_USER_API_KEY` when the key came from there ## Context A user logged in with staging selected, later ran a command without the env var, and got `Invalid or revoked user API key`. The key was valid: `user_data.json` recorded `base_url`, but `ComposioUserContext` replaced it with the env-selected backend (production by default) on every run, so the staging key went to production, and logging in again would have swapped the working staging key for a production one. Every API client, the login session and its dashboard URL, `link`'s dashboard URL, and `composio run`'s child environment already read `ctx.data.baseURL`/`webURL`, so fixing the context fixes them; analytics failure delivery (`readApiBaseUrl`, which runs in a detached worker without the context) now calls the same `resolveBackend`. Interaction with #4754: `resolveConsumerExecutionTransport` is unchanged. With no env var it still picks the Dashboard, and the Dashboard execution reads `ctx.data.webURL`, so a staging login now executes through the staging Dashboard instead of production's. One gap remains: a login recorded with a custom `COMPOSIO_BASE_URL` but no `COMPOSIO_WEB_URL` keeps the production Dashboard as its `web_url`, so a later `composio execute` without env vars goes there. That is no worse than before this change, and making the transport rule aware of the stored backend belongs in a follow-up. Testing: - `pnpm --filter @composio/cli test`: 2207 passed, 1 skipped (`validate:command-tests` at 2 exemptions); `typecheck`, `lint:effect`, oxlint, prettier, and repo-root `pnpm typecheck` pass - new tests fail on `next`: the resolution matrix (stored staging with no env → staging; with `COMPOSIO_BASE_URL` → production plus the mismatch; `COMPOSIO_USER_API_KEY` → default), `update` and `orgs switch` keeping `base_url`, re-login keeping staging, logout forgetting it, `readApiBaseUrl`, and two spawned-CLI cases (warning on stderr only; a stored login pointing at a local 401 server receives the request and prints the hint with empty stdout). Two cases (no stored key → default; login under `COMPOSIO_ENVIRONMENT=staging` records staging) pass on `next` too and guard the unchanged behaviour - compiled-binary smoke with an isolated `HOME`, a bogus `uak_` key, and two local listeners A and B: with no env vars `orgs list` hit A with the stored key; with `COMPOSIO_BASE_URL=B` it hit only B and printed the warning on stderr with empty stdout; `orgs switch --org-id org_x` under that override changed `org_id` and left `base_url`/`web_url` pointing at A

Alberto Schiabel committed Oct 21, 2026 at 00:22 UTC 021d65784d348a29908eaf74ebd24eb65b54eb48
29 files changed +868 -88
ts/packages/cli/AGENTS.md
+1 -1
@@ -148,7 +148,7 @@ Steps 3–4 (and the TypeScript compiler they need) ship as the `generation-runt
148 ### Configuration
149
150 - CLI: `cli-config.ts` enables help and version global actions. `commands/root-help.ts` derives the native `help` command tree and delegates documents to Effect. The formatter keeps version output bare and appends a short root overview. Hidden debug settings use `Flag.withHidden`; the diagnostic group uses `Command.unlisted` (the pinned framework's hidden-command API). `commands/argv-compat.ts` preserves optional `listen --stream` values and inserts the native `--` boundary for legacy undelimited `run` script arguments. Effect parses the script tail through `Argument.variadic`; never strip its flags. `setup skill` installs agent skills; `--dangerously-allow` is local to `dev triggers disable`.
151 -- Environment: `src/config/` declares every variable the CLI reads under its full name, grouped into `APP_CONFIG` (user-facing `COMPOSIO_*`, see the README), `DEBUG_CONFIG`, `TELEMETRY_CONFIG`, `HOST_CONFIG` (shell, CI, agent host), and `GITHUB_CONFIG`. Values flow through the ambient `ConfigProvider` (the process environment by default; tests provide `ConfigProvider.fromEnvRecord`). Read a variable through its catalog, never with an inline `Config.String('COMPOSIO_…')`.
151 +- Environment: `src/config/` declares every variable the CLI reads under its full name, grouped into `APP_CONFIG` (user-facing `COMPOSIO_*`, see the README), `DEBUG_CONFIG`, `TELEMETRY_CONFIG`, `HOST_CONFIG` (shell, CI, agent host), and `GITHUB_CONFIG`. Values flow through the ambient `ConfigProvider` (the process environment by default; tests provide `ConfigProvider.fromEnvRecord`). Read a variable through its catalog, never with an inline `Config.String('COMPOSIO_…')`. The backend URLs follow one rule, `resolveBackend` (`src/config/backend.ts`): `COMPOSIO_BASE_URL` or `COMPOSIO_ENVIRONMENT` when set, else the backend the stored login recorded, else production. Read them from `ComposioUserContext` (`ctx.data.baseURL`, `ctx.data.webURL`), not from `APP_CONFIG.BASE_URL`/`WEB_URL`, which hold only the env-selected values; only `ctx.login` records a login's backend.
152 - User config: `~/.composio/user-config.json`
153 - Cache files: `toolkits.json`, `tools.json`, `tools-as-enums.json`, `trigger-types.json`
154
ts/packages/cli/CHANGELOG.md
+15
@@ -37,6 +37,21 @@
37 - `composio dev triggers create` without a `<trigger-name>`, or with
38 `--trigger-config` that is not a JSON object
39 - `composio dev triggers enable` without an `<id>`
40 +- The CLI now calls the backend you logged in to. `composio login` already
41 + recorded it as `base_url` in `user_data.json`, but every command replaced it
42 + with the production default unless `COMPOSIO_BASE_URL` or
43 + `COMPOSIO_ENVIRONMENT` was set, so a staging login sent its key to production
44 + and failed with `Invalid or revoked user API key`. Those variables still win
45 + when set, and the CLI warns on stderr when one sends the stored key to a
46 + different backend than the one that issued it. A key from
47 + `COMPOSIO_USER_API_KEY` keeps using the backend the environment selects.
48 + `composio execute` follows the same rule for the Dashboard it calls, using
49 + the recorded `web_url`. `composio orgs switch` no longer rewrites the
50 + recorded backend, and a key from `COMPOSIO_USER_API_KEY` is no longer written
51 + to `user_data.json`. `composio login --agent` records the backend the
52 + environment selects, since agents.composio.dev issued its key. A rejected
53 + user API key now prints how to log in again, naming the backend and
54 + Dashboard when they are not production's.
55 - `composio link` and `composio dev connected-accounts link` reword their usage
56 and status messages on stderr: the rejected `--auth-config` on the root
57 command, a toolkit passed together with `--auth-config`, a missing toolkit,
ts/packages/cli/README.md
+4 -2
@@ -61,8 +61,8 @@ By default, both files are stored in `~/.composio`, but you can specify a custom
61 | ---------------------------------------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------ |
62 | COMPOSIO_USER_API_KEY | `user_data.json`: `api_key` | Composio user API key | None |
63 | COMPOSIO_ENVIRONMENT | - | Selects the production or staging URL defaults | production |
64 -| COMPOSIO_BASE_URL | `user_data.json`: `base_url` | The base URL of the Composio backend API | https://backend.composio.dev |
65 -| COMPOSIO_WEB_URL | `user_data.json`: `web_url` | The base URL of the Composio web app | https://dashboard.composio.dev/ |
64 +| COMPOSIO_BASE_URL | `user_data.json`: `base_url` | The base URL of the Composio backend API (see below) | https://backend.composio.dev |
65 +| COMPOSIO_WEB_URL | `user_data.json`: `web_url` | The base URL of the Composio web app (see below) | https://dashboard.composio.dev/ |
66 | COMPOSIO_CACHE_DIR | - | The directory where the Composio CLI stores cache files | ~/.composio |
67 | COMPOSIO_SESSION_DIR | `config.json`: `artifact_directory` | The root directory for CLI session artifacts | `COMPOSIO_CACHE_DIR`, then `artifact_directory`, then `$TMPDIR/composio` |
68 | COMPOSIO_BIN_DIR | - | The directory `composio install` adds to `PATH` (see below) | Resolved from the running binary |
@@ -79,6 +79,8 @@ By default, both files are stored in `~/.composio`, but you can specify a custom
79 | FORCE_USE_CACHE | - | Whether to force the use of previously cached HTTP responses | None |
80 | NO_COLOR | - | If set, disables color output in the CLI (https://no-color.org/) | None |
81
82 +`composio login` records the backend it logged in to as `base_url` and `web_url` in `user_data.json`, and later commands keep using it. Setting `COMPOSIO_BASE_URL` or `COMPOSIO_ENVIRONMENT` overrides it; when that sends the stored API key to a different backend, the CLI prints a warning on stderr. A key from `COMPOSIO_USER_API_KEY` always uses the backend the environment selects. `composio logout` forgets the recorded backend.
83 +
84 The CLI and its installer use these variables to coordinate nested commands. They aren't intended for manual configuration.
85
86 | Environment Variable | Description | Default |
ts/packages/cli/src/analytics/dispatch.ts
+31 -5
@@ -1,11 +1,22 @@
1 import { cliRequestHeaders } from 'src/services/client-provenance';
2 import process from 'node:process';
3 import type { PlatformError } from 'effect/PlatformError';
4 -import { Cause, Clock, DateTime, Effect, FileSystem, Option, Path, Predicate } from 'effect';
4 +import {
5 + Cause,
6 + Clock,
7 + DateTime,
8 + Effect,
9 + FileSystem,
10 + Option,
11 + Path,
12 + Predicate,
13 + Schema,
14 +} from 'effect';
15 import { Base64Url } from 'effect/encoding';
16 import { HttpClient, HttpClientRequest } from 'effect/http';
17 import * as constants from 'src/constants';
18 import { APP_CONFIG, TELEMETRY_CONFIG } from 'src/config';
19 +import { resolveBackend, withoutTrailingSlashes } from 'src/config/backend';
20 import { getDetachedWorkerSpawnArgs, spawnDetached } from 'src/services/detached-process';
21 import { atomicWriteFileString } from 'src/utils/atomic-write';
22 import { sha256Hex } from 'src/utils/checksums';
@@ -469,12 +480,27 @@ const withCliSessionId = (event: NonNullable<TrackEvent>, cliSessionId?: string)
480 },
481 });
482
472 -// The same URL the CLI itself talks to: `COMPOSIO_BASE_URL`, else the `COMPOSIO_ENVIRONMENT`
473 -// default. The persisted login URL is not consulted, matching `ComposioUserContext`.
474 -export const readApiBaseUrl = Effect.orDie(APP_CONFIG.BASE_URL).pipe(
475 - Effect.map(url => url.replace(/\/+$/u, ''))
483 +// A stored login in user_data.json: its key and the backend that issued it. The keychain
484 +// modes keep the key out of the file, and then this reports no key to send either.
485 +const decodeStoredLogin = Schema.decodeUnknownOption(
486 + Schema.Struct({ api_key: Schema.NonEmptyString, base_url: Schema.NonEmptyString })
487 );
488
489 +// The same URL the CLI itself talks to, resolved like `ComposioUserContext` does: an env var
490 +// that selects a backend, else the stored login's backend, else production.
491 +export const readApiBaseUrl = Effect.gen(function* () {
492 + const env = yield* Effect.orDie(APP_CONFIG.BACKEND);
493 + const envApiKey = yield* Effect.orDie(APP_CONFIG.USER_API_KEY);
494 + const stored =
495 + envApiKey === undefined
496 + ? Option.map(decodeStoredLogin(yield* readUserConfig), login => ({
497 + baseURL: login.base_url,
498 + webURL: Option.none<string>(),
499 + }))
500 + : Option.none();
501 + return withoutTrailingSlashes(resolveBackend(env, stored).baseURL);
502 +});
503 +
504 const getCliCodactFailuresEndpoint = Effect.map(
505 readApiBaseUrl,
506 baseUrl => `${baseUrl}${CLI_CODACT_FAILURES_PATH}`
ts/packages/cli/src/cli-main.ts
+50 -3
@@ -4,7 +4,17 @@
4 * and the exit code. runWithConfig accepts full argv and removes the executable prefix.
5 */
6 import process from 'node:process';
7 -import { Cause, ConfigProvider, Effect, Exit, Layer, Logger, Predicate, Runtime } from 'effect';
7 +import {
8 + Cause,
9 + ConfigProvider,
10 + Effect,
11 + Exit,
12 + Layer,
13 + Logger,
14 + Option,
15 + Predicate,
16 + Runtime,
17 +} from 'effect';
18 import { captureErrors, prettyPrintFromCapturedErrors } from 'effect-errors/index';
19 import { CliConfig, CliError } from 'effect/cli';
20 import { FetchHttpClient } from 'effect/http';
@@ -26,7 +36,13 @@ import { NodeOs } from 'src/services/node-os';
36 import { NodeProcess } from 'src/services/node-process';
37 import { JsPackageManagerDetector } from 'src/services/js-package-manager-detector';
38 import { ComposioCliUserConfigLive } from 'src/services/cli-user-config';
29 -import { ComposioUserContextLive as _ComposioUserContextLive } from 'src/services/user-context';
39 +import {
40 + ComposioUserContext,
41 + ComposioUserContextLive as _ComposioUserContextLive,
42 +} from 'src/services/user-context';
43 +import { formatBackendMismatch } from 'src/config/backend';
44 +import { isRejectedUserApiKey, rejectedUserApiKeyHint } from 'src/effects/rejected-user-api-key';
45 +import { extractMessage } from 'src/utils/api-error-extraction';
46 import { UpgradeBinary } from 'src/services/upgrade-binary';
47 import { TerminalUI, TerminalUILive } from 'src/services/terminal-ui';
48 import { TriggersRealtime } from 'src/services/triggers-realtime';
@@ -258,8 +274,29 @@ export type CliBootstrapOptions = {
274 readonly argv: ReadonlyArray<string>;
275 };
276
277 +/** Writes `message` to stderr: as a decorated warning on a terminal, as plain text otherwise. */
278 +const warn = (message: string) =>
279 + Effect.gen(function* () {
280 + const ui = yield* TerminalUI;
281 + if ((yield* ui.capabilities).canDecorate) {
282 + yield* ui.log.warn(message);
283 + } else {
284 + yield* ui.error(`Warning: ${message}`);
285 + }
286 + });
287 +
288 +/** Warns, before any request, when an env var sends the stored key to another backend. */
289 +const warnOnBackendMismatch = Effect.gen(function* () {
290 + const ctx = yield* ComposioUserContext;
291 + yield* Option.match(ctx.backendMismatch, {
292 + onNone: () => Effect.void,
293 + onSome: mismatch => warn(formatBackendMismatch(mismatch)),
294 + });
295 +});
296 +
297 const cliProgram = (argv: ReadonlyArray<string>) =>
262 - showUpdateNotice.pipe(
298 + warnOnBackendMismatch.pipe(
299 + Effect.andThen(showUpdateNotice),
300 Effect.andThen(showPluginAcquisitionHint(argv)),
301 Effect.andThen(runWithTelemetry(argv)),
302 Effect.catchIf(
@@ -292,6 +329,16 @@ const cliProgram = (argv: ReadonlyArray<string>) =>
329 process.exitCode = 1;
330 })
331 ),
332 + // A rejected user API key gets the backend's message and the way to log in again, from
333 + // whichever command it escaped.
334 + Effect.catchIf(isRejectedUserApiKey, error =>
335 + Effect.gen(function* () {
336 + const ui = yield* TerminalUI;
337 + yield* ui.error(extractMessage(error) ?? 'The user API key was rejected.');
338 + yield* ui.error(yield* rejectedUserApiKeyHint);
339 + process.exitCode = 1;
340 + })
341 + ),
342 Effect.catchIf(
343 (error): error is ShellSetupAbortError => error instanceof ShellSetupAbortError,
344 // `composio install` already printed the abort reason; the typed failure
ts/packages/cli/src/commands/orgs/switch/orgs.switch.handler.ts
+2 -1
@@ -45,7 +45,8 @@ export const runOrgsSwitch = ({ orgId, limit }: OrgsSwitchParams) =>
45 onNone: () => ui.outro(NO_ORG_SELECTED_OUTRO),
46 onSome: org =>
47 Effect.gen(function* () {
48 - yield* ctx.login(apiKey, org.id, Option.getOrUndefined(ctx.data.testUserId));
48 + // Same key, new org: the login's recorded backend stays as it is.
49 + yield* ctx.update({ orgId: Option.some(org.id) });
50 yield* linkAnalyticsIdentityForOrg({ apiKey, orgId: org.id });
51
52 yield* ui.log.success(updatedOrgMessage(org.name));
ts/packages/cli/src/config/app.ts
+39 -8
@@ -1,5 +1,6 @@
1 -import { Config, Schema } from 'effect';
1 +import { Config, Option, Schema } from 'effect';
2 import * as constants from 'src/constants';
3 +import type { EnvBackend } from './backend';
4 import { flag, optionalLogLevel, optionalString } from './env';
5
6 const ENVIRONMENT = optionalString('COMPOSIO_ENVIRONMENT');
@@ -13,12 +14,39 @@ const url = (name: string, prodDefault: string, stagingDefault: string) =>
14 )
15 );
16
17 +const BASE_URL = url('COMPOSIO_BASE_URL', constants.DEFAULT_BASE_URL, constants.STAGING_BASE_URL);
18 +const WEB_URL = url('COMPOSIO_WEB_URL', constants.DEFAULT_WEB_URL, constants.STAGING_WEB_URL);
19 +
20 +const BACKEND: Config.Config<EnvBackend> = Config.all({
21 + baseURL: BASE_URL,
22 + webURL: WEB_URL,
23 + explicitBaseURL: optionalString('COMPOSIO_BASE_URL'),
24 + explicitWebURL: optionalString('COMPOSIO_WEB_URL'),
25 + environment: ENVIRONMENT,
26 +}).pipe(
27 + Config.map(({ baseURL, webURL, explicitBaseURL, explicitWebURL, environment }) => ({
28 + baseURL,
29 + webURL,
30 + selectedBy:
31 + explicitBaseURL !== undefined
32 + ? Option.some('COMPOSIO_BASE_URL' as const)
33 + : environment !== undefined
34 + ? Option.some('COMPOSIO_ENVIRONMENT' as const)
35 + : Option.none(),
36 + webURLSet: explicitWebURL !== undefined,
37 + }))
38 +);
39 +
40 /**
41 * The `COMPOSIO_*` variables users set to configure the CLI, documented in the README.
42 *
19 - * URL precedence (highest → lowest):
20 - * COMPOSIO_BASE_URL → COMPOSIO_ENVIRONMENT-derived → DEFAULT_BASE_URL
21 - * COMPOSIO_WEB_URL → COMPOSIO_ENVIRONMENT-derived → DEFAULT_WEB_URL
43 + * URL precedence (highest → lowest), applied by `resolveBackend` in `./backend.ts`:
44 + * COMPOSIO_BASE_URL → COMPOSIO_ENVIRONMENT-derived → stored login's `base_url` → DEFAULT_BASE_URL
45 + * COMPOSIO_WEB_URL → COMPOSIO_ENVIRONMENT-derived → stored login's `web_url` → DEFAULT_WEB_URL
46 + *
47 + * The stored login's URLs are the backend `composio login` recorded. They apply only while
48 + * neither COMPOSIO_BASE_URL nor COMPOSIO_ENVIRONMENT is set, and only to the stored key: a key
49 + * from COMPOSIO_USER_API_KEY uses the env-selected URLs.
50 */
51 export const APP_CONFIG = {
52 // The API key for the Composio API
@@ -27,11 +55,14 @@ export const APP_CONFIG = {
55 // The deployment environment ("production" | "staging"). Controls URL defaults.
56 ENVIRONMENT,
57
30 - // The base URL for the Composio API
31 - BASE_URL: url('COMPOSIO_BASE_URL', constants.DEFAULT_BASE_URL, constants.STAGING_BASE_URL),
58 + // The base URL for the Composio API the environment selects, before a stored login applies
59 + BASE_URL,
60 +
61 + // The base URL for the Composio web app the environment selects, before a stored login applies
62 + WEB_URL,
63
33 - // The base URL for the Composio web app
34 - WEB_URL: url('COMPOSIO_WEB_URL', constants.DEFAULT_WEB_URL, constants.STAGING_WEB_URL),
64 + // Both URLs above, with which variables set them; `resolveBackend` takes it
65 + BACKEND,
66
67 // The cache directory for the Composio CLI
68 CACHE_DIR: optionalString('COMPOSIO_CACHE_DIR'),
ts/packages/cli/src/config/backend.ts new
+74
@@ -0,0 +1,74 @@
1 +import { Option } from 'effect';
2 +
3 +/** The environment variable that chose the backend, when one did. */
4 +export type BackendVariable = 'COMPOSIO_BASE_URL' | 'COMPOSIO_ENVIRONMENT';
5 +
6 +/** The backend the environment selects (`APP_CONFIG.BACKEND`). */
7 +export interface EnvBackend {
8 + /** `COMPOSIO_BASE_URL`, else the `COMPOSIO_ENVIRONMENT` default, else production. */
9 + readonly baseURL: string;
10 + /** `COMPOSIO_WEB_URL`, else the `COMPOSIO_ENVIRONMENT` default, else production. */
11 + readonly webURL: string;
12 + /** `COMPOSIO_BASE_URL` when set, else `COMPOSIO_ENVIRONMENT` when set. */
13 + readonly selectedBy: Option.Option<BackendVariable>;
14 + /** Whether `COMPOSIO_WEB_URL` is set. */
15 + readonly webURLSet: boolean;
16 +}
17 +
18 +/** The backend a stored login was issued by, as `composio login` recorded it. */
19 +export interface StoredBackend {
20 + readonly baseURL: string;
21 + readonly webURL: Option.Option<string>;
22 +}
23 +
24 +export interface Backend {
25 + readonly baseURL: string;
26 + readonly webURL: string;
27 +}
28 +
29 +/**
30 + * The backend the CLI talks to. An env var that selects a backend wins; otherwise a stored
31 + * login keeps using the backend that issued its key, so a staging login keeps calling staging
32 + * after `COMPOSIO_ENVIRONMENT` is unset. Pass `Option.none()` as `stored` for a key that is not
33 + * the stored login's (`COMPOSIO_USER_API_KEY`) or when nobody is logged in.
34 + */
35 +export const resolveBackend = (env: EnvBackend, stored: Option.Option<StoredBackend>): Backend => {
36 + const login = Option.isSome(env.selectedBy) ? Option.none<StoredBackend>() : stored;
37 + return {
38 + baseURL: Option.match(login, { onNone: () => env.baseURL, onSome: s => s.baseURL }),
39 + webURL: env.webURLSet
40 + ? env.webURL
41 + : Option.flatMap(login, s => s.webURL).pipe(Option.getOrElse(() => env.webURL)),
42 + };
43 +};
44 +
45 +export interface BackendMismatch {
46 + readonly variable: BackendVariable;
47 + /** The backend that issued the stored key. */
48 + readonly issuedBy: string;
49 + /** The backend the env var sends it to instead. */
50 + readonly selected: string;
51 +}
52 +
53 +export const withoutTrailingSlashes = (url: string) => url.replace(/\/+$/u, '');
54 +
55 +/** Set when an env var sends the stored login's key to a backend other than its issuer. */
56 +export const backendMismatch = (
57 + env: EnvBackend,
58 + stored: Option.Option<StoredBackend>
59 +): Option.Option<BackendMismatch> =>
60 + Option.flatMap(stored, login =>
61 + Option.flatMap(env.selectedBy, variable =>
62 + withoutTrailingSlashes(login.baseURL) === withoutTrailingSlashes(env.baseURL)
63 + ? Option.none()
64 + : Option.some({
65 + variable,
66 + issuedBy: withoutTrailingSlashes(login.baseURL),
67 + selected: withoutTrailingSlashes(env.baseURL),
68 + })
69 + )
70 + );
71 +
72 +export const formatBackendMismatch = (mismatch: BackendMismatch) =>
73 + `${mismatch.variable} sends your stored API key to ${mismatch.selected}, but it was issued by ${mismatch.issuedBy}. ` +
74 + `Unset ${mismatch.variable} to use the backend you logged in to, or run \`composio logout && composio login\` to log in to ${mismatch.selected} instead.`;
ts/packages/cli/src/effects/handle-http-error.ts
+8 -5
@@ -4,6 +4,7 @@ import type { ClientApiError } from 'src/services/composio-errors';
4 import { NodeProcess } from 'src/services/node-process';
5 import type { TerminalUI } from 'src/services/terminal-ui';
6 import { describeDecodeError, isClientDecodeError } from 'src/utils/api-error-extraction';
7 +import { isRejectedUserApiKey, rejectedUserApiKeyHint } from 'src/effects/rejected-user-api-key';
8
9 export interface Suggestion {
10 readonly label: string;
@@ -26,12 +27,14 @@ interface ErrorReport {
27 readonly hint?: string;
28 }
29
29 -const reportOf = (e: ClientApiError): ErrorReport => {
30 - if (isClientDecodeError(e)) return describeDecodeError(e);
30 +const reportOf = (e: ClientApiError): Effect.Effect<ErrorReport> => {
31 + if (isClientDecodeError(e)) return Effect.succeed(describeDecodeError(e));
32 if (isAPIError(e)) {
32 - return { message: e.details?.message, suggestedFix: e.details?.suggested_fix };
33 + return isRejectedUserApiKey(e)
34 + ? Effect.map(rejectedUserApiKeyHint, hint => ({ message: e.details?.message, hint }))
35 + : Effect.succeed({ message: e.details?.message, suggestedFix: e.details?.suggested_fix });
36 }
34 - return {};
37 + return Effect.succeed({});
38 };
39
40 /**
@@ -77,7 +80,7 @@ export const handleClientApiError =
80 const proc = yield* NodeProcess;
81 yield* proc.setExitCode(1);
82
80 - const report = reportOf(e);
83 + const report = yield* reportOf(e);
84 const message = report.message ?? opts.fallbackMessage;
85 const hint = report.hint ?? opts.hint;
86
ts/packages/cli/src/effects/rejected-user-api-key.ts new
+55
@@ -0,0 +1,55 @@
1 +import { Effect, Option } from 'effect';
2 +import { APP_CONFIG } from 'src/config';
3 +import { withoutTrailingSlashes } from 'src/config/backend';
4 +import * as constants from 'src/constants';
5 +import { ComposioUserContext } from 'src/services/user-context';
6 +import { findApiError } from 'src/utils/api-error-extraction';
7 +
8 +/** Whether `value` (or a failure it wraps) is the backend rejecting the user API key. */
9 +export const isRejectedUserApiKey = (value: unknown): boolean =>
10 + findApiError(value)?.details?.slug === 'UserApiKey_Unauthorized';
11 +
12 +/**
13 + * The env vars that make `composio login` target the backend at `baseURL` and its Dashboard at
14 + * `webURL`, as a command prefix. `COMPOSIO_WEB_URL` is named only when `webURL` is not the
15 + * Dashboard the other variables already select, so the new login session opens where it can
16 + * be completed.
17 + */
18 +/** `value` as one shell word: unchanged when it is plainly safe, else single-quoted. */
19 +const shellWord = (value: string) =>
20 + /^[\w@%+=:,./-]+$/u.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
21 +
22 +const loginTargetPrefix = (baseURL: string, webURL: string) => {
23 + const base = withoutTrailingSlashes(baseURL);
24 + const [backendVar, impliedWebURL] =
25 + base === withoutTrailingSlashes(constants.DEFAULT_BASE_URL)
26 + ? ['', constants.DEFAULT_WEB_URL]
27 + : base === withoutTrailingSlashes(constants.STAGING_BASE_URL)
28 + ? ['COMPOSIO_ENVIRONMENT=staging ', constants.STAGING_WEB_URL]
29 + : [`COMPOSIO_BASE_URL=${shellWord(base)} `, constants.DEFAULT_WEB_URL];
30 + const web = withoutTrailingSlashes(webURL);
31 + const webVar =
32 + web === withoutTrailingSlashes(impliedWebURL) ? '' : `COMPOSIO_WEB_URL=${shellWord(web)} `;
33 + return `${backendVar}${webVar}`;
34 +};
35 +
36 +/**
37 + * How to recover from a rejected user API key. `composio logout` forgets the stored login's
38 + * backend, so the login command names the backend that rejected the key, and its Dashboard,
39 + * when they are not production's. Reads the user context when the caller has one, without requiring it.
40 + */
41 +export const rejectedUserApiKeyHint = Effect.gen(function* () {
42 + const keyFromEnv = yield* APP_CONFIG.USER_API_KEY.pipe(
43 + Effect.map(key => key !== undefined),
44 + Effect.orElseSucceed(() => false)
45 + );
46 + if (keyFromEnv) {
47 + return 'Replace the key in COMPOSIO_USER_API_KEY, then retry.';
48 + }
49 + const ctx = yield* Effect.serviceOption(ComposioUserContext);
50 + const prefix = Option.match(ctx, {
51 + onNone: () => '',
52 + onSome: c => loginTargetPrefix(c.data.baseURL, c.data.webURL),
53 + });
54 + return `Log in again, then retry:\n> composio logout && ${prefix}composio login`;
55 +});
ts/packages/cli/src/services/agents.ts
+2 -1
@@ -476,7 +476,8 @@ export const loginWithAgentIdentity = (identity: AgentIdentity) =>
476 });
477 }
478
479 - yield* ctx.login(userApiKey, orgId);
479 + // agents.composio.dev issued this key, not whichever backend an earlier login recorded.
480 + yield* ctx.login(userApiKey, orgId, undefined, { issuer: 'environment' });
481 // Best-effort analytics stitch after the credential persists; must never break login.
482 yield* getSessionInfoByUserApiKey({ userApiKey, orgId }).pipe(
483 Effect.flatMap(info => linkApolloIdentityForAnalytics(info.org_member.id, userApiKey)),
ts/packages/cli/src/services/user-context.ts
+78 -43
@@ -11,6 +11,12 @@ import { JsonRecordSchema } from 'src/effects/json';
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';
@@ -148,28 +154,43 @@ const deleteKeyring = (deps: KeyringDeps) =>
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
@@ -180,26 +201,44 @@ export const rawComposioUserContextLive = Layer.effect(
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,
@@ -210,10 +249,11 @@ export const rawComposioUserContextLive = Layer.effect(
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(),
@@ -222,46 +262,38 @@ export const rawComposioUserContextLive = Layer.effect(
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));
@@ -273,20 +305,19 @@ export const rawComposioUserContextLive = Layer.effect(
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;
@@ -317,6 +348,7 @@ export const rawComposioUserContextLive = Layer.effect(
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');
@@ -325,6 +357,7 @@ export const rawComposioUserContextLive = Layer.effect(
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);
@@ -336,8 +369,7 @@ export const rawComposioUserContextLive = Layer.effect(
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,
@@ -347,6 +379,9 @@ export const rawComposioUserContextLive = Layer.effect(
379 get data() {
380 return snapshot();
381 },
382 + get backendMismatch() {
383 + return backendMismatch(envBackend, storedLogin());
384 + },
385 isLoggedIn,
386 update,
387 login,
ts/packages/cli/test/__fixtures__/user-config-staging-login/.composio/user_data.json new
+6
@@ -0,0 +1,6 @@
1 +{
2 + "api_key": "uak_staging_login",
3 + "base_url": "https://staging-backend.composio.dev",
4 + "web_url": "https://staging-dashboard.composio.dev/",
5 + "org_id": "org_1"
6 +}
ts/packages/cli/test/__utils__/layers/agents.ts
+1
@@ -83,6 +83,7 @@ export const AgentHandlerTest = (fixture: AgentHandlerFixture = {}) => {
83 projectId: Option.none(),
84 testUserId: Option.none(),
85 },
86 + backendMismatch: Option.none(),
87 isLoggedIn: () => Option.isSome(apiKey),
88 logout: Effect.void,
89 login: (loginApiKey, orgId) =>
ts/packages/cli/test/src/analytics.dispatch.test.ts
+20
@@ -165,6 +165,26 @@ describe('CLI analytics dispatch', () => {
165 }
166 );
167
168 + it.effect('sends failures to the backend the stored login was issued by', () => {
169 + const home = tempy.temporaryDirectory();
170 + const cacheDir = tempy.temporaryDirectory();
171 + vi.stubEnv('COMPOSIO_CACHE_DIR', cacheDir);
172 + // Blank reads as unset, whatever the host environment holds.
173 + vi.stubEnv('COMPOSIO_BASE_URL', '');
174 + vi.stubEnv('COMPOSIO_ENVIRONMENT', '');
175 + vi.stubEnv('COMPOSIO_USER_API_KEY', '');
176 + writeFileSync(
177 + path.join(cacheDir, USER_CONFIG_FILE_NAME),
178 + JSON.stringify({ api_key: 'uak_staging', base_url: 'https://staging-backend.composio.dev/' })
179 + );
180 +
181 + return Effect.gen(function* () {
182 + expect(yield* readApiBaseUrl).toBe('https://staging-backend.composio.dev');
183 + vi.stubEnv('COMPOSIO_ENVIRONMENT', 'production');
184 + expect(yield* readApiBaseUrl).toBe('https://backend.composio.dev');
185 + }).pipe(Effect.provide(makePlatformLayer(home)));
186 + });
187 +
188 it.effect('ignores malformed worker payloads', () => {
189 const home = tempy.temporaryDirectory();
190
ts/packages/cli/test/src/cli-main.test.ts
+98 -1
@@ -1,8 +1,9 @@
1 import fs from 'node:fs';
2 import path from 'node:path';
3 -import { spawnSync } from 'node:child_process';
3 +import { spawn, spawnSync } from 'node:child_process';
4 import { describe, expect, it } from 'vitest';
5 import * as tempy from 'tempy';
6 +import { withHttpServer } from 'test/__utils__/http-server';
7
8 describe('CLI process error handling', () => {
9 it.each([
@@ -191,3 +192,99 @@ describe('CLI process error handling', () => {
192 expect(`${result.stdout}\n${result.stderr}`).toContain('posthog_delivery_skipped');
193 });
194 });
195 +
196 +describe('CLI backend of a stored login', () => {
197 + const STAGING_BASE_URL = 'https://staging-backend.composio.dev';
198 +
199 + /** A cache dir holding a stored login issued by `baseURL`. */
200 + const storedLogin = (baseURL: string) => {
201 + const configDirectory = tempy.temporaryDirectory();
202 + fs.writeFileSync(
203 + path.join(configDirectory, 'user_data.json'),
204 + JSON.stringify({ api_key: 'uak_stored', base_url: baseURL, web_url: null, org_id: 'org_1' })
205 + );
206 + return configDirectory;
207 + };
208 +
209 + /** The environment of a spawned CLI: no backend variables from the host, telemetry off. */
210 + const cliEnv = (configDirectory: string, extra: Record<string, string> = {}) => {
211 + const {
212 + COMPOSIO_BASE_URL: _baseURL,
213 + COMPOSIO_WEB_URL: _webURL,
214 + COMPOSIO_ENVIRONMENT: _environment,
215 + COMPOSIO_USER_API_KEY: _apiKey,
216 + ...host
217 + } = process.env;
218 + return {
219 + ...host,
220 + CI: '1',
221 + NO_COLOR: '1',
222 + HOME: configDirectory,
223 + COMPOSIO_CACHE_DIR: configDirectory,
224 + COMPOSIO_CLI_TELEMETRY_DISABLED: '1',
225 + ...extra,
226 + };
227 + };
228 +
229 + it('warns on stderr only when an env var sends the stored key to another backend', () => {
230 + const configDirectory = storedLogin(STAGING_BASE_URL);
231 +
232 + const result = spawnSync('bun', ['run', 'src/bin.ts', '--version'], {
233 + cwd: process.cwd(),
234 + encoding: 'utf8',
235 + env: cliEnv(configDirectory, { COMPOSIO_BASE_URL: 'http://127.0.0.1:9' }),
236 + });
237 +
238 + expect(result.status).toBe(0);
239 + const warning =
240 + 'COMPOSIO_BASE_URL sends your stored API key to http://127.0.0.1:9, but it was issued by https://staging-backend.composio.dev.';
241 + expect(result.stderr.split(warning)).toHaveLength(2);
242 + expect(result.stdout).not.toContain('COMPOSIO_BASE_URL');
243 +
244 + const unset = spawnSync('bun', ['run', 'src/bin.ts', '--version'], {
245 + cwd: process.cwd(),
246 + encoding: 'utf8',
247 + env: cliEnv(configDirectory),
248 + });
249 + expect(unset.stderr).not.toContain('sends your stored API key');
250 + });
251 +
252 + it('sends requests to the stored backend and explains a rejected key', async () => {
253 + const requests: Array<{ url?: string; key?: string | string[] }> = [];
254 + await withHttpServer(
255 + (req, res) => {
256 + requests.push({ url: req.url, key: req.headers['x-user-api-key'] });
257 + res.writeHead(401, { 'content-type': 'application/json' });
258 + res.end(
259 + JSON.stringify({
260 + error: {
261 + message: 'Invalid or revoked user API key',
262 + code: 1803,
263 + slug: 'UserApiKey_Unauthorized',
264 + status: 401,
265 + },
266 + })
267 + );
268 + },
269 + async baseURL => {
270 + const configDirectory = storedLogin(baseURL);
271 + const child = spawn('bun', ['run', 'src/bin.ts', 'orgs', 'list'], {
272 + cwd: process.cwd(),
273 + env: cliEnv(configDirectory),
274 + });
275 + let stdout = '';
276 + let stderr = '';
277 + child.stdout.on('data', chunk => (stdout += String(chunk)));
278 + child.stderr.on('data', chunk => (stderr += String(chunk)));
279 + const status = await new Promise<number | null>(resolve => child.on('close', resolve));
280 +
281 + expect(requests.length).toBeGreaterThan(0);
282 + expect(requests[0]?.key).toBe('uak_stored');
283 + expect(status).toBe(1);
284 + expect(stdout).toBe('');
285 + expect(stderr).toContain('Invalid or revoked user API key');
286 + expect(stderr).toContain(`composio logout && COMPOSIO_BASE_URL=${baseURL} composio login`);
287 + }
288 + );
289 + });
290 +});
ts/packages/cli/test/src/commands/connected-accounts/link/connected-accounts.link.handler.test.ts
+1
@@ -238,6 +238,7 @@ const linkHandlerTest = (fixture: LinkFixture = {}) => {
238 projectId: Option.none(),
239 testUserId: fixture.globalTestUserId ?? Option.none(),
240 },
241 + backendMismatch: Option.none(),
242 isLoggedIn: () => true,
243 logout: Effect.void,
244 login: () => Effect.void,
ts/packages/cli/test/src/commands/connected-accounts/list/connected-accounts.list.handler.test.ts
+1
@@ -134,6 +134,7 @@ const listTest = (fixture: ListFixture = {}) => {
134 projectId: Option.none(),
135 testUserId: Option.none(),
136 },
137 + backendMismatch: Option.none(),
138 isLoggedIn: () => true,
139 logout: Effect.void,
140 login: () => Effect.void,
ts/packages/cli/test/src/commands/login/login.handler.test.ts
+1
@@ -195,6 +195,7 @@ const loginHandlerTest = (fixture: LoginFixture = {}) => {
195 projectId: Option.none(),
196 testUserId: Option.none(),
197 },
198 + backendMismatch: Option.none(),
199 isLoggedIn: () => Option.isSome(apiKey),
200 logout: Effect.void,
201 login: (loginApiKey, orgId, testUserId) =>
ts/packages/cli/test/src/commands/orgs/list/orgs.list.handler.test.ts
+1
@@ -76,6 +76,7 @@ const orgsListTest = (fixture: OrgsListFixture = {}) => {
76 projectId: Option.none(),
77 testUserId: Option.none(),
78 },
79 + backendMismatch: Option.none(),
80 isLoggedIn: () => Option.isSome(apiKey),
81 logout: Effect.void,
82 login: () => Effect.void,
ts/packages/cli/test/src/commands/orgs/switch/orgs.switch.cmd.test.ts
+26
@@ -169,4 +169,30 @@ describe('CLI: composio orgs switch', () => {
169 );
170 }
171 );
172 +
173 + layer(
174 + TestLive({
175 + fixture: 'user-config-staging-login',
176 + baseConfigProvider: ConfigProvider.fromEnvRecord({
177 + COMPOSIO_BASE_URL: 'https://backend.composio.dev',
178 + }),
179 + accountData: {
180 + sessionInfo: () =>
181 + makeSessionInfo({ orgId: 'org_2', orgName: 'Org 2', orgMemberId: 'member_2' }),
182 + },
183 + })
184 + )('[Given] a staging login and COMPOSIO_BASE_URL pointing elsewhere', it => {
185 + it.effect('[Then] it switches the org and keeps the backend the login was issued by', () =>
186 + Effect.gen(function* () {
187 + yield* cli(['orgs', 'switch', '--org-id', 'org_2']);
188 +
189 + expect(yield* readStoredUserConfig).toMatchObject({
190 + api_key: 'uak_staging_login',
191 + org_id: 'org_2',
192 + base_url: 'https://staging-backend.composio.dev',
193 + web_url: 'https://staging-dashboard.composio.dev/',
194 + });
195 + })
196 + );
197 + });
198 });
ts/packages/cli/test/src/commands/orgs/switch/orgs.switch.handler.test.ts
+21 -18
@@ -11,6 +11,7 @@ import { ComposioClientSingleton } from 'src/services/composio-clients';
11 import { NodeOs } from 'src/services/node-os';
12 import { TerminalUI } from 'src/services/terminal-ui';
13 import { ComposioUserContext } from 'src/services/user-context';
14 +import type { UserData } from 'src/models/user-data';
15 import { MockConsole } from 'test/__utils__';
16 import type { MockAccountRequest, MockRequestScope } from 'test/__utils__/layers/accounts';
17 import { makeShadowClient } from 'test/__utils__/layers/shadow-client';
@@ -43,8 +44,6 @@ const ORGANIZATIONS: ReadonlyArray<OrganizationSummary> = [
44 { id: 'org_third', name: 'Third Org' },
45 ];
46
46 -type LoginCall = readonly [apiKey: string, orgId?: string, testUserId?: string];
47 -
47 interface OrgsSwitchFixture {
48 readonly apiKey?: Option.Option<string>;
49 readonly orgId?: Option.Option<string>;
@@ -55,13 +54,14 @@ interface OrgsSwitchFixture {
54 }
55
56 /**
58 - * What `runOrgsSwitch` reads: a user context whose `login` calls land in `logins`, the account
57 + * What `runOrgsSwitch` reads: a user context whose org updates land in `orgUpdates` (switching
58 + * must not log in again, so `login` fails the test), the account
59 * family of the mock client, and a headless terminal whose picker answers with `pick` and
60 * records the options it was shown in `prompts`, and whose stdout data lands in `outputs`.
61 */
62 const orgsSwitchTest = (fixture: OrgsSwitchFixture = {}) => {
63 const outputs: Array<string> = [];
64 - const logins: Array<LoginCall> = [];
64 + const orgUpdates: Array<string | undefined> = [];
65 const prompts: Array<ReadonlyArray<{ readonly label: string; readonly hint?: string }>> = [];
66 const requests: Array<MockAccountRequest> = [];
67 const apiKey = fixture.apiKey ?? Option.some('uak_orgs_switch');
@@ -115,13 +115,16 @@ const orgsSwitchTest = (fixture: OrgsSwitchFixture = {}) => {
115 projectId: Option.none(),
116 testUserId: fixture.testUserId ?? Option.none(),
117 },
118 + backendMismatch: Option.none(),
119 isLoggedIn: () => Option.isSome(apiKey),
120 logout: Effect.void,
120 - login: (...call: LoginCall) =>
121 + login: () => Effect.die('orgs switch must update the org, not log in again'),
122 + update: (data: Partial<UserData>) =>
123 Effect.sync(() => {
122 - logins.push(call);
124 + orgUpdates.push(
125 + data.orgId === undefined ? undefined : Option.getOrUndefined(data.orgId)
126 + );
127 }),
124 - update: () => Effect.void,
128 })
129 ),
130 Layer.succeed(
@@ -140,7 +143,7 @@ const orgsSwitchTest = (fixture: OrgsSwitchFixture = {}) => {
143 return NodeOs.of({ homedir: dir, tmpdir: dir, arch: 'arm64', platform: 'darwin' });
144 })
145 );
143 - return { layer, outputs, logins, prompts, requests };
146 + return { layer, outputs, orgUpdates, prompts, requests };
147 };
148
149 const orgListLimits = (requests: ReadonlyArray<MockAccountRequest>) =>
@@ -150,7 +153,7 @@ const orgListLimits = (requests: ReadonlyArray<MockAccountRequest>) =>
153
154 describe('runOrgsSwitch', () => {
155 it.effect('[Given] --org-id [Then] stores it without listing or prompting', () => {
153 - const { layer, outputs, logins, prompts, requests } = orgsSwitchTest({
156 + const { layer, outputs, orgUpdates, prompts, requests } = orgsSwitchTest({
157 testUserId: Option.some('test_user'),
158 });
159 return Effect.gen(function* () {
@@ -158,7 +161,7 @@ describe('runOrgsSwitch', () => {
161
162 expect(orgListLimits(requests)).toEqual([]);
163 expect(prompts).toEqual([]);
161 - expect(logins).toEqual([['uak_orgs_switch', 'org_explicit', 'test_user']]);
164 + expect(orgUpdates).toEqual(['org_explicit']);
165 expect(analytics.linked).toEqual(['member_org_explicit']);
166 expect(outputs).toEqual([JSON.stringify({ scope: 'global', org_id: 'org_explicit' })]);
167 }).pipe(Effect.provide(layer));
@@ -167,7 +170,7 @@ describe('runOrgsSwitch', () => {
170 it.effect(
171 '[Given] several orgs and a current one [Then] the picker lists the current org first and stores the pick',
172 () => {
170 - const { layer, outputs, logins, prompts } = orgsSwitchTest({
173 + const { layer, outputs, orgUpdates, prompts } = orgsSwitchTest({
174 orgId: Option.some('org_current'),
175 pick: 'Third Org',
176 });
@@ -181,7 +184,7 @@ describe('runOrgsSwitch', () => {
184 { label: 'Third Org', hint: 'org_third' },
185 ],
186 ]);
184 - expect(logins).toEqual([['uak_orgs_switch', 'org_third', undefined]]);
187 + expect(orgUpdates).toEqual(['org_third']);
188 expect(analytics.linked).toEqual(['member_org_third']);
189 expect(outputs).toEqual([JSON.stringify({ scope: 'global', org_id: 'org_third' })]);
190 }).pipe(Effect.provide(layer));
@@ -200,23 +203,23 @@ describe('runOrgsSwitch', () => {
203 });
204
205 it.effect('[Given] one org [Then] it is stored without prompting', () => {
203 - const { layer, logins, prompts } = orgsSwitchTest({
206 + const { layer, orgUpdates, prompts } = orgsSwitchTest({
207 organizations: [{ id: 'org_only', name: 'Only Org' }],
208 });
209 return Effect.gen(function* () {
210 yield* runOrgsSwitch({ orgId: Option.none(), limit: 50 });
211
212 expect(prompts).toEqual([]);
210 - expect(logins).toEqual([['uak_orgs_switch', 'org_only', undefined]]);
213 + expect(orgUpdates).toEqual(['org_only']);
214 }).pipe(Effect.provide(layer));
215 });
216
217 it.effect('[Given] no orgs [Then] stores nothing, links nothing, and outputs nothing', () => {
215 - const { layer, outputs, logins } = orgsSwitchTest({ organizations: [] });
218 + const { layer, outputs, orgUpdates } = orgsSwitchTest({ organizations: [] });
219 return Effect.gen(function* () {
220 yield* runOrgsSwitch({ orgId: Option.none(), limit: 50 });
221
219 - expect(logins).toEqual([]);
222 + expect(orgUpdates).toEqual([]);
223 expect(analytics.linked).toEqual([]);
224 expect(outputs).toEqual([]);
225 expect(yield* MockConsole.getLines()).toContain(`-- ${NO_ORG_SELECTED_OUTRO} --`);
@@ -240,13 +243,13 @@ describe('runOrgsSwitch', () => {
243 it.effect(
244 '[Given] no stored API key [Then] fails with NotLoggedInError before any request',
245 () => {
243 - const { layer, logins, requests } = orgsSwitchTest({ apiKey: Option.none() });
246 + const { layer, orgUpdates, requests } = orgsSwitchTest({ apiKey: Option.none() });
247 return Effect.gen(function* () {
248 const error = yield* Effect.flip(runOrgsSwitch({ orgId: Option.none(), limit: 50 }));
249
250 expect(error).toMatchObject({ _tag: 'commands/NotLoggedInError' });
251 expect(requests).toEqual([]);
249 - expect(logins).toEqual([]);
252 + expect(orgUpdates).toEqual([]);
253 }).pipe(Effect.provide(layer));
254 }
255 );
ts/packages/cli/test/src/commands/projects/list/projects.list.handler.test.ts
+1
@@ -65,6 +65,7 @@ const projectsListTest = (fixture: ProjectsListFixture = {}) => {
65 projectId: Option.none(),
66 testUserId: Option.none(),
67 },
68 + backendMismatch: Option.none(),
69 isLoggedIn: () => Option.isSome(apiKey),
70 logout: Effect.void,
71 login: () => Effect.void,
ts/packages/cli/test/src/config/app.test.ts
+12
@@ -17,6 +17,12 @@ describe('APP_CONFIG', () => {
17 ENVIRONMENT: undefined,
18 BASE_URL: constants.DEFAULT_BASE_URL,
19 WEB_URL: constants.DEFAULT_WEB_URL,
20 + BACKEND: {
21 + baseURL: constants.DEFAULT_BASE_URL,
22 + webURL: constants.DEFAULT_WEB_URL,
23 + selectedBy: Option.none(),
24 + webURLSet: false,
25 + },
26 CACHE_DIR: undefined,
27 SESSION_DIR: undefined,
28 BIN_DIR: undefined,
@@ -69,6 +75,12 @@ describe('APP_CONFIG', () => {
75 ENVIRONMENT: undefined,
76 BASE_URL: 'https://test.localhost',
77 WEB_URL: 'https://web.localhost',
78 + BACKEND: {
79 + baseURL: 'https://test.localhost',
80 + webURL: 'https://web.localhost',
81 + selectedBy: Option.some('COMPOSIO_BASE_URL' as const),
82 + webURLSet: true,
83 + },
84 CACHE_DIR: '/tmp/composio-cache',
85 SESSION_DIR: undefined,
86 BIN_DIR: '/usr/local/bin',
ts/packages/cli/test/src/effects/rejected-user-api-key.test.ts new
+96
@@ -0,0 +1,96 @@
1 +import { describe, expect, it } from '@effect/vitest';
2 +import { ConfigProvider, Effect, Layer, Option } from 'effect';
3 +import { rejectedUserApiKeyHint } from 'src/effects/rejected-user-api-key';
4 +import { ComposioUserContext } from 'src/services/user-context';
5 +
6 +const PRODUCTION = { base: 'https://backend.composio.dev', web: 'https://dashboard.composio.dev/' };
7 +const STAGING = {
8 + base: 'https://staging-backend.composio.dev',
9 + web: 'https://staging-dashboard.composio.dev/',
10 +};
11 +
12 +/** The hint for a stored login whose resolved backend is `baseURL` with its Dashboard at `webURL`. */
13 +const hintFor = (baseURL: string, webURL: string, env: Record<string, string> = {}) =>
14 + rejectedUserApiKeyHint.pipe(
15 + Effect.provide(
16 + Layer.mergeAll(
17 + Layer.succeed(ConfigProvider.ConfigProvider, ConfigProvider.fromEnv({ env })),
18 + Layer.succeed(
19 + ComposioUserContext,
20 + ComposioUserContext.of({
21 + data: {
22 + apiKey: Option.some('uak_stored'),
23 + baseURL,
24 + webURL,
25 + orgId: Option.none(),
26 + projectId: Option.none(),
27 + testUserId: Option.none(),
28 + },
29 + backendMismatch: Option.none(),
30 + isLoggedIn: () => true,
31 + logout: Effect.void,
32 + login: () => Effect.void,
33 + update: () => Effect.void,
34 + })
35 + )
36 + )
37 + )
38 + );
39 +
40 +describe('rejectedUserApiKeyHint', () => {
41 + it.effect.each([
42 + { name: 'production', base: PRODUCTION.base, web: PRODUCTION.web, prefix: '' },
43 + {
44 + name: 'staging',
45 + base: STAGING.base,
46 + web: STAGING.web,
47 + prefix: 'COMPOSIO_ENVIRONMENT=staging ',
48 + },
49 + {
50 + name: 'a custom backend with the production Dashboard',
51 + base: 'https://api.example.test',
52 + web: PRODUCTION.web,
53 + prefix: 'COMPOSIO_BASE_URL=https://api.example.test ',
54 + },
55 + {
56 + name: 'a custom backend and a custom Dashboard',
57 + base: 'https://api.example.test',
58 + web: 'https://app.example.test/',
59 + prefix:
60 + 'COMPOSIO_BASE_URL=https://api.example.test COMPOSIO_WEB_URL=https://app.example.test ',
61 + },
62 + {
63 + name: 'staging with a custom Dashboard',
64 + base: STAGING.base,
65 + web: 'https://app.example.test',
66 + prefix: 'COMPOSIO_ENVIRONMENT=staging COMPOSIO_WEB_URL=https://app.example.test ',
67 + },
68 + {
69 + name: 'production with a custom Dashboard',
70 + base: PRODUCTION.base,
71 + web: 'https://app.example.test',
72 + prefix: 'COMPOSIO_WEB_URL=https://app.example.test ',
73 + },
74 + {
75 + name: 'URLs with shell characters',
76 + base: "https://api.example.test/o'brien",
77 + web: 'https://app.example.test/preview&team',
78 + prefix:
79 + "COMPOSIO_BASE_URL='https://api.example.test/o'\\''brien' COMPOSIO_WEB_URL='https://app.example.test/preview&team' ",
80 + },
81 + ])('[Given] a stored login on $name [Then] the login command targets it', c =>
82 + Effect.gen(function* () {
83 + expect(yield* hintFor(c.base, c.web)).toBe(
84 + `Log in again, then retry:\n> composio logout && ${c.prefix}composio login`
85 + );
86 + })
87 + );
88 +
89 + it.effect('[Given] a key from COMPOSIO_USER_API_KEY [Then] it says to replace that key', () =>
90 + Effect.gen(function* () {
91 + expect(yield* hintFor(STAGING.base, STAGING.web, { COMPOSIO_USER_API_KEY: 'uak_env' })).toBe(
92 + 'Replace the key in COMPOSIO_USER_API_KEY, then retry.'
93 + );
94 + })
95 + );
96 +});
ts/packages/cli/test/src/services/command-project.test.ts
+1
@@ -27,6 +27,7 @@ const userContext = (orgId: Option.Option<string>) =>
27 projectId: Option.none(),
28 testUserId: Option.none(),
29 },
30 + backendMismatch: Option.none(),
31 isLoggedIn: () => true,
32 logout: Effect.void,
33 login: () => Effect.void,
ts/packages/cli/test/src/services/dashboard-tool-execution.test.ts
+1
@@ -88,6 +88,7 @@ const userContext = (
88 projectId: Option.none(),
89 testUserId: Option.none(),
90 },
91 + backendMismatch: Option.none(),
92 isLoggedIn: () => true,
93 logout: Effect.void,
94 login: () => Effect.void,
ts/packages/cli/test/src/services/tool-permissions.test.ts
+1
@@ -110,6 +110,7 @@ const permissionsClientLayer = (responses: {
110 projectId: Option.none(),
111 testUserId: Option.none(),
112 },
113 + backendMismatch: Option.none(),
114 isLoggedIn: () => true,
115 logout: Effect.void,
116 login: () => Effect.void,
ts/packages/cli/test/src/services/user-context.test.ts
+221
@@ -422,4 +422,225 @@ describe('ComposioUserContext', () => {
422 });
423 });
424 });
425 +
426 + describe('[When] resolving the backend of a stored login', () => {
427 + const STAGING = {
428 + base_url: 'https://staging-backend.composio.dev',
429 + web_url: 'https://staging-dashboard.composio.dev/',
430 + };
431 + const PRODUCTION = {
432 + base_url: 'https://backend.composio.dev',
433 + web_url: 'https://dashboard.composio.dev/',
434 + };
435 +
436 + /** Builds the context over a home whose user_data.json is `stored` (none when undefined). */
437 + const withContext = <A, E>(
438 + env: Record<string, string>,
439 + stored: Record<string, unknown> | undefined,
440 + use: (ctx: ComposioUserContext['Service'], userDataPath: string) => Effect.Effect<A, E>
441 + ) => {
442 + const home = tempy.temporaryDirectory();
443 + const userDataPath = path.join(home, '.composio', 'user_data.json');
444 + if (stored !== undefined) {
445 + fs.mkdirSync(path.dirname(userDataPath), { recursive: true });
446 + fs.writeFileSync(userDataPath, JSON.stringify(stored));
447 + }
448 + const layer = Layer.provideMerge(
449 + ComposioUserContextLive,
450 + Layer.mergeAll(
451 + BunFileSystem.layer,
452 + BunPath.layer,
453 + Layer.succeed(NodeOs, defaultNodeOs({ homedir: home })),
454 + withMapConfigProvider(new Map(Object.entries(env)))
455 + )
456 + );
457 + return Effect.flatMap(ComposioUserContext, ctx => use(ctx, userDataPath)).pipe(
458 + Effect.provide(layer)
459 + );
460 + };
461 + const readStored = (userDataPath: string) =>
462 + JSON.parse(fs.readFileSync(userDataPath, 'utf8')) as Record<string, unknown>;
463 + const stagingLogin = { api_key: 'uak_staging', org_id: 'org_1', ...STAGING };
464 +
465 + it.effect('[Given] a staging login and no env var [Then] it uses staging', () =>
466 + withContext({}, stagingLogin, ctx =>
467 + Effect.sync(() => {
468 + assertEquals(ctx.data.baseURL, STAGING.base_url);
469 + assertEquals(ctx.data.webURL, STAGING.web_url);
470 + assertEquals(Option.isNone(ctx.backendMismatch), true);
471 + })
472 + )
473 + );
474 +
475 + it.effect(
476 + '[Given] a staging login and COMPOSIO_BASE_URL [Then] the env var wins and the mismatch is reported',
477 + () =>
478 + withContext({ COMPOSIO_BASE_URL: PRODUCTION.base_url }, stagingLogin, ctx =>
479 + Effect.sync(() => {
480 + assertEquals(ctx.data.baseURL, PRODUCTION.base_url);
481 + assertEquals(ctx.data.webURL, PRODUCTION.web_url);
482 + deepStrictEqual(
483 + ctx.backendMismatch,
484 + Option.some({
485 + variable: 'COMPOSIO_BASE_URL' as const,
486 + issuedBy: STAGING.base_url,
487 + selected: PRODUCTION.base_url,
488 + })
489 + );
490 + })
491 + )
492 + );
493 +
494 + it.effect(
495 + '[Given] a staging login and COMPOSIO_ENVIRONMENT=staging [Then] nothing is reported',
496 + () =>
497 + withContext({ COMPOSIO_ENVIRONMENT: 'staging' }, stagingLogin, ctx =>
498 + Effect.sync(() => {
499 + assertEquals(ctx.data.baseURL, STAGING.base_url);
500 + assertEquals(Option.isNone(ctx.backendMismatch), true);
501 + })
502 + )
503 + );
504 +
505 + it.effect(
506 + '[Given] COMPOSIO_USER_API_KEY and no env var [Then] it uses the default backend',
507 + () =>
508 + withContext({ COMPOSIO_USER_API_KEY: 'uak_env' }, stagingLogin, ctx =>
509 + Effect.sync(() => {
510 + assertEquals(ctx.data.baseURL, PRODUCTION.base_url);
511 + assertEquals(ctx.data.webURL, PRODUCTION.web_url);
512 + assertEquals(Option.isNone(ctx.backendMismatch), true);
513 + })
514 + )
515 + );
516 +
517 + it.effect(
518 + '[Given] a recorded backend but no stored key [Then] it uses the default backend',
519 + () =>
520 + withContext({}, { api_key: null, ...STAGING }, ctx =>
521 + Effect.sync(() => {
522 + assertEquals(ctx.data.baseURL, PRODUCTION.base_url);
523 + assertEquals(ctx.data.webURL, PRODUCTION.web_url);
524 + })
525 + )
526 + );
527 +
528 + it.effect(
529 + '[Given] an env override [When] the user data is updated [Then] the stored backend is kept',
530 + () =>
531 + withContext(
532 + { COMPOSIO_BASE_URL: 'http://127.0.0.1:9' },
533 + stagingLogin,
534 + (ctx, userDataPath) =>
535 + Effect.gen(function* () {
536 + yield* ctx.update({ orgId: Option.some('org_2') });
537 + const stored = readStored(userDataPath);
538 + assertEquals(stored.org_id, 'org_2');
539 + assertEquals(stored.base_url, STAGING.base_url);
540 + assertEquals(stored.web_url, STAGING.web_url);
541 + })
542 + )
543 + );
544 +
545 + it.effect(
546 + '[Given] COMPOSIO_ENVIRONMENT=staging [When] logging in [Then] the staging backend is recorded',
547 + () =>
548 + withContext({ COMPOSIO_ENVIRONMENT: 'staging' }, undefined, (ctx, userDataPath) =>
549 + Effect.gen(function* () {
550 + yield* ctx.login('uak_new', 'org_1');
551 + const stored = readStored(userDataPath);
552 + assertEquals(stored.base_url, STAGING.base_url);
553 + assertEquals(stored.web_url, STAGING.web_url);
554 + })
555 + )
556 + );
557 +
558 + it.effect(
559 + '[Given] a staging login and no env var [When] logging in again [Then] staging stays recorded',
560 + () =>
561 + withContext({}, stagingLogin, (ctx, userDataPath) =>
562 + Effect.gen(function* () {
563 + yield* ctx.login('uak_again', 'org_1');
564 + assertEquals(readStored(userDataPath).base_url, STAGING.base_url);
565 + assertEquals(ctx.data.baseURL, STAGING.base_url);
566 + })
567 + )
568 + );
569 +
570 + it.effect(
571 + '[Given] a staging login and COMPOSIO_USER_API_KEY [When] the user data is updated [Then] the stored key stays paired with its backend',
572 + () =>
573 + withContext(
574 + { COMPOSIO_USER_API_KEY: 'uak_env_production' },
575 + stagingLogin,
576 + (ctx, userDataPath) =>
577 + Effect.gen(function* () {
578 + yield* ctx.update({ orgId: Option.some('org_2') });
579 + const stored = readStored(userDataPath);
580 + assertEquals(stored.org_id, 'org_2');
581 + assertEquals(stored.api_key, 'uak_staging');
582 + assertEquals(stored.base_url, STAGING.base_url);
583 + // The env key still serves this run's requests.
584 + assertEquals(Option.getOrUndefined(ctx.data.apiKey), 'uak_env_production');
585 + })
586 + )
587 + );
588 +
589 + it.effect(
590 + '[Given] COMPOSIO_USER_API_KEY and no stored login [When] the user data is updated [Then] the env key is not written',
591 + () =>
592 + withContext({ COMPOSIO_USER_API_KEY: 'uak_env_only' }, undefined, (ctx, userDataPath) =>
593 + Effect.gen(function* () {
594 + yield* ctx.update({ orgId: Option.some('org_2') });
595 + const stored = readStored(userDataPath);
596 + assertEquals(stored.org_id, 'org_2');
597 + assertEquals(stored.api_key ?? null, null);
598 + })
599 + )
600 + );
601 +
602 + it.effect(
603 + '[Given] a login recorded against another backend [When] an agent identity logs in [Then] the env-selected backend is recorded',
604 + () =>
605 + withContext(
606 + {},
607 + { api_key: 'uak_old', base_url: 'https://proxy.example.test', web_url: null },
608 + (ctx, userDataPath) =>
609 + Effect.gen(function* () {
610 + yield* ctx.login('uak_agent', 'org_agent', undefined, { issuer: 'environment' });
611 + const stored = readStored(userDataPath);
612 + assertEquals(stored.api_key, 'uak_agent');
613 + assertEquals(stored.base_url, PRODUCTION.base_url);
614 + assertEquals(stored.web_url, PRODUCTION.web_url);
615 + assertEquals(ctx.data.baseURL, PRODUCTION.base_url);
616 + })
617 + )
618 + );
619 +
620 + it.effect(
621 + '[Given] COMPOSIO_ENVIRONMENT=staging and an older production login [When] an agent identity logs in [Then] staging is recorded',
622 + () =>
623 + withContext(
624 + { COMPOSIO_ENVIRONMENT: 'staging' },
625 + { api_key: 'uak_old', ...PRODUCTION },
626 + (ctx, userDataPath) =>
627 + Effect.gen(function* () {
628 + yield* ctx.login('uak_agent', 'org_agent', undefined, { issuer: 'environment' });
629 + assertEquals(readStored(userDataPath).base_url, STAGING.base_url);
630 + })
631 + )
632 + );
633 +
634 + it.effect('[When] logging out [Then] the recorded backend is forgotten', () =>
635 + withContext({}, stagingLogin, (ctx, userDataPath) =>
636 + Effect.gen(function* () {
637 + yield* ctx.logout;
638 + const stored = readStored(userDataPath);
639 + assertEquals(stored.base_url, null);
640 + assertEquals(stored.web_url, null);
641 + assertEquals(ctx.data.baseURL, PRODUCTION.base_url);
642 + })
643 + )
644 + );
645 + });
646 });