@composio/core 0.18.0 → 0.18.1
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-Bz0f52QR.mjs} +16 -6
- package/dist/{CustomTool-BKhHv2hJ.d.mts → CustomTool-VRfWzMix.d.mts} +1 -1
- package/dist/{FileModifierErrors-B8V8_3VE.mjs → FileModifierErrors-CwB-Inm9.mjs} +1 -1
- package/dist/{SsrfErrors-DNJt57GL.mjs → SsrfErrors-xhdVE4yw.mjs} +123 -3
- package/dist/{Telemetry-CBtSnWrm.mjs → Telemetry-Dw9W5RSp.mjs} +2 -34
- package/dist/{cancellation-jUVItfHw.mjs → cancellation-P5YUlcfz.mjs} +2 -2
- package/dist/{composio-CldtZUyC.d.mts → composio-Cb3d1jFe.d.mts} +7 -7
- package/dist/{customTool.types-DC5fPOOi.d.mts → customTool.types-B6ej_8XZ.d.mts} +36 -34
- package/dist/docs/reference/sdk-reference/typescript/session.mdx +4 -3
- package/dist/{errors-DyZt79fi.mjs → errors-Ue9wMrPK.mjs} +2 -2
- package/dist/experimental/index.d.mts +2 -2
- package/dist/experimental/index.mjs +1 -1
- package/dist/{fileUtils.node-BwpUOF0s.mjs → fileUtils.node-KE5Fa-af.mjs} +7 -7
- package/dist/index.d.mts +7 -6
- package/dist/index.mjs +54 -34
- package/dist/models/Files.node.mjs +2 -2
- package/dist/{sensitiveFileUploadPaths-B0w8dqpv.mjs → sensitiveFileUploadPaths-QN7w4n8v.mjs} +1 -1
- package/dist/{ssrfGuard.node-DlxO8uzr.mjs → ssrfGuard.node-BLX6b-Rf.mjs} +96 -19
- package/dist/{types-BgsRW-XH.d.mts → types-CGdgK442.d.mts} +2 -2
- package/dist/utils/config-defaults/ConfigDefaults.node.d.mts +1 -1
- package/dist/utils/config-defaults/ConfigDefaults.workerd.d.mts +1 -1
- package/dist/utils/modifiers/FileToolModifier.node.d.mts +1 -1
- package/dist/utils/modifiers/FileToolModifier.node.mjs +5 -5
- package/dist/utils/modifiers/FileToolModifier.workerd.d.mts +1 -1
- package/dist/utils/ssrfGuard.node.mjs +1 -1
- package/dist/utils/ssrfGuard.workerd.d.mts +1 -1
- package/dist/utils/ssrfGuard.workerd.mjs +2 -2
- package/package.json +20 -2
- package/src/models/CustomTool.ts +41 -6
- package/src/models/RemoteFile.ts +54 -36
- package/src/models/ToolRouterSession.ts +9 -4
- package/src/models/Triggers.ts +15 -0
- package/src/telemetry/redact.ts +133 -6
- package/src/utils/fileUtils.node.ts +10 -2
- 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 +29 -17
- package/src/utils/ssrfGuard.workerd.ts +5 -1
package/src/models/CustomTool.ts
CHANGED
|
@@ -514,7 +514,11 @@ export function buildCustomToolsMapFromResponse(
|
|
|
514
514
|
}
|
|
515
515
|
}
|
|
516
516
|
|
|
517
|
-
const findHandle = (
|
|
517
|
+
const findHandle = (
|
|
518
|
+
finalSlug: string,
|
|
519
|
+
originalSlug: string,
|
|
520
|
+
toolkit?: string
|
|
521
|
+
): HandleMatch | undefined => {
|
|
518
522
|
const originalSlugKey = originalSlug.toUpperCase();
|
|
519
523
|
const qualifiedMatch = handlesByQualifiedOriginalSlug.get(
|
|
520
524
|
qualifiedOriginalSlugKey(toolkit, originalSlugKey)
|
|
@@ -522,13 +526,26 @@ export function buildCustomToolsMapFromResponse(
|
|
|
522
526
|
if (qualifiedMatch) return qualifiedMatch;
|
|
523
527
|
|
|
524
528
|
const bareMatches = handlesByOriginalSlug.get(originalSlugKey) ?? [];
|
|
525
|
-
|
|
529
|
+
// Response tool not defined locally; nothing to route in-process.
|
|
530
|
+
if (bareMatches.length === 0) return undefined;
|
|
531
|
+
// A bare match may only stand in when the response carries no toolkit identity.
|
|
532
|
+
// Binding a toolkit child to another toolkit's handler would silently execute
|
|
533
|
+
// the wrong implementation.
|
|
534
|
+
if (toolkit === undefined && bareMatches.length === 1) return bareMatches[0];
|
|
535
|
+
|
|
536
|
+
const registered = [
|
|
537
|
+
...new Set(bareMatches.map(m => (m.toolkit ?? 'custom').toUpperCase())),
|
|
538
|
+
].sort();
|
|
539
|
+
throw new ValidationError(
|
|
540
|
+
`Cannot map custom tool "${finalSlug}": original slug "${originalSlug}" for toolkit ` +
|
|
541
|
+
`"${toolkit ?? 'custom'}" has no exact local match. Registered for toolkits: ${registered.join(', ')}.`
|
|
542
|
+
);
|
|
526
543
|
};
|
|
527
544
|
|
|
528
545
|
const addEntry = (finalSlug: string, originalSlug: string, toolkit?: string | null) => {
|
|
529
546
|
const resolvedToolkit = toolkit ?? undefined;
|
|
530
|
-
const match = findHandle(originalSlug, resolvedToolkit);
|
|
531
|
-
if (!match) return;
|
|
547
|
+
const match = findHandle(finalSlug, originalSlug, resolvedToolkit);
|
|
548
|
+
if (!match) return;
|
|
532
549
|
|
|
533
550
|
const finalSlugKey = finalSlug.toUpperCase();
|
|
534
551
|
if (byFinalSlug.has(finalSlugKey)) {
|
|
@@ -537,13 +554,21 @@ export function buildCustomToolsMapFromResponse(
|
|
|
537
554
|
);
|
|
538
555
|
}
|
|
539
556
|
|
|
557
|
+
const entryToolkit = resolvedToolkit ?? match.toolkit;
|
|
558
|
+
const qualifiedKey = qualifiedOriginalSlugKey(entryToolkit, originalSlug);
|
|
559
|
+
if (byToolkitAndOriginalSlug.has(qualifiedKey)) {
|
|
560
|
+
throw new ValidationError(
|
|
561
|
+
`Custom tool slug collision: original slug "${match.handle.slug}" is already registered for toolkit "${entryToolkit ?? 'custom'}".`
|
|
562
|
+
);
|
|
563
|
+
}
|
|
564
|
+
|
|
540
565
|
const entry: CustomToolsMapEntry = {
|
|
541
566
|
handle: match.handle,
|
|
542
567
|
finalSlug,
|
|
543
|
-
toolkit:
|
|
568
|
+
toolkit: entryToolkit,
|
|
544
569
|
};
|
|
545
570
|
byFinalSlug.set(finalSlugKey, entry);
|
|
546
|
-
byToolkitAndOriginalSlug.set(
|
|
571
|
+
byToolkitAndOriginalSlug.set(qualifiedKey, entry);
|
|
547
572
|
addOriginalSlugAlias({ byOriginalSlug, ambiguousOriginalSlugs, originalSlug, entry });
|
|
548
573
|
};
|
|
549
574
|
|
|
@@ -563,6 +588,16 @@ export function buildCustomToolsMapFromResponse(
|
|
|
563
588
|
}
|
|
564
589
|
}
|
|
565
590
|
|
|
591
|
+
// Ambiguity follows the local definitions, not whichever subset the response
|
|
592
|
+
// happened to include: a shared child slug must never become callable by its
|
|
593
|
+
// bare name just because a sibling was omitted.
|
|
594
|
+
for (const [originalSlugKey, matches] of handlesByOriginalSlug) {
|
|
595
|
+
if (matches.length > 1) {
|
|
596
|
+
byOriginalSlug.delete(originalSlugKey);
|
|
597
|
+
ambiguousOriginalSlugs.add(originalSlugKey);
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
|
|
566
601
|
return {
|
|
567
602
|
byFinalSlug,
|
|
568
603
|
byOriginalSlug,
|
package/src/models/RemoteFile.ts
CHANGED
|
@@ -8,7 +8,12 @@ function getParentDir(filePath: string): string {
|
|
|
8
8
|
return filePath.slice(0, lastSep);
|
|
9
9
|
}
|
|
10
10
|
import { RemoteFileData, RemoteFileDataSchema } from '../types/ToolRouterSessionFilesMount.types';
|
|
11
|
-
import {
|
|
11
|
+
import {
|
|
12
|
+
ComposioBlockedInternalUrlError,
|
|
13
|
+
RemoteFileDownloadError,
|
|
14
|
+
ValidationError,
|
|
15
|
+
} from '../errors';
|
|
16
|
+
import { readResponseBodyWithLimit } from '../utils/readResponseBody';
|
|
12
17
|
|
|
13
18
|
/**
|
|
14
19
|
* Represents a file stored in a tool router session's file mount.
|
|
@@ -77,31 +82,58 @@ export class RemoteFile {
|
|
|
77
82
|
return platform.basename(this.mountRelativePath);
|
|
78
83
|
}
|
|
79
84
|
|
|
85
|
+
private downloadError(message: string, cause: unknown, response?: Response) {
|
|
86
|
+
return new RemoteFileDownloadError(message, {
|
|
87
|
+
statusCode: response?.status,
|
|
88
|
+
statusText: response?.statusText,
|
|
89
|
+
downloadUrl: this.downloadUrl,
|
|
90
|
+
mountRelativePath: this.mountRelativePath,
|
|
91
|
+
filename: this.filename,
|
|
92
|
+
cause,
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
private async downloadBytes(): Promise<{ content: Uint8Array; contentType: string }> {
|
|
97
|
+
let response: Response;
|
|
98
|
+
try {
|
|
99
|
+
response = await ssrfSafeFetchWhereSupported(this.downloadUrl);
|
|
100
|
+
} catch (error) {
|
|
101
|
+
if (error instanceof ComposioBlockedInternalUrlError) {
|
|
102
|
+
throw error;
|
|
103
|
+
}
|
|
104
|
+
throw this.downloadError('Failed to download file', error);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
if (!response.ok) {
|
|
108
|
+
await response.body?.cancel().catch(() => undefined);
|
|
109
|
+
throw this.downloadError(
|
|
110
|
+
`Failed to download file: ${response.status} ${response.statusText}`,
|
|
111
|
+
new Error(`HTTP ${response.status}: ${response.statusText}`),
|
|
112
|
+
response
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
try {
|
|
117
|
+
const content = response.body
|
|
118
|
+
? await readResponseBodyWithLimit(response)
|
|
119
|
+
: new Uint8Array(await response.arrayBuffer());
|
|
120
|
+
return {
|
|
121
|
+
content,
|
|
122
|
+
contentType: response.headers?.get?.('content-type') ?? '',
|
|
123
|
+
};
|
|
124
|
+
} catch (error) {
|
|
125
|
+
await response.body?.cancel().catch(() => undefined);
|
|
126
|
+
throw this.downloadError('Failed to read downloaded file', error, response);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
80
130
|
/**
|
|
81
131
|
* Fetches the file content as a buffer.
|
|
82
132
|
* @returns The file content as a Uint8Array
|
|
83
133
|
* @throws RemoteFileDownloadError if the fetch fails
|
|
84
134
|
*/
|
|
85
135
|
async buffer(): Promise<Uint8Array> {
|
|
86
|
-
|
|
87
|
-
// input like every other response field, and its bytes are handed straight
|
|
88
|
-
// back to the caller. See ssrfGuard.node.ts.
|
|
89
|
-
const response = await ssrfSafeFetchWhereSupported(this.downloadUrl);
|
|
90
|
-
if (!response.ok) {
|
|
91
|
-
throw new RemoteFileDownloadError(
|
|
92
|
-
`Failed to download file: ${response.status} ${response.statusText}`,
|
|
93
|
-
{
|
|
94
|
-
statusCode: response.status,
|
|
95
|
-
statusText: response.statusText,
|
|
96
|
-
downloadUrl: this.downloadUrl,
|
|
97
|
-
mountRelativePath: this.mountRelativePath,
|
|
98
|
-
filename: this.filename,
|
|
99
|
-
cause: new Error(`HTTP ${response.status}: ${response.statusText}`),
|
|
100
|
-
}
|
|
101
|
-
);
|
|
102
|
-
}
|
|
103
|
-
const arrayBuffer = await response.arrayBuffer();
|
|
104
|
-
return new Uint8Array(arrayBuffer);
|
|
136
|
+
return (await this.downloadBytes()).content;
|
|
105
137
|
}
|
|
106
138
|
|
|
107
139
|
/**
|
|
@@ -120,22 +152,8 @@ export class RemoteFile {
|
|
|
120
152
|
* @throws RemoteFileDownloadError if the fetch fails
|
|
121
153
|
*/
|
|
122
154
|
async blob(): Promise<Blob> {
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
if (!response.ok) {
|
|
126
|
-
throw new RemoteFileDownloadError(
|
|
127
|
-
`Failed to download file: ${response.status} ${response.statusText}`,
|
|
128
|
-
{
|
|
129
|
-
statusCode: response.status,
|
|
130
|
-
statusText: response.statusText,
|
|
131
|
-
downloadUrl: this.downloadUrl,
|
|
132
|
-
mountRelativePath: this.mountRelativePath,
|
|
133
|
-
filename: this.filename,
|
|
134
|
-
cause: new Error(`HTTP ${response.status}: ${response.statusText}`),
|
|
135
|
-
}
|
|
136
|
-
);
|
|
137
|
-
}
|
|
138
|
-
return response.blob();
|
|
155
|
+
const { content, contentType } = await this.downloadBytes();
|
|
156
|
+
return new Blob([content as BlobPart], { type: contentType });
|
|
139
157
|
}
|
|
140
158
|
|
|
141
159
|
/**
|
|
@@ -375,9 +375,13 @@ export class ToolRouterSession<
|
|
|
375
375
|
tools: tk.tools.map(tool => {
|
|
376
376
|
// Look up by toolkit + original slug so toolkits can safely reuse common names
|
|
377
377
|
// like VERSION, CLICK, or SEARCH without losing the backend-assigned final slug.
|
|
378
|
+
// Only trust a bare alias that belongs to this toolkit.
|
|
379
|
+
const bare = this.customToolsMap!.byOriginalSlug.get(tool.slug.toUpperCase());
|
|
378
380
|
const entry =
|
|
379
381
|
findCustomToolMapEntryByToolkitAndOriginalSlug(this.customToolsMap, tk.slug, tool.slug) ??
|
|
380
|
-
|
|
382
|
+
(bare?.toolkit && bare.toolkit.toLowerCase() === tk.slug.toLowerCase()
|
|
383
|
+
? bare
|
|
384
|
+
: undefined);
|
|
381
385
|
return {
|
|
382
386
|
slug: entry?.finalSlug ?? tool.slug,
|
|
383
387
|
name: tool.name,
|
|
@@ -555,9 +559,10 @@ export class ToolRouterSession<
|
|
|
555
559
|
/**
|
|
556
560
|
* Execute a tool within the session.
|
|
557
561
|
*
|
|
558
|
-
* For custom tools, accepts the
|
|
559
|
-
*
|
|
560
|
-
*
|
|
562
|
+
* For custom tools, accepts the full slug (e.g. "LOCAL_GREP") or the
|
|
563
|
+
* original slug (e.g. "GREP") when that original slug is unique across
|
|
564
|
+
* the session's custom tools and toolkits. Custom tools are executed
|
|
565
|
+
* in-process; remote tools are sent to the Composio backend.
|
|
561
566
|
*
|
|
562
567
|
* @param toolSlug - The tool slug to execute
|
|
563
568
|
* @param arguments_ - Optional tool arguments
|
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 &&
|
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
|
};
|
|
@@ -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/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 {
|
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import { isIP } from 'node:net';
|
|
2
|
+
import { request as httpRequest } from 'node:http';
|
|
3
|
+
import { request as httpsRequest } from 'node:https';
|
|
4
|
+
import { Readable } from 'node:stream';
|
|
2
5
|
import type { Agent } from 'undici';
|
|
3
6
|
|
|
4
7
|
/**
|
|
@@ -36,6 +39,37 @@ const GLOBAL_DISPATCHER_SYMBOLS = [
|
|
|
36
39
|
let undici: Promise<typeof import('undici')> | undefined;
|
|
37
40
|
const loadUndici = (): Promise<typeof import('undici')> => (undici ??= import('undici'));
|
|
38
41
|
|
|
42
|
+
const lookupPinnedAddresses = (
|
|
43
|
+
addresses: ReadonlyArray<string>,
|
|
44
|
+
options: { all?: boolean },
|
|
45
|
+
callback: (
|
|
46
|
+
error: NodeJS.ErrnoException | null,
|
|
47
|
+
address: string | Array<{ address: string; family: number }>,
|
|
48
|
+
family?: number
|
|
49
|
+
) => void
|
|
50
|
+
) => {
|
|
51
|
+
if (options.all) {
|
|
52
|
+
callback(
|
|
53
|
+
null,
|
|
54
|
+
addresses.map(address => ({ address, family: isIP(address) }))
|
|
55
|
+
);
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const [address] = addresses;
|
|
60
|
+
callback(null, address, isIP(address));
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
const knownBodyLength = (body: BodyInit | null | undefined): number | undefined => {
|
|
64
|
+
if (body === null || body === undefined) return undefined;
|
|
65
|
+
if (typeof body === 'string') return new TextEncoder().encode(body).byteLength;
|
|
66
|
+
if (body instanceof URLSearchParams) return new TextEncoder().encode(body.toString()).byteLength;
|
|
67
|
+
if (body instanceof ArrayBuffer) return body.byteLength;
|
|
68
|
+
if (ArrayBuffer.isView(body)) return body.byteLength;
|
|
69
|
+
if (body instanceof Blob) return body.size;
|
|
70
|
+
return undefined;
|
|
71
|
+
};
|
|
72
|
+
|
|
39
73
|
/**
|
|
40
74
|
* A `fetch` dispatcher that connects to `addresses` instead of resolving the
|
|
41
75
|
* hostname again.
|
|
@@ -71,24 +105,86 @@ export const createPinnedDispatcher = async (addresses: ReadonlyArray<string>):
|
|
|
71
105
|
// off, or a `family`/`localAddress` was requested. Answering in the
|
|
72
106
|
// wrong shape is rejected as an invalid address, which would fail
|
|
73
107
|
// every pinned fetch in such a process.
|
|
74
|
-
|
|
75
|
-
// All of them, in resolver order: handing over a single address of a
|
|
76
|
-
// dual-stack host would strand callers whose network cannot reach
|
|
77
|
-
// that family, where the runtime would otherwise have fallen back.
|
|
78
|
-
callback(
|
|
79
|
-
null,
|
|
80
|
-
addresses.map(address => ({ address, family: isIP(address) }))
|
|
81
|
-
);
|
|
82
|
-
return;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
const [address] = addresses;
|
|
86
|
-
callback(null, address, isIP(address));
|
|
108
|
+
lookupPinnedAddresses(addresses, options, callback);
|
|
87
109
|
},
|
|
88
110
|
},
|
|
89
111
|
});
|
|
90
112
|
};
|
|
91
113
|
|
|
114
|
+
/**
|
|
115
|
+
* Fetch through the Node-compatible HTTP client while pinning DNS resolution.
|
|
116
|
+
*
|
|
117
|
+
* Bun implements the Node HTTP client and its `lookup` hook, but its native
|
|
118
|
+
* `fetch` ignores undici's `dispatcher` option. This transport preserves the
|
|
119
|
+
* original hostname for Host and TLS SNI while making the socket use an
|
|
120
|
+
* address that the SSRF guard already validated.
|
|
121
|
+
*/
|
|
122
|
+
export const pinnedHttpFetch = async (
|
|
123
|
+
rawUrl: string,
|
|
124
|
+
init: RequestInit,
|
|
125
|
+
addresses: ReadonlyArray<string>
|
|
126
|
+
): Promise<Response> => {
|
|
127
|
+
const normalized = new Request(rawUrl, init);
|
|
128
|
+
const url = new URL(rawUrl);
|
|
129
|
+
const request = url.protocol === 'https:' ? httpsRequest : httpRequest;
|
|
130
|
+
const headers = new Headers(normalized.headers);
|
|
131
|
+
const bodyLength = knownBodyLength(init.body);
|
|
132
|
+
if (bodyLength !== undefined && !headers.has('content-length')) {
|
|
133
|
+
headers.set('content-length', String(bodyLength));
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return new Promise<Response>((resolve, reject) => {
|
|
137
|
+
const outgoing = request(
|
|
138
|
+
url,
|
|
139
|
+
{
|
|
140
|
+
method: normalized.method,
|
|
141
|
+
headers: Object.fromEntries(headers.entries()),
|
|
142
|
+
signal: normalized.signal,
|
|
143
|
+
lookup: (_hostname, options, callback) =>
|
|
144
|
+
lookupPinnedAddresses(addresses, options, callback),
|
|
145
|
+
},
|
|
146
|
+
incoming => {
|
|
147
|
+
const headers = new Headers();
|
|
148
|
+
for (let index = 0; index < incoming.rawHeaders.length; index += 2) {
|
|
149
|
+
headers.append(incoming.rawHeaders[index], incoming.rawHeaders[index + 1]);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const status = incoming.statusCode ?? 500;
|
|
153
|
+
const body = [101, 103, 204, 205, 304].includes(status)
|
|
154
|
+
? null
|
|
155
|
+
: (Readable.toWeb(incoming) as ReadableStream<Uint8Array>);
|
|
156
|
+
resolve(
|
|
157
|
+
new Response(body, {
|
|
158
|
+
status,
|
|
159
|
+
statusText: incoming.statusMessage,
|
|
160
|
+
headers,
|
|
161
|
+
})
|
|
162
|
+
);
|
|
163
|
+
}
|
|
164
|
+
);
|
|
165
|
+
|
|
166
|
+
outgoing.once('error', reject);
|
|
167
|
+
|
|
168
|
+
void (async () => {
|
|
169
|
+
try {
|
|
170
|
+
if (normalized.body) {
|
|
171
|
+
const reader = normalized.body.getReader();
|
|
172
|
+
while (true) {
|
|
173
|
+
const { done, value } = await reader.read();
|
|
174
|
+
if (done) break;
|
|
175
|
+
if (!outgoing.write(value)) {
|
|
176
|
+
await new Promise<void>(resolveDrain => outgoing.once('drain', resolveDrain));
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
outgoing.end();
|
|
181
|
+
} catch (error) {
|
|
182
|
+
outgoing.destroy(error instanceof Error ? error : new Error(String(error)));
|
|
183
|
+
}
|
|
184
|
+
})();
|
|
185
|
+
});
|
|
186
|
+
};
|
|
187
|
+
|
|
92
188
|
/**
|
|
93
189
|
* Whether the process-wide dispatcher `fetch` falls back to (when a request
|
|
94
190
|
* carries no `dispatcher` of its own) is something other than a stock `Agent`.
|
package/src/utils/sdk.ts
CHANGED
|
@@ -53,7 +53,7 @@ export function getSDKConfig(baseUrl?: string | null, apiKey?: string | null) {
|
|
|
53
53
|
ComposioError.handleAndThrow(new ComposioNoAPIKeyError());
|
|
54
54
|
}
|
|
55
55
|
|
|
56
|
-
logger.debug('Environment',
|
|
56
|
+
logger.debug('Environment', 'API Key: [REDACTED]');
|
|
57
57
|
logger.debug('Environment', `Base URL: ${baseURLParsed}`);
|
|
58
58
|
|
|
59
59
|
return { baseURL: baseURLParsed, apiKey: apiKeyParsed };
|