Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
| 1 | import { z } from 'zod/v3'; |
| 2 | import { Auth } from '@composio/client'; |
| 3 | import type { Scope } from '@composio/client'; |
| 4 | import { |
| 5 | ComposioAPIKeyKindError, |
| 6 | ComposioNoAPIKeyError, |
| 7 | ComposioScopeConfigError, |
| 8 | } from '../errors/SDKErrors'; |
| 9 | import { COMPOSIO_DIR, DEFAULT_BASE_URL, USER_DATA_FILE_NAME } from './constants'; |
| 10 | import { getEnvsWithPrefix, getEnvVariable } from './env'; |
| 11 | import logger from './logger'; |
| 12 | import { ComposioError } from '../errors/ComposioError'; |
| 13 | import { ToolkitVersion, ToolkitVersionParam, ToolkitVersions } from '../types/tool.types'; |
| 14 | import type { ComposioRequestHeaders } from '../types/composio.types'; |
| 15 | import { normalizeToolkitSlug } from './toolkitVersion'; |
| 16 | import { platform } from '#platform'; |
| 17 | |
| 18 | /** |
| 19 | * Header that carries a Composio user API key (`uak_...`) instead of a project |
| 20 | * API key. It is the only default header the credential resolver reads. |
| 21 | */ |
| 22 | export const USER_API_KEY_HEADER = 'x-user-api-key'; |
| 23 | |
| 24 | /** Prefix of Composio user API keys as issued by `composio login`. */ |
| 25 | const USER_API_KEY_PREFIX = 'uak_'; |
| 26 | |
| 27 | /** |
| 28 | * Header that carries the project API key. The SDK only ever sets it from the |
| 29 | * resolved `apiKey`; a caller-placed entry in `defaultHeaders` is rejected |
| 30 | * when project-key auth is disabled. |
| 31 | */ |
| 32 | export const PROJECT_API_KEY_HEADER = 'x-api-key'; |
| 33 | |
| 34 | /** Header that carries the organization API key (`oak_...`). */ |
| 35 | export const ORG_API_KEY_HEADER = 'x-org-api-key'; |
| 36 | |
| 37 | /** Header carrying the organization nano ID that scopes user-key requests. */ |
| 38 | export const ORG_ID_HEADER = 'x-org-id'; |
| 39 | |
| 40 | /** Header carrying the project nano ID that scopes user-key requests. */ |
| 41 | export const PROJECT_ID_HEADER = 'x-project-id'; |
| 42 | |
| 43 | /** |
| 44 | * Header names the SDK owns: the API client sends a credential from its |
| 45 | * `auth` and the scope from its `scope`, and refuses these names in its |
| 46 | * `defaultHeaders`. The SDK folds caller-supplied entries into its own |
| 47 | * credential and scope options instead of forwarding them. |
| 48 | */ |
| 49 | const SDK_OWNED_HEADERS = [ |
| 50 | PROJECT_API_KEY_HEADER, |
| 51 | USER_API_KEY_HEADER, |
| 52 | ORG_API_KEY_HEADER, |
| 53 | ORG_ID_HEADER, |
| 54 | PROJECT_ID_HEADER, |
| 55 | ]; |
| 56 | |
| 57 | // File path helpers |
| 58 | export const userDataPath = () => { |
| 59 | try { |
| 60 | const homeDir = platform.homedir(); |
| 61 | if (!homeDir) { |
| 62 | return null; |
| 63 | } |
| 64 | return platform.joinPath(homeDir, COMPOSIO_DIR, USER_DATA_FILE_NAME); |
| 65 | } catch (_error) { |
| 66 | logger.debug('Environment', `Unable to get user data path`); |
| 67 | return null; |
| 68 | } |
| 69 | }; |
| 70 | |
| 71 | /** |
| 72 | * Shape of `~/.composio/user_data.json`. The file is written by the Composio |
| 73 | * CLI; only the two fields the SDK consumes are validated, everything else is |
| 74 | * carried through untouched. |
| 75 | */ |
| 76 | const UserDataFileSchema = z |
| 77 | .object({ |
| 78 | api_key: z.string().nullish(), |
| 79 | base_url: z.string().nullish(), |
| 80 | }) |
| 81 | .passthrough(); |
| 82 | |
| 83 | export type UserDataFile = z.infer<typeof UserDataFileSchema>; |
| 84 | |
| 85 | export type UserDataFileRead = |
| 86 | /** No file system, no home directory, or no file: nothing to fall back to. */ |
| 87 | | { status: 'missing' } |
| 88 | /** The file exists but is not JSON or does not have the expected shape. */ |
| 89 | | { status: 'malformed'; path: string; reason: string } |
| 90 | | { status: 'ok'; path: string; data: UserDataFile }; |
| 91 | |
| 92 | /** |
| 93 | * Reads and validates the user data JSON file from the Composio directory. |
| 94 | * File contents never appear in the returned diagnostics. |
| 95 | */ |
| 96 | export const readUserDataFile = (): UserDataFileRead => { |
| 97 | if (!platform.supportsFileSystem) { |
| 98 | return { status: 'missing' }; |
| 99 | } |
| 100 | const dataPath = userDataPath(); |
| 101 | if (!dataPath) { |
| 102 | return { status: 'missing' }; |
| 103 | } |
| 104 | |
| 105 | let raw: string | Uint8Array; |
| 106 | try { |
| 107 | raw = platform.readFileSync(dataPath, 'utf8'); |
| 108 | } catch (_error) { |
| 109 | logger.debug('Environment', 'No user data file found'); |
| 110 | return { status: 'missing' }; |
| 111 | } |
| 112 | |
| 113 | let json: unknown; |
| 114 | try { |
| 115 | json = JSON.parse(typeof raw === 'string' ? raw : new TextDecoder().decode(raw)); |
| 116 | } catch (_error) { |
| 117 | logger.debug('Environment', `User data file at ${dataPath} could not be parsed as JSON`); |
| 118 | return { status: 'malformed', path: dataPath, reason: 'could not be parsed as JSON' }; |
| 119 | } |
| 120 | |
| 121 | const parsed = UserDataFileSchema.safeParse(json); |
| 122 | if (!parsed.success) { |
| 123 | const fields = parsed.error.issues |
| 124 | .map(issue => issue.path.join('.')) |
| 125 | .filter(Boolean) |
| 126 | .join(', '); |
| 127 | const reason = fields |
| 128 | ? `has an unexpected shape (invalid field${fields.includes(',') ? 's' : ''}: ${fields})` |
| 129 | : 'has an unexpected shape (expected a JSON object)'; |
| 130 | logger.debug('Environment', `User data file at ${dataPath} ${reason}`); |
| 131 | return { status: 'malformed', path: dataPath, reason }; |
| 132 | } |
| 133 | |
| 134 | return { status: 'ok', path: dataPath, data: parsed.data }; |
| 135 | }; |
| 136 | |
| 137 | const findHeader = ( |
| 138 | headers: ComposioRequestHeaders | undefined, |
| 139 | name: string |
| 140 | ): { name: string; value: string } | undefined => { |
| 141 | if (!headers) { |
| 142 | return undefined; |
| 143 | } |
| 144 | const wanted = name.toLowerCase(); |
| 145 | for (const [key, value] of Object.entries(headers)) { |
| 146 | if (key.toLowerCase() === wanted) { |
| 147 | return { name: key, value }; |
| 148 | } |
| 149 | } |
| 150 | return undefined; |
| 151 | }; |
| 152 | |
| 153 | /** |
| 154 | * Returns the `x-user-api-key` entry from a header map, if it carries a |
| 155 | * non-empty value. Matches the header name case-insensitively and ignores |
| 156 | * every other header. |
| 157 | */ |
| 158 | export const getUserApiKeyHeader = ( |
| 159 | headers: ComposioRequestHeaders | undefined |
| 160 | ): { name: string; value: string } | undefined => getCredentialHeader(headers, USER_API_KEY_HEADER); |
| 161 | |
| 162 | const getCredentialHeader = ( |
| 163 | headers: ComposioRequestHeaders | undefined, |
| 164 | name: string |
| 165 | ): { name: string; value: string } | undefined => { |
| 166 | const header = findHeader(headers, name); |
| 167 | return header && typeof header.value === 'string' && header.value.length > 0 ? header : undefined; |
| 168 | }; |
| 169 | |
| 170 | export type CredentialHeaderInput = { |
| 171 | /** The project API key the client resolved, or `null` when disabled. */ |
| 172 | apiKey: string | null | undefined; |
| 173 | /** The user API key the client resolved (`userApiKey` option or `COMPOSIO_USER_API_KEY`). */ |
| 174 | userApiKey: string | null | undefined; |
| 175 | /** The organization API key the client resolved (`orgApiKey` option or `COMPOSIO_ORG_API_KEY`). */ |
| 176 | orgApiKey?: string | null; |
| 177 | /** The default headers configured on the SDK instance; only `x-user-api-key` is consulted. */ |
| 178 | defaultHeaders: ComposioRequestHeaders | undefined; |
| 179 | }; |
| 180 | |
| 181 | /** |
| 182 | * The single credential header that mirrors what the API client puts on the |
| 183 | * wire for an SDK instance. A non-empty `x-user-api-key` entry in the default |
| 184 | * headers wins: the client treats a caller-placed credential header as the |
| 185 | * credential and suppresses the configured keys. Otherwise the project key |
| 186 | * travels as `x-api-key`, otherwise the resolved user API key as |
| 187 | * `x-user-api-key`, otherwise the organization API key as `x-org-api-key` |
| 188 | * (the order {@link toClientAuth} picks them in). Empty when no credential is |
| 189 | * held. The environment is never consulted here. |
| 190 | */ |
| 191 | export const resolveCredentialHeaders = (input: CredentialHeaderInput): Record<string, string> => { |
| 192 | const userApiKeyHeader = getUserApiKeyHeader(input.defaultHeaders); |
| 193 | if (userApiKeyHeader) { |
| 194 | return { [USER_API_KEY_HEADER]: userApiKeyHeader.value }; |
| 195 | } |
| 196 | if (hasValue(input.apiKey)) { |
| 197 | return { [PROJECT_API_KEY_HEADER]: input.apiKey }; |
| 198 | } |
| 199 | if (hasValue(input.userApiKey)) { |
| 200 | return { [USER_API_KEY_HEADER]: input.userApiKey }; |
| 201 | } |
| 202 | if (hasValue(input.orgApiKey)) { |
| 203 | return { [ORG_API_KEY_HEADER]: input.orgApiKey }; |
| 204 | } |
| 205 | return {}; |
| 206 | }; |
| 207 | |
| 208 | export type SDKScopeOptions = { |
| 209 | /** The `orgId` constructor option. */ |
| 210 | orgId?: string; |
| 211 | /** The `projectId` constructor option. */ |
| 212 | projectId?: string; |
| 213 | /** Default headers the SDK will attach to every request. */ |
| 214 | defaultHeaders?: ComposioRequestHeaders; |
| 215 | }; |
| 216 | |
| 217 | export type SDKScope = { |
| 218 | orgId?: string; |
| 219 | projectId?: string; |
| 220 | }; |
| 221 | |
| 222 | const resolveScopeValue = ( |
| 223 | option: string | undefined, |
| 224 | headers: ComposioRequestHeaders | undefined, |
| 225 | headerName: string, |
| 226 | optionName: 'orgId' | 'projectId' |
| 227 | ): string | undefined => { |
| 228 | const header = findHeader(headers, headerName); |
| 229 | const headerValue = header && header.value.length > 0 ? header.value : undefined; |
| 230 | const optionValue = hasValue(option) ? option : undefined; |
| 231 | if (optionValue !== undefined && headerValue !== undefined && optionValue !== headerValue) { |
| 232 | throw new ComposioScopeConfigError( |
| 233 | `\`${optionName}\` and the \`${headerName}\` default header disagree`, |
| 234 | { |
| 235 | cause: `The ${optionName} option and the ${headerName} entry in defaultHeaders carry different values; the SDK keeps a single scope source`, |
| 236 | meta: { option: optionName, header: headerName }, |
| 237 | } |
| 238 | ); |
| 239 | } |
| 240 | return optionValue ?? headerValue; |
| 241 | }; |
| 242 | |
| 243 | /** |
| 244 | * Resolves the organization/project scope of an SDK instance. |
| 245 | * |
| 246 | * The scope comes from the `orgId` / `projectId` options, or from the |
| 247 | * `x-org-id` / `x-project-id` default headers when the options are omitted. |
| 248 | * A value present in both places must agree, and the two IDs must be supplied |
| 249 | * together: a user API key without an explicit scope keeps the API default |
| 250 | * (the developer project), so a half-configured scope is rejected instead of |
| 251 | * silently selecting a project. |
| 252 | */ |
| 253 | export function resolveSDKScope(options: SDKScopeOptions): SDKScope { |
| 254 | const orgId = resolveScopeValue(options.orgId, options.defaultHeaders, ORG_ID_HEADER, 'orgId'); |
| 255 | const projectId = resolveScopeValue( |
| 256 | options.projectId, |
| 257 | options.defaultHeaders, |
| 258 | PROJECT_ID_HEADER, |
| 259 | 'projectId' |
| 260 | ); |
| 261 | if ((orgId === undefined) !== (projectId === undefined)) { |
| 262 | throw new ComposioScopeConfigError( |
| 263 | orgId === undefined |
| 264 | ? '`projectId` requires `orgId`: the organization and project nano IDs scope requests together' |
| 265 | : '`orgId` requires `projectId`: the organization and project nano IDs scope requests together', |
| 266 | { |
| 267 | cause: 'Only one of the two scope identifiers was configured', |
| 268 | meta: { orgId: orgId !== undefined, projectId: projectId !== undefined }, |
| 269 | } |
| 270 | ); |
| 271 | } |
| 272 | return orgId === undefined || projectId === undefined ? {} : { orgId, projectId }; |
| 273 | } |
| 274 | |
| 275 | /** |
| 276 | * The API client `scope` for a resolved SDK scope: the organization and |
| 277 | * project nano IDs the client sends as `x-org-id` / `x-project-id`, or |
| 278 | * `undefined` when the instance is unscoped. |
| 279 | */ |
| 280 | export const toClientScope = (scope: SDKScope): Scope | undefined => |
| 281 | scope.orgId && scope.projectId |
| 282 | ? { organizationId: scope.orgId, projectId: scope.projectId } |
| 283 | : undefined; |
| 284 | |
| 285 | /** |
| 286 | * `headers` without the credential and scope entries the SDK owns (matched |
| 287 | * case-insensitively). Those travel through the API client's `auth` and |
| 288 | * `scope`, which refuse the same names in `defaultHeaders`. |
| 289 | */ |
| 290 | export const withoutSDKOwnedHeaders = ( |
| 291 | headers: ComposioRequestHeaders | undefined |
| 292 | ): ComposioRequestHeaders | undefined => |
| 293 | headers === undefined |
| 294 | ? undefined |
| 295 | : Object.fromEntries( |
| 296 | Object.entries(headers).filter(([name]) => !SDK_OWNED_HEADERS.includes(name.toLowerCase())) |
| 297 | ); |
| 298 | |
| 299 | export type SDKConfigOptions = { |
| 300 | /** Default headers the SDK will attach to every request. */ |
| 301 | defaultHeaders?: ComposioRequestHeaders; |
| 302 | /** |
| 303 | * The `userApiKey` constructor option, exactly as the caller passed it: |
| 304 | * `undefined` lets the API client read `COMPOSIO_USER_API_KEY`, `null` |
| 305 | * disables that fallback. |
| 306 | */ |
| 307 | userApiKey?: string | null; |
| 308 | /** |
| 309 | * The `orgApiKey` constructor option, exactly as the caller passed it: |
| 310 | * `undefined` lets the API client read `COMPOSIO_ORG_API_KEY`, `null` |
| 311 | * disables that fallback. |
| 312 | */ |
| 313 | orgApiKey?: string | null; |
| 314 | }; |
| 315 | |
| 316 | export type SDKConfig = { |
| 317 | baseURL: string; |
| 318 | /** The project API key to send as `x-api-key`, or `null` when project-key auth is disabled. */ |
| 319 | apiKey: string | null; |
| 320 | }; |
| 321 | |
| 322 | const hasValue = (value: string | null | undefined): value is string => |
| 323 | typeof value === 'string' && value.length > 0; |
| 324 | |
| 325 | /** |
| 326 | * Mirrors how the API client resolves `userApiKey` / `orgApiKey`: an explicit |
| 327 | * value (including `null`) is final, `undefined` falls back to the environment. |
| 328 | */ |
| 329 | const resolveAlternateCredential = ( |
| 330 | explicit: string | null | undefined, |
| 331 | envName: string |
| 332 | ): string | undefined => { |
| 333 | if (explicit !== undefined) { |
| 334 | return hasValue(explicit) ? explicit : undefined; |
| 335 | } |
| 336 | const fromEnv = getEnvVariable(envName); |
| 337 | return hasValue(fromEnv) ? fromEnv : undefined; |
| 338 | }; |
| 339 | |
| 340 | /** |
| 341 | * The user API key the API client will hold: the `userApiKey` option when it |
| 342 | * was passed (including `null`, which disables the fallback), otherwise |
| 343 | * `COMPOSIO_USER_API_KEY`. |
| 344 | */ |
| 345 | export const resolveUserApiKey = (userApiKey: string | null | undefined): string | undefined => |
| 346 | resolveAlternateCredential(userApiKey, 'COMPOSIO_USER_API_KEY'); |
| 347 | |
| 348 | /** |
| 349 | * The organization API key the instance holds: the `orgApiKey` option when it |
| 350 | * was passed (including `null`, which disables the fallback), otherwise |
| 351 | * `COMPOSIO_ORG_API_KEY`. |
| 352 | */ |
| 353 | export const resolveOrgApiKey = (orgApiKey: string | null | undefined): string | undefined => |
| 354 | resolveAlternateCredential(orgApiKey, 'COMPOSIO_ORG_API_KEY'); |
| 355 | |
| 356 | /** |
| 357 | * Whether the instance holds a credential other than the project key: a user |
| 358 | * or organization API key (explicit or environment-resolved, as the API client |
| 359 | * will see it), or a user or organization API key placed in the default |
| 360 | * headers, which {@link resolveSDKCredentials} folds in. |
| 361 | */ |
| 362 | const hasAlternateCredential = (options: SDKConfigOptions): boolean => |
| 363 | resolveUserApiKey(options.userApiKey) !== undefined || |
| 364 | resolveOrgApiKey(options.orgApiKey) !== undefined || |
| 365 | getUserApiKeyHeader(options.defaultHeaders) !== undefined || |
| 366 | getCredentialHeader(options.defaultHeaders, ORG_API_KEY_HEADER) !== undefined; |
| 367 | |
| 368 | /** |
| 369 | * The credentials an SDK instance authenticates with, after the environment |
| 370 | * fallbacks and the credential default headers are applied. `null` is a |
| 371 | * credential the instance does not hold. |
| 372 | */ |
| 373 | export type SDKCredentials = { |
| 374 | /** The project API key, or `null` when project-key auth is disabled. */ |
| 375 | apiKey: string | null; |
| 376 | /** The user API key (`uak_...`), or `null`. */ |
| 377 | userApiKey: string | null; |
| 378 | /** The organization API key (`oak_...`), or `null`. */ |
| 379 | orgApiKey: string | null; |
| 380 | }; |
| 381 | |
| 382 | export type SDKCredentialsInput = { |
| 383 | /** The project API key {@link getSDKConfig} resolved. */ |
| 384 | apiKey: string | null; |
| 385 | /** The `userApiKey` option as passed: `undefined` falls back to `COMPOSIO_USER_API_KEY`. */ |
| 386 | userApiKey?: string | null; |
| 387 | /** The `orgApiKey` option as passed: `undefined` falls back to `COMPOSIO_ORG_API_KEY`. */ |
| 388 | orgApiKey?: string | null; |
| 389 | /** Default headers the caller configured; only the credential headers are read. */ |
| 390 | defaultHeaders?: ComposioRequestHeaders; |
| 391 | }; |
| 392 | |
| 393 | const CREDENTIAL_HEADERS = [PROJECT_API_KEY_HEADER, USER_API_KEY_HEADER, ORG_API_KEY_HEADER]; |
| 394 | |
| 395 | /** |
| 396 | * Resolves the credentials of an SDK instance. |
| 397 | * |
| 398 | * The user and organization keys fall back to `COMPOSIO_USER_API_KEY` and |
| 399 | * `COMPOSIO_ORG_API_KEY` when their option is omitted. A non-empty credential |
| 400 | * header in `defaultHeaders` (any letter case) is folded in as the credential |
| 401 | * it names, and it is the credential the instance sends, as it was when the |
| 402 | * header itself went on the wire: an `x-user-api-key` or `x-org-api-key` entry |
| 403 | * disables the project key and takes the place of the configured user or |
| 404 | * organization key, and an `x-api-key` entry takes the place of the project |
| 405 | * key. At most one credential header may be set: the API rejects a request |
| 406 | * that carries two. |
| 407 | */ |
| 408 | export function resolveSDKCredentials(input: SDKCredentialsInput): SDKCredentials { |
| 409 | const headers = CREDENTIAL_HEADERS.flatMap(name => { |
| 410 | const header = findHeader(input.defaultHeaders, name); |
| 411 | return header && hasValue(header.value) ? [{ ...header, canonical: name }] : []; |
| 412 | }); |
| 413 | if (headers.length > 1) { |
| 414 | throw new ComposioError('`defaultHeaders` carries more than one credential header', { |
| 415 | cause: `The API accepts exactly one credential per request, and \`defaultHeaders\` sets ${headers |
| 416 | .map(header => `\`${header.name}\``) |
| 417 | .join(' and ')}`, |
| 418 | possibleFixes: [ |
| 419 | 'Pass credentials through `apiKey`, `userApiKey` and `orgApiKey` instead of default headers', |
| 420 | 'Keep at most one of `x-api-key`, `x-user-api-key` and `x-org-api-key` in `defaultHeaders`', |
| 421 | ], |
| 422 | }); |
| 423 | } |
| 424 | const userApiKey = resolveUserApiKey(input.userApiKey) ?? null; |
| 425 | const orgApiKey = resolveOrgApiKey(input.orgApiKey) ?? null; |
| 426 | const [header] = headers; |
| 427 | switch (header?.canonical) { |
| 428 | case USER_API_KEY_HEADER: |
| 429 | return { apiKey: null, userApiKey: header.value, orgApiKey }; |
| 430 | case ORG_API_KEY_HEADER: |
| 431 | return { apiKey: null, userApiKey: null, orgApiKey: header.value }; |
| 432 | case PROJECT_API_KEY_HEADER: |
| 433 | return { apiKey: header.value, userApiKey, orgApiKey }; |
| 434 | default: |
| 435 | return { apiKey: input.apiKey, userApiKey, orgApiKey }; |
| 436 | } |
| 437 | } |
| 438 | |
| 439 | /** |
| 440 | * The API client `auth` for the credentials of an SDK instance. |
| 441 | * |
| 442 | * - A project key alone authenticates every request with it. |
| 443 | * - A project key with a user and/or organization key selects one per |
| 444 | * operation: the project key wherever the operation accepts it, otherwise |
| 445 | * the first declared scheme a key is held for. |
| 446 | * - Without a project key, the user key authenticates every request (sessions |
| 447 | * included, whose operations declare no scheme), and the organization key |
| 448 | * does when it is the only one held. |
| 449 | */ |
| 450 | export const toClientAuth = (credentials: SDKCredentials): Auth => { |
| 451 | const { apiKey, userApiKey, orgApiKey } = credentials; |
| 452 | if (apiKey !== null) { |
| 453 | return userApiKey === null && orgApiKey === null |
| 454 | ? Auth.project(apiKey) |
| 455 | : Auth.auto({ |
| 456 | project: apiKey, |
| 457 | user: userApiKey ?? undefined, |
| 458 | organization: orgApiKey ?? undefined, |
| 459 | }); |
| 460 | } |
| 461 | if (userApiKey !== null) { |
| 462 | return Auth.user(userApiKey); |
| 463 | } |
| 464 | if (orgApiKey !== null) { |
| 465 | return Auth.organization(orgApiKey); |
| 466 | } |
| 467 | throw new ComposioNoAPIKeyError(); |
| 468 | }; |
| 469 | |
| 470 | /** |
| 471 | * Resolves the base URL and project API key the SDK will use. |
| 472 | * |
| 473 | * Project key resolution distinguishes three caller intents: |
| 474 | * - a non-empty string is used as-is and nothing else is consulted; |
| 475 | * - `undefined` (or an empty string) falls back to `COMPOSIO_API_KEY`, then to |
| 476 | * the `api_key` stored by the CLI in `~/.composio/user_data.json`; |
| 477 | * - `null` disables project-key auth: neither `COMPOSIO_API_KEY` nor the stored |
| 478 | * `api_key` is read, and the resolver only succeeds when the instance holds |
| 479 | * another credential: a `userApiKey` or `orgApiKey` (explicit, or resolved |
| 480 | * from `COMPOSIO_USER_API_KEY` / `COMPOSIO_ORG_API_KEY` the way the API |
| 481 | * client does), or a non-empty `x-user-api-key` or `x-org-api-key` entry in |
| 482 | * `defaultHeaders`. |
| 483 | * An `x-api-key` entry in `defaultHeaders` (any letter case) is rejected in |
| 484 | * that mode: the project credential is only ever set from `apiKey`. |
| 485 | * |
| 486 | * A stored `uak_` user key is never used as a project key: when it is the only |
| 487 | * candidate the resolver throws a {@link ComposioAPIKeyKindError} that names the |
| 488 | * problem without echoing the key. |
| 489 | */ |
| 490 | export function getSDKConfig( |
| 491 | baseUrl?: string | null, |
| 492 | apiKey?: string | null, |
| 493 | options: SDKConfigOptions = {} |
| 494 | ): SDKConfig { |
| 495 | let userData: UserDataFileRead | undefined; |
| 496 | const readUserData = () => { |
| 497 | userData ??= readUserDataFile(); |
| 498 | return userData; |
| 499 | }; |
| 500 | const userDataValue = (field: 'api_key' | 'base_url'): string | undefined => { |
| 501 | const read = readUserData(); |
| 502 | return read.status === 'ok' && hasValue(read.data[field]) ? read.data[field] : undefined; |
| 503 | }; |
| 504 | |
| 505 | const resolveApiKey = (): string | null => { |
| 506 | if (apiKey === null) { |
| 507 | const projectKeyHeader = findHeader(options.defaultHeaders, PROJECT_API_KEY_HEADER); |
| 508 | if (projectKeyHeader) { |
| 509 | throw new ComposioNoAPIKeyError( |
| 510 | `Project API key resolution is disabled, but \`defaultHeaders\` carries a \`${projectKeyHeader.name}\` entry`, |
| 511 | { |
| 512 | cause: |
| 513 | '`apiKey: null` sends no project key, so a raw x-api-key default header would bypass that choice; the SDK keeps a single source for the project credential', |
| 514 | possibleFixes: [ |
| 515 | `Pass the project API key via \`apiKey\` instead of a raw \`${PROJECT_API_KEY_HEADER}\` default header`, |
| 516 | `Remove the \`${projectKeyHeader.name}\` entry from \`defaultHeaders\` to authenticate with the user or organization API key alone`, |
| 517 | ], |
| 518 | } |
| 519 | ); |
| 520 | } |
| 521 | if (hasAlternateCredential(options)) { |
| 522 | return null; |
| 523 | } |
| 524 | throw new ComposioNoAPIKeyError('Project API key resolution is disabled', { |
| 525 | cause: |
| 526 | '`apiKey: null` turns off the COMPOSIO_API_KEY and user config file fallbacks, and no user or organization API key was configured', |
| 527 | possibleFixes: [ |
| 528 | 'Pass a project API key via `apiKey`, or omit it to fall back to COMPOSIO_API_KEY', |
| 529 | 'To authenticate with a user API key instead, keep `apiKey: null` and pass `userApiKey` (or set COMPOSIO_USER_API_KEY)', |
| 530 | `Alternatively, keep \`apiKey: null\` and set the \`${USER_API_KEY_HEADER}\` default header`, |
| 531 | ], |
| 532 | }); |
| 533 | } |
| 534 | |
| 535 | if (hasValue(apiKey)) { |
| 536 | return apiKey; |
| 537 | } |
| 538 | |
| 539 | const envApiKey = getEnvVariable('COMPOSIO_API_KEY'); |
| 540 | if (hasValue(envApiKey)) { |
| 541 | return envApiKey; |
| 542 | } |
| 543 | |
| 544 | const read = readUserData(); |
| 545 | const storedApiKey = userDataValue('api_key'); |
| 546 | if (read.status === 'ok' && hasValue(storedApiKey)) { |
| 547 | if (storedApiKey.startsWith(USER_API_KEY_PREFIX)) { |
| 548 | throw new ComposioAPIKeyKindError(undefined, { |
| 549 | cause: `The user config file at ${read.path} holds a user API key written by the Composio CLI; it cannot authenticate SDK requests as a project`, |
| 550 | meta: { userDataFilePath: read.path }, |
| 551 | }); |
| 552 | } |
| 553 | return storedApiKey; |
| 554 | } |
| 555 | |
| 556 | if (read.status === 'malformed') { |
| 557 | throw new ComposioNoAPIKeyError('No Composio API key provided', { |
| 558 | cause: `No API key was passed in the params or in COMPOSIO_API_KEY, and the user config file at ${read.path} ${read.reason}`, |
| 559 | }); |
| 560 | } |
| 561 | throw new ComposioNoAPIKeyError(); |
| 562 | }; |
| 563 | |
| 564 | let apiKeyParsed: string | null; |
| 565 | try { |
| 566 | apiKeyParsed = resolveApiKey(); |
| 567 | } catch (error) { |
| 568 | ComposioError.handleAndThrow(error); |
| 569 | } |
| 570 | |
| 571 | const baseURLParsed = |
| 572 | (hasValue(baseUrl) ? baseUrl : undefined) ?? |
| 573 | getEnvVariable('COMPOSIO_BASE_URL') ?? |
| 574 | userDataValue('base_url') ?? |
| 575 | DEFAULT_BASE_URL; |
| 576 | |
| 577 | logger.debug( |
| 578 | 'Environment', |
| 579 | apiKeyParsed === null ? 'API Key: [DISABLED]' : 'API Key: [REDACTED]' |
| 580 | ); |
| 581 | logger.debug('Environment', `Base URL: ${baseURLParsed}`); |
| 582 | |
| 583 | return { baseURL: baseURLParsed, apiKey: apiKeyParsed }; |
| 584 | } |
| 585 | |
| 586 | /** |
| 587 | * Gets toolkit versions configuration by merging environment variables, user-provided defaults, and fallbacks. |
| 588 | * |
| 589 | * Priority order: |
| 590 | * 1. If defaultVersions is a string, use it as global version for all toolkits |
| 591 | * 2. User-provided toolkit version mappings (defaultVersions object) |
| 592 | * 3. Environment variables (COMPOSIO_TOOLKIT_VERSION_<TOOLKIT_NAME>) |
| 593 | * 4. Fallback to 'latest' if no versions are configured |
| 594 | * |
| 595 | * @param defaultVersions - Optional default versions configuration (string for global version or object mapping toolkit names to versions) |
| 596 | * @returns Toolkit versions configuration - either a global version string, toolkit-specific version mapping, or 'latest' |
| 597 | */ |
| 598 | export function getToolkitVersionsFromEnv( |
| 599 | defaultVersions?: ToolkitVersionParam |
| 600 | ): ToolkitVersionParam { |
| 601 | // if already set by user either a single version or 'latest' use that as is / override everything else |
| 602 | if (defaultVersions && typeof defaultVersions === 'string') { |
| 603 | return defaultVersions; |
| 604 | } |
| 605 | |
| 606 | // check if there are envs similar to COMPOSIO_TOOLKIT_VERSION_GITHUB then extract the toolkit name |
| 607 | const envPrefixedVersions = getEnvsWithPrefix(`COMPOSIO_TOOLKIT_VERSION_`); |
| 608 | const toolkitVersionsFromEnv = Object.entries(envPrefixedVersions).reduce((acc, [key, value]) => { |
| 609 | const toolkitName = key.replace('COMPOSIO_TOOLKIT_VERSION_', ''); |
| 610 | acc[normalizeToolkitSlug(toolkitName)] = value as ToolkitVersion; |
| 611 | return acc; |
| 612 | }, {} as ToolkitVersions); |
| 613 | |
| 614 | // normalize keys via normalizeToolkitSlug (the same helper the lookup uses); |
| 615 | // user provided values act as overrides |
| 616 | let userProvidedToolkitVersions = {}; |
| 617 | if (defaultVersions && typeof defaultVersions === 'object') { |
| 618 | userProvidedToolkitVersions = Object.fromEntries( |
| 619 | Object.entries(defaultVersions).map(([key, value]) => [normalizeToolkitSlug(key), value]) |
| 620 | ); |
| 621 | } |
| 622 | |
| 623 | // final toolkit versions |
| 624 | const toolkitVersions = { |
| 625 | ...toolkitVersionsFromEnv, |
| 626 | ...userProvidedToolkitVersions, |
| 627 | }; |
| 628 | |
| 629 | // if the toolkitVersions are empty, use 'latest' |
| 630 | if (Object.keys(toolkitVersions).length === 0) { |
| 631 | return 'latest'; |
| 632 | } |
| 633 | |
| 634 | return toolkitVersions; |
| 635 | } |