@dudko.dev/agent-web 0.0.37 → 0.0.39

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