@composio/core 0.18.0 → 0.19.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.
- package/dist/{CustomTool-C4tv-GL1.mjs → CustomTool-BMlZfJVz.mjs} +16 -6
- package/dist/{CustomTool-BKhHv2hJ.d.mts → CustomTool-CB5vm1Jc.d.mts} +1 -1
- package/dist/{FileModifierErrors-B8V8_3VE.mjs → FileModifierErrors-BqFmpRsm.mjs} +1 -1
- package/dist/{FileToolModifier.utils.neutral-D_YkHwZP.mjs → FileToolModifier.utils.neutral-DWFpnsj2.mjs} +4 -2
- package/dist/{SsrfErrors-DNJt57GL.mjs → SsrfErrors-C91YhASE.mjs} +137 -13
- package/dist/{Telemetry-CBtSnWrm.mjs → Telemetry-HlftxMx6.mjs} +2 -34
- package/dist/{cancellation-jUVItfHw.mjs → cancellation-CXpfmiVo.mjs} +7 -5
- package/dist/{composio-CldtZUyC.d.mts → composio-DLGaeN70.d.mts} +333 -32
- package/dist/{customTool.types-DC5fPOOi.d.mts → customTool.types-BAmEh3MB.d.mts} +131 -38
- package/dist/docs/reference/sdk-reference/typescript/auth-configs.mdx +2 -2
- package/dist/docs/reference/sdk-reference/typescript/composio.mdx +3 -13
- package/dist/docs/reference/sdk-reference/typescript/session.mdx +50 -6
- package/dist/docs/reference/sdk-reference/typescript/toolkits.mdx +4 -4
- package/dist/docs/reference/sdk-reference/typescript/tools.mdx +33 -23
- package/dist/docs/reference/sdk-reference/typescript/triggers.mdx +3 -2
- package/dist/{errors-DyZt79fi.mjs → errors-BuEKehbI.mjs} +23 -3
- package/dist/experimental/index.d.mts +2 -2
- package/dist/experimental/index.mjs +1 -1
- package/dist/{fileUtils.node-BwpUOF0s.mjs → fileUtils.node-L7XD8UPr.mjs} +11 -9
- package/dist/index.d.mts +164 -104
- package/dist/index.mjs +382 -153
- package/dist/models/Files.node.d.mts +2 -3
- package/dist/models/Files.node.mjs +2 -2
- package/dist/models/Files.workerd.d.mts +2 -3
- package/dist/platform/node.d.mts +2 -3
- package/dist/platform/workerd.d.mts +2 -3
- package/dist/{sensitiveFileUploadPaths-B0w8dqpv.mjs → sensitiveFileUploadPaths-B6pBt9lO.mjs} +10 -7
- package/dist/{ssrfGuard.node-DlxO8uzr.mjs → ssrfGuard.node-B9xQB4za.mjs} +197 -30
- package/dist/{types-BgsRW-XH.d.mts → types-CxLPO0Xq.d.mts} +2 -2
- package/dist/utils/config-defaults/ConfigDefaults.node.d.mts +3 -4
- package/dist/utils/config-defaults/ConfigDefaults.workerd.d.mts +3 -4
- package/dist/utils/modifiers/FileToolModifier.node.d.mts +3 -4
- package/dist/utils/modifiers/FileToolModifier.node.mjs +6 -6
- package/dist/utils/modifiers/FileToolModifier.workerd.d.mts +3 -4
- package/dist/utils/modifiers/FileToolModifier.workerd.mjs +1 -1
- package/dist/utils/ssrfGuard.node.d.mts +19 -10
- package/dist/utils/ssrfGuard.node.mjs +1 -1
- package/dist/utils/ssrfGuard.workerd.d.mts +12 -4
- package/dist/utils/ssrfGuard.workerd.mjs +2 -2
- package/package.json +26 -8
- package/src/errors/ToolErrors.ts +24 -0
- package/src/index.ts +4 -0
- package/src/models/CustomTool.ts +41 -6
- package/src/models/MCP.ts +29 -15
- package/src/models/RemoteFile.ts +54 -36
- package/src/models/ToolRouter.ts +1 -0
- package/src/models/ToolRouterSession.ts +115 -13
- package/src/models/Toolkits.ts +1 -2
- package/src/models/Tools.ts +55 -25
- package/src/models/Triggers.ts +22 -2
- package/src/services/pusher/Pusher.ts +29 -10
- package/src/telemetry/redact.ts +133 -6
- package/src/types/toolRouter.types.ts +54 -3
- package/src/types/toolkit.types.ts +17 -0
- package/src/utils/fileUtils.node.ts +10 -2
- package/src/utils/jsonSchema.ts +4 -1
- package/src/utils/logger.ts +6 -6
- package/src/utils/pinnedDispatcher.node.ts +109 -13
- package/src/utils/sdk.ts +1 -1
- package/src/utils/ssrfGuard.node.ts +153 -27
- package/src/utils/ssrfGuard.workerd.ts +15 -1
- package/src/utils/transformers/toolkits.ts +79 -2
package/src/models/Tools.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import ComposioClient from '@composio/client';
|
|
1
|
+
import ComposioClient, { APIError } from '@composio/client';
|
|
2
2
|
import { FileToolModifier } from '#file_tool_modifier';
|
|
3
3
|
import {
|
|
4
4
|
Tool,
|
|
@@ -42,6 +42,7 @@ import logger from '../utils/logger';
|
|
|
42
42
|
import { ExecuteToolFn, GlobalExecuteToolFn } from '../types/provider.types';
|
|
43
43
|
import {
|
|
44
44
|
ComposioInvalidModifierError,
|
|
45
|
+
ComposioToolFetchError,
|
|
45
46
|
ComposioToolNotFoundError,
|
|
46
47
|
ComposioProviderNotDefinedError,
|
|
47
48
|
ComposioToolVersionRequiredError,
|
|
@@ -710,7 +711,17 @@ export class Tools<
|
|
|
710
711
|
if (error instanceof ComposioRequestCancelledError) {
|
|
711
712
|
throw error;
|
|
712
713
|
}
|
|
713
|
-
|
|
714
|
+
// The tools endpoint reports an unknown slug as 404 (or 400 for a
|
|
715
|
+
// malformed one). Anything else (401, 5xx, network) is not "not found",
|
|
716
|
+
// so keep the client error reachable as `cause` under a generic error.
|
|
717
|
+
if (error instanceof APIError && (error.status === 404 || error.status === 400)) {
|
|
718
|
+
throw new ComposioToolNotFoundError(`Tool with slug ${slug} not found`, {
|
|
719
|
+
meta: { slug },
|
|
720
|
+
cause: error,
|
|
721
|
+
});
|
|
722
|
+
}
|
|
723
|
+
throw new ComposioToolFetchError(`Unable to retrieve tool with slug ${slug}`, {
|
|
724
|
+
meta: { slug },
|
|
714
725
|
cause: error,
|
|
715
726
|
});
|
|
716
727
|
}
|
|
@@ -1097,6 +1108,10 @@ export class Tools<
|
|
|
1097
1108
|
*
|
|
1098
1109
|
* @example Execute with a specific version (recommended for production)
|
|
1099
1110
|
* ```typescript
|
|
1111
|
+
* // Look up the tool's current version once, then pin that string in your code or config
|
|
1112
|
+
* const { version } = await composio.tools.getRawComposioToolBySlug('GITHUB_GET_REPOS');
|
|
1113
|
+
* console.log(version); // e.g. '20250909_00'
|
|
1114
|
+
*
|
|
1100
1115
|
* const result = await composio.tools.execute('GITHUB_GET_REPOS', {
|
|
1101
1116
|
* userId: 'default',
|
|
1102
1117
|
* version: '20250909_00',
|
|
@@ -1283,21 +1298,27 @@ export class Tools<
|
|
|
1283
1298
|
}
|
|
1284
1299
|
|
|
1285
1300
|
/**
|
|
1286
|
-
*
|
|
1301
|
+
* Generates arguments for a tool from a natural-language description of the task.
|
|
1287
1302
|
*
|
|
1288
|
-
*
|
|
1303
|
+
* Composio uses an LLM to fill the tool's input parameters from `text`. Review the
|
|
1304
|
+
* generated arguments before passing them to `tools.execute()`.
|
|
1289
1305
|
*
|
|
1290
|
-
* @param {string} slug - The
|
|
1291
|
-
* @param {ToolGetInputParams} body - The
|
|
1292
|
-
* @
|
|
1306
|
+
* @param {string} slug - The slug of the tool to generate arguments for
|
|
1307
|
+
* @param {ToolGetInputParams} body - The generation request
|
|
1308
|
+
* @param {string} body.text - What you want the tool to do, in natural language
|
|
1309
|
+
* @param {string} [body.custom_description] - Extra context about the tool for the LLM
|
|
1310
|
+
* @param {string} [body.system_prompt] - System prompt that steers the LLM
|
|
1311
|
+
* @param {string} [body.version] - Tool version to generate arguments for
|
|
1312
|
+
* @returns {Promise<ToolGetInputResponse>} The generated `arguments`, or an `error` when generation fails
|
|
1293
1313
|
*
|
|
1294
1314
|
* @example
|
|
1295
1315
|
* ```typescript
|
|
1296
|
-
*
|
|
1297
|
-
*
|
|
1298
|
-
*
|
|
1316
|
+
* const { arguments: args, error } = await composio.tools.getInput('GITHUB_CREATE_ISSUE', {
|
|
1317
|
+
* text: 'Open an issue in composiohq/composio titled "Docs typo" describing the broken link',
|
|
1318
|
+
* version: '20250909_00',
|
|
1299
1319
|
* });
|
|
1300
|
-
*
|
|
1320
|
+
* if (error) throw new Error(error);
|
|
1321
|
+
* console.log(args); // { owner: 'composiohq', repo: 'composio', title: 'Docs typo', ... }
|
|
1301
1322
|
* ```
|
|
1302
1323
|
*/
|
|
1303
1324
|
async getInput(
|
|
@@ -1312,26 +1333,35 @@ export class Tools<
|
|
|
1312
1333
|
}
|
|
1313
1334
|
|
|
1314
1335
|
/**
|
|
1315
|
-
*
|
|
1336
|
+
* Sends an HTTP request to a toolkit's API, authenticated as a connected account.
|
|
1316
1337
|
*
|
|
1317
|
-
*
|
|
1318
|
-
*
|
|
1338
|
+
* Use it to call an endpoint that no predefined tool covers. Composio injects the
|
|
1339
|
+
* connected account's credentials on the server side.
|
|
1319
1340
|
*
|
|
1320
|
-
*
|
|
1321
|
-
*
|
|
1341
|
+
* A relative `endpoint` is appended to the toolkit's base URL, and that base URL can
|
|
1342
|
+
* already include a path. Google Calendar's base URL is
|
|
1343
|
+
* `https://www.googleapis.com/calendar/v3`, so pass `/users/me/calendarList`, not
|
|
1344
|
+
* `/calendar/v3/users/me/calendarList` (which resolves to `/calendar/v3/calendar/v3/...`
|
|
1345
|
+
* and returns a 404 from Google). An absolute URL on the same domain is sent as-is.
|
|
1346
|
+
*
|
|
1347
|
+
* @param {ToolProxyParams} body - The proxy request
|
|
1348
|
+
* @param {string} body.endpoint - Path relative to the toolkit's base URL, or an absolute URL
|
|
1349
|
+
* @param {'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'} body.method - HTTP method
|
|
1350
|
+
* @param {string} [body.connectedAccountId] - The connected account to authenticate as
|
|
1351
|
+
* @param {unknown} [body.body] - JSON request body
|
|
1352
|
+
* @param {Array<{ in: 'query' | 'header'; name: string; value: string | number }>} [body.parameters] - Extra query parameters or headers
|
|
1353
|
+
* @returns {Promise<ToolProxyResponse>} The upstream status, headers, and parsed body
|
|
1322
1354
|
*
|
|
1323
1355
|
* @example
|
|
1324
1356
|
* ```typescript
|
|
1325
|
-
* //
|
|
1326
|
-
* const
|
|
1327
|
-
*
|
|
1328
|
-
*
|
|
1329
|
-
*
|
|
1330
|
-
*
|
|
1331
|
-
* method: 'GET'
|
|
1332
|
-
* }
|
|
1357
|
+
* // Google Calendar's base URL is https://www.googleapis.com/calendar/v3
|
|
1358
|
+
* const { status, data } = await composio.tools.proxyExecute({
|
|
1359
|
+
* endpoint: '/users/me/calendarList',
|
|
1360
|
+
* method: 'GET',
|
|
1361
|
+
* connectedAccountId: 'ca_...',
|
|
1362
|
+
* parameters: [{ in: 'query', name: 'maxResults', value: 10 }],
|
|
1333
1363
|
* });
|
|
1334
|
-
* console.log(
|
|
1364
|
+
* console.log(status, data);
|
|
1335
1365
|
* ```
|
|
1336
1366
|
*/
|
|
1337
1367
|
async proxyExecute(
|
package/src/models/Triggers.ts
CHANGED
|
@@ -558,6 +558,21 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
|
|
|
558
558
|
return false;
|
|
559
559
|
}
|
|
560
560
|
|
|
561
|
+
// Check if authConfigId filter matches.
|
|
562
|
+
// Only V3 trigger payloads (and the legacy TriggerData shape) carry an auth config id;
|
|
563
|
+
// V1/V2 payloads and non-trigger V3 events normalize it to '', so this filter drops
|
|
564
|
+
// those events entirely. This mirrors the Python SDK's `auth_config_id` filter.
|
|
565
|
+
if (
|
|
566
|
+
filters.authConfigId &&
|
|
567
|
+
filters.authConfigId !== data.metadata.connectedAccount.authConfigId
|
|
568
|
+
) {
|
|
569
|
+
logger.debug(
|
|
570
|
+
'Trigger does not match authConfigId filter',
|
|
571
|
+
JSON.stringify(filters.authConfigId, null, 2)
|
|
572
|
+
);
|
|
573
|
+
return false;
|
|
574
|
+
}
|
|
575
|
+
|
|
561
576
|
// Check if triggerName filter matches
|
|
562
577
|
if (
|
|
563
578
|
filters.triggerSlug?.length &&
|
|
@@ -597,6 +612,10 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
|
|
|
597
612
|
*
|
|
598
613
|
* @param fn - The function to call when a trigger is received
|
|
599
614
|
* @param filters - The filters to apply to the triggers
|
|
615
|
+
* @param onSubscriptionError - Optional callback invoked with the raw Pusher payload when
|
|
616
|
+
* the underlying subscription fails (for example on auth or permission rejection). The
|
|
617
|
+
* subscribe promise still resolves; this is the only programmatic signal of the failure.
|
|
618
|
+
* Errors thrown from — or promises rejected by — the callback are contained and logged.
|
|
600
619
|
*
|
|
601
620
|
* @example
|
|
602
621
|
* ```ts
|
|
@@ -608,7 +627,8 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
|
|
|
608
627
|
*/
|
|
609
628
|
async subscribe(
|
|
610
629
|
fn: (_data: IncomingTriggerPayload) => void,
|
|
611
|
-
filters: TriggerSubscribeParams = {}
|
|
630
|
+
filters: TriggerSubscribeParams = {},
|
|
631
|
+
onSubscriptionError?: (data: Record<string, unknown>) => void
|
|
612
632
|
) {
|
|
613
633
|
if (!fn) throw new Error('Function is required for trigger subscription');
|
|
614
634
|
|
|
@@ -636,7 +656,7 @@ export class Triggers<TProvider extends BaseComposioProvider<unknown, unknown, u
|
|
|
636
656
|
} else {
|
|
637
657
|
logger.debug('Trigger does not match filters', JSON.stringify(parsedFilters.data, null, 2));
|
|
638
658
|
}
|
|
639
|
-
});
|
|
659
|
+
}, onSubscriptionError);
|
|
640
660
|
}
|
|
641
661
|
|
|
642
662
|
/**
|
|
@@ -162,22 +162,43 @@ export class PusherService {
|
|
|
162
162
|
* @param channelName - The name of the Pusher channel to subscribe to
|
|
163
163
|
* @param event - The event to subscribe to
|
|
164
164
|
* @param fn - The function to call when the event is received
|
|
165
|
+
* @param onSubscriptionError - Optional callback invoked with the raw payload when the
|
|
166
|
+
* Pusher subscription fails (for example on auth or permission rejection). Errors thrown
|
|
167
|
+
* from — or promises rejected by — this callback are contained and logged, never rethrown.
|
|
165
168
|
*/
|
|
166
|
-
async subscribe(
|
|
169
|
+
async subscribe(
|
|
170
|
+
fn: (data: Record<string, unknown>) => void,
|
|
171
|
+
onSubscriptionError?: (data: Record<string, unknown>) => void
|
|
172
|
+
) {
|
|
167
173
|
try {
|
|
168
174
|
logger.debug(`[PusherService] Subscribing to channel: ${this.pusherChannel}`);
|
|
169
175
|
const pusherClient = await this.getPusherClient();
|
|
170
176
|
const channel = await pusherClient.subscribe(this.pusherChannel);
|
|
171
177
|
|
|
172
178
|
// add subscription error handling
|
|
179
|
+
const logCallbackFailure = (callbackError: unknown) => {
|
|
180
|
+
const errorMessage =
|
|
181
|
+
callbackError instanceof Error ? callbackError.message : String(callbackError);
|
|
182
|
+
logger.error('❌ Error in subscription error callback:', errorMessage);
|
|
183
|
+
};
|
|
173
184
|
channel.bind('pusher:subscription_error', (data: Record<string, unknown>) => {
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
185
|
+
logger.error('Trigger subscription error:', data);
|
|
186
|
+
|
|
187
|
+
// surface the failure to the caller without letting a faulty
|
|
188
|
+
// handler crash the host (same containment as the trigger callback).
|
|
189
|
+
// A handler may be async: contain rejected promises too, or the
|
|
190
|
+
// rejection escapes as an unhandled rejection after subscribe()
|
|
191
|
+
// already resolved.
|
|
192
|
+
try {
|
|
193
|
+
Promise.resolve(onSubscriptionError?.(data)).catch(logCallbackFailure);
|
|
194
|
+
} catch (callbackError: unknown) {
|
|
195
|
+
logCallbackFailure(callbackError);
|
|
196
|
+
}
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
// log success only when Pusher itself confirms the subscription
|
|
200
|
+
channel.bind('pusher:subscription_succeeded', () => {
|
|
201
|
+
logger.info(`✅ Subscribed to triggers. You should start receiving events now.`);
|
|
181
202
|
});
|
|
182
203
|
|
|
183
204
|
// wrap the callback to handle errors
|
|
@@ -192,8 +213,6 @@ export class PusherService {
|
|
|
192
213
|
};
|
|
193
214
|
|
|
194
215
|
this.bindWithChunking(channel as PusherClient, 'trigger_to_client', safeCallback);
|
|
195
|
-
|
|
196
|
-
logger.info(`✅ Subscribed to triggers. You should start receiving events now.`);
|
|
197
216
|
} catch (error) {
|
|
198
217
|
throw new ComposioFailedToSubscribeToPusherChannelError(
|
|
199
218
|
'Failed to subscribe to Pusher channel',
|
package/src/telemetry/redact.ts
CHANGED
|
@@ -13,6 +13,33 @@
|
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
15
|
const REDACTED = '[REDACTED]';
|
|
16
|
+
const SECRET_KEY_PATTERN = String.raw`authorization|auth|api[-_]?key|apikey|x-api-key|access[-_]?token|refresh[-_]?token|client[-_]?secret|secret|password|passwd|pwd`;
|
|
17
|
+
const SECRET_KEY_WITH_PREFIX_PATTERN = String.raw`(?:[A-Za-z0-9]+_)*(?:${SECRET_KEY_PATTERN})`;
|
|
18
|
+
const QUOTED_SECRET_KEY_PREFIX = String.raw`(["'])(${SECRET_KEY_WITH_PREFIX_PATTERN})\1(\s*[:=]+\s*)`;
|
|
19
|
+
const BARE_SECRET_KEY_PREFIX = String.raw`(?<![A-Za-z0-9"'])(${SECRET_KEY_PATTERN})\b(\s*[:=]+\s*)`;
|
|
20
|
+
const ESCAPED_SECRET_KEY_PREFIX = String.raw`(?<![A-Za-z0-9])(${SECRET_KEY_PATTERN})\b((?:\\["'])?\s*[:=]+\s*)`;
|
|
21
|
+
const SECRET_PAIR_PREFIX = String.raw`(?<![A-Za-z0-9])(${SECRET_KEY_PATTERN})\b(["']?\s*[:=]+\s*)`;
|
|
22
|
+
const BARE_KEY_DOUBLE_QUOTED_VALUE = new RegExp(
|
|
23
|
+
String.raw`${BARE_SECRET_KEY_PREFIX}"((?:\\.|[^"\\\r\n])*)"`,
|
|
24
|
+
'gi'
|
|
25
|
+
);
|
|
26
|
+
const BARE_KEY_SINGLE_QUOTED_VALUE = new RegExp(
|
|
27
|
+
String.raw`${BARE_SECRET_KEY_PREFIX}'((?:\\.|[^'\\\r\n])*)'`,
|
|
28
|
+
'gi'
|
|
29
|
+
);
|
|
30
|
+
const BARE_KEY_ESCAPED_DOUBLE_QUOTED_VALUE = new RegExp(
|
|
31
|
+
String.raw`${ESCAPED_SECRET_KEY_PREFIX}\\"((?:\\.|[^"\\\r\n])*)\\"`,
|
|
32
|
+
'gi'
|
|
33
|
+
);
|
|
34
|
+
const BARE_KEY_ESCAPED_SINGLE_QUOTED_VALUE = new RegExp(
|
|
35
|
+
String.raw`${ESCAPED_SECRET_KEY_PREFIX}\\'((?:\\.|[^'\\\r\n])*)\\'`,
|
|
36
|
+
'gi'
|
|
37
|
+
);
|
|
38
|
+
const SECRET_PAIR_UNQUOTED = new RegExp(
|
|
39
|
+
String.raw`${SECRET_PAIR_PREFIX}(?!\\["'])([^\s"',}&]+)`,
|
|
40
|
+
'gi'
|
|
41
|
+
);
|
|
42
|
+
const CONTAINS_QUOTED_FIELD = /(?:^|[,{\s])(["'])[^"'\\\r\n]+\1\s*[:=]\s*$/;
|
|
16
43
|
|
|
17
44
|
const REDACTION_RULES: ReadonlyArray<readonly [RegExp, string]> = [
|
|
18
45
|
// URL query strings — tokens, presigned signatures, one-time codes.
|
|
@@ -20,17 +47,113 @@ const REDACTION_RULES: ReadonlyArray<readonly [RegExp, string]> = [
|
|
|
20
47
|
// Authorization scheme + credential: `Bearer <token>`, `Basic <token>`.
|
|
21
48
|
[/\b(bearer|basic)\s+[A-Za-z0-9._~+/=-]+/gi, `$1 ${REDACTED}`],
|
|
22
49
|
// Secret-ish `key: value` / `key=value` / `key: "value"` / `key: 'value'` pairs.
|
|
23
|
-
//
|
|
24
|
-
//
|
|
25
|
-
// between the name and the colon.
|
|
50
|
+
// Match quoted keys separately so key-like prose cannot treat an enclosing
|
|
51
|
+
// string's closing quote as the start of a secret value.
|
|
26
52
|
// Leading lookbehind (not \b) so env-style names like COMPOSIO_API_KEY still
|
|
27
53
|
// match: underscore is a word char, so \b can't fire between COMPOSIO_ and API.
|
|
28
54
|
[
|
|
29
|
-
|
|
30
|
-
`$1$2$3${REDACTED}
|
|
55
|
+
new RegExp(String.raw`${QUOTED_SECRET_KEY_PREFIX}"(?:\\.|[^"\\\r\n])*"`, 'gi'),
|
|
56
|
+
`$1$2$1$3"${REDACTED}"`,
|
|
57
|
+
],
|
|
58
|
+
[
|
|
59
|
+
new RegExp(String.raw`${QUOTED_SECRET_KEY_PREFIX}'(?:\\.|[^'\\\r\n])*'`, 'gi'),
|
|
60
|
+
`$1$2$1$3'${REDACTED}'`,
|
|
31
61
|
],
|
|
32
62
|
];
|
|
33
63
|
|
|
64
|
+
const isWordCharacter = (character: string): boolean => /[\p{L}\p{N}_]/u.test(character);
|
|
65
|
+
|
|
66
|
+
const activeQuotesAt = (
|
|
67
|
+
input: string,
|
|
68
|
+
offsets: ReadonlySet<number>
|
|
69
|
+
): ReadonlyMap<number, '"' | "'" | undefined> => {
|
|
70
|
+
const activeQuotes = new Map<number, '"' | "'" | undefined>();
|
|
71
|
+
let quote: '"' | "'" | undefined;
|
|
72
|
+
let escaped = false;
|
|
73
|
+
let lastOffset = -1;
|
|
74
|
+
for (const offset of offsets) lastOffset = Math.max(lastOffset, offset);
|
|
75
|
+
|
|
76
|
+
for (let position = 0; position < input.length; position += 1) {
|
|
77
|
+
const character = input[position];
|
|
78
|
+
if (offsets.has(position)) {
|
|
79
|
+
activeQuotes.set(position, quote);
|
|
80
|
+
if (position === lastOffset) break;
|
|
81
|
+
}
|
|
82
|
+
if (character === '\n' || character === '\r') {
|
|
83
|
+
quote = undefined;
|
|
84
|
+
escaped = false;
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
const previous =
|
|
88
|
+
position > 0 && !['\n', '\r'].includes(input[position - 1]) ? input[position - 1] : '';
|
|
89
|
+
const following = input[position + 1] ?? '';
|
|
90
|
+
if (!quote) {
|
|
91
|
+
if (character === '"' || (character === "'" && !isWordCharacter(previous))) {
|
|
92
|
+
quote = character;
|
|
93
|
+
}
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
if (escaped) escaped = false;
|
|
97
|
+
else if (character === '\\') escaped = true;
|
|
98
|
+
else if (character === quote) {
|
|
99
|
+
if (quote === "'" && isWordCharacter(previous) && isWordCharacter(following)) continue;
|
|
100
|
+
quote = undefined;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return activeQuotes;
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
const completesQuotedFieldAt = (input: string, index: number, quote: '"' | "'"): boolean => {
|
|
108
|
+
let escaped = false;
|
|
109
|
+
for (let position = index; position < input.length; position += 1) {
|
|
110
|
+
const character = input[position];
|
|
111
|
+
if (character === '\n' || character === '\r') return false;
|
|
112
|
+
if (escaped) {
|
|
113
|
+
escaped = false;
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
if (character === '\\') {
|
|
117
|
+
escaped = true;
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
if (character !== quote) continue;
|
|
121
|
+
|
|
122
|
+
let separator = position + 1;
|
|
123
|
+
while (separator < input.length && /\s/.test(input[separator])) separator += 1;
|
|
124
|
+
return input[separator] === ':' || input[separator] === '=';
|
|
125
|
+
}
|
|
126
|
+
return false;
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
const redactBareQuotedValue = (input: string, pattern: RegExp, quote: '"' | "'"): string => {
|
|
130
|
+
pattern.lastIndex = 0;
|
|
131
|
+
const matches = Array.from(input.matchAll(pattern));
|
|
132
|
+
if (matches.length === 0) return input;
|
|
133
|
+
|
|
134
|
+
const activeQuotes = activeQuotesAt(input, new Set(matches.map(match => match.index)));
|
|
135
|
+
const parts: string[] = [];
|
|
136
|
+
let cursor = 0;
|
|
137
|
+
|
|
138
|
+
for (const match of matches) {
|
|
139
|
+
const offset = match.index;
|
|
140
|
+
parts.push(input.slice(cursor, offset));
|
|
141
|
+
if (
|
|
142
|
+
activeQuotes.get(offset) === quote &&
|
|
143
|
+
(completesQuotedFieldAt(input, offset + match[0].length, quote) ||
|
|
144
|
+
CONTAINS_QUOTED_FIELD.test(match[3]))
|
|
145
|
+
) {
|
|
146
|
+
parts.push(match[0]);
|
|
147
|
+
} else {
|
|
148
|
+
parts.push(`${match[1]}${match[2]}${quote}${REDACTED}${quote}`);
|
|
149
|
+
}
|
|
150
|
+
cursor = offset + match[0].length;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
parts.push(input.slice(cursor));
|
|
154
|
+
return parts.join('');
|
|
155
|
+
};
|
|
156
|
+
|
|
34
157
|
/**
|
|
35
158
|
* Redact common secret shapes from a free-form string. Returns the input
|
|
36
159
|
* unchanged when it is empty or `undefined`.
|
|
@@ -41,5 +164,9 @@ export const redactSensitiveText = (input: string | undefined): string | undefin
|
|
|
41
164
|
for (const [pattern, replacement] of REDACTION_RULES) {
|
|
42
165
|
output = output.replace(pattern, replacement);
|
|
43
166
|
}
|
|
44
|
-
|
|
167
|
+
output = output.replace(BARE_KEY_ESCAPED_DOUBLE_QUOTED_VALUE, `$1$2\\"${REDACTED}\\"`);
|
|
168
|
+
output = output.replace(BARE_KEY_ESCAPED_SINGLE_QUOTED_VALUE, `$1$2\\'${REDACTED}\\'`);
|
|
169
|
+
output = redactBareQuotedValue(output, BARE_KEY_DOUBLE_QUOTED_VALUE, '"');
|
|
170
|
+
output = redactBareQuotedValue(output, BARE_KEY_SINGLE_QUOTED_VALUE, "'");
|
|
171
|
+
return output.replace(SECRET_PAIR_UNQUOTED, `$1$2${REDACTED}`);
|
|
45
172
|
};
|
|
@@ -5,6 +5,7 @@ import { ConnectionRequest } from './connectionRequest.types';
|
|
|
5
5
|
import type { ComposioRequestOptions } from './requestOptions.types';
|
|
6
6
|
import type { ToolRouterSessionFilesMount } from '../models/ToolRouterSessionFileMount';
|
|
7
7
|
import type { SessionCreateResponse } from '@composio/client/resources/tool-router/session/session.mjs';
|
|
8
|
+
import { ConnectedAccountExperimentalSchema } from './connectedAccounts.types';
|
|
8
9
|
import type {
|
|
9
10
|
CustomTool,
|
|
10
11
|
CustomToolkit,
|
|
@@ -591,7 +592,9 @@ export type ToolRouterSessionExecuteFn = (
|
|
|
591
592
|
|
|
592
593
|
export interface ToolRouterSessionExecuteOptions {
|
|
593
594
|
/**
|
|
594
|
-
* Account identifier for direct app tool execution
|
|
595
|
+
* Account identifier for direct app tool execution. Accepted on every project:
|
|
596
|
+
* in multi-account sessions it picks the account; on single-account projects it
|
|
597
|
+
* must match one of the session's active connections for the toolkit.
|
|
595
598
|
* Meta/helper tools either ignore this top-level field or define
|
|
596
599
|
* their own account-selection fields, for example
|
|
597
600
|
* COMPOSIO_MULTI_EXECUTE_TOOL.tools[].account.
|
|
@@ -605,7 +608,16 @@ export type ToolRouterSessionWorkbenchConfig = SessionCreateResponse.Config.Work
|
|
|
605
608
|
|
|
606
609
|
export type ToolRouterSessionWarning = SessionCreateResponse.Warning;
|
|
607
610
|
|
|
611
|
+
/**
|
|
612
|
+
* Server-side session configuration as returned by the API: toolkit and tool
|
|
613
|
+
* allowlists, tags, auth configs, connected accounts, manage_connections,
|
|
614
|
+
* preload, sandbox (`workbench`), search and execute settings.
|
|
615
|
+
*/
|
|
616
|
+
export type ToolRouterSessionConfig = SessionCreateResponse.Config;
|
|
617
|
+
|
|
608
618
|
export interface ToolRouterSessionMetadata {
|
|
619
|
+
/** Present on every session built from an API response; the constructor synthesises a minimal config when absent. */
|
|
620
|
+
config?: ToolRouterSessionConfig;
|
|
609
621
|
preload?: ToolRouterSessionPreloadConfig;
|
|
610
622
|
workbench?: ToolRouterSessionWorkbenchConfig;
|
|
611
623
|
configVersion?: number;
|
|
@@ -699,7 +711,9 @@ export const ToolRouterUpdateSessionConfigSchema = z
|
|
|
699
711
|
|
|
700
712
|
export type ToolRouterUpdateSessionConfig = z.infer<typeof ToolRouterUpdateSessionConfigSchema>;
|
|
701
713
|
|
|
702
|
-
export type ToolRouterSessionUpdateFn = (
|
|
714
|
+
export type ToolRouterSessionUpdateFn = (
|
|
715
|
+
config: ToolRouterUpdateSessionConfig
|
|
716
|
+
) => Promise<ToolRouterSessionConfig>;
|
|
703
717
|
|
|
704
718
|
export const ToolRouterSessionDeleteResponseSchema = z.object({
|
|
705
719
|
sessionId: z.string(),
|
|
@@ -711,6 +725,35 @@ export type ToolRouterSessionDeleteFn = (
|
|
|
711
725
|
requestOptions?: ComposioRequestOptions
|
|
712
726
|
) => Promise<ToolRouterSessionDeleteResponse>;
|
|
713
727
|
|
|
728
|
+
export const ToolRouterSessionEnsureConnectedOptionsSchema = z.object({
|
|
729
|
+
callbackUrl: z.string().optional(),
|
|
730
|
+
alias: z.string().optional(),
|
|
731
|
+
experimental: ConnectedAccountExperimentalSchema.optional(),
|
|
732
|
+
/** Max time to wait for a newly-initiated connection to become active, in milliseconds. Defaults to 60000. */
|
|
733
|
+
timeout: z.number().int().positive().optional(),
|
|
734
|
+
});
|
|
735
|
+
export type ToolRouterSessionEnsureConnectedOptions = z.infer<
|
|
736
|
+
typeof ToolRouterSessionEnsureConnectedOptionsSchema
|
|
737
|
+
>;
|
|
738
|
+
|
|
739
|
+
export type ToolRouterSessionEnsureConnectedResult = {
|
|
740
|
+
/** Canonical slug of the toolkit this call ensured. */
|
|
741
|
+
toolkit: string;
|
|
742
|
+
/** True when the session already had an active connection (or a no-auth toolkit) — no link was created. */
|
|
743
|
+
wasConnected: boolean;
|
|
744
|
+
/** The active connected account backing the toolkit. Omitted for no-auth toolkits. */
|
|
745
|
+
connectedAccount?: {
|
|
746
|
+
id: string;
|
|
747
|
+
status: string;
|
|
748
|
+
};
|
|
749
|
+
};
|
|
750
|
+
|
|
751
|
+
export type ToolRouterSessionEnsureConnectedFn = (
|
|
752
|
+
toolkit: string,
|
|
753
|
+
options?: ToolRouterSessionEnsureConnectedOptions,
|
|
754
|
+
requestOptions?: ComposioRequestOptions
|
|
755
|
+
) => Promise<ToolRouterSessionEnsureConnectedResult>;
|
|
756
|
+
|
|
714
757
|
/** Session type returned by ToolRouter.create() and ToolRouter.use() */
|
|
715
758
|
export interface Session<
|
|
716
759
|
TToolCollection,
|
|
@@ -719,6 +762,12 @@ export interface Session<
|
|
|
719
762
|
> {
|
|
720
763
|
sessionId: string;
|
|
721
764
|
mcp: ToolRouterMCPServerConfig;
|
|
765
|
+
/**
|
|
766
|
+
* Server-side session configuration (toolkit/tool allowlists, tags, preload,
|
|
767
|
+
* sandbox, manage_connections) as returned by the API. Refreshed in place by
|
|
768
|
+
* `update()`.
|
|
769
|
+
*/
|
|
770
|
+
config: ToolRouterSessionConfig;
|
|
722
771
|
/** Stored preload configuration for this session. */
|
|
723
772
|
preload: ToolRouterSessionPreloadConfig;
|
|
724
773
|
/**
|
|
@@ -739,12 +788,14 @@ export interface Session<
|
|
|
739
788
|
warnings: ToolRouterSessionWarning[];
|
|
740
789
|
tools: ToolRouterToolsFn<TToolCollection, TTool, TProvider>;
|
|
741
790
|
authorize: ToolRouterAuthorizeFn;
|
|
791
|
+
/** Ensure a toolkit has an active connection, linking and waiting only when needed. */
|
|
792
|
+
ensureConnected: ToolRouterSessionEnsureConnectedFn;
|
|
742
793
|
toolkits: ToolRouterToolkitsFn;
|
|
743
794
|
/** Search for tools by semantic use case */
|
|
744
795
|
search: ToolRouterSessionSearchFn;
|
|
745
796
|
/** Execute a tool within the session */
|
|
746
797
|
execute: ToolRouterSessionExecuteFn;
|
|
747
|
-
/** Update the session configuration. Mutates this session in-place
|
|
798
|
+
/** Update the session configuration. Mutates this session in-place and resolves to the updated `config`. */
|
|
748
799
|
update: ToolRouterSessionUpdateFn;
|
|
749
800
|
/** Delete the session. Deleted sessions are no longer retrievable or executable. */
|
|
750
801
|
delete: ToolRouterSessionDeleteFn;
|
|
@@ -66,10 +66,27 @@ export const ToolkitAuthFieldSchema = z.object({
|
|
|
66
66
|
name: z.string(),
|
|
67
67
|
type: z.string(),
|
|
68
68
|
default: z.string().nullable().optional(),
|
|
69
|
+
/**
|
|
70
|
+
* Whether this field holds a secret/credential value. Clients use it to
|
|
71
|
+
* decide whether to mask the input when collecting the value in their own
|
|
72
|
+
* UI. The property is absent when the API omits the flag for the field.
|
|
73
|
+
*/
|
|
74
|
+
isSecret: z.boolean().optional(),
|
|
75
|
+
/**
|
|
76
|
+
* The legacy template name the API reports for this field, mapped from
|
|
77
|
+
* `legacy_template_name`. The API declares it as an optional string without
|
|
78
|
+
* further documenting its semantics.
|
|
79
|
+
*/
|
|
80
|
+
legacyTemplateName: z.string().optional(),
|
|
69
81
|
});
|
|
70
82
|
export const ToolkitAuthConfigDetailsSchema = z.object({
|
|
71
83
|
name: z.string(),
|
|
72
84
|
mode: z.string(),
|
|
85
|
+
/**
|
|
86
|
+
* URL to a page where users can obtain or configure credentials for this
|
|
87
|
+
* authentication method, e.g. `https://github.com/settings/tokens`.
|
|
88
|
+
*/
|
|
89
|
+
authHintUrl: z.string().nullable().optional(),
|
|
73
90
|
fields: z.object({
|
|
74
91
|
authConfigCreation: z.object({
|
|
75
92
|
optional: z.array(ToolkitAuthFieldSchema),
|
|
@@ -340,6 +340,7 @@ export const downloadFileFromS3 = async ({
|
|
|
340
340
|
mimeType,
|
|
341
341
|
fileDownloadDir,
|
|
342
342
|
signal,
|
|
343
|
+
maxDownloadBytes,
|
|
343
344
|
}: {
|
|
344
345
|
toolSlug: string;
|
|
345
346
|
s3Url: string;
|
|
@@ -350,6 +351,11 @@ export const downloadFileFromS3 = async ({
|
|
|
350
351
|
*/
|
|
351
352
|
fileDownloadDir?: string;
|
|
352
353
|
signal?: AbortSignal;
|
|
354
|
+
/**
|
|
355
|
+
* Maximum number of bytes to read from the response before rejecting.
|
|
356
|
+
* Defaults to {@link MAX_URL_UPLOAD_SIZE_BYTES} (100 MiB).
|
|
357
|
+
*/
|
|
358
|
+
maxDownloadBytes?: number;
|
|
353
359
|
}): Promise<FileDownloadData> => {
|
|
354
360
|
// SSRF guard: `s3Url` is a field of the tool-execution response, so it is no
|
|
355
361
|
// more trusted than a user-supplied URL — and the bytes it returns are
|
|
@@ -358,11 +364,13 @@ export const downloadFileFromS3 = async ({
|
|
|
358
364
|
if (!response.ok) {
|
|
359
365
|
throw new Error(`Failed to download file: ${response.statusText}`);
|
|
360
366
|
}
|
|
361
|
-
|
|
367
|
+
// The response is attacker-influencable and streamed to disk, so the body is
|
|
368
|
+
// read through the shared size guard rather than buffered wholesale.
|
|
369
|
+
const data = await readResponseBodyWithLimit(response, maxDownloadBytes);
|
|
362
370
|
|
|
363
371
|
const extension = getExtensionFromMimeType(mimeType);
|
|
364
372
|
const fileName = generateTimestampedFilename(extension, `${toolSlug}_`);
|
|
365
|
-
const filePath = saveFile(fileName,
|
|
373
|
+
const filePath = saveFile(fileName, data, {
|
|
366
374
|
isTempFile: fileDownloadDir === undefined,
|
|
367
375
|
outputDir: fileDownloadDir,
|
|
368
376
|
});
|
package/src/utils/jsonSchema.ts
CHANGED
|
@@ -495,7 +495,10 @@ export function jsonSchemaToZodSchema<T extends z.ZodTypeAny>(
|
|
|
495
495
|
const zodSchema = jsonSchemaToZod(schema) as T;
|
|
496
496
|
return zodSchema;
|
|
497
497
|
} catch (error) {
|
|
498
|
-
|
|
498
|
+
// The cause names the offending property path; surface it in the message
|
|
499
|
+
// so a single malformed property is identifiable without unwrapping.
|
|
500
|
+
const detail = error instanceof Error ? `: ${error.message}` : '';
|
|
501
|
+
throw new JsonSchemaToZodError(`Failed to convert JSON Schema to Zod Schema${detail}`, {
|
|
499
502
|
cause: error,
|
|
500
503
|
});
|
|
501
504
|
}
|
package/src/utils/logger.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import pc from 'picocolors';
|
|
2
|
-
import { getEnvVariable } from './env';
|
|
3
2
|
import { COMPOSIO_LOG_LEVEL } from './constants';
|
|
3
|
+
import { redactSensitiveText } from '../telemetry/redact';
|
|
4
4
|
|
|
5
5
|
// Define log levels with corresponding priorities
|
|
6
6
|
export const LOG_LEVELS = {
|
|
@@ -28,7 +28,7 @@ interface LoggerOptions {
|
|
|
28
28
|
includeTimestamp?: boolean;
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
-
class Logger {
|
|
31
|
+
export class Logger {
|
|
32
32
|
private readonly level: LogLevel;
|
|
33
33
|
private readonly includeTimestamp: boolean;
|
|
34
34
|
private readonly console: Console;
|
|
@@ -57,12 +57,12 @@ class Logger {
|
|
|
57
57
|
})
|
|
58
58
|
.join('\n');
|
|
59
59
|
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
60
|
+
const redactedArgs = redactSensitiveText(formattedArgs) ?? formattedArgs;
|
|
61
|
+
|
|
62
|
+
if (!this.includeTimestamp) return redactedArgs;
|
|
63
63
|
|
|
64
64
|
const timestamp = new Date().toISOString();
|
|
65
|
-
return `${pc.gray(timestamp)} - ${
|
|
65
|
+
return `${pc.gray(timestamp)} - ${redactedArgs}`;
|
|
66
66
|
}
|
|
67
67
|
|
|
68
68
|
private shouldLog(level: LogLevel): boolean {
|