@ai-sdk/provider-utils 5.0.75 → 5.0.78

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-sdk/provider-utils",
3
- "version": "5.0.75",
3
+ "version": "5.0.78",
4
4
  "type": "module",
5
5
  "license": "Apache-2.0",
6
6
  "sideEffects": false,
@@ -42,7 +42,7 @@
42
42
  }
43
43
  },
44
44
  "dependencies": {
45
- "@ai-sdk/provider": "4.0.36",
45
+ "@ai-sdk/provider": "4.0.37",
46
46
  "@standard-schema/spec": "^1.1.0",
47
47
  "@workflow/serde": "4.1.0",
48
48
  "eventsource-parser": "^3.0.8",
@@ -341,13 +341,16 @@ export function detectMediaType({
341
341
  });
342
342
  }
343
343
 
344
- const signatures = topLevelSignatureTables[topLevelType as TopLevelMediaType];
345
-
346
- if (signatures === undefined) {
344
+ if (
345
+ !Object.prototype.hasOwnProperty.call(topLevelSignatureTables, topLevelType)
346
+ ) {
347
347
  return undefined;
348
348
  }
349
349
 
350
- return detectMediaTypeBySignatures({ data, signatures });
350
+ return detectMediaTypeBySignatures({
351
+ data,
352
+ signatures: topLevelSignatureTables[topLevelType as TopLevelMediaType],
353
+ });
351
354
  }
352
355
 
353
356
  /**
@@ -3,7 +3,7 @@ import { DownloadError } from './download-error';
3
3
  import type { FetchFunction } from './fetch-function';
4
4
  import { isBrowserRuntime } from './is-browser-runtime';
5
5
  import { isSameOrigin } from './is-same-origin';
6
- import { getDefaultDownloadFetch } from './safe-node-fetch';
6
+ import { getDefaultDownloadFetch, isNodeRuntime } from './safe-node-fetch';
7
7
  import { sanitizeRequestHeaders } from './sanitize-request-headers';
8
8
  import { validateDownloadUrl } from './validate-download-url';
9
9
 
@@ -39,6 +39,7 @@ export async function fetchWithValidatedEndpoint({
39
39
  fetch: customFetch,
40
40
  trustedOrigin,
41
41
  redirect = 'error',
42
+ requireDnsValidation = false,
42
43
  }: {
43
44
  url: string | URL;
44
45
  init?: RequestInit;
@@ -49,6 +50,11 @@ export async function fetchWithValidatedEndpoint({
49
50
  */
50
51
  trustedOrigin?: string;
51
52
  redirect?: 'error' | 'manual';
53
+ /**
54
+ * Reject untrusted URLs on server runtimes without a DNS-pinned default
55
+ * transport unless an explicit custom fetch provides equivalent validation.
56
+ */
57
+ requireDnsValidation?: boolean;
52
58
  }): Promise<Response> {
53
59
  const urlText = url.toString();
54
60
  const isTrusted =
@@ -56,6 +62,20 @@ export async function fetchWithValidatedEndpoint({
56
62
 
57
63
  if (!isTrusted) {
58
64
  validateDownloadUrl(urlText);
65
+
66
+ if (
67
+ requireDnsValidation &&
68
+ (customFetch == null || customFetch === globalThis.fetch) &&
69
+ !isNodeRuntime() &&
70
+ // A window alias alone does not distinguish older Deno from a browser.
71
+ !(isBrowserRuntime() && typeof document !== 'undefined')
72
+ ) {
73
+ throw new DownloadError({
74
+ url: urlText,
75
+ message:
76
+ 'This server runtime requires a custom fetch with connect-time DNS validation for untrusted URLs',
77
+ });
78
+ }
59
79
  }
60
80
 
61
81
  const fetch =
@@ -80,6 +100,9 @@ export async function fetchWithValidatedEndpoint({
80
100
  * target (e.g. an internal address) before we ever see its URL, defeating the
81
101
  * guard.
82
102
  *
103
+ * Manually followed redirects from HTTPS to HTTP are rejected before requesting
104
+ * the target.
105
+ *
83
106
  * Request headers are also protected: {@link sanitizeRequestHeaders} strips
84
107
  * proxy/metadata/cookie/hop-by-hop headers before the first request, and all
85
108
  * caller headers except `User-Agent` are dropped on a cross-origin redirect.
@@ -193,6 +216,16 @@ export async function fetchWithValidatedRedirects({
193
216
  void cancelResponseBody(response);
194
217
  const nextUrl = new URL(location, currentUrl).toString();
195
218
 
219
+ if (
220
+ new URL(currentUrl).protocol === 'https:' &&
221
+ new URL(nextUrl).protocol === 'http:'
222
+ ) {
223
+ throw new DownloadError({
224
+ url,
225
+ message: 'Redirect from HTTPS to HTTP was blocked',
226
+ });
227
+ }
228
+
196
229
  // Drop all caller headers except the user-agent before following a
197
230
  // redirect that crosses origin. Only stripping Authorization (as the
198
231
  // fetch spec does) is not enough on the server: providers authenticate
package/src/index.ts CHANGED
@@ -76,6 +76,10 @@ export { normalizeBatchRequestCounts } from './normalize-batch-request-counts';
76
76
  export * from './parse-json';
77
77
  export { parseJsonEventStream } from './parse-json-event-stream';
78
78
  export { parseProviderOptions } from './parse-provider-options';
79
+ export {
80
+ resolveProviderOptions,
81
+ type ProviderOptionsResolution,
82
+ } from './resolve-provider-options';
79
83
  export * from './post-multipart-stream-to-api';
80
84
  export * from './post-to-api';
81
85
  export {
@@ -113,6 +117,10 @@ export {
113
117
  export { serializeModelOptions } from './serialize-model-options';
114
118
  export { SerializationError } from './serialization-error';
115
119
  export { secureJsonParse } from './secure-json-parse';
120
+ export {
121
+ withTelemetryRedaction,
122
+ redactTelemetryValue,
123
+ } from './telemetry-redaction';
116
124
  export {
117
125
  SPEECH_STREAM_START_FRAME_TYPE as EXPERIMENTAL_SPEECH_STREAM_START_FRAME_TYPE,
118
126
  SPEECH_STREAM_TEXT_DELTA_FRAME_TYPE as EXPERIMENTAL_SPEECH_STREAM_TEXT_DELTA_FRAME_TYPE,
@@ -2,6 +2,7 @@ import { tool, type ProviderDefinedTool, type Tool } from './types/tool';
2
2
  import type { FlexibleSchema } from './schema';
3
3
  import type { Context } from './types/context';
4
4
  import type { ToolExecuteFunction } from './types/tool-execute-function';
5
+ import { withTelemetryRedaction } from './telemetry-redaction';
5
6
  /**
6
7
  * A provider-defined tool is a tool for which the provider defines the input
7
8
  * and output schemas, but does not execute the tool.
@@ -28,9 +29,12 @@ export function createProviderDefinedToolFactory<
28
29
  >({
29
30
  id,
30
31
  inputSchema,
32
+ redactArgs,
31
33
  }: {
32
34
  id: `${string}.${string}`;
33
35
  inputSchema: FlexibleSchema<INPUT>;
36
+ /** Provider-owned telemetry view of the tool configuration. */
37
+ redactArgs?: (args: Record<string, unknown>) => Record<string, unknown>;
34
38
  }): ProviderDefinedToolFactory<INPUT, ARGS, CONTEXT> {
35
39
  return <OUTPUT>({
36
40
  execute,
@@ -54,7 +58,8 @@ export function createProviderDefinedToolFactory<
54
58
  type: 'provider',
55
59
  isProviderExecuted: false,
56
60
  id,
57
- args,
61
+ args:
62
+ redactArgs == null ? args : withTelemetryRedaction(args, redactArgs),
58
63
  inputSchema,
59
64
  outputSchema,
60
65
  execute,
@@ -91,10 +96,13 @@ export function createProviderDefinedToolFactoryWithOutputSchema<
91
96
  id,
92
97
  inputSchema,
93
98
  outputSchema,
99
+ redactArgs,
94
100
  }: {
95
101
  id: `${string}.${string}`;
96
102
  inputSchema: FlexibleSchema<INPUT>;
97
103
  outputSchema: FlexibleSchema<OUTPUT>;
104
+ /** Provider-owned telemetry view of the tool configuration. */
105
+ redactArgs?: (args: Record<string, unknown>) => Record<string, unknown>;
98
106
  }): ProviderDefinedToolFactoryWithOutputSchema<INPUT, OUTPUT, ARGS, CONTEXT> {
99
107
  return ({
100
108
  execute,
@@ -116,7 +124,8 @@ export function createProviderDefinedToolFactoryWithOutputSchema<
116
124
  type: 'provider',
117
125
  isProviderExecuted: false,
118
126
  id,
119
- args,
127
+ args:
128
+ redactArgs == null ? args : withTelemetryRedaction(args, redactArgs),
120
129
  inputSchema,
121
130
  outputSchema,
122
131
  execute,
@@ -1,6 +1,7 @@
1
1
  import type { FlexibleSchema } from './schema';
2
2
  import type { Context } from './types/context';
3
3
  import { tool, type ProviderExecutedTool, type Tool } from './types/tool';
4
+ import { withTelemetryRedaction } from './telemetry-redaction';
4
5
  /**
5
6
  * A provider-executed tool is a tool for which the provider executes the tool.
6
7
  */
@@ -27,6 +28,7 @@ export function createProviderExecutedToolFactory<
27
28
  inputSchema,
28
29
  outputSchema,
29
30
  supportsDeferredResults,
31
+ redactArgs,
30
32
  }: {
31
33
  id: `${string}.${string}`;
32
34
  inputSchema: FlexibleSchema<INPUT>;
@@ -43,6 +45,8 @@ export function createProviderExecutedToolFactory<
43
45
  * @default false
44
46
  */
45
47
  supportsDeferredResults?: boolean;
48
+ /** Provider-owned telemetry view of the tool configuration. */
49
+ redactArgs?: (args: Record<string, unknown>) => Record<string, unknown>;
46
50
  }): ProviderExecutedToolFactory<INPUT, OUTPUT, ARGS, CONTEXT> {
47
51
  return ({
48
52
  onInputStart,
@@ -58,7 +62,8 @@ export function createProviderExecutedToolFactory<
58
62
  type: 'provider',
59
63
  isProviderExecuted: true,
60
64
  id,
61
- args,
65
+ args:
66
+ redactArgs == null ? args : withTelemetryRedaction(args, redactArgs),
62
67
  inputSchema,
63
68
  outputSchema,
64
69
  onInputStart,
@@ -0,0 +1,68 @@
1
+ import type { FlexibleSchema } from './schema';
2
+ import { parseProviderOptions } from './parse-provider-options';
3
+
4
+ /**
5
+ * How options found under several `providerOptions` namespaces are combined.
6
+ *
7
+ * - `first`: namespaces are aliases. The first namespace that is present wins
8
+ * as a whole and later namespaces are ignored (no merging).
9
+ * - `merge`: every present namespace is parsed and the results are merged in
10
+ * order, so later namespaces override earlier ones key by key.
11
+ */
12
+ export type ProviderOptionsResolution = 'first' | 'merge';
13
+
14
+ /**
15
+ * Parses provider options that a model accepts under more than one
16
+ * `providerOptions` namespace, e.g. a canonical key plus a provider-specific
17
+ * or legacy alias.
18
+ *
19
+ * Each present namespace is validated against `schema` exactly like
20
+ * `parseProviderOptions` does, so an invalid namespace throws.
21
+ *
22
+ * @returns the resolved options (`undefined` when no namespace is present)
23
+ * and the namespaces that contributed to them, in resolution order.
24
+ */
25
+ export async function resolveProviderOptions<OPTIONS>({
26
+ providerOptions,
27
+ namespaces,
28
+ resolution,
29
+ schema,
30
+ }: {
31
+ providerOptions: Record<string, unknown> | undefined;
32
+ namespaces: readonly string[];
33
+ resolution: ProviderOptionsResolution;
34
+ schema: FlexibleSchema<OPTIONS>;
35
+ }): Promise<{
36
+ options: OPTIONS | undefined;
37
+ namespaces: string[];
38
+ }> {
39
+ const parsed: OPTIONS[] = [];
40
+ const matched: string[] = [];
41
+
42
+ for (const namespace of new Set(namespaces)) {
43
+ const options = await parseProviderOptions({
44
+ provider: namespace,
45
+ providerOptions,
46
+ schema,
47
+ });
48
+
49
+ if (options == null) {
50
+ continue;
51
+ }
52
+
53
+ if (resolution === 'first') {
54
+ return { options, namespaces: [namespace] };
55
+ }
56
+
57
+ parsed.push(options);
58
+ matched.push(namespace);
59
+ }
60
+
61
+ return {
62
+ options:
63
+ parsed.length === 0
64
+ ? undefined
65
+ : (Object.assign({}, ...parsed) as OPTIONS),
66
+ namespaces: matched,
67
+ };
68
+ }
@@ -0,0 +1,32 @@
1
+ const telemetryRedaction = Symbol.for('vercel.ai.telemetry.redact');
2
+
3
+ /**
4
+ * Attach a provider-owned telemetry view without changing the original value.
5
+ * The annotation is not serialized or included in enumerable application data.
6
+ * Keep the annotated object when forwarding tool arguments or provider metadata.
7
+ */
8
+ export function withTelemetryRedaction<T extends Record<string, unknown>>(
9
+ value: T,
10
+ redact: (value: T) => T,
11
+ ): T {
12
+ return Object.create(Object.getPrototypeOf(value), {
13
+ ...Object.getOwnPropertyDescriptors(value),
14
+ [telemetryRedaction]: { value: redact, configurable: true },
15
+ });
16
+ }
17
+
18
+ /** Apply the provider's telemetry view, leaving unannotated values unchanged. */
19
+ export function redactTelemetryValue<T>(value: T): T | undefined {
20
+ if (value == null || typeof value !== 'object') return value;
21
+ const redact = Object.getOwnPropertyDescriptor(
22
+ value,
23
+ telemetryRedaction,
24
+ )?.value;
25
+ if (typeof redact !== 'function') return value;
26
+ try {
27
+ return redact(value);
28
+ } catch {
29
+ // A broken provider redactor must neither expose credentials nor fail the call.
30
+ return undefined;
31
+ }
32
+ }