@dudko.dev/agent-web 0.0.37 → 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/README.md +156 -4
- package/dist/agent-web.js +270 -110
- package/dist/agent-web.js.map +1 -1
- package/dist/chunk-AY2BZYZY.js +573 -0
- package/dist/chunk-AY2BZYZY.js.map +1 -0
- package/dist/chunk-CTXDKSDD.js +39 -0
- package/dist/chunk-CTXDKSDD.js.map +1 -0
- package/dist/{chunk-CPSDKXO6.js → chunk-T6LZW7ML.js} +27 -35
- package/dist/chunk-T6LZW7ML.js.map +1 -0
- package/dist/chunk-V3JOK7EW.js +929 -0
- package/dist/chunk-V3JOK7EW.js.map +1 -0
- package/dist/index.cjs +5980 -3627
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +363 -3
- package/dist/index.d.ts +363 -3
- package/dist/index.js +1183 -583
- package/dist/index.js.map +1 -1
- package/dist/mcp.cjs +879 -13
- package/dist/mcp.cjs.map +1 -1
- package/dist/mcp.d.cts +372 -13
- package/dist/mcp.d.ts +372 -13
- package/dist/mcp.js +857 -15
- package/dist/mcp.js.map +1 -1
- package/dist/sandbox-AMO2SA4X.js +269 -0
- package/dist/sandbox-AMO2SA4X.js.map +1 -0
- package/dist/sandbox-worker.cjs +745 -0
- package/dist/sandbox-worker.cjs.map +1 -0
- package/dist/sandbox-worker.d.cts +37 -0
- package/dist/sandbox-worker.d.ts +37 -0
- package/dist/sandbox-worker.js +27 -0
- package/dist/sandbox-worker.js.map +1 -0
- package/package.json +23 -4
- package/dist/chunk-CPSDKXO6.js.map +0 -1
package/dist/mcp.cjs
CHANGED
|
@@ -20,12 +20,17 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
20
20
|
// src/mcp/index.ts
|
|
21
21
|
var mcp_exports = {};
|
|
22
22
|
__export(mcp_exports, {
|
|
23
|
+
BrowserEnterpriseOAuthProvider: () => BrowserEnterpriseOAuthProvider,
|
|
23
24
|
BrowserOAuthProvider: () => BrowserOAuthProvider,
|
|
25
|
+
ENTERPRISE_MANAGED_AUTHORIZATION_EXTENSION: () => ENTERPRISE_MANAGED_AUTHORIZATION_EXTENSION,
|
|
26
|
+
EnterpriseOAuthError: () => EnterpriseOAuthError,
|
|
24
27
|
MemoryOAuthStorage: () => MemoryOAuthStorage,
|
|
25
|
-
UnauthorizedError: () =>
|
|
28
|
+
UnauthorizedError: () => import_auth4.UnauthorizedError,
|
|
26
29
|
VaultOAuthStorage: () => VaultOAuthStorage,
|
|
27
30
|
beginMcpOAuth: () => beginMcpOAuth,
|
|
31
|
+
checkAuthorizationResponseIssuer: () => checkAuthorizationResponseIssuer,
|
|
28
32
|
connectMcpHttp: () => connectMcpHttp,
|
|
33
|
+
createEnterpriseOAuthProvider: () => createEnterpriseOAuthProvider,
|
|
29
34
|
diagnoseMcpCors: () => diagnoseMcpCors,
|
|
30
35
|
finishMcpOAuth: () => finishMcpOAuth,
|
|
31
36
|
flattenContent: () => flattenContent,
|
|
@@ -208,11 +213,48 @@ var assertSecureOAuthUrl = (url, label = "MCP server") => {
|
|
|
208
213
|
`${label}: MCP OAuth requires https (or a loopback host) - refusing to send tokens to "${url}"`
|
|
209
214
|
);
|
|
210
215
|
};
|
|
216
|
+
var assertClientMetadataUrl = (url, label = "MCP OAuth") => {
|
|
217
|
+
let parsed;
|
|
218
|
+
try {
|
|
219
|
+
parsed = new URL(url);
|
|
220
|
+
} catch {
|
|
221
|
+
throw new Error(`${label}: clientMetadataUrl "${url}" is not a valid URL`);
|
|
222
|
+
}
|
|
223
|
+
if (parsed.protocol === "https:" && parsed.pathname !== "/") return;
|
|
224
|
+
throw new Error(
|
|
225
|
+
`${label}: clientMetadataUrl requires https and a non-root path - refusing "${url}"`
|
|
226
|
+
);
|
|
227
|
+
};
|
|
228
|
+
var checkAuthorizationResponseIssuer = (iss, discoveryState, clientIssuer) => {
|
|
229
|
+
const metadata = discoveryState?.authorizationServerMetadata;
|
|
230
|
+
const expected = discoveryState ? metadata?.issuer ?? String(discoveryState.authorizationServerUrl) : clientIssuer;
|
|
231
|
+
if (iss === void 0) {
|
|
232
|
+
if (metadata?.authorization_response_iss_parameter_supported === true) {
|
|
233
|
+
throw new Error(
|
|
234
|
+
'Authorization response carried no "iss", which this authorization server says it always sends; refusing to exchange the code (possible mix-up attack)'
|
|
235
|
+
);
|
|
236
|
+
}
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
if (expected !== void 0 && iss !== expected) {
|
|
240
|
+
throw new Error(
|
|
241
|
+
`Authorization response came from issuer "${iss}", expected "${expected}"; refusing to exchange the code (possible mix-up attack)`
|
|
242
|
+
);
|
|
243
|
+
}
|
|
244
|
+
};
|
|
211
245
|
var randomToken = () => {
|
|
212
246
|
const bytes = new Uint8Array(32);
|
|
213
247
|
globalThis.crypto.getRandomValues(bytes);
|
|
214
248
|
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
215
249
|
};
|
|
250
|
+
var applicationTypeFor = (redirectUrl) => {
|
|
251
|
+
try {
|
|
252
|
+
const u = new URL(redirectUrl);
|
|
253
|
+
return u.protocol === "https:" && !LOOPBACK_HOSTS.has(u.hostname) ? "web" : "native";
|
|
254
|
+
} catch {
|
|
255
|
+
return "native";
|
|
256
|
+
}
|
|
257
|
+
};
|
|
216
258
|
var BrowserOAuthProvider = class {
|
|
217
259
|
/** Set when the SDK asks for an authorization redirect; read it in your UI. */
|
|
218
260
|
authorizationUrl;
|
|
@@ -221,10 +263,15 @@ var BrowserOAuthProvider = class {
|
|
|
221
263
|
ns;
|
|
222
264
|
_redirectUrl;
|
|
223
265
|
_clientMetadata;
|
|
266
|
+
_clientMetadataUrl;
|
|
224
267
|
skewMs;
|
|
225
268
|
onRedirect;
|
|
226
269
|
constructor(opts) {
|
|
227
270
|
assertSecureOAuthUrl(opts.serverUrl);
|
|
271
|
+
if (opts.clientMetadataUrl !== void 0) {
|
|
272
|
+
assertClientMetadataUrl(opts.clientMetadataUrl);
|
|
273
|
+
this._clientMetadataUrl = opts.clientMetadataUrl;
|
|
274
|
+
}
|
|
228
275
|
this.serverUrl = opts.serverUrl;
|
|
229
276
|
this.storage = opts.storage ?? new VaultOAuthStorage();
|
|
230
277
|
this.ns = namespaceFor(opts.serverUrl);
|
|
@@ -239,6 +286,8 @@ var BrowserOAuthProvider = class {
|
|
|
239
286
|
// Public client: a browser cannot hold a client_secret. PKCE is what
|
|
240
287
|
// actually protects the code exchange.
|
|
241
288
|
token_endpoint_auth_method: "none",
|
|
289
|
+
// By the redirect: an https page is 'web', a loopback one (local dev) is 'native'.
|
|
290
|
+
application_type: applicationTypeFor(this._redirectUrl),
|
|
242
291
|
...opts.scope ? { scope: opts.scope } : {},
|
|
243
292
|
...opts.clientMetadata
|
|
244
293
|
};
|
|
@@ -249,6 +298,10 @@ var BrowserOAuthProvider = class {
|
|
|
249
298
|
get clientMetadata() {
|
|
250
299
|
return this._clientMetadata;
|
|
251
300
|
}
|
|
301
|
+
/** The client ID metadata document URL (CIMD), when one was configured. */
|
|
302
|
+
get clientMetadataUrl() {
|
|
303
|
+
return this._clientMetadataUrl;
|
|
304
|
+
}
|
|
252
305
|
key(suffix) {
|
|
253
306
|
return `${this.ns}:${suffix}`;
|
|
254
307
|
}
|
|
@@ -305,18 +358,36 @@ var BrowserOAuthProvider = class {
|
|
|
305
358
|
}
|
|
306
359
|
return v;
|
|
307
360
|
}
|
|
361
|
+
/**
|
|
362
|
+
* What discovery found (the authorization server, its metadata, the resource
|
|
363
|
+
* metadata). The SDK reuses it instead of discovering again - after the
|
|
364
|
+
* redirect back too - and {@link finishMcpOAuth} reads the expected issuer
|
|
365
|
+
* from it.
|
|
366
|
+
*/
|
|
367
|
+
async saveDiscoveryState(state) {
|
|
368
|
+
await this.storage.set(this.key("discovery"), JSON.stringify(state));
|
|
369
|
+
}
|
|
370
|
+
async discoveryState() {
|
|
371
|
+
const state = await this.readJSON("discovery");
|
|
372
|
+
if (!state || typeof state !== "object" || typeof state.authorizationServerUrl !== "string") {
|
|
373
|
+
return void 0;
|
|
374
|
+
}
|
|
375
|
+
return state;
|
|
376
|
+
}
|
|
308
377
|
async redirectToAuthorization(url) {
|
|
309
378
|
this.authorizationUrl = url;
|
|
310
379
|
await this.onRedirect?.(url);
|
|
311
380
|
}
|
|
312
381
|
/**
|
|
313
382
|
* Called by the SDK when the server rejects what we hold: `'tokens'` after an
|
|
314
|
-
* `invalid_grant` (dead refresh token), `'
|
|
315
|
-
*
|
|
316
|
-
*
|
|
383
|
+
* `invalid_grant` (dead refresh token), `'all'` after an `invalid_client`
|
|
384
|
+
* (the AS forgot our dynamic registration). `'client'`, `'verifier'` and
|
|
385
|
+
* `'discovery'` are in its type and handled the same way: one key each.
|
|
386
|
+
* Clearing lets the SDK re-discover, re-register and re-authorize without the
|
|
387
|
+
* user clearing site data.
|
|
317
388
|
*/
|
|
318
389
|
async invalidateCredentials(scope) {
|
|
319
|
-
const targets = scope === "all" ? ["tokens", "client", "verifier", "state"] : [scope];
|
|
390
|
+
const targets = scope === "all" ? ["tokens", "client", "verifier", "state", "discovery"] : [scope];
|
|
320
391
|
await Promise.all(targets.map((t) => this.storage.delete(this.key(t))));
|
|
321
392
|
}
|
|
322
393
|
/** True when there is no access token, or it expires within the skew window. */
|
|
@@ -330,7 +401,7 @@ var BrowserOAuthProvider = class {
|
|
|
330
401
|
async isAuthorized() {
|
|
331
402
|
return await this.tokens() !== void 0;
|
|
332
403
|
}
|
|
333
|
-
/** Forget tokens, registration, verifier and
|
|
404
|
+
/** Forget tokens, registration, verifier, state and discovery for this server. */
|
|
334
405
|
async reset() {
|
|
335
406
|
this.authorizationUrl = void 0;
|
|
336
407
|
await this.invalidateCredentials("all");
|
|
@@ -359,6 +430,7 @@ var readOAuthCallback = (input) => {
|
|
|
359
430
|
return {
|
|
360
431
|
code,
|
|
361
432
|
state: params.get("state") ?? void 0,
|
|
433
|
+
iss: params.get("iss") ?? void 0,
|
|
362
434
|
error,
|
|
363
435
|
errorDescription: params.get("error_description") ?? void 0
|
|
364
436
|
};
|
|
@@ -375,6 +447,11 @@ var finishMcpOAuth = async (provider, callback, opts = {}) => {
|
|
|
375
447
|
if (!await provider.verifyState(callback.state)) {
|
|
376
448
|
throw new Error("Authorization state mismatch; refusing to exchange the code (possible CSRF)");
|
|
377
449
|
}
|
|
450
|
+
checkAuthorizationResponseIssuer(
|
|
451
|
+
callback.iss,
|
|
452
|
+
await provider.discoveryState(),
|
|
453
|
+
(await provider.clientInformation())?.issuer
|
|
454
|
+
);
|
|
378
455
|
const result = await (0, import_auth.auth)(provider, {
|
|
379
456
|
serverUrl: provider.serverUrl,
|
|
380
457
|
authorizationCode: callback.code,
|
|
@@ -441,6 +518,10 @@ var flattenContent = (content) => {
|
|
|
441
518
|
if (allText) return parts.map((p) => p.text).join("\n");
|
|
442
519
|
return parts.map((p) => p?.type === "text" && typeof p.text === "string" ? p.text : p);
|
|
443
520
|
};
|
|
521
|
+
var asEnterpriseProvider = (provider) => {
|
|
522
|
+
const p = provider;
|
|
523
|
+
return typeof p.extension === "string" && typeof p.authorize === "function" && typeof p.transportFetch === "function" ? provider : void 0;
|
|
524
|
+
};
|
|
444
525
|
var RefreshOnlyAbort = class extends Error {
|
|
445
526
|
};
|
|
446
527
|
var refreshOnly = (p) => ({
|
|
@@ -470,10 +551,20 @@ var refreshOnly = (p) => ({
|
|
|
470
551
|
throw new RefreshOnlyAbort();
|
|
471
552
|
}
|
|
472
553
|
});
|
|
473
|
-
var refreshIfExpired = async (provider, serverUrl, fetchFn, log, name) => {
|
|
554
|
+
var refreshIfExpired = async (provider, serverUrl, fetchFn, log, name, detailLog) => {
|
|
474
555
|
const check = provider.isAccessTokenExpired;
|
|
475
556
|
if (typeof check !== "function") return;
|
|
476
557
|
if (!await check.call(provider)) return;
|
|
558
|
+
const enterprise = asEnterpriseProvider(provider);
|
|
559
|
+
if (enterprise) {
|
|
560
|
+
try {
|
|
561
|
+
await enterprise.authorize({ fetch: fetchFn, onLog: detailLog });
|
|
562
|
+
} catch (err) {
|
|
563
|
+
if (err?.hop !== "discovery") throw err;
|
|
564
|
+
log("info", `[mcp] ${name}: ${err instanceof Error ? err.message : String(err)}; continuing`);
|
|
565
|
+
}
|
|
566
|
+
return;
|
|
567
|
+
}
|
|
477
568
|
const tokens = await provider.tokens();
|
|
478
569
|
if (!tokens?.refresh_token) return;
|
|
479
570
|
try {
|
|
@@ -556,20 +647,24 @@ var connectAndList = async (name, cfg, opts, log, onClient) => {
|
|
|
556
647
|
);
|
|
557
648
|
}
|
|
558
649
|
assertSecureOAuthUrl(cfg.url, name);
|
|
559
|
-
await refreshIfExpired(cfg.authProvider, cfg.url, cfg.fetch, log, name);
|
|
650
|
+
await refreshIfExpired(cfg.authProvider, cfg.url, cfg.fetch, log, name, opts.onLog);
|
|
560
651
|
}
|
|
561
652
|
const transport = new import_streamableHttp.StreamableHTTPClientTransport(new URL(cfg.url), {
|
|
562
653
|
requestInit: headers ? { headers } : void 0,
|
|
563
654
|
authProvider: cfg.authProvider,
|
|
564
|
-
|
|
655
|
+
// The enterprise provider reports a refused grant itself: a short typed
|
|
656
|
+
// error for the caller, the server's words (redacted) to the log.
|
|
657
|
+
fetch: cfg.authProvider && asEnterpriseProvider(cfg.authProvider)?.transportFetch(cfg.fetch, opts.onLog) || cfg.fetch,
|
|
565
658
|
reconnectionOptions: { ...DEFAULT_RECONNECTION, ...cfg.reconnection }
|
|
566
659
|
});
|
|
567
660
|
transport.onerror = (err) => log("warn", `[mcp] ${name}: transport error - ${err.message}`);
|
|
568
661
|
transport.onclose = () => log("info", `[mcp] ${name}: transport closed`);
|
|
569
|
-
const
|
|
570
|
-
|
|
571
|
-
version: opts.clientVersion ?? "0.0.0"
|
|
572
|
-
|
|
662
|
+
const enterprise = cfg.authProvider ? asEnterpriseProvider(cfg.authProvider) : void 0;
|
|
663
|
+
const client = new import_client.Client(
|
|
664
|
+
{ name: opts.clientName ?? "agent-web", version: opts.clientVersion ?? "0.0.0" },
|
|
665
|
+
// An extension is opt-in: it is declared only by the client that uses it.
|
|
666
|
+
enterprise ? { capabilities: { extensions: { [enterprise.extension]: {} } } } : void 0
|
|
667
|
+
);
|
|
573
668
|
onClient(client);
|
|
574
669
|
await client.connect(transport);
|
|
575
670
|
if (opts.onToolsChanged) {
|
|
@@ -673,15 +768,786 @@ var connectMcpHttp = async (servers, opts = {}) => {
|
|
|
673
768
|
};
|
|
674
769
|
|
|
675
770
|
// src/mcp/index.ts
|
|
771
|
+
var import_auth4 = require("@modelcontextprotocol/sdk/client/auth.js");
|
|
772
|
+
|
|
773
|
+
// src/mcp/enterprise-oauth.ts
|
|
676
774
|
var import_auth3 = require("@modelcontextprotocol/sdk/client/auth.js");
|
|
775
|
+
|
|
776
|
+
// src/logger.ts
|
|
777
|
+
var WEIGHT = {
|
|
778
|
+
silent: 0,
|
|
779
|
+
error: 1,
|
|
780
|
+
warn: 2,
|
|
781
|
+
info: 3,
|
|
782
|
+
debug: 4
|
|
783
|
+
};
|
|
784
|
+
var PREFIX = "[agent-web]";
|
|
785
|
+
var noop = () => void 0;
|
|
786
|
+
var createLogger = (level = "warn", sink = console) => {
|
|
787
|
+
const at = (min, fn) => WEIGHT[level] >= WEIGHT[min] ? (...args) => fn.call(sink, PREFIX, ...args) : noop;
|
|
788
|
+
return {
|
|
789
|
+
level,
|
|
790
|
+
error: at("error", sink.error),
|
|
791
|
+
warn: at("warn", sink.warn),
|
|
792
|
+
info: at("info", sink.info),
|
|
793
|
+
debug: at("debug", sink.debug)
|
|
794
|
+
};
|
|
795
|
+
};
|
|
796
|
+
|
|
797
|
+
// src/mcp/enterprise-oauth.ts
|
|
798
|
+
var ENTERPRISE_MANAGED_AUTHORIZATION_EXTENSION = "io.modelcontextprotocol/enterprise-managed-authorization";
|
|
799
|
+
var GRANT_TOKEN_EXCHANGE = "urn:ietf:params:oauth:grant-type:token-exchange";
|
|
800
|
+
var GRANT_JWT_BEARER = "urn:ietf:params:oauth:grant-type:jwt-bearer";
|
|
801
|
+
var TOKEN_TYPE_ID_JAG = "urn:ietf:params:oauth:token-type:id-jag";
|
|
802
|
+
var TOKEN_TYPE_ID_TOKEN = "urn:ietf:params:oauth:token-type:id_token";
|
|
803
|
+
var CLIENT_ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
|
|
804
|
+
var CLIENT_ASSERTION_LIFETIME_SECONDS = 60;
|
|
805
|
+
var EnterpriseOAuthError = class extends Error {
|
|
806
|
+
hop;
|
|
807
|
+
/** The OAuth `error` code the server answered with, when it sent one. */
|
|
808
|
+
code;
|
|
809
|
+
constructor(hop, message, code) {
|
|
810
|
+
super(message);
|
|
811
|
+
this.name = "EnterpriseOAuthError";
|
|
812
|
+
this.hop = hop;
|
|
813
|
+
this.code = code;
|
|
814
|
+
}
|
|
815
|
+
};
|
|
816
|
+
var DEFAULT_SKEW_SECONDS2 = 30;
|
|
817
|
+
var namespaceFor2 = (serverUrl) => {
|
|
818
|
+
const u = new URL(serverUrl);
|
|
819
|
+
return `mcp-enterprise-oauth:${u.origin}${u.pathname.replace(/\/+$/, "")}${u.search}`;
|
|
820
|
+
};
|
|
821
|
+
var sameIssuer = (a, b) => a === b || a === `${b}/` || b === `${a}/`;
|
|
822
|
+
var stripFragment = (url) => {
|
|
823
|
+
const u = new URL(url);
|
|
824
|
+
u.hash = "";
|
|
825
|
+
return u.href;
|
|
826
|
+
};
|
|
827
|
+
var resourceCovers = (resource, serverUrl) => {
|
|
828
|
+
let published;
|
|
829
|
+
try {
|
|
830
|
+
published = new URL(resource);
|
|
831
|
+
} catch {
|
|
832
|
+
return false;
|
|
833
|
+
}
|
|
834
|
+
const requested = new URL(serverUrl);
|
|
835
|
+
if (published.origin !== requested.origin) {
|
|
836
|
+
return false;
|
|
837
|
+
}
|
|
838
|
+
const slashed = (p) => p.endsWith("/") ? p : `${p}/`;
|
|
839
|
+
return slashed(requested.pathname).startsWith(slashed(published.pathname));
|
|
840
|
+
};
|
|
841
|
+
var enterpriseGrantTarget = (serverUrl, state, expectedIssuer) => {
|
|
842
|
+
const refuse = (message) => {
|
|
843
|
+
throw new EnterpriseOAuthError("discovery", `Enterprise MCP authorization: ${message}`);
|
|
844
|
+
};
|
|
845
|
+
if (!state) {
|
|
846
|
+
return refuse("nothing is known about the authorization server of this MCP server yet");
|
|
847
|
+
}
|
|
848
|
+
const asUrl = String(state.authorizationServerUrl);
|
|
849
|
+
const metadata = state.authorizationServerMetadata;
|
|
850
|
+
const issuer = metadata?.issuer;
|
|
851
|
+
if (typeof issuer !== "string" || !issuer) {
|
|
852
|
+
return refuse(
|
|
853
|
+
`the authorization server "${asUrl}" published no metadata with an issuer, so there is no audience to ask the identity provider for`
|
|
854
|
+
);
|
|
855
|
+
}
|
|
856
|
+
if (!sameIssuer(issuer, asUrl)) {
|
|
857
|
+
return refuse(
|
|
858
|
+
`the metadata fetched for "${asUrl}" names another issuer ("${issuer}"); refusing to request a grant for it`
|
|
859
|
+
);
|
|
860
|
+
}
|
|
861
|
+
if (expectedIssuer !== void 0 && !sameIssuer(issuer, expectedIssuer)) {
|
|
862
|
+
return refuse(
|
|
863
|
+
`this MCP server points at the authorization server "${issuer}", expected "${expectedIssuer}"; refusing to send credentials there`
|
|
864
|
+
);
|
|
865
|
+
}
|
|
866
|
+
try {
|
|
867
|
+
assertSecureOAuthUrl(asUrl, "MCP authorization server");
|
|
868
|
+
if (typeof metadata?.token_endpoint === "string") {
|
|
869
|
+
assertSecureOAuthUrl(metadata.token_endpoint, "MCP authorization server token endpoint");
|
|
870
|
+
}
|
|
871
|
+
} catch (err) {
|
|
872
|
+
return refuse(err.message);
|
|
873
|
+
}
|
|
874
|
+
const published = state.resourceMetadata?.resource;
|
|
875
|
+
if (published !== void 0 && !resourceCovers(published, serverUrl)) {
|
|
876
|
+
return refuse(
|
|
877
|
+
`the protected resource "${published}" this server published does not cover "${serverUrl}"`
|
|
878
|
+
);
|
|
879
|
+
}
|
|
880
|
+
return {
|
|
881
|
+
audience: issuer,
|
|
882
|
+
resource: published ?? stripFragment(serverUrl),
|
|
883
|
+
// Handed out only here, after the issuer and the scheme checks above.
|
|
884
|
+
...typeof metadata?.token_endpoint === "string" && metadata.token_endpoint ? { tokenEndpoint: metadata.token_endpoint } : {}
|
|
885
|
+
};
|
|
886
|
+
};
|
|
887
|
+
var printable = (value, max = 300) => {
|
|
888
|
+
if (typeof value !== "string") {
|
|
889
|
+
return void 0;
|
|
890
|
+
}
|
|
891
|
+
const clean = value.replace(/[^\x20-\x7e]+/g, " ").trim();
|
|
892
|
+
if (!clean) {
|
|
893
|
+
return void 0;
|
|
894
|
+
}
|
|
895
|
+
return clean.length > max ? `${clean.slice(0, max)}...` : clean;
|
|
896
|
+
};
|
|
897
|
+
var formEncode = (value) => new URLSearchParams({ v: value }).toString().slice(2);
|
|
898
|
+
var redact = (message, secrets) => {
|
|
899
|
+
let out = message;
|
|
900
|
+
for (const secret of secrets) {
|
|
901
|
+
if (!secret) {
|
|
902
|
+
continue;
|
|
903
|
+
}
|
|
904
|
+
const spellings = [secret, encodeURIComponent(secret), formEncode(secret)];
|
|
905
|
+
for (const spelling of new Set(spellings)) {
|
|
906
|
+
out = out.split(spelling).join("[redacted]");
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
return out;
|
|
910
|
+
};
|
|
911
|
+
var ALGORITHMS = [
|
|
912
|
+
"ES256",
|
|
913
|
+
"ES384",
|
|
914
|
+
"ES512",
|
|
915
|
+
"RS256",
|
|
916
|
+
"RS384",
|
|
917
|
+
"RS512",
|
|
918
|
+
"PS256",
|
|
919
|
+
"PS384",
|
|
920
|
+
"PS512"
|
|
921
|
+
];
|
|
922
|
+
var base64Url = (bytes) => {
|
|
923
|
+
let binary = "";
|
|
924
|
+
for (const byte of bytes) {
|
|
925
|
+
binary += String.fromCharCode(byte);
|
|
926
|
+
}
|
|
927
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
928
|
+
};
|
|
929
|
+
var base64UrlJson = (value) => base64Url(new TextEncoder().encode(JSON.stringify(value)));
|
|
930
|
+
var isCryptoKey = (key) => typeof key.extractable === "boolean" && typeof key.algorithm === "object" && Array.isArray(key.usages);
|
|
931
|
+
var signAssertionInput = async (algorithm, privateKey, input) => {
|
|
932
|
+
const bits = algorithm.slice(2);
|
|
933
|
+
const hash = `SHA-${bits}`;
|
|
934
|
+
const family = algorithm.slice(0, 2);
|
|
935
|
+
const importAs = family === "ES" ? { name: "ECDSA", namedCurve: bits === "512" ? "P-521" : `P-${bits}` } : { name: family === "PS" ? "RSA-PSS" : "RSASSA-PKCS1-v1_5", hash };
|
|
936
|
+
const signAs = family === "ES" ? { name: "ECDSA", hash } : family === "PS" ? { name: "RSA-PSS", saltLength: Number(bits) / 8 } : { name: "RSASSA-PKCS1-v1_5" };
|
|
937
|
+
const { subtle } = globalThis.crypto;
|
|
938
|
+
let key;
|
|
939
|
+
if (isCryptoKey(privateKey)) {
|
|
940
|
+
key = privateKey;
|
|
941
|
+
const made = key.algorithm;
|
|
942
|
+
const fits = key.type === "private" && made.name === importAs.name && (family === "ES" ? made.namedCurve === importAs.namedCurve : made.hash?.name === hash);
|
|
943
|
+
if (!fits) {
|
|
944
|
+
throw new Error("key does not fit the algorithm");
|
|
945
|
+
}
|
|
946
|
+
} else {
|
|
947
|
+
if (typeof privateKey.d !== "string") {
|
|
948
|
+
throw new Error("not a private key");
|
|
949
|
+
}
|
|
950
|
+
const { alg: _alg, use: _use, key_ops: _ops, ...jwk } = privateKey;
|
|
951
|
+
key = await subtle.importKey("jwk", jwk, importAs, false, ["sign"]);
|
|
952
|
+
}
|
|
953
|
+
return new Uint8Array(await subtle.sign(signAs, key, new TextEncoder().encode(input)));
|
|
954
|
+
};
|
|
955
|
+
var keySecrets = (key) => {
|
|
956
|
+
if (key === void 0) {
|
|
957
|
+
return [];
|
|
958
|
+
}
|
|
959
|
+
const jwk = key;
|
|
960
|
+
return ["d", "p", "q", "dp", "dq", "qi", "k"].map((member) => jwk[member]).filter((v) => typeof v === "string" && v.length > 0);
|
|
961
|
+
};
|
|
962
|
+
var createClientAssertion = async (req) => {
|
|
963
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
964
|
+
const header = {
|
|
965
|
+
alg: req.algorithm,
|
|
966
|
+
typ: req.type === "JWT" ? "JWT" : "client-authentication+jwt",
|
|
967
|
+
...req.keyId ? { kid: req.keyId } : {}
|
|
968
|
+
};
|
|
969
|
+
const payload = {
|
|
970
|
+
iss: req.clientId,
|
|
971
|
+
sub: req.clientId,
|
|
972
|
+
aud: req.audience,
|
|
973
|
+
jti: globalThis.crypto.randomUUID(),
|
|
974
|
+
iat: now,
|
|
975
|
+
exp: now + CLIENT_ASSERTION_LIFETIME_SECONDS
|
|
976
|
+
};
|
|
977
|
+
const input = `${base64UrlJson(header)}.${base64UrlJson(payload)}`;
|
|
978
|
+
let signature;
|
|
979
|
+
try {
|
|
980
|
+
signature = await signAssertionInput(req.algorithm, req.privateKey, input);
|
|
981
|
+
} catch {
|
|
982
|
+
throw new Error(
|
|
983
|
+
`Enterprise MCP authorization: could not sign the client assertion with ${req.algorithm}; check that privateKey is a private key for that algorithm`
|
|
984
|
+
);
|
|
985
|
+
}
|
|
986
|
+
return `${input}.${base64Url(signature)}`;
|
|
987
|
+
};
|
|
988
|
+
var requestIdJag = async (req) => {
|
|
989
|
+
const { idp } = req;
|
|
990
|
+
const secrets = [
|
|
991
|
+
req.idToken,
|
|
992
|
+
idp.clientSecret,
|
|
993
|
+
req.clientAssertion,
|
|
994
|
+
...keySecrets(idp.privateKey)
|
|
995
|
+
];
|
|
996
|
+
const said = (value, max) => printable(typeof value === "string" ? redact(value, secrets) : value, max);
|
|
997
|
+
const fail = (message, code) => {
|
|
998
|
+
throw new EnterpriseOAuthError(
|
|
999
|
+
"idp",
|
|
1000
|
+
redact(`Enterprise IdP token exchange failed: ${message}`, secrets),
|
|
1001
|
+
code
|
|
1002
|
+
);
|
|
1003
|
+
};
|
|
1004
|
+
const params = new URLSearchParams({
|
|
1005
|
+
grant_type: GRANT_TOKEN_EXCHANGE,
|
|
1006
|
+
requested_token_type: TOKEN_TYPE_ID_JAG,
|
|
1007
|
+
audience: req.audience,
|
|
1008
|
+
resource: req.resource,
|
|
1009
|
+
subject_token: req.idToken,
|
|
1010
|
+
subject_token_type: TOKEN_TYPE_ID_TOKEN
|
|
1011
|
+
});
|
|
1012
|
+
if (req.scope) {
|
|
1013
|
+
params.set("scope", req.scope);
|
|
1014
|
+
}
|
|
1015
|
+
const headers = new Headers({
|
|
1016
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
1017
|
+
Accept: "application/json"
|
|
1018
|
+
});
|
|
1019
|
+
if (idp.clientAuthMethod === "private_key_jwt") {
|
|
1020
|
+
if (!req.clientAssertion) {
|
|
1021
|
+
return fail("no client assertion was made for the identity provider");
|
|
1022
|
+
}
|
|
1023
|
+
params.set("client_assertion_type", CLIENT_ASSERTION_TYPE);
|
|
1024
|
+
params.set("client_assertion", req.clientAssertion);
|
|
1025
|
+
} else if (idp.clientSecret === void 0 || idp.clientAuthMethod === "client_secret_post") {
|
|
1026
|
+
params.set("client_id", idp.clientId);
|
|
1027
|
+
if (idp.clientSecret !== void 0) {
|
|
1028
|
+
params.set("client_secret", idp.clientSecret);
|
|
1029
|
+
}
|
|
1030
|
+
} else {
|
|
1031
|
+
headers.set(
|
|
1032
|
+
"Authorization",
|
|
1033
|
+
`Basic ${btoa(`${formEncode(idp.clientId)}:${formEncode(idp.clientSecret)}`)}`
|
|
1034
|
+
);
|
|
1035
|
+
}
|
|
1036
|
+
let response;
|
|
1037
|
+
try {
|
|
1038
|
+
response = await (req.fetch ?? fetch)(idp.tokenEndpoint, {
|
|
1039
|
+
method: "POST",
|
|
1040
|
+
headers,
|
|
1041
|
+
body: params,
|
|
1042
|
+
redirect: "error"
|
|
1043
|
+
});
|
|
1044
|
+
} catch (err) {
|
|
1045
|
+
return fail(
|
|
1046
|
+
`the request did not complete (${said(err?.message) ?? "network error"})`
|
|
1047
|
+
);
|
|
1048
|
+
}
|
|
1049
|
+
let body = {};
|
|
1050
|
+
try {
|
|
1051
|
+
const parsed = await response.json();
|
|
1052
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
1053
|
+
body = parsed;
|
|
1054
|
+
}
|
|
1055
|
+
} catch {
|
|
1056
|
+
}
|
|
1057
|
+
if (!response.ok) {
|
|
1058
|
+
const code = said(body.error, 80);
|
|
1059
|
+
const description = said(body.error_description);
|
|
1060
|
+
return fail(
|
|
1061
|
+
`the identity provider answered ${response.status}${code ? ` ${code}` : ""}${description ? ` - ${description}` : ""}`,
|
|
1062
|
+
code
|
|
1063
|
+
);
|
|
1064
|
+
}
|
|
1065
|
+
if (body.issued_token_type !== TOKEN_TYPE_ID_JAG) {
|
|
1066
|
+
return fail(
|
|
1067
|
+
`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`
|
|
1068
|
+
);
|
|
1069
|
+
}
|
|
1070
|
+
if (typeof body.access_token !== "string" || !body.access_token) {
|
|
1071
|
+
return fail(
|
|
1072
|
+
"the identity provider returned no ID-JAG; nothing was sent to the MCP authorization server"
|
|
1073
|
+
);
|
|
1074
|
+
}
|
|
1075
|
+
return body.access_token;
|
|
1076
|
+
};
|
|
1077
|
+
var looksLikeUrl = (value) => /^[a-z][a-z0-9+.-]*:\/\//i.test(value);
|
|
1078
|
+
var configError = (message) => new Error(`Enterprise MCP authorization: ${message}`);
|
|
1079
|
+
var ASSERTION_AUDIENCES = ["issuer", "token-endpoint"];
|
|
1080
|
+
var ASSERTION_TYPES = ["client-authentication+jwt", "JWT"];
|
|
1081
|
+
var checkAssertionShape = (prefix, hop) => {
|
|
1082
|
+
if (hop.assertionAudience !== void 0 && !ASSERTION_AUDIENCES.includes(hop.assertionAudience)) {
|
|
1083
|
+
throw configError(`${prefix}assertionAudience must be 'issuer' or 'token-endpoint'`);
|
|
1084
|
+
}
|
|
1085
|
+
if (hop.assertionType !== void 0 && !ASSERTION_TYPES.includes(hop.assertionType)) {
|
|
1086
|
+
throw configError(`${prefix}assertionType must be 'client-authentication+jwt' or 'JWT'`);
|
|
1087
|
+
}
|
|
1088
|
+
if (hop.clientAuthMethod !== "private_key_jwt" && (hop.assertionAudience !== void 0 || hop.assertionType !== void 0)) {
|
|
1089
|
+
throw configError(
|
|
1090
|
+
`${prefix}assertionAudience and ${prefix}assertionType are only used with ${prefix}clientAuthMethod 'private_key_jwt'`
|
|
1091
|
+
);
|
|
1092
|
+
}
|
|
1093
|
+
};
|
|
1094
|
+
var checkOptions = (opts) => {
|
|
1095
|
+
assertSecureOAuthUrl(opts.serverUrl);
|
|
1096
|
+
assertSecureOAuthUrl(opts.idp?.tokenEndpoint, "Enterprise IdP token endpoint");
|
|
1097
|
+
if (opts.expectedIssuer !== void 0) {
|
|
1098
|
+
assertSecureOAuthUrl(opts.expectedIssuer, "MCP authorization server");
|
|
1099
|
+
}
|
|
1100
|
+
const { idp } = opts;
|
|
1101
|
+
if (!opts.clientId || !idp.clientId) {
|
|
1102
|
+
throw configError("clientId and idp.clientId are required");
|
|
1103
|
+
}
|
|
1104
|
+
if (typeof opts.getIdToken !== "function") {
|
|
1105
|
+
throw configError("getIdToken is required");
|
|
1106
|
+
}
|
|
1107
|
+
const method = opts.clientAuthMethod;
|
|
1108
|
+
if (looksLikeUrl(opts.clientId)) {
|
|
1109
|
+
let url;
|
|
1110
|
+
try {
|
|
1111
|
+
url = new URL(opts.clientId);
|
|
1112
|
+
} catch {
|
|
1113
|
+
}
|
|
1114
|
+
if (!url || url.protocol !== "https:" || url.pathname === "/") {
|
|
1115
|
+
throw configError(
|
|
1116
|
+
`a clientId that is a URL is a client ID metadata document: it requires https and a non-root path - refusing "${opts.clientId}"`
|
|
1117
|
+
);
|
|
1118
|
+
}
|
|
1119
|
+
if (opts.clientSecret) {
|
|
1120
|
+
throw configError(
|
|
1121
|
+
"a client ID metadata document cannot be used with clientSecret: use private_key_jwt, or no credential"
|
|
1122
|
+
);
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
if (opts.clientSecret && (method === "private_key_jwt" || method === "none")) {
|
|
1126
|
+
throw configError(`clientSecret is not used with clientAuthMethod '${method}': remove one`);
|
|
1127
|
+
}
|
|
1128
|
+
if ((method === "client_secret_basic" || method === "client_secret_post") && !opts.clientSecret) {
|
|
1129
|
+
throw configError(`clientAuthMethod '${method}' needs clientSecret`);
|
|
1130
|
+
}
|
|
1131
|
+
if (opts.clientSecret && opts.expectedIssuer === void 0) {
|
|
1132
|
+
throw configError(
|
|
1133
|
+
"clientSecret needs expectedIssuer: without the issuer of the authorization server, the MCP server decides who receives the secret"
|
|
1134
|
+
);
|
|
1135
|
+
}
|
|
1136
|
+
if (method === "private_key_jwt") {
|
|
1137
|
+
if (opts.privateKey === void 0 || !ALGORITHMS.includes(opts.algorithm)) {
|
|
1138
|
+
throw configError(
|
|
1139
|
+
`clientAuthMethod 'private_key_jwt' needs privateKey and an algorithm (${ALGORITHMS.join(", ")})`
|
|
1140
|
+
);
|
|
1141
|
+
}
|
|
1142
|
+
if (opts.expectedIssuer === void 0) {
|
|
1143
|
+
throw configError(
|
|
1144
|
+
"private_key_jwt needs expectedIssuer: the audience of the client assertion must not come from the MCP server alone"
|
|
1145
|
+
);
|
|
1146
|
+
}
|
|
1147
|
+
} else if (opts.privateKey !== void 0) {
|
|
1148
|
+
throw configError("privateKey is only used with clientAuthMethod 'private_key_jwt'");
|
|
1149
|
+
}
|
|
1150
|
+
checkAssertionShape("", opts);
|
|
1151
|
+
checkAssertionShape("idp.", idp);
|
|
1152
|
+
if (idp.clientAuthMethod === "private_key_jwt") {
|
|
1153
|
+
if (idp.privateKey === void 0 || !ALGORITHMS.includes(idp.algorithm)) {
|
|
1154
|
+
throw configError(
|
|
1155
|
+
`idp.clientAuthMethod 'private_key_jwt' needs idp.privateKey and an idp.algorithm (${ALGORITHMS.join(", ")})`
|
|
1156
|
+
);
|
|
1157
|
+
}
|
|
1158
|
+
if (idp.assertionAudience !== "token-endpoint" && !idp.issuer) {
|
|
1159
|
+
throw configError(
|
|
1160
|
+
"idp.clientAuthMethod private_key_jwt needs idp.issuer: it is the audience of the client assertion (or set idp.assertionAudience to 'token-endpoint')"
|
|
1161
|
+
);
|
|
1162
|
+
}
|
|
1163
|
+
if (idp.clientSecret) {
|
|
1164
|
+
throw configError("idp.clientSecret is not used with idp.clientAuthMethod 'private_key_jwt'");
|
|
1165
|
+
}
|
|
1166
|
+
} else if (idp.privateKey !== void 0) {
|
|
1167
|
+
throw configError("idp.privateKey is only used with idp.clientAuthMethod 'private_key_jwt'");
|
|
1168
|
+
}
|
|
1169
|
+
if (idp.issuer !== void 0) {
|
|
1170
|
+
assertSecureOAuthUrl(idp.issuer, "Enterprise IdP issuer");
|
|
1171
|
+
}
|
|
1172
|
+
};
|
|
1173
|
+
var formParam = (body, name) => {
|
|
1174
|
+
if (body instanceof URLSearchParams) {
|
|
1175
|
+
return body.get(name) ?? void 0;
|
|
1176
|
+
}
|
|
1177
|
+
if (typeof body === "string") {
|
|
1178
|
+
return new URLSearchParams(body).get(name) ?? void 0;
|
|
1179
|
+
}
|
|
1180
|
+
return void 0;
|
|
1181
|
+
};
|
|
1182
|
+
var oauthCode = (value) => typeof value === "string" && /^[A-Za-z0-9_.-]{1,64}$/.test(value) ? value : void 0;
|
|
1183
|
+
var BrowserEnterpriseOAuthProvider = class {
|
|
1184
|
+
serverUrl;
|
|
1185
|
+
/** The MCP extension this provider implements; the connector declares it. */
|
|
1186
|
+
extension = ENTERPRISE_MANAGED_AUTHORIZATION_EXTENSION;
|
|
1187
|
+
/**
|
|
1188
|
+
* Present only with an explicit `clientAuthMethod`: the SDK then leaves the
|
|
1189
|
+
* client authentication of the grant to it (a `private_key_jwt` assertion is
|
|
1190
|
+
* signed here, for the issuer discovery found and `expectedIssuer` confirmed).
|
|
1191
|
+
*/
|
|
1192
|
+
addClientAuthentication;
|
|
1193
|
+
// True private fields: the options hold the secrets, the private keys and the
|
|
1194
|
+
// ID token callback, and nothing that prints or serializes the provider
|
|
1195
|
+
// (console.log, the devtools object view, JSON.stringify) can reach them.
|
|
1196
|
+
#opts;
|
|
1197
|
+
#storage;
|
|
1198
|
+
#ns;
|
|
1199
|
+
#skewMs;
|
|
1200
|
+
#clientMetadata;
|
|
1201
|
+
// Held (in memory only) between a granted ID-JAG and the access token it
|
|
1202
|
+
// buys: a failure in that window belongs to the MCP authorization server,
|
|
1203
|
+
// and nothing said about it may carry the grant or the client assertion.
|
|
1204
|
+
#pendingAssertion;
|
|
1205
|
+
#pendingClientAssertion;
|
|
1206
|
+
constructor(opts) {
|
|
1207
|
+
checkOptions(opts);
|
|
1208
|
+
this.serverUrl = opts.serverUrl;
|
|
1209
|
+
this.#opts = opts;
|
|
1210
|
+
this.#storage = opts.storage ?? new VaultOAuthStorage();
|
|
1211
|
+
this.#ns = namespaceFor2(opts.serverUrl);
|
|
1212
|
+
this.#skewMs = (opts.expirySkewSeconds ?? DEFAULT_SKEW_SECONDS2) * 1e3;
|
|
1213
|
+
this.#clientMetadata = {
|
|
1214
|
+
client_name: "agent-web",
|
|
1215
|
+
redirect_uris: [],
|
|
1216
|
+
grant_types: [GRANT_TOKEN_EXCHANGE, GRANT_JWT_BEARER],
|
|
1217
|
+
token_endpoint_auth_method: opts.clientAuthMethod ?? (opts.clientSecret ? "client_secret_basic" : "none"),
|
|
1218
|
+
...opts.scope ? { scope: opts.scope } : {}
|
|
1219
|
+
};
|
|
1220
|
+
if (opts.clientAuthMethod !== void 0) {
|
|
1221
|
+
this.addClientAuthentication = (headers, params) => this.#authenticateClient(headers, params);
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
/** Never set: this is what tells the SDK the flow has no human step. */
|
|
1225
|
+
get redirectUrl() {
|
|
1226
|
+
return void 0;
|
|
1227
|
+
}
|
|
1228
|
+
get clientMetadata() {
|
|
1229
|
+
return this.#clientMetadata;
|
|
1230
|
+
}
|
|
1231
|
+
#key(suffix) {
|
|
1232
|
+
return `${this.#ns}:${suffix}`;
|
|
1233
|
+
}
|
|
1234
|
+
async #readJSON(suffix) {
|
|
1235
|
+
try {
|
|
1236
|
+
const raw = await this.#storage.get(this.#key(suffix));
|
|
1237
|
+
if (raw === void 0) {
|
|
1238
|
+
return void 0;
|
|
1239
|
+
}
|
|
1240
|
+
return JSON.parse(raw);
|
|
1241
|
+
} catch {
|
|
1242
|
+
await this.#storage.delete(this.#key(suffix)).catch(() => {
|
|
1243
|
+
});
|
|
1244
|
+
return void 0;
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
/** Everything of this provider that must not appear in an error or a log line. */
|
|
1248
|
+
#secrets() {
|
|
1249
|
+
return [
|
|
1250
|
+
this.#pendingAssertion,
|
|
1251
|
+
this.#pendingClientAssertion,
|
|
1252
|
+
this.#opts.clientSecret,
|
|
1253
|
+
this.#opts.idp.clientSecret,
|
|
1254
|
+
...keySecrets(this.#opts.privateKey),
|
|
1255
|
+
...keySecrets(this.#opts.idp.privateKey)
|
|
1256
|
+
];
|
|
1257
|
+
}
|
|
1258
|
+
/** The detail an error leaves out, to the log: redacted first, then clipped. */
|
|
1259
|
+
#report(log, detail) {
|
|
1260
|
+
const sink = log ?? this.#opts.onLog ?? ((_level, message) => createLogger().warn(message));
|
|
1261
|
+
const safe = printable(redact(detail, this.#secrets()), 600) ?? "no detail";
|
|
1262
|
+
try {
|
|
1263
|
+
sink("warn", `[mcp] enterprise authorization for ${this.serverUrl}: ${safe}`);
|
|
1264
|
+
} catch {
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
/**
|
|
1268
|
+
* The pre-registered client, from configuration and never from storage.
|
|
1269
|
+
* With `expectedIssuer` it carries that stamp, and the SDK then refuses to
|
|
1270
|
+
* present it to any other authorization server.
|
|
1271
|
+
*/
|
|
1272
|
+
clientInformation() {
|
|
1273
|
+
return {
|
|
1274
|
+
client_id: this.#opts.clientId,
|
|
1275
|
+
...this.#opts.clientSecret ? { client_secret: this.#opts.clientSecret } : {},
|
|
1276
|
+
...this.#opts.expectedIssuer ? { issuer: this.#opts.expectedIssuer } : {}
|
|
1277
|
+
};
|
|
1278
|
+
}
|
|
1279
|
+
async tokens() {
|
|
1280
|
+
return (await this.#readJSON("tokens"))?.tokens;
|
|
1281
|
+
}
|
|
1282
|
+
async saveTokens(tokens) {
|
|
1283
|
+
this.#pendingAssertion = void 0;
|
|
1284
|
+
this.#pendingClientAssertion = void 0;
|
|
1285
|
+
const stored = {
|
|
1286
|
+
tokens,
|
|
1287
|
+
expiresAt: typeof tokens.expires_in === "number" ? Date.now() + tokens.expires_in * 1e3 : void 0
|
|
1288
|
+
};
|
|
1289
|
+
await this.#storage.set(this.#key("tokens"), JSON.stringify(stored));
|
|
1290
|
+
}
|
|
1291
|
+
async saveDiscoveryState(state) {
|
|
1292
|
+
await this.#storage.set(this.#key("discovery"), JSON.stringify(state));
|
|
1293
|
+
}
|
|
1294
|
+
async discoveryState() {
|
|
1295
|
+
const state = await this.#readJSON("discovery");
|
|
1296
|
+
if (!state || typeof state !== "object" || typeof state.authorizationServerUrl !== "string") {
|
|
1297
|
+
return void 0;
|
|
1298
|
+
}
|
|
1299
|
+
return state;
|
|
1300
|
+
}
|
|
1301
|
+
/**
|
|
1302
|
+
* Called by the SDK inside `auth()`, after discovery and before the token
|
|
1303
|
+
* request to the MCP authorization server: get an ID token from the host,
|
|
1304
|
+
* exchange it at the IdP for an ID-JAG addressed to exactly the authorization
|
|
1305
|
+
* server and resource discovery found for this server, and hand the SDK the
|
|
1306
|
+
* `jwt-bearer` request. Throws before anything reaches the authorization
|
|
1307
|
+
* server when discovery cannot be trusted or the IdP's answer is not an ID-JAG.
|
|
1308
|
+
*/
|
|
1309
|
+
async prepareTokenRequest(scope) {
|
|
1310
|
+
this.#pendingAssertion = void 0;
|
|
1311
|
+
this.#pendingClientAssertion = void 0;
|
|
1312
|
+
let target;
|
|
1313
|
+
try {
|
|
1314
|
+
target = enterpriseGrantTarget(
|
|
1315
|
+
this.serverUrl,
|
|
1316
|
+
await this.discoveryState(),
|
|
1317
|
+
this.#opts.expectedIssuer
|
|
1318
|
+
);
|
|
1319
|
+
} catch (err) {
|
|
1320
|
+
await this.#storage.delete(this.#key("discovery"));
|
|
1321
|
+
throw err;
|
|
1322
|
+
}
|
|
1323
|
+
let idToken;
|
|
1324
|
+
try {
|
|
1325
|
+
idToken = await this.#opts.getIdToken();
|
|
1326
|
+
} catch {
|
|
1327
|
+
throw new EnterpriseOAuthError(
|
|
1328
|
+
"idp",
|
|
1329
|
+
"Enterprise IdP token exchange failed: getIdToken() threw, so there is no ID token to exchange"
|
|
1330
|
+
);
|
|
1331
|
+
}
|
|
1332
|
+
if (typeof idToken !== "string" || !idToken) {
|
|
1333
|
+
throw new EnterpriseOAuthError(
|
|
1334
|
+
"idp",
|
|
1335
|
+
"Enterprise IdP token exchange failed: getIdToken() returned no ID token"
|
|
1336
|
+
);
|
|
1337
|
+
}
|
|
1338
|
+
const { idp } = this.#opts;
|
|
1339
|
+
const clientAssertion = idp.clientAuthMethod === "private_key_jwt" ? await createClientAssertion({
|
|
1340
|
+
clientId: idp.clientId,
|
|
1341
|
+
audience: idp.assertionAudience === "token-endpoint" ? idp.tokenEndpoint : idp.issuer,
|
|
1342
|
+
privateKey: idp.privateKey,
|
|
1343
|
+
algorithm: idp.algorithm,
|
|
1344
|
+
keyId: idp.keyId,
|
|
1345
|
+
type: idp.assertionType
|
|
1346
|
+
}).catch((err) => {
|
|
1347
|
+
throw new EnterpriseOAuthError("idp", err.message);
|
|
1348
|
+
}) : void 0;
|
|
1349
|
+
const assertion = await requestIdJag({
|
|
1350
|
+
idp,
|
|
1351
|
+
idToken,
|
|
1352
|
+
audience: target.audience,
|
|
1353
|
+
resource: target.resource,
|
|
1354
|
+
scope: scope ?? this.#opts.scope,
|
|
1355
|
+
clientAssertion,
|
|
1356
|
+
fetch: this.#opts.fetch
|
|
1357
|
+
});
|
|
1358
|
+
this.#pendingAssertion = assertion;
|
|
1359
|
+
return new URLSearchParams({ grant_type: GRANT_JWT_BEARER, assertion });
|
|
1360
|
+
}
|
|
1361
|
+
/** The client authentication of the grant, when `clientAuthMethod` says how. */
|
|
1362
|
+
async #authenticateClient(headers, params) {
|
|
1363
|
+
const { clientId, clientSecret, clientAuthMethod } = this.#opts;
|
|
1364
|
+
if (clientAuthMethod === "private_key_jwt") {
|
|
1365
|
+
const target = enterpriseGrantTarget(
|
|
1366
|
+
this.serverUrl,
|
|
1367
|
+
await this.discoveryState(),
|
|
1368
|
+
this.#opts.expectedIssuer
|
|
1369
|
+
);
|
|
1370
|
+
const audience = this.#opts.assertionAudience === "token-endpoint" ? target.tokenEndpoint : target.audience;
|
|
1371
|
+
if (audience === void 0) {
|
|
1372
|
+
this.#pendingAssertion = void 0;
|
|
1373
|
+
throw new EnterpriseOAuthError(
|
|
1374
|
+
"discovery",
|
|
1375
|
+
`Enterprise MCP authorization: the authorization server "${target.audience}" published no token endpoint, so there is no audience for the client assertion (assertionAudience 'token-endpoint')`
|
|
1376
|
+
);
|
|
1377
|
+
}
|
|
1378
|
+
const assertion = await createClientAssertion({
|
|
1379
|
+
clientId,
|
|
1380
|
+
audience,
|
|
1381
|
+
privateKey: this.#opts.privateKey,
|
|
1382
|
+
algorithm: this.#opts.algorithm,
|
|
1383
|
+
keyId: this.#opts.keyId,
|
|
1384
|
+
type: this.#opts.assertionType
|
|
1385
|
+
}).catch((err) => {
|
|
1386
|
+
this.#pendingAssertion = void 0;
|
|
1387
|
+
throw new EnterpriseOAuthError("authorization-server", err.message);
|
|
1388
|
+
});
|
|
1389
|
+
this.#pendingClientAssertion = assertion;
|
|
1390
|
+
params.set("client_assertion_type", CLIENT_ASSERTION_TYPE);
|
|
1391
|
+
params.set("client_assertion", assertion);
|
|
1392
|
+
return;
|
|
1393
|
+
}
|
|
1394
|
+
if (clientAuthMethod === "client_secret_basic") {
|
|
1395
|
+
headers.set(
|
|
1396
|
+
"Authorization",
|
|
1397
|
+
`Basic ${btoa(`${formEncode(clientId)}:${formEncode(clientSecret)}`)}`
|
|
1398
|
+
);
|
|
1399
|
+
return;
|
|
1400
|
+
}
|
|
1401
|
+
params.set("client_id", clientId);
|
|
1402
|
+
if (clientAuthMethod === "client_secret_post") {
|
|
1403
|
+
params.set("client_secret", clientSecret);
|
|
1404
|
+
}
|
|
1405
|
+
}
|
|
1406
|
+
/** The codes of the interactive flow: this provider has none. */
|
|
1407
|
+
redirectToAuthorization() {
|
|
1408
|
+
throw new Error("Enterprise MCP authorization has no interactive step");
|
|
1409
|
+
}
|
|
1410
|
+
saveCodeVerifier() {
|
|
1411
|
+
throw new Error("Enterprise MCP authorization has no interactive step");
|
|
1412
|
+
}
|
|
1413
|
+
codeVerifier() {
|
|
1414
|
+
throw new Error("Enterprise MCP authorization has no interactive step");
|
|
1415
|
+
}
|
|
1416
|
+
/**
|
|
1417
|
+
* Called by the SDK when the authorization server rejects what it was sent.
|
|
1418
|
+
* The client is configuration, so there is nothing of it to forget; tokens
|
|
1419
|
+
* and discovery are dropped as asked.
|
|
1420
|
+
*/
|
|
1421
|
+
async invalidateCredentials(scope) {
|
|
1422
|
+
const targets = scope === "all" ? ["tokens", "discovery"] : scope === "tokens" || scope === "discovery" ? [scope] : [];
|
|
1423
|
+
await Promise.all(targets.map((t) => this.#storage.delete(this.#key(t))));
|
|
1424
|
+
}
|
|
1425
|
+
/** True when there is no access token, or it expires within the skew window. */
|
|
1426
|
+
async isAccessTokenExpired() {
|
|
1427
|
+
const stored = await this.#readJSON("tokens");
|
|
1428
|
+
if (!stored?.tokens?.access_token) {
|
|
1429
|
+
return true;
|
|
1430
|
+
}
|
|
1431
|
+
if (stored.expiresAt === void 0) {
|
|
1432
|
+
return false;
|
|
1433
|
+
}
|
|
1434
|
+
return Date.now() + this.#skewMs >= stored.expiresAt;
|
|
1435
|
+
}
|
|
1436
|
+
async isAuthorized() {
|
|
1437
|
+
return await this.tokens() !== void 0;
|
|
1438
|
+
}
|
|
1439
|
+
/**
|
|
1440
|
+
* The fetch to give the transport that carries this provider (the connector
|
|
1441
|
+
* does). It changes one thing: when the request that carries the ID-JAG is
|
|
1442
|
+
* refused, the caller gets an `EnterpriseOAuthError` (`hop:
|
|
1443
|
+
* 'authorization-server'`) with a short message - the OAuth error code and
|
|
1444
|
+
* the status - and what the server said in full goes to `log`, redacted.
|
|
1445
|
+
* That holds whenever the SDK asks for a token, at connect or in the middle
|
|
1446
|
+
* of a session, so an application never has the server's raw words to show.
|
|
1447
|
+
* A refusal is final: every grant is already a fresh one, so the SDK's
|
|
1448
|
+
* "drop the token and try again" would only repeat the IdP exchange.
|
|
1449
|
+
*/
|
|
1450
|
+
transportFetch(base, log) {
|
|
1451
|
+
const inner = base ?? ((url, init) => fetch(url, init));
|
|
1452
|
+
return async (url, init) => {
|
|
1453
|
+
const grant = this.#pendingAssertion;
|
|
1454
|
+
if (grant === void 0 || formParam(init?.body, "assertion") !== grant) {
|
|
1455
|
+
return inner(url, init);
|
|
1456
|
+
}
|
|
1457
|
+
let response;
|
|
1458
|
+
try {
|
|
1459
|
+
response = await inner(url, init);
|
|
1460
|
+
} catch (err) {
|
|
1461
|
+
this.#report(log, `the grant request did not complete: ${err?.message ?? err}`);
|
|
1462
|
+
this.#pendingAssertion = void 0;
|
|
1463
|
+
this.#pendingClientAssertion = void 0;
|
|
1464
|
+
throw new EnterpriseOAuthError(
|
|
1465
|
+
"authorization-server",
|
|
1466
|
+
"MCP authorization server could not be reached for the ID-JAG grant"
|
|
1467
|
+
);
|
|
1468
|
+
}
|
|
1469
|
+
if (response.status < 400) {
|
|
1470
|
+
return response;
|
|
1471
|
+
}
|
|
1472
|
+
const text = await response.text().catch(() => "");
|
|
1473
|
+
let body = {};
|
|
1474
|
+
try {
|
|
1475
|
+
const parsed = JSON.parse(text);
|
|
1476
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
1477
|
+
body = parsed;
|
|
1478
|
+
}
|
|
1479
|
+
} catch {
|
|
1480
|
+
}
|
|
1481
|
+
const code = oauthCode(body.error);
|
|
1482
|
+
const description = typeof body.error_description === "string" ? body.error_description : text;
|
|
1483
|
+
this.#report(
|
|
1484
|
+
log,
|
|
1485
|
+
`the authorization server refused the ID-JAG grant with ${response.status}${code ? ` ${code}` : ""}${description ? `: ${description}` : ""}`
|
|
1486
|
+
);
|
|
1487
|
+
this.#pendingAssertion = void 0;
|
|
1488
|
+
this.#pendingClientAssertion = void 0;
|
|
1489
|
+
throw new EnterpriseOAuthError(
|
|
1490
|
+
"authorization-server",
|
|
1491
|
+
`MCP authorization server refused the ID-JAG grant: ${code ?? "no error code"} (HTTP ${response.status})`,
|
|
1492
|
+
code
|
|
1493
|
+
);
|
|
1494
|
+
};
|
|
1495
|
+
}
|
|
1496
|
+
/**
|
|
1497
|
+
* Run the whole flow now (discovery, IdP exchange, grant) and store the
|
|
1498
|
+
* access token. `connectMcpHttp` calls it before connecting when there is
|
|
1499
|
+
* no usable token; call it yourself to fail early. A refusal is an
|
|
1500
|
+
* `EnterpriseOAuthError` whose `hop` says who refused.
|
|
1501
|
+
*/
|
|
1502
|
+
async authorize(opts = {}) {
|
|
1503
|
+
try {
|
|
1504
|
+
await (0, import_auth3.auth)(this, {
|
|
1505
|
+
serverUrl: this.serverUrl,
|
|
1506
|
+
fetchFn: this.transportFetch(opts.fetch, opts.onLog)
|
|
1507
|
+
});
|
|
1508
|
+
} catch (err) {
|
|
1509
|
+
if (err instanceof EnterpriseOAuthError) {
|
|
1510
|
+
throw err;
|
|
1511
|
+
}
|
|
1512
|
+
const detail = err?.message ?? String(err);
|
|
1513
|
+
if (this.#pendingAssertion !== void 0) {
|
|
1514
|
+
this.#report(opts.onLog, `the answer to the ID-JAG grant could not be used: ${detail}`);
|
|
1515
|
+
this.#pendingAssertion = void 0;
|
|
1516
|
+
this.#pendingClientAssertion = void 0;
|
|
1517
|
+
throw new EnterpriseOAuthError(
|
|
1518
|
+
"authorization-server",
|
|
1519
|
+
"MCP authorization server answered the ID-JAG grant with something that is not a token response"
|
|
1520
|
+
);
|
|
1521
|
+
}
|
|
1522
|
+
await this.#storage.delete(this.#key("discovery")).catch(() => {
|
|
1523
|
+
});
|
|
1524
|
+
const message = printable(redact(detail, this.#secrets()), 500) ?? "no reason given";
|
|
1525
|
+
throw new EnterpriseOAuthError(
|
|
1526
|
+
"discovery",
|
|
1527
|
+
`Enterprise MCP authorization: discovery failed (${message})`,
|
|
1528
|
+
oauthCode(err?.errorCode)
|
|
1529
|
+
);
|
|
1530
|
+
}
|
|
1531
|
+
}
|
|
1532
|
+
/** Forget the access token and what discovery found for this server. */
|
|
1533
|
+
async reset() {
|
|
1534
|
+
await this.invalidateCredentials("all");
|
|
1535
|
+
}
|
|
1536
|
+
};
|
|
1537
|
+
var createEnterpriseOAuthProvider = (opts) => new BrowserEnterpriseOAuthProvider(opts);
|
|
677
1538
|
// Annotate the CommonJS export names for ESM import in node:
|
|
678
1539
|
0 && (module.exports = {
|
|
1540
|
+
BrowserEnterpriseOAuthProvider,
|
|
679
1541
|
BrowserOAuthProvider,
|
|
1542
|
+
ENTERPRISE_MANAGED_AUTHORIZATION_EXTENSION,
|
|
1543
|
+
EnterpriseOAuthError,
|
|
680
1544
|
MemoryOAuthStorage,
|
|
681
1545
|
UnauthorizedError,
|
|
682
1546
|
VaultOAuthStorage,
|
|
683
1547
|
beginMcpOAuth,
|
|
1548
|
+
checkAuthorizationResponseIssuer,
|
|
684
1549
|
connectMcpHttp,
|
|
1550
|
+
createEnterpriseOAuthProvider,
|
|
685
1551
|
diagnoseMcpCors,
|
|
686
1552
|
finishMcpOAuth,
|
|
687
1553
|
flattenContent,
|