@mcp-z/client 1.2.0 → 1.3.0

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 (95) hide show
  1. package/README.md +22 -0
  2. package/dist/cjs/auth/capability-discovery.js +16 -6
  3. package/dist/cjs/auth/capability-discovery.js.map +1 -1
  4. package/dist/cjs/auth/discovery-fetch.d.cts +22 -2
  5. package/dist/cjs/auth/discovery-fetch.d.ts +22 -2
  6. package/dist/cjs/auth/discovery-fetch.js +440 -124
  7. package/dist/cjs/auth/discovery-fetch.js.map +1 -1
  8. package/dist/cjs/auth/interactive-oauth-flow.d.cts +9 -2
  9. package/dist/cjs/auth/interactive-oauth-flow.d.ts +9 -2
  10. package/dist/cjs/auth/interactive-oauth-flow.js +29 -11
  11. package/dist/cjs/auth/interactive-oauth-flow.js.map +1 -1
  12. package/dist/cjs/auth/oauth-callback-listener.js +4 -0
  13. package/dist/cjs/auth/oauth-callback-listener.js.map +1 -1
  14. package/dist/cjs/auth/types.d.cts +29 -4
  15. package/dist/cjs/auth/types.d.ts +29 -4
  16. package/dist/cjs/auth/types.js.map +1 -1
  17. package/dist/cjs/client-helpers.d.cts +5 -6
  18. package/dist/cjs/client-helpers.d.ts +5 -6
  19. package/dist/cjs/client-helpers.js +8 -8
  20. package/dist/cjs/client-helpers.js.map +1 -1
  21. package/dist/cjs/connection/connect-client.d.cts +12 -11
  22. package/dist/cjs/connection/connect-client.d.ts +12 -11
  23. package/dist/cjs/connection/connect-client.js +31 -47
  24. package/dist/cjs/connection/connect-client.js.map +1 -1
  25. package/dist/cjs/connection/existing-process-transport.d.cts +1 -2
  26. package/dist/cjs/connection/existing-process-transport.d.ts +1 -2
  27. package/dist/cjs/connection/existing-process-transport.js +3 -3
  28. package/dist/cjs/connection/existing-process-transport.js.map +1 -1
  29. package/dist/cjs/dcr/dcr-authenticator.d.cts +36 -5
  30. package/dist/cjs/dcr/dcr-authenticator.d.ts +36 -5
  31. package/dist/cjs/dcr/dcr-authenticator.js +473 -57
  32. package/dist/cjs/dcr/dcr-authenticator.js.map +1 -1
  33. package/dist/cjs/dcr/dynamic-client-registrar.d.cts +2 -2
  34. package/dist/cjs/dcr/dynamic-client-registrar.d.ts +2 -2
  35. package/dist/cjs/dcr/dynamic-client-registrar.js +10 -11
  36. package/dist/cjs/dcr/dynamic-client-registrar.js.map +1 -1
  37. package/dist/cjs/index.d.cts +2 -0
  38. package/dist/cjs/index.d.ts +2 -0
  39. package/dist/cjs/index.js +8 -2
  40. package/dist/cjs/index.js.map +1 -1
  41. package/dist/cjs/lib/url-utils.d.cts +17 -0
  42. package/dist/cjs/lib/url-utils.d.ts +17 -0
  43. package/dist/cjs/lib/url-utils.js +22 -2
  44. package/dist/cjs/lib/url-utils.js.map +1 -1
  45. package/dist/cjs/response-wrappers.d.cts +1 -1
  46. package/dist/cjs/response-wrappers.d.ts +1 -1
  47. package/dist/cjs/response-wrappers.js.map +1 -1
  48. package/dist/cjs/search/search.d.cts +1 -1
  49. package/dist/cjs/search/search.d.ts +1 -1
  50. package/dist/cjs/search/search.js.map +1 -1
  51. package/dist/esm/auth/capability-discovery.js +16 -6
  52. package/dist/esm/auth/capability-discovery.js.map +1 -1
  53. package/dist/esm/auth/discovery-fetch.d.ts +22 -2
  54. package/dist/esm/auth/discovery-fetch.js +234 -54
  55. package/dist/esm/auth/discovery-fetch.js.map +1 -1
  56. package/dist/esm/auth/interactive-oauth-flow.d.ts +9 -2
  57. package/dist/esm/auth/interactive-oauth-flow.js +28 -10
  58. package/dist/esm/auth/interactive-oauth-flow.js.map +1 -1
  59. package/dist/esm/auth/oauth-callback-listener.js +4 -0
  60. package/dist/esm/auth/oauth-callback-listener.js.map +1 -1
  61. package/dist/esm/auth/types.d.ts +29 -4
  62. package/dist/esm/auth/types.js.map +1 -1
  63. package/dist/esm/client-helpers.d.ts +5 -6
  64. package/dist/esm/client-helpers.js +8 -8
  65. package/dist/esm/client-helpers.js.map +1 -1
  66. package/dist/esm/connection/connect-client.d.ts +12 -11
  67. package/dist/esm/connection/connect-client.js +32 -38
  68. package/dist/esm/connection/connect-client.js.map +1 -1
  69. package/dist/esm/connection/existing-process-transport.d.ts +1 -2
  70. package/dist/esm/connection/existing-process-transport.js +1 -1
  71. package/dist/esm/connection/existing-process-transport.js.map +1 -1
  72. package/dist/esm/dcr/dcr-authenticator.d.ts +36 -5
  73. package/dist/esm/dcr/dcr-authenticator.js +129 -52
  74. package/dist/esm/dcr/dcr-authenticator.js.map +1 -1
  75. package/dist/esm/dcr/dynamic-client-registrar.d.ts +2 -2
  76. package/dist/esm/dcr/dynamic-client-registrar.js +7 -6
  77. package/dist/esm/dcr/dynamic-client-registrar.js.map +1 -1
  78. package/dist/esm/index.d.ts +2 -0
  79. package/dist/esm/index.js +4 -1
  80. package/dist/esm/index.js.map +1 -1
  81. package/dist/esm/lib/url-utils.d.ts +17 -0
  82. package/dist/esm/lib/url-utils.js +34 -2
  83. package/dist/esm/lib/url-utils.js.map +1 -1
  84. package/dist/esm/response-wrappers.d.ts +1 -1
  85. package/dist/esm/response-wrappers.js.map +1 -1
  86. package/dist/esm/search/search.d.ts +1 -1
  87. package/dist/esm/search/search.js.map +1 -1
  88. package/package.json +4 -4
  89. package/dist/cjs/monkey-patches.d.cts +0 -6
  90. package/dist/cjs/monkey-patches.d.ts +0 -6
  91. package/dist/cjs/monkey-patches.js +0 -233
  92. package/dist/cjs/monkey-patches.js.map +0 -1
  93. package/dist/esm/monkey-patches.d.ts +0 -6
  94. package/dist/esm/monkey-patches.js +0 -32
  95. package/dist/esm/monkey-patches.js.map +0 -1
@@ -38,11 +38,21 @@ import { discoverAuthorizationServerIssuer, discoverAuthorizationServerMetadata,
38
38
  * if (caps.supportsDcr) {
39
39
  * console.log('Registration endpoint:', caps.registrationEndpoint);
40
40
  * }
41
- */ function buildCapabilities(metadata, scopes) {
41
+ */ function buildCapabilities(metadata, scopes, resource) {
42
42
  const supportsDcr = !!metadata.registration_endpoint;
43
43
  const capabilities = {
44
- supportsDcr
44
+ supportsDcr,
45
+ authorizationResponseIssSupported: metadata.authorization_response_iss_parameter_supported === true
45
46
  };
47
+ if (metadata.issuer) {
48
+ capabilities.issuer = metadata.issuer;
49
+ }
50
+ // Carried from the RFC 9728 document, not from the URL we were given: the
51
+ // resource server names itself, and that name is what RFC 8707 audience-binds
52
+ // a token to.
53
+ if (resource) {
54
+ capabilities.resource = resource;
55
+ }
46
56
  if (metadata.registration_endpoint) {
47
57
  capabilities.registrationEndpoint = metadata.registration_endpoint;
48
58
  }
@@ -60,12 +70,12 @@ import { discoverAuthorizationServerIssuer, discoverAuthorizationServerMetadata,
60
70
  }
61
71
  return capabilities;
62
72
  }
63
- async function resolveCapabilitiesFromAuthorizationServer(authServerUrl, scopes, allowLoopback) {
73
+ async function resolveCapabilitiesFromAuthorizationServer(authServerUrl, scopes, allowLoopback, resource) {
64
74
  const metadata = await discoverAuthorizationServerMetadata(authServerUrl, {
65
75
  allowLoopback
66
76
  });
67
77
  if (!metadata) return null;
68
- return buildCapabilities(metadata, scopes);
78
+ return buildCapabilities(metadata, scopes, resource);
69
79
  }
70
80
  export async function probeAuthCapabilities(baseUrl) {
71
81
  try {
@@ -86,13 +96,13 @@ export async function probeAuthCapabilities(baseUrl) {
86
96
  supportsDcr: false
87
97
  };
88
98
  }
89
- const capabilities = await resolveCapabilitiesFromAuthorizationServer(authServerUrl, resourceMetadata.scopes_supported, allowLoopback);
99
+ const capabilities = await resolveCapabilitiesFromAuthorizationServer(authServerUrl, resourceMetadata.scopes_supported, allowLoopback, resourceMetadata.resource);
90
100
  if (capabilities) {
91
101
  return capabilities;
92
102
  }
93
103
  const issuer = await discoverAuthorizationServerIssuer(baseUrl);
94
104
  if (issuer) {
95
- const issuerCapabilities = await resolveCapabilitiesFromAuthorizationServer(issuer, resourceMetadata.scopes_supported, allowLoopback);
105
+ const issuerCapabilities = await resolveCapabilitiesFromAuthorizationServer(issuer, resourceMetadata.scopes_supported, allowLoopback, resourceMetadata.resource);
96
106
  if (issuerCapabilities) return issuerCapabilities;
97
107
  }
98
108
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/auth/capability-discovery.ts"],"sourcesContent":["/**\n * OAuth Server Capability Discovery\n * Probes RFC 9728 (Protected Resource) and RFC 8414 (Authorization Server) metadata\n */\n\nimport { normalizeUrl } from '../lib/url-utils.ts';\nimport { isLoopbackUrl } from './discovery-fetch.ts';\nimport { discoverAuthorizationServerIssuer, discoverAuthorizationServerMetadata, discoverProtectedResourceMetadata } from './rfc9728-discovery.ts';\nimport type { AuthCapabilities, AuthorizationServerMetadata } from './types.ts';\n\n/**\n * Extract origin (protocol + host) from a URL\n * @param url - Full URL that may include a path\n * @returns Origin (e.g., \"https://example.com\") or original string if invalid URL\n *\n * @example\n * getOrigin('https://example.com/mcp') // → 'https://example.com'\n * getOrigin('http://localhost:9999/api/v1/mcp') // → 'http://localhost:9999'\n */\nfunction getOrigin(url: string): string {\n try {\n return new URL(url).origin;\n } catch {\n // Invalid URL - return as-is for graceful degradation\n return url;\n }\n}\n\n/**\n * Probe OAuth server capabilities using RFC 9728 → RFC 8414 discovery chain\n * Returns capabilities including DCR support detection\n *\n * Discovery Strategy:\n * 1. Try RFC 9728 Protected Resource Metadata (supports cross-domain OAuth)\n * 2. If found, use first authorization_server to discover RFC 8414 Authorization Server Metadata\n * 3. Fall back to direct RFC 8414 discovery at resource origin\n *\n * @param baseUrl - Base URL of the protected resource (e.g., https://ai.todoist.net/mcp)\n * @returns AuthCapabilities object with discovered endpoints and features\n *\n * @example\n * // Todoist case: MCP at ai.todoist.net/mcp, OAuth at todoist.com\n * const caps = await probeAuthCapabilities('https://ai.todoist.net/mcp');\n * if (caps.supportsDcr) {\n * console.log('Registration endpoint:', caps.registrationEndpoint);\n * }\n */\nfunction buildCapabilities(metadata: AuthorizationServerMetadata, scopes?: string[]): AuthCapabilities {\n const supportsDcr = !!metadata.registration_endpoint;\n const capabilities: AuthCapabilities = { supportsDcr };\n\n if (metadata.registration_endpoint) {\n capabilities.registrationEndpoint = metadata.registration_endpoint;\n }\n if (metadata.authorization_endpoint) {\n capabilities.authorizationEndpoint = metadata.authorization_endpoint;\n }\n if (metadata.token_endpoint) capabilities.tokenEndpoint = metadata.token_endpoint;\n if (metadata.introspection_endpoint) {\n capabilities.introspectionEndpoint = metadata.introspection_endpoint;\n }\n\n if (scopes && scopes.length > 0) {\n capabilities.scopes = scopes;\n } else if (metadata.scopes_supported) {\n capabilities.scopes = metadata.scopes_supported;\n }\n\n return capabilities;\n}\n\nasync function resolveCapabilitiesFromAuthorizationServer(authServerUrl: string, scopes: string[] | undefined, allowLoopback: boolean): Promise<AuthCapabilities | null> {\n const metadata = await discoverAuthorizationServerMetadata(authServerUrl, { allowLoopback });\n if (!metadata) return null;\n return buildCapabilities(metadata, scopes);\n}\n\nexport async function probeAuthCapabilities(baseUrl: string): Promise<AuthCapabilities> {\n try {\n const normalizedBaseUrl = normalizeUrl(baseUrl);\n // Trust signal for every authorization-server fetch below: whether the\n // configured MCP server is itself loopback, never a remote-supplied URL.\n const allowLoopback = isLoopbackUrl(normalizedBaseUrl);\n // Strategy 1: Try RFC 9728 Protected Resource Metadata discovery\n // This handles cross-domain OAuth (e.g., Todoist: ai.todoist.net/mcp → todoist.com)\n const resourceMetadata = await discoverProtectedResourceMetadata(normalizedBaseUrl);\n\n if (resourceMetadata && resourceMetadata.authorization_servers.length > 0) {\n // Found protected resource metadata with authorization servers\n // Discover the authorization server's metadata (RFC 8414)\n const authServerUrl = resourceMetadata.authorization_servers[0];\n if (!authServerUrl) {\n // Array has length > 0 but first element is undefined/null - skip this path\n return { supportsDcr: false };\n }\n const capabilities = await resolveCapabilitiesFromAuthorizationServer(authServerUrl, resourceMetadata.scopes_supported, allowLoopback);\n if (capabilities) {\n return capabilities;\n }\n\n const issuer = await discoverAuthorizationServerIssuer(baseUrl);\n if (issuer) {\n const issuerCapabilities = await resolveCapabilitiesFromAuthorizationServer(issuer, resourceMetadata.scopes_supported, allowLoopback);\n if (issuerCapabilities) return issuerCapabilities;\n }\n }\n\n const issuer = await discoverAuthorizationServerIssuer(normalizedBaseUrl);\n if (issuer) {\n const issuerCapabilities = await resolveCapabilitiesFromAuthorizationServer(issuer, undefined, allowLoopback);\n if (issuerCapabilities) return issuerCapabilities;\n }\n\n // Strategy 2: Fall back to direct RFC 8414 discovery at resource origin\n // This handles same-domain OAuth (traditional setup)\n const origin = getOrigin(normalizedBaseUrl);\n const originCapabilities = await resolveCapabilitiesFromAuthorizationServer(origin, undefined, allowLoopback);\n if (originCapabilities) return originCapabilities;\n\n // No OAuth metadata found\n return { supportsDcr: false };\n } catch (_error) {\n // Network error, invalid JSON, or other fetch failure\n // Gracefully degrade - assume no DCR support\n return { supportsDcr: false };\n }\n}\n"],"names":["normalizeUrl","isLoopbackUrl","discoverAuthorizationServerIssuer","discoverAuthorizationServerMetadata","discoverProtectedResourceMetadata","getOrigin","url","URL","origin","buildCapabilities","metadata","scopes","supportsDcr","registration_endpoint","capabilities","registrationEndpoint","authorization_endpoint","authorizationEndpoint","token_endpoint","tokenEndpoint","introspection_endpoint","introspectionEndpoint","length","scopes_supported","resolveCapabilitiesFromAuthorizationServer","authServerUrl","allowLoopback","probeAuthCapabilities","baseUrl","normalizedBaseUrl","resourceMetadata","authorization_servers","issuer","issuerCapabilities","undefined","originCapabilities","_error"],"mappings":"AAAA;;;CAGC,GAED,SAASA,YAAY,QAAQ,sBAAsB;AACnD,SAASC,aAAa,QAAQ,uBAAuB;AACrD,SAASC,iCAAiC,EAAEC,mCAAmC,EAAEC,iCAAiC,QAAQ,yBAAyB;AAGnJ;;;;;;;;CAQC,GACD,SAASC,UAAUC,GAAW;IAC5B,IAAI;QACF,OAAO,IAAIC,IAAID,KAAKE,MAAM;IAC5B,EAAE,OAAM;QACN,sDAAsD;QACtD,OAAOF;IACT;AACF;AAEA;;;;;;;;;;;;;;;;;;CAkBC,GACD,SAASG,kBAAkBC,QAA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AME,eAAe,MAAMU,2CAA2CC,eAAeK,iBAAiBP,gBAAgB,EAAEG;YACxH,IAAIZ,cAAc;gBAChB,OAAOA;YACT;YAEA,MAAMkB,SAAS,MAAM9B,kCAAkC0B;YACvD,IAAII,QAAQ;gBACV,MAAMC,qBAAqB,MAAMT,2CAA2CQ,QAAQF,iBAAiBP,gBAAgB,EAAEG;gBACvH,IAAIO,oBAAoB,OAAOA;YACjC;QACF;QAEA,MAAMD,SAAS,MAAM9B,kCAAkC2B;QACvD,IAAIG,QAAQ;YACV,MAAMC,qBAAqB,MAAMT,2CAA2CQ,QAAQE,WAAWR;YAC/F,IAAIO,oBAAoB,OAAOA;QACjC;QAEA,wEAAwE;QACxE,qDAAqD;QACrD,MAAMzB,SAASH,UAAUwB;QACzB,MAAMM,qBAAqB,MAAMX,2CAA2ChB,QAAQ0B,WAAWR;QAC/F,IAAIS,oBAAoB,OAAOA;QAE/B,0BAA0B;QAC1B,OAAO;YAAEvB,aAAa;QAAM;IAC9B,EAAE,OAAOwB,QAAQ;QACf,sDAAsD;QACtD,6CAA6C;QAC7C,OAAO;YAAExB,aAAa;QAAM;IAC9B;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/auth/capability-discovery.ts"],"sourcesContent":["/**\n * OAuth Server Capability Discovery\n * Probes RFC 9728 (Protected Resource) and RFC 8414 (Authorization Server) metadata\n */\n\nimport { normalizeUrl } from '../lib/url-utils.ts';\nimport { isLoopbackUrl } from './discovery-fetch.ts';\nimport { discoverAuthorizationServerIssuer, discoverAuthorizationServerMetadata, discoverProtectedResourceMetadata } from './rfc9728-discovery.ts';\nimport type { AuthCapabilities, AuthorizationServerMetadata } from './types.ts';\n\n/**\n * Extract origin (protocol + host) from a URL\n * @param url - Full URL that may include a path\n * @returns Origin (e.g., \"https://example.com\") or original string if invalid URL\n *\n * @example\n * getOrigin('https://example.com/mcp') // → 'https://example.com'\n * getOrigin('http://localhost:9999/api/v1/mcp') // → 'http://localhost:9999'\n */\nfunction getOrigin(url: string): string {\n try {\n return new URL(url).origin;\n } catch {\n // Invalid URL - return as-is for graceful degradation\n return url;\n }\n}\n\n/**\n * Probe OAuth server capabilities using RFC 9728 → RFC 8414 discovery chain\n * Returns capabilities including DCR support detection\n *\n * Discovery Strategy:\n * 1. Try RFC 9728 Protected Resource Metadata (supports cross-domain OAuth)\n * 2. If found, use first authorization_server to discover RFC 8414 Authorization Server Metadata\n * 3. Fall back to direct RFC 8414 discovery at resource origin\n *\n * @param baseUrl - Base URL of the protected resource (e.g., https://ai.todoist.net/mcp)\n * @returns AuthCapabilities object with discovered endpoints and features\n *\n * @example\n * // Todoist case: MCP at ai.todoist.net/mcp, OAuth at todoist.com\n * const caps = await probeAuthCapabilities('https://ai.todoist.net/mcp');\n * if (caps.supportsDcr) {\n * console.log('Registration endpoint:', caps.registrationEndpoint);\n * }\n */\nfunction buildCapabilities(metadata: AuthorizationServerMetadata, scopes?: string[], resource?: string): AuthCapabilities {\n const supportsDcr = !!metadata.registration_endpoint;\n const capabilities: AuthCapabilities = { supportsDcr, authorizationResponseIssSupported: metadata.authorization_response_iss_parameter_supported === true };\n\n if (metadata.issuer) {\n capabilities.issuer = metadata.issuer;\n }\n\n // Carried from the RFC 9728 document, not from the URL we were given: the\n // resource server names itself, and that name is what RFC 8707 audience-binds\n // a token to.\n if (resource) {\n capabilities.resource = resource;\n }\n\n if (metadata.registration_endpoint) {\n capabilities.registrationEndpoint = metadata.registration_endpoint;\n }\n if (metadata.authorization_endpoint) {\n capabilities.authorizationEndpoint = metadata.authorization_endpoint;\n }\n if (metadata.token_endpoint) capabilities.tokenEndpoint = metadata.token_endpoint;\n if (metadata.introspection_endpoint) {\n capabilities.introspectionEndpoint = metadata.introspection_endpoint;\n }\n\n if (scopes && scopes.length > 0) {\n capabilities.scopes = scopes;\n } else if (metadata.scopes_supported) {\n capabilities.scopes = metadata.scopes_supported;\n }\n\n return capabilities;\n}\n\nasync function resolveCapabilitiesFromAuthorizationServer(authServerUrl: string, scopes: string[] | undefined, allowLoopback: boolean, resource?: string): Promise<AuthCapabilities | null> {\n const metadata = await discoverAuthorizationServerMetadata(authServerUrl, { allowLoopback });\n if (!metadata) return null;\n return buildCapabilities(metadata, scopes, resource);\n}\n\nexport async function probeAuthCapabilities(baseUrl: string): Promise<AuthCapabilities> {\n try {\n const normalizedBaseUrl = normalizeUrl(baseUrl);\n // Trust signal for every authorization-server fetch below: whether the\n // configured MCP server is itself loopback, never a remote-supplied URL.\n const allowLoopback = isLoopbackUrl(normalizedBaseUrl);\n // Strategy 1: Try RFC 9728 Protected Resource Metadata discovery\n // This handles cross-domain OAuth (e.g., Todoist: ai.todoist.net/mcp → todoist.com)\n const resourceMetadata = await discoverProtectedResourceMetadata(normalizedBaseUrl);\n\n if (resourceMetadata && resourceMetadata.authorization_servers.length > 0) {\n // Found protected resource metadata with authorization servers\n // Discover the authorization server's metadata (RFC 8414)\n const authServerUrl = resourceMetadata.authorization_servers[0];\n if (!authServerUrl) {\n // Array has length > 0 but first element is undefined/null - skip this path\n return { supportsDcr: false };\n }\n const capabilities = await resolveCapabilitiesFromAuthorizationServer(authServerUrl, resourceMetadata.scopes_supported, allowLoopback, resourceMetadata.resource);\n if (capabilities) {\n return capabilities;\n }\n\n const issuer = await discoverAuthorizationServerIssuer(baseUrl);\n if (issuer) {\n const issuerCapabilities = await resolveCapabilitiesFromAuthorizationServer(issuer, resourceMetadata.scopes_supported, allowLoopback, resourceMetadata.resource);\n if (issuerCapabilities) return issuerCapabilities;\n }\n }\n\n const issuer = await discoverAuthorizationServerIssuer(normalizedBaseUrl);\n if (issuer) {\n const issuerCapabilities = await resolveCapabilitiesFromAuthorizationServer(issuer, undefined, allowLoopback);\n if (issuerCapabilities) return issuerCapabilities;\n }\n\n // Strategy 2: Fall back to direct RFC 8414 discovery at resource origin\n // This handles same-domain OAuth (traditional setup)\n const origin = getOrigin(normalizedBaseUrl);\n const originCapabilities = await resolveCapabilitiesFromAuthorizationServer(origin, undefined, allowLoopback);\n if (originCapabilities) return originCapabilities;\n\n // No OAuth metadata found\n return { supportsDcr: false };\n } catch (_error) {\n // Network error, invalid JSON, or other fetch failure\n // Gracefully degrade - assume no DCR support\n return { supportsDcr: false };\n }\n}\n"],"names":["normalizeUrl","isLoopbackUrl","discoverAuthorizationServerIssuer","discoverAuthorizationServerMetadata","discoverProtectedResourceMetadata","getOrigin","url","URL","origin","buildCapabilities","metadata","scopes","resource","supportsDcr","registration_endpoint","capabilities","authorizationResponseIssSupported","authorization_response_iss_parameter_supported","issuer","registrationEndpoint","authorization_endpoint","authorizationEndpoint","token_endpoint","tokenEndpoint","introspection_endpoint","introspectionEndpoint","length","scopes_supported","resolveCapabilitiesFromAuthorizationServer","authServerUrl","allowLoopback","probeAuthCapabilities","baseUrl","normalizedBaseUrl","resourceMetadata","authorization_servers","issuerCapabilities","undefined","originCapabilities","_error"],"mappings":"AAAA;;;CAGC,GAED,SAASA,YAAY,QAAQ,sBAAsB;AACnD,SAASC,aAAa,QAAQ,uBAAuB;AACrD,SAASC,iCAAiC,EAAEC,mCAAmC,EAAEC,iCAAiC,QAAQ,yBAAyB;AAGnJ;;;;;;;;CAQC,GACD,SAASC,UAAUC,GAAW;IAC5B,IAAI;QACF,OAAO,IAAIC,IAAID,KAAKE,MAAM;IAC5B,EAAE,OAAM;QACN,sDAAsD;QACtD,OAAOF;IACT;AACF;AAEA;;;;;;;;;;;;;;;;;;CAkBC,GACD,SAASG,kBAAkBC,QAAqC,EAAEC,MAAiB,EAAEC,QAAiB;IACpG,MAAMC,cAAc,CAAC,CAACH,SAASI,qBAAqB;IACpD,MAAMC,eAAiC;QAAEF;QAAaG,mCAAmCN,SAASO,8CAA8C,KAAK;IAAK;IAE1J,IAAIP,SAASQ,MAAM,EAAE;QACnBH,aAAaG,MAAM,GAAGR,SAASQ,MAAM;IACvC;IAEA,0EAA0E;IAC1E,8EAA8E;IAC9E,cAAc;IACd,IAAIN,UAAU;QACZG,aAAaH,QAAQ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,EAAEG,eAAeI,iBAAiBtB,QAAQ;YAChK,IAAIG,cAAc;gBAChB,OAAOA;YACT;YAEA,MAAMG,SAAS,MAAMhB,kCAAkC8B;YACvD,IAAId,QAAQ;gBACV,MAAMkB,qBAAqB,MAAMR,2CAA2CV,QAAQgB,iBAAiBP,gBAAgB,EAAEG,eAAeI,iBAAiBtB,QAAQ;gBAC/J,IAAIwB,oBAAoB,OAAOA;YACjC;QACF;QAEA,MAAMlB,SAAS,MAAMhB,kCAAkC+B;QACvD,IAAIf,QAAQ;YACV,MAAMkB,qBAAqB,MAAMR,2CAA2CV,QAAQmB,WAAWP;YAC/F,IAAIM,oBAAoB,OAAOA;QACjC;QAEA,wEAAwE;QACxE,qDAAqD;QACrD,MAAM5B,SAASH,UAAU4B;QACzB,MAAMK,qBAAqB,MAAMV,2CAA2CpB,QAAQ6B,WAAWP;QAC/F,IAAIQ,oBAAoB,OAAOA;QAE/B,0BAA0B;QAC1B,OAAO;YAAEzB,aAAa;QAAM;IAC9B,EAAE,OAAO0B,QAAQ;QACf,sDAAsD;QACtD,6CAA6C;QAC7C,OAAO;YAAE1B,aAAa;QAAM;IAC9B;AACF"}
@@ -1,6 +1,15 @@
1
1
  export declare class DiscoveryFetchError extends Error {
2
2
  constructor(message: string);
3
3
  }
4
+ type LookupRecord = {
5
+ address: string;
6
+ family: number;
7
+ };
8
+ /** DNS implementation, injectable for deterministic tests. Same contract as `dns.lookup` with `{ all: true, verbatim: true }`. */
9
+ type Lookup = (hostname: string, options: {
10
+ all: true;
11
+ verbatim: true;
12
+ }, callback: (error: NodeJS.ErrnoException | null, addresses: LookupRecord[]) => void) => void;
4
13
  /**
5
14
  * True if `rawUrl`'s host is loopback, used to decide `allowLoopback` grants
6
15
  * from the URL the caller configured, not remote-supplied data. Fails closed on an unparseable URL.
@@ -13,15 +22,25 @@ export interface DiscoveryFetchOptions {
13
22
  */
14
23
  allowLoopback?: boolean;
15
24
  /**
16
- * Per-request connect/read timeout in ms. Defaults to `DEFAULT_TIMEOUT_MS`;
17
- * overridable so tests can bound slow-failure cases.
25
+ * Per-hop timeout in ms, applied to both the DNS resolution and the request.
26
+ * Defaults to `DEFAULT_TIMEOUT_MS`; overridable so tests can bound slow-failure cases.
18
27
  */
19
28
  timeoutMs?: number;
29
+ /**
30
+ * DNS implementation used for the pre-request resolution, injectable for
31
+ * deterministic tests. Defaults to `dns.lookup`.
32
+ */
33
+ lookup?: Lookup;
20
34
  }
21
35
  /**
22
36
  * Fetches an OAuth-discovery URL with SSRF mitigations applied to the
23
37
  * initial URL and every redirect hop; redirects are validated, not auto-followed.
24
38
  *
39
+ * The hostname is resolved once, every returned address is validated, and the
40
+ * validated set is pinned into the request through a custom `lookup`, so the
41
+ * request cannot resolve the hostname a second time and cannot be steered to
42
+ * a different address by a DNS-rebinding answer.
43
+ *
25
44
  * @param rawUrl - URL to fetch; may be remote-server-supplied (the threat this guards against).
26
45
  * @param init - Standard fetch options; `redirect` is always forced to `'manual'`.
27
46
  * @param context - Short label used only in error messages, never echoing the URL.
@@ -33,3 +52,4 @@ export declare function discoveryFetch(rawUrl: string, init?: RequestInit, conte
33
52
  * while reading (not after buffering the whole thing).
34
53
  */
35
54
  export declare function readDiscoveryJson<T>(response: Response, context: string): Promise<T>;
55
+ export {};
@@ -1,7 +1,9 @@
1
1
  /**
2
2
  * Hardened fetch for OAuth discovery URLs, which the remote MCP server
3
3
  * controls (SSRF mitigation). See ARCHITECTURE.md's "SSRF mitigation" section for the threat model.
4
- */ import dns from 'node:dns/promises';
4
+ */ import dns from 'node:dns';
5
+ import http from 'node:http';
6
+ import https from 'node:https';
5
7
  import { isIP } from 'node:net';
6
8
  import ipaddr from 'ipaddr.js';
7
9
  export class DiscoveryFetchError extends Error {
@@ -46,6 +48,13 @@ function stripBrackets(hostname) {
46
48
  return true; // unparseable - fail closed
47
49
  }
48
50
  }
51
+ function isLoopbackAddress(address) {
52
+ try {
53
+ return ipaddr.process(address).range() === 'loopback';
54
+ } catch {
55
+ return false;
56
+ }
57
+ }
49
58
  /**
50
59
  * Validates scheme and, for literal-IP hosts, address range. `allowLoopback`
51
60
  * reflects trust in the calling server, never in `rawUrl` itself.
@@ -70,88 +79,227 @@ function stripBrackets(hostname) {
70
79
  }
71
80
  return url;
72
81
  }
82
+ function lookupAll(hostname, lookup, timeoutMs) {
83
+ return new Promise((resolve, reject)=>{
84
+ let settled = false;
85
+ const deadline = setTimeout(()=>{
86
+ if (!settled) {
87
+ settled = true;
88
+ reject(new Error('DNS resolution timed out'));
89
+ }
90
+ }, timeoutMs);
91
+ try {
92
+ lookup(hostname, {
93
+ all: true,
94
+ verbatim: true
95
+ }, (error, addresses)=>{
96
+ if (settled) return;
97
+ settled = true;
98
+ clearTimeout(deadline);
99
+ if (error || addresses.length === 0) reject(new Error('DNS resolution failed'));
100
+ else resolve(addresses);
101
+ });
102
+ } catch {
103
+ if (!settled) {
104
+ settled = true;
105
+ clearTimeout(deadline);
106
+ reject(new Error('DNS resolution failed'));
107
+ }
108
+ }
109
+ });
110
+ }
73
111
  /**
74
- * Resolves the hostname and rejects it if any address is private/reserved.
75
- * Does not close the DNS-rebinding TOCTOU race against `fetch`'s own resolution a moment later.
76
- */ async function assertResolvesToSafeAddress(url, context, allowLoopback) {
112
+ * Resolves the hostname once, rejects it unless every returned address is
113
+ * acceptable, and returns the validated set. The set is pinned into the
114
+ * request itself (see `requestOnce`), which is what closes the DNS-rebinding
115
+ * TOCTOU: the transport can only dial addresses that were already validated,
116
+ * and it never resolves the hostname a second time.
117
+ */ async function resolveSafeAddresses(url, context, allowLoopback, lookup, timeoutMs) {
77
118
  const host = stripBrackets(url.hostname);
78
- if (isIP(host)) return; // literal IP already fully checked in assertSafeUrl
79
- if (allowLoopback && isLoopbackHost(host)) return; // literal "localhost" under a trusted-loopback grant
119
+ if (isIP(host)) return [
120
+ {
121
+ address: host,
122
+ family: host.includes(':') ? 6 : 4
123
+ }
124
+ ]; // literal IP already fully checked in assertSafeUrl
125
+ // Literal `localhost` under a trusted-loopback grant: still resolved, and the
126
+ // answers must be loopback - the grant covers loopback, not "wherever
127
+ // localhost happens to point".
128
+ const loopbackGrant = allowLoopback && isLoopbackHost(host);
80
129
  let addresses;
81
130
  try {
82
- const records = await dns.lookup(host, {
83
- all: true,
84
- verbatim: true
85
- });
86
- addresses = records.map((record)=>record.address);
131
+ addresses = await lookupAll(host, lookup, timeoutMs);
87
132
  } catch {
88
133
  throw new DiscoveryFetchError(`Refusing to fetch ${context}: host could not be resolved`);
89
134
  }
90
- if (addresses.length === 0 || addresses.some((address)=>isBlockedAddress(address))) {
135
+ if (loopbackGrant) {
136
+ if (!addresses.every((record)=>isLoopbackAddress(record.address))) {
137
+ throw new DiscoveryFetchError(`Refusing to fetch ${context}: host does not resolve to a loopback address`);
138
+ }
139
+ } else if (addresses.some((record)=>isBlockedAddress(record.address))) {
91
140
  throw new DiscoveryFetchError(`Refusing to fetch ${context}: host resolves to an address that is not publicly routable`);
92
141
  }
142
+ return addresses;
93
143
  }
94
- async function readLimited(response, context, maxBytes) {
95
- var _response_body;
96
- const contentLength = response.headers.get('content-length');
97
- if (contentLength && Number(contentLength) > maxBytes) {
98
- throw new DiscoveryFetchError(`Refusing to read ${context}: response too large`);
99
- }
100
- const reader = (_response_body = response.body) === null || _response_body === void 0 ? void 0 : _response_body.getReader();
101
- if (!reader) {
102
- const text = await response.text();
103
- if (Buffer.byteLength(text, 'utf8') > maxBytes) {
104
- throw new DiscoveryFetchError(`Refusing to read ${context}: response too large`);
144
+ /**
145
+ * A `net` lookup that can only ever answer with `addresses` - the set already
146
+ * validated for this URL. The request is built against the original URL (so
147
+ * SNI and certificate verification still see the hostname), but the
148
+ * connection can only land on a validated address.
149
+ */ function pinnedLookup(addresses) {
150
+ return (_hostname, options, callback)=>{
151
+ if (typeof options === 'object' && options.all === true) {
152
+ callback(null, addresses);
153
+ return;
105
154
  }
106
- return text;
107
- }
108
- const chunks = [];
109
- let total = 0;
110
- try {
111
- for(;;){
112
- const { done, value } = await reader.read();
113
- if (done) break;
114
- if (!value) continue;
115
- total += value.byteLength;
116
- if (total > maxBytes) {
117
- throw new DiscoveryFetchError(`Refusing to read ${context}: response too large`);
155
+ const first = addresses[0];
156
+ if (!first) {
157
+ callback(Object.assign(new Error('no validated address'), {
158
+ code: 'ENOTFOUND'
159
+ }), '', 0);
160
+ return;
161
+ }
162
+ callback(null, first.address, first.family);
163
+ };
164
+ }
165
+ function toRequestHeaders(init) {
166
+ const headers = new Headers(init.headers);
167
+ const out = {};
168
+ for (const [name, value] of headers)out[name] = value;
169
+ return out;
170
+ }
171
+ async function toRequestBody(body) {
172
+ if (body === undefined || body === null) return undefined;
173
+ if (typeof body === 'string') return Buffer.from(body);
174
+ if (body instanceof URLSearchParams) return Buffer.from(body.toString());
175
+ if (body instanceof Blob) return Buffer.from(await body.arrayBuffer());
176
+ if (body instanceof ArrayBuffer) return Buffer.from(body);
177
+ if (ArrayBuffer.isView(body)) return Buffer.from(body.buffer, body.byteOffset, body.byteLength);
178
+ if (typeof ReadableStream !== 'undefined' && body instanceof ReadableStream) {
179
+ const reader = body.getReader();
180
+ const chunks = [];
181
+ try {
182
+ for(;;){
183
+ const { done, value } = await reader.read();
184
+ if (done) break;
185
+ if (value) chunks.push(value);
118
186
  }
119
- chunks.push(value);
187
+ } finally{
188
+ reader.releaseLock();
120
189
  }
121
- } finally{
122
- reader.releaseLock();
190
+ return Buffer.concat(chunks.map((chunk)=>Buffer.from(chunk)));
123
191
  }
124
- return Buffer.concat(chunks.map((chunk)=>Buffer.from(chunk))).toString('utf8');
192
+ throw new Error('unsupported request body');
193
+ }
194
+ function toResponse(status, statusText, headers, body) {
195
+ const responseHeaders = new Headers();
196
+ for (const [name, value] of Object.entries(headers)){
197
+ if (value === undefined) continue;
198
+ if (Array.isArray(value)) {
199
+ for (const entry of value)responseHeaders.append(name, entry);
200
+ } else {
201
+ responseHeaders.append(name, value);
202
+ }
203
+ }
204
+ // The fetch spec gives these statuses a null body, and the Response
205
+ // constructor rejects a body for them.
206
+ const nullBody = status === 204 || status === 205 || status === 304;
207
+ return new Response(nullBody ? null : body, {
208
+ status,
209
+ statusText,
210
+ headers: responseHeaders
211
+ });
125
212
  }
126
- async function fetchOnce(url, init, context, allowLoopback, timeoutMs) {
127
- await assertResolvesToSafeAddress(url, context, allowLoopback);
128
- const controller = new AbortController();
129
- const timeout = setTimeout(()=>controller.abort(), timeoutMs);
213
+ async function requestOnce(url, init, context, addresses, timeoutMs) {
214
+ var _init_method;
215
+ let body;
130
216
  try {
131
- return await fetch(url, {
132
- ...init,
133
- redirect: 'manual',
134
- signal: controller.signal
135
- });
217
+ body = await toRequestBody(init.body);
136
218
  } catch {
137
- // Never surface the underlying error (ECONNREFUSED host/port, DNS detail, etc.)
138
219
  throw new DiscoveryFetchError(`Failed to fetch ${context}`);
139
- } finally{
140
- clearTimeout(timeout);
141
220
  }
221
+ const transport = url.protocol === 'https:' ? https : http;
222
+ const options = {
223
+ method: ((_init_method = init.method) !== null && _init_method !== void 0 ? _init_method : 'GET').toUpperCase(),
224
+ headers: toRequestHeaders(init),
225
+ agent: false,
226
+ lookup: pinnedLookup(addresses)
227
+ };
228
+ return new Promise((resolve, reject)=>{
229
+ let settled = false;
230
+ let req;
231
+ let res;
232
+ const fail = (message)=>{
233
+ if (!settled) {
234
+ settled = true;
235
+ clearTimeout(deadline);
236
+ reject(new DiscoveryFetchError(message));
237
+ }
238
+ };
239
+ const deadline = setTimeout(()=>{
240
+ res === null || res === void 0 ? void 0 : res.destroy();
241
+ req === null || req === void 0 ? void 0 : req.destroy();
242
+ fail(`Failed to fetch ${context}`);
243
+ }, timeoutMs);
244
+ try {
245
+ req = transport.request(url, options, (response)=>{
246
+ var _response_statusMessage;
247
+ res = response;
248
+ const status = response.statusCode;
249
+ const statusText = (_response_statusMessage = response.statusMessage) !== null && _response_statusMessage !== void 0 ? _response_statusMessage : '';
250
+ if (status === undefined || status < 200 || status > 599) {
251
+ response.destroy();
252
+ fail(`Failed to fetch ${context}`);
253
+ return;
254
+ }
255
+ const chunks = [];
256
+ let total = 0;
257
+ response.on('data', (chunk)=>{
258
+ total += chunk.length;
259
+ if (total > MAX_BODY_BYTES) {
260
+ response.destroy();
261
+ fail(`Refusing to read ${context}: response too large`);
262
+ return;
263
+ }
264
+ chunks.push(chunk);
265
+ });
266
+ response.once('error', ()=>fail(`Failed to fetch ${context}`));
267
+ response.once('end', ()=>{
268
+ if (settled) return;
269
+ settled = true;
270
+ clearTimeout(deadline);
271
+ resolve(toResponse(status, statusText, response.headers, Buffer.concat(chunks)));
272
+ });
273
+ });
274
+ } catch {
275
+ fail(`Failed to fetch ${context}`);
276
+ return;
277
+ }
278
+ req.once('error', ()=>fail(`Failed to fetch ${context}`));
279
+ req.end(body);
280
+ });
281
+ }
282
+ async function fetchOnce(url, init, context, allowLoopback, timeoutMs, lookup) {
283
+ const addresses = await resolveSafeAddresses(url, context, allowLoopback, lookup, timeoutMs);
284
+ return requestOnce(url, init, context, addresses, timeoutMs);
142
285
  }
143
286
  /**
144
287
  * Fetches an OAuth-discovery URL with SSRF mitigations applied to the
145
288
  * initial URL and every redirect hop; redirects are validated, not auto-followed.
146
289
  *
290
+ * The hostname is resolved once, every returned address is validated, and the
291
+ * validated set is pinned into the request through a custom `lookup`, so the
292
+ * request cannot resolve the hostname a second time and cannot be steered to
293
+ * a different address by a DNS-rebinding answer.
294
+ *
147
295
  * @param rawUrl - URL to fetch; may be remote-server-supplied (the threat this guards against).
148
296
  * @param init - Standard fetch options; `redirect` is always forced to `'manual'`.
149
297
  * @param context - Short label used only in error messages, never echoing the URL.
150
298
  * @param options - See `DiscoveryFetchOptions`.
151
299
  */ export async function discoveryFetch(rawUrl, init = {}, context = 'discovery URL', options = {}) {
152
- const { allowLoopback = false, timeoutMs = DEFAULT_TIMEOUT_MS } = options;
300
+ const { allowLoopback = false, timeoutMs = DEFAULT_TIMEOUT_MS, lookup = dns.lookup } = options;
153
301
  let url = assertSafeUrl(rawUrl, context, allowLoopback);
154
- let response = await fetchOnce(url, init, context, allowLoopback, timeoutMs);
302
+ let response = await fetchOnce(url, init, context, allowLoopback, timeoutMs, lookup);
155
303
  let redirectsLeft = MAX_REDIRECTS;
156
304
  while(response.status >= 300 && response.status < 400){
157
305
  const location = response.headers.get('location');
@@ -167,7 +315,7 @@ async function fetchOnce(url, init, context, allowLoopback, timeoutMs) {
167
315
  throw new DiscoveryFetchError(`Refusing to fetch ${context}: invalid redirect target`);
168
316
  }
169
317
  url = assertSafeUrl(nextUrl.toString(), context, allowLoopback);
170
- response = await fetchOnce(url, init, context, allowLoopback, timeoutMs);
318
+ response = await fetchOnce(url, init, context, allowLoopback, timeoutMs, lookup);
171
319
  }
172
320
  return response;
173
321
  }
@@ -182,3 +330,35 @@ async function fetchOnce(url, init, context, allowLoopback, timeoutMs) {
182
330
  throw new DiscoveryFetchError(`Refusing to parse ${context}: invalid JSON`);
183
331
  }
184
332
  }
333
+ async function readLimited(response, context, maxBytes) {
334
+ var _response_body;
335
+ const contentLength = response.headers.get('content-length');
336
+ if (contentLength && Number(contentLength) > maxBytes) {
337
+ throw new DiscoveryFetchError(`Refusing to read ${context}: response too large`);
338
+ }
339
+ const reader = (_response_body = response.body) === null || _response_body === void 0 ? void 0 : _response_body.getReader();
340
+ if (!reader) {
341
+ const text = await response.text();
342
+ if (Buffer.byteLength(text, 'utf8') > maxBytes) {
343
+ throw new DiscoveryFetchError(`Refusing to read ${context}: response too large`);
344
+ }
345
+ return text;
346
+ }
347
+ const chunks = [];
348
+ let total = 0;
349
+ try {
350
+ for(;;){
351
+ const { done, value } = await reader.read();
352
+ if (done) break;
353
+ if (!value) continue;
354
+ total += value.byteLength;
355
+ if (total > maxBytes) {
356
+ throw new DiscoveryFetchError(`Refusing to read ${context}: response too large`);
357
+ }
358
+ chunks.push(value);
359
+ }
360
+ } finally{
361
+ reader.releaseLock();
362
+ }
363
+ return Buffer.concat(chunks.map((chunk)=>Buffer.from(chunk))).toString('utf8');
364
+ }
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/auth/discovery-fetch.ts"],"sourcesContent":["/**\n * Hardened fetch for OAuth discovery URLs, which the remote MCP server\n * controls (SSRF mitigation). See ARCHITECTURE.md's \"SSRF mitigation\" section for the threat model.\n */\nimport dns from 'node:dns/promises';\nimport { isIP } from 'node:net';\nimport ipaddr from 'ipaddr.js';\n\nexport class DiscoveryFetchError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'DiscoveryFetchError';\n }\n}\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst MAX_REDIRECTS = 5;\nconst MAX_BODY_BYTES = 1_000_000; // 1 MB - discovery documents are small JSON\n\nfunction stripBrackets(hostname: string): string {\n return hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname;\n}\n\n/** True for the literal hostname `localhost` or an IP literal in the loopback range. */\nfunction isLoopbackHost(hostname: string): boolean {\n const host = stripBrackets(hostname).toLowerCase();\n if (host === 'localhost') return true;\n if (isIP(host)) {\n try {\n return ipaddr.process(host).range() === 'loopback';\n } catch {\n return false;\n }\n }\n return false;\n}\n\n/**\n * True if `rawUrl`'s host is loopback, used to decide `allowLoopback` grants\n * from the URL the caller configured, not remote-supplied data. Fails closed on an unparseable URL.\n */\nexport function isLoopbackUrl(rawUrl: string): boolean {\n try {\n return isLoopbackHost(new URL(rawUrl).hostname);\n } catch {\n return false;\n }\n}\n\n/** True when the address is anything other than ordinary public unicast space. */\nfunction isBlockedAddress(address: string): boolean {\n try {\n // ipaddr.process() normalizes IPv4-mapped IPv6 (::ffff:a.b.c.d) to IPv4 first.\n return ipaddr.process(address).range() !== 'unicast';\n } catch {\n return true; // unparseable - fail closed\n }\n}\n\n/**\n * Validates scheme and, for literal-IP hosts, address range. `allowLoopback`\n * reflects trust in the calling server, never in `rawUrl` itself.\n */\nfunction assertSafeUrl(rawUrl: string, context: string, allowLoopback: boolean): URL {\n let url: URL;\n try {\n url = new URL(rawUrl);\n } catch {\n throw new DiscoveryFetchError(`Refusing to fetch ${context}: invalid URL`);\n }\n\n if (url.protocol !== 'https:' && url.protocol !== 'http:') {\n throw new DiscoveryFetchError(`Refusing to fetch ${context}: unsupported scheme`);\n }\n\n const host = stripBrackets(url.hostname);\n const trustedLoopback = allowLoopback && isLoopbackHost(host);\n if (trustedLoopback) return url; // this call's own grant covers it, regardless of scheme\n\n if (url.protocol === 'http:') {\n throw new DiscoveryFetchError(`Refusing to fetch ${context}: http:// is only allowed for a trusted loopback origin`);\n }\n\n if (isIP(host) && isBlockedAddress(host)) {\n throw new DiscoveryFetchError(`Refusing to fetch ${context}: address is not publicly routable`);\n }\n\n return url;\n}\n\n/**\n * Resolves the hostname and rejects it if any address is private/reserved.\n * Does not close the DNS-rebinding TOCTOU race against `fetch`'s own resolution a moment later.\n */\nasync function assertResolvesToSafeAddress(url: URL, context: string, allowLoopback: boolean): Promise<void> {\n const host = stripBrackets(url.hostname);\n if (isIP(host)) return; // literal IP already fully checked in assertSafeUrl\n if (allowLoopback && isLoopbackHost(host)) return; // literal \"localhost\" under a trusted-loopback grant\n\n let addresses: string[];\n try {\n const records = await dns.lookup(host, { all: true, verbatim: true });\n addresses = records.map((record) => record.address);\n } catch {\n throw new DiscoveryFetchError(`Refusing to fetch ${context}: host could not be resolved`);\n }\n\n if (addresses.length === 0 || addresses.some((address) => isBlockedAddress(address))) {\n throw new DiscoveryFetchError(`Refusing to fetch ${context}: host resolves to an address that is not publicly routable`);\n }\n}\n\nasync function readLimited(response: Response, context: string, maxBytes: number): Promise<string> {\n const contentLength = response.headers.get('content-length');\n if (contentLength && Number(contentLength) > maxBytes) {\n throw new DiscoveryFetchError(`Refusing to read ${context}: response too large`);\n }\n\n const reader = response.body?.getReader();\n if (!reader) {\n const text = await response.text();\n if (Buffer.byteLength(text, 'utf8') > maxBytes) {\n throw new DiscoveryFetchError(`Refusing to read ${context}: response too large`);\n }\n return text;\n }\n\n const chunks: Uint8Array[] = [];\n let total = 0;\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (!value) continue;\n total += value.byteLength;\n if (total > maxBytes) {\n throw new DiscoveryFetchError(`Refusing to read ${context}: response too large`);\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n\n return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk))).toString('utf8');\n}\n\nasync function fetchOnce(url: URL, init: RequestInit, context: string, allowLoopback: boolean, timeoutMs: number): Promise<Response> {\n await assertResolvesToSafeAddress(url, context, allowLoopback);\n\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), timeoutMs);\n try {\n return await fetch(url, { ...init, redirect: 'manual', signal: controller.signal });\n } catch {\n // Never surface the underlying error (ECONNREFUSED host/port, DNS detail, etc.)\n throw new DiscoveryFetchError(`Failed to fetch ${context}`);\n } finally {\n clearTimeout(timeout);\n }\n}\n\nexport interface DiscoveryFetchOptions {\n /**\n * Loopback trust grant for this fetch, computed from the server the caller\n * is actually talking to - never from the URL being fetched. Defaults to `false`.\n */\n allowLoopback?: boolean;\n /**\n * Per-request connect/read timeout in ms. Defaults to `DEFAULT_TIMEOUT_MS`;\n * overridable so tests can bound slow-failure cases.\n */\n timeoutMs?: number;\n}\n\n/**\n * Fetches an OAuth-discovery URL with SSRF mitigations applied to the\n * initial URL and every redirect hop; redirects are validated, not auto-followed.\n *\n * @param rawUrl - URL to fetch; may be remote-server-supplied (the threat this guards against).\n * @param init - Standard fetch options; `redirect` is always forced to `'manual'`.\n * @param context - Short label used only in error messages, never echoing the URL.\n * @param options - See `DiscoveryFetchOptions`.\n */\nexport async function discoveryFetch(rawUrl: string, init: RequestInit = {}, context = 'discovery URL', options: DiscoveryFetchOptions = {}): Promise<Response> {\n const { allowLoopback = false, timeoutMs = DEFAULT_TIMEOUT_MS } = options;\n\n let url = assertSafeUrl(rawUrl, context, allowLoopback);\n let response = await fetchOnce(url, init, context, allowLoopback, timeoutMs);\n\n let redirectsLeft = MAX_REDIRECTS;\n while (response.status >= 300 && response.status < 400) {\n const location = response.headers.get('location');\n if (!location) break;\n if (redirectsLeft <= 0) {\n throw new DiscoveryFetchError(`Refusing to fetch ${context}: too many redirects`);\n }\n redirectsLeft -= 1;\n\n let nextUrl: URL;\n try {\n nextUrl = new URL(location, url);\n } catch {\n throw new DiscoveryFetchError(`Refusing to fetch ${context}: invalid redirect target`);\n }\n url = assertSafeUrl(nextUrl.toString(), context, allowLoopback);\n response = await fetchOnce(url, init, context, allowLoopback, timeoutMs);\n }\n\n return response;\n}\n\n/**\n * Parse a `discoveryFetch` response body as JSON, enforcing `MAX_BODY_BYTES`\n * while reading (not after buffering the whole thing).\n */\nexport async function readDiscoveryJson<T>(response: Response, context: string): Promise<T> {\n const text = await readLimited(response, context, MAX_BODY_BYTES);\n try {\n return JSON.parse(text) as T;\n } catch {\n throw new DiscoveryFetchError(`Refusing to parse ${context}: invalid JSON`);\n }\n}\n"],"names":["dns","isIP","ipaddr","DiscoveryFetchError","Error","message","name","DEFAULT_TIMEOUT_MS","MAX_REDIRECTS","MAX_BODY_BYTES","stripBrackets","hostname","startsWith","endsWith","slice","isLoopbackHost","host","toLowerCase","process","range","isLoopbackUrl","rawUrl","URL","isBlockedAddress","address","assertSafeUrl","context","allowLoopback","url","protocol","trustedLoopback","assertResolvesToSafeAddress","addresses","records","lookup","all","verbatim","map","record","length","some","readLimited","response","maxBytes","contentLength","headers","get","Number","reader","body","getReader","text","Buffer","byteLength","chunks","total","done","value","read","push","releaseLock","concat","chunk","from","toString","fetchOnce","init","timeoutMs","controller","AbortController","timeout","setTimeout","abort","fetch","redirect","signal","clearTimeout","discoveryFetch","options","redirectsLeft","status","location","nextUrl","readDiscoveryJson","JSON","parse"],"mappings":"AAAA;;;CAGC,GACD,OAAOA,SAAS,oBAAoB;AACpC,SAASC,IAAI,QAAQ,WAAW;AAChC,OAAOC,YAAY,YAAY;AAE/B,OAAO,MAAMC,4BAA4BC;IACvC,YAAYC,OAAe,CAAE;QAC3B,KAAK,CAACA;QACN,IAAI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fetch.ts"],"sourcesContent":["/**\n * Hardened fetch for OAuth discovery URLs, which the remote MCP server\n * controls (SSRF mitigation). See ARCHITECTURE.md's \"SSRF mitigation\" section for the threat model.\n */\nimport dns from 'node:dns';\nimport http from 'node:http';\nimport https from 'node:https';\nimport { isIP, type LookupFunction } from 'node:net';\nimport ipaddr from 'ipaddr.js';\n\nexport class DiscoveryFetchError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'DiscoveryFetchError';\n }\n}\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst MAX_REDIRECTS = 5;\nconst MAX_BODY_BYTES = 1_000_000; // 1 MB - discovery documents are small JSON\n\ntype LookupRecord = { address: string; family: number };\n/** DNS implementation, injectable for deterministic tests. Same contract as `dns.lookup` with `{ all: true, verbatim: true }`. */\ntype Lookup = (hostname: string, options: { all: true; verbatim: true }, callback: (error: NodeJS.ErrnoException | null, addresses: LookupRecord[]) => void) => void;\n\nfunction stripBrackets(hostname: string): string {\n return hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname;\n}\n\n/** True for the literal hostname `localhost` or an IP literal in the loopback range. */\nfunction isLoopbackHost(hostname: string): boolean {\n const host = stripBrackets(hostname).toLowerCase();\n if (host === 'localhost') return true;\n if (isIP(host)) {\n try {\n return ipaddr.process(host).range() === 'loopback';\n } catch {\n return false;\n }\n }\n return false;\n}\n\n/**\n * True if `rawUrl`'s host is loopback, used to decide `allowLoopback` grants\n * from the URL the caller configured, not remote-supplied data. Fails closed on an unparseable URL.\n */\nexport function isLoopbackUrl(rawUrl: string): boolean {\n try {\n return isLoopbackHost(new URL(rawUrl).hostname);\n } catch {\n return false;\n }\n}\n\n/** True when the address is anything other than ordinary public unicast space. */\nfunction isBlockedAddress(address: string): boolean {\n try {\n // ipaddr.process() normalizes IPv4-mapped IPv6 (::ffff:a.b.c.d) to IPv4 first.\n return ipaddr.process(address).range() !== 'unicast';\n } catch {\n return true; // unparseable - fail closed\n }\n}\n\nfunction isLoopbackAddress(address: string): boolean {\n try {\n return ipaddr.process(address).range() === 'loopback';\n } catch {\n return false;\n }\n}\n\n/**\n * Validates scheme and, for literal-IP hosts, address range. `allowLoopback`\n * reflects trust in the calling server, never in `rawUrl` itself.\n */\nfunction assertSafeUrl(rawUrl: string, context: string, allowLoopback: boolean): URL {\n let url: URL;\n try {\n url = new URL(rawUrl);\n } catch {\n throw new DiscoveryFetchError(`Refusing to fetch ${context}: invalid URL`);\n }\n\n if (url.protocol !== 'https:' && url.protocol !== 'http:') {\n throw new DiscoveryFetchError(`Refusing to fetch ${context}: unsupported scheme`);\n }\n\n const host = stripBrackets(url.hostname);\n const trustedLoopback = allowLoopback && isLoopbackHost(host);\n if (trustedLoopback) return url; // this call's own grant covers it, regardless of scheme\n\n if (url.protocol === 'http:') {\n throw new DiscoveryFetchError(`Refusing to fetch ${context}: http:// is only allowed for a trusted loopback origin`);\n }\n\n if (isIP(host) && isBlockedAddress(host)) {\n throw new DiscoveryFetchError(`Refusing to fetch ${context}: address is not publicly routable`);\n }\n\n return url;\n}\n\nfunction lookupAll(hostname: string, lookup: Lookup, timeoutMs: number): Promise<LookupRecord[]> {\n return new Promise((resolve, reject) => {\n let settled = false;\n const deadline = setTimeout(() => {\n if (!settled) {\n settled = true;\n reject(new Error('DNS resolution timed out'));\n }\n }, timeoutMs);\n try {\n lookup(hostname, { all: true, verbatim: true }, (error, addresses) => {\n if (settled) return;\n settled = true;\n clearTimeout(deadline);\n if (error || addresses.length === 0) reject(new Error('DNS resolution failed'));\n else resolve(addresses);\n });\n } catch {\n if (!settled) {\n settled = true;\n clearTimeout(deadline);\n reject(new Error('DNS resolution failed'));\n }\n }\n });\n}\n\n/**\n * Resolves the hostname once, rejects it unless every returned address is\n * acceptable, and returns the validated set. The set is pinned into the\n * request itself (see `requestOnce`), which is what closes the DNS-rebinding\n * TOCTOU: the transport can only dial addresses that were already validated,\n * and it never resolves the hostname a second time.\n */\nasync function resolveSafeAddresses(url: URL, context: string, allowLoopback: boolean, lookup: Lookup, timeoutMs: number): Promise<LookupRecord[]> {\n const host = stripBrackets(url.hostname);\n if (isIP(host)) return [{ address: host, family: host.includes(':') ? 6 : 4 }]; // literal IP already fully checked in assertSafeUrl\n\n // Literal `localhost` under a trusted-loopback grant: still resolved, and the\n // answers must be loopback - the grant covers loopback, not \"wherever\n // localhost happens to point\".\n const loopbackGrant = allowLoopback && isLoopbackHost(host);\n\n let addresses: LookupRecord[];\n try {\n addresses = await lookupAll(host, lookup, timeoutMs);\n } catch {\n throw new DiscoveryFetchError(`Refusing to fetch ${context}: host could not be resolved`);\n }\n\n if (loopbackGrant) {\n if (!addresses.every((record) => isLoopbackAddress(record.address))) {\n throw new DiscoveryFetchError(`Refusing to fetch ${context}: host does not resolve to a loopback address`);\n }\n } else if (addresses.some((record) => isBlockedAddress(record.address))) {\n throw new DiscoveryFetchError(`Refusing to fetch ${context}: host resolves to an address that is not publicly routable`);\n }\n\n return addresses;\n}\n\n/**\n * A `net` lookup that can only ever answer with `addresses` - the set already\n * validated for this URL. The request is built against the original URL (so\n * SNI and certificate verification still see the hostname), but the\n * connection can only land on a validated address.\n */\nfunction pinnedLookup(addresses: LookupRecord[]): LookupFunction {\n return (_hostname, options, callback) => {\n if (typeof options === 'object' && options.all === true) {\n callback(null, addresses);\n return;\n }\n const first = addresses[0];\n if (!first) {\n callback(Object.assign(new Error('no validated address'), { code: 'ENOTFOUND' }) as NodeJS.ErrnoException, '', 0);\n return;\n }\n callback(null, first.address, first.family);\n };\n}\n\nfunction toRequestHeaders(init: RequestInit): Record<string, string> {\n const headers = new Headers(init.headers);\n const out: Record<string, string> = {};\n for (const [name, value] of headers) out[name] = value;\n return out;\n}\n\nasync function toRequestBody(body: RequestInit['body']): Promise<Buffer | undefined> {\n if (body === undefined || body === null) return undefined;\n if (typeof body === 'string') return Buffer.from(body);\n if (body instanceof URLSearchParams) return Buffer.from(body.toString());\n if (body instanceof Blob) return Buffer.from(await body.arrayBuffer());\n if (body instanceof ArrayBuffer) return Buffer.from(body);\n if (ArrayBuffer.isView(body)) return Buffer.from(body.buffer, body.byteOffset, body.byteLength);\n if (typeof ReadableStream !== 'undefined' && body instanceof ReadableStream) {\n const reader = body.getReader();\n const chunks: Uint8Array[] = [];\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (value) chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk)));\n }\n throw new Error('unsupported request body');\n}\n\nfunction toResponse(status: number, statusText: string, headers: http.IncomingHttpHeaders, body: Buffer): Response {\n const responseHeaders = new Headers();\n for (const [name, value] of Object.entries(headers)) {\n if (value === undefined) continue;\n if (Array.isArray(value)) {\n for (const entry of value) responseHeaders.append(name, entry);\n } else {\n responseHeaders.append(name, value);\n }\n }\n // The fetch spec gives these statuses a null body, and the Response\n // constructor rejects a body for them.\n const nullBody = status === 204 || status === 205 || status === 304;\n return new Response(nullBody ? null : body, { status, statusText, headers: responseHeaders });\n}\n\nasync function requestOnce(url: URL, init: RequestInit, context: string, addresses: LookupRecord[], timeoutMs: number): Promise<Response> {\n let body: Buffer | undefined;\n try {\n body = await toRequestBody(init.body);\n } catch {\n throw new DiscoveryFetchError(`Failed to fetch ${context}`);\n }\n\n const transport = url.protocol === 'https:' ? https : http;\n const options: http.RequestOptions = { method: (init.method ?? 'GET').toUpperCase(), headers: toRequestHeaders(init), agent: false, lookup: pinnedLookup(addresses) };\n\n return new Promise<Response>((resolve, reject) => {\n let settled = false;\n let req: http.ClientRequest | undefined;\n let res: http.IncomingMessage | undefined;\n const fail = (message: string): void => {\n if (!settled) {\n settled = true;\n clearTimeout(deadline);\n reject(new DiscoveryFetchError(message));\n }\n };\n const deadline = setTimeout(() => {\n res?.destroy();\n req?.destroy();\n fail(`Failed to fetch ${context}`);\n }, timeoutMs);\n\n try {\n req = transport.request(url, options, (response) => {\n res = response;\n const status = response.statusCode;\n const statusText = response.statusMessage ?? '';\n if (status === undefined || status < 200 || status > 599) {\n response.destroy();\n fail(`Failed to fetch ${context}`);\n return;\n }\n const chunks: Buffer[] = [];\n let total = 0;\n response.on('data', (chunk: Buffer) => {\n total += chunk.length;\n if (total > MAX_BODY_BYTES) {\n response.destroy();\n fail(`Refusing to read ${context}: response too large`);\n return;\n }\n chunks.push(chunk);\n });\n response.once('error', () => fail(`Failed to fetch ${context}`));\n response.once('end', () => {\n if (settled) return;\n settled = true;\n clearTimeout(deadline);\n resolve(toResponse(status, statusText, response.headers, Buffer.concat(chunks)));\n });\n });\n } catch {\n fail(`Failed to fetch ${context}`);\n return;\n }\n\n req.once('error', () => fail(`Failed to fetch ${context}`));\n req.end(body);\n });\n}\n\nasync function fetchOnce(url: URL, init: RequestInit, context: string, allowLoopback: boolean, timeoutMs: number, lookup: Lookup): Promise<Response> {\n const addresses = await resolveSafeAddresses(url, context, allowLoopback, lookup, timeoutMs);\n return requestOnce(url, init, context, addresses, timeoutMs);\n}\n\nexport interface DiscoveryFetchOptions {\n /**\n * Loopback trust grant for this fetch, computed from the server the caller\n * is actually talking to - never from the URL being fetched. Defaults to `false`.\n */\n allowLoopback?: boolean;\n /**\n * Per-hop timeout in ms, applied to both the DNS resolution and the request.\n * Defaults to `DEFAULT_TIMEOUT_MS`; overridable so tests can bound slow-failure cases.\n */\n timeoutMs?: number;\n /**\n * DNS implementation used for the pre-request resolution, injectable for\n * deterministic tests. Defaults to `dns.lookup`.\n */\n lookup?: Lookup;\n}\n\n/**\n * Fetches an OAuth-discovery URL with SSRF mitigations applied to the\n * initial URL and every redirect hop; redirects are validated, not auto-followed.\n *\n * The hostname is resolved once, every returned address is validated, and the\n * validated set is pinned into the request through a custom `lookup`, so the\n * request cannot resolve the hostname a second time and cannot be steered to\n * a different address by a DNS-rebinding answer.\n *\n * @param rawUrl - URL to fetch; may be remote-server-supplied (the threat this guards against).\n * @param init - Standard fetch options; `redirect` is always forced to `'manual'`.\n * @param context - Short label used only in error messages, never echoing the URL.\n * @param options - See `DiscoveryFetchOptions`.\n */\nexport async function discoveryFetch(rawUrl: string, init: RequestInit = {}, context = 'discovery URL', options: DiscoveryFetchOptions = {}): Promise<Response> {\n const { allowLoopback = false, timeoutMs = DEFAULT_TIMEOUT_MS, lookup = dns.lookup as unknown as Lookup } = options;\n\n let url = assertSafeUrl(rawUrl, context, allowLoopback);\n let response = await fetchOnce(url, init, context, allowLoopback, timeoutMs, lookup);\n\n let redirectsLeft = MAX_REDIRECTS;\n while (response.status >= 300 && response.status < 400) {\n const location = response.headers.get('location');\n if (!location) break;\n if (redirectsLeft <= 0) {\n throw new DiscoveryFetchError(`Refusing to fetch ${context}: too many redirects`);\n }\n redirectsLeft -= 1;\n\n let nextUrl: URL;\n try {\n nextUrl = new URL(location, url);\n } catch {\n throw new DiscoveryFetchError(`Refusing to fetch ${context}: invalid redirect target`);\n }\n url = assertSafeUrl(nextUrl.toString(), context, allowLoopback);\n response = await fetchOnce(url, init, context, allowLoopback, timeoutMs, lookup);\n }\n\n return response;\n}\n\n/**\n * Parse a `discoveryFetch` response body as JSON, enforcing `MAX_BODY_BYTES`\n * while reading (not after buffering the whole thing).\n */\nexport async function readDiscoveryJson<T>(response: Response, context: string): Promise<T> {\n const text = await readLimited(response, context, MAX_BODY_BYTES);\n try {\n return JSON.parse(text) as T;\n } catch {\n throw new DiscoveryFetchError(`Refusing to parse ${context}: invalid JSON`);\n }\n}\n\nasync function readLimited(response: Response, context: string, maxBytes: number): Promise<string> {\n const contentLength = response.headers.get('content-length');\n if (contentLength && Number(contentLength) > maxBytes) {\n throw new DiscoveryFetchError(`Refusing to read ${context}: response too large`);\n }\n\n const reader = response.body?.getReader();\n if (!reader) {\n const text = await response.text();\n if (Buffer.byteLength(text, 'utf8') > maxBytes) {\n throw new DiscoveryFetchError(`Refusing to read ${context}: response too large`);\n }\n return text;\n }\n\n const chunks: Uint8Array[] = [];\n let total = 0;\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (!value) continue;\n total += value.byteLength;\n if (total > maxBytes) {\n throw new DiscoveryFetchError(`Refusing to read ${context}: response too large`);\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n\n return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk))).toString('utf8');\n}\n"],"names":["dns","http","https","isIP","ipaddr","DiscoveryFetchError","Error","message","name","DEFAULT_TIMEOUT_MS","MAX_REDIRECTS","MAX_BODY_BYTES","stripBrackets","hostname","startsWith","endsWith","slice","isLoopbackHost","host","toLowerCase","process","range","isLoopbackUrl","rawUrl","URL","isBlockedAddress","address","isLoopbackAddress","assertSafeUrl","context","allowLoopback","url","protocol","trustedLoopback","lookupAll","lookup","timeoutMs","Promise","resolve","reject","settled","deadline","setTimeout","all","verbatim","error","addresses","clearTimeout","length","resolveSafeAddresses","family","includes","loopbackGrant","every","record","some","pinnedLookup","_hostname","options","callback","first","Object","assign","code","toRequestHeaders","init","headers","Headers","out","value","toRequestBody","body","undefined","Buffer","from","URLSearchParams","toString","Blob","arrayBuffer","ArrayBuffer","isView","buffer","byteOffset","byteLength","ReadableStream","reader","getReader","chunks","done","read","push","releaseLock","concat","map","chunk","toResponse","status","statusText","responseHeaders","entries","Array","isArray","entry","append","nullBody","Response","requestOnce","transport","method","toUpperCase","agent","req","res","fail","destroy","request","response","statusCode","statusMessage","total","on","once","end","fetchOnce","discoveryFetch","redirectsLeft","location","get","nextUrl","readDiscoveryJson","text","readLimited","JSON","parse","maxBytes","contentLength","Number"],"mappings":"AAAA;;;CAGC,GACD,OAAOA,SAAS,WAAW;AAC3B,OAAOC,UAAU,YAAY;AAC7B,OAAOC,WAAW,aAAa;AAC/B,SAASC,IAAI,QAA6B,WAAW;AACrD,OAAOC,YAAY,YAAY;AAE/B,OAAO,MAAMC,4BAA4BC;IACvC,YAAYC,OAAe,CAAE;QAC3B,KAAK,CAACA;QACN,IAAI,CAACC,IAAI,GAAG;IACd;AACF;AAEA,MAAMC,qBAAqB;AAC3B,MAAMC,gBAAgB;AACtB,MAAMC,iBAAiB,SA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OD,iBAAiBD,UAAU;QACrD,MAAM,IAAIjI,oBAAoB,CAAC,iBAAiB,EAAEwB,QAAQ,oBAAoB,CAAC;IACjF;IAEA,MAAMwD,UAAS+B,iBAAAA,SAAS7C,IAAI,cAAb6C,qCAAAA,eAAe9B,SAAS;IACvC,IAAI,CAACD,QAAQ;QACX,MAAM6C,OAAO,MAAMd,SAASc,IAAI;QAChC,IAAIzD,OAAOU,UAAU,CAAC+C,MAAM,UAAUI,UAAU;YAC9C,MAAM,IAAIjI,oBAAoB,CAAC,iBAAiB,EAAEwB,QAAQ,oBAAoB,CAAC;QACjF;QACA,OAAOqG;IACT;IAEA,MAAM3C,SAAuB,EAAE;IAC/B,IAAIgC,QAAQ;IACZ,IAAI;QACF,OAAS;YACP,MAAM,EAAE/B,IAAI,EAAEnB,KAAK,EAAE,GAAG,MAAMgB,OAAOI,IAAI;YACzC,IAAID,MAAM;YACV,IAAI,CAACnB,OAAO;YACZkD,SAASlD,MAAMc,UAAU;YACzB,IAAIoC,QAAQe,UAAU;gBACpB,MAAM,IAAIjI,oBAAoB,CAAC,iBAAiB,EAAEwB,QAAQ,oBAAoB,CAAC;YACjF;YACA0D,OAAOG,IAAI,CAACrB;QACd;IACF,SAAU;QACRgB,OAAOM,WAAW;IACpB;IAEA,OAAOlB,OAAOmB,MAAM,CAACL,OAAOM,GAAG,CAAC,CAACC,QAAUrB,OAAOC,IAAI,CAACoB,SAASlB,QAAQ,CAAC;AAC3E"}
@@ -29,12 +29,18 @@ export declare class InteractiveOAuthFlow {
29
29
  * 'https://example.com/oauth/token',
30
30
  * 'client-id',
31
31
  * 'client-secret',
32
- * { port, scopes: ['read', 'write'] }
32
+ * { port, issuer: 'https://example.com', resource: 'https://example.com/mcp', scopes: ['read', 'write'] }
33
33
  * );
34
34
  */
35
35
  performAuthFlow(authorizationEndpoint: string, tokenEndpoint: string, clientId: string, clientSecret: string, options: OAuthFlowOptions): Promise<TokenSet>;
36
+ /**
37
+ * Rejects an authorization response that was not minted by the issuer
38
+ * discovered before the flow started (RFC 9207 authorization-server mix-up).
39
+ */
40
+ private assertResponseIssuer;
36
41
  /**
37
42
  * Exchanges an authorization code for access and refresh tokens.
43
+ * @param resource - Canonical resource server URI, audience-binding the token (RFC 8707).
38
44
  * @param allowLoopback - Loopback trust grant computed by the caller from the server it is actually talking to, never from `tokenEndpoint`.
39
45
  * @param codeVerifier - Optional PKCE code verifier (RFC 7636).
40
46
  */
@@ -45,11 +51,12 @@ export declare class InteractiveOAuthFlow {
45
51
  * @param refreshToken - Refresh token from a previous token set.
46
52
  * @param clientId - OAuth client ID.
47
53
  * @param clientSecret - OAuth client secret.
54
+ * @param resource - Canonical resource server URI, audience-binding the token (RFC 8707).
48
55
  * @param allowLoopback - Loopback trust grant computed by the caller from the server it is actually talking to, never from `tokenEndpoint`. Defaults to `false`.
49
56
  * @returns New token set with a refreshed access token.
50
57
  * @throws Error if refresh fails.
51
58
  */
52
- refreshTokens(tokenEndpoint: string, refreshToken: string, clientId: string, clientSecret: string, allowLoopback?: boolean): Promise<TokenSet>;
59
+ refreshTokens(tokenEndpoint: string, refreshToken: string, clientId: string, clientSecret: string, resource: string, allowLoopback?: boolean): Promise<TokenSet>;
53
60
  /**
54
61
  * Open browser to authorization URL
55
62
  * Uses platform-specific command to open default browser