@composio/core 0.18.1 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/dist/{CustomTool-VRfWzMix.d.mts → CustomTool-B3m-188G.d.mts} +1 -1
  2. package/dist/{CustomTool-Bz0f52QR.mjs → CustomTool-fYEFjSLM.mjs} +1 -1
  3. package/dist/{FileModifierErrors-CwB-Inm9.mjs → FileModifierErrors-CdGSABoq.mjs} +1 -1
  4. package/dist/{FileToolModifier.utils.neutral-D_YkHwZP.mjs → FileToolModifier.utils.neutral-DWFpnsj2.mjs} +4 -2
  5. package/dist/{SsrfErrors-xhdVE4yw.mjs → SsrfErrors-DiQldIdC.mjs} +32 -17
  6. package/dist/{Telemetry-Dw9W5RSp.mjs → Telemetry-JRJJYS4I.mjs} +2 -2
  7. package/dist/{cancellation-P5YUlcfz.mjs → cancellation-Dwa9lGHA.mjs} +7 -5
  8. package/dist/{composio-Cb3d1jFe.d.mts → composio-B36OXii1.d.mts} +3017 -144
  9. package/dist/{customTool.types-B6ej_8XZ.d.mts → customTool.types-C436M_D0.d.mts} +525 -101
  10. package/dist/docs/reference/sdk-reference/typescript/auth-configs.mdx +10 -10
  11. package/dist/docs/reference/sdk-reference/typescript/composio.mdx +8 -15
  12. package/dist/docs/reference/sdk-reference/typescript/connected-accounts.mdx +101 -18
  13. package/dist/docs/reference/sdk-reference/typescript/custom-toolkits.mdx +123 -0
  14. package/dist/docs/reference/sdk-reference/typescript/experimental.mdx +9 -2
  15. package/dist/docs/reference/sdk-reference/typescript/index.mdx +7 -0
  16. package/dist/docs/reference/sdk-reference/typescript/keyring.mdx +56 -0
  17. package/dist/docs/reference/sdk-reference/typescript/logs.mdx +78 -0
  18. package/dist/docs/reference/sdk-reference/typescript/mcp.mdx +15 -15
  19. package/dist/docs/reference/sdk-reference/typescript/meta.json +8 -1
  20. package/dist/docs/reference/sdk-reference/typescript/session-files.mdx +10 -10
  21. package/dist/docs/reference/sdk-reference/typescript/session.mdx +117 -24
  22. package/dist/docs/reference/sdk-reference/typescript/sessions.mdx +24 -10
  23. package/dist/docs/reference/sdk-reference/typescript/toolkits.mdx +151 -14
  24. package/dist/docs/reference/sdk-reference/typescript/tools.mdx +50 -40
  25. package/dist/docs/reference/sdk-reference/typescript/triggers.mdx +26 -25
  26. package/dist/docs/reference/sdk-reference/typescript/usage.mdx +78 -0
  27. package/dist/docs/reference/sdk-reference/typescript/webhook-endpoints.mdx +162 -0
  28. package/dist/docs/reference/sdk-reference/typescript/webhook-subscriptions.mdx +218 -0
  29. package/dist/docs/reference/sdk-reference/typescript/webhooks.mdx +20 -0
  30. package/dist/{errors-Ue9wMrPK.mjs → errors-D_A4b2c2.mjs} +143 -4
  31. package/dist/experimental/index.d.mts +2 -2
  32. package/dist/experimental/index.mjs +1 -1
  33. package/dist/{fileUtils.node-KE5Fa-af.mjs → fileUtils.node-DNLhLg0W.mjs} +8 -6
  34. package/dist/index.d.mts +418 -146
  35. package/dist/index.mjs +2728 -349
  36. package/dist/models/Files.node.d.mts +2 -3
  37. package/dist/models/Files.node.mjs +2 -2
  38. package/dist/models/Files.workerd.d.mts +2 -3
  39. package/dist/platform/node.d.mts +2 -3
  40. package/dist/platform/workerd.d.mts +2 -3
  41. package/dist/{sensitiveFileUploadPaths-QN7w4n8v.mjs → sensitiveFileUploadPaths-BlLp-Yo2.mjs} +10 -7
  42. package/dist/{ssrfGuard.node-BLX6b-Rf.mjs → ssrfGuard.node-BZ270bcu.mjs} +104 -14
  43. package/dist/{types-CGdgK442.d.mts → types-Br3GBya5.d.mts} +2 -2
  44. package/dist/utils/config-defaults/ConfigDefaults.node.d.mts +3 -4
  45. package/dist/utils/config-defaults/ConfigDefaults.workerd.d.mts +3 -4
  46. package/dist/utils/modifiers/FileToolModifier.node.d.mts +3 -4
  47. package/dist/utils/modifiers/FileToolModifier.node.mjs +6 -6
  48. package/dist/utils/modifiers/FileToolModifier.workerd.d.mts +3 -4
  49. package/dist/utils/modifiers/FileToolModifier.workerd.mjs +1 -1
  50. package/dist/utils/ssrfGuard.node.d.mts +19 -10
  51. package/dist/utils/ssrfGuard.node.mjs +1 -1
  52. package/dist/utils/ssrfGuard.workerd.d.mts +12 -4
  53. package/dist/utils/ssrfGuard.workerd.mjs +2 -2
  54. package/package.json +9 -9
  55. package/src/composio.ts +207 -10
  56. package/src/errors/ConnectedAccountsErrors.ts +47 -0
  57. package/src/errors/SDKErrors.ts +52 -0
  58. package/src/errors/ToolErrors.ts +24 -0
  59. package/src/errors/ToolRouterErrors.ts +57 -0
  60. package/src/errors/index.ts +3 -0
  61. package/src/index.ts +15 -0
  62. package/src/lib/toolRouterMcp.ts +132 -0
  63. package/src/lib/toolRouterParams.ts +116 -29
  64. package/src/models/ConnectedAccounts.ts +118 -2
  65. package/src/models/CustomToolkits.ts +169 -0
  66. package/src/models/Experimental.ts +27 -0
  67. package/src/models/Keyring.ts +65 -0
  68. package/src/models/Logs.ts +101 -0
  69. package/src/models/MCP.ts +29 -15
  70. package/src/models/ToolRouter.ts +43 -14
  71. package/src/models/ToolRouterSession.ts +224 -16
  72. package/src/models/Toolkits.ts +181 -2
  73. package/src/models/Tools.ts +58 -26
  74. package/src/models/Triggers.ts +10 -90
  75. package/src/models/Usage.ts +119 -0
  76. package/src/models/Webhooks.ts +520 -0
  77. package/src/services/pusher/Pusher.ts +46 -16
  78. package/src/types/authConfigs.types.ts +2 -0
  79. package/src/types/connectedAccounts.types.ts +54 -0
  80. package/src/types/customToolkits.types.ts +102 -0
  81. package/src/types/keyring.types.ts +32 -0
  82. package/src/types/logs.types.ts +108 -0
  83. package/src/types/toolRouter.types.ts +259 -14
  84. package/src/types/toolkit.types.ts +161 -0
  85. package/src/types/usage.types.ts +81 -0
  86. package/src/types/webhooks.types.ts +143 -0
  87. package/src/utils/constants.ts +1 -5
  88. package/src/utils/jsonSchema.ts +4 -1
  89. package/src/utils/logger.ts +39 -7
  90. package/src/utils/sdk.ts +385 -22
  91. package/src/utils/ssrfGuard.node.ts +127 -13
  92. package/src/utils/ssrfGuard.workerd.ts +11 -1
  93. package/src/utils/transformers/connectedAccounts.ts +37 -2
  94. package/src/utils/transformers/customToolkits.ts +98 -0
  95. package/src/utils/transformers/keyring.ts +24 -0
  96. package/src/utils/transformers/logs.ts +85 -0
  97. package/src/utils/transformers/toolkits.ts +183 -3
  98. package/src/utils/transformers/triggers.ts +2 -2
  99. package/src/utils/transformers/usage.ts +77 -0
  100. package/src/utils/transformers/webhooks.ts +139 -0
package/src/utils/sdk.ts CHANGED
@@ -1,12 +1,40 @@
1
- import { ComposioNoAPIKeyError } from '../errors/SDKErrors';
1
+ import { z } from 'zod/v3';
2
+ import {
3
+ ComposioAPIKeyKindError,
4
+ ComposioNoAPIKeyError,
5
+ ComposioScopeConfigError,
6
+ } from '../errors/SDKErrors';
2
7
  import { COMPOSIO_DIR, DEFAULT_BASE_URL, USER_DATA_FILE_NAME } from './constants';
3
8
  import { getEnvsWithPrefix, getEnvVariable } from './env';
4
9
  import logger from './logger';
5
10
  import { ComposioError } from '../errors/ComposioError';
6
11
  import { ToolkitVersion, ToolkitVersionParam, ToolkitVersions } from '../types/tool.types';
12
+ import type { ComposioRequestHeaders } from '../types/composio.types';
7
13
  import { normalizeToolkitSlug } from './toolkitVersion';
8
14
  import { platform } from '#platform';
9
15
 
16
+ /**
17
+ * Header that carries a Composio user API key (`uak_...`) instead of a project
18
+ * API key. It is the only default header the credential resolver reads.
19
+ */
20
+ export const USER_API_KEY_HEADER = 'x-user-api-key';
21
+
22
+ /** Prefix of Composio user API keys as issued by `composio login`. */
23
+ const USER_API_KEY_PREFIX = 'uak_';
24
+
25
+ /**
26
+ * Header that carries the project API key. The SDK only ever sets it from the
27
+ * resolved `apiKey`; a caller-placed entry in `defaultHeaders` is rejected
28
+ * when project-key auth is disabled.
29
+ */
30
+ export const PROJECT_API_KEY_HEADER = 'x-api-key';
31
+
32
+ /** Header carrying the organization nano ID that scopes user-key requests. */
33
+ export const ORG_ID_HEADER = 'x-org-id';
34
+
35
+ /** Header carrying the project nano ID that scopes user-key requests. */
36
+ export const PROJECT_ID_HEADER = 'x-project-id';
37
+
10
38
  // File path helpers
11
39
  export const userDataPath = () => {
12
40
  try {
@@ -22,38 +50,373 @@ export const userDataPath = () => {
22
50
  };
23
51
 
24
52
  /**
25
- * Reads and parses the user data JSON file from the Composio directory.
26
- *
27
- * @returns The parsed user data object containing user configuration (api_key, base_url, etc.), or empty object if file doesn't exist or can't be read
53
+ * Shape of `~/.composio/user_data.json`. The file is written by the Composio
54
+ * CLI; only the two fields the SDK consumes are validated, everything else is
55
+ * carried through untouched.
56
+ */
57
+ const UserDataFileSchema = z
58
+ .object({
59
+ api_key: z.string().nullish(),
60
+ base_url: z.string().nullish(),
61
+ })
62
+ .passthrough();
63
+
64
+ export type UserDataFile = z.infer<typeof UserDataFileSchema>;
65
+
66
+ export type UserDataFileRead =
67
+ /** No file system, no home directory, or no file: nothing to fall back to. */
68
+ | { status: 'missing' }
69
+ /** The file exists but is not JSON or does not have the expected shape. */
70
+ | { status: 'malformed'; path: string; reason: string }
71
+ | { status: 'ok'; path: string; data: UserDataFile };
72
+
73
+ /**
74
+ * Reads and validates the user data JSON file from the Composio directory.
75
+ * File contents never appear in the returned diagnostics.
28
76
  */
29
- export const getUserDataJson = () => {
77
+ export const readUserDataFile = (): UserDataFileRead => {
78
+ if (!platform.supportsFileSystem) {
79
+ return { status: 'missing' };
80
+ }
81
+ const dataPath = userDataPath();
82
+ if (!dataPath) {
83
+ return { status: 'missing' };
84
+ }
85
+
86
+ let raw: string | Uint8Array;
30
87
  try {
31
- const dataPath = userDataPath();
32
- if (!dataPath || !platform.supportsFileSystem) {
33
- return {};
34
- }
35
- const data = platform.readFileSync(dataPath, 'utf8');
36
- return JSON.parse(data as string);
88
+ raw = platform.readFileSync(dataPath, 'utf8');
37
89
  } catch (_error) {
38
90
  logger.debug('Environment', 'No user data file found');
39
- return {};
91
+ return { status: 'missing' };
92
+ }
93
+
94
+ let json: unknown;
95
+ try {
96
+ json = JSON.parse(typeof raw === 'string' ? raw : new TextDecoder().decode(raw));
97
+ } catch (_error) {
98
+ logger.debug('Environment', `User data file at ${dataPath} could not be parsed as JSON`);
99
+ return { status: 'malformed', path: dataPath, reason: 'could not be parsed as JSON' };
100
+ }
101
+
102
+ const parsed = UserDataFileSchema.safeParse(json);
103
+ if (!parsed.success) {
104
+ const fields = parsed.error.issues
105
+ .map(issue => issue.path.join('.'))
106
+ .filter(Boolean)
107
+ .join(', ');
108
+ const reason = fields
109
+ ? `has an unexpected shape (invalid field${fields.includes(',') ? 's' : ''}: ${fields})`
110
+ : 'has an unexpected shape (expected a JSON object)';
111
+ logger.debug('Environment', `User data file at ${dataPath} ${reason}`);
112
+ return { status: 'malformed', path: dataPath, reason };
113
+ }
114
+
115
+ return { status: 'ok', path: dataPath, data: parsed.data };
116
+ };
117
+
118
+ const findHeader = (
119
+ headers: ComposioRequestHeaders | undefined,
120
+ name: string
121
+ ): { name: string; value: string } | undefined => {
122
+ if (!headers) {
123
+ return undefined;
124
+ }
125
+ const wanted = name.toLowerCase();
126
+ for (const [key, value] of Object.entries(headers)) {
127
+ if (key.toLowerCase() === wanted) {
128
+ return { name: key, value };
129
+ }
40
130
  }
131
+ return undefined;
41
132
  };
42
133
 
43
- // Client configuration functions
44
- export function getSDKConfig(baseUrl?: string | null, apiKey?: string | null) {
45
- const userData = getUserDataJson();
46
- const { api_key: apiKeyFromUserConfig, base_url: baseURLFromUserConfig } = userData;
134
+ /**
135
+ * Returns the `x-user-api-key` entry from a header map, if it carries a
136
+ * non-empty value. Matches the header name case-insensitively and ignores
137
+ * every other header.
138
+ */
139
+ export const getUserApiKeyHeader = (
140
+ headers: ComposioRequestHeaders | undefined
141
+ ): { name: string; value: string } | undefined => {
142
+ const header = findHeader(headers, USER_API_KEY_HEADER);
143
+ return header && typeof header.value === 'string' && header.value.length > 0 ? header : undefined;
144
+ };
47
145
 
48
- const baseURLParsed =
49
- baseUrl || getEnvVariable('COMPOSIO_BASE_URL') || baseURLFromUserConfig || DEFAULT_BASE_URL;
50
- const apiKeyParsed = apiKey || getEnvVariable('COMPOSIO_API_KEY') || apiKeyFromUserConfig || '';
146
+ export type CredentialHeaderInput = {
147
+ /** The project API key the client resolved, or `null` when disabled. */
148
+ apiKey: string | null | undefined;
149
+ /** The user API key the client resolved (`userApiKey` option or `COMPOSIO_USER_API_KEY`). */
150
+ userApiKey: string | null | undefined;
151
+ /** The default headers configured on the SDK instance; only `x-user-api-key` is consulted. */
152
+ defaultHeaders: ComposioRequestHeaders | undefined;
153
+ };
154
+
155
+ /**
156
+ * The single credential header that mirrors what the API client puts on the
157
+ * wire for an SDK instance. A non-empty `x-user-api-key` entry in the default
158
+ * headers wins: the client treats a caller-placed credential header as the
159
+ * credential and suppresses the configured keys. Otherwise the project key
160
+ * travels as `x-api-key`, otherwise the resolved user API key as
161
+ * `x-user-api-key`. Empty when no credential is held. The environment is
162
+ * never consulted here.
163
+ */
164
+ export const resolveCredentialHeaders = (input: CredentialHeaderInput): Record<string, string> => {
165
+ const userApiKeyHeader = getUserApiKeyHeader(input.defaultHeaders);
166
+ if (userApiKeyHeader) {
167
+ return { [USER_API_KEY_HEADER]: userApiKeyHeader.value };
168
+ }
169
+ if (hasValue(input.apiKey)) {
170
+ return { [PROJECT_API_KEY_HEADER]: input.apiKey };
171
+ }
172
+ if (hasValue(input.userApiKey)) {
173
+ return { [USER_API_KEY_HEADER]: input.userApiKey };
174
+ }
175
+ return {};
176
+ };
177
+
178
+ export type SDKScopeOptions = {
179
+ /** The `orgId` constructor option. */
180
+ orgId?: string;
181
+ /** The `projectId` constructor option. */
182
+ projectId?: string;
183
+ /** Default headers the SDK will attach to every request. */
184
+ defaultHeaders?: ComposioRequestHeaders;
185
+ };
186
+
187
+ export type SDKScope = {
188
+ orgId?: string;
189
+ projectId?: string;
190
+ };
191
+
192
+ const resolveScopeValue = (
193
+ option: string | undefined,
194
+ headers: ComposioRequestHeaders | undefined,
195
+ headerName: string,
196
+ optionName: 'orgId' | 'projectId'
197
+ ): string | undefined => {
198
+ const header = findHeader(headers, headerName);
199
+ const headerValue = header && header.value.length > 0 ? header.value : undefined;
200
+ const optionValue = hasValue(option) ? option : undefined;
201
+ if (optionValue !== undefined && headerValue !== undefined && optionValue !== headerValue) {
202
+ throw new ComposioScopeConfigError(
203
+ `\`${optionName}\` and the \`${headerName}\` default header disagree`,
204
+ {
205
+ cause: `The ${optionName} option and the ${headerName} entry in defaultHeaders carry different values; the SDK keeps a single scope source`,
206
+ meta: { option: optionName, header: headerName },
207
+ }
208
+ );
209
+ }
210
+ return optionValue ?? headerValue;
211
+ };
212
+
213
+ /**
214
+ * Resolves the organization/project scope of an SDK instance.
215
+ *
216
+ * The scope comes from the `orgId` / `projectId` options, or from the
217
+ * `x-org-id` / `x-project-id` default headers when the options are omitted.
218
+ * A value present in both places must agree, and the two IDs must be supplied
219
+ * together: a user API key without an explicit scope keeps the API default
220
+ * (the developer project), so a half-configured scope is rejected instead of
221
+ * silently selecting a project.
222
+ */
223
+ export function resolveSDKScope(options: SDKScopeOptions): SDKScope {
224
+ const orgId = resolveScopeValue(options.orgId, options.defaultHeaders, ORG_ID_HEADER, 'orgId');
225
+ const projectId = resolveScopeValue(
226
+ options.projectId,
227
+ options.defaultHeaders,
228
+ PROJECT_ID_HEADER,
229
+ 'projectId'
230
+ );
231
+ if ((orgId === undefined) !== (projectId === undefined)) {
232
+ throw new ComposioScopeConfigError(
233
+ orgId === undefined
234
+ ? '`projectId` requires `orgId`: the organization and project nano IDs scope requests together'
235
+ : '`orgId` requires `projectId`: the organization and project nano IDs scope requests together',
236
+ {
237
+ cause: 'Only one of the two scope identifiers was configured',
238
+ meta: { orgId: orgId !== undefined, projectId: projectId !== undefined },
239
+ }
240
+ );
241
+ }
242
+ return orgId === undefined || projectId === undefined ? {} : { orgId, projectId };
243
+ }
244
+
245
+ /** The `x-org-id` / `x-project-id` headers for a resolved scope. */
246
+ export const getScopeHeaders = (scope: SDKScope): ComposioRequestHeaders =>
247
+ scope.orgId && scope.projectId
248
+ ? { [ORG_ID_HEADER]: scope.orgId, [PROJECT_ID_HEADER]: scope.projectId }
249
+ : {};
250
+
251
+ export type SDKConfigOptions = {
252
+ /** Default headers the SDK will attach to every request. */
253
+ defaultHeaders?: ComposioRequestHeaders;
254
+ /**
255
+ * The `userApiKey` constructor option, exactly as the caller passed it:
256
+ * `undefined` lets the API client read `COMPOSIO_USER_API_KEY`, `null`
257
+ * disables that fallback.
258
+ */
259
+ userApiKey?: string | null;
260
+ /**
261
+ * The `orgApiKey` constructor option, exactly as the caller passed it:
262
+ * `undefined` lets the API client read `COMPOSIO_ORG_API_KEY`, `null`
263
+ * disables that fallback.
264
+ */
265
+ orgApiKey?: string | null;
266
+ };
267
+
268
+ export type SDKConfig = {
269
+ baseURL: string;
270
+ /** The project API key to send as `x-api-key`, or `null` when project-key auth is disabled. */
271
+ apiKey: string | null;
272
+ };
273
+
274
+ const hasValue = (value: string | null | undefined): value is string =>
275
+ typeof value === 'string' && value.length > 0;
276
+
277
+ /**
278
+ * Mirrors how the API client resolves `userApiKey` / `orgApiKey`: an explicit
279
+ * value (including `null`) is final, `undefined` falls back to the environment.
280
+ */
281
+ const resolveAlternateCredential = (
282
+ explicit: string | null | undefined,
283
+ envName: string
284
+ ): string | undefined => {
285
+ if (explicit !== undefined) {
286
+ return hasValue(explicit) ? explicit : undefined;
287
+ }
288
+ const fromEnv = getEnvVariable(envName);
289
+ return hasValue(fromEnv) ? fromEnv : undefined;
290
+ };
291
+
292
+ /**
293
+ * The user API key the API client will hold: the `userApiKey` option when it
294
+ * was passed (including `null`, which disables the fallback), otherwise
295
+ * `COMPOSIO_USER_API_KEY`.
296
+ */
297
+ export const resolveUserApiKey = (userApiKey: string | null | undefined): string | undefined =>
298
+ resolveAlternateCredential(userApiKey, 'COMPOSIO_USER_API_KEY');
51
299
 
52
- if (!apiKeyParsed) {
53
- ComposioError.handleAndThrow(new ComposioNoAPIKeyError());
300
+ /**
301
+ * Whether the instance holds a credential other than the project key: a user
302
+ * or organization API key (explicit or environment-resolved, as the API client
303
+ * will see it), or a user API key placed in the default headers.
304
+ */
305
+ const hasAlternateCredential = (options: SDKConfigOptions): boolean =>
306
+ resolveUserApiKey(options.userApiKey) !== undefined ||
307
+ resolveAlternateCredential(options.orgApiKey, 'COMPOSIO_ORG_API_KEY') !== undefined ||
308
+ getUserApiKeyHeader(options.defaultHeaders) !== undefined;
309
+
310
+ /**
311
+ * Resolves the base URL and project API key the SDK will use.
312
+ *
313
+ * Project key resolution distinguishes three caller intents:
314
+ * - a non-empty string is used as-is and nothing else is consulted;
315
+ * - `undefined` (or an empty string) falls back to `COMPOSIO_API_KEY`, then to
316
+ * the `api_key` stored by the CLI in `~/.composio/user_data.json`;
317
+ * - `null` disables project-key auth: neither `COMPOSIO_API_KEY` nor the stored
318
+ * `api_key` is read, and the resolver only succeeds when the instance holds
319
+ * another credential: a `userApiKey` or `orgApiKey` (explicit, or resolved
320
+ * from `COMPOSIO_USER_API_KEY` / `COMPOSIO_ORG_API_KEY` the way the API
321
+ * client does), or a non-empty `x-user-api-key` entry in `defaultHeaders`.
322
+ * An `x-api-key` entry in `defaultHeaders` (any letter case) is rejected in
323
+ * that mode: the project credential is only ever set from `apiKey`.
324
+ *
325
+ * A stored `uak_` user key is never used as a project key: when it is the only
326
+ * candidate the resolver throws a {@link ComposioAPIKeyKindError} that names the
327
+ * problem without echoing the key.
328
+ */
329
+ export function getSDKConfig(
330
+ baseUrl?: string | null,
331
+ apiKey?: string | null,
332
+ options: SDKConfigOptions = {}
333
+ ): SDKConfig {
334
+ let userData: UserDataFileRead | undefined;
335
+ const readUserData = () => {
336
+ userData ??= readUserDataFile();
337
+ return userData;
338
+ };
339
+ const userDataValue = (field: 'api_key' | 'base_url'): string | undefined => {
340
+ const read = readUserData();
341
+ return read.status === 'ok' && hasValue(read.data[field]) ? read.data[field] : undefined;
342
+ };
343
+
344
+ const resolveApiKey = (): string | null => {
345
+ if (apiKey === null) {
346
+ const projectKeyHeader = findHeader(options.defaultHeaders, PROJECT_API_KEY_HEADER);
347
+ if (projectKeyHeader) {
348
+ throw new ComposioNoAPIKeyError(
349
+ `Project API key resolution is disabled, but \`defaultHeaders\` carries a \`${projectKeyHeader.name}\` entry`,
350
+ {
351
+ cause:
352
+ '`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',
353
+ possibleFixes: [
354
+ `Pass the project API key via \`apiKey\` instead of a raw \`${PROJECT_API_KEY_HEADER}\` default header`,
355
+ `Remove the \`${projectKeyHeader.name}\` entry from \`defaultHeaders\` to authenticate with the user or organization API key alone`,
356
+ ],
357
+ }
358
+ );
359
+ }
360
+ if (hasAlternateCredential(options)) {
361
+ return null;
362
+ }
363
+ throw new ComposioNoAPIKeyError('Project API key resolution is disabled', {
364
+ cause:
365
+ '`apiKey: null` turns off the COMPOSIO_API_KEY and user config file fallbacks, and no user or organization API key was configured',
366
+ possibleFixes: [
367
+ 'Pass a project API key via `apiKey`, or omit it to fall back to COMPOSIO_API_KEY',
368
+ 'To authenticate with a user API key instead, keep `apiKey: null` and pass `userApiKey` (or set COMPOSIO_USER_API_KEY)',
369
+ `Alternatively, keep \`apiKey: null\` and set the \`${USER_API_KEY_HEADER}\` default header`,
370
+ ],
371
+ });
372
+ }
373
+
374
+ if (hasValue(apiKey)) {
375
+ return apiKey;
376
+ }
377
+
378
+ const envApiKey = getEnvVariable('COMPOSIO_API_KEY');
379
+ if (hasValue(envApiKey)) {
380
+ return envApiKey;
381
+ }
382
+
383
+ const read = readUserData();
384
+ const storedApiKey = userDataValue('api_key');
385
+ if (read.status === 'ok' && hasValue(storedApiKey)) {
386
+ if (storedApiKey.startsWith(USER_API_KEY_PREFIX)) {
387
+ throw new ComposioAPIKeyKindError(undefined, {
388
+ 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`,
389
+ meta: { userDataFilePath: read.path },
390
+ });
391
+ }
392
+ return storedApiKey;
393
+ }
394
+
395
+ if (read.status === 'malformed') {
396
+ throw new ComposioNoAPIKeyError('No Composio API key provided', {
397
+ cause: `No API key was passed in the params or in COMPOSIO_API_KEY, and the user config file at ${read.path} ${read.reason}`,
398
+ });
399
+ }
400
+ throw new ComposioNoAPIKeyError();
401
+ };
402
+
403
+ let apiKeyParsed: string | null;
404
+ try {
405
+ apiKeyParsed = resolveApiKey();
406
+ } catch (error) {
407
+ ComposioError.handleAndThrow(error);
54
408
  }
55
409
 
56
- logger.debug('Environment', 'API Key: [REDACTED]');
410
+ const baseURLParsed =
411
+ (hasValue(baseUrl) ? baseUrl : undefined) ??
412
+ getEnvVariable('COMPOSIO_BASE_URL') ??
413
+ userDataValue('base_url') ??
414
+ DEFAULT_BASE_URL;
415
+
416
+ logger.debug(
417
+ 'Environment',
418
+ apiKeyParsed === null ? 'API Key: [DISABLED]' : 'API Key: [REDACTED]'
419
+ );
57
420
  logger.debug('Environment', `Base URL: ${baseURLParsed}`);
58
421
 
59
422
  return { baseURL: baseURLParsed, apiKey: apiKeyParsed };
@@ -27,7 +27,7 @@ import {
27
27
  * to a public address during validation and rebind to an internal one before
28
28
  * the connect — a TOCTOU window the Python guard closes the same way.
29
29
  *
30
- * Residual: a hop whose effective dispatcher is a configured route — a
30
+ * By default, a hop whose effective dispatcher is a configured route — a
31
31
  * caller-supplied `init.dispatcher`, a non-stock global dispatcher (a
32
32
  * `ProxyAgent` or `EnvHttpProxyAgent` installed via `setGlobalDispatcher`), or
33
33
  * the runtime's env-proxy mode (automatic on Bun, opt-in via
@@ -35,11 +35,90 @@ import {
35
35
  * pre-flight validation. Pinning would dial the validated address instead of
36
36
  * the proxy, and the proxy resolves the hostname itself where the SDK cannot
37
37
  * see or pin that resolution. The Python guard carries the same residual for
38
- * the same reason (`_proxy_applies`).
38
+ * the same reason (`_proxy_applies`). Callers that cannot accept that residual
39
+ * can set `requirePinnedConnection`, which fails closed before fetching.
39
40
  */
40
41
 
41
42
  const MAX_REDIRECTS = 5;
42
43
 
44
+ export interface SsrfSafeFetchOptions {
45
+ /** Maximum number of redirects to follow. Defaults to 5. */
46
+ maxRedirects?: number;
47
+ /**
48
+ * Refuse a request when a configured dispatcher or environment proxy means
49
+ * the connection cannot be pinned to the address validated by the guard.
50
+ */
51
+ requirePinnedConnection?: boolean;
52
+ }
53
+
54
+ /**
55
+ * The Fetch standard's "redirect status" set. A 3xx outside it is not a
56
+ * redirect to follow even when it carries a `location` — `304 Not Modified`
57
+ * and `305 Use Proxy` most of all, and following those would replay the
58
+ * request against a target the caller never asked for. The Python guard
59
+ * follows the same set (`_REDIRECT_STATUS_CODES`).
60
+ */
61
+ const REDIRECT_STATUS_CODES = new Set([301, 302, 303, 307, 308]);
62
+
63
+ /**
64
+ * Headers that describe a request body, so they have to go when the body does:
65
+ * the Fetch standard's "request-body-header name" set, plus the two the Python
66
+ * guard also drops because `requests` recomputes them from the body it sends.
67
+ */
68
+ const BODY_HEADERS = [
69
+ 'content-encoding',
70
+ 'content-language',
71
+ 'content-length',
72
+ 'content-location',
73
+ 'content-type',
74
+ 'transfer-encoding',
75
+ ];
76
+
77
+ /**
78
+ * The method the hop after a redirect uses, or `null` to replay as-is. A
79
+ * returned method also means the request body goes.
80
+ *
81
+ * These are the Fetch standard's redirect rules, which following redirects by
82
+ * hand (`redirect: 'manual'`) means `fetch` never applies for us: `303` points
83
+ * at a result URL that has no use for the original body, so every method loses
84
+ * it and everything but `HEAD` becomes a `GET`; `301`/`302` do the same to a
85
+ * `POST` only; `307`/`308` replay both. Without this, a `303` answering an
86
+ * upload would PUT the payload again at a URL that expects a GET. The Python
87
+ * guard applies the same rules in `safe_request`.
88
+ */
89
+ const redirectRewrite = (status: number, method: string): string | null => {
90
+ if (status === 303) return method === 'HEAD' ? 'HEAD' : 'GET';
91
+ if ((status === 301 || status === 302) && method === 'POST') return 'GET';
92
+ return null;
93
+ };
94
+
95
+ /**
96
+ * Headers that carry a credential for the origin the request was addressed
97
+ * to, so they must not follow a redirect to a different origin. The Fetch
98
+ * standard strips `Authorization` on a cross-origin redirect; `Cookie` and
99
+ * `Proxy-Authorization` go with it the way `requests` and curl drop them on a
100
+ * host change. `redirect: 'manual'` means `fetch` never applies that rule for
101
+ * us either. The Python guard drops the same three (`_CREDENTIAL_HEADERS`).
102
+ */
103
+ const CREDENTIAL_HEADERS = ['authorization', 'cookie', 'proxy-authorization'];
104
+
105
+ const applyRedirectSemantics = (
106
+ init: RequestInit,
107
+ status: number,
108
+ fromUrl: string,
109
+ toUrl: string
110
+ ): RequestInit => {
111
+ const method = redirectRewrite(status, (init.method ?? 'GET').toUpperCase());
112
+ const crossOrigin = new URL(fromUrl).origin !== new URL(toUrl).origin;
113
+ if (method === null && !crossOrigin) return init;
114
+
115
+ const headers = new Headers(init.headers);
116
+ if (method !== null) for (const name of BODY_HEADERS) headers.delete(name);
117
+ if (crossOrigin) for (const name of CREDENTIAL_HEADERS) headers.delete(name);
118
+ if (method === null) return { ...init, headers };
119
+ return { ...init, method, body: undefined, headers };
120
+ };
121
+
43
122
  /**
44
123
  * Whether the runtime would route `url` through an env proxy the SDK cannot
45
124
  * see into. Bun honors proxy environment variables automatically. Node's
@@ -77,6 +156,7 @@ const IPV4_BLOCKED_CIDRS: ReadonlyArray<readonly [string, number]> = [
77
156
  ['172.16.0.0', 12], // private
78
157
  ['192.0.0.0', 24], // IETF protocol assignments
79
158
  ['192.0.2.0', 24], // TEST-NET-1
159
+ ['192.88.99.0', 24], // 6to4 relay anycast (deprecated, RFC 7526)
80
160
  ['192.168.0.0', 16], // private
81
161
  ['198.18.0.0', 15], // benchmarking
82
162
  ['198.51.100.0', 24], // TEST-NET-2
@@ -146,8 +226,20 @@ const isBlockedIpv6 = (ip: string): boolean => {
146
226
  return isBlockedIpv4Long((((h[6] << 16) >>> 0) | h[7]) >>> 0);
147
227
  }
148
228
 
229
+ // Transition and tunnel ranges. Each one either carries an arbitrary IPv4
230
+ // address in its low bits or is reserved, so a public-looking literal here
231
+ // can still name internal space: `2002:7f00:1::` is 6to4 for `127.0.0.1`.
232
+ // Blocking the whole range rather than decoding it matches the Python guard,
233
+ // where `ipaddress.is_global` already rejects all of them.
234
+ if (h[0] === 0x2001 && (h[1] & 0xfe00) === 0) return true; // IETF protocol assignments 2001::/23 (incl. Teredo)
235
+ if (h[0] === 0x2001 && h[1] === 0x0db8) return true; // documentation 2001:db8::/32
236
+ if (h[0] === 0x2002) return true; // 6to4 2002::/16
237
+ if (h[0] === 0x0064 && h[1] === 0xff9b && h[2] === 0x0001) return true; // local-use NAT64 64:ff9b:1::/48
238
+ if (h[0] === 0x0100 && h[1] === 0 && h[2] === 0 && h[3] === 0) return true; // discard-only 100::/64
239
+
149
240
  if ((h[0] & 0xfe00) === 0xfc00) return true; // unique local fc00::/7
150
241
  if ((h[0] & 0xffc0) === 0xfe80) return true; // link-local fe80::/10
242
+ if ((h[0] & 0xffc0) === 0xfec0) return true; // site-local fec0::/10 (deprecated)
151
243
  if ((h[0] & 0xff00) === 0xff00) return true; // multicast ff00::/8
152
244
 
153
245
  return false;
@@ -221,18 +313,27 @@ export const assertSafeFetchTarget = async (rawUrl: string): Promise<string[]> =
221
313
  * connects to the address it validated, and re-validates and re-pins every
222
314
  * redirect hop (redirects are followed manually up to {@link MAX_REDIRECTS}).
223
315
  * Intermediate redirect bodies are cancelled; non-redirect responses are
224
- * returned unchanged.
316
+ * returned unchanged. Each hop carries the method, body, and credential headers
317
+ * the Fetch standard says it should — see {@link applyRedirectSemantics}.
225
318
  *
226
- * A hop whose effective dispatcher is a configured route (caller-supplied
227
- * `init.dispatcher`, non-stock global dispatcher, env-proxy mode) is *not*
228
- * pinned — see the module residual above.
319
+ * By default, a hop whose effective dispatcher is a configured route
320
+ * (caller-supplied `init.dispatcher`, non-stock global dispatcher, env-proxy
321
+ * mode) is *not* pinned. Set `requirePinnedConnection` to fail closed instead.
229
322
  */
230
323
  export const ssrfSafeFetch = async (
231
324
  rawUrl: string,
232
325
  init: RequestInit = {},
233
- maxRedirects: number = MAX_REDIRECTS
326
+ optionsOrMaxRedirects: SsrfSafeFetchOptions | number = {}
234
327
  ): Promise<Response> => {
328
+ const options =
329
+ typeof optionsOrMaxRedirects === 'number'
330
+ ? { maxRedirects: optionsOrMaxRedirects }
331
+ : optionsOrMaxRedirects;
332
+ const maxRedirects = options.maxRedirects ?? MAX_REDIRECTS;
235
333
  let currentUrl = rawUrl;
334
+ // Rebound per hop: a redirect can drop the method and body (see
335
+ // `applyRedirectSemantics`), and the following hops must send what is left.
336
+ let currentInit = init;
236
337
 
237
338
  for (let hop = 0; hop <= maxRedirects; hop++) {
238
339
  const addresses = await assertSafeFetchTarget(currentUrl);
@@ -241,26 +342,37 @@ export const ssrfSafeFetch = async (
241
342
  // Pinning replaces the connect target; through a configured route that
242
343
  // would dial the validated origin instead of the route's next hop (the
243
344
  // proxy), so those hops keep the pre-flight check only.
244
- const callerDispatcher = (init as RequestInit & { dispatcher?: unknown }).dispatcher;
345
+ const callerDispatcher = (currentInit as RequestInit & { dispatcher?: unknown }).dispatcher;
245
346
  const respectConfiguredRoute =
246
347
  callerDispatcher !== undefined ||
247
348
  envProxyApplies(new URL(currentUrl), isBun) ||
248
349
  hasCustomGlobalDispatcher();
249
350
 
351
+ if (options.requirePinnedConnection && respectConfiguredRoute) {
352
+ throw new ComposioBlockedInternalUrlError(
353
+ 'Refusing to fetch through a configured network route because the validated address cannot be pinned',
354
+ { url: currentUrl }
355
+ );
356
+ }
357
+
250
358
  const dispatcher =
251
359
  respectConfiguredRoute || isBun ? undefined : await createPinnedDispatcher(addresses);
252
360
 
253
361
  let response: Response;
254
362
  try {
255
363
  if (isBun && !respectConfiguredRoute) {
256
- response = await pinnedHttpFetch(currentUrl, { ...init, redirect: 'manual' }, addresses);
364
+ response = await pinnedHttpFetch(
365
+ currentUrl,
366
+ { ...currentInit, redirect: 'manual' },
367
+ addresses
368
+ );
257
369
  } else {
258
370
  // `dispatcher` is a Node-only extension to `RequestInit`.
259
371
  response = await fetch(
260
372
  currentUrl,
261
373
  (dispatcher === undefined
262
- ? { ...init, redirect: 'manual' }
263
- : { ...init, redirect: 'manual', dispatcher }) as RequestInit
374
+ ? { ...currentInit, redirect: 'manual' }
375
+ : { ...currentInit, redirect: 'manual', dispatcher }) as RequestInit
264
376
  );
265
377
  }
266
378
  } catch (error) {
@@ -277,7 +389,7 @@ export const ssrfSafeFetch = async (
277
389
  }
278
390
 
279
391
  const isRedirect =
280
- response.status >= 300 && response.status < 400 && response.headers.has('location');
392
+ REDIRECT_STATUS_CODES.has(response.status) && response.headers.has('location');
281
393
  if (!isRedirect) {
282
394
  return response;
283
395
  }
@@ -286,7 +398,9 @@ export const ssrfSafeFetch = async (
286
398
  // than leaving it to the garbage collector (mirrors `readResponseBodyWithLimit`).
287
399
  await response.body?.cancel().catch(() => undefined);
288
400
 
289
- currentUrl = new URL(response.headers.get('location')!, currentUrl).toString();
401
+ const nextUrl = new URL(response.headers.get('location')!, currentUrl).toString();
402
+ currentInit = applyRedirectSemantics(currentInit, response.status, currentUrl, nextUrl);
403
+ currentUrl = nextUrl;
290
404
  }
291
405
 
292
406
  throw new ComposioBlockedInternalUrlError(
@@ -1,5 +1,15 @@
1
1
  import { ComposioBlockedInternalUrlError } from '../errors/SsrfErrors';
2
2
 
3
+ export interface SsrfSafeFetchOptions {
4
+ /** Maximum number of redirects to follow. Defaults to 5. */
5
+ maxRedirects?: number;
6
+ /**
7
+ * Refuse a request when a configured dispatcher or environment proxy means
8
+ * the connection cannot be pinned to the address validated by the guard.
9
+ */
10
+ requirePinnedConnection?: boolean;
11
+ }
12
+
3
13
  /**
4
14
  * Edge runtimes do not expose the DNS resolution APIs needed to prove that a
5
15
  * hostname is publicly routable before connecting. Fail closed instead of
@@ -8,7 +18,7 @@ import { ComposioBlockedInternalUrlError } from '../errors/SsrfErrors';
8
18
  export const ssrfSafeFetch = async (
9
19
  rawUrl: string,
10
20
  _init: RequestInit = {},
11
- _maxRedirects?: number
21
+ _optionsOrMaxRedirects: SsrfSafeFetchOptions | number = {}
12
22
  ): Promise<Response> => {
13
23
  throw new ComposioBlockedInternalUrlError(
14
24
  'URL file uploads are not supported in edge runtimes because the destination cannot be safely validated',