@ai-sdk/provider-utils 3.0.44 → 3.0.46

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/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # @ai-sdk/provider-utils
2
2
 
3
+ ## 3.0.46
4
+
5
+ ### Patch Changes
6
+
7
+ - c31e0a2: Require a DNS-pinned fetch for untrusted MCP OAuth discovery and metadata-derived token/registration URLs on server runtimes without a protected default transport. Preserve developer-configured endpoints and allow explicitly supplied fetch implementations that provide equivalent connect-time validation. Browser workers without a DOM follow the same explicit custom-fetch requirement.
8
+
9
+ ## 3.0.45
10
+
11
+ ### Patch Changes
12
+
13
+ - 49c554d: Validate response-supplied Black Forest Labs polling and image URLs, including redirects, to block requests to private destinations outside the configured provider origin. Preserve self-hosted endpoints and withhold credentials from foreign origins and cross-origin redirects.
14
+ - b753c03: Reject HTTPS-to-HTTP redirects in validated downloads before requesting the insecure target, including when it matches a configured trusted origin.
15
+
3
16
  ## 3.0.44
4
17
 
5
18
  ### Patch Changes
package/dist/index.d.mts CHANGED
@@ -93,7 +93,7 @@ type FetchFunction = typeof globalThis.fetch;
93
93
  * Redirects are rejected by default. Callers using `redirect: 'manual'` must
94
94
  * validate the Location target before issuing another request.
95
95
  */
96
- declare function fetchWithValidatedEndpoint({ url, init, fetch: customFetch, trustedOrigin, redirect, }: {
96
+ declare function fetchWithValidatedEndpoint({ url, init, fetch: customFetch, trustedOrigin, redirect, requireDnsValidation, }: {
97
97
  url: string | URL;
98
98
  init?: RequestInit;
99
99
  fetch?: FetchFunction;
@@ -103,6 +103,11 @@ declare function fetchWithValidatedEndpoint({ url, init, fetch: customFetch, tru
103
103
  */
104
104
  trustedOrigin?: string;
105
105
  redirect?: 'error' | 'manual';
106
+ /**
107
+ * Reject untrusted URLs on server runtimes without a DNS-pinned default
108
+ * transport unless an explicit custom fetch provides equivalent validation.
109
+ */
110
+ requireDnsValidation?: boolean;
106
111
  }): Promise<Response>;
107
112
  /**
108
113
  * Fetches a URL while enforcing the SSRF download guard on every hop.
@@ -113,6 +118,12 @@ declare function fetchWithValidatedEndpoint({ url, init, fetch: customFetch, tru
113
118
  * target (e.g. an internal address) before we ever see its URL, defeating the
114
119
  * SSRF guard.
115
120
  *
121
+ * Manually followed redirects from HTTPS to HTTP are rejected before requesting
122
+ * the target.
123
+ *
124
+ * All caller headers except User-Agent are dropped on cross-origin redirects.
125
+ * Callers must decide which credentials may be sent to the initial URL.
126
+ *
116
127
  * A `redirect: 'manual'` request yields an unreadable opaque response in the
117
128
  * browser (and in other spec-compliant fetch implementations), so the redirect
118
129
  * target cannot be validated here. In a real browser this is safe to follow
@@ -347,13 +358,44 @@ declare const createJsonResponseHandler: <T>(responseSchema: FlexibleValidator<T
347
358
  declare const createBinaryResponseHandler: () => ResponseHandler<Uint8Array>;
348
359
  declare const createStatusCodeErrorResponseHandler: () => ResponseHandler<APICallError>;
349
360
 
350
- declare const getFromApi: <T>({ url, headers, successfulResponseHandler, failedResponseHandler, abortSignal, fetch, }: {
361
+ declare const getFromApi: <T>({ url, headers, successfulResponseHandler, failedResponseHandler, abortSignal, fetch, validateUrl, credentialedOrigin, trustedOrigin, }: {
351
362
  url: string;
352
363
  headers?: Record<string, string | undefined>;
353
364
  failedResponseHandler: ResponseHandler<Error>;
354
365
  successfulResponseHandler: ResponseHandler<T>;
355
366
  abortSignal?: AbortSignal;
356
367
  fetch?: FetchFunction;
368
+ /**
369
+ * Set `true` when `url` is untrusted (e.g. taken from a provider response
370
+ * body): it is routed through {@link fetchWithValidatedRedirects}, which
371
+ * rejects private/loopback/link-local targets and re-validates redirect
372
+ * hops; blocked URLs throw `DownloadError`. Set `false` only for URLs built
373
+ * from a developer-configured endpoint.
374
+ *
375
+ * Optional for backwards compatibility with existing callers; omitting it
376
+ * behaves like `false` (no validation).
377
+ */
378
+ validateUrl?: boolean;
379
+ /**
380
+ * When set, `headers` are sent only if `url` is same-origin with this origin
381
+ * (the user-agent suffix is always kept). Pass the provider's configured
382
+ * base URL alongside `validateUrl: true` so credentials never ride a request
383
+ * to a response-supplied host on a different origin (e.g. a CDN). Redirects
384
+ * that later cross origin drop all caller headers regardless (see
385
+ * {@link fetchWithValidatedRedirects}).
386
+ */
387
+ credentialedOrigin?: string;
388
+ /**
389
+ * A developer-configured origin (e.g. the provider's `baseURL`) that is
390
+ * exempt from URL validation when `validateUrl` is `true`. A response URL
391
+ * (or redirect hop) that is same-origin with it is fetched without target
392
+ * validation — it points at exactly the host a config-derived
393
+ * `validateUrl: false` request would fetch anyway, so blocking it would
394
+ * only break legitimate self-hosted / localhost deployments whose response
395
+ * URLs point back at the configured host. Hops on any other origin are
396
+ * still validated. Must never be derived from response data.
397
+ */
398
+ trustedOrigin?: string;
357
399
  }) => Promise<{
358
400
  value: T;
359
401
  rawValue?: unknown;
package/dist/index.d.ts CHANGED
@@ -93,7 +93,7 @@ type FetchFunction = typeof globalThis.fetch;
93
93
  * Redirects are rejected by default. Callers using `redirect: 'manual'` must
94
94
  * validate the Location target before issuing another request.
95
95
  */
96
- declare function fetchWithValidatedEndpoint({ url, init, fetch: customFetch, trustedOrigin, redirect, }: {
96
+ declare function fetchWithValidatedEndpoint({ url, init, fetch: customFetch, trustedOrigin, redirect, requireDnsValidation, }: {
97
97
  url: string | URL;
98
98
  init?: RequestInit;
99
99
  fetch?: FetchFunction;
@@ -103,6 +103,11 @@ declare function fetchWithValidatedEndpoint({ url, init, fetch: customFetch, tru
103
103
  */
104
104
  trustedOrigin?: string;
105
105
  redirect?: 'error' | 'manual';
106
+ /**
107
+ * Reject untrusted URLs on server runtimes without a DNS-pinned default
108
+ * transport unless an explicit custom fetch provides equivalent validation.
109
+ */
110
+ requireDnsValidation?: boolean;
106
111
  }): Promise<Response>;
107
112
  /**
108
113
  * Fetches a URL while enforcing the SSRF download guard on every hop.
@@ -113,6 +118,12 @@ declare function fetchWithValidatedEndpoint({ url, init, fetch: customFetch, tru
113
118
  * target (e.g. an internal address) before we ever see its URL, defeating the
114
119
  * SSRF guard.
115
120
  *
121
+ * Manually followed redirects from HTTPS to HTTP are rejected before requesting
122
+ * the target.
123
+ *
124
+ * All caller headers except User-Agent are dropped on cross-origin redirects.
125
+ * Callers must decide which credentials may be sent to the initial URL.
126
+ *
116
127
  * A `redirect: 'manual'` request yields an unreadable opaque response in the
117
128
  * browser (and in other spec-compliant fetch implementations), so the redirect
118
129
  * target cannot be validated here. In a real browser this is safe to follow
@@ -347,13 +358,44 @@ declare const createJsonResponseHandler: <T>(responseSchema: FlexibleValidator<T
347
358
  declare const createBinaryResponseHandler: () => ResponseHandler<Uint8Array>;
348
359
  declare const createStatusCodeErrorResponseHandler: () => ResponseHandler<APICallError>;
349
360
 
350
- declare const getFromApi: <T>({ url, headers, successfulResponseHandler, failedResponseHandler, abortSignal, fetch, }: {
361
+ declare const getFromApi: <T>({ url, headers, successfulResponseHandler, failedResponseHandler, abortSignal, fetch, validateUrl, credentialedOrigin, trustedOrigin, }: {
351
362
  url: string;
352
363
  headers?: Record<string, string | undefined>;
353
364
  failedResponseHandler: ResponseHandler<Error>;
354
365
  successfulResponseHandler: ResponseHandler<T>;
355
366
  abortSignal?: AbortSignal;
356
367
  fetch?: FetchFunction;
368
+ /**
369
+ * Set `true` when `url` is untrusted (e.g. taken from a provider response
370
+ * body): it is routed through {@link fetchWithValidatedRedirects}, which
371
+ * rejects private/loopback/link-local targets and re-validates redirect
372
+ * hops; blocked URLs throw `DownloadError`. Set `false` only for URLs built
373
+ * from a developer-configured endpoint.
374
+ *
375
+ * Optional for backwards compatibility with existing callers; omitting it
376
+ * behaves like `false` (no validation).
377
+ */
378
+ validateUrl?: boolean;
379
+ /**
380
+ * When set, `headers` are sent only if `url` is same-origin with this origin
381
+ * (the user-agent suffix is always kept). Pass the provider's configured
382
+ * base URL alongside `validateUrl: true` so credentials never ride a request
383
+ * to a response-supplied host on a different origin (e.g. a CDN). Redirects
384
+ * that later cross origin drop all caller headers regardless (see
385
+ * {@link fetchWithValidatedRedirects}).
386
+ */
387
+ credentialedOrigin?: string;
388
+ /**
389
+ * A developer-configured origin (e.g. the provider's `baseURL`) that is
390
+ * exempt from URL validation when `validateUrl` is `true`. A response URL
391
+ * (or redirect hop) that is same-origin with it is fetched without target
392
+ * validation — it points at exactly the host a config-derived
393
+ * `validateUrl: false` request would fetch anyway, so blocking it would
394
+ * only break legitimate self-hosted / localhost deployments whose response
395
+ * URLs point back at the configured host. Hops on any other origin are
396
+ * still validated. Must never be derived from response data.
397
+ */
398
+ trustedOrigin?: string;
357
399
  }) => Promise<{
358
400
  value: T;
359
401
  rawValue?: unknown;
package/dist/index.js CHANGED
@@ -543,12 +543,20 @@ async function fetchWithValidatedEndpoint({
543
543
  init,
544
544
  fetch: customFetch,
545
545
  trustedOrigin,
546
- redirect = "error"
546
+ redirect = "error",
547
+ requireDnsValidation = false
547
548
  }) {
548
549
  const urlText = url.toString();
549
550
  const isTrusted = trustedOrigin !== void 0 && isSameOrigin(urlText, trustedOrigin);
550
551
  if (!isTrusted) {
551
552
  validateDownloadUrl(urlText);
553
+ if (requireDnsValidation && (customFetch == null || customFetch === globalThis.fetch) && !isNodeRuntime() && // A window alias alone does not distinguish older Deno from a browser.
554
+ !(isBrowserRuntime() && typeof document !== "undefined")) {
555
+ throw new DownloadError({
556
+ url: urlText,
557
+ message: "This server runtime requires a custom fetch with connect-time DNS validation for untrusted URLs"
558
+ });
559
+ }
552
560
  }
553
561
  const fetch = isTrusted && customFetch != null ? customFetch : isTrusted ? globalThis.fetch : await getValidatedFetch(customFetch);
554
562
  return await fetch(url, {
@@ -565,10 +573,12 @@ async function fetchWithValidatedRedirects({
565
573
  trustedOrigin
566
574
  }) {
567
575
  var _a2;
568
- const baseInit = { signal: abortSignal };
569
- if (headers !== void 0) {
570
- baseInit.headers = headers;
571
- }
576
+ let currentHeaders = headers === void 0 ? void 0 : new Headers(headers);
577
+ const perHopInit = (redirect) => ({
578
+ signal: abortSignal,
579
+ redirect,
580
+ ...currentHeaders === void 0 ? {} : { headers: new Headers(currentHeaders) }
581
+ });
572
582
  let currentUrl = url;
573
583
  for (let redirectCount = 0; redirectCount <= maxRedirects; redirectCount++) {
574
584
  const isTrustedHop = trustedOrigin !== void 0 && isSameOrigin(currentUrl, trustedOrigin);
@@ -576,10 +586,7 @@ async function fetchWithValidatedRedirects({
576
586
  validateDownloadUrl(currentUrl);
577
587
  }
578
588
  const fetch = isTrustedHop && customFetch != null ? customFetch : isTrustedHop ? globalThis.fetch : await getValidatedFetch(customFetch);
579
- const response = await fetch(currentUrl, {
580
- ...baseInit,
581
- redirect: "manual"
582
- });
589
+ const response = await fetch(currentUrl, perHopInit("manual"));
583
590
  if (response.type === "opaqueredirect") {
584
591
  if (!isBrowserRuntime()) {
585
592
  throw new DownloadError({
@@ -587,12 +594,25 @@ async function fetchWithValidatedRedirects({
587
594
  message: `Redirect from ${currentUrl} could not be validated and was blocked`
588
595
  });
589
596
  }
590
- return await fetch(currentUrl, { ...baseInit, redirect: "follow" });
597
+ return await fetch(currentUrl, perHopInit("follow"));
591
598
  }
592
599
  const location = (_a2 = response.headers) == null ? void 0 : _a2.get("location");
593
600
  if (response.status >= 300 && response.status < 400 && location) {
594
- await cancelResponseBody(response);
595
- currentUrl = new URL(location, currentUrl).toString();
601
+ void cancelResponseBody(response);
602
+ const nextUrl = new URL(location, currentUrl).toString();
603
+ if (new URL(currentUrl).protocol === "https:" && new URL(nextUrl).protocol === "http:") {
604
+ throw new DownloadError({
605
+ url,
606
+ message: "Redirect from HTTPS to HTTP was blocked"
607
+ });
608
+ }
609
+ if (currentHeaders !== void 0 && !isSameOrigin(nextUrl, currentUrl)) {
610
+ const userAgent = currentHeaders.get("user-agent");
611
+ currentHeaders = new Headers(
612
+ userAgent == null ? void 0 : { "user-agent": userAgent }
613
+ );
614
+ }
615
+ currentUrl = nextUrl;
596
616
  continue;
597
617
  }
598
618
  return response;
@@ -849,7 +869,7 @@ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
849
869
  }
850
870
 
851
871
  // src/version.ts
852
- var VERSION = true ? "3.0.44" : "0.0.0-test";
872
+ var VERSION = true ? "3.0.46" : "0.0.0-test";
853
873
 
854
874
  // src/get-from-api.ts
855
875
  var getOriginalFetch = () => globalThis.fetch;
@@ -859,16 +879,28 @@ var getFromApi = async ({
859
879
  successfulResponseHandler,
860
880
  failedResponseHandler,
861
881
  abortSignal,
862
- fetch = getOriginalFetch()
882
+ fetch,
883
+ validateUrl,
884
+ credentialedOrigin,
885
+ trustedOrigin
863
886
  }) => {
864
887
  try {
865
- const response = await fetch(url, {
888
+ const requestFetch = fetch != null ? fetch : getOriginalFetch();
889
+ const outgoingHeaders = credentialedOrigin !== void 0 && !isSameOrigin(url, credentialedOrigin) ? {} : headers;
890
+ const requestHeaders = withUserAgentSuffix(
891
+ outgoingHeaders,
892
+ `ai-sdk/provider-utils/${VERSION}`,
893
+ getRuntimeEnvironmentUserAgent()
894
+ );
895
+ const response = validateUrl ? await fetchWithValidatedRedirects({
896
+ url,
897
+ headers: requestHeaders,
898
+ abortSignal,
899
+ fetch,
900
+ trustedOrigin
901
+ }) : await requestFetch(url, {
866
902
  method: "GET",
867
- headers: withUserAgentSuffix(
868
- headers,
869
- `ai-sdk/provider-utils/${VERSION}`,
870
- getRuntimeEnvironmentUserAgent()
871
- ),
903
+ headers: requestHeaders,
872
904
  signal: abortSignal
873
905
  });
874
906
  const responseHeaders = extractResponseHeaders(response);