@ai-sdk/provider-utils 3.0.44 → 3.0.45

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,12 @@
1
1
  # @ai-sdk/provider-utils
2
2
 
3
+ ## 3.0.45
4
+
5
+ ### Patch Changes
6
+
7
+ - 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.
8
+ - b753c03: Reject HTTPS-to-HTTP redirects in validated downloads before requesting the insecure target, including when it matches a configured trusted origin.
9
+
3
10
  ## 3.0.44
4
11
 
5
12
  ### Patch Changes
package/dist/index.d.mts CHANGED
@@ -113,6 +113,12 @@ declare function fetchWithValidatedEndpoint({ url, init, fetch: customFetch, tru
113
113
  * target (e.g. an internal address) before we ever see its URL, defeating the
114
114
  * SSRF guard.
115
115
  *
116
+ * Manually followed redirects from HTTPS to HTTP are rejected before requesting
117
+ * the target.
118
+ *
119
+ * All caller headers except User-Agent are dropped on cross-origin redirects.
120
+ * Callers must decide which credentials may be sent to the initial URL.
121
+ *
116
122
  * A `redirect: 'manual'` request yields an unreadable opaque response in the
117
123
  * browser (and in other spec-compliant fetch implementations), so the redirect
118
124
  * target cannot be validated here. In a real browser this is safe to follow
@@ -347,13 +353,44 @@ declare const createJsonResponseHandler: <T>(responseSchema: FlexibleValidator<T
347
353
  declare const createBinaryResponseHandler: () => ResponseHandler<Uint8Array>;
348
354
  declare const createStatusCodeErrorResponseHandler: () => ResponseHandler<APICallError>;
349
355
 
350
- declare const getFromApi: <T>({ url, headers, successfulResponseHandler, failedResponseHandler, abortSignal, fetch, }: {
356
+ declare const getFromApi: <T>({ url, headers, successfulResponseHandler, failedResponseHandler, abortSignal, fetch, validateUrl, credentialedOrigin, trustedOrigin, }: {
351
357
  url: string;
352
358
  headers?: Record<string, string | undefined>;
353
359
  failedResponseHandler: ResponseHandler<Error>;
354
360
  successfulResponseHandler: ResponseHandler<T>;
355
361
  abortSignal?: AbortSignal;
356
362
  fetch?: FetchFunction;
363
+ /**
364
+ * Set `true` when `url` is untrusted (e.g. taken from a provider response
365
+ * body): it is routed through {@link fetchWithValidatedRedirects}, which
366
+ * rejects private/loopback/link-local targets and re-validates redirect
367
+ * hops; blocked URLs throw `DownloadError`. Set `false` only for URLs built
368
+ * from a developer-configured endpoint.
369
+ *
370
+ * Optional for backwards compatibility with existing callers; omitting it
371
+ * behaves like `false` (no validation).
372
+ */
373
+ validateUrl?: boolean;
374
+ /**
375
+ * When set, `headers` are sent only if `url` is same-origin with this origin
376
+ * (the user-agent suffix is always kept). Pass the provider's configured
377
+ * base URL alongside `validateUrl: true` so credentials never ride a request
378
+ * to a response-supplied host on a different origin (e.g. a CDN). Redirects
379
+ * that later cross origin drop all caller headers regardless (see
380
+ * {@link fetchWithValidatedRedirects}).
381
+ */
382
+ credentialedOrigin?: string;
383
+ /**
384
+ * A developer-configured origin (e.g. the provider's `baseURL`) that is
385
+ * exempt from URL validation when `validateUrl` is `true`. A response URL
386
+ * (or redirect hop) that is same-origin with it is fetched without target
387
+ * validation — it points at exactly the host a config-derived
388
+ * `validateUrl: false` request would fetch anyway, so blocking it would
389
+ * only break legitimate self-hosted / localhost deployments whose response
390
+ * URLs point back at the configured host. Hops on any other origin are
391
+ * still validated. Must never be derived from response data.
392
+ */
393
+ trustedOrigin?: string;
357
394
  }) => Promise<{
358
395
  value: T;
359
396
  rawValue?: unknown;
package/dist/index.d.ts CHANGED
@@ -113,6 +113,12 @@ declare function fetchWithValidatedEndpoint({ url, init, fetch: customFetch, tru
113
113
  * target (e.g. an internal address) before we ever see its URL, defeating the
114
114
  * SSRF guard.
115
115
  *
116
+ * Manually followed redirects from HTTPS to HTTP are rejected before requesting
117
+ * the target.
118
+ *
119
+ * All caller headers except User-Agent are dropped on cross-origin redirects.
120
+ * Callers must decide which credentials may be sent to the initial URL.
121
+ *
116
122
  * A `redirect: 'manual'` request yields an unreadable opaque response in the
117
123
  * browser (and in other spec-compliant fetch implementations), so the redirect
118
124
  * target cannot be validated here. In a real browser this is safe to follow
@@ -347,13 +353,44 @@ declare const createJsonResponseHandler: <T>(responseSchema: FlexibleValidator<T
347
353
  declare const createBinaryResponseHandler: () => ResponseHandler<Uint8Array>;
348
354
  declare const createStatusCodeErrorResponseHandler: () => ResponseHandler<APICallError>;
349
355
 
350
- declare const getFromApi: <T>({ url, headers, successfulResponseHandler, failedResponseHandler, abortSignal, fetch, }: {
356
+ declare const getFromApi: <T>({ url, headers, successfulResponseHandler, failedResponseHandler, abortSignal, fetch, validateUrl, credentialedOrigin, trustedOrigin, }: {
351
357
  url: string;
352
358
  headers?: Record<string, string | undefined>;
353
359
  failedResponseHandler: ResponseHandler<Error>;
354
360
  successfulResponseHandler: ResponseHandler<T>;
355
361
  abortSignal?: AbortSignal;
356
362
  fetch?: FetchFunction;
363
+ /**
364
+ * Set `true` when `url` is untrusted (e.g. taken from a provider response
365
+ * body): it is routed through {@link fetchWithValidatedRedirects}, which
366
+ * rejects private/loopback/link-local targets and re-validates redirect
367
+ * hops; blocked URLs throw `DownloadError`. Set `false` only for URLs built
368
+ * from a developer-configured endpoint.
369
+ *
370
+ * Optional for backwards compatibility with existing callers; omitting it
371
+ * behaves like `false` (no validation).
372
+ */
373
+ validateUrl?: boolean;
374
+ /**
375
+ * When set, `headers` are sent only if `url` is same-origin with this origin
376
+ * (the user-agent suffix is always kept). Pass the provider's configured
377
+ * base URL alongside `validateUrl: true` so credentials never ride a request
378
+ * to a response-supplied host on a different origin (e.g. a CDN). Redirects
379
+ * that later cross origin drop all caller headers regardless (see
380
+ * {@link fetchWithValidatedRedirects}).
381
+ */
382
+ credentialedOrigin?: string;
383
+ /**
384
+ * A developer-configured origin (e.g. the provider's `baseURL`) that is
385
+ * exempt from URL validation when `validateUrl` is `true`. A response URL
386
+ * (or redirect hop) that is same-origin with it is fetched without target
387
+ * validation — it points at exactly the host a config-derived
388
+ * `validateUrl: false` request would fetch anyway, so blocking it would
389
+ * only break legitimate self-hosted / localhost deployments whose response
390
+ * URLs point back at the configured host. Hops on any other origin are
391
+ * still validated. Must never be derived from response data.
392
+ */
393
+ trustedOrigin?: string;
357
394
  }) => Promise<{
358
395
  value: T;
359
396
  rawValue?: unknown;
package/dist/index.js CHANGED
@@ -565,10 +565,12 @@ async function fetchWithValidatedRedirects({
565
565
  trustedOrigin
566
566
  }) {
567
567
  var _a2;
568
- const baseInit = { signal: abortSignal };
569
- if (headers !== void 0) {
570
- baseInit.headers = headers;
571
- }
568
+ let currentHeaders = headers === void 0 ? void 0 : new Headers(headers);
569
+ const perHopInit = (redirect) => ({
570
+ signal: abortSignal,
571
+ redirect,
572
+ ...currentHeaders === void 0 ? {} : { headers: new Headers(currentHeaders) }
573
+ });
572
574
  let currentUrl = url;
573
575
  for (let redirectCount = 0; redirectCount <= maxRedirects; redirectCount++) {
574
576
  const isTrustedHop = trustedOrigin !== void 0 && isSameOrigin(currentUrl, trustedOrigin);
@@ -576,10 +578,7 @@ async function fetchWithValidatedRedirects({
576
578
  validateDownloadUrl(currentUrl);
577
579
  }
578
580
  const fetch = isTrustedHop && customFetch != null ? customFetch : isTrustedHop ? globalThis.fetch : await getValidatedFetch(customFetch);
579
- const response = await fetch(currentUrl, {
580
- ...baseInit,
581
- redirect: "manual"
582
- });
581
+ const response = await fetch(currentUrl, perHopInit("manual"));
583
582
  if (response.type === "opaqueredirect") {
584
583
  if (!isBrowserRuntime()) {
585
584
  throw new DownloadError({
@@ -587,12 +586,25 @@ async function fetchWithValidatedRedirects({
587
586
  message: `Redirect from ${currentUrl} could not be validated and was blocked`
588
587
  });
589
588
  }
590
- return await fetch(currentUrl, { ...baseInit, redirect: "follow" });
589
+ return await fetch(currentUrl, perHopInit("follow"));
591
590
  }
592
591
  const location = (_a2 = response.headers) == null ? void 0 : _a2.get("location");
593
592
  if (response.status >= 300 && response.status < 400 && location) {
594
- await cancelResponseBody(response);
595
- currentUrl = new URL(location, currentUrl).toString();
593
+ void cancelResponseBody(response);
594
+ const nextUrl = new URL(location, currentUrl).toString();
595
+ if (new URL(currentUrl).protocol === "https:" && new URL(nextUrl).protocol === "http:") {
596
+ throw new DownloadError({
597
+ url,
598
+ message: "Redirect from HTTPS to HTTP was blocked"
599
+ });
600
+ }
601
+ if (currentHeaders !== void 0 && !isSameOrigin(nextUrl, currentUrl)) {
602
+ const userAgent = currentHeaders.get("user-agent");
603
+ currentHeaders = new Headers(
604
+ userAgent == null ? void 0 : { "user-agent": userAgent }
605
+ );
606
+ }
607
+ currentUrl = nextUrl;
596
608
  continue;
597
609
  }
598
610
  return response;
@@ -849,7 +861,7 @@ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
849
861
  }
850
862
 
851
863
  // src/version.ts
852
- var VERSION = true ? "3.0.44" : "0.0.0-test";
864
+ var VERSION = true ? "3.0.45" : "0.0.0-test";
853
865
 
854
866
  // src/get-from-api.ts
855
867
  var getOriginalFetch = () => globalThis.fetch;
@@ -859,16 +871,28 @@ var getFromApi = async ({
859
871
  successfulResponseHandler,
860
872
  failedResponseHandler,
861
873
  abortSignal,
862
- fetch = getOriginalFetch()
874
+ fetch,
875
+ validateUrl,
876
+ credentialedOrigin,
877
+ trustedOrigin
863
878
  }) => {
864
879
  try {
865
- const response = await fetch(url, {
880
+ const requestFetch = fetch != null ? fetch : getOriginalFetch();
881
+ const outgoingHeaders = credentialedOrigin !== void 0 && !isSameOrigin(url, credentialedOrigin) ? {} : headers;
882
+ const requestHeaders = withUserAgentSuffix(
883
+ outgoingHeaders,
884
+ `ai-sdk/provider-utils/${VERSION}`,
885
+ getRuntimeEnvironmentUserAgent()
886
+ );
887
+ const response = validateUrl ? await fetchWithValidatedRedirects({
888
+ url,
889
+ headers: requestHeaders,
890
+ abortSignal,
891
+ fetch,
892
+ trustedOrigin
893
+ }) : await requestFetch(url, {
866
894
  method: "GET",
867
- headers: withUserAgentSuffix(
868
- headers,
869
- `ai-sdk/provider-utils/${VERSION}`,
870
- getRuntimeEnvironmentUserAgent()
871
- ),
895
+ headers: requestHeaders,
872
896
  signal: abortSignal
873
897
  });
874
898
  const responseHeaders = extractResponseHeaders(response);