@composio/core 0.17.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.
Files changed (54) hide show
  1. package/dist/{CustomTool-l-j5HtEf.mjs → CustomTool-Bz0f52QR.mjs} +16 -6
  2. package/dist/{CustomTool-Uip-fhPw.d.mts → CustomTool-VRfWzMix.d.mts} +1 -1
  3. package/dist/{FileModifierErrors-B8V8_3VE.mjs → FileModifierErrors-CwB-Inm9.mjs} +1 -1
  4. package/dist/FileToolModifier.utils.neutral-D_YkHwZP.mjs +188 -0
  5. package/dist/{SsrfErrors-DNJt57GL.mjs → SsrfErrors-xhdVE4yw.mjs} +123 -3
  6. package/dist/{Telemetry-DuGJSwUt.mjs → Telemetry-Dw9W5RSp.mjs} +28 -44
  7. package/dist/cancellation-P5YUlcfz.mjs +704 -0
  8. package/dist/{composio-B27X6i6A.d.mts → composio-Cb3d1jFe.d.mts} +250 -244
  9. package/dist/{customTool.types-B2Ava_j5.d.mts → customTool.types-B6ej_8XZ.d.mts} +146 -144
  10. package/dist/docs/reference/sdk-reference/typescript/session-files.mdx +1 -1
  11. package/dist/docs/reference/sdk-reference/typescript/session.mdx +4 -3
  12. package/dist/{errors-BcEUHZbq.mjs → errors-Ue9wMrPK.mjs} +5 -2
  13. package/dist/experimental/index.d.mts +2 -2
  14. package/dist/experimental/index.mjs +1 -1
  15. package/dist/{fileUtils.node-B1Wn848p.mjs → fileUtils.node-KE5Fa-af.mjs} +7 -7
  16. package/dist/index.d.mts +108 -8
  17. package/dist/index.mjs +109 -55
  18. package/dist/models/Files.node.mjs +2 -2
  19. package/dist/{sensitiveFileUploadPaths-BVEt0peg.mjs → sensitiveFileUploadPaths-QN7w4n8v.mjs} +24 -7
  20. package/dist/ssrfGuard.node-BLX6b-Rf.mjs +384 -0
  21. package/dist/{types-DdZJuMm2.d.mts → types-CGdgK442.d.mts} +2 -2
  22. package/dist/utils/config-defaults/ConfigDefaults.node.d.mts +1 -1
  23. package/dist/utils/config-defaults/ConfigDefaults.workerd.d.mts +1 -1
  24. package/dist/utils/modifiers/FileToolModifier.node.d.mts +1 -1
  25. package/dist/utils/modifiers/FileToolModifier.node.mjs +59 -103
  26. package/dist/utils/modifiers/FileToolModifier.workerd.d.mts +1 -1
  27. package/dist/utils/modifiers/FileToolModifier.workerd.mjs +1 -1
  28. package/dist/utils/ssrfGuard.node.d.mts +14 -5
  29. package/dist/utils/ssrfGuard.node.mjs +1 -161
  30. package/dist/utils/ssrfGuard.workerd.d.mts +1 -1
  31. package/dist/utils/ssrfGuard.workerd.mjs +2 -2
  32. package/package.json +25 -3
  33. package/src/errors/ToolErrors.ts +1 -0
  34. package/src/errors/ValidationErrors.ts +2 -0
  35. package/src/index.ts +6 -0
  36. package/src/models/CustomTool.ts +41 -6
  37. package/src/models/RemoteFile.ts +54 -36
  38. package/src/models/ToolRouterSession.ts +45 -12
  39. package/src/models/Tools.ts +102 -39
  40. package/src/models/Triggers.ts +15 -0
  41. package/src/services/telemetry/TelemetryService.ts +27 -12
  42. package/src/telemetry/redact.ts +133 -6
  43. package/src/utils/fileUtils.node.ts +10 -2
  44. package/src/utils/jsonSchema.ts +505 -27
  45. package/src/utils/logger.ts +6 -6
  46. package/src/utils/modifiers/FileToolModifier.node.ts +85 -181
  47. package/src/utils/modifiers/FileToolModifier.utils.neutral.ts +199 -0
  48. package/src/utils/pinnedDispatcher.node.ts +214 -0
  49. package/src/utils/sdk.ts +1 -1
  50. package/src/utils/sensitiveFileUploadPaths.ts +36 -9
  51. package/src/utils/ssrfGuard.node.ts +101 -11
  52. package/src/utils/ssrfGuard.workerd.ts +5 -1
  53. package/dist/FileToolModifier.utils.neutral-B5rT711M.mjs +0 -72
  54. package/dist/cancellation-NVtGf3St.mjs +0 -364
@@ -54,7 +54,11 @@ import { handleToolExecutionError } from '../errors/ToolErrors';
54
54
  import type { SessionExecuteParams } from '@composio/client/resources/tool-router/session/session.mjs';
55
55
  import { CONFIG_DEFAULTS } from '../utils/config-defaults';
56
56
  import { resolveEffectiveUploadAllowlist } from '../utils/fileDirs';
57
- import { schemaHasFileUploadable } from '../utils/modifiers/FileToolModifier.utils.neutral';
57
+ import {
58
+ dropEmptyFileUploads,
59
+ schemaHasFileUploadable,
60
+ } from '../utils/modifiers/FileToolModifier.utils.neutral';
61
+ import { dereferenceJsonSchema } from '../utils/jsonSchema';
58
62
  import { ComposioRequestOptions } from '../types/requestOptions.types';
59
63
  import { withCancellation } from '../utils/cancellation';
60
64
  import { ComposioRequestCancelledError } from '../errors/SDKErrors';
@@ -268,12 +272,56 @@ export class Tools<
268
272
  if (requestOptions?.signal?.aborted) {
269
273
  throw new ComposioRequestCancelledError();
270
274
  }
275
+ let modifiedParams = await this.applyFileUploadModifiers(
276
+ tool,
277
+ { toolSlug, toolkitSlug, params },
278
+ modifiers?.beforeFileUpload,
279
+ requestOptions
280
+ );
281
+
282
+ // apply the before execute modifiers
283
+ if (modifiers?.beforeExecute) {
284
+ if (typeof modifiers.beforeExecute === 'function') {
285
+ modifiedParams = await modifiers.beforeExecute({
286
+ toolSlug,
287
+ toolkitSlug,
288
+ params: modifiedParams,
289
+ });
290
+ if (requestOptions?.signal?.aborted) {
291
+ throw new ComposioRequestCancelledError();
292
+ }
293
+ } else {
294
+ throw new ComposioInvalidModifierError('Invalid beforeExecute modifier. Not a function.');
295
+ }
296
+ }
297
+ return modifiedParams;
298
+ }
299
+
300
+ /**
301
+ * Applies schema-aware file preprocessing shared by direct and Tool Router
302
+ * session execution. This always runs before the caller's `beforeExecute`
303
+ * hook so the hook observes the exact arguments sent to the backend.
304
+ */
305
+ private async applyFileUploadModifiers(
306
+ tool: Tool,
307
+ {
308
+ toolSlug,
309
+ toolkitSlug,
310
+ params,
311
+ }: {
312
+ toolSlug: string;
313
+ toolkitSlug: string;
314
+ params: ToolExecuteParams;
315
+ },
316
+ beforeFileUpload?: ExecuteToolModifiers['beforeFileUpload'],
317
+ requestOptions?: ComposioRequestOptions
318
+ ): Promise<ToolExecuteParams> {
271
319
  let modifiedParams = params;
272
320
  // if auto upload download files is enabled, upload the files to the Composio API
273
321
  if (this.autoUploadDownloadFiles) {
274
322
  const fileToolModifier = new FileToolModifier(this.client, {
275
323
  ...this.fileUploadPathOptions,
276
- beforeFileUpload: modifiers?.beforeFileUpload,
324
+ beforeFileUpload,
277
325
  });
278
326
  modifiedParams = await fileToolModifier.fileUploadModifier(tool, {
279
327
  toolSlug,
@@ -284,40 +332,37 @@ export class Tools<
284
332
  if (requestOptions?.signal?.aborted) {
285
333
  throw new ComposioRequestCancelledError();
286
334
  }
287
- } else if (
288
- schemaHasFileUploadable(tool.inputParameters) &&
289
- !this.warnedAutoUploadDisabledForTool.has(toolSlug)
290
- ) {
291
- // With auto-upload off, the raw `{ name, mimetype, s3key }` shape is
292
- // what the LLM / caller sees on `tool.inputParameters`. LLMs can't
293
- // produce a valid `s3key` and will hallucinate one, which then fails
294
- // at the staging-lookup step on the backend. Nudge the caller toward
295
- // manual staging or opting into auto-upload.
296
- this.warnedAutoUploadDisabledForTool.add(toolSlug);
297
- logger.warn(
298
- `Tool "${toolSlug}" (toolkit "${toolkitSlug}") has a file-uploadable input, but ` +
299
- `\`dangerouslyAllowAutoUploadDownloadFiles\` is disabled. The SDK will forward ` +
300
- `the file argument as-is; if it isn't already a staged ` +
301
- `{ name, mimetype, s3key } descriptor, the backend will reject the call. Either:\n` +
302
- ` 1) Stage the file yourself: \`const f = await composio.files.upload({ file, toolSlug, toolkitSlug }); ` +
303
- `await composio.tools.execute('${toolSlug}', { userId, arguments: { <fileField>: f } })\`, or\n` +
304
- ` 2) Enable auto-upload with a scoped allowlist: ` +
305
- `\`new Composio({ dangerouslyAllowAutoUploadDownloadFiles: true, fileUploadDirs: ['/safe/dir'] })\`.`
306
- );
307
- }
308
- // apply the before execute modifiers
309
- if (modifiers?.beforeExecute) {
310
- if (typeof modifiers.beforeExecute === 'function') {
311
- modifiedParams = await modifiers.beforeExecute({
312
- toolSlug,
313
- toolkitSlug,
314
- params: modifiedParams,
315
- });
316
- if (requestOptions?.signal?.aborted) {
317
- throw new ComposioRequestCancelledError();
318
- }
319
- } else {
320
- throw new ComposioInvalidModifierError('Invalid beforeExecute modifier. Not a function.');
335
+ } else if (tool.inputParameters && schemaHasFileUploadable(tool.inputParameters)) {
336
+ // Auto-upload is opt-in, but "no file" must still be sent as an
337
+ // omitted key rather than `''`, which the backend rejects
338
+ // (https://github.com/ComposioHQ/composio/issues/4233).
339
+ if (modifiedParams.arguments) {
340
+ modifiedParams = {
341
+ ...modifiedParams,
342
+ arguments: (await dropEmptyFileUploads(
343
+ modifiedParams.arguments,
344
+ dereferenceJsonSchema(tool.inputParameters, { onUnresolved: 'sentinel' })
345
+ )) as ToolExecuteParams['arguments'],
346
+ };
347
+ }
348
+
349
+ if (!this.warnedAutoUploadDisabledForTool.has(toolSlug)) {
350
+ // With auto-upload off, the raw `{ name, mimetype, s3key }` shape is
351
+ // what the LLM / caller sees on `tool.inputParameters`. LLMs can't
352
+ // produce a valid `s3key` and will hallucinate one, which then fails
353
+ // at the staging-lookup step on the backend. Nudge the caller toward
354
+ // manual staging or opting into auto-upload.
355
+ this.warnedAutoUploadDisabledForTool.add(toolSlug);
356
+ logger.warn(
357
+ `Tool "${toolSlug}" (toolkit "${toolkitSlug}") has a file-uploadable input, but ` +
358
+ `\`dangerouslyAllowAutoUploadDownloadFiles\` is disabled. The SDK will forward ` +
359
+ `the file argument as-is; if it isn't already a staged ` +
360
+ `{ name, mimetype, s3key } descriptor, the backend will reject the call. Either:\n` +
361
+ ` 1) Stage the file yourself: \`const f = await composio.files.upload({ file, toolSlug, toolkitSlug }); ` +
362
+ `await composio.tools.execute('${toolSlug}', { userId, arguments: { <fileField>: f } })\`, or\n` +
363
+ ` 2) Enable auto-upload with a scoped allowlist: ` +
364
+ `\`new Composio({ dangerouslyAllowAutoUploadDownloadFiles: true, fileUploadDirs: ['/safe/dir'] })\`.`
365
+ );
321
366
  }
322
367
  }
323
368
  return modifiedParams;
@@ -851,9 +896,10 @@ export class Tools<
851
896
  wrapToolsForToolRouter(
852
897
  sessionId: string,
853
898
  tools: Tool[],
854
- modifiers?: SessionExecuteMetaModifiers
899
+ modifiers?: SessionExecuteMetaModifiers,
900
+ rawTools: Tool[] = tools.map(tool => ToolSchema.parse(tool))
855
901
  ): Tool[] {
856
- const executeToolFn = this.createExecuteToolFnForToolRouter(sessionId, tools, modifiers);
902
+ const executeToolFn = this.createExecuteToolFnForToolRouter(sessionId, rawTools, modifiers);
857
903
  return this.provider.wrapTools(tools, executeToolFn) as Tool[];
858
904
  }
859
905
 
@@ -1150,9 +1196,25 @@ export class Tools<
1150
1196
  });
1151
1197
  }
1152
1198
 
1153
- // Apply beforeExecute modifier if provided
1154
1199
  let modifiedParams = body.arguments ?? {};
1155
1200
  const toolkitSlug = tool?.toolkit?.slug ?? 'composio';
1201
+
1202
+ if (tool) {
1203
+ const fileModifiedParams = await this.applyFileUploadModifiers(
1204
+ tool,
1205
+ {
1206
+ toolSlug,
1207
+ toolkitSlug,
1208
+ params: { arguments: modifiedParams },
1209
+ },
1210
+ undefined,
1211
+ requestOptions
1212
+ );
1213
+ modifiedParams = fileModifiedParams.arguments ?? {};
1214
+ }
1215
+
1216
+ // Apply beforeExecute modifier after file preprocessing so the hook sees
1217
+ // the same arguments that will be sent to the Tool Router.
1156
1218
  if (modifiers?.beforeExecute) {
1157
1219
  modifiedParams = await modifiers.beforeExecute({
1158
1220
  toolSlug,
@@ -1308,6 +1370,7 @@ export class Tools<
1308
1370
  * @deprecated The `customConnectionData` proxy param is deprecated and will be
1309
1371
  * removed in a future release. Use `customAuthParams` instead.
1310
1372
  */
1373
+ // oxlint-disable-next-line typescript/ban-ts-comment -- generated client versions disagree about this deprecated field
1311
1374
  // @ts-ignore
1312
1375
  custom_connection_data: toolProxyParams.data.customConnectionData,
1313
1376
  } as ComposioToolProxyParams;
@@ -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 &&
@@ -2,22 +2,43 @@ import logger from '../../utils/logger';
2
2
  import { TelemetryMetricPayloadBody, TelemetryPayload } from './TelemetryService.types';
3
3
 
4
4
  const TELEMETRY_URL = 'https://telemetry.composio.dev/v1';
5
+ const TELEMETRY_TIMEOUT_MS = 3_000;
5
6
 
6
7
  export class TelemetryService {
7
8
  /**
8
- * Sends a metric to the Telemetry API.
9
- * @param payload - The payload to send to the Telemetry API.
10
- * @returns The response from the Telemetry API.
9
+ * POSTs a best-effort telemetry payload, bounding the request so a stalled
10
+ * endpoint cannot leave it pending indefinitely.
11
+ *
12
+ * A hand-rolled timer rather than AbortSignal.timeout so it can be cleared the
13
+ * moment the response lands: an uncleared timer is itself pending work, which on
14
+ * workerd pins the request context open for the full timeout on every successful
15
+ * send. Mirrors the bound applied to the npm version check.
11
16
  */
12
- static async sendMetric(payload: TelemetryMetricPayloadBody) {
17
+ private static async postWithTimeout(url: string, payload: unknown) {
18
+ const controller = new AbortController();
19
+ const timer = setTimeout(() => controller.abort(), TELEMETRY_TIMEOUT_MS);
13
20
  try {
14
- const result = await fetch(`${TELEMETRY_URL}/metrics/invocations`, {
21
+ return await fetch(url, {
15
22
  method: 'POST',
16
23
  headers: {
17
24
  'Content-Type': 'application/json',
18
25
  },
19
26
  body: JSON.stringify(payload),
27
+ signal: controller.signal,
20
28
  });
29
+ } finally {
30
+ clearTimeout(timer);
31
+ }
32
+ }
33
+
34
+ /**
35
+ * Sends a metric to the Telemetry API.
36
+ * @param payload - The payload to send to the Telemetry API.
37
+ * @returns The response from the Telemetry API.
38
+ */
39
+ static async sendMetric(payload: TelemetryMetricPayloadBody) {
40
+ try {
41
+ const result = await this.postWithTimeout(`${TELEMETRY_URL}/metrics/invocations`, payload);
21
42
  return result;
22
43
  } catch (error) {
23
44
  // ignore error for now; telemetry failures should never affect SDK calls
@@ -32,13 +53,7 @@ export class TelemetryService {
32
53
  */
33
54
  static async sendErrorLog(payload: TelemetryPayload) {
34
55
  try {
35
- const result = await fetch(`${TELEMETRY_URL}/errors`, {
36
- method: 'POST',
37
- headers: {
38
- 'Content-Type': 'application/json',
39
- },
40
- body: JSON.stringify(payload),
41
- });
56
+ const result = await this.postWithTimeout(`${TELEMETRY_URL}/errors`, payload);
42
57
  return result;
43
58
  } catch (error) {
44
59
  // ignore error for now; telemetry failures should never affect SDK calls
@@ -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
- // The separator group allows a quote directly after the key name so JSON is
24
- // covered: in `{"api_key": "secret"}` the key's own closing quote sits
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
- /(?<![A-Za-z0-9])(authorization|api[-_]?key|apikey|x-api-key|access[-_]?token|refresh[-_]?token|client[-_]?secret|secret|password|passwd|pwd)\b(["']?\s*[:=]+\s*)(["']?)([^\s"',}&]+)\3/gi,
30
- `$1$2$3${REDACTED}$3`,
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
- return output;
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
- const data = await response.arrayBuffer();
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, new Uint8Array(data), {
373
+ const filePath = saveFile(fileName, data, {
366
374
  isTempFile: fileDownloadDir === undefined,
367
375
  outputDir: fileDownloadDir,
368
376
  });