fastmcp 4.25.1 → 4.26.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 (38) hide show
  1. package/README.md +10 -2
  2. package/dist/FastMCP.cjs +3 -3
  3. package/dist/FastMCP.d.cts +3 -2
  4. package/dist/FastMCP.d.ts +3 -2
  5. package/dist/FastMCP.js +2 -2
  6. package/dist/{OAuthProvider-CPC9zG96.d.cts → OAuthProvider-5T2VSp7V.d.cts} +34 -1
  7. package/dist/{OAuthProvider-CPC9zG96.d.ts → OAuthProvider-5T2VSp7V.d.ts} +34 -1
  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-SQSE766U.js → chunk-GUHJKVLX.js} +67 -32
  13. package/dist/chunk-GUHJKVLX.js.map +1 -0
  14. package/dist/{chunk-3VYVXSBB.js → chunk-KYUSH4TQ.js} +188 -41
  15. package/dist/chunk-KYUSH4TQ.js.map +1 -0
  16. package/dist/{chunk-VWHJYU4V.cjs → chunk-MT5SJOZ5.cjs} +96 -61
  17. package/dist/chunk-MT5SJOZ5.cjs.map +1 -0
  18. package/dist/{chunk-AKHG27NY.cjs → chunk-UNS6EZVP.cjs} +202 -55
  19. package/dist/chunk-UNS6EZVP.cjs.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 +22 -9
  29. package/dist/openapi/index.cjs.map +1 -1
  30. package/dist/openapi/index.d.cts +6 -5
  31. package/dist/openapi/index.d.ts +6 -5
  32. package/dist/openapi/index.js +16 -3
  33. package/dist/openapi/index.js.map +1 -1
  34. package/package.json +1 -1
  35. package/dist/chunk-3VYVXSBB.js.map +0 -1
  36. package/dist/chunk-AKHG27NY.cjs.map +0 -1
  37. package/dist/chunk-SQSE766U.js.map +0 -1
  38. package/dist/chunk-VWHJYU4V.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 _optionalChain([result, 'optionalAccess', _ => _.then]) === "function") {
36
+ Promise.resolve(result).catch(() => {
37
+ });
38
+ }
39
+ return result === true;
40
+ }
35
41
 
36
42
  // src/auth/OAuthProxy.ts
37
43
  var _crypto = require('crypto');
@@ -127,6 +133,7 @@ var oauthTransactionStorageSchema = _zod.z.object({
127
133
  clientCodeChallenge: _zod.z.string(),
128
134
  clientCodeChallengeMethod: _zod.z.string(),
129
135
  clientId: _zod.z.string(),
136
+ consentBinding: _zod.z.string().optional(),
130
137
  consentGiven: _zod.z.boolean().optional(),
131
138
  createdAt: storedDateSchema,
132
139
  expiresAt: storedDateSchema,
@@ -455,7 +462,7 @@ async function readBoundedText(response) {
455
462
  await cancelResponseBody(response);
456
463
  return null;
457
464
  }
458
- const reader = _optionalChain([response, 'access', _ => _.body, 'optionalAccess', _2 => _2.getReader, 'call', _3 => _3()]);
465
+ const reader = _optionalChain([response, 'access', _2 => _2.body, 'optionalAccess', _3 => _3.getReader, 'call', _4 => _4()]);
459
466
  if (!reader) {
460
467
  return null;
461
468
  }
@@ -576,7 +583,7 @@ var ClaimsExtractor = (_class = class {
576
583
  if (this.PROTECTED_CLAIMS.has(key)) {
577
584
  continue;
578
585
  }
579
- if (_optionalChain([this, 'access', _4 => _4.config, 'access', _5 => _5.blockedClaims, 'optionalAccess', _6 => _6.includes, 'call', _7 => _7(key)])) {
586
+ if (_optionalChain([this, 'access', _5 => _5.config, 'access', _6 => _6.blockedClaims, 'optionalAccess', _7 => _7.includes, 'call', _8 => _8(key)])) {
580
587
  continue;
581
588
  }
582
589
  if (this.config.allowedClaims && !this.config.allowedClaims.includes(key)) {
@@ -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 (e8) {
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,8 @@ var MemoryTokenStorage = (_class3 = class {
1341
1386
  }, _class3);
1342
1387
 
1343
1388
  // src/auth/OAuthProxy.ts
1389
+ var CONSENT_COOKIE_VALUE = /^[\w-]{43}$/;
1390
+ var MAX_CLIENT_REGISTRATION_BYTES = 32 * 1024;
1344
1391
  var RESERVED_AUTHORIZATION_PARAMS = /* @__PURE__ */ new Set([
1345
1392
  "client_id",
1346
1393
  "code_challenge",
@@ -1386,7 +1433,6 @@ var OAuthProxy = (_class4 = class {
1386
1433
  allowPlainPkce: true,
1387
1434
  authorizationCodeTtl: DEFAULT_AUTHORIZATION_CODE_TTL,
1388
1435
  authorizationResponseIss: true,
1389
- consentRequired: true,
1390
1436
  enableCimd: false,
1391
1437
  enableTokenSwap: true,
1392
1438
  // Enabled by default for security
@@ -1394,7 +1440,10 @@ var OAuthProxy = (_class4 = class {
1394
1440
  transactionTtl: DEFAULT_TRANSACTION_TTL,
1395
1441
  upstreamRequestTimeoutMs: DEFAULT_UPSTREAM_REQUEST_TIMEOUT_MS,
1396
1442
  upstreamTokenEndpointAuthMethod: "client_secret_basic",
1397
- ...config
1443
+ ...config,
1444
+ // Spreading an explicit `undefined` over the default would turn consent
1445
+ // off for a caller that only meant to pass an option along.
1446
+ consentRequired: _nullishCoalesce(config.consentRequired, () => ( true))
1398
1447
  };
1399
1448
  let storage = config.tokenStorage;
1400
1449
  if (!storage) {
@@ -1431,7 +1480,7 @@ var OAuthProxy = (_class4 = class {
1431
1480
  /**
1432
1481
  * OAuth authorization endpoint
1433
1482
  */
1434
- async authorize(params) {
1483
+ async authorize(params, request) {
1435
1484
  if (!params.client_id || !params.redirect_uri || !params.response_type) {
1436
1485
  throw new OAuthProxyError(
1437
1486
  "invalid_request",
@@ -1490,11 +1539,17 @@ var OAuthProxy = (_class4 = class {
1490
1539
  );
1491
1540
  }
1492
1541
  }
1493
- const transaction = await this.createTransaction(params);
1494
- if (this.config.consentRequired && !transaction.consentGiven) {
1542
+ const consentBinding = this.config.consentRequired ? _nullishCoalesce((request && this.consentCookieValue(request)), () => ( this.generateId())) : void 0;
1543
+ const transaction = await this.createTransaction(params, consentBinding);
1544
+ if (consentBinding && !transaction.consentGiven) {
1545
+ const clientName = _optionalChain([registeredClient, 'access', _9 => _9.metadata, 'optionalAccess', _10 => _10.client_name]);
1495
1546
  return this.consentManager.createConsentResponse(
1496
1547
  transaction,
1497
- this.getProviderName()
1548
+ this.getProviderName(),
1549
+ {
1550
+ clientName: typeof clientName === "string" ? clientName : void 0,
1551
+ cookie: this.consentCookie(consentBinding)
1552
+ }
1498
1553
  );
1499
1554
  }
1500
1555
  return this.redirectToUpstream(transaction);
@@ -1507,7 +1562,7 @@ var OAuthProxy = (_class4 = class {
1507
1562
  clearInterval(this.cleanupInterval);
1508
1563
  this.cleanupInterval = null;
1509
1564
  }
1510
- _optionalChain([this, 'access', _8 => _8.ownedTokenStorage, 'optionalAccess', _9 => _9.destroy, 'call', _10 => _10()]);
1565
+ _optionalChain([this, 'access', _11 => _11.ownedTokenStorage, 'optionalAccess', _12 => _12.destroy, 'call', _13 => _13()]);
1511
1566
  this.registeredClientsByClientId.clear();
1512
1567
  }
1513
1568
  /**
@@ -1661,6 +1716,12 @@ var OAuthProxy = (_class4 = class {
1661
1716
  if (!transaction) {
1662
1717
  throw new OAuthProxyError("invalid_request", "Invalid or expired state");
1663
1718
  }
1719
+ if (this.config.consentRequired && !(transaction.consentGiven && this.isConsentBoundTo(request, transaction))) {
1720
+ throw new OAuthProxyError(
1721
+ "access_denied",
1722
+ "This authorization request was not approved in this browser"
1723
+ );
1724
+ }
1664
1725
  if (!await this.isTransactionCallbackRegistered(transaction)) {
1665
1726
  throw new OAuthProxyError(
1666
1727
  "invalid_request",
@@ -1708,6 +1769,12 @@ var OAuthProxy = (_class4 = class {
1708
1769
  "Invalid or expired transaction"
1709
1770
  );
1710
1771
  }
1772
+ if (!this.isConsentBoundTo(request, transaction)) {
1773
+ throw new OAuthProxyError(
1774
+ "invalid_request",
1775
+ "Consent must be given in the browser that requested it"
1776
+ );
1777
+ }
1711
1778
  if (action === "deny") {
1712
1779
  await this.stateStore.deleteTransaction(transactionId);
1713
1780
  if (!await this.isTransactionCallbackRegistered(transaction)) {
@@ -1748,7 +1815,7 @@ var OAuthProxy = (_class4 = class {
1748
1815
  return null;
1749
1816
  }
1750
1817
  const result = await this.jwtIssuer.verify(fastmcpToken);
1751
- if (!result.valid || !_optionalChain([result, 'access', _11 => _11.claims, 'optionalAccess', _12 => _12.jti])) {
1818
+ if (!result.valid || !_optionalChain([result, 'access', _14 => _14.claims, 'optionalAccess', _15 => _15.jti])) {
1752
1819
  return null;
1753
1820
  }
1754
1821
  if (result.claims.token_use !== "access") {
@@ -1763,7 +1830,15 @@ var OAuthProxy = (_class4 = class {
1763
1830
  const upstreamTokens = await this.tokenStorage.get(
1764
1831
  `upstream:${mapping.upstreamTokenKey}`
1765
1832
  );
1766
- return upstreamTokens;
1833
+ if (!upstreamTokens || !Array.isArray(mapping.scope)) {
1834
+ return upstreamTokens;
1835
+ }
1836
+ return {
1837
+ ...upstreamTokens,
1838
+ scope: mapping.scope.filter(
1839
+ (scope) => upstreamTokens.scope.includes(scope)
1840
+ )
1841
+ };
1767
1842
  }
1768
1843
  /**
1769
1844
  * RFC 7591 Dynamic Client Registration
@@ -1775,6 +1850,27 @@ var OAuthProxy = (_class4 = class {
1775
1850
  "redirect_uris is required"
1776
1851
  );
1777
1852
  }
1853
+ const metadata = {
1854
+ client_name: request.client_name,
1855
+ client_uri: request.client_uri,
1856
+ contacts: request.contacts,
1857
+ jwks: request.jwks,
1858
+ jwks_uri: request.jwks_uri,
1859
+ logo_uri: request.logo_uri,
1860
+ policy_uri: request.policy_uri,
1861
+ scope: request.scope,
1862
+ software_id: request.software_id,
1863
+ software_version: request.software_version,
1864
+ tos_uri: request.tos_uri
1865
+ };
1866
+ if (Buffer.byteLength(
1867
+ JSON.stringify({ metadata, redirect_uris: request.redirect_uris })
1868
+ ) > MAX_CLIENT_REGISTRATION_BYTES) {
1869
+ throw new OAuthProxyError(
1870
+ "invalid_client_metadata",
1871
+ `Client metadata must not exceed ${MAX_CLIENT_REGISTRATION_BYTES} bytes`
1872
+ );
1873
+ }
1778
1874
  for (const uri of request.redirect_uris) {
1779
1875
  if (!this.validateRedirectUri(uri)) {
1780
1876
  throw new OAuthProxyError(
@@ -1796,19 +1892,7 @@ var OAuthProxy = (_class4 = class {
1796
1892
  callbackUrl: request.redirect_uris[0],
1797
1893
  clientId: proxyClientId,
1798
1894
  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
- },
1895
+ metadata,
1812
1896
  redirectUris: request.redirect_uris,
1813
1897
  registeredAt: /* @__PURE__ */ new Date(),
1814
1898
  tokenEndpointAuthMethod
@@ -1907,10 +1991,49 @@ var OAuthProxy = (_class4 = class {
1907
1991
  );
1908
1992
  });
1909
1993
  }
1994
+ /**
1995
+ * The cookie that ties consent requests to the browser they were shown to.
1996
+ * A browser holds one, shared by every request it has open, and it lasts as
1997
+ * long as a request does. `Lax` lets it travel with the provider's redirect
1998
+ * back to the callback, which is a cross-site navigation. Over HTTPS the
1999
+ * `__Host-` prefix keeps another host on the same site from setting it.
2000
+ */
2001
+ consentCookie(value) {
2002
+ return [
2003
+ `${this.consentCookieName()}=${value}`,
2004
+ "Path=/",
2005
+ `Max-Age=${this.config.transactionTtl || 600}`,
2006
+ "HttpOnly",
2007
+ "SameSite=Lax",
2008
+ ...this.isServedOverHttps() ? ["Secure"] : []
2009
+ ].join("; ");
2010
+ }
2011
+ consentCookieName() {
2012
+ return `${this.isServedOverHttps() ? "__Host-" : ""}fastmcp-consent`;
2013
+ }
2014
+ /**
2015
+ * The consent cookie `request` carries, if it carries a well-formed one.
2016
+ *
2017
+ * Only the spaces and tabs that may surround a cookie are dropped. Trimming
2018
+ * all white space would take a cookie whose name begins with, say, a
2019
+ * no-break space for this one, and a browser does not hold such a name to
2020
+ * the `__Host-` rules.
2021
+ */
2022
+ consentCookieValue(request) {
2023
+ const name = this.consentCookieName();
2024
+ for (const pair of (_nullishCoalesce(request.headers.get("cookie"), () => ( ""))).split(";")) {
2025
+ const separator = pair.indexOf("=");
2026
+ if (separator !== -1 && withoutOptionalWhitespace(pair.slice(0, separator)) === name) {
2027
+ const value = withoutOptionalWhitespace(pair.slice(separator + 1));
2028
+ return CONSENT_COOKIE_VALUE.test(value) ? value : void 0;
2029
+ }
2030
+ }
2031
+ return void 0;
2032
+ }
1910
2033
  /**
1911
2034
  * Create a new OAuth transaction
1912
2035
  */
1913
- async createTransaction(params) {
2036
+ async createTransaction(params, consentBinding) {
1914
2037
  const transactionId = this.generateId();
1915
2038
  const proxyPkce = PKCEUtils.generatePair("S256");
1916
2039
  const transaction = {
@@ -1918,6 +2041,7 @@ var OAuthProxy = (_class4 = class {
1918
2041
  clientCodeChallenge: params.code_challenge || "",
1919
2042
  clientCodeChallengeMethod: params.code_challenge_method || "plain",
1920
2043
  clientId: params.client_id,
2044
+ ...consentBinding && { consentBinding: sha256(consentBinding) },
1921
2045
  createdAt: /* @__PURE__ */ new Date(),
1922
2046
  expiresAt: new Date(
1923
2047
  Date.now() + (this.config.transactionTtl || 600) * 1e3
@@ -1960,7 +2084,7 @@ var OAuthProxy = (_class4 = class {
1960
2084
  const error = await tokenResponse.json();
1961
2085
  errorCode = error.error || "server_error";
1962
2086
  errorDescription = error.error_description;
1963
- } catch (e8) {
2087
+ } catch (e9) {
1964
2088
  errorDescription = `Upstream returned HTTP ${tokenResponse.status} ${tokenResponse.statusText}`;
1965
2089
  }
1966
2090
  throw new OAuthProxyError(errorCode, errorDescription);
@@ -1985,7 +2109,7 @@ var OAuthProxy = (_class4 = class {
1985
2109
  throw new Error("JWT issuer not initialized");
1986
2110
  }
1987
2111
  const result = await this.jwtIssuer.verify(token);
1988
- if (!result.valid || !_optionalChain([result, 'access', _13 => _13.claims, 'optionalAccess', _14 => _14.jti])) {
2112
+ if (!result.valid || !_optionalChain([result, 'access', _16 => _16.claims, 'optionalAccess', _17 => _17.jti])) {
1989
2113
  throw new Error("Failed to extract JTI from token");
1990
2114
  }
1991
2115
  return result.claims.jti;
@@ -2150,7 +2274,7 @@ var OAuthProxy = (_class4 = class {
2150
2274
  const error = await tokenResponse.json();
2151
2275
  errorCode = error.error || "invalid_grant";
2152
2276
  errorDescription = error.error_description;
2153
- } catch (e9) {
2277
+ } catch (e10) {
2154
2278
  errorDescription = `Upstream returned HTTP ${tokenResponse.status} ${tokenResponse.statusText}`;
2155
2279
  }
2156
2280
  throw new OAuthProxyError(errorCode, errorDescription);
@@ -2245,6 +2369,12 @@ var OAuthProxy = (_class4 = class {
2245
2369
  if (refreshedUpstreamTokens.scope.length === 0) {
2246
2370
  refreshedUpstreamTokens.scope = upstreamTokens.scope;
2247
2371
  }
2372
+ const requestedScope = [
2373
+ ...new Set(_optionalChain([request, 'access', _18 => _18.scope, 'optionalAccess', _19 => _19.split, 'call', _20 => _20(" "), 'access', _21 => _21.filter, 'call', _22 => _22(Boolean)]))
2374
+ ];
2375
+ const accessTokenScope = requestedScope.length > 0 && requestedScope.every(
2376
+ (scope) => refreshedUpstreamTokens.scope.includes(scope)
2377
+ ) ? requestedScope : refreshedUpstreamTokens.scope;
2248
2378
  const refreshTokenTtl = _nullishCoalesce(_nullishCoalesce(refreshedUpstreamTokens.refreshExpiresIn, () => ( this.config.refreshTokenTtl)), () => ( DEFAULT_REFRESH_TOKEN_TTL));
2249
2379
  const accessTokenTtl = this.calculateAccessTokenTtl(
2250
2380
  refreshedUpstreamTokens
@@ -2259,7 +2389,8 @@ var OAuthProxy = (_class4 = class {
2259
2389
  mapping.clientId,
2260
2390
  refreshedUpstreamTokens,
2261
2391
  mapping.upstreamTokenKey,
2262
- caller.authenticated
2392
+ caller.authenticated,
2393
+ accessTokenScope
2263
2394
  );
2264
2395
  } catch (error) {
2265
2396
  try {
@@ -2273,6 +2404,21 @@ var OAuthProxy = (_class4 = class {
2273
2404
  throw error;
2274
2405
  }
2275
2406
  }
2407
+ /**
2408
+ * Whether `request` comes from the browser the transaction's consent screen
2409
+ * was shown to: it carries the cookie that screen set. A transaction that
2410
+ * never had a consent screen is bound to no browser.
2411
+ */
2412
+ isConsentBoundTo(request, transaction) {
2413
+ const presented = this.consentCookieValue(request);
2414
+ return Boolean(
2415
+ presented && transaction.consentBinding && equalsConstantTime(sha256(presented), transaction.consentBinding)
2416
+ );
2417
+ }
2418
+ /** Whether browsers reach this proxy over HTTPS, going by its `baseUrl`. */
2419
+ isServedOverHttps() {
2420
+ return /^https:/i.test(this.config.baseUrl);
2421
+ }
2276
2422
  /**
2277
2423
  * Issue swapped tokens (JWT pattern)
2278
2424
  * Issues short-lived FastMCP JWTs and stores upstream tokens securely
@@ -2353,7 +2499,7 @@ var OAuthProxy = (_class4 = class {
2353
2499
  /**
2354
2500
  * Issue swapped tokens for refresh flow
2355
2501
  */
2356
- async issueSwappedTokensForRefresh(clientId, upstreamTokens, upstreamTokenKey, clientAuthenticated) {
2502
+ async issueSwappedTokensForRefresh(clientId, upstreamTokens, upstreamTokenKey, clientAuthenticated, accessTokenScope = upstreamTokens.scope) {
2357
2503
  if (!this.jwtIssuer) {
2358
2504
  throw new Error("JWT issuer not initialized");
2359
2505
  }
@@ -2362,7 +2508,7 @@ var OAuthProxy = (_class4 = class {
2362
2508
  const refreshTokenTtl = upstreamTokens.refreshToken ? _nullishCoalesce(_nullishCoalesce(upstreamTokens.refreshExpiresIn, () => ( this.config.refreshTokenTtl)), () => ( DEFAULT_REFRESH_TOKEN_TTL)) : 0;
2363
2509
  const accessToken = this.jwtIssuer.issueAccessToken(
2364
2510
  clientId,
2365
- upstreamTokens.scope,
2511
+ accessTokenScope,
2366
2512
  customClaims || void 0,
2367
2513
  accessTokenTtl
2368
2514
  );
@@ -2374,7 +2520,7 @@ var OAuthProxy = (_class4 = class {
2374
2520
  createdAt: /* @__PURE__ */ new Date(),
2375
2521
  expiresAt: new Date(Date.now() + accessTokenTtl * 1e3),
2376
2522
  jti: accessJti,
2377
- scope: upstreamTokens.scope,
2523
+ scope: accessTokenScope,
2378
2524
  upstreamTokenKey
2379
2525
  },
2380
2526
  accessTokenTtl
@@ -2382,7 +2528,7 @@ var OAuthProxy = (_class4 = class {
2382
2528
  const response = {
2383
2529
  access_token: accessToken,
2384
2530
  expires_in: accessTokenTtl,
2385
- scope: upstreamTokens.scope.join(" "),
2531
+ scope: accessTokenScope.join(" "),
2386
2532
  token_type: "Bearer"
2387
2533
  };
2388
2534
  if (upstreamTokens.refreshToken) {
@@ -2423,7 +2569,7 @@ var OAuthProxy = (_class4 = class {
2423
2569
  transaction.clientId,
2424
2570
  transaction.clientCallbackUrl
2425
2571
  );
2426
- return _nullishCoalesce(_optionalChain([registeredClient, 'optionalAccess', _15 => _15.redirectUris, 'access', _16 => _16.includes, 'call', _17 => _17(transaction.clientCallbackUrl)]), () => ( false));
2572
+ return _nullishCoalesce(_optionalChain([registeredClient, 'optionalAccess', _23 => _23.redirectUris, 'access', _24 => _24.includes, 'call', _25 => _25(transaction.clientCallbackUrl)]), () => ( false));
2427
2573
  }
2428
2574
  /**
2429
2575
  * Match URI against pattern (supports wildcards)
@@ -2548,7 +2694,7 @@ var OAuthProxy = (_class4 = class {
2548
2694
  const error = await tokenResponse.json();
2549
2695
  errorCode = error.error || "invalid_grant";
2550
2696
  errorDescription = error.error_description || "Upstream refresh failed";
2551
- } catch (e10) {
2697
+ } catch (e11) {
2552
2698
  errorDescription = `Upstream returned HTTP ${tokenResponse.status} ${tokenResponse.statusText}`;
2553
2699
  }
2554
2700
  throw new OAuthProxyError(errorCode, errorDescription);
@@ -2697,7 +2843,7 @@ var OAuthProxy = (_class4 = class {
2697
2843
  let parsed;
2698
2844
  try {
2699
2845
  parsed = new URL(uri);
2700
- } catch (e11) {
2846
+ } catch (e12) {
2701
2847
  return false;
2702
2848
  }
2703
2849
  if (parsed.username !== "" || parsed.password !== "") {
@@ -2728,6 +2874,7 @@ var describeUnauthenticatedClient = (client) => {
2728
2874
  };
2729
2875
  var isTokenEndpointAuthMethod = (value) => TOKEN_ENDPOINT_AUTH_METHODS.includes(value);
2730
2876
  var sha256 = (value) => _crypto.createHash.call(void 0, "sha256").update(value).digest("base64url");
2877
+ var withoutOptionalWhitespace = (value) => value.replace(/^[ \t]+|[ \t]+$/g, "");
2731
2878
  var secretsMatch = (presented, expected) => equalsConstantTime(sha256(presented), sha256(expected));
2732
2879
  var OAuthProxyError = class extends Error {
2733
2880
  constructor(code, description, statusCode = 400) {
@@ -2789,7 +2936,7 @@ var AuthProvider = class {
2789
2936
  if (!request) {
2790
2937
  return void 0;
2791
2938
  }
2792
- const authHeader = _optionalChain([request, 'access', _18 => _18.headers, 'optionalAccess', _19 => _19.authorization]);
2939
+ const authHeader = _optionalChain([request, 'access', _26 => _26.headers, 'optionalAccess', _27 => _27.authorization]);
2793
2940
  if (!authHeader || !authHeader.startsWith("Bearer ")) {
2794
2941
  return void 0;
2795
2942
  }
@@ -3031,7 +3178,7 @@ var DiskStore = (_class5 = class {
3031
3178
  console.warn(`Failed to read/parse file ${file}, deleting:`, error);
3032
3179
  try {
3033
3180
  await _promises.rm.call(void 0, _path.join.call(void 0, this.directory, file));
3034
- } catch (e12) {
3181
+ } catch (e13) {
3035
3182
  }
3036
3183
  }
3037
3184
  }
@@ -3114,7 +3261,7 @@ var DiskStore = (_class5 = class {
3114
3261
  await this.ensureDirectory();
3115
3262
  const files = await _promises.readdir.call(void 0, this.directory);
3116
3263
  return files.filter((f) => f.endsWith(this.fileExtension)).length;
3117
- } catch (e13) {
3264
+ } catch (e14) {
3118
3265
  return 0;
3119
3266
  }
3120
3267
  }
@@ -3183,7 +3330,7 @@ var DiskStore = (_class5 = class {
3183
3330
  await _promises.rename.call(void 0, source, destination);
3184
3331
  return;
3185
3332
  } catch (error) {
3186
- const code = _optionalChain([error, 'optionalAccess', _20 => _20.code]);
3333
+ const code = _optionalChain([error, 'optionalAccess', _28 => _28.code]);
3187
3334
  if (process.platform !== "win32" || attempt >= 5 || !["EACCES", "EBUSY", "EPERM"].includes(_nullishCoalesce(code, () => ( "")))) {
3188
3335
  throw error;
3189
3336
  }
@@ -3359,4 +3506,4 @@ Original error: ${error.message}`
3359
3506
 
3360
3507
 
3361
3508
  exports.cancelResponseBody = cancelResponseBody; exports.getAuthSession = getAuthSession; exports.requireAll = requireAll; exports.requireAny = requireAny; exports.requireAuth = requireAuth; exports.requireRole = requireRole; exports.requireScopes = requireScopes; exports.DEFAULT_ACCESS_TOKEN_TTL = DEFAULT_ACCESS_TOKEN_TTL; exports.DEFAULT_ACCESS_TOKEN_TTL_NO_REFRESH = DEFAULT_ACCESS_TOKEN_TTL_NO_REFRESH; exports.DEFAULT_REFRESH_TOKEN_TTL = DEFAULT_REFRESH_TOKEN_TTL; exports.TOKEN_ENDPOINT_AUTH_METHODS = TOKEN_ENDPOINT_AUTH_METHODS; exports.DEFAULT_AUTHORIZATION_CODE_TTL = DEFAULT_AUTHORIZATION_CODE_TTL; exports.DEFAULT_TRANSACTION_TTL = DEFAULT_TRANSACTION_TTL; exports.ConsentManager = ConsentManager; exports.JWTIssuer = JWTIssuer; exports.PKCEUtils = PKCEUtils; exports.EncryptedTokenStorage = EncryptedTokenStorage; exports.MemoryTokenStorage = MemoryTokenStorage; exports.OAuthProxy = OAuthProxy; exports.OAuthProxyError = OAuthProxyError; exports.AuthProvider = AuthProvider; exports.AzureProvider = AzureProvider; exports.GitHubProvider = GitHubProvider; exports.GoogleProvider = GoogleProvider; exports.OAuthProvider = OAuthProvider; exports.DiskStore = DiskStore; exports.JWKSVerifier = JWKSVerifier;
3362
- //# sourceMappingURL=chunk-AKHG27NY.cjs.map
3509
+ //# sourceMappingURL=chunk-UNS6EZVP.cjs.map