@dudko.dev/agent-web 0.0.36 → 0.0.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mcp.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import {
2
- IndexedDBVault
3
- } from "./chunk-CPSDKXO6.js";
2
+ IndexedDBVault,
3
+ createLogger
4
+ } from "./chunk-T6LZW7ML.js";
5
+ import "./chunk-CTXDKSDD.js";
4
6
 
5
7
  // src/mcp/http.ts
6
8
  import {
@@ -15,7 +17,9 @@ import { ToolListChangedNotificationSchema } from "@modelcontextprotocol/sdk/typ
15
17
  import { dynamicTool, jsonSchema } from "ai";
16
18
 
17
19
  // src/mcp/oauth.ts
18
- import { auth } from "@modelcontextprotocol/sdk/client/auth.js";
20
+ import {
21
+ auth
22
+ } from "@modelcontextprotocol/sdk/client/auth.js";
19
23
  var VaultOAuthStorage = class {
20
24
  vault;
21
25
  constructor(opts = {}) {
@@ -61,11 +65,48 @@ var assertSecureOAuthUrl = (url, label = "MCP server") => {
61
65
  `${label}: MCP OAuth requires https (or a loopback host) - refusing to send tokens to "${url}"`
62
66
  );
63
67
  };
68
+ var assertClientMetadataUrl = (url, label = "MCP OAuth") => {
69
+ let parsed;
70
+ try {
71
+ parsed = new URL(url);
72
+ } catch {
73
+ throw new Error(`${label}: clientMetadataUrl "${url}" is not a valid URL`);
74
+ }
75
+ if (parsed.protocol === "https:" && parsed.pathname !== "/") return;
76
+ throw new Error(
77
+ `${label}: clientMetadataUrl requires https and a non-root path - refusing "${url}"`
78
+ );
79
+ };
80
+ var checkAuthorizationResponseIssuer = (iss, discoveryState, clientIssuer) => {
81
+ const metadata = discoveryState?.authorizationServerMetadata;
82
+ const expected = discoveryState ? metadata?.issuer ?? String(discoveryState.authorizationServerUrl) : clientIssuer;
83
+ if (iss === void 0) {
84
+ if (metadata?.authorization_response_iss_parameter_supported === true) {
85
+ throw new Error(
86
+ 'Authorization response carried no "iss", which this authorization server says it always sends; refusing to exchange the code (possible mix-up attack)'
87
+ );
88
+ }
89
+ return;
90
+ }
91
+ if (expected !== void 0 && iss !== expected) {
92
+ throw new Error(
93
+ `Authorization response came from issuer "${iss}", expected "${expected}"; refusing to exchange the code (possible mix-up attack)`
94
+ );
95
+ }
96
+ };
64
97
  var randomToken = () => {
65
98
  const bytes = new Uint8Array(32);
66
99
  globalThis.crypto.getRandomValues(bytes);
67
100
  return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
68
101
  };
102
+ var applicationTypeFor = (redirectUrl) => {
103
+ try {
104
+ const u = new URL(redirectUrl);
105
+ return u.protocol === "https:" && !LOOPBACK_HOSTS.has(u.hostname) ? "web" : "native";
106
+ } catch {
107
+ return "native";
108
+ }
109
+ };
69
110
  var BrowserOAuthProvider = class {
70
111
  /** Set when the SDK asks for an authorization redirect; read it in your UI. */
71
112
  authorizationUrl;
@@ -74,10 +115,15 @@ var BrowserOAuthProvider = class {
74
115
  ns;
75
116
  _redirectUrl;
76
117
  _clientMetadata;
118
+ _clientMetadataUrl;
77
119
  skewMs;
78
120
  onRedirect;
79
121
  constructor(opts) {
80
122
  assertSecureOAuthUrl(opts.serverUrl);
123
+ if (opts.clientMetadataUrl !== void 0) {
124
+ assertClientMetadataUrl(opts.clientMetadataUrl);
125
+ this._clientMetadataUrl = opts.clientMetadataUrl;
126
+ }
81
127
  this.serverUrl = opts.serverUrl;
82
128
  this.storage = opts.storage ?? new VaultOAuthStorage();
83
129
  this.ns = namespaceFor(opts.serverUrl);
@@ -92,6 +138,8 @@ var BrowserOAuthProvider = class {
92
138
  // Public client: a browser cannot hold a client_secret. PKCE is what
93
139
  // actually protects the code exchange.
94
140
  token_endpoint_auth_method: "none",
141
+ // By the redirect: an https page is 'web', a loopback one (local dev) is 'native'.
142
+ application_type: applicationTypeFor(this._redirectUrl),
95
143
  ...opts.scope ? { scope: opts.scope } : {},
96
144
  ...opts.clientMetadata
97
145
  };
@@ -102,6 +150,10 @@ var BrowserOAuthProvider = class {
102
150
  get clientMetadata() {
103
151
  return this._clientMetadata;
104
152
  }
153
+ /** The client ID metadata document URL (CIMD), when one was configured. */
154
+ get clientMetadataUrl() {
155
+ return this._clientMetadataUrl;
156
+ }
105
157
  key(suffix) {
106
158
  return `${this.ns}:${suffix}`;
107
159
  }
@@ -158,18 +210,36 @@ var BrowserOAuthProvider = class {
158
210
  }
159
211
  return v;
160
212
  }
213
+ /**
214
+ * What discovery found (the authorization server, its metadata, the resource
215
+ * metadata). The SDK reuses it instead of discovering again - after the
216
+ * redirect back too - and {@link finishMcpOAuth} reads the expected issuer
217
+ * from it.
218
+ */
219
+ async saveDiscoveryState(state) {
220
+ await this.storage.set(this.key("discovery"), JSON.stringify(state));
221
+ }
222
+ async discoveryState() {
223
+ const state = await this.readJSON("discovery");
224
+ if (!state || typeof state !== "object" || typeof state.authorizationServerUrl !== "string") {
225
+ return void 0;
226
+ }
227
+ return state;
228
+ }
161
229
  async redirectToAuthorization(url) {
162
230
  this.authorizationUrl = url;
163
231
  await this.onRedirect?.(url);
164
232
  }
165
233
  /**
166
234
  * Called by the SDK when the server rejects what we hold: `'tokens'` after an
167
- * `invalid_grant` (dead refresh token), `'client'` / `'all'` after an
168
- * `invalid_client` (the AS forgot our dynamic registration). Clearing lets
169
- * the SDK re-register and re-authorize without the user clearing site data.
235
+ * `invalid_grant` (dead refresh token), `'all'` after an `invalid_client`
236
+ * (the AS forgot our dynamic registration). `'client'`, `'verifier'` and
237
+ * `'discovery'` are in its type and handled the same way: one key each.
238
+ * Clearing lets the SDK re-discover, re-register and re-authorize without the
239
+ * user clearing site data.
170
240
  */
171
241
  async invalidateCredentials(scope) {
172
- const targets = scope === "all" ? ["tokens", "client", "verifier", "state"] : [scope];
242
+ const targets = scope === "all" ? ["tokens", "client", "verifier", "state", "discovery"] : [scope];
173
243
  await Promise.all(targets.map((t) => this.storage.delete(this.key(t))));
174
244
  }
175
245
  /** True when there is no access token, or it expires within the skew window. */
@@ -183,7 +253,7 @@ var BrowserOAuthProvider = class {
183
253
  async isAuthorized() {
184
254
  return await this.tokens() !== void 0;
185
255
  }
186
- /** Forget tokens, registration, verifier and state for this server. */
256
+ /** Forget tokens, registration, verifier, state and discovery for this server. */
187
257
  async reset() {
188
258
  this.authorizationUrl = void 0;
189
259
  await this.invalidateCredentials("all");
@@ -212,6 +282,7 @@ var readOAuthCallback = (input) => {
212
282
  return {
213
283
  code,
214
284
  state: params.get("state") ?? void 0,
285
+ iss: params.get("iss") ?? void 0,
215
286
  error,
216
287
  errorDescription: params.get("error_description") ?? void 0
217
288
  };
@@ -228,6 +299,11 @@ var finishMcpOAuth = async (provider, callback, opts = {}) => {
228
299
  if (!await provider.verifyState(callback.state)) {
229
300
  throw new Error("Authorization state mismatch; refusing to exchange the code (possible CSRF)");
230
301
  }
302
+ checkAuthorizationResponseIssuer(
303
+ callback.iss,
304
+ await provider.discoveryState(),
305
+ (await provider.clientInformation())?.issuer
306
+ );
231
307
  const result = await auth(provider, {
232
308
  serverUrl: provider.serverUrl,
233
309
  authorizationCode: callback.code,
@@ -294,6 +370,10 @@ var flattenContent = (content) => {
294
370
  if (allText) return parts.map((p) => p.text).join("\n");
295
371
  return parts.map((p) => p?.type === "text" && typeof p.text === "string" ? p.text : p);
296
372
  };
373
+ var asEnterpriseProvider = (provider) => {
374
+ const p = provider;
375
+ return typeof p.extension === "string" && typeof p.authorize === "function" && typeof p.transportFetch === "function" ? provider : void 0;
376
+ };
297
377
  var RefreshOnlyAbort = class extends Error {
298
378
  };
299
379
  var refreshOnly = (p) => ({
@@ -323,10 +403,20 @@ var refreshOnly = (p) => ({
323
403
  throw new RefreshOnlyAbort();
324
404
  }
325
405
  });
326
- var refreshIfExpired = async (provider, serverUrl, fetchFn, log, name) => {
406
+ var refreshIfExpired = async (provider, serverUrl, fetchFn, log, name, detailLog) => {
327
407
  const check = provider.isAccessTokenExpired;
328
408
  if (typeof check !== "function") return;
329
409
  if (!await check.call(provider)) return;
410
+ const enterprise = asEnterpriseProvider(provider);
411
+ if (enterprise) {
412
+ try {
413
+ await enterprise.authorize({ fetch: fetchFn, onLog: detailLog });
414
+ } catch (err) {
415
+ if (err?.hop !== "discovery") throw err;
416
+ log("info", `[mcp] ${name}: ${err instanceof Error ? err.message : String(err)}; continuing`);
417
+ }
418
+ return;
419
+ }
330
420
  const tokens = await provider.tokens();
331
421
  if (!tokens?.refresh_token) return;
332
422
  try {
@@ -409,20 +499,24 @@ var connectAndList = async (name, cfg, opts, log, onClient) => {
409
499
  );
410
500
  }
411
501
  assertSecureOAuthUrl(cfg.url, name);
412
- await refreshIfExpired(cfg.authProvider, cfg.url, cfg.fetch, log, name);
502
+ await refreshIfExpired(cfg.authProvider, cfg.url, cfg.fetch, log, name, opts.onLog);
413
503
  }
414
504
  const transport = new StreamableHTTPClientTransport(new URL(cfg.url), {
415
505
  requestInit: headers ? { headers } : void 0,
416
506
  authProvider: cfg.authProvider,
417
- fetch: cfg.fetch,
507
+ // The enterprise provider reports a refused grant itself: a short typed
508
+ // error for the caller, the server's words (redacted) to the log.
509
+ fetch: cfg.authProvider && asEnterpriseProvider(cfg.authProvider)?.transportFetch(cfg.fetch, opts.onLog) || cfg.fetch,
418
510
  reconnectionOptions: { ...DEFAULT_RECONNECTION, ...cfg.reconnection }
419
511
  });
420
512
  transport.onerror = (err) => log("warn", `[mcp] ${name}: transport error - ${err.message}`);
421
513
  transport.onclose = () => log("info", `[mcp] ${name}: transport closed`);
422
- const client = new Client({
423
- name: opts.clientName ?? "agent-web",
424
- version: opts.clientVersion ?? "0.0.0"
425
- });
514
+ const enterprise = cfg.authProvider ? asEnterpriseProvider(cfg.authProvider) : void 0;
515
+ const client = new Client(
516
+ { name: opts.clientName ?? "agent-web", version: opts.clientVersion ?? "0.0.0" },
517
+ // An extension is opt-in: it is declared only by the client that uses it.
518
+ enterprise ? { capabilities: { extensions: { [enterprise.extension]: {} } } } : void 0
519
+ );
426
520
  onClient(client);
427
521
  await client.connect(transport);
428
522
  if (opts.onToolsChanged) {
@@ -527,13 +621,761 @@ var connectMcpHttp = async (servers, opts = {}) => {
527
621
 
528
622
  // src/mcp/index.ts
529
623
  import { UnauthorizedError as UnauthorizedError2 } from "@modelcontextprotocol/sdk/client/auth.js";
624
+
625
+ // src/mcp/enterprise-oauth.ts
626
+ import { auth as auth3 } from "@modelcontextprotocol/sdk/client/auth.js";
627
+ var ENTERPRISE_MANAGED_AUTHORIZATION_EXTENSION = "io.modelcontextprotocol/enterprise-managed-authorization";
628
+ var GRANT_TOKEN_EXCHANGE = "urn:ietf:params:oauth:grant-type:token-exchange";
629
+ var GRANT_JWT_BEARER = "urn:ietf:params:oauth:grant-type:jwt-bearer";
630
+ var TOKEN_TYPE_ID_JAG = "urn:ietf:params:oauth:token-type:id-jag";
631
+ var TOKEN_TYPE_ID_TOKEN = "urn:ietf:params:oauth:token-type:id_token";
632
+ var CLIENT_ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
633
+ var CLIENT_ASSERTION_LIFETIME_SECONDS = 60;
634
+ var EnterpriseOAuthError = class extends Error {
635
+ hop;
636
+ /** The OAuth `error` code the server answered with, when it sent one. */
637
+ code;
638
+ constructor(hop, message, code) {
639
+ super(message);
640
+ this.name = "EnterpriseOAuthError";
641
+ this.hop = hop;
642
+ this.code = code;
643
+ }
644
+ };
645
+ var DEFAULT_SKEW_SECONDS2 = 30;
646
+ var namespaceFor2 = (serverUrl) => {
647
+ const u = new URL(serverUrl);
648
+ return `mcp-enterprise-oauth:${u.origin}${u.pathname.replace(/\/+$/, "")}${u.search}`;
649
+ };
650
+ var sameIssuer = (a, b) => a === b || a === `${b}/` || b === `${a}/`;
651
+ var stripFragment = (url) => {
652
+ const u = new URL(url);
653
+ u.hash = "";
654
+ return u.href;
655
+ };
656
+ var resourceCovers = (resource, serverUrl) => {
657
+ let published;
658
+ try {
659
+ published = new URL(resource);
660
+ } catch {
661
+ return false;
662
+ }
663
+ const requested = new URL(serverUrl);
664
+ if (published.origin !== requested.origin) {
665
+ return false;
666
+ }
667
+ const slashed = (p) => p.endsWith("/") ? p : `${p}/`;
668
+ return slashed(requested.pathname).startsWith(slashed(published.pathname));
669
+ };
670
+ var enterpriseGrantTarget = (serverUrl, state, expectedIssuer) => {
671
+ const refuse = (message) => {
672
+ throw new EnterpriseOAuthError("discovery", `Enterprise MCP authorization: ${message}`);
673
+ };
674
+ if (!state) {
675
+ return refuse("nothing is known about the authorization server of this MCP server yet");
676
+ }
677
+ const asUrl = String(state.authorizationServerUrl);
678
+ const metadata = state.authorizationServerMetadata;
679
+ const issuer = metadata?.issuer;
680
+ if (typeof issuer !== "string" || !issuer) {
681
+ return refuse(
682
+ `the authorization server "${asUrl}" published no metadata with an issuer, so there is no audience to ask the identity provider for`
683
+ );
684
+ }
685
+ if (!sameIssuer(issuer, asUrl)) {
686
+ return refuse(
687
+ `the metadata fetched for "${asUrl}" names another issuer ("${issuer}"); refusing to request a grant for it`
688
+ );
689
+ }
690
+ if (expectedIssuer !== void 0 && !sameIssuer(issuer, expectedIssuer)) {
691
+ return refuse(
692
+ `this MCP server points at the authorization server "${issuer}", expected "${expectedIssuer}"; refusing to send credentials there`
693
+ );
694
+ }
695
+ try {
696
+ assertSecureOAuthUrl(asUrl, "MCP authorization server");
697
+ if (typeof metadata?.token_endpoint === "string") {
698
+ assertSecureOAuthUrl(metadata.token_endpoint, "MCP authorization server token endpoint");
699
+ }
700
+ } catch (err) {
701
+ return refuse(err.message);
702
+ }
703
+ const published = state.resourceMetadata?.resource;
704
+ if (published !== void 0 && !resourceCovers(published, serverUrl)) {
705
+ return refuse(
706
+ `the protected resource "${published}" this server published does not cover "${serverUrl}"`
707
+ );
708
+ }
709
+ return {
710
+ audience: issuer,
711
+ resource: published ?? stripFragment(serverUrl),
712
+ // Handed out only here, after the issuer and the scheme checks above.
713
+ ...typeof metadata?.token_endpoint === "string" && metadata.token_endpoint ? { tokenEndpoint: metadata.token_endpoint } : {}
714
+ };
715
+ };
716
+ var printable = (value, max = 300) => {
717
+ if (typeof value !== "string") {
718
+ return void 0;
719
+ }
720
+ const clean = value.replace(/[^\x20-\x7e]+/g, " ").trim();
721
+ if (!clean) {
722
+ return void 0;
723
+ }
724
+ return clean.length > max ? `${clean.slice(0, max)}...` : clean;
725
+ };
726
+ var formEncode = (value) => new URLSearchParams({ v: value }).toString().slice(2);
727
+ var redact = (message, secrets) => {
728
+ let out = message;
729
+ for (const secret of secrets) {
730
+ if (!secret) {
731
+ continue;
732
+ }
733
+ const spellings = [secret, encodeURIComponent(secret), formEncode(secret)];
734
+ for (const spelling of new Set(spellings)) {
735
+ out = out.split(spelling).join("[redacted]");
736
+ }
737
+ }
738
+ return out;
739
+ };
740
+ var ALGORITHMS = [
741
+ "ES256",
742
+ "ES384",
743
+ "ES512",
744
+ "RS256",
745
+ "RS384",
746
+ "RS512",
747
+ "PS256",
748
+ "PS384",
749
+ "PS512"
750
+ ];
751
+ var base64Url = (bytes) => {
752
+ let binary = "";
753
+ for (const byte of bytes) {
754
+ binary += String.fromCharCode(byte);
755
+ }
756
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
757
+ };
758
+ var base64UrlJson = (value) => base64Url(new TextEncoder().encode(JSON.stringify(value)));
759
+ var isCryptoKey = (key) => typeof key.extractable === "boolean" && typeof key.algorithm === "object" && Array.isArray(key.usages);
760
+ var signAssertionInput = async (algorithm, privateKey, input) => {
761
+ const bits = algorithm.slice(2);
762
+ const hash = `SHA-${bits}`;
763
+ const family = algorithm.slice(0, 2);
764
+ const importAs = family === "ES" ? { name: "ECDSA", namedCurve: bits === "512" ? "P-521" : `P-${bits}` } : { name: family === "PS" ? "RSA-PSS" : "RSASSA-PKCS1-v1_5", hash };
765
+ const signAs = family === "ES" ? { name: "ECDSA", hash } : family === "PS" ? { name: "RSA-PSS", saltLength: Number(bits) / 8 } : { name: "RSASSA-PKCS1-v1_5" };
766
+ const { subtle } = globalThis.crypto;
767
+ let key;
768
+ if (isCryptoKey(privateKey)) {
769
+ key = privateKey;
770
+ const made = key.algorithm;
771
+ const fits = key.type === "private" && made.name === importAs.name && (family === "ES" ? made.namedCurve === importAs.namedCurve : made.hash?.name === hash);
772
+ if (!fits) {
773
+ throw new Error("key does not fit the algorithm");
774
+ }
775
+ } else {
776
+ if (typeof privateKey.d !== "string") {
777
+ throw new Error("not a private key");
778
+ }
779
+ const { alg: _alg, use: _use, key_ops: _ops, ...jwk } = privateKey;
780
+ key = await subtle.importKey("jwk", jwk, importAs, false, ["sign"]);
781
+ }
782
+ return new Uint8Array(await subtle.sign(signAs, key, new TextEncoder().encode(input)));
783
+ };
784
+ var keySecrets = (key) => {
785
+ if (key === void 0) {
786
+ return [];
787
+ }
788
+ const jwk = key;
789
+ return ["d", "p", "q", "dp", "dq", "qi", "k"].map((member) => jwk[member]).filter((v) => typeof v === "string" && v.length > 0);
790
+ };
791
+ var createClientAssertion = async (req) => {
792
+ const now = Math.floor(Date.now() / 1e3);
793
+ const header = {
794
+ alg: req.algorithm,
795
+ typ: req.type === "JWT" ? "JWT" : "client-authentication+jwt",
796
+ ...req.keyId ? { kid: req.keyId } : {}
797
+ };
798
+ const payload = {
799
+ iss: req.clientId,
800
+ sub: req.clientId,
801
+ aud: req.audience,
802
+ jti: globalThis.crypto.randomUUID(),
803
+ iat: now,
804
+ exp: now + CLIENT_ASSERTION_LIFETIME_SECONDS
805
+ };
806
+ const input = `${base64UrlJson(header)}.${base64UrlJson(payload)}`;
807
+ let signature;
808
+ try {
809
+ signature = await signAssertionInput(req.algorithm, req.privateKey, input);
810
+ } catch {
811
+ throw new Error(
812
+ `Enterprise MCP authorization: could not sign the client assertion with ${req.algorithm}; check that privateKey is a private key for that algorithm`
813
+ );
814
+ }
815
+ return `${input}.${base64Url(signature)}`;
816
+ };
817
+ var requestIdJag = async (req) => {
818
+ const { idp } = req;
819
+ const secrets = [
820
+ req.idToken,
821
+ idp.clientSecret,
822
+ req.clientAssertion,
823
+ ...keySecrets(idp.privateKey)
824
+ ];
825
+ const said = (value, max) => printable(typeof value === "string" ? redact(value, secrets) : value, max);
826
+ const fail = (message, code) => {
827
+ throw new EnterpriseOAuthError(
828
+ "idp",
829
+ redact(`Enterprise IdP token exchange failed: ${message}`, secrets),
830
+ code
831
+ );
832
+ };
833
+ const params = new URLSearchParams({
834
+ grant_type: GRANT_TOKEN_EXCHANGE,
835
+ requested_token_type: TOKEN_TYPE_ID_JAG,
836
+ audience: req.audience,
837
+ resource: req.resource,
838
+ subject_token: req.idToken,
839
+ subject_token_type: TOKEN_TYPE_ID_TOKEN
840
+ });
841
+ if (req.scope) {
842
+ params.set("scope", req.scope);
843
+ }
844
+ const headers = new Headers({
845
+ "Content-Type": "application/x-www-form-urlencoded",
846
+ Accept: "application/json"
847
+ });
848
+ if (idp.clientAuthMethod === "private_key_jwt") {
849
+ if (!req.clientAssertion) {
850
+ return fail("no client assertion was made for the identity provider");
851
+ }
852
+ params.set("client_assertion_type", CLIENT_ASSERTION_TYPE);
853
+ params.set("client_assertion", req.clientAssertion);
854
+ } else if (idp.clientSecret === void 0 || idp.clientAuthMethod === "client_secret_post") {
855
+ params.set("client_id", idp.clientId);
856
+ if (idp.clientSecret !== void 0) {
857
+ params.set("client_secret", idp.clientSecret);
858
+ }
859
+ } else {
860
+ headers.set(
861
+ "Authorization",
862
+ `Basic ${btoa(`${formEncode(idp.clientId)}:${formEncode(idp.clientSecret)}`)}`
863
+ );
864
+ }
865
+ let response;
866
+ try {
867
+ response = await (req.fetch ?? fetch)(idp.tokenEndpoint, {
868
+ method: "POST",
869
+ headers,
870
+ body: params,
871
+ redirect: "error"
872
+ });
873
+ } catch (err) {
874
+ return fail(
875
+ `the request did not complete (${said(err?.message) ?? "network error"})`
876
+ );
877
+ }
878
+ let body = {};
879
+ try {
880
+ const parsed = await response.json();
881
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
882
+ body = parsed;
883
+ }
884
+ } catch {
885
+ }
886
+ if (!response.ok) {
887
+ const code = said(body.error, 80);
888
+ const description = said(body.error_description);
889
+ return fail(
890
+ `the identity provider answered ${response.status}${code ? ` ${code}` : ""}${description ? ` - ${description}` : ""}`,
891
+ code
892
+ );
893
+ }
894
+ if (body.issued_token_type !== TOKEN_TYPE_ID_JAG) {
895
+ return fail(
896
+ `the identity provider returned ${said(body.issued_token_type, 120) ?? "no issued_token_type"} where an ID-JAG (${TOKEN_TYPE_ID_JAG}) was requested; nothing was sent to the MCP authorization server`
897
+ );
898
+ }
899
+ if (typeof body.access_token !== "string" || !body.access_token) {
900
+ return fail(
901
+ "the identity provider returned no ID-JAG; nothing was sent to the MCP authorization server"
902
+ );
903
+ }
904
+ return body.access_token;
905
+ };
906
+ var looksLikeUrl = (value) => /^[a-z][a-z0-9+.-]*:\/\//i.test(value);
907
+ var configError = (message) => new Error(`Enterprise MCP authorization: ${message}`);
908
+ var ASSERTION_AUDIENCES = ["issuer", "token-endpoint"];
909
+ var ASSERTION_TYPES = ["client-authentication+jwt", "JWT"];
910
+ var checkAssertionShape = (prefix, hop) => {
911
+ if (hop.assertionAudience !== void 0 && !ASSERTION_AUDIENCES.includes(hop.assertionAudience)) {
912
+ throw configError(`${prefix}assertionAudience must be 'issuer' or 'token-endpoint'`);
913
+ }
914
+ if (hop.assertionType !== void 0 && !ASSERTION_TYPES.includes(hop.assertionType)) {
915
+ throw configError(`${prefix}assertionType must be 'client-authentication+jwt' or 'JWT'`);
916
+ }
917
+ if (hop.clientAuthMethod !== "private_key_jwt" && (hop.assertionAudience !== void 0 || hop.assertionType !== void 0)) {
918
+ throw configError(
919
+ `${prefix}assertionAudience and ${prefix}assertionType are only used with ${prefix}clientAuthMethod 'private_key_jwt'`
920
+ );
921
+ }
922
+ };
923
+ var checkOptions = (opts) => {
924
+ assertSecureOAuthUrl(opts.serverUrl);
925
+ assertSecureOAuthUrl(opts.idp?.tokenEndpoint, "Enterprise IdP token endpoint");
926
+ if (opts.expectedIssuer !== void 0) {
927
+ assertSecureOAuthUrl(opts.expectedIssuer, "MCP authorization server");
928
+ }
929
+ const { idp } = opts;
930
+ if (!opts.clientId || !idp.clientId) {
931
+ throw configError("clientId and idp.clientId are required");
932
+ }
933
+ if (typeof opts.getIdToken !== "function") {
934
+ throw configError("getIdToken is required");
935
+ }
936
+ const method = opts.clientAuthMethod;
937
+ if (looksLikeUrl(opts.clientId)) {
938
+ let url;
939
+ try {
940
+ url = new URL(opts.clientId);
941
+ } catch {
942
+ }
943
+ if (!url || url.protocol !== "https:" || url.pathname === "/") {
944
+ throw configError(
945
+ `a clientId that is a URL is a client ID metadata document: it requires https and a non-root path - refusing "${opts.clientId}"`
946
+ );
947
+ }
948
+ if (opts.clientSecret) {
949
+ throw configError(
950
+ "a client ID metadata document cannot be used with clientSecret: use private_key_jwt, or no credential"
951
+ );
952
+ }
953
+ }
954
+ if (opts.clientSecret && (method === "private_key_jwt" || method === "none")) {
955
+ throw configError(`clientSecret is not used with clientAuthMethod '${method}': remove one`);
956
+ }
957
+ if ((method === "client_secret_basic" || method === "client_secret_post") && !opts.clientSecret) {
958
+ throw configError(`clientAuthMethod '${method}' needs clientSecret`);
959
+ }
960
+ if (opts.clientSecret && opts.expectedIssuer === void 0) {
961
+ throw configError(
962
+ "clientSecret needs expectedIssuer: without the issuer of the authorization server, the MCP server decides who receives the secret"
963
+ );
964
+ }
965
+ if (method === "private_key_jwt") {
966
+ if (opts.privateKey === void 0 || !ALGORITHMS.includes(opts.algorithm)) {
967
+ throw configError(
968
+ `clientAuthMethod 'private_key_jwt' needs privateKey and an algorithm (${ALGORITHMS.join(", ")})`
969
+ );
970
+ }
971
+ if (opts.expectedIssuer === void 0) {
972
+ throw configError(
973
+ "private_key_jwt needs expectedIssuer: the audience of the client assertion must not come from the MCP server alone"
974
+ );
975
+ }
976
+ } else if (opts.privateKey !== void 0) {
977
+ throw configError("privateKey is only used with clientAuthMethod 'private_key_jwt'");
978
+ }
979
+ checkAssertionShape("", opts);
980
+ checkAssertionShape("idp.", idp);
981
+ if (idp.clientAuthMethod === "private_key_jwt") {
982
+ if (idp.privateKey === void 0 || !ALGORITHMS.includes(idp.algorithm)) {
983
+ throw configError(
984
+ `idp.clientAuthMethod 'private_key_jwt' needs idp.privateKey and an idp.algorithm (${ALGORITHMS.join(", ")})`
985
+ );
986
+ }
987
+ if (idp.assertionAudience !== "token-endpoint" && !idp.issuer) {
988
+ throw configError(
989
+ "idp.clientAuthMethod private_key_jwt needs idp.issuer: it is the audience of the client assertion (or set idp.assertionAudience to 'token-endpoint')"
990
+ );
991
+ }
992
+ if (idp.clientSecret) {
993
+ throw configError("idp.clientSecret is not used with idp.clientAuthMethod 'private_key_jwt'");
994
+ }
995
+ } else if (idp.privateKey !== void 0) {
996
+ throw configError("idp.privateKey is only used with idp.clientAuthMethod 'private_key_jwt'");
997
+ }
998
+ if (idp.issuer !== void 0) {
999
+ assertSecureOAuthUrl(idp.issuer, "Enterprise IdP issuer");
1000
+ }
1001
+ };
1002
+ var formParam = (body, name) => {
1003
+ if (body instanceof URLSearchParams) {
1004
+ return body.get(name) ?? void 0;
1005
+ }
1006
+ if (typeof body === "string") {
1007
+ return new URLSearchParams(body).get(name) ?? void 0;
1008
+ }
1009
+ return void 0;
1010
+ };
1011
+ var oauthCode = (value) => typeof value === "string" && /^[A-Za-z0-9_.-]{1,64}$/.test(value) ? value : void 0;
1012
+ var BrowserEnterpriseOAuthProvider = class {
1013
+ serverUrl;
1014
+ /** The MCP extension this provider implements; the connector declares it. */
1015
+ extension = ENTERPRISE_MANAGED_AUTHORIZATION_EXTENSION;
1016
+ /**
1017
+ * Present only with an explicit `clientAuthMethod`: the SDK then leaves the
1018
+ * client authentication of the grant to it (a `private_key_jwt` assertion is
1019
+ * signed here, for the issuer discovery found and `expectedIssuer` confirmed).
1020
+ */
1021
+ addClientAuthentication;
1022
+ // True private fields: the options hold the secrets, the private keys and the
1023
+ // ID token callback, and nothing that prints or serializes the provider
1024
+ // (console.log, the devtools object view, JSON.stringify) can reach them.
1025
+ #opts;
1026
+ #storage;
1027
+ #ns;
1028
+ #skewMs;
1029
+ #clientMetadata;
1030
+ // Held (in memory only) between a granted ID-JAG and the access token it
1031
+ // buys: a failure in that window belongs to the MCP authorization server,
1032
+ // and nothing said about it may carry the grant or the client assertion.
1033
+ #pendingAssertion;
1034
+ #pendingClientAssertion;
1035
+ constructor(opts) {
1036
+ checkOptions(opts);
1037
+ this.serverUrl = opts.serverUrl;
1038
+ this.#opts = opts;
1039
+ this.#storage = opts.storage ?? new VaultOAuthStorage();
1040
+ this.#ns = namespaceFor2(opts.serverUrl);
1041
+ this.#skewMs = (opts.expirySkewSeconds ?? DEFAULT_SKEW_SECONDS2) * 1e3;
1042
+ this.#clientMetadata = {
1043
+ client_name: "agent-web",
1044
+ redirect_uris: [],
1045
+ grant_types: [GRANT_TOKEN_EXCHANGE, GRANT_JWT_BEARER],
1046
+ token_endpoint_auth_method: opts.clientAuthMethod ?? (opts.clientSecret ? "client_secret_basic" : "none"),
1047
+ ...opts.scope ? { scope: opts.scope } : {}
1048
+ };
1049
+ if (opts.clientAuthMethod !== void 0) {
1050
+ this.addClientAuthentication = (headers, params) => this.#authenticateClient(headers, params);
1051
+ }
1052
+ }
1053
+ /** Never set: this is what tells the SDK the flow has no human step. */
1054
+ get redirectUrl() {
1055
+ return void 0;
1056
+ }
1057
+ get clientMetadata() {
1058
+ return this.#clientMetadata;
1059
+ }
1060
+ #key(suffix) {
1061
+ return `${this.#ns}:${suffix}`;
1062
+ }
1063
+ async #readJSON(suffix) {
1064
+ try {
1065
+ const raw = await this.#storage.get(this.#key(suffix));
1066
+ if (raw === void 0) {
1067
+ return void 0;
1068
+ }
1069
+ return JSON.parse(raw);
1070
+ } catch {
1071
+ await this.#storage.delete(this.#key(suffix)).catch(() => {
1072
+ });
1073
+ return void 0;
1074
+ }
1075
+ }
1076
+ /** Everything of this provider that must not appear in an error or a log line. */
1077
+ #secrets() {
1078
+ return [
1079
+ this.#pendingAssertion,
1080
+ this.#pendingClientAssertion,
1081
+ this.#opts.clientSecret,
1082
+ this.#opts.idp.clientSecret,
1083
+ ...keySecrets(this.#opts.privateKey),
1084
+ ...keySecrets(this.#opts.idp.privateKey)
1085
+ ];
1086
+ }
1087
+ /** The detail an error leaves out, to the log: redacted first, then clipped. */
1088
+ #report(log, detail) {
1089
+ const sink = log ?? this.#opts.onLog ?? ((_level, message) => createLogger().warn(message));
1090
+ const safe = printable(redact(detail, this.#secrets()), 600) ?? "no detail";
1091
+ try {
1092
+ sink("warn", `[mcp] enterprise authorization for ${this.serverUrl}: ${safe}`);
1093
+ } catch {
1094
+ }
1095
+ }
1096
+ /**
1097
+ * The pre-registered client, from configuration and never from storage.
1098
+ * With `expectedIssuer` it carries that stamp, and the SDK then refuses to
1099
+ * present it to any other authorization server.
1100
+ */
1101
+ clientInformation() {
1102
+ return {
1103
+ client_id: this.#opts.clientId,
1104
+ ...this.#opts.clientSecret ? { client_secret: this.#opts.clientSecret } : {},
1105
+ ...this.#opts.expectedIssuer ? { issuer: this.#opts.expectedIssuer } : {}
1106
+ };
1107
+ }
1108
+ async tokens() {
1109
+ return (await this.#readJSON("tokens"))?.tokens;
1110
+ }
1111
+ async saveTokens(tokens) {
1112
+ this.#pendingAssertion = void 0;
1113
+ this.#pendingClientAssertion = void 0;
1114
+ const stored = {
1115
+ tokens,
1116
+ expiresAt: typeof tokens.expires_in === "number" ? Date.now() + tokens.expires_in * 1e3 : void 0
1117
+ };
1118
+ await this.#storage.set(this.#key("tokens"), JSON.stringify(stored));
1119
+ }
1120
+ async saveDiscoveryState(state) {
1121
+ await this.#storage.set(this.#key("discovery"), JSON.stringify(state));
1122
+ }
1123
+ async discoveryState() {
1124
+ const state = await this.#readJSON("discovery");
1125
+ if (!state || typeof state !== "object" || typeof state.authorizationServerUrl !== "string") {
1126
+ return void 0;
1127
+ }
1128
+ return state;
1129
+ }
1130
+ /**
1131
+ * Called by the SDK inside `auth()`, after discovery and before the token
1132
+ * request to the MCP authorization server: get an ID token from the host,
1133
+ * exchange it at the IdP for an ID-JAG addressed to exactly the authorization
1134
+ * server and resource discovery found for this server, and hand the SDK the
1135
+ * `jwt-bearer` request. Throws before anything reaches the authorization
1136
+ * server when discovery cannot be trusted or the IdP's answer is not an ID-JAG.
1137
+ */
1138
+ async prepareTokenRequest(scope) {
1139
+ this.#pendingAssertion = void 0;
1140
+ this.#pendingClientAssertion = void 0;
1141
+ let target;
1142
+ try {
1143
+ target = enterpriseGrantTarget(
1144
+ this.serverUrl,
1145
+ await this.discoveryState(),
1146
+ this.#opts.expectedIssuer
1147
+ );
1148
+ } catch (err) {
1149
+ await this.#storage.delete(this.#key("discovery"));
1150
+ throw err;
1151
+ }
1152
+ let idToken;
1153
+ try {
1154
+ idToken = await this.#opts.getIdToken();
1155
+ } catch {
1156
+ throw new EnterpriseOAuthError(
1157
+ "idp",
1158
+ "Enterprise IdP token exchange failed: getIdToken() threw, so there is no ID token to exchange"
1159
+ );
1160
+ }
1161
+ if (typeof idToken !== "string" || !idToken) {
1162
+ throw new EnterpriseOAuthError(
1163
+ "idp",
1164
+ "Enterprise IdP token exchange failed: getIdToken() returned no ID token"
1165
+ );
1166
+ }
1167
+ const { idp } = this.#opts;
1168
+ const clientAssertion = idp.clientAuthMethod === "private_key_jwt" ? await createClientAssertion({
1169
+ clientId: idp.clientId,
1170
+ audience: idp.assertionAudience === "token-endpoint" ? idp.tokenEndpoint : idp.issuer,
1171
+ privateKey: idp.privateKey,
1172
+ algorithm: idp.algorithm,
1173
+ keyId: idp.keyId,
1174
+ type: idp.assertionType
1175
+ }).catch((err) => {
1176
+ throw new EnterpriseOAuthError("idp", err.message);
1177
+ }) : void 0;
1178
+ const assertion = await requestIdJag({
1179
+ idp,
1180
+ idToken,
1181
+ audience: target.audience,
1182
+ resource: target.resource,
1183
+ scope: scope ?? this.#opts.scope,
1184
+ clientAssertion,
1185
+ fetch: this.#opts.fetch
1186
+ });
1187
+ this.#pendingAssertion = assertion;
1188
+ return new URLSearchParams({ grant_type: GRANT_JWT_BEARER, assertion });
1189
+ }
1190
+ /** The client authentication of the grant, when `clientAuthMethod` says how. */
1191
+ async #authenticateClient(headers, params) {
1192
+ const { clientId, clientSecret, clientAuthMethod } = this.#opts;
1193
+ if (clientAuthMethod === "private_key_jwt") {
1194
+ const target = enterpriseGrantTarget(
1195
+ this.serverUrl,
1196
+ await this.discoveryState(),
1197
+ this.#opts.expectedIssuer
1198
+ );
1199
+ const audience = this.#opts.assertionAudience === "token-endpoint" ? target.tokenEndpoint : target.audience;
1200
+ if (audience === void 0) {
1201
+ this.#pendingAssertion = void 0;
1202
+ throw new EnterpriseOAuthError(
1203
+ "discovery",
1204
+ `Enterprise MCP authorization: the authorization server "${target.audience}" published no token endpoint, so there is no audience for the client assertion (assertionAudience 'token-endpoint')`
1205
+ );
1206
+ }
1207
+ const assertion = await createClientAssertion({
1208
+ clientId,
1209
+ audience,
1210
+ privateKey: this.#opts.privateKey,
1211
+ algorithm: this.#opts.algorithm,
1212
+ keyId: this.#opts.keyId,
1213
+ type: this.#opts.assertionType
1214
+ }).catch((err) => {
1215
+ this.#pendingAssertion = void 0;
1216
+ throw new EnterpriseOAuthError("authorization-server", err.message);
1217
+ });
1218
+ this.#pendingClientAssertion = assertion;
1219
+ params.set("client_assertion_type", CLIENT_ASSERTION_TYPE);
1220
+ params.set("client_assertion", assertion);
1221
+ return;
1222
+ }
1223
+ if (clientAuthMethod === "client_secret_basic") {
1224
+ headers.set(
1225
+ "Authorization",
1226
+ `Basic ${btoa(`${formEncode(clientId)}:${formEncode(clientSecret)}`)}`
1227
+ );
1228
+ return;
1229
+ }
1230
+ params.set("client_id", clientId);
1231
+ if (clientAuthMethod === "client_secret_post") {
1232
+ params.set("client_secret", clientSecret);
1233
+ }
1234
+ }
1235
+ /** The codes of the interactive flow: this provider has none. */
1236
+ redirectToAuthorization() {
1237
+ throw new Error("Enterprise MCP authorization has no interactive step");
1238
+ }
1239
+ saveCodeVerifier() {
1240
+ throw new Error("Enterprise MCP authorization has no interactive step");
1241
+ }
1242
+ codeVerifier() {
1243
+ throw new Error("Enterprise MCP authorization has no interactive step");
1244
+ }
1245
+ /**
1246
+ * Called by the SDK when the authorization server rejects what it was sent.
1247
+ * The client is configuration, so there is nothing of it to forget; tokens
1248
+ * and discovery are dropped as asked.
1249
+ */
1250
+ async invalidateCredentials(scope) {
1251
+ const targets = scope === "all" ? ["tokens", "discovery"] : scope === "tokens" || scope === "discovery" ? [scope] : [];
1252
+ await Promise.all(targets.map((t) => this.#storage.delete(this.#key(t))));
1253
+ }
1254
+ /** True when there is no access token, or it expires within the skew window. */
1255
+ async isAccessTokenExpired() {
1256
+ const stored = await this.#readJSON("tokens");
1257
+ if (!stored?.tokens?.access_token) {
1258
+ return true;
1259
+ }
1260
+ if (stored.expiresAt === void 0) {
1261
+ return false;
1262
+ }
1263
+ return Date.now() + this.#skewMs >= stored.expiresAt;
1264
+ }
1265
+ async isAuthorized() {
1266
+ return await this.tokens() !== void 0;
1267
+ }
1268
+ /**
1269
+ * The fetch to give the transport that carries this provider (the connector
1270
+ * does). It changes one thing: when the request that carries the ID-JAG is
1271
+ * refused, the caller gets an `EnterpriseOAuthError` (`hop:
1272
+ * 'authorization-server'`) with a short message - the OAuth error code and
1273
+ * the status - and what the server said in full goes to `log`, redacted.
1274
+ * That holds whenever the SDK asks for a token, at connect or in the middle
1275
+ * of a session, so an application never has the server's raw words to show.
1276
+ * A refusal is final: every grant is already a fresh one, so the SDK's
1277
+ * "drop the token and try again" would only repeat the IdP exchange.
1278
+ */
1279
+ transportFetch(base, log) {
1280
+ const inner = base ?? ((url, init) => fetch(url, init));
1281
+ return async (url, init) => {
1282
+ const grant = this.#pendingAssertion;
1283
+ if (grant === void 0 || formParam(init?.body, "assertion") !== grant) {
1284
+ return inner(url, init);
1285
+ }
1286
+ let response;
1287
+ try {
1288
+ response = await inner(url, init);
1289
+ } catch (err) {
1290
+ this.#report(log, `the grant request did not complete: ${err?.message ?? err}`);
1291
+ this.#pendingAssertion = void 0;
1292
+ this.#pendingClientAssertion = void 0;
1293
+ throw new EnterpriseOAuthError(
1294
+ "authorization-server",
1295
+ "MCP authorization server could not be reached for the ID-JAG grant"
1296
+ );
1297
+ }
1298
+ if (response.status < 400) {
1299
+ return response;
1300
+ }
1301
+ const text = await response.text().catch(() => "");
1302
+ let body = {};
1303
+ try {
1304
+ const parsed = JSON.parse(text);
1305
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
1306
+ body = parsed;
1307
+ }
1308
+ } catch {
1309
+ }
1310
+ const code = oauthCode(body.error);
1311
+ const description = typeof body.error_description === "string" ? body.error_description : text;
1312
+ this.#report(
1313
+ log,
1314
+ `the authorization server refused the ID-JAG grant with ${response.status}${code ? ` ${code}` : ""}${description ? `: ${description}` : ""}`
1315
+ );
1316
+ this.#pendingAssertion = void 0;
1317
+ this.#pendingClientAssertion = void 0;
1318
+ throw new EnterpriseOAuthError(
1319
+ "authorization-server",
1320
+ `MCP authorization server refused the ID-JAG grant: ${code ?? "no error code"} (HTTP ${response.status})`,
1321
+ code
1322
+ );
1323
+ };
1324
+ }
1325
+ /**
1326
+ * Run the whole flow now (discovery, IdP exchange, grant) and store the
1327
+ * access token. `connectMcpHttp` calls it before connecting when there is
1328
+ * no usable token; call it yourself to fail early. A refusal is an
1329
+ * `EnterpriseOAuthError` whose `hop` says who refused.
1330
+ */
1331
+ async authorize(opts = {}) {
1332
+ try {
1333
+ await auth3(this, {
1334
+ serverUrl: this.serverUrl,
1335
+ fetchFn: this.transportFetch(opts.fetch, opts.onLog)
1336
+ });
1337
+ } catch (err) {
1338
+ if (err instanceof EnterpriseOAuthError) {
1339
+ throw err;
1340
+ }
1341
+ const detail = err?.message ?? String(err);
1342
+ if (this.#pendingAssertion !== void 0) {
1343
+ this.#report(opts.onLog, `the answer to the ID-JAG grant could not be used: ${detail}`);
1344
+ this.#pendingAssertion = void 0;
1345
+ this.#pendingClientAssertion = void 0;
1346
+ throw new EnterpriseOAuthError(
1347
+ "authorization-server",
1348
+ "MCP authorization server answered the ID-JAG grant with something that is not a token response"
1349
+ );
1350
+ }
1351
+ await this.#storage.delete(this.#key("discovery")).catch(() => {
1352
+ });
1353
+ const message = printable(redact(detail, this.#secrets()), 500) ?? "no reason given";
1354
+ throw new EnterpriseOAuthError(
1355
+ "discovery",
1356
+ `Enterprise MCP authorization: discovery failed (${message})`,
1357
+ oauthCode(err?.errorCode)
1358
+ );
1359
+ }
1360
+ }
1361
+ /** Forget the access token and what discovery found for this server. */
1362
+ async reset() {
1363
+ await this.invalidateCredentials("all");
1364
+ }
1365
+ };
1366
+ var createEnterpriseOAuthProvider = (opts) => new BrowserEnterpriseOAuthProvider(opts);
530
1367
  export {
1368
+ BrowserEnterpriseOAuthProvider,
531
1369
  BrowserOAuthProvider,
1370
+ ENTERPRISE_MANAGED_AUTHORIZATION_EXTENSION,
1371
+ EnterpriseOAuthError,
532
1372
  MemoryOAuthStorage,
533
1373
  UnauthorizedError2 as UnauthorizedError,
534
1374
  VaultOAuthStorage,
535
1375
  beginMcpOAuth,
1376
+ checkAuthorizationResponseIssuer,
536
1377
  connectMcpHttp,
1378
+ createEnterpriseOAuthProvider,
537
1379
  diagnoseMcpCors,
538
1380
  finishMcpOAuth,
539
1381
  flattenContent,