@earendil-works/pi-mcp 1.5.0 → 1.5.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 (74) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +59 -3
  3. package/dist/config.d.ts +117 -0
  4. package/dist/config.d.ts.map +1 -0
  5. package/dist/config.js +153 -0
  6. package/dist/config.js.map +1 -0
  7. package/dist/index.d.ts +5 -0
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +5 -0
  10. package/dist/index.js.map +1 -1
  11. package/dist/input-schema.d.ts +7 -0
  12. package/dist/input-schema.d.ts.map +1 -0
  13. package/dist/input-schema.js +13 -0
  14. package/dist/input-schema.js.map +1 -0
  15. package/dist/naming.d.ts +18 -0
  16. package/dist/naming.d.ts.map +1 -0
  17. package/dist/naming.js +29 -0
  18. package/dist/naming.js.map +1 -0
  19. package/dist/oauth/auth-provider.d.ts +52 -0
  20. package/dist/oauth/auth-provider.d.ts.map +1 -0
  21. package/dist/oauth/auth-provider.js +97 -0
  22. package/dist/oauth/auth-provider.js.map +1 -0
  23. package/dist/oauth/callback.d.ts.map +1 -1
  24. package/dist/oauth/callback.js +5 -1
  25. package/dist/oauth/callback.js.map +1 -1
  26. package/dist/oauth/client-settings.d.ts +107 -0
  27. package/dist/oauth/client-settings.d.ts.map +1 -0
  28. package/dist/oauth/client-settings.js +114 -0
  29. package/dist/oauth/client-settings.js.map +1 -0
  30. package/dist/oauth/discovery.js +1 -1
  31. package/dist/oauth/discovery.js.map +1 -1
  32. package/dist/oauth/errors.d.ts +7 -0
  33. package/dist/oauth/errors.d.ts.map +1 -1
  34. package/dist/oauth/errors.js +10 -0
  35. package/dist/oauth/errors.js.map +1 -1
  36. package/dist/oauth/flow.d.ts +10 -0
  37. package/dist/oauth/flow.d.ts.map +1 -1
  38. package/dist/oauth/flow.js +31 -8
  39. package/dist/oauth/flow.js.map +1 -1
  40. package/dist/oauth/index.d.ts +5 -1
  41. package/dist/oauth/index.d.ts.map +1 -1
  42. package/dist/oauth/index.js +4 -1
  43. package/dist/oauth/index.js.map +1 -1
  44. package/dist/oauth/loopback.d.ts +51 -0
  45. package/dist/oauth/loopback.d.ts.map +1 -0
  46. package/dist/oauth/loopback.js +98 -0
  47. package/dist/oauth/loopback.js.map +1 -0
  48. package/dist/oauth/sign-in.d.ts +73 -0
  49. package/dist/oauth/sign-in.d.ts.map +1 -0
  50. package/dist/oauth/sign-in.js +182 -0
  51. package/dist/oauth/sign-in.js.map +1 -0
  52. package/dist/oauth/types.js +1 -1
  53. package/dist/oauth/types.js.map +1 -1
  54. package/dist/output-limit.d.ts +24 -0
  55. package/dist/output-limit.d.ts.map +1 -0
  56. package/dist/output-limit.js +58 -0
  57. package/dist/output-limit.js.map +1 -0
  58. package/dist/transports/lines.d.ts +34 -0
  59. package/dist/transports/lines.d.ts.map +1 -0
  60. package/dist/transports/lines.js +85 -0
  61. package/dist/transports/lines.js.map +1 -0
  62. package/dist/transports/pipe.d.ts +49 -0
  63. package/dist/transports/pipe.d.ts.map +1 -0
  64. package/dist/transports/pipe.js +96 -0
  65. package/dist/transports/pipe.js.map +1 -0
  66. package/dist/transports/stdio.d.ts +1 -4
  67. package/dist/transports/stdio.d.ts.map +1 -1
  68. package/dist/transports/stdio.js +20 -51
  69. package/dist/transports/stdio.js.map +1 -1
  70. package/dist/transports/streamable-http.d.ts.map +1 -1
  71. package/dist/transports/streamable-http.js +77 -12
  72. package/dist/transports/streamable-http.js.map +1 -1
  73. package/package.json +2 -2
  74. /package/{LICENSES → THIRD_PARTY_NOTICES}/modelcontextprotocol-typescript-sdk.txt +0 -0
@@ -22,4 +22,11 @@ export declare class OAuthRegistrationError extends Error {
22
22
  export declare class McpOAuthAuthorizationRequiredError extends Error {
23
23
  constructor();
24
24
  }
25
+ /**
26
+ * Thrown by `McpOAuthServerStore.withRefreshLock()` when another process holds the refresh lock for the
27
+ * whole wait. `startMcpSignIn()` then skips the refresh and goes to the browser step.
28
+ */
29
+ export declare class McpRefreshLockBusyError extends Error {
30
+ constructor();
31
+ }
25
32
  //# sourceMappingURL=errors.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/oauth/errors.ts"],"names":[],"mappings":"AAAA,qBAAa,UAAW,SAAQ,KAAK;IACpC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAEtC,YAAY,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,EAK3D;CACD;AAED,qBAAa,wBAAyB,SAAQ,KAAK;IAClD,wEAAwE;IACxE,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IACtC,2GAA2G;IAC3G,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAEtC,YAAY,QAAQ,EAAE,MAAM,GAAG,SAAS,EAAE,QAAQ,EAAE,MAAM,GAAG,SAAS,EAMrE;CACD;AAED,qBAAa,0BAA2B,SAAQ,KAAK;IACpD,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAE1B,YAAY,QAAQ,EAAE,MAAM,EAI3B;CACD;AAED,qBAAa,sBAAuB,SAAQ,KAAK;IAChD,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAEtB,YAAY,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAKvC;CACD;AAED,qBAAa,kCAAmC,SAAQ,KAAK;IAC5D,cAGC;CACD"}
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/oauth/errors.ts"],"names":[],"mappings":"AAAA,qBAAa,UAAW,SAAQ,KAAK;IACpC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAEtC,YAAY,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,EAK3D;CACD;AAED,qBAAa,wBAAyB,SAAQ,KAAK;IAClD,wEAAwE;IACxE,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IACtC,2GAA2G;IAC3G,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAEtC,YAAY,QAAQ,EAAE,MAAM,GAAG,SAAS,EAAE,QAAQ,EAAE,MAAM,GAAG,SAAS,EAMrE;CACD;AAED,qBAAa,0BAA2B,SAAQ,KAAK;IACpD,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAE1B,YAAY,QAAQ,EAAE,MAAM,EAI3B;CACD;AAED,qBAAa,sBAAuB,SAAQ,KAAK;IAChD,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAEtB,YAAY,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAKvC;CACD;AAED,qBAAa,kCAAmC,SAAQ,KAAK;IAC5D,cAGC;CACD;AAED;;;GAGG;AACH,qBAAa,uBAAwB,SAAQ,KAAK;IACjD,cAGC;CACD"}
@@ -45,4 +45,14 @@ export class McpOAuthAuthorizationRequiredError extends Error {
45
45
  this.name = "McpOAuthAuthorizationRequiredError";
46
46
  }
47
47
  }
48
+ /**
49
+ * Thrown by `McpOAuthServerStore.withRefreshLock()` when another process holds the refresh lock for the
50
+ * whole wait. `startMcpSignIn()` then skips the refresh and goes to the browser step.
51
+ */
52
+ export class McpRefreshLockBusyError extends Error {
53
+ constructor() {
54
+ super("Another process is refreshing the MCP server's tokens");
55
+ this.name = "McpRefreshLockBusyError";
56
+ }
57
+ }
48
58
  //# sourceMappingURL=errors.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/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AAY,MAAc,EAAE,IAAY;QACvC,KAAK,CAAC,wDAAwD,MAAM,KAAK,IAAI,EAAE,CAAC,CAAC;QACjF,IAAI,CAAC,IAAI,GAAG,wBAAwB,CAAC;QACrC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAClB,CAAC;CACD;AAED,MAAM,OAAO,kCAAmC,SAAQ,KAAK;IAC5D;QACC,KAAK,CAAC,mDAAmD,CAAC,CAAC;QAC3D,IAAI,CAAC,IAAI,GAAG,oCAAoC,CAAC;IAClD,CAAC;CACD","sourcesContent":["export class OAuthError extends Error {\n\treadonly code: string;\n\treadonly errorUri: string | undefined;\n\n\tconstructor(code: string, message: string, errorUri?: string) {\n\t\tsuper(message || code);\n\t\tthis.name = \"OAuthError\";\n\t\tthis.code = code;\n\t\tthis.errorUri = errorUri;\n\t}\n}\n\nexport class OAuthIssuerMismatchError extends Error {\n\t/** `undefined` when no authorization server metadata was discovered. */\n\treadonly expected: string | undefined;\n\t/** `undefined` when an authorization response lacks the `iss` parameter its server promised (RFC 9207). */\n\treadonly received: string | undefined;\n\n\tconstructor(expected: string | undefined, received: string | undefined) {\n\t\tconst format = (issuer: string | undefined) => (issuer === undefined ? \"none\" : JSON.stringify(issuer));\n\t\tsuper(`OAuth issuer mismatch: expected ${format(expected)}, received ${format(received)}`);\n\t\tthis.name = \"OAuthIssuerMismatchError\";\n\t\tthis.expected = expected;\n\t\tthis.received = received;\n\t}\n}\n\nexport class OAuthInsecureEndpointError extends Error {\n\treadonly endpoint: string;\n\n\tconstructor(endpoint: string) {\n\t\tsuper(`Refusing to send OAuth credentials to non-HTTPS endpoint ${endpoint}`);\n\t\tthis.name = \"OAuthInsecureEndpointError\";\n\t\tthis.endpoint = endpoint;\n\t}\n}\n\nexport class OAuthRegistrationError extends Error {\n\treadonly status: number;\n\treadonly body: string;\n\n\tconstructor(status: number, body: string) {\n\t\tsuper(`OAuth dynamic client registration failed with status ${status}: ${body}`);\n\t\tthis.name = \"OAuthRegistrationError\";\n\t\tthis.status = status;\n\t\tthis.body = body;\n\t}\n}\n\nexport class McpOAuthAuthorizationRequiredError extends Error {\n\tconstructor() {\n\t\tsuper(\"MCP OAuth authorization requires user interaction\");\n\t\tthis.name = \"McpOAuthAuthorizationRequiredError\";\n\t}\n}\n"]}
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/oauth/errors.ts"],"names":[],"mappings":"AAAA,MAAM,OAAO,UAAW,SAAQ,KAAK;IAC3B,IAAI,CAAS;IACb,QAAQ,CAAqB;IAEtC,YAAY,IAAY,EAAE,OAAe,EAAE,QAAiB;QAC3D,KAAK,CAAC,OAAO,IAAI,IAAI,CAAC,CAAC;QACvB,IAAI,CAAC,IAAI,GAAG,YAAY,CAAC;QACzB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC1B,CAAC;CACD;AAED,MAAM,OAAO,wBAAyB,SAAQ,KAAK;IAClD,wEAAwE;IAC/D,QAAQ,CAAqB;IACtC,2GAA2G;IAClG,QAAQ,CAAqB;IAEtC,YAAY,QAA4B,EAAE,QAA4B;QACrE,MAAM,MAAM,GAAG,CAAC,MAA0B,EAAE,EAAE,CAAC,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC;QACxG,KAAK,CAAC,mCAAmC,MAAM,CAAC,QAAQ,CAAC,cAAc,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;QAC3F,IAAI,CAAC,IAAI,GAAG,0BAA0B,CAAC;QACvC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC1B,CAAC;CACD;AAED,MAAM,OAAO,0BAA2B,SAAQ,KAAK;IAC3C,QAAQ,CAAS;IAE1B,YAAY,QAAgB;QAC3B,KAAK,CAAC,4DAA4D,QAAQ,EAAE,CAAC,CAAC;QAC9E,IAAI,CAAC,IAAI,GAAG,4BAA4B,CAAC;QACzC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC1B,CAAC;CACD;AAED,MAAM,OAAO,sBAAuB,SAAQ,KAAK;IACvC,MAAM,CAAS;IACf,IAAI,CAAS;IAEtB,YAAY,MAAc,EAAE,IAAY;QACvC,KAAK,CAAC,wDAAwD,MAAM,KAAK,IAAI,EAAE,CAAC,CAAC;QACjF,IAAI,CAAC,IAAI,GAAG,wBAAwB,CAAC;QACrC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAClB,CAAC;CACD;AAED,MAAM,OAAO,kCAAmC,SAAQ,KAAK;IAC5D;QACC,KAAK,CAAC,mDAAmD,CAAC,CAAC;QAC3D,IAAI,CAAC,IAAI,GAAG,oCAAoC,CAAC;IAClD,CAAC;CACD;AAED;;;GAGG;AACH,MAAM,OAAO,uBAAwB,SAAQ,KAAK;IACjD;QACC,KAAK,CAAC,uDAAuD,CAAC,CAAC;QAC/D,IAAI,CAAC,IAAI,GAAG,yBAAyB,CAAC;IACvC,CAAC;CACD","sourcesContent":["export class OAuthError extends Error {\n\treadonly code: string;\n\treadonly errorUri: string | undefined;\n\n\tconstructor(code: string, message: string, errorUri?: string) {\n\t\tsuper(message || code);\n\t\tthis.name = \"OAuthError\";\n\t\tthis.code = code;\n\t\tthis.errorUri = errorUri;\n\t}\n}\n\nexport class OAuthIssuerMismatchError extends Error {\n\t/** `undefined` when no authorization server metadata was discovered. */\n\treadonly expected: string | undefined;\n\t/** `undefined` when an authorization response lacks the `iss` parameter its server promised (RFC 9207). */\n\treadonly received: string | undefined;\n\n\tconstructor(expected: string | undefined, received: string | undefined) {\n\t\tconst format = (issuer: string | undefined) => (issuer === undefined ? \"none\" : JSON.stringify(issuer));\n\t\tsuper(`OAuth issuer mismatch: expected ${format(expected)}, received ${format(received)}`);\n\t\tthis.name = \"OAuthIssuerMismatchError\";\n\t\tthis.expected = expected;\n\t\tthis.received = received;\n\t}\n}\n\nexport class OAuthInsecureEndpointError extends Error {\n\treadonly endpoint: string;\n\n\tconstructor(endpoint: string) {\n\t\tsuper(`Refusing to send OAuth credentials to non-HTTPS endpoint ${endpoint}`);\n\t\tthis.name = \"OAuthInsecureEndpointError\";\n\t\tthis.endpoint = endpoint;\n\t}\n}\n\nexport class OAuthRegistrationError extends Error {\n\treadonly status: number;\n\treadonly body: string;\n\n\tconstructor(status: number, body: string) {\n\t\tsuper(`OAuth dynamic client registration failed with status ${status}: ${body}`);\n\t\tthis.name = \"OAuthRegistrationError\";\n\t\tthis.status = status;\n\t\tthis.body = body;\n\t}\n}\n\nexport class McpOAuthAuthorizationRequiredError extends Error {\n\tconstructor() {\n\t\tsuper(\"MCP OAuth authorization requires user interaction\");\n\t\tthis.name = \"McpOAuthAuthorizationRequiredError\";\n\t}\n}\n\n/**\n * Thrown by `McpOAuthServerStore.withRefreshLock()` when another process holds the refresh lock for the\n * whole wait. `startMcpSignIn()` then skips the refresh and goes to the browser step.\n */\nexport class McpRefreshLockBusyError extends Error {\n\tconstructor() {\n\t\tsuper(\"Another process is refreshing the MCP server's tokens\");\n\t\tthis.name = \"McpRefreshLockBusyError\";\n\t}\n}\n"]}
@@ -49,6 +49,16 @@ export interface OAuthFlowOptions {
49
49
  * server asks for scopes the current grant lacks (a refresh keeps the old scope).
50
50
  */
51
51
  skipRefresh?: boolean;
52
+ /**
53
+ * Only refresh the stored tokens: return `REDIRECT` instead of registering a client or preparing an
54
+ * authorization request, so a pending authorization (its `state` and PKCE verifier) stays usable.
55
+ */
56
+ refreshOnly?: boolean;
57
+ /**
58
+ * With `authorizationCode`: the redirect URI the authorization request used. The exchange fails before
59
+ * sending the code when the flow would send another one (RFC 6749 section 4.1.3 requires the same).
60
+ */
61
+ authorizationRedirectUrl?: string;
52
62
  }
53
63
  export type OAuthFlowResult = "AUTHORIZED" | "REDIRECT";
54
64
  export interface TokenRequestOptions {
@@ -1 +1 @@
1
- {"version":3,"file":"flow.d.ts","sourceRoot":"","sources":["../../src/oauth/flow.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,YAAY,EAAE,QAAQ,EAAuB,MAAM,qBAAqB,CAAC;AAevF,OAAO,EACN,KAAK,2BAA2B,EAGhC,KAAK,0BAA0B,EAC/B,KAAK,2BAA2B,EAChC,KAAK,mBAAmB,EACxB,KAAK,mBAAmB,EACxB,KAAK,WAAW,EAGhB,MAAM,YAAY,CAAC;AAEpB,MAAM,MAAM,uBAAuB,GAAG,CACrC,OAAO,EAAE,OAAO,EAChB,MAAM,EAAE,eAAe,EACvB,GAAG,EAAE,MAAM,GAAG,GAAG,EACjB,QAAQ,CAAC,EAAE,2BAA2B,KAClC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;AAE1B,oGAAoG;AACpG,MAAM,WAAW,2BAA2B;IAC3C,GAAG,EAAE,MAAM,CAAC;IACZ,WAAW,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,mBAAmB;IACnC,QAAQ,CAAC,WAAW,EAAE,MAAM,GAAG,GAAG,CAAC;IACnC,QAAQ,CAAC,cAAc,EAAE,mBAAmB,CAAC;IAC7C;;;;OAIG;IACH,sBAAsB,CAAC,CAAC,QAAQ,EAAE,2BAA2B,GAAG,SAAS,GAAG,2BAA2B,GAAG,SAAS,CAAC;IACpH,KAAK,CAAC,IAAI,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IACnC,iBAAiB,IAAI,2BAA2B,GAAG,SAAS,GAAG,OAAO,CAAC,2BAA2B,GAAG,SAAS,CAAC,CAAC;IAChH,qBAAqB,CAAC,CAAC,WAAW,EAAE,2BAA2B,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACvF,MAAM,IAAI,WAAW,GAAG,SAAS,GAAG,OAAO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,wBAAsB,cAAc,CACnC,sBAAsB,EAAE,MAAM,GAAG,GAAG,EACpC,OAAO,EAAE;IACR,QAAQ,CAAC,EAAE,2BAA2B,CAAC;IACvC,cAAc,EAAE,mBAAmB,CAAC;IACpC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,QAAQ,CAAC;IACjB,MAAM,CAAC,EAAE,WAAW,CAAC;CACrB,GACC,OAAO,CAAC,0BAA0B,CAAC,CAoBrC;AAED,wBAAsB,yBAAyB,CAC9C,sBAAsB,EAAE,MAAM,GAAG,GAAG,EACpC,OAAO,EAAE,mBAAmB,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,GAAG,GAAG,CAAA;CAAE,GAC9F,OAAO,CAAC,WAAW,CAAC,CAWtB;AAED,wBAAsB,oBAAoB,CACzC,sBAAsB,EAAE,MAAM,GAAG,GAAG,EACpC,OAAO,EAAE,mBAAmB,GAAG;IAAE,YAAY,EAAE,MAAM,CAAA;CAAE,GACrD,OAAO,CAAC,WAAW,CAAC,CAOtB;AAMD;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,EAAE,UAAU,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CAI3G;AAyID,wBAAsB,YAAY,CAAC,QAAQ,EAAE,mBAAmB,EAAE,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,eAAe,CAAC,CAwBrH;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,mBAAmB,GAAG,YAAY,CA8B9E"}
@@ -1,6 +1,6 @@
1
1
  /*
2
2
  * Adapted from modelcontextprotocol/typescript-sdk v1.29.0 src/client/auth.ts.
3
- * Copyright (c) 2024 Anthropic, PBC. Licensed under MIT; see LICENSES/.
3
+ * Copyright (c) 2024 Anthropic, PBC. Licensed under MIT; see THIRD_PARTY_NOTICES/.
4
4
  * Modified to remove SDK/Zod dependencies and use WebCrypto for PKCE.
5
5
  */
6
6
  import { isObject } from "../protocol/jsonrpc.js";
@@ -167,7 +167,7 @@ export function stepUpScope(granted, challenged) {
167
167
  const scopes = [granted, challenged].flatMap((scope) => scope?.split(/\s+/).filter(Boolean) ?? []);
168
168
  return [...new Set(scopes)].join(" ");
169
169
  }
170
- async function runFlow(provider, options) {
170
+ async function runFlow(provider, options, use = {}) {
171
171
  const metadataUrl = options.authorizationServerMetadataUrl && secureEndpoint(options.authorizationServerMetadataUrl);
172
172
  // With a configured metadata URL, discovery is not cached, so changing the URL applies at once.
173
173
  const cached = metadataUrl ? undefined : await provider.discoveryState?.();
@@ -200,16 +200,28 @@ async function runFlow(provider, options) {
200
200
  // `||`, not `??`: an empty scope (for example from `scopes_supported: []`) falls through to the next source.
201
201
  const scope = options.scope || discovered.resourceMetadata?.scopes_supported?.join(" ") || provider.clientMetadata.scope;
202
202
  const stored = await provider.clientInformation();
203
+ use.storedClientId = stored?.client_id;
203
204
  const clientDocument = stored ? undefined : provider.clientMetadataDocument?.(metadata);
204
205
  if (clientDocument) {
205
206
  const url = new URL(clientDocument.url);
206
207
  if (url.protocol !== "https:" || url.pathname === "/")
207
208
  throw new Error("Invalid OAuth client metadata URL");
208
209
  }
210
+ // The document's redirect URI may differ from the provider's, for example by a server-specific path.
211
+ const redirectUrl = clientDocument?.redirectUrl ?? String(provider.redirectUrl);
212
+ // Checked first: another redirect URI also explains a client that is missing for the exchange.
213
+ if (options.authorizationCode && options.authorizationRedirectUrl !== undefined) {
214
+ if (redirectUrl !== options.authorizationRedirectUrl) {
215
+ throw new Error(`The code exchange would use the redirect URI ${redirectUrl}, but the authorization request used ${options.authorizationRedirectUrl}`);
216
+ }
217
+ }
209
218
  let client = stored ?? (clientDocument && { client_id: clientDocument.url });
210
219
  if (!client) {
211
- if (options.authorizationCode)
212
- throw new Error("OAuth client information is missing during code exchange");
220
+ if (options.refreshOnly)
221
+ return "REDIRECT";
222
+ if (options.authorizationCode) {
223
+ throw new Error("OAuth client information is missing during code exchange: the authorization request's client was removed, or the client settings changed");
224
+ }
213
225
  if (!provider.saveClientInformation)
214
226
  throw new Error("OAuth client information cannot be persisted");
215
227
  client = await registerClient(discovered.authorizationServerUrl, {
@@ -221,8 +233,6 @@ async function runFlow(provider, options) {
221
233
  });
222
234
  await provider.saveClientInformation(client);
223
235
  }
224
- // The document's redirect URI may differ from the provider's, for example by a server-specific path.
225
- const redirectUrl = clientDocument?.redirectUrl ?? provider.redirectUrl;
226
236
  const tokenOptions = {
227
237
  metadata,
228
238
  clientInformation: client,
@@ -268,6 +278,8 @@ async function runFlow(provider, options) {
268
278
  throw error;
269
279
  }
270
280
  }
281
+ if (options.refreshOnly)
282
+ return "REDIRECT";
271
283
  const state = await provider.state?.();
272
284
  const authorization = await startAuthorization(discovered.authorizationServerUrl, {
273
285
  metadata,
@@ -282,12 +294,23 @@ async function runFlow(provider, options) {
282
294
  return "REDIRECT";
283
295
  }
284
296
  export async function authorizeMcp(provider, options) {
297
+ const use = {};
285
298
  try {
286
- return await runFlow(provider, options);
299
+ return await runFlow(provider, options, use);
287
300
  }
288
301
  catch (error) {
289
302
  if (error instanceof OAuthError && ["invalid_client", "unauthorized_client"].includes(error.code)) {
290
- await provider.invalidateCredentials?.("all");
303
+ // A refresh keeps a pending authorization's `state` and verifier: they are the user's sign-in. A client
304
+ // stored meanwhile (by a sign-in that completed) is not the one the server rejected, so it stays.
305
+ if (options.refreshOnly) {
306
+ if ((await provider.clientInformation())?.client_id === use.storedClientId) {
307
+ for (const kind of ["client", "tokens", "discovery"])
308
+ await provider.invalidateCredentials?.(kind);
309
+ }
310
+ }
311
+ else {
312
+ await provider.invalidateCredentials?.("all");
313
+ }
291
314
  return runFlow(provider, options);
292
315
  }
293
316
  if (error instanceof OAuthError && error.code === "invalid_grant") {
@@ -1 +1 @@
1
- {"version":3,"file":"flow.js","sourceRoot":"","sources":["../../src/oauth/flow.ts"],"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CAAC;YACtB,CAAC,CAAC,CAAC;YACJ,MAAM,QAAQ,CAAC;QAChB,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["/*\n * Adapted from modelcontextprotocol/typescript-sdk v1.29.0 src/client/auth.ts.\n * Copyright (c) 2024 Anthropic, PBC. Licensed under MIT; see LICENSES/.\n * Modified to remove SDK/Zod dependencies and use WebCrypto for PKCE.\n */\n\nimport type { AuthProvider, McpFetch, UnauthorizedContext } from \"../auth-provider.ts\";\nimport { isObject } from \"../protocol/jsonrpc.ts\";\nimport {\n\tdiscoverAuthorizationServerMetadata,\n\tdiscoverOAuthServerInfo,\n\tparseWwwAuthenticate,\n\tselectResource,\n} from \"./discovery.ts\";\nimport {\n\tMcpOAuthAuthorizationRequiredError,\n\tOAuthError,\n\tOAuthInsecureEndpointError,\n\tOAuthIssuerMismatchError,\n\tOAuthRegistrationError,\n} from \"./errors.ts\";\nimport {\n\ttype AuthorizationServerMetadata,\n\tisHttpUrl,\n\ttype OAuthClientInformation,\n\ttype OAuthClientInformationFull,\n\ttype OAuthClientInformationMixed,\n\ttype OAuthClientMetadata,\n\ttype OAuthDiscoveryState,\n\ttype OAuthTokens,\n\tparseClientInformation,\n\tparseOAuthTokens,\n} from \"./types.ts\";\n\nexport type AddClientAuthentication = (\n\theaders: Headers,\n\tparams: URLSearchParams,\n\turl: string | URL,\n\tmetadata?: AuthorizationServerMetadata,\n) => void | Promise<void>;\n\n/** A Client ID Metadata Document: an https URL used as `client_id`, and a redirect URI it lists. */\nexport interface OAuthClientMetadataDocument {\n\turl: string;\n\tredirectUrl: string;\n}\n\nexport interface OAuthClientProvider {\n\treadonly redirectUrl: string | URL;\n\treadonly clientMetadata: OAuthClientMetadata;\n\t/**\n\t * Client ID Metadata Document to identify as instead of registering dynamically, or `undefined` to\n\t * register. Called when no client information is stored; the document is not stored. `metadata` is\n\t * `undefined` when the authorization server has none; check `client_id_metadata_document_supported`.\n\t */\n\tclientMetadataDocument?(metadata: AuthorizationServerMetadata | undefined): OAuthClientMetadataDocument | undefined;\n\tstate?(): string | Promise<string>;\n\tclientInformation(): OAuthClientInformationMixed | undefined | Promise<OAuthClientInformationMixed | undefined>;\n\tsaveClientInformation?(information: OAuthClientInformationMixed): void | Promise<void>;\n\ttokens(): OAuthTokens | undefined | Promise<OAuthTokens | undefined>;\n\tsaveTokens(tokens: OAuthTokens): void | Promise<void>;\n\tredirectToAuthorization(url: URL): void | Promise<void>;\n\tsaveCodeVerifier(verifier: string): void | Promise<void>;\n\tcodeVerifier(): string | Promise<string>;\n\taddClientAuthentication?: AddClientAuthentication;\n\tinvalidateCredentials?(kind: \"all\" | \"client\" | \"tokens\" | \"verifier\" | \"discovery\"): void | Promise<void>;\n\tsaveDiscoveryState?(state: OAuthDiscoveryState): void | Promise<void>;\n\tdiscoveryState?(): OAuthDiscoveryState | undefined | Promise<OAuthDiscoveryState | undefined>;\n}\n\nexport interface OAuthFlowOptions {\n\tserverUrl: string | URL;\n\tauthorizationCode?: string;\n\t/** `iss` parameter of the authorization response that delivered `authorizationCode` (RFC 9207). */\n\tiss?: string;\n\tscope?: string;\n\tresourceMetadataUrl?: URL;\n\t/**\n\t * Authorization server metadata document to use instead of discovery, for servers that advertise a\n\t * wrong authorization server or none. It is trusted as configured. Must use https, except on loopback.\n\t */\n\tauthorizationServerMetadataUrl?: URL;\n\tfetch?: McpFetch;\n\t/** Aborts every request of the flow. Requests have no time limit of their own; combine with a timeout as needed. */\n\tsignal?: AbortSignal;\n\tskipIssuerValidation?: boolean;\n\t/**\n\t * Go straight to the authorization redirect instead of refreshing stored tokens, for example when the\n\t * server asks for scopes the current grant lacks (a refresh keeps the old scope).\n\t */\n\tskipRefresh?: boolean;\n}\n\nexport type OAuthFlowResult = \"AUTHORIZED\" | \"REDIRECT\";\ntype ClientAuthMethod = \"client_secret_basic\" | \"client_secret_post\" | \"none\";\n\nexport interface TokenRequestOptions {\n\tmetadata?: AuthorizationServerMetadata;\n\tclientInformation: OAuthClientInformationMixed;\n\tresource?: string;\n\taddClientAuthentication?: AddClientAuthentication;\n\tfetch?: McpFetch;\n\tsignal?: AbortSignal;\n}\n\nfunction loopback(hostname: string): boolean {\n\treturn hostname === \"localhost\" || hostname === \"127.0.0.1\" || hostname === \"[::1]\" || hostname === \"::1\";\n}\n\n/**\n * The OpenID Connect `application_type` for `redirect_uris` (MCP SEP-837). Without one, OpenID Connect servers\n * assume `web`, which rejects http loopback redirect URIs. Loopback hosts and custom schemes are native (RFC 8252).\n */\nfunction applicationType(redirectUris: readonly string[]): \"native\" | \"web\" {\n\tconst native = redirectUris.some((uri) => {\n\t\tif (!URL.canParse(uri)) return false;\n\t\tconst url = new URL(uri);\n\t\treturn (url.protocol !== \"http:\" && url.protocol !== \"https:\") || loopback(url.hostname);\n\t});\n\treturn native ? \"native\" : \"web\";\n}\n\nfunction secureEndpoint(value: string | URL): URL {\n\tconst url = new URL(value);\n\tif (url.protocol !== \"https:\" && !loopback(url.hostname)) throw new OAuthInsecureEndpointError(url.href);\n\treturn url;\n}\n\nfunction selectClientAuthMethod(information: OAuthClientInformationMixed, supported: string[]): ClientAuthMethod {\n\tconst hinted = \"token_endpoint_auth_method\" in information ? information.token_endpoint_auth_method : undefined;\n\tif (\n\t\thinted &&\n\t\t[\"client_secret_basic\", \"client_secret_post\", \"none\"].includes(hinted) &&\n\t\t(supported.length === 0 || supported.includes(hinted))\n\t) {\n\t\treturn hinted as ClientAuthMethod;\n\t}\n\tif (supported.length === 0) return information.client_secret ? \"client_secret_basic\" : \"none\";\n\tif (information.client_secret && supported.includes(\"client_secret_basic\")) return \"client_secret_basic\";\n\tif (information.client_secret && supported.includes(\"client_secret_post\")) return \"client_secret_post\";\n\tif (supported.includes(\"none\")) return \"none\";\n\treturn information.client_secret ? \"client_secret_post\" : \"none\";\n}\n\nfunction applyClientAuthentication(\n\tmethod: ClientAuthMethod,\n\tinformation: OAuthClientInformation,\n\theaders: Headers,\n\tparams: URLSearchParams,\n): void {\n\tif (method === \"client_secret_basic\") {\n\t\tif (!information.client_secret) throw new Error(\"client_secret_basic requires a client secret\");\n\t\theaders.set(\n\t\t\t\"Authorization\",\n\t\t\t`Basic ${Buffer.from(`${information.client_id}:${information.client_secret}`).toString(\"base64\")}`,\n\t\t);\n\t} else {\n\t\tparams.set(\"client_id\", information.client_id);\n\t\tif (method === \"client_secret_post\" && information.client_secret)\n\t\t\tparams.set(\"client_secret\", information.client_secret);\n\t}\n}\n\nasync function pkce(): Promise<{ verifier: string; challenge: string }> {\n\tconst bytes = crypto.getRandomValues(new Uint8Array(32));\n\tconst verifier = Buffer.from(bytes).toString(\"base64url\");\n\tconst digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(verifier));\n\treturn { verifier, challenge: Buffer.from(digest).toString(\"base64url\") };\n}\n\nexport async function startAuthorization(\n\tauthorizationServerUrl: string | URL,\n\toptions: {\n\t\tmetadata?: AuthorizationServerMetadata;\n\t\tclientInformation: OAuthClientInformationMixed;\n\t\tredirectUrl: string | URL;\n\t\tscope?: string;\n\t\tstate?: string;\n\t\tresource?: string;\n\t},\n): Promise<{ authorizationUrl: URL; codeVerifier: string }> {\n\tconst metadata = options.metadata;\n\tif (metadata && !metadata.response_types_supported.includes(\"code\")) {\n\t\tthrow new Error(\"Authorization server does not support authorization codes\");\n\t}\n\tif (metadata?.code_challenge_methods_supported && !metadata.code_challenge_methods_supported.includes(\"S256\")) {\n\t\tthrow new Error(\"Authorization server does not support PKCE S256\");\n\t}\n\tconst url = new URL(metadata?.authorization_endpoint ?? new URL(\"/authorize\", authorizationServerUrl));\n\t// Callers open this URL with the platform URL handler, which also launches files and custom protocols.\n\tif (!isHttpUrl(url)) throw new Error(`Invalid authorization endpoint ${url.href}`);\n\tconst { verifier, challenge } = await pkce();\n\turl.searchParams.set(\"response_type\", \"code\");\n\turl.searchParams.set(\"client_id\", options.clientInformation.client_id);\n\turl.searchParams.set(\"code_challenge\", challenge);\n\turl.searchParams.set(\"code_challenge_method\", \"S256\");\n\turl.searchParams.set(\"redirect_uri\", String(options.redirectUrl));\n\tif (options.state) url.searchParams.set(\"state\", options.state);\n\tif (options.scope) url.searchParams.set(\"scope\", options.scope);\n\tif (options.scope?.split(/\\s+/).includes(\"offline_access\")) url.searchParams.set(\"prompt\", \"consent\");\n\tif (options.resource) url.searchParams.set(\"resource\", options.resource);\n\treturn { authorizationUrl: url, codeVerifier: verifier };\n}\n\nasync function tokenRequest(\n\tauthorizationServerUrl: string | URL,\n\toptions: TokenRequestOptions,\n\tparams: URLSearchParams,\n): Promise<OAuthTokens> {\n\tconst url = secureEndpoint(options.metadata?.token_endpoint ?? new URL(\"/token\", authorizationServerUrl));\n\tconst headers = new Headers({ Accept: \"application/json\", \"content-type\": \"application/x-www-form-urlencoded\" });\n\tif (options.resource) params.set(\"resource\", options.resource);\n\tif (options.addClientAuthentication) {\n\t\tawait options.addClientAuthentication(headers, params, url, options.metadata);\n\t} else {\n\t\tapplyClientAuthentication(\n\t\t\tselectClientAuthMethod(\n\t\t\t\toptions.clientInformation,\n\t\t\t\toptions.metadata?.token_endpoint_auth_methods_supported ?? [],\n\t\t\t),\n\t\t\toptions.clientInformation,\n\t\t\theaders,\n\t\t\tparams,\n\t\t);\n\t}\n\tconst response = await (options.fetch ?? globalThis.fetch)(url, {\n\t\tmethod: \"POST\",\n\t\theaders,\n\t\tbody: params,\n\t\tsignal: options.signal,\n\t});\n\tconst text = await response.text();\n\tlet value: unknown;\n\ttry {\n\t\tvalue = JSON.parse(text);\n\t} catch {}\n\t// Servers may report OAuth errors with any status, so check the body before the status.\n\tif (isObject(value) && typeof value.error === \"string\") {\n\t\tthrow new OAuthError(\n\t\t\tvalue.error,\n\t\t\ttypeof value.error_description === \"string\" ? value.error_description : value.error,\n\t\t\ttypeof value.error_uri === \"string\" ? value.error_uri : undefined,\n\t\t);\n\t}\n\tif (!response.ok) throw new OAuthError(\"server_error\", `HTTP ${response.status}: ${text}`);\n\treturn parseOAuthTokens(value);\n}\n\nexport async function registerClient(\n\tauthorizationServerUrl: string | URL,\n\toptions: {\n\t\tmetadata?: AuthorizationServerMetadata;\n\t\tclientMetadata: OAuthClientMetadata;\n\t\tscope?: string;\n\t\tfetch?: McpFetch;\n\t\tsignal?: AbortSignal;\n\t},\n): Promise<OAuthClientInformationFull> {\n\tconst endpoint = options.metadata?.registration_endpoint;\n\tif (options.metadata && !endpoint)\n\t\tthrow new Error(\"Authorization server does not support dynamic client registration\");\n\tconst response = await (options.fetch ?? globalThis.fetch)(\n\t\tnew URL(endpoint ?? new URL(\"/register\", authorizationServerUrl)),\n\t\t{\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { Accept: \"application/json\", \"content-type\": \"application/json\" },\n\t\t\tbody: JSON.stringify({\n\t\t\t\t...options.clientMetadata,\n\t\t\t\tapplication_type:\n\t\t\t\t\toptions.clientMetadata.application_type ?? applicationType(options.clientMetadata.redirect_uris),\n\t\t\t\t...(options.scope ? { scope: options.scope } : {}),\n\t\t\t}),\n\t\t\tsignal: options.signal,\n\t\t},\n\t);\n\tif (!response.ok) throw new OAuthRegistrationError(response.status, await response.text());\n\treturn parseClientInformation(await response.json());\n}\n\nexport async function exchangeAuthorizationCode(\n\tauthorizationServerUrl: string | URL,\n\toptions: TokenRequestOptions & { code: string; codeVerifier: string; redirectUrl: string | URL },\n): Promise<OAuthTokens> {\n\treturn tokenRequest(\n\t\tauthorizationServerUrl,\n\t\toptions,\n\t\tnew URLSearchParams({\n\t\t\tgrant_type: \"authorization_code\",\n\t\t\tcode: options.code,\n\t\t\tcode_verifier: options.codeVerifier,\n\t\t\tredirect_uri: String(options.redirectUrl),\n\t\t}),\n\t);\n}\n\nexport async function refreshAuthorization(\n\tauthorizationServerUrl: string | URL,\n\toptions: TokenRequestOptions & { refreshToken: string },\n): Promise<OAuthTokens> {\n\tconst tokens = await tokenRequest(\n\t\tauthorizationServerUrl,\n\t\toptions,\n\t\tnew URLSearchParams({ grant_type: \"refresh_token\", refresh_token: options.refreshToken }),\n\t);\n\treturn { refresh_token: options.refreshToken, ...tokens };\n}\n\nfunction withScope(tokens: OAuthTokens, scope: string | undefined): OAuthTokens {\n\treturn tokens.scope === undefined && scope ? { ...tokens, scope } : tokens;\n}\n\n/**\n * Scopes for a step-up authorization: the challenged scopes plus the ones granted so far, since a\n * challenge may list only the missing scopes and a token with just those would lose access the old\n * one had (SEP-2350). Without challenged scopes, `undefined` lets the flow pick its default.\n */\nexport function stepUpScope(granted: string | undefined, challenged: string | undefined): string | undefined {\n\tif (!challenged) return undefined;\n\tconst scopes = [granted, challenged].flatMap((scope) => scope?.split(/\\s+/).filter(Boolean) ?? []);\n\treturn [...new Set(scopes)].join(\" \");\n}\n\nasync function runFlow(provider: OAuthClientProvider, options: OAuthFlowOptions): Promise<OAuthFlowResult> {\n\tconst metadataUrl = options.authorizationServerMetadataUrl && secureEndpoint(options.authorizationServerMetadataUrl);\n\t// With a configured metadata URL, discovery is not cached, so changing the URL applies at once.\n\tconst cached = metadataUrl ? undefined : await provider.discoveryState?.();\n\tconst discovered = cached?.authorizationServerUrl\n\t\t? {\n\t\t\t\tauthorizationServerUrl: cached.authorizationServerUrl,\n\t\t\t\tauthorizationServerMetadata:\n\t\t\t\t\tcached.authorizationServerMetadata ??\n\t\t\t\t\t(await discoverAuthorizationServerMetadata(cached.authorizationServerUrl, {\n\t\t\t\t\t\tfetch: options.fetch,\n\t\t\t\t\t\tskipIssuerValidation: options.skipIssuerValidation,\n\t\t\t\t\t\tsignal: options.signal,\n\t\t\t\t\t})),\n\t\t\t\tresourceMetadata: cached.resourceMetadata,\n\t\t\t}\n\t\t: await discoverOAuthServerInfo(options.serverUrl, {\n\t\t\t\tresourceMetadataUrl: options.resourceMetadataUrl,\n\t\t\t\tauthorizationServerMetadataUrl: metadataUrl,\n\t\t\t\tfetch: options.fetch,\n\t\t\t\tskipIssuerValidation: options.skipIssuerValidation,\n\t\t\t\tsignal: options.signal,\n\t\t\t});\n\tif (!metadataUrl) {\n\t\tawait provider.saveDiscoveryState?.({\n\t\t\t...discovered,\n\t\t\t...(options.resourceMetadataUrl ? { resourceMetadataUrl: options.resourceMetadataUrl.href } : {}),\n\t\t});\n\t}\n\tconst metadata = discovered.authorizationServerMetadata;\n\tconst resource = selectResource(options.serverUrl, discovered.resourceMetadata);\n\t// `||`, not `??`: an empty scope (for example from `scopes_supported: []`) falls through to the next source.\n\tconst scope =\n\t\toptions.scope || discovered.resourceMetadata?.scopes_supported?.join(\" \") || provider.clientMetadata.scope;\n\tconst stored = await provider.clientInformation();\n\tconst clientDocument = stored ? undefined : provider.clientMetadataDocument?.(metadata);\n\tif (clientDocument) {\n\t\tconst url = new URL(clientDocument.url);\n\t\tif (url.protocol !== \"https:\" || url.pathname === \"/\") throw new Error(\"Invalid OAuth client metadata URL\");\n\t}\n\tlet client = stored ?? (clientDocument && { client_id: clientDocument.url });\n\tif (!client) {\n\t\tif (options.authorizationCode) throw new Error(\"OAuth client information is missing during code exchange\");\n\t\tif (!provider.saveClientInformation) throw new Error(\"OAuth client information cannot be persisted\");\n\t\tclient = await registerClient(discovered.authorizationServerUrl, {\n\t\t\tmetadata,\n\t\t\tclientMetadata: provider.clientMetadata,\n\t\t\tscope,\n\t\t\tfetch: options.fetch,\n\t\t\tsignal: options.signal,\n\t\t});\n\t\tawait provider.saveClientInformation(client);\n\t}\n\t// The document's redirect URI may differ from the provider's, for example by a server-specific path.\n\tconst redirectUrl = clientDocument?.redirectUrl ?? provider.redirectUrl;\n\tconst tokenOptions: TokenRequestOptions = {\n\t\tmetadata,\n\t\tclientInformation: client,\n\t\tresource,\n\t\taddClientAuthentication: provider.addClientAuthentication,\n\t\tfetch: options.fetch,\n\t\tsignal: options.signal,\n\t};\n\tif (options.authorizationCode) {\n\t\t// RFC 9207: never send a code from another authorization server to this one. Without metadata there\n\t\t// is no issuer to compare with, so any `iss` is rejected.\n\t\tconst iss = options.iss;\n\t\tif (iss !== undefined || metadata?.authorization_response_iss_parameter_supported) {\n\t\t\tif (iss !== metadata?.issuer) throw new OAuthIssuerMismatchError(metadata?.issuer, iss);\n\t\t}\n\t\tconst tokens = await exchangeAuthorizationCode(discovered.authorizationServerUrl, {\n\t\t\t...tokenOptions,\n\t\t\tcode: options.authorizationCode,\n\t\t\tcodeVerifier: await provider.codeVerifier(),\n\t\t\tredirectUrl,\n\t\t});\n\t\t// A response without `scope` grants the requested scope (RFC 6749 §5.1). Recorded so a step-up can\n\t\t// keep it. Callers pass the options of the authorization request, so `scope` is what was requested.\n\t\tawait provider.saveTokens(withScope(tokens, scope));\n\t\treturn \"AUTHORIZED\";\n\t}\n\tconst existing = options.skipRefresh ? undefined : await provider.tokens();\n\tif (existing?.refresh_token) {\n\t\ttry {\n\t\t\tconst tokens = await refreshAuthorization(discovered.authorizationServerUrl, {\n\t\t\t\t...tokenOptions,\n\t\t\t\trefreshToken: existing.refresh_token,\n\t\t\t});\n\t\t\t// A refresh without `scope` keeps the scope of the grant (RFC 6749 §6).\n\t\t\tawait provider.saveTokens(withScope(tokens, existing.scope));\n\t\t\treturn \"AUTHORIZED\";\n\t\t} catch (error) {\n\t\t\tif (options.signal?.aborted || error instanceof OAuthInsecureEndpointError) throw error;\n\t\t\tif (error instanceof OAuthError && error.code !== \"server_error\") throw error;\n\t\t}\n\t}\n\tconst state = await provider.state?.();\n\tconst authorization = await startAuthorization(discovered.authorizationServerUrl, {\n\t\tmetadata,\n\t\tclientInformation: client,\n\t\tredirectUrl,\n\t\tscope,\n\t\tstate,\n\t\tresource,\n\t});\n\tawait provider.saveCodeVerifier(authorization.codeVerifier);\n\tawait provider.redirectToAuthorization(authorization.authorizationUrl);\n\treturn \"REDIRECT\";\n}\n\nexport async function authorizeMcp(provider: OAuthClientProvider, options: OAuthFlowOptions): Promise<OAuthFlowResult> {\n\ttry {\n\t\treturn await runFlow(provider, options);\n\t} catch (error) {\n\t\tif (error instanceof OAuthError && [\"invalid_client\", \"unauthorized_client\"].includes(error.code)) {\n\t\t\tawait provider.invalidateCredentials?.(\"all\");\n\t\t\treturn runFlow(provider, options);\n\t\t}\n\t\tif (error instanceof OAuthError && error.code === \"invalid_grant\") {\n\t\t\tawait provider.invalidateCredentials?.(\"tokens\");\n\t\t\treturn runFlow(provider, options);\n\t\t}\n\t\tthrow error;\n\t}\n}\n\n/**\n * Auth provider for `StreamableHttpTransport`. After a 401 it refreshes the tokens, or throws\n * `McpOAuthAuthorizationRequiredError` when the user has to authorize (again). Concurrent 401s share\n * one refresh, and a request whose token was already replaced is just retried: with rotating refresh\n * tokens, a second refresh with the old refresh token would fail and discard the new grant.\n */\nexport function adaptOAuthProvider(provider: OAuthClientProvider): AuthProvider {\n\tlet inFlight: Promise<void> | undefined;\n\treturn {\n\t\ttoken: async () => (await provider.tokens())?.access_token,\n\t\tonUnauthorized: async (context: UnauthorizedContext) => {\n\t\t\tconst challenge = parseWwwAuthenticate(context.response.headers.get(\"www-authenticate\"));\n\t\t\tconst insufficientScope = challenge.error === \"insufficient_scope\";\n\t\t\tif (!insufficientScope && !inFlight && context.token !== undefined) {\n\t\t\t\tconst current = (await provider.tokens())?.access_token;\n\t\t\t\tif (current !== undefined && current !== context.token) return;\n\t\t\t}\n\t\t\tinFlight ??= Promise.resolve(insufficientScope ? provider.tokens() : undefined)\n\t\t\t\t.then((granted) =>\n\t\t\t\t\tauthorizeMcp(provider, {\n\t\t\t\t\t\tserverUrl: context.serverUrl,\n\t\t\t\t\t\tresourceMetadataUrl: challenge.resourceMetadataUrl,\n\t\t\t\t\t\tscope: insufficientScope ? stepUpScope(granted?.scope, challenge.scope) : challenge.scope,\n\t\t\t\t\t\tfetch: context.fetch,\n\t\t\t\t\t\tskipRefresh: insufficientScope,\n\t\t\t\t\t}),\n\t\t\t\t)\n\t\t\t\t.then((result) => {\n\t\t\t\t\tif (result === \"REDIRECT\") throw new McpOAuthAuthorizationRequiredError();\n\t\t\t\t})\n\t\t\t\t.finally(() => {\n\t\t\t\t\tinFlight = undefined;\n\t\t\t\t});\n\t\t\tawait inFlight;\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,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E,IAAI,CAAC,iBAAiB,IAAI,CAAC,QAAQ,IAAI,OAAO,CAAC,KAAK,KAAK,SAAS,EAAE,CAAC;gBACpE,MAAM,OAAO,GAAG,CAAC,MAAM,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,YAAY,CAAC;gBACxD,IAAI,OAAO,KAAK,SAAS,IAAI,OAAO,KAAK,OAAO,CAAC,KAAK;oBAAE,OAAO;YAChE,CAAC;YACD,QAAQ,KAAK,OAAO,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;iBAC7E,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE,CACjB,YAAY,CAAC,QAAQ,EAAE;gBACtB,SAAS,EAAE,OAAO,CAAC,SAAS;gBAC5B,mBAAmB,EAAE,SAAS,CAAC,mBAAmB;gBAClD,KAAK,EAAE,iBAAiB,CAAC,CAAC,CAAC,WAAW,CAAC,OAAO,EAAE,KAAK,EAAE,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,KAAK;gBACzF,KAAK,EAAE,OAAO,CAAC,KAAK;gBACpB,WAAW,EAAE,iBAAiB;aAC9B,CAAC,CACF;iBACA,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE;gBAChB,IAAI,MAAM,KAAK,UAAU;oBAAE,MAAM,IAAI,kCAAkC,EAAE,CAAC;YAC3E,CAAC,CAAC;iBACD,OAAO,CAAC,GAAG,EAAE;gBACb,QAAQ,GAAG,SAAS,CAAC;YACtB,CAAC,CAAC,CAAC;YACJ,MAAM,QAAQ,CAAC;QAChB,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["/*\n * Adapted from modelcontextprotocol/typescript-sdk v1.29.0 src/client/auth.ts.\n * Copyright (c) 2024 Anthropic, PBC. Licensed under MIT; see THIRD_PARTY_NOTICES/.\n * Modified to remove SDK/Zod dependencies and use WebCrypto for PKCE.\n */\n\nimport type { AuthProvider, McpFetch, UnauthorizedContext } from \"../auth-provider.ts\";\nimport { isObject } from \"../protocol/jsonrpc.ts\";\nimport {\n\tdiscoverAuthorizationServerMetadata,\n\tdiscoverOAuthServerInfo,\n\tparseWwwAuthenticate,\n\tselectResource,\n} from \"./discovery.ts\";\nimport {\n\tMcpOAuthAuthorizationRequiredError,\n\tOAuthError,\n\tOAuthInsecureEndpointError,\n\tOAuthIssuerMismatchError,\n\tOAuthRegistrationError,\n} from \"./errors.ts\";\nimport {\n\ttype AuthorizationServerMetadata,\n\tisHttpUrl,\n\ttype OAuthClientInformation,\n\ttype OAuthClientInformationFull,\n\ttype OAuthClientInformationMixed,\n\ttype OAuthClientMetadata,\n\ttype OAuthDiscoveryState,\n\ttype OAuthTokens,\n\tparseClientInformation,\n\tparseOAuthTokens,\n} from \"./types.ts\";\n\nexport type AddClientAuthentication = (\n\theaders: Headers,\n\tparams: URLSearchParams,\n\turl: string | URL,\n\tmetadata?: AuthorizationServerMetadata,\n) => void | Promise<void>;\n\n/** A Client ID Metadata Document: an https URL used as `client_id`, and a redirect URI it lists. */\nexport interface OAuthClientMetadataDocument {\n\turl: string;\n\tredirectUrl: string;\n}\n\nexport interface OAuthClientProvider {\n\treadonly redirectUrl: string | URL;\n\treadonly clientMetadata: OAuthClientMetadata;\n\t/**\n\t * Client ID Metadata Document to identify as instead of registering dynamically, or `undefined` to\n\t * register. Called when no client information is stored; the document is not stored. `metadata` is\n\t * `undefined` when the authorization server has none; check `client_id_metadata_document_supported`.\n\t */\n\tclientMetadataDocument?(metadata: AuthorizationServerMetadata | undefined): OAuthClientMetadataDocument | undefined;\n\tstate?(): string | Promise<string>;\n\tclientInformation(): OAuthClientInformationMixed | undefined | Promise<OAuthClientInformationMixed | undefined>;\n\tsaveClientInformation?(information: OAuthClientInformationMixed): void | Promise<void>;\n\ttokens(): OAuthTokens | undefined | Promise<OAuthTokens | undefined>;\n\tsaveTokens(tokens: OAuthTokens): void | Promise<void>;\n\tredirectToAuthorization(url: URL): void | Promise<void>;\n\tsaveCodeVerifier(verifier: string): void | Promise<void>;\n\tcodeVerifier(): string | Promise<string>;\n\taddClientAuthentication?: AddClientAuthentication;\n\tinvalidateCredentials?(kind: \"all\" | \"client\" | \"tokens\" | \"verifier\" | \"discovery\"): void | Promise<void>;\n\tsaveDiscoveryState?(state: OAuthDiscoveryState): void | Promise<void>;\n\tdiscoveryState?(): OAuthDiscoveryState | undefined | Promise<OAuthDiscoveryState | undefined>;\n}\n\nexport interface OAuthFlowOptions {\n\tserverUrl: string | URL;\n\tauthorizationCode?: string;\n\t/** `iss` parameter of the authorization response that delivered `authorizationCode` (RFC 9207). */\n\tiss?: string;\n\tscope?: string;\n\tresourceMetadataUrl?: URL;\n\t/**\n\t * Authorization server metadata document to use instead of discovery, for servers that advertise a\n\t * wrong authorization server or none. It is trusted as configured. Must use https, except on loopback.\n\t */\n\tauthorizationServerMetadataUrl?: URL;\n\tfetch?: McpFetch;\n\t/** Aborts every request of the flow. Requests have no time limit of their own; combine with a timeout as needed. */\n\tsignal?: AbortSignal;\n\tskipIssuerValidation?: boolean;\n\t/**\n\t * Go straight to the authorization redirect instead of refreshing stored tokens, for example when the\n\t * server asks for scopes the current grant lacks (a refresh keeps the old scope).\n\t */\n\tskipRefresh?: boolean;\n\t/**\n\t * Only refresh the stored tokens: return `REDIRECT` instead of registering a client or preparing an\n\t * authorization request, so a pending authorization (its `state` and PKCE verifier) stays usable.\n\t */\n\trefreshOnly?: boolean;\n\t/**\n\t * With `authorizationCode`: the redirect URI the authorization request used. The exchange fails before\n\t * sending the code when the flow would send another one (RFC 6749 section 4.1.3 requires the same).\n\t */\n\tauthorizationRedirectUrl?: string;\n}\n\nexport type OAuthFlowResult = \"AUTHORIZED\" | \"REDIRECT\";\ntype ClientAuthMethod = \"client_secret_basic\" | \"client_secret_post\" | \"none\";\n\nexport interface TokenRequestOptions {\n\tmetadata?: AuthorizationServerMetadata;\n\tclientInformation: OAuthClientInformationMixed;\n\tresource?: string;\n\taddClientAuthentication?: AddClientAuthentication;\n\tfetch?: McpFetch;\n\tsignal?: AbortSignal;\n}\n\nfunction loopback(hostname: string): boolean {\n\treturn hostname === \"localhost\" || hostname === \"127.0.0.1\" || hostname === \"[::1]\" || hostname === \"::1\";\n}\n\n/**\n * The OpenID Connect `application_type` for `redirect_uris` (MCP SEP-837). Without one, OpenID Connect servers\n * assume `web`, which rejects http loopback redirect URIs. Loopback hosts and custom schemes are native (RFC 8252).\n */\nfunction applicationType(redirectUris: readonly string[]): \"native\" | \"web\" {\n\tconst native = redirectUris.some((uri) => {\n\t\tif (!URL.canParse(uri)) return false;\n\t\tconst url = new URL(uri);\n\t\treturn (url.protocol !== \"http:\" && url.protocol !== \"https:\") || loopback(url.hostname);\n\t});\n\treturn native ? \"native\" : \"web\";\n}\n\nfunction secureEndpoint(value: string | URL): URL {\n\tconst url = new URL(value);\n\tif (url.protocol !== \"https:\" && !loopback(url.hostname)) throw new OAuthInsecureEndpointError(url.href);\n\treturn url;\n}\n\nfunction selectClientAuthMethod(information: OAuthClientInformationMixed, supported: string[]): ClientAuthMethod {\n\tconst hinted = \"token_endpoint_auth_method\" in information ? information.token_endpoint_auth_method : undefined;\n\tif (\n\t\thinted &&\n\t\t[\"client_secret_basic\", \"client_secret_post\", \"none\"].includes(hinted) &&\n\t\t(supported.length === 0 || supported.includes(hinted))\n\t) {\n\t\treturn hinted as ClientAuthMethod;\n\t}\n\tif (supported.length === 0) return information.client_secret ? \"client_secret_basic\" : \"none\";\n\tif (information.client_secret && supported.includes(\"client_secret_basic\")) return \"client_secret_basic\";\n\tif (information.client_secret && supported.includes(\"client_secret_post\")) return \"client_secret_post\";\n\tif (supported.includes(\"none\")) return \"none\";\n\treturn information.client_secret ? \"client_secret_post\" : \"none\";\n}\n\nfunction applyClientAuthentication(\n\tmethod: ClientAuthMethod,\n\tinformation: OAuthClientInformation,\n\theaders: Headers,\n\tparams: URLSearchParams,\n): void {\n\tif (method === \"client_secret_basic\") {\n\t\tif (!information.client_secret) throw new Error(\"client_secret_basic requires a client secret\");\n\t\theaders.set(\n\t\t\t\"Authorization\",\n\t\t\t`Basic ${Buffer.from(`${information.client_id}:${information.client_secret}`).toString(\"base64\")}`,\n\t\t);\n\t} else {\n\t\tparams.set(\"client_id\", information.client_id);\n\t\tif (method === \"client_secret_post\" && information.client_secret)\n\t\t\tparams.set(\"client_secret\", information.client_secret);\n\t}\n}\n\nasync function pkce(): Promise<{ verifier: string; challenge: string }> {\n\tconst bytes = crypto.getRandomValues(new Uint8Array(32));\n\tconst verifier = Buffer.from(bytes).toString(\"base64url\");\n\tconst digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(verifier));\n\treturn { verifier, challenge: Buffer.from(digest).toString(\"base64url\") };\n}\n\nexport async function startAuthorization(\n\tauthorizationServerUrl: string | URL,\n\toptions: {\n\t\tmetadata?: AuthorizationServerMetadata;\n\t\tclientInformation: OAuthClientInformationMixed;\n\t\tredirectUrl: string | URL;\n\t\tscope?: string;\n\t\tstate?: string;\n\t\tresource?: string;\n\t},\n): Promise<{ authorizationUrl: URL; codeVerifier: string }> {\n\tconst metadata = options.metadata;\n\tif (metadata && !metadata.response_types_supported.includes(\"code\")) {\n\t\tthrow new Error(\"Authorization server does not support authorization codes\");\n\t}\n\tif (metadata?.code_challenge_methods_supported && !metadata.code_challenge_methods_supported.includes(\"S256\")) {\n\t\tthrow new Error(\"Authorization server does not support PKCE S256\");\n\t}\n\tconst url = new URL(metadata?.authorization_endpoint ?? new URL(\"/authorize\", authorizationServerUrl));\n\t// Callers open this URL with the platform URL handler, which also launches files and custom protocols.\n\tif (!isHttpUrl(url)) throw new Error(`Invalid authorization endpoint ${url.href}`);\n\tconst { verifier, challenge } = await pkce();\n\turl.searchParams.set(\"response_type\", \"code\");\n\turl.searchParams.set(\"client_id\", options.clientInformation.client_id);\n\turl.searchParams.set(\"code_challenge\", challenge);\n\turl.searchParams.set(\"code_challenge_method\", \"S256\");\n\turl.searchParams.set(\"redirect_uri\", String(options.redirectUrl));\n\tif (options.state) url.searchParams.set(\"state\", options.state);\n\tif (options.scope) url.searchParams.set(\"scope\", options.scope);\n\tif (options.scope?.split(/\\s+/).includes(\"offline_access\")) url.searchParams.set(\"prompt\", \"consent\");\n\tif (options.resource) url.searchParams.set(\"resource\", options.resource);\n\treturn { authorizationUrl: url, codeVerifier: verifier };\n}\n\nasync function tokenRequest(\n\tauthorizationServerUrl: string | URL,\n\toptions: TokenRequestOptions,\n\tparams: URLSearchParams,\n): Promise<OAuthTokens> {\n\tconst url = secureEndpoint(options.metadata?.token_endpoint ?? new URL(\"/token\", authorizationServerUrl));\n\tconst headers = new Headers({ Accept: \"application/json\", \"content-type\": \"application/x-www-form-urlencoded\" });\n\tif (options.resource) params.set(\"resource\", options.resource);\n\tif (options.addClientAuthentication) {\n\t\tawait options.addClientAuthentication(headers, params, url, options.metadata);\n\t} else {\n\t\tapplyClientAuthentication(\n\t\t\tselectClientAuthMethod(\n\t\t\t\toptions.clientInformation,\n\t\t\t\toptions.metadata?.token_endpoint_auth_methods_supported ?? [],\n\t\t\t),\n\t\t\toptions.clientInformation,\n\t\t\theaders,\n\t\t\tparams,\n\t\t);\n\t}\n\tconst response = await (options.fetch ?? globalThis.fetch)(url, {\n\t\tmethod: \"POST\",\n\t\theaders,\n\t\tbody: params,\n\t\tsignal: options.signal,\n\t});\n\tconst text = await response.text();\n\tlet value: unknown;\n\ttry {\n\t\tvalue = JSON.parse(text);\n\t} catch {}\n\t// Servers may report OAuth errors with any status, so check the body before the status.\n\tif (isObject(value) && typeof value.error === \"string\") {\n\t\tthrow new OAuthError(\n\t\t\tvalue.error,\n\t\t\ttypeof value.error_description === \"string\" ? value.error_description : value.error,\n\t\t\ttypeof value.error_uri === \"string\" ? value.error_uri : undefined,\n\t\t);\n\t}\n\tif (!response.ok) throw new OAuthError(\"server_error\", `HTTP ${response.status}: ${text}`);\n\treturn parseOAuthTokens(value);\n}\n\nexport async function registerClient(\n\tauthorizationServerUrl: string | URL,\n\toptions: {\n\t\tmetadata?: AuthorizationServerMetadata;\n\t\tclientMetadata: OAuthClientMetadata;\n\t\tscope?: string;\n\t\tfetch?: McpFetch;\n\t\tsignal?: AbortSignal;\n\t},\n): Promise<OAuthClientInformationFull> {\n\tconst endpoint = options.metadata?.registration_endpoint;\n\tif (options.metadata && !endpoint)\n\t\tthrow new Error(\"Authorization server does not support dynamic client registration\");\n\tconst response = await (options.fetch ?? globalThis.fetch)(\n\t\tnew URL(endpoint ?? new URL(\"/register\", authorizationServerUrl)),\n\t\t{\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { Accept: \"application/json\", \"content-type\": \"application/json\" },\n\t\t\tbody: JSON.stringify({\n\t\t\t\t...options.clientMetadata,\n\t\t\t\tapplication_type:\n\t\t\t\t\toptions.clientMetadata.application_type ?? applicationType(options.clientMetadata.redirect_uris),\n\t\t\t\t...(options.scope ? { scope: options.scope } : {}),\n\t\t\t}),\n\t\t\tsignal: options.signal,\n\t\t},\n\t);\n\tif (!response.ok) throw new OAuthRegistrationError(response.status, await response.text());\n\treturn parseClientInformation(await response.json());\n}\n\nexport async function exchangeAuthorizationCode(\n\tauthorizationServerUrl: string | URL,\n\toptions: TokenRequestOptions & { code: string; codeVerifier: string; redirectUrl: string | URL },\n): Promise<OAuthTokens> {\n\treturn tokenRequest(\n\t\tauthorizationServerUrl,\n\t\toptions,\n\t\tnew URLSearchParams({\n\t\t\tgrant_type: \"authorization_code\",\n\t\t\tcode: options.code,\n\t\t\tcode_verifier: options.codeVerifier,\n\t\t\tredirect_uri: String(options.redirectUrl),\n\t\t}),\n\t);\n}\n\nexport async function refreshAuthorization(\n\tauthorizationServerUrl: string | URL,\n\toptions: TokenRequestOptions & { refreshToken: string },\n): Promise<OAuthTokens> {\n\tconst tokens = await tokenRequest(\n\t\tauthorizationServerUrl,\n\t\toptions,\n\t\tnew URLSearchParams({ grant_type: \"refresh_token\", refresh_token: options.refreshToken }),\n\t);\n\treturn { refresh_token: options.refreshToken, ...tokens };\n}\n\nfunction withScope(tokens: OAuthTokens, scope: string | undefined): OAuthTokens {\n\treturn tokens.scope === undefined && scope ? { ...tokens, scope } : tokens;\n}\n\n/**\n * Scopes for a step-up authorization: the challenged scopes plus the ones granted so far, since a\n * challenge may list only the missing scopes and a token with just those would lose access the old\n * one had (SEP-2350). Without challenged scopes, `undefined` lets the flow pick its default.\n */\nexport function stepUpScope(granted: string | undefined, challenged: string | undefined): string | undefined {\n\tif (!challenged) return undefined;\n\tconst scopes = [granted, challenged].flatMap((scope) => scope?.split(/\\s+/).filter(Boolean) ?? []);\n\treturn [...new Set(scopes)].join(\" \");\n}\n\n/** What a flow used, for deciding what to invalidate after it failed. */\ninterface FlowUse {\n\t/** `client_id` of the stored client the flow used; `undefined` when none was stored. */\n\tstoredClientId?: string;\n}\n\nasync function runFlow(\n\tprovider: OAuthClientProvider,\n\toptions: OAuthFlowOptions,\n\tuse: FlowUse = {},\n): Promise<OAuthFlowResult> {\n\tconst metadataUrl = options.authorizationServerMetadataUrl && secureEndpoint(options.authorizationServerMetadataUrl);\n\t// With a configured metadata URL, discovery is not cached, so changing the URL applies at once.\n\tconst cached = metadataUrl ? undefined : await provider.discoveryState?.();\n\tconst discovered = cached?.authorizationServerUrl\n\t\t? {\n\t\t\t\tauthorizationServerUrl: cached.authorizationServerUrl,\n\t\t\t\tauthorizationServerMetadata:\n\t\t\t\t\tcached.authorizationServerMetadata ??\n\t\t\t\t\t(await discoverAuthorizationServerMetadata(cached.authorizationServerUrl, {\n\t\t\t\t\t\tfetch: options.fetch,\n\t\t\t\t\t\tskipIssuerValidation: options.skipIssuerValidation,\n\t\t\t\t\t\tsignal: options.signal,\n\t\t\t\t\t})),\n\t\t\t\tresourceMetadata: cached.resourceMetadata,\n\t\t\t}\n\t\t: await discoverOAuthServerInfo(options.serverUrl, {\n\t\t\t\tresourceMetadataUrl: options.resourceMetadataUrl,\n\t\t\t\tauthorizationServerMetadataUrl: metadataUrl,\n\t\t\t\tfetch: options.fetch,\n\t\t\t\tskipIssuerValidation: options.skipIssuerValidation,\n\t\t\t\tsignal: options.signal,\n\t\t\t});\n\tif (!metadataUrl) {\n\t\tawait provider.saveDiscoveryState?.({\n\t\t\t...discovered,\n\t\t\t...(options.resourceMetadataUrl ? { resourceMetadataUrl: options.resourceMetadataUrl.href } : {}),\n\t\t});\n\t}\n\tconst metadata = discovered.authorizationServerMetadata;\n\tconst resource = selectResource(options.serverUrl, discovered.resourceMetadata);\n\t// `||`, not `??`: an empty scope (for example from `scopes_supported: []`) falls through to the next source.\n\tconst scope =\n\t\toptions.scope || discovered.resourceMetadata?.scopes_supported?.join(\" \") || provider.clientMetadata.scope;\n\tconst stored = await provider.clientInformation();\n\tuse.storedClientId = stored?.client_id;\n\tconst clientDocument = stored ? undefined : provider.clientMetadataDocument?.(metadata);\n\tif (clientDocument) {\n\t\tconst url = new URL(clientDocument.url);\n\t\tif (url.protocol !== \"https:\" || url.pathname === \"/\") throw new Error(\"Invalid OAuth client metadata URL\");\n\t}\n\t// The document's redirect URI may differ from the provider's, for example by a server-specific path.\n\tconst redirectUrl = clientDocument?.redirectUrl ?? String(provider.redirectUrl);\n\t// Checked first: another redirect URI also explains a client that is missing for the exchange.\n\tif (options.authorizationCode && options.authorizationRedirectUrl !== undefined) {\n\t\tif (redirectUrl !== options.authorizationRedirectUrl) {\n\t\t\tthrow new Error(\n\t\t\t\t`The code exchange would use the redirect URI ${redirectUrl}, but the authorization request used ${options.authorizationRedirectUrl}`,\n\t\t\t);\n\t\t}\n\t}\n\tlet client = stored ?? (clientDocument && { client_id: clientDocument.url });\n\tif (!client) {\n\t\tif (options.refreshOnly) return \"REDIRECT\";\n\t\tif (options.authorizationCode) {\n\t\t\tthrow new Error(\n\t\t\t\t\"OAuth client information is missing during code exchange: the authorization request's client was removed, or the client settings changed\",\n\t\t\t);\n\t\t}\n\t\tif (!provider.saveClientInformation) throw new Error(\"OAuth client information cannot be persisted\");\n\t\tclient = await registerClient(discovered.authorizationServerUrl, {\n\t\t\tmetadata,\n\t\t\tclientMetadata: provider.clientMetadata,\n\t\t\tscope,\n\t\t\tfetch: options.fetch,\n\t\t\tsignal: options.signal,\n\t\t});\n\t\tawait provider.saveClientInformation(client);\n\t}\n\tconst tokenOptions: TokenRequestOptions = {\n\t\tmetadata,\n\t\tclientInformation: client,\n\t\tresource,\n\t\taddClientAuthentication: provider.addClientAuthentication,\n\t\tfetch: options.fetch,\n\t\tsignal: options.signal,\n\t};\n\tif (options.authorizationCode) {\n\t\t// RFC 9207: never send a code from another authorization server to this one. Without metadata there\n\t\t// is no issuer to compare with, so any `iss` is rejected.\n\t\tconst iss = options.iss;\n\t\tif (iss !== undefined || metadata?.authorization_response_iss_parameter_supported) {\n\t\t\tif (iss !== metadata?.issuer) throw new OAuthIssuerMismatchError(metadata?.issuer, iss);\n\t\t}\n\t\tconst tokens = await exchangeAuthorizationCode(discovered.authorizationServerUrl, {\n\t\t\t...tokenOptions,\n\t\t\tcode: options.authorizationCode,\n\t\t\tcodeVerifier: await provider.codeVerifier(),\n\t\t\tredirectUrl,\n\t\t});\n\t\t// A response without `scope` grants the requested scope (RFC 6749 §5.1). Recorded so a step-up can\n\t\t// keep it. Callers pass the options of the authorization request, so `scope` is what was requested.\n\t\tawait provider.saveTokens(withScope(tokens, scope));\n\t\treturn \"AUTHORIZED\";\n\t}\n\tconst existing = options.skipRefresh ? undefined : await provider.tokens();\n\tif (existing?.refresh_token) {\n\t\ttry {\n\t\t\tconst tokens = await refreshAuthorization(discovered.authorizationServerUrl, {\n\t\t\t\t...tokenOptions,\n\t\t\t\trefreshToken: existing.refresh_token,\n\t\t\t});\n\t\t\t// A refresh without `scope` keeps the scope of the grant (RFC 6749 §6).\n\t\t\tawait provider.saveTokens(withScope(tokens, existing.scope));\n\t\t\treturn \"AUTHORIZED\";\n\t\t} catch (error) {\n\t\t\tif (options.signal?.aborted || error instanceof OAuthInsecureEndpointError) throw error;\n\t\t\tif (error instanceof OAuthError && error.code !== \"server_error\") throw error;\n\t\t}\n\t}\n\tif (options.refreshOnly) return \"REDIRECT\";\n\tconst state = await provider.state?.();\n\tconst authorization = await startAuthorization(discovered.authorizationServerUrl, {\n\t\tmetadata,\n\t\tclientInformation: client,\n\t\tredirectUrl,\n\t\tscope,\n\t\tstate,\n\t\tresource,\n\t});\n\tawait provider.saveCodeVerifier(authorization.codeVerifier);\n\tawait provider.redirectToAuthorization(authorization.authorizationUrl);\n\treturn \"REDIRECT\";\n}\n\nexport async function authorizeMcp(provider: OAuthClientProvider, options: OAuthFlowOptions): Promise<OAuthFlowResult> {\n\tconst use: FlowUse = {};\n\ttry {\n\t\treturn await runFlow(provider, options, use);\n\t} catch (error) {\n\t\tif (error instanceof OAuthError && [\"invalid_client\", \"unauthorized_client\"].includes(error.code)) {\n\t\t\t// A refresh keeps a pending authorization's `state` and verifier: they are the user's sign-in. A client\n\t\t\t// stored meanwhile (by a sign-in that completed) is not the one the server rejected, so it stays.\n\t\t\tif (options.refreshOnly) {\n\t\t\t\tif ((await provider.clientInformation())?.client_id === use.storedClientId) {\n\t\t\t\t\tfor (const kind of [\"client\", \"tokens\", \"discovery\"] as const)\n\t\t\t\t\t\tawait provider.invalidateCredentials?.(kind);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tawait provider.invalidateCredentials?.(\"all\");\n\t\t\t}\n\t\t\treturn runFlow(provider, options);\n\t\t}\n\t\tif (error instanceof OAuthError && error.code === \"invalid_grant\") {\n\t\t\tawait provider.invalidateCredentials?.(\"tokens\");\n\t\t\treturn runFlow(provider, options);\n\t\t}\n\t\tthrow error;\n\t}\n}\n\n/**\n * Auth provider for `StreamableHttpTransport`. After a 401 it refreshes the tokens, or throws\n * `McpOAuthAuthorizationRequiredError` when the user has to authorize (again). Concurrent 401s share\n * one refresh, and a request whose token was already replaced is just retried: with rotating refresh\n * tokens, a second refresh with the old refresh token would fail and discard the new grant.\n */\nexport function adaptOAuthProvider(provider: OAuthClientProvider): AuthProvider {\n\tlet inFlight: Promise<void> | undefined;\n\treturn {\n\t\ttoken: async () => (await provider.tokens())?.access_token,\n\t\tonUnauthorized: async (context: UnauthorizedContext) => {\n\t\t\tconst challenge = parseWwwAuthenticate(context.response.headers.get(\"www-authenticate\"));\n\t\t\tconst insufficientScope = challenge.error === \"insufficient_scope\";\n\t\t\tif (!insufficientScope && !inFlight && context.token !== undefined) {\n\t\t\t\tconst current = (await provider.tokens())?.access_token;\n\t\t\t\tif (current !== undefined && current !== context.token) return;\n\t\t\t}\n\t\t\tinFlight ??= Promise.resolve(insufficientScope ? provider.tokens() : undefined)\n\t\t\t\t.then((granted) =>\n\t\t\t\t\tauthorizeMcp(provider, {\n\t\t\t\t\t\tserverUrl: context.serverUrl,\n\t\t\t\t\t\tresourceMetadataUrl: challenge.resourceMetadataUrl,\n\t\t\t\t\t\tscope: insufficientScope ? stepUpScope(granted?.scope, challenge.scope) : challenge.scope,\n\t\t\t\t\t\tfetch: context.fetch,\n\t\t\t\t\t\tskipRefresh: insufficientScope,\n\t\t\t\t\t}),\n\t\t\t\t)\n\t\t\t\t.then((result) => {\n\t\t\t\t\tif (result === \"REDIRECT\") throw new McpOAuthAuthorizationRequiredError();\n\t\t\t\t})\n\t\t\t\t.finally(() => {\n\t\t\t\t\tinFlight = undefined;\n\t\t\t\t});\n\t\t\tawait inFlight;\n\t\t},\n\t};\n}\n"]}
@@ -1,7 +1,11 @@
1
+ export { createMcpAuthProvider, type McpAuthProvider } from "./auth-provider.ts";
1
2
  export { type OAuthCallback, type OAuthCallbackPage, OAuthCallbackServer, type OAuthCallbackServerOptions, } from "./callback.ts";
3
+ export type { McpClientMetadataDocuments, McpOAuthClientOptions, McpOAuthServerStore, McpOAuthSettings, } from "./client-settings.ts";
2
4
  export { buildAuthorizationServerDiscoveryUrls, discoverAuthorizationServerMetadata, discoverOAuthServerInfo, discoverProtectedResourceMetadata, parseWwwAuthenticate, resourceUrlFromServerUrl, selectResource, } from "./discovery.ts";
3
- export { McpOAuthAuthorizationRequiredError, OAuthError, OAuthInsecureEndpointError, OAuthIssuerMismatchError, OAuthRegistrationError, } from "./errors.ts";
5
+ export { McpOAuthAuthorizationRequiredError, McpRefreshLockBusyError, OAuthError, OAuthInsecureEndpointError, OAuthIssuerMismatchError, OAuthRegistrationError, } from "./errors.ts";
4
6
  export { type AddClientAuthentication, adaptOAuthProvider, authorizeMcp, exchangeAuthorizationCode, type OAuthClientMetadataDocument, type OAuthClientProvider, type OAuthFlowOptions, type OAuthFlowResult, refreshAuthorization, registerClient, startAuthorization, stepUpScope, type TokenRequestOptions, } from "./flow.ts";
7
+ export { listenForLoopbackSignIn, type McpLoopbackCallback, responseFromRedirectUrl, waitForLoopbackSignIn, } from "./loopback.ts";
5
8
  export { McpOAuthProvider, type McpOAuthProviderOptions, type McpOAuthState, type McpOAuthStateStore, MemoryOAuthStateStore, } from "./provider.ts";
9
+ export { completeMcpSignIn, type McpAuthorizationResponse, McpSignInCancelledError, type McpSignInOptions, type McpSignInRedirect, type McpSignInStart, startMcpSignIn, } from "./sign-in.ts";
6
10
  export type { AuthorizationServerMetadata, OAuthChallenge, OAuthClientInformation, OAuthClientInformationFull, OAuthClientInformationMixed, OAuthClientMetadata, OAuthDiscoveryState, OAuthProtectedResourceMetadata, OAuthServerInfo, OAuthTokens, } from "./types.ts";
7
11
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/oauth/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,aAAa,EAClB,KAAK,iBAAiB,EACtB,mBAAmB,EACnB,KAAK,0BAA0B,GAC/B,MAAM,eAAe,CAAC;AACvB,OAAO,EACN,qCAAqC,EACrC,mCAAmC,EACnC,uBAAuB,EACvB,iCAAiC,EACjC,oBAAoB,EACpB,wBAAwB,EACxB,cAAc,GACd,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACN,kCAAkC,EAClC,UAAU,EACV,0BAA0B,EAC1B,wBAAwB,EACxB,sBAAsB,GACtB,MAAM,aAAa,CAAC;AACrB,OAAO,EACN,KAAK,uBAAuB,EAC5B,kBAAkB,EAClB,YAAY,EACZ,yBAAyB,EACzB,KAAK,2BAA2B,EAChC,KAAK,mBAAmB,EACxB,KAAK,gBAAgB,EACrB,KAAK,eAAe,EACpB,oBAAoB,EACpB,cAAc,EACd,kBAAkB,EAClB,WAAW,EACX,KAAK,mBAAmB,GACxB,MAAM,WAAW,CAAC;AACnB,OAAO,EACN,gBAAgB,EAChB,KAAK,uBAAuB,EAC5B,KAAK,aAAa,EAClB,KAAK,kBAAkB,EACvB,qBAAqB,GACrB,MAAM,eAAe,CAAC;AACvB,YAAY,EACX,2BAA2B,EAC3B,cAAc,EACd,sBAAsB,EACtB,0BAA0B,EAC1B,2BAA2B,EAC3B,mBAAmB,EACnB,mBAAmB,EACnB,8BAA8B,EAC9B,eAAe,EACf,WAAW,GACX,MAAM,YAAY,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/oauth/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,KAAK,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACjF,OAAO,EACN,KAAK,aAAa,EAClB,KAAK,iBAAiB,EACtB,mBAAmB,EACnB,KAAK,0BAA0B,GAC/B,MAAM,eAAe,CAAC;AACvB,YAAY,EACX,0BAA0B,EAC1B,qBAAqB,EACrB,mBAAmB,EACnB,gBAAgB,GAChB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACN,qCAAqC,EACrC,mCAAmC,EACnC,uBAAuB,EACvB,iCAAiC,EACjC,oBAAoB,EACpB,wBAAwB,EACxB,cAAc,GACd,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACN,kCAAkC,EAClC,uBAAuB,EACvB,UAAU,EACV,0BAA0B,EAC1B,wBAAwB,EACxB,sBAAsB,GACtB,MAAM,aAAa,CAAC;AACrB,OAAO,EACN,KAAK,uBAAuB,EAC5B,kBAAkB,EAClB,YAAY,EACZ,yBAAyB,EACzB,KAAK,2BAA2B,EAChC,KAAK,mBAAmB,EACxB,KAAK,gBAAgB,EACrB,KAAK,eAAe,EACpB,oBAAoB,EACpB,cAAc,EACd,kBAAkB,EAClB,WAAW,EACX,KAAK,mBAAmB,GACxB,MAAM,WAAW,CAAC;AACnB,OAAO,EACN,uBAAuB,EACvB,KAAK,mBAAmB,EACxB,uBAAuB,EACvB,qBAAqB,GACrB,MAAM,eAAe,CAAC;AACvB,OAAO,EACN,gBAAgB,EAChB,KAAK,uBAAuB,EAC5B,KAAK,aAAa,EAClB,KAAK,kBAAkB,EACvB,qBAAqB,GACrB,MAAM,eAAe,CAAC;AACvB,OAAO,EACN,iBAAiB,EACjB,KAAK,wBAAwB,EAC7B,uBAAuB,EACvB,KAAK,gBAAgB,EACrB,KAAK,iBAAiB,EACtB,KAAK,cAAc,EACnB,cAAc,GACd,MAAM,cAAc,CAAC;AACtB,YAAY,EACX,2BAA2B,EAC3B,cAAc,EACd,sBAAsB,EACtB,0BAA0B,EAC1B,2BAA2B,EAC3B,mBAAmB,EACnB,mBAAmB,EACnB,8BAA8B,EAC9B,eAAe,EACf,WAAW,GACX,MAAM,YAAY,CAAC"}
@@ -1,6 +1,9 @@
1
+ export { createMcpAuthProvider } from "./auth-provider.js";
1
2
  export { OAuthCallbackServer, } from "./callback.js";
2
3
  export { buildAuthorizationServerDiscoveryUrls, discoverAuthorizationServerMetadata, discoverOAuthServerInfo, discoverProtectedResourceMetadata, parseWwwAuthenticate, resourceUrlFromServerUrl, selectResource, } from "./discovery.js";
3
- export { McpOAuthAuthorizationRequiredError, OAuthError, OAuthInsecureEndpointError, OAuthIssuerMismatchError, OAuthRegistrationError, } from "./errors.js";
4
+ export { McpOAuthAuthorizationRequiredError, McpRefreshLockBusyError, OAuthError, OAuthInsecureEndpointError, OAuthIssuerMismatchError, OAuthRegistrationError, } from "./errors.js";
4
5
  export { adaptOAuthProvider, authorizeMcp, exchangeAuthorizationCode, refreshAuthorization, registerClient, startAuthorization, stepUpScope, } from "./flow.js";
6
+ export { listenForLoopbackSignIn, responseFromRedirectUrl, waitForLoopbackSignIn, } from "./loopback.js";
5
7
  export { McpOAuthProvider, MemoryOAuthStateStore, } from "./provider.js";
8
+ export { completeMcpSignIn, McpSignInCancelledError, startMcpSignIn, } from "./sign-in.js";
6
9
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/oauth/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,mBAAmB,GAEnB,MAAM,eAAe,CAAC;AACvB,OAAO,EACN,qCAAqC,EACrC,mCAAmC,EACnC,uBAAuB,EACvB,iCAAiC,EACjC,oBAAoB,EACpB,wBAAwB,EACxB,cAAc,GACd,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACN,kCAAkC,EAClC,UAAU,EACV,0BAA0B,EAC1B,wBAAwB,EACxB,sBAAsB,GACtB,MAAM,aAAa,CAAC;AACrB,OAAO,EAEN,kBAAkB,EAClB,YAAY,EACZ,yBAAyB,EAKzB,oBAAoB,EACpB,cAAc,EACd,kBAAkB,EAClB,WAAW,GAEX,MAAM,WAAW,CAAC;AACnB,OAAO,EACN,gBAAgB,EAIhB,qBAAqB,GACrB,MAAM,eAAe,CAAC","sourcesContent":["export {\n\ttype OAuthCallback,\n\ttype OAuthCallbackPage,\n\tOAuthCallbackServer,\n\ttype OAuthCallbackServerOptions,\n} from \"./callback.ts\";\nexport {\n\tbuildAuthorizationServerDiscoveryUrls,\n\tdiscoverAuthorizationServerMetadata,\n\tdiscoverOAuthServerInfo,\n\tdiscoverProtectedResourceMetadata,\n\tparseWwwAuthenticate,\n\tresourceUrlFromServerUrl,\n\tselectResource,\n} from \"./discovery.ts\";\nexport {\n\tMcpOAuthAuthorizationRequiredError,\n\tOAuthError,\n\tOAuthInsecureEndpointError,\n\tOAuthIssuerMismatchError,\n\tOAuthRegistrationError,\n} from \"./errors.ts\";\nexport {\n\ttype AddClientAuthentication,\n\tadaptOAuthProvider,\n\tauthorizeMcp,\n\texchangeAuthorizationCode,\n\ttype OAuthClientMetadataDocument,\n\ttype OAuthClientProvider,\n\ttype OAuthFlowOptions,\n\ttype OAuthFlowResult,\n\trefreshAuthorization,\n\tregisterClient,\n\tstartAuthorization,\n\tstepUpScope,\n\ttype TokenRequestOptions,\n} from \"./flow.ts\";\nexport {\n\tMcpOAuthProvider,\n\ttype McpOAuthProviderOptions,\n\ttype McpOAuthState,\n\ttype McpOAuthStateStore,\n\tMemoryOAuthStateStore,\n} from \"./provider.ts\";\nexport type {\n\tAuthorizationServerMetadata,\n\tOAuthChallenge,\n\tOAuthClientInformation,\n\tOAuthClientInformationFull,\n\tOAuthClientInformationMixed,\n\tOAuthClientMetadata,\n\tOAuthDiscoveryState,\n\tOAuthProtectedResourceMetadata,\n\tOAuthServerInfo,\n\tOAuthTokens,\n} from \"./types.ts\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/oauth/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAwB,MAAM,oBAAoB,CAAC;AACjF,OAAO,EAGN,mBAAmB,GAEnB,MAAM,eAAe,CAAC;AAOvB,OAAO,EACN,qCAAqC,EACrC,mCAAmC,EACnC,uBAAuB,EACvB,iCAAiC,EACjC,oBAAoB,EACpB,wBAAwB,EACxB,cAAc,GACd,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACN,kCAAkC,EAClC,uBAAuB,EACvB,UAAU,EACV,0BAA0B,EAC1B,wBAAwB,EACxB,sBAAsB,GACtB,MAAM,aAAa,CAAC;AACrB,OAAO,EAEN,kBAAkB,EAClB,YAAY,EACZ,yBAAyB,EAKzB,oBAAoB,EACpB,cAAc,EACd,kBAAkB,EAClB,WAAW,GAEX,MAAM,WAAW,CAAC;AACnB,OAAO,EACN,uBAAuB,EAEvB,uBAAuB,EACvB,qBAAqB,GACrB,MAAM,eAAe,CAAC;AACvB,OAAO,EACN,gBAAgB,EAIhB,qBAAqB,GACrB,MAAM,eAAe,CAAC;AACvB,OAAO,EACN,iBAAiB,EAEjB,uBAAuB,EAIvB,cAAc,GACd,MAAM,cAAc,CAAC","sourcesContent":["export { createMcpAuthProvider, type McpAuthProvider } from \"./auth-provider.ts\";\nexport {\n\ttype OAuthCallback,\n\ttype OAuthCallbackPage,\n\tOAuthCallbackServer,\n\ttype OAuthCallbackServerOptions,\n} from \"./callback.ts\";\nexport type {\n\tMcpClientMetadataDocuments,\n\tMcpOAuthClientOptions,\n\tMcpOAuthServerStore,\n\tMcpOAuthSettings,\n} from \"./client-settings.ts\";\nexport {\n\tbuildAuthorizationServerDiscoveryUrls,\n\tdiscoverAuthorizationServerMetadata,\n\tdiscoverOAuthServerInfo,\n\tdiscoverProtectedResourceMetadata,\n\tparseWwwAuthenticate,\n\tresourceUrlFromServerUrl,\n\tselectResource,\n} from \"./discovery.ts\";\nexport {\n\tMcpOAuthAuthorizationRequiredError,\n\tMcpRefreshLockBusyError,\n\tOAuthError,\n\tOAuthInsecureEndpointError,\n\tOAuthIssuerMismatchError,\n\tOAuthRegistrationError,\n} from \"./errors.ts\";\nexport {\n\ttype AddClientAuthentication,\n\tadaptOAuthProvider,\n\tauthorizeMcp,\n\texchangeAuthorizationCode,\n\ttype OAuthClientMetadataDocument,\n\ttype OAuthClientProvider,\n\ttype OAuthFlowOptions,\n\ttype OAuthFlowResult,\n\trefreshAuthorization,\n\tregisterClient,\n\tstartAuthorization,\n\tstepUpScope,\n\ttype TokenRequestOptions,\n} from \"./flow.ts\";\nexport {\n\tlistenForLoopbackSignIn,\n\ttype McpLoopbackCallback,\n\tresponseFromRedirectUrl,\n\twaitForLoopbackSignIn,\n} from \"./loopback.ts\";\nexport {\n\tMcpOAuthProvider,\n\ttype McpOAuthProviderOptions,\n\ttype McpOAuthState,\n\ttype McpOAuthStateStore,\n\tMemoryOAuthStateStore,\n} from \"./provider.ts\";\nexport {\n\tcompleteMcpSignIn,\n\ttype McpAuthorizationResponse,\n\tMcpSignInCancelledError,\n\ttype McpSignInOptions,\n\ttype McpSignInRedirect,\n\ttype McpSignInStart,\n\tstartMcpSignIn,\n} from \"./sign-in.ts\";\nexport type {\n\tAuthorizationServerMetadata,\n\tOAuthChallenge,\n\tOAuthClientInformation,\n\tOAuthClientInformationFull,\n\tOAuthClientInformationMixed,\n\tOAuthClientMetadata,\n\tOAuthDiscoveryState,\n\tOAuthProtectedResourceMetadata,\n\tOAuthServerInfo,\n\tOAuthTokens,\n} from \"./types.ts\";\n"]}
@@ -0,0 +1,51 @@
1
+ /**
2
+ * How the authorization response of a sign-in reaches a local application: a loopback callback server
3
+ * the browser redirects to, or a redirect URL the user pastes from the browser address bar.
4
+ */
5
+ import { type OAuthCallbackPage, OAuthCallbackServer } from "./callback.ts";
6
+ import { type McpClientMetadataDocuments, type McpOAuthSettings } from "./client-settings.ts";
7
+ import type { McpOAuthStateStore } from "./provider.ts";
8
+ import { type McpAuthorizationResponse, type McpSignInRedirect } from "./sign-in.ts";
9
+ /** A loopback callback server and the redirect URI it serves. */
10
+ export interface McpLoopbackCallback {
11
+ callback: OAuthCallbackServer;
12
+ /** Pass to `startMcpSignIn` and `completeMcpSignIn`. */
13
+ redirectUrl: string;
14
+ }
15
+ /**
16
+ * Listen for the authorization response of a sign-in on loopback, where `settings` say: `callbackUrl`
17
+ * and `callbackPort`, else the port of the stored client's redirect URI (so that client stays valid) or
18
+ * a free one. Pass the sign-in's `clientMetadataDocuments`, so the callback server also serves the
19
+ * server-specific redirect URI. Close the callback server when the sign-in ends.
20
+ */
21
+ export declare function listenForLoopbackSignIn(options: {
22
+ serverUrl: string;
23
+ store: McpOAuthStateStore;
24
+ settings: McpOAuthSettings;
25
+ clientMetadataDocuments?: McpClientMetadataDocuments;
26
+ /** Renders the browser page after the redirect. Default: plain text. */
27
+ renderPage?: (page: OAuthCallbackPage) => string;
28
+ }): Promise<McpLoopbackCallback>;
29
+ /**
30
+ * Wait for the authorization response on a loopback callback server, or for a redirect URL the user
31
+ * pastes from the browser address bar, whichever comes first. Aborting `signal` stops the wait with
32
+ * `McpSignInCancelledError`.
33
+ */
34
+ export declare function waitForLoopbackSignIn(options: {
35
+ callback: OAuthCallbackServer;
36
+ /** The `redirect` result of `startMcpSignIn`. */
37
+ authorization: McpSignInRedirect;
38
+ /**
39
+ * Ask for the redirect URL, for when the browser cannot reach the loopback callback (for example over
40
+ * SSH). Aborted once the callback arrives or the sign-in is cancelled. Resolving to `undefined` or an
41
+ * empty string cancels the sign-in.
42
+ */
43
+ promptForRedirectUrl?: (signal: AbortSignal) => Promise<string | undefined>;
44
+ signal?: AbortSignal;
45
+ }): Promise<McpAuthorizationResponse>;
46
+ /**
47
+ * The authorization response in a redirect URL the user pasted from the browser address bar. Fails when
48
+ * the URL is not on the sign-in's redirect URI, carries another `state`, or reports an error.
49
+ */
50
+ export declare function responseFromRedirectUrl(input: string, authorization: Pick<McpSignInRedirect, "state" | "redirectUrl">): McpAuthorizationResponse;
51
+ //# sourceMappingURL=loopback.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loopback.d.ts","sourceRoot":"","sources":["../../src/oauth/loopback.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,KAAK,iBAAiB,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAC5E,OAAO,EAEN,KAAK,0BAA0B,EAC/B,KAAK,gBAAgB,EAIrB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AACxD,OAAO,EAEN,KAAK,wBAAwB,EAE7B,KAAK,iBAAiB,EACtB,MAAM,cAAc,CAAC;AAEtB,iEAAiE;AACjE,MAAM,WAAW,mBAAmB;IACnC,QAAQ,EAAE,mBAAmB,CAAC;IAC9B,wDAAwD;IACxD,WAAW,EAAE,MAAM,CAAC;CACpB;AAED;;;;;GAKG;AACH,wBAAsB,uBAAuB,CAAC,OAAO,EAAE;IACtD,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,kBAAkB,CAAC;IAC1B,QAAQ,EAAE,gBAAgB,CAAC;IAC3B,uBAAuB,CAAC,EAAE,0BAA0B,CAAC;IACrD,wEAAwE;IACxE,UAAU,CAAC,EAAE,CAAC,IAAI,EAAE,iBAAiB,KAAK,MAAM,CAAC;CACjD,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAuB/B;AAED;;;;GAIG;AACH,wBAAsB,qBAAqB,CAAC,OAAO,EAAE;IACpD,QAAQ,EAAE,mBAAmB,CAAC;IAC9B,iDAAiD;IACjD,aAAa,EAAE,iBAAiB,CAAC;IACjC;;;;OAIG;IACH,oBAAoB,CAAC,EAAE,CAAC,MAAM,EAAE,WAAW,KAAK,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;IAC5E,MAAM,CAAC,EAAE,WAAW,CAAC;CACrB,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAwBpC;AAED;;;GAGG;AACH,wBAAgB,uBAAuB,CACtC,KAAK,EAAE,MAAM,EACb,aAAa,EAAE,IAAI,CAAC,iBAAiB,EAAE,OAAO,GAAG,aAAa,CAAC,GAC7D,wBAAwB,CAoB1B"}
@@ -0,0 +1,98 @@
1
+ /**
2
+ * How the authorization response of a sign-in reaches a local application: a loopback callback server
3
+ * the browser redirects to, or a redirect URL the user pastes from the browser address bar.
4
+ */
5
+ import { OAuthCallbackServer } from "./callback.js";
6
+ import { loopbackSettings, offersClientMetadataDocument, registeredRedirectUrls, serverSpecificPath, } from "./client-settings.js";
7
+ import { cancellable, McpSignInCancelledError, } from "./sign-in.js";
8
+ /**
9
+ * Listen for the authorization response of a sign-in on loopback, where `settings` say: `callbackUrl`
10
+ * and `callbackPort`, else the port of the stored client's redirect URI (so that client stays valid) or
11
+ * a free one. Pass the sign-in's `clientMetadataDocuments`, so the callback server also serves the
12
+ * server-specific redirect URI. Close the callback server when the sign-in ends.
13
+ */
14
+ export async function listenForLoopbackSignIn(options) {
15
+ const { settings } = options;
16
+ const loopback = loopbackSettings(settings);
17
+ const registered = registeredRedirectUrls((await options.store.load())?.clientInformation)[0];
18
+ const port = loopback.port ?? (registered ? Number(new URL(registered).port) || undefined : undefined);
19
+ const offersDocument = offersClientMetadataDocument(settings, options.clientMetadataDocuments, loopback.url);
20
+ const listenOptions = {
21
+ host: loopback.host,
22
+ redirectHost: loopback.redirectHost,
23
+ path: loopback.path,
24
+ // The redirect URI of a server-specific Client ID Metadata Document.
25
+ extraPaths: offersDocument ? [serverSpecificPath(loopback.path, options.serverUrl)] : [],
26
+ renderPage: options.renderPage,
27
+ };
28
+ let callback;
29
+ try {
30
+ callback = await OAuthCallbackServer.listen({ ...listenOptions, port: port ?? 0 });
31
+ }
32
+ catch (error) {
33
+ // A configured port is required; the stored client's port is only preferred.
34
+ if (loopback.port !== undefined || port === undefined)
35
+ throw error;
36
+ callback = await OAuthCallbackServer.listen(listenOptions);
37
+ }
38
+ return { callback, redirectUrl: loopback.fixedRedirectUrl ?? callback.redirectUrl };
39
+ }
40
+ /**
41
+ * Wait for the authorization response on a loopback callback server, or for a redirect URL the user
42
+ * pastes from the browser address bar, whichever comes first. Aborting `signal` stops the wait with
43
+ * `McpSignInCancelledError`.
44
+ */
45
+ export async function waitForLoopbackSignIn(options) {
46
+ const { authorization } = options;
47
+ const controller = new AbortController();
48
+ const signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal;
49
+ const fromBrowser = options.callback.waitForCallback(authorization.state, new URL(authorization.redirectUrl).pathname);
50
+ const fromUser = options.promptForRedirectUrl
51
+ ? options.promptForRedirectUrl(signal).then((input) => {
52
+ if (!input?.trim())
53
+ throw new McpSignInCancelledError();
54
+ return responseFromRedirectUrl(input, authorization);
55
+ })
56
+ : new Promise((_, reject) => {
57
+ signal.addEventListener("abort", () => reject(new McpSignInCancelledError()), { once: true });
58
+ });
59
+ try {
60
+ return await cancellable(options.signal, () => Promise.race([fromBrowser, fromUser]));
61
+ }
62
+ finally {
63
+ // The losing side rejects once the prompt is aborted or the callback server closes.
64
+ controller.abort();
65
+ fromBrowser.catch(() => undefined);
66
+ fromUser.catch(() => undefined);
67
+ }
68
+ }
69
+ /**
70
+ * The authorization response in a redirect URL the user pasted from the browser address bar. Fails when
71
+ * the URL is not on the sign-in's redirect URI, carries another `state`, or reports an error.
72
+ */
73
+ export function responseFromRedirectUrl(input, authorization) {
74
+ let url;
75
+ try {
76
+ url = new URL(input.trim());
77
+ }
78
+ catch {
79
+ throw new Error("Expected the full redirect URL from the browser address bar");
80
+ }
81
+ const redirectUrl = new URL(authorization.redirectUrl);
82
+ // A server-specific redirect URI tells authorization servers apart, so it must match exactly.
83
+ if (url.origin !== redirectUrl.origin || url.pathname !== redirectUrl.pathname) {
84
+ throw new Error("The redirect URL does not match this sign-in's redirect URI");
85
+ }
86
+ const error = url.searchParams.get("error");
87
+ if (error)
88
+ throw new Error(url.searchParams.get("error_description") ?? error);
89
+ const state = url.searchParams.get("state");
90
+ if (state !== authorization.state)
91
+ throw new Error("The redirect URL belongs to a different sign-in");
92
+ const code = url.searchParams.get("code");
93
+ if (!code)
94
+ throw new Error("The redirect URL does not contain an authorization code");
95
+ const iss = url.searchParams.get("iss");
96
+ return { code, state, ...(iss ? { iss } : {}) };
97
+ }
98
+ //# sourceMappingURL=loopback.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loopback.js","sourceRoot":"","sources":["../../src/oauth/loopback.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAA0B,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAC5E,OAAO,EACN,gBAAgB,EAGhB,4BAA4B,EAC5B,sBAAsB,EACtB,kBAAkB,GAClB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EACN,WAAW,EAEX,uBAAuB,GAEvB,MAAM,cAAc,CAAC;AAStB;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAAC,OAO7C;IACA,MAAM,EAAE,QAAQ,EAAE,GAAG,OAAO,C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AAC,CAAC;IACtG,MAAM,IAAI,GAAG,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IAC1C,IAAI,CAAC,IAAI;QAAE,MAAM,IAAI,KAAK,CAAC,yDAAyD,CAAC,CAAC;IACtF,MAAM,GAAG,GAAG,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACxC,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC;AACjD,CAAC","sourcesContent":["/**\n * How the authorization response of a sign-in reaches a local application: a loopback callback server\n * the browser redirects to, or a redirect URL the user pastes from the browser address bar.\n */\n\nimport { type OAuthCallbackPage, OAuthCallbackServer } from \"./callback.ts\";\nimport {\n\tloopbackSettings,\n\ttype McpClientMetadataDocuments,\n\ttype McpOAuthSettings,\n\toffersClientMetadataDocument,\n\tregisteredRedirectUrls,\n\tserverSpecificPath,\n} from \"./client-settings.ts\";\nimport type { McpOAuthStateStore } from \"./provider.ts\";\nimport {\n\tcancellable,\n\ttype McpAuthorizationResponse,\n\tMcpSignInCancelledError,\n\ttype McpSignInRedirect,\n} from \"./sign-in.ts\";\n\n/** A loopback callback server and the redirect URI it serves. */\nexport interface McpLoopbackCallback {\n\tcallback: OAuthCallbackServer;\n\t/** Pass to `startMcpSignIn` and `completeMcpSignIn`. */\n\tredirectUrl: string;\n}\n\n/**\n * Listen for the authorization response of a sign-in on loopback, where `settings` say: `callbackUrl`\n * and `callbackPort`, else the port of the stored client's redirect URI (so that client stays valid) or\n * a free one. Pass the sign-in's `clientMetadataDocuments`, so the callback server also serves the\n * server-specific redirect URI. Close the callback server when the sign-in ends.\n */\nexport async function listenForLoopbackSignIn(options: {\n\tserverUrl: string;\n\tstore: McpOAuthStateStore;\n\tsettings: McpOAuthSettings;\n\tclientMetadataDocuments?: McpClientMetadataDocuments;\n\t/** Renders the browser page after the redirect. Default: plain text. */\n\trenderPage?: (page: OAuthCallbackPage) => string;\n}): Promise<McpLoopbackCallback> {\n\tconst { settings } = options;\n\tconst loopback = loopbackSettings(settings);\n\tconst registered = registeredRedirectUrls((await options.store.load())?.clientInformation)[0];\n\tconst port = loopback.port ?? (registered ? Number(new URL(registered).port) || undefined : undefined);\n\tconst offersDocument = offersClientMetadataDocument(settings, options.clientMetadataDocuments, loopback.url);\n\tconst listenOptions = {\n\t\thost: loopback.host,\n\t\tredirectHost: loopback.redirectHost,\n\t\tpath: loopback.path,\n\t\t// The redirect URI of a server-specific Client ID Metadata Document.\n\t\textraPaths: offersDocument ? [serverSpecificPath(loopback.path, options.serverUrl)] : [],\n\t\trenderPage: options.renderPage,\n\t};\n\tlet callback: OAuthCallbackServer;\n\ttry {\n\t\tcallback = await OAuthCallbackServer.listen({ ...listenOptions, port: port ?? 0 });\n\t} catch (error) {\n\t\t// A configured port is required; the stored client's port is only preferred.\n\t\tif (loopback.port !== undefined || port === undefined) throw error;\n\t\tcallback = await OAuthCallbackServer.listen(listenOptions);\n\t}\n\treturn { callback, redirectUrl: loopback.fixedRedirectUrl ?? callback.redirectUrl };\n}\n\n/**\n * Wait for the authorization response on a loopback callback server, or for a redirect URL the user\n * pastes from the browser address bar, whichever comes first. Aborting `signal` stops the wait with\n * `McpSignInCancelledError`.\n */\nexport async function waitForLoopbackSignIn(options: {\n\tcallback: OAuthCallbackServer;\n\t/** The `redirect` result of `startMcpSignIn`. */\n\tauthorization: McpSignInRedirect;\n\t/**\n\t * Ask for the redirect URL, for when the browser cannot reach the loopback callback (for example over\n\t * SSH). Aborted once the callback arrives or the sign-in is cancelled. Resolving to `undefined` or an\n\t * empty string cancels the sign-in.\n\t */\n\tpromptForRedirectUrl?: (signal: AbortSignal) => Promise<string | undefined>;\n\tsignal?: AbortSignal;\n}): Promise<McpAuthorizationResponse> {\n\tconst { authorization } = options;\n\tconst controller = new AbortController();\n\tconst signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal;\n\tconst fromBrowser = options.callback.waitForCallback(\n\t\tauthorization.state,\n\t\tnew URL(authorization.redirectUrl).pathname,\n\t);\n\tconst fromUser = options.promptForRedirectUrl\n\t\t? options.promptForRedirectUrl(signal).then((input) => {\n\t\t\t\tif (!input?.trim()) throw new McpSignInCancelledError();\n\t\t\t\treturn responseFromRedirectUrl(input, authorization);\n\t\t\t})\n\t\t: new Promise<never>((_, reject) => {\n\t\t\t\tsignal.addEventListener(\"abort\", () => reject(new McpSignInCancelledError()), { once: true });\n\t\t\t});\n\ttry {\n\t\treturn await cancellable(options.signal, () => Promise.race([fromBrowser, fromUser]));\n\t} finally {\n\t\t// The losing side rejects once the prompt is aborted or the callback server closes.\n\t\tcontroller.abort();\n\t\tfromBrowser.catch(() => undefined);\n\t\tfromUser.catch(() => undefined);\n\t}\n}\n\n/**\n * The authorization response in a redirect URL the user pasted from the browser address bar. Fails when\n * the URL is not on the sign-in's redirect URI, carries another `state`, or reports an error.\n */\nexport function responseFromRedirectUrl(\n\tinput: string,\n\tauthorization: Pick<McpSignInRedirect, \"state\" | \"redirectUrl\">,\n): McpAuthorizationResponse {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(input.trim());\n\t} catch {\n\t\tthrow new Error(\"Expected the full redirect URL from the browser address bar\");\n\t}\n\tconst redirectUrl = new URL(authorization.redirectUrl);\n\t// A server-specific redirect URI tells authorization servers apart, so it must match exactly.\n\tif (url.origin !== redirectUrl.origin || url.pathname !== redirectUrl.pathname) {\n\t\tthrow new Error(\"The redirect URL does not match this sign-in's redirect URI\");\n\t}\n\tconst error = url.searchParams.get(\"error\");\n\tif (error) throw new Error(url.searchParams.get(\"error_description\") ?? error);\n\tconst state = url.searchParams.get(\"state\");\n\tif (state !== authorization.state) throw new Error(\"The redirect URL belongs to a different sign-in\");\n\tconst code = url.searchParams.get(\"code\");\n\tif (!code) throw new Error(\"The redirect URL does not contain an authorization code\");\n\tconst iss = url.searchParams.get(\"iss\");\n\treturn { code, state, ...(iss ? { iss } : {}) };\n}\n"]}