fastmcp 4.26.0 → 4.26.2

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 (36) hide show
  1. package/README.md +16 -6
  2. package/dist/FastMCP.cjs +3 -3
  3. package/dist/FastMCP.d.cts +2 -2
  4. package/dist/FastMCP.d.ts +2 -2
  5. package/dist/FastMCP.js +2 -2
  6. package/dist/{OAuthProvider-CPC9zG96.d.cts → OAuthProvider-B7VDZGyx.d.cts} +55 -3
  7. package/dist/{OAuthProvider-CPC9zG96.d.ts → OAuthProvider-B7VDZGyx.d.ts} +55 -3
  8. package/dist/auth/index.cjs +2 -2
  9. package/dist/auth/index.d.cts +17 -3
  10. package/dist/auth/index.d.ts +17 -3
  11. package/dist/auth/index.js +1 -1
  12. package/dist/{chunk-LUGELV2V.js → chunk-ASOZUCE2.js} +180 -36
  13. package/dist/chunk-ASOZUCE2.js.map +1 -0
  14. package/dist/{chunk-AKHG27NY.cjs → chunk-HVKGDRTL.cjs} +286 -66
  15. package/dist/chunk-HVKGDRTL.cjs.map +1 -0
  16. package/dist/{chunk-ZHTH5HQD.cjs → chunk-UULT6NOS.cjs} +212 -68
  17. package/dist/chunk-UULT6NOS.cjs.map +1 -0
  18. package/dist/{chunk-3VYVXSBB.js → chunk-W6P57SNV.js} +272 -52
  19. package/dist/chunk-W6P57SNV.js.map +1 -0
  20. package/dist/edge/index.cjs +110 -16
  21. package/dist/edge/index.cjs.map +1 -1
  22. package/dist/edge/index.d.cts +7 -2
  23. package/dist/edge/index.d.ts +7 -2
  24. package/dist/edge/index.js +110 -16
  25. package/dist/edge/index.js.map +1 -1
  26. package/dist/examples/custom-routes.cjs +3 -3
  27. package/dist/examples/custom-routes.js +2 -2
  28. package/dist/openapi/index.cjs +8 -8
  29. package/dist/openapi/index.d.cts +1 -1
  30. package/dist/openapi/index.d.ts +1 -1
  31. package/dist/openapi/index.js +2 -2
  32. package/package.json +1 -1
  33. package/dist/chunk-3VYVXSBB.js.map +0 -1
  34. package/dist/chunk-AKHG27NY.cjs.map +0 -1
  35. package/dist/chunk-LUGELV2V.js.map +0 -1
  36. package/dist/chunk-ZHTH5HQD.cjs.map +0 -1
@@ -6,12 +6,10 @@ function getAuthSession(session) {
6
6
  return session;
7
7
  }
8
8
  function requireAll(...checks) {
9
- return (auth) => checks.every(
10
- (check) => typeof check === "function" ? check(auth) : check
11
- );
9
+ return (auth) => checks.every((check) => passes(check, auth));
12
10
  }
13
11
  function requireAny(...checks) {
14
- return (auth) => checks.some((check) => typeof check === "function" ? check(auth) : check);
12
+ return (auth) => checks.some((check) => passes(check, auth));
15
13
  }
16
14
  function requireAuth(auth) {
17
15
  return auth !== void 0 && auth !== null;
@@ -32,6 +30,14 @@ function requireScopes(...requiredScopes) {
32
30
  return requiredScopes.every((scope) => scopeSet.has(scope));
33
31
  };
34
32
  }
33
+ function passes(check, auth) {
34
+ const result = typeof check === "function" ? check(auth) : check;
35
+ if (typeof result?.then === "function") {
36
+ Promise.resolve(result).catch(() => {
37
+ });
38
+ }
39
+ return result === true;
40
+ }
35
41
 
36
42
  // src/auth/OAuthProxy.ts
37
43
  import { createHash as createHash2, randomBytes as randomBytes4 } from "crypto";
@@ -127,6 +133,7 @@ var oauthTransactionStorageSchema = z.object({
127
133
  clientCodeChallenge: z.string(),
128
134
  clientCodeChallengeMethod: z.string(),
129
135
  clientId: z.string(),
136
+ consentBinding: z.string().optional(),
130
137
  consentGiven: z.boolean().optional(),
131
138
  createdAt: storedDateSchema,
132
139
  expiresAt: storedDateSchema,
@@ -646,28 +653,38 @@ var ConsentManager = class {
646
653
  }
647
654
  /**
648
655
  * Create HTTP response with consent screen
656
+ *
657
+ * `cookie` is a `Set-Cookie` value that ties the request to the browser the
658
+ * screen is shown to. The screen may not be framed: a page that embeds it
659
+ * could have the user approve without seeing what they are approving.
649
660
  */
650
- createConsentResponse(transaction, provider) {
661
+ createConsentResponse(transaction, provider, options = {}) {
651
662
  const consentData = {
652
- clientName: "MCP Client",
663
+ clientName: options.clientName || "MCP Client",
653
664
  provider,
665
+ redirectUri: transaction.clientCallbackUrl,
654
666
  scope: transaction.scope,
655
667
  timestamp: Date.now(),
656
668
  transactionId: transaction.id
657
669
  };
658
670
  const html = this.generateConsentScreen(consentData);
659
- return new Response(html, {
660
- headers: {
661
- "Content-Type": "text/html; charset=utf-8"
662
- },
663
- status: 200
671
+ const headers = new Headers({
672
+ "Cache-Control": "no-store",
673
+ "Content-Security-Policy": "frame-ancestors 'none'",
674
+ "Content-Type": "text/html; charset=utf-8",
675
+ "X-Frame-Options": "DENY"
664
676
  });
677
+ if (options.cookie) {
678
+ headers.append("Set-Cookie", options.cookie);
679
+ }
680
+ return new Response(html, { headers, status: 200 });
665
681
  }
666
682
  /**
667
683
  * Generate HTML for consent screen
668
684
  */
669
685
  generateConsentScreen(data) {
670
- const { clientName, provider, scope, transactionId } = data;
686
+ const { clientName, provider, redirectUri, scope, transactionId } = data;
687
+ const destination = redirectUri && this.describeDestination(redirectUri);
671
688
  return `
672
689
  <!DOCTYPE html>
673
690
  <html lang="en">
@@ -735,6 +752,12 @@ var ConsentManager = class {
735
752
  font-weight: 600;
736
753
  }
737
754
 
755
+ .destination {
756
+ color: #4a5568;
757
+ font-size: 14px;
758
+ overflow-wrap: anywhere;
759
+ }
760
+
738
761
  .permissions {
739
762
  margin-top: 16px;
740
763
  }
@@ -833,10 +856,15 @@ var ConsentManager = class {
833
856
 
834
857
  <div class="app-info">
835
858
  <h2>
836
- <span class="app-name">${this.escapeHtml(clientName || "An application")}</span>
859
+ <span class="app-name">${this.escapeHtml((clientName || "An application").slice(0, 100))}</span>
837
860
  requests access
838
861
  </h2>
839
-
862
+ ${destination ? `
863
+ <p class="destination">
864
+ If you approve, you will be sent to
865
+ <strong>${this.escapeHtml(destination)}</strong>
866
+ </p>
867
+ ` : ""}
840
868
  <div class="permissions">
841
869
  <h3>This will allow the app to:</h3>
842
870
  <ul>
@@ -904,6 +932,23 @@ var ConsentManager = class {
904
932
  return null;
905
933
  }
906
934
  }
935
+ /**
936
+ * Where a redirect URI leads, as the browser will read it rather than as it
937
+ * was typed: the parsed host, so that a look-alike character, a tab or a
938
+ * backslash shows for what it does. A long host keeps its end, which is the
939
+ * part that says whose it is.
940
+ */
941
+ describeDestination(redirectUri) {
942
+ let url;
943
+ try {
944
+ url = new URL(redirectUri);
945
+ } catch {
946
+ return void 0;
947
+ }
948
+ const host = url.host.length > 80 ? `\u2026${url.host.slice(-80)}` : url.host;
949
+ const path = url.pathname.length > 80 ? `${url.pathname.slice(0, 80)}\u2026` : url.pathname;
950
+ return host ? `${url.protocol}//${host}${path}` : `${url.protocol}${path}`;
951
+ }
907
952
  /**
908
953
  * Escape HTML to prevent XSS
909
954
  */
@@ -1341,6 +1386,15 @@ var MemoryTokenStorage = class {
1341
1386
  };
1342
1387
 
1343
1388
  // src/auth/OAuthProxy.ts
1389
+ var DEFAULT_PORTS = {
1390
+ "ftp:": "21",
1391
+ "http:": "80",
1392
+ "https:": "443",
1393
+ "ws:": "80",
1394
+ "wss:": "443"
1395
+ };
1396
+ var CONSENT_COOKIE_VALUE = /^[\w-]{43}$/;
1397
+ var MAX_CLIENT_REGISTRATION_BYTES = 32 * 1024;
1344
1398
  var RESERVED_AUTHORIZATION_PARAMS = /* @__PURE__ */ new Set([
1345
1399
  "client_id",
1346
1400
  "code_challenge",
@@ -1386,7 +1440,6 @@ var OAuthProxy = class {
1386
1440
  allowPlainPkce: true,
1387
1441
  authorizationCodeTtl: DEFAULT_AUTHORIZATION_CODE_TTL,
1388
1442
  authorizationResponseIss: true,
1389
- consentRequired: true,
1390
1443
  enableCimd: false,
1391
1444
  enableTokenSwap: true,
1392
1445
  // Enabled by default for security
@@ -1394,7 +1447,10 @@ var OAuthProxy = class {
1394
1447
  transactionTtl: DEFAULT_TRANSACTION_TTL,
1395
1448
  upstreamRequestTimeoutMs: DEFAULT_UPSTREAM_REQUEST_TIMEOUT_MS,
1396
1449
  upstreamTokenEndpointAuthMethod: "client_secret_basic",
1397
- ...config
1450
+ ...config,
1451
+ // Spreading an explicit `undefined` over the default would turn consent
1452
+ // off for a caller that only meant to pass an option along.
1453
+ consentRequired: config.consentRequired ?? true
1398
1454
  };
1399
1455
  let storage = config.tokenStorage;
1400
1456
  if (!storage) {
@@ -1431,7 +1487,7 @@ var OAuthProxy = class {
1431
1487
  /**
1432
1488
  * OAuth authorization endpoint
1433
1489
  */
1434
- async authorize(params) {
1490
+ async authorize(params, request) {
1435
1491
  if (!params.client_id || !params.redirect_uri || !params.response_type) {
1436
1492
  throw new OAuthProxyError(
1437
1493
  "invalid_request",
@@ -1457,6 +1513,12 @@ var OAuthProxy = class {
1457
1513
  "redirect_uri is not registered for this client"
1458
1514
  );
1459
1515
  }
1516
+ if (!this.validateRedirectUri(params.redirect_uri)) {
1517
+ throw new OAuthProxyError(
1518
+ "invalid_request",
1519
+ "redirect_uri is no longer allowed"
1520
+ );
1521
+ }
1460
1522
  if (params.code_challenge && !params.code_challenge_method) {
1461
1523
  throw new OAuthProxyError(
1462
1524
  "invalid_request",
@@ -1490,11 +1552,17 @@ var OAuthProxy = class {
1490
1552
  );
1491
1553
  }
1492
1554
  }
1493
- const transaction = await this.createTransaction(params);
1494
- if (this.config.consentRequired && !transaction.consentGiven) {
1555
+ const consentBinding = this.config.consentRequired ? (request && this.consentCookieValue(request)) ?? this.generateId() : void 0;
1556
+ const transaction = await this.createTransaction(params, consentBinding);
1557
+ if (consentBinding && !transaction.consentGiven) {
1558
+ const clientName = registeredClient.metadata?.client_name;
1495
1559
  return this.consentManager.createConsentResponse(
1496
1560
  transaction,
1497
- this.getProviderName()
1561
+ this.getProviderName(),
1562
+ {
1563
+ clientName: typeof clientName === "string" ? clientName : void 0,
1564
+ cookie: this.consentCookie(consentBinding)
1565
+ }
1498
1566
  );
1499
1567
  }
1500
1568
  return this.redirectToUpstream(transaction);
@@ -1661,6 +1729,12 @@ var OAuthProxy = class {
1661
1729
  if (!transaction) {
1662
1730
  throw new OAuthProxyError("invalid_request", "Invalid or expired state");
1663
1731
  }
1732
+ if (this.config.consentRequired && !(transaction.consentGiven && this.isConsentBoundTo(request, transaction))) {
1733
+ throw new OAuthProxyError(
1734
+ "access_denied",
1735
+ "This authorization request was not approved in this browser"
1736
+ );
1737
+ }
1664
1738
  if (!await this.isTransactionCallbackRegistered(transaction)) {
1665
1739
  throw new OAuthProxyError(
1666
1740
  "invalid_request",
@@ -1708,6 +1782,12 @@ var OAuthProxy = class {
1708
1782
  "Invalid or expired transaction"
1709
1783
  );
1710
1784
  }
1785
+ if (!this.isConsentBoundTo(request, transaction)) {
1786
+ throw new OAuthProxyError(
1787
+ "invalid_request",
1788
+ "Consent must be given in the browser that requested it"
1789
+ );
1790
+ }
1711
1791
  if (action === "deny") {
1712
1792
  await this.stateStore.deleteTransaction(transactionId);
1713
1793
  if (!await this.isTransactionCallbackRegistered(transaction)) {
@@ -1763,7 +1843,15 @@ var OAuthProxy = class {
1763
1843
  const upstreamTokens = await this.tokenStorage.get(
1764
1844
  `upstream:${mapping.upstreamTokenKey}`
1765
1845
  );
1766
- return upstreamTokens;
1846
+ if (!upstreamTokens || !Array.isArray(mapping.scope)) {
1847
+ return upstreamTokens;
1848
+ }
1849
+ return {
1850
+ ...upstreamTokens,
1851
+ scope: mapping.scope.filter(
1852
+ (scope) => upstreamTokens.scope.includes(scope)
1853
+ )
1854
+ };
1767
1855
  }
1768
1856
  /**
1769
1857
  * RFC 7591 Dynamic Client Registration
@@ -1775,6 +1863,27 @@ var OAuthProxy = class {
1775
1863
  "redirect_uris is required"
1776
1864
  );
1777
1865
  }
1866
+ const metadata = {
1867
+ client_name: request.client_name,
1868
+ client_uri: request.client_uri,
1869
+ contacts: request.contacts,
1870
+ jwks: request.jwks,
1871
+ jwks_uri: request.jwks_uri,
1872
+ logo_uri: request.logo_uri,
1873
+ policy_uri: request.policy_uri,
1874
+ scope: request.scope,
1875
+ software_id: request.software_id,
1876
+ software_version: request.software_version,
1877
+ tos_uri: request.tos_uri
1878
+ };
1879
+ if (Buffer.byteLength(
1880
+ JSON.stringify({ metadata, redirect_uris: request.redirect_uris })
1881
+ ) > MAX_CLIENT_REGISTRATION_BYTES) {
1882
+ throw new OAuthProxyError(
1883
+ "invalid_client_metadata",
1884
+ `Client metadata must not exceed ${MAX_CLIENT_REGISTRATION_BYTES} bytes`
1885
+ );
1886
+ }
1778
1887
  for (const uri of request.redirect_uris) {
1779
1888
  if (!this.validateRedirectUri(uri)) {
1780
1889
  throw new OAuthProxyError(
@@ -1796,19 +1905,7 @@ var OAuthProxy = class {
1796
1905
  callbackUrl: request.redirect_uris[0],
1797
1906
  clientId: proxyClientId,
1798
1907
  clientSecret: proxyClientSecret,
1799
- metadata: {
1800
- client_name: request.client_name,
1801
- client_uri: request.client_uri,
1802
- contacts: request.contacts,
1803
- jwks: request.jwks,
1804
- jwks_uri: request.jwks_uri,
1805
- logo_uri: request.logo_uri,
1806
- policy_uri: request.policy_uri,
1807
- scope: request.scope,
1808
- software_id: request.software_id,
1809
- software_version: request.software_version,
1810
- tos_uri: request.tos_uri
1811
- },
1908
+ metadata,
1812
1909
  redirectUris: request.redirect_uris,
1813
1910
  registeredAt: /* @__PURE__ */ new Date(),
1814
1911
  tokenEndpointAuthMethod
@@ -1907,10 +2004,49 @@ var OAuthProxy = class {
1907
2004
  );
1908
2005
  });
1909
2006
  }
2007
+ /**
2008
+ * The cookie that ties consent requests to the browser they were shown to.
2009
+ * A browser holds one, shared by every request it has open, and it lasts as
2010
+ * long as a request does. `Lax` lets it travel with the provider's redirect
2011
+ * back to the callback, which is a cross-site navigation. Over HTTPS the
2012
+ * `__Host-` prefix keeps another host on the same site from setting it.
2013
+ */
2014
+ consentCookie(value) {
2015
+ return [
2016
+ `${this.consentCookieName()}=${value}`,
2017
+ "Path=/",
2018
+ `Max-Age=${this.config.transactionTtl || 600}`,
2019
+ "HttpOnly",
2020
+ "SameSite=Lax",
2021
+ ...this.isServedOverHttps() ? ["Secure"] : []
2022
+ ].join("; ");
2023
+ }
2024
+ consentCookieName() {
2025
+ return `${this.isServedOverHttps() ? "__Host-" : ""}fastmcp-consent`;
2026
+ }
2027
+ /**
2028
+ * The consent cookie `request` carries, if it carries a well-formed one.
2029
+ *
2030
+ * Only the spaces and tabs that may surround a cookie are dropped. Trimming
2031
+ * all white space would take a cookie whose name begins with, say, a
2032
+ * no-break space for this one, and a browser does not hold such a name to
2033
+ * the `__Host-` rules.
2034
+ */
2035
+ consentCookieValue(request) {
2036
+ const name = this.consentCookieName();
2037
+ for (const pair of (request.headers.get("cookie") ?? "").split(";")) {
2038
+ const separator = pair.indexOf("=");
2039
+ if (separator !== -1 && withoutOptionalWhitespace(pair.slice(0, separator)) === name) {
2040
+ const value = withoutOptionalWhitespace(pair.slice(separator + 1));
2041
+ return CONSENT_COOKIE_VALUE.test(value) ? value : void 0;
2042
+ }
2043
+ }
2044
+ return void 0;
2045
+ }
1910
2046
  /**
1911
2047
  * Create a new OAuth transaction
1912
2048
  */
1913
- async createTransaction(params) {
2049
+ async createTransaction(params, consentBinding) {
1914
2050
  const transactionId = this.generateId();
1915
2051
  const proxyPkce = PKCEUtils.generatePair("S256");
1916
2052
  const transaction = {
@@ -1918,6 +2054,7 @@ var OAuthProxy = class {
1918
2054
  clientCodeChallenge: params.code_challenge || "",
1919
2055
  clientCodeChallengeMethod: params.code_challenge_method || "plain",
1920
2056
  clientId: params.client_id,
2057
+ ...consentBinding && { consentBinding: sha256(consentBinding) },
1921
2058
  createdAt: /* @__PURE__ */ new Date(),
1922
2059
  expiresAt: new Date(
1923
2060
  Date.now() + (this.config.transactionTtl || 600) * 1e3
@@ -2245,6 +2382,12 @@ var OAuthProxy = class {
2245
2382
  if (refreshedUpstreamTokens.scope.length === 0) {
2246
2383
  refreshedUpstreamTokens.scope = upstreamTokens.scope;
2247
2384
  }
2385
+ const requestedScope = [
2386
+ ...new Set(request.scope?.split(" ").filter(Boolean))
2387
+ ];
2388
+ const accessTokenScope = requestedScope.length > 0 && requestedScope.every(
2389
+ (scope) => refreshedUpstreamTokens.scope.includes(scope)
2390
+ ) ? requestedScope : refreshedUpstreamTokens.scope;
2248
2391
  const refreshTokenTtl = refreshedUpstreamTokens.refreshExpiresIn ?? this.config.refreshTokenTtl ?? DEFAULT_REFRESH_TOKEN_TTL;
2249
2392
  const accessTokenTtl = this.calculateAccessTokenTtl(
2250
2393
  refreshedUpstreamTokens
@@ -2259,7 +2402,8 @@ var OAuthProxy = class {
2259
2402
  mapping.clientId,
2260
2403
  refreshedUpstreamTokens,
2261
2404
  mapping.upstreamTokenKey,
2262
- caller.authenticated
2405
+ caller.authenticated,
2406
+ accessTokenScope
2263
2407
  );
2264
2408
  } catch (error) {
2265
2409
  try {
@@ -2273,6 +2417,21 @@ var OAuthProxy = class {
2273
2417
  throw error;
2274
2418
  }
2275
2419
  }
2420
+ /**
2421
+ * Whether `request` comes from the browser the transaction's consent screen
2422
+ * was shown to: it carries the cookie that screen set. A transaction that
2423
+ * never had a consent screen is bound to no browser.
2424
+ */
2425
+ isConsentBoundTo(request, transaction) {
2426
+ const presented = this.consentCookieValue(request);
2427
+ return Boolean(
2428
+ presented && transaction.consentBinding && equalsConstantTime(sha256(presented), transaction.consentBinding)
2429
+ );
2430
+ }
2431
+ /** Whether browsers reach this proxy over HTTPS, going by its `baseUrl`. */
2432
+ isServedOverHttps() {
2433
+ return /^https:/i.test(this.config.baseUrl);
2434
+ }
2276
2435
  /**
2277
2436
  * Issue swapped tokens (JWT pattern)
2278
2437
  * Issues short-lived FastMCP JWTs and stores upstream tokens securely
@@ -2353,7 +2512,7 @@ var OAuthProxy = class {
2353
2512
  /**
2354
2513
  * Issue swapped tokens for refresh flow
2355
2514
  */
2356
- async issueSwappedTokensForRefresh(clientId, upstreamTokens, upstreamTokenKey, clientAuthenticated) {
2515
+ async issueSwappedTokensForRefresh(clientId, upstreamTokens, upstreamTokenKey, clientAuthenticated, accessTokenScope = upstreamTokens.scope) {
2357
2516
  if (!this.jwtIssuer) {
2358
2517
  throw new Error("JWT issuer not initialized");
2359
2518
  }
@@ -2362,7 +2521,7 @@ var OAuthProxy = class {
2362
2521
  const refreshTokenTtl = upstreamTokens.refreshToken ? upstreamTokens.refreshExpiresIn ?? this.config.refreshTokenTtl ?? DEFAULT_REFRESH_TOKEN_TTL : 0;
2363
2522
  const accessToken = this.jwtIssuer.issueAccessToken(
2364
2523
  clientId,
2365
- upstreamTokens.scope,
2524
+ accessTokenScope,
2366
2525
  customClaims || void 0,
2367
2526
  accessTokenTtl
2368
2527
  );
@@ -2374,7 +2533,7 @@ var OAuthProxy = class {
2374
2533
  createdAt: /* @__PURE__ */ new Date(),
2375
2534
  expiresAt: new Date(Date.now() + accessTokenTtl * 1e3),
2376
2535
  jti: accessJti,
2377
- scope: upstreamTokens.scope,
2536
+ scope: accessTokenScope,
2378
2537
  upstreamTokenKey
2379
2538
  },
2380
2539
  accessTokenTtl
@@ -2382,7 +2541,7 @@ var OAuthProxy = class {
2382
2541
  const response = {
2383
2542
  access_token: accessToken,
2384
2543
  expires_in: accessTokenTtl,
2385
- scope: upstreamTokens.scope.join(" "),
2544
+ scope: accessTokenScope.join(" "),
2386
2545
  token_type: "Bearer"
2387
2546
  };
2388
2547
  if (upstreamTokens.refreshToken) {
@@ -2426,16 +2585,39 @@ var OAuthProxy = class {
2426
2585
  return registeredClient?.redirectUris.includes(transaction.clientCallbackUrl) ?? false;
2427
2586
  }
2428
2587
  /**
2429
- * Match URI against pattern (supports wildcards)
2430
- */
2431
- matchesPattern(uri, pattern) {
2432
- const regex = new RegExp(
2433
- "^" + pattern.replace(
2434
- /[.*+?^${}()|[\]\\]/g,
2435
- (char) => char === "*" ? ".*" : char === "?" ? "." : "\\" + char
2436
- ) + "$"
2437
- );
2438
- return regex.test(uri);
2588
+ * Whether a redirect URI matches a pattern.
2589
+ *
2590
+ * The pattern is a glob over the URI as it is written, and the host the URI
2591
+ * really leads to must match the pattern's host as well: `*` runs past the
2592
+ * end of a host, so the text of `https://*.example.com/*` could otherwise be
2593
+ * found in the path of a URI on any host at all. The URI's host is the one
2594
+ * a browser goes to, which a backslash or a tab can make other than it is
2595
+ * written. The pattern's runs from after `://` to the first `/` or `#`.
2596
+ *
2597
+ * A `?` there may stand for a character, as in `localhost:30??`, or start
2598
+ * the query, as in `https://app.example.com?source=*`, where the host ends.
2599
+ * A URI may match the pattern read any of these ways, if its host matches
2600
+ * the host that reading gives.
2601
+ */
2602
+ matchesPattern(uri, pattern, parsed) {
2603
+ const scheme = /^[a-z*?][a-z\d+.\-*?]*:\/\//i.exec(pattern);
2604
+ if (!scheme) {
2605
+ return globToRegExp(pattern).test(uri);
2606
+ }
2607
+ const hostStart = scheme[0].length;
2608
+ const length = pattern.slice(hostStart).search(/[/#]/);
2609
+ const hostEnd = length === -1 ? pattern.length : hostStart + length;
2610
+ if (globToRegExp(pattern).test(uri) && leadsToHost(parsed, pattern.slice(hostStart, hostEnd))) {
2611
+ return true;
2612
+ }
2613
+ for (let query = hostStart; query < hostEnd; query++) {
2614
+ if (pattern[query] === "?" && new RegExp(
2615
+ `^${globSource(pattern.slice(0, query))}\\?${globSource(pattern.slice(query + 1))}$`
2616
+ ).test(uri) && leadsToHost(parsed, pattern.slice(hostStart, query))) {
2617
+ return true;
2618
+ }
2619
+ }
2620
+ return false;
2439
2621
  }
2440
2622
  /**
2441
2623
  * Parse token response that can be either JSON or URL-encoded
@@ -2712,7 +2894,7 @@ var OAuthProxy = class {
2712
2894
  "http://127.0.0.1:*"
2713
2895
  ];
2714
2896
  return effectivePatterns.some(
2715
- (pattern) => this.matchesPattern(uri, pattern)
2897
+ (pattern) => this.matchesPattern(uri, pattern, parsed)
2716
2898
  );
2717
2899
  }
2718
2900
  };
@@ -2726,8 +2908,46 @@ var describeUnauthenticatedClient = (client) => {
2726
2908
  }
2727
2909
  return "clients that do not authenticate with their client_secret";
2728
2910
  };
2911
+ var leadsToHost = (uri, host) => {
2912
+ const portStart = host.lastIndexOf(":");
2913
+ const hasPort = portStart > host.lastIndexOf("]");
2914
+ const name = writeHostName(
2915
+ uri.protocol,
2916
+ hasPort ? host.slice(0, portStart) : host
2917
+ );
2918
+ const trailing = /[*?]*$/.exec(name)[0];
2919
+ const nameSource = /^\*+$/.test(name) ? ".*" : globSource(name.slice(0, name.length - trailing.length)) + trailing.replace(/\*/g, "[^.]*").replace(/\?/g, "[^.]");
2920
+ const expected = new RegExp(
2921
+ `^${nameSource}${hasPort ? globSource(host.slice(portStart)) : ""}$`
2922
+ );
2923
+ const candidates = [uri.host.toLowerCase()];
2924
+ const defaultPort = DEFAULT_PORTS[uri.protocol];
2925
+ if (uri.port === "" && defaultPort) {
2926
+ candidates.push(`${uri.hostname.toLowerCase()}:${defaultPort}`);
2927
+ }
2928
+ return candidates.some((candidate) => expected.test(candidate));
2929
+ };
2930
+ var writeHostName = (protocol, name) => {
2931
+ if (/[?#/\\@]/.test(name)) {
2932
+ return name.toLowerCase();
2933
+ }
2934
+ try {
2935
+ const { hostname } = new URL(`${protocol}//${name}`);
2936
+ if (hostname.split("*").length === name.split("*").length) {
2937
+ return hostname.toLowerCase();
2938
+ }
2939
+ } catch {
2940
+ }
2941
+ return name.toLowerCase();
2942
+ };
2943
+ var globSource = (glob) => glob.replace(
2944
+ /[.*+?^${}()|[\]\\]/g,
2945
+ (char) => char === "*" ? ".*" : char === "?" ? "." : "\\" + char
2946
+ );
2947
+ var globToRegExp = (glob) => new RegExp(`^${globSource(glob)}$`);
2729
2948
  var isTokenEndpointAuthMethod = (value) => TOKEN_ENDPOINT_AUTH_METHODS.includes(value);
2730
2949
  var sha256 = (value) => createHash2("sha256").update(value).digest("base64url");
2950
+ var withoutOptionalWhitespace = (value) => value.replace(/^[ \t]+|[ \t]+$/g, "");
2731
2951
  var secretsMatch = (presented, expected) => equalsConstantTime(sha256(presented), sha256(expected));
2732
2952
  var OAuthProxyError = class extends Error {
2733
2953
  constructor(code, description, statusCode = 400) {
@@ -3359,4 +3579,4 @@ export {
3359
3579
  DiskStore,
3360
3580
  JWKSVerifier
3361
3581
  };
3362
- //# sourceMappingURL=chunk-3VYVXSBB.js.map
3582
+ //# sourceMappingURL=chunk-W6P57SNV.js.map