@mcpfn/auth 0.0.1 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,3 +1,41 @@
1
+ import { discoverOAuthProtectedResourceMetadata, discoverAuthorizationServerMetadata } from '@modelcontextprotocol/sdk/client/auth.js';
2
+ import { redactOAuthValue, generateStateId } from '@superfunctions/oauth-core';
3
+
4
+ // src/auth-response.ts
5
+ function json(status, body, headers = {}) {
6
+ return new Response(JSON.stringify(body), {
7
+ status,
8
+ headers: {
9
+ "content-type": "application/json; charset=utf-8",
10
+ "cache-control": "no-store",
11
+ ...Object.fromEntries(new Headers(headers))
12
+ }
13
+ });
14
+ }
15
+ function readBearerToken(request) {
16
+ if (new URL(request.url).searchParams.has("access_token")) return void 0;
17
+ const authorization = request.headers.get("authorization");
18
+ if (!authorization) return void 0;
19
+ const match = /^Bearer\s+([^\s]+)$/i.exec(authorization.trim());
20
+ return match?.[1];
21
+ }
22
+ function bearerChallengeResponse(status, metadataUrl, details) {
23
+ const fields = [
24
+ `resource_metadata="${metadataUrl.toString()}"`,
25
+ `error="${sanitizeChallengeValue(details.error)}"`,
26
+ `error_description="${sanitizeChallengeValue(details.description)}"`
27
+ ];
28
+ if (details.scope) fields.push(`scope="${sanitizeChallengeValue(details.scope)}"`);
29
+ return json(
30
+ status,
31
+ { error: details.error, error_description: details.description },
32
+ { "www-authenticate": `Bearer ${fields.join(", ")}` }
33
+ );
34
+ }
35
+ function sanitizeChallengeValue(value) {
36
+ return value.replace(/[\u0000-\u001f\u007f"\\]/g, "");
37
+ }
38
+
1
39
  // src/enterprise.ts
2
40
  var MCP_ENTERPRISE_MANAGED_AUTHORIZATION_EXTENSION_ID = "io.modelcontextprotocol/enterprise-managed-authorization";
3
41
  var MCP_ID_JAG_GRANT_PROFILE = "urn:ietf:params:oauth:grant-profile:id-jag";
@@ -21,6 +59,1594 @@ function enterpriseManagedAuthorizationClientMetadata() {
21
59
  }
22
60
  };
23
61
  }
62
+ async function diagnoseMcpAuthorization(target, options = {}) {
63
+ const targetUrl = new URL(target.toString());
64
+ targetUrl.hash = "";
65
+ const steps = [];
66
+ const fetchImplementation = boundedFetch(
67
+ options.fetchImplementation ?? globalThis.fetch,
68
+ options.timeoutMs ?? 1e4
69
+ );
70
+ let resourceMetadata;
71
+ let authorizationServerMetadata;
72
+ const resourceStartedAt = performance.now();
73
+ try {
74
+ resourceMetadata = await discoverOAuthProtectedResourceMetadata(
75
+ targetUrl,
76
+ {
77
+ protocolVersion: options.protocolVersion,
78
+ resourceMetadataUrl: options.resourceMetadataUrl
79
+ },
80
+ fetchImplementation
81
+ );
82
+ if (!resourceMetadata) {
83
+ throw new Error("No OAuth protected-resource metadata was found");
84
+ }
85
+ steps.push({
86
+ phase: "resource-discovery",
87
+ status: "passed",
88
+ durationMs: performance.now() - resourceStartedAt
89
+ });
90
+ } catch (error) {
91
+ steps.push({
92
+ phase: "resource-discovery",
93
+ status: "failed",
94
+ durationMs: performance.now() - resourceStartedAt,
95
+ error: errorMessage(error)
96
+ });
97
+ return redactReport({ ok: false, target: targetUrl.toString(), steps });
98
+ }
99
+ const authorizationServerUrl = resourceMetadata?.authorization_servers?.[0] ?? targetUrl.origin;
100
+ const authorizationStartedAt = performance.now();
101
+ try {
102
+ authorizationServerMetadata = await discoverAuthorizationServerMetadata(
103
+ authorizationServerUrl,
104
+ {
105
+ fetchFn: fetchImplementation,
106
+ protocolVersion: options.protocolVersion
107
+ }
108
+ );
109
+ if (!authorizationServerMetadata) {
110
+ throw new Error("No RFC 8414 or OpenID Connect authorization metadata was found");
111
+ }
112
+ steps.push({
113
+ phase: "authorization-server-discovery",
114
+ status: "passed",
115
+ durationMs: performance.now() - authorizationStartedAt
116
+ });
117
+ } catch (error) {
118
+ steps.push({
119
+ phase: "authorization-server-discovery",
120
+ status: "failed",
121
+ durationMs: performance.now() - authorizationStartedAt,
122
+ error: errorMessage(error)
123
+ });
124
+ }
125
+ return redactReport({
126
+ ok: steps.every((step) => step.status === "passed"),
127
+ target: targetUrl.toString(),
128
+ resourceMetadata,
129
+ authorizationServerMetadata,
130
+ steps
131
+ });
132
+ }
133
+ function boundedFetch(fetchImplementation, timeoutMs) {
134
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 1) {
135
+ throw new Error("McpFn authorization diagnostic timeoutMs must be positive");
136
+ }
137
+ return async (input, init = {}) => {
138
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
139
+ const signal = init.signal ? AbortSignal.any([init.signal, timeoutSignal]) : timeoutSignal;
140
+ return fetchImplementation(input, { ...init, signal });
141
+ };
142
+ }
143
+ function redactReport(report) {
144
+ return redactOAuthValue(report);
145
+ }
146
+ function errorMessage(error) {
147
+ return error instanceof Error ? error.message : String(error);
148
+ }
149
+
150
+ // src/redirects.ts
151
+ var McpFnRedirectMismatchError = class extends Error {
152
+ code = "MCPFN_REDIRECT_MISMATCH";
153
+ requested;
154
+ constructor(requested) {
155
+ super("The authorization redirect URI is not registered for this MCP client");
156
+ this.name = "McpFnRedirectMismatchError";
157
+ this.requested = redactRedirect(requested);
158
+ }
159
+ };
160
+ function normalizeMcpRedirectUri(value, policy = {}) {
161
+ let url;
162
+ try {
163
+ url = new URL(value.toString());
164
+ } catch {
165
+ throw new McpFnRedirectMismatchError(String(value));
166
+ }
167
+ if (url.username || url.password || url.hash || url.hostname.includes("*")) {
168
+ throw new McpFnRedirectMismatchError(url.toString());
169
+ }
170
+ if (url.protocol === "https:") return url.toString();
171
+ if (url.protocol === "http:" && isLoopback(url, policy)) return url.toString();
172
+ if (policy.allowPrivateUseSchemes === true && isReverseDomainPrivateUseScheme(url.protocol)) {
173
+ return url.toString();
174
+ }
175
+ throw new McpFnRedirectMismatchError(url.toString());
176
+ }
177
+ function matchMcpRedirectUri(requested, registeredRedirectUris, policy = {}) {
178
+ const actual = new URL(normalizeMcpRedirectUri(requested, policy));
179
+ for (const candidateValue of registeredRedirectUris) {
180
+ const candidate = new URL(normalizeMcpRedirectUri(candidateValue, policy));
181
+ if (candidate.toString() === actual.toString()) {
182
+ return {
183
+ requested: actual.toString(),
184
+ registered: candidate.toString(),
185
+ kind: "exact"
186
+ };
187
+ }
188
+ if (policy.allowDynamicLoopbackPort !== false && isLoopback(actual, policy) && isLoopback(candidate, policy) && candidate.port === "" && actual.port !== "" && equalExceptPort(actual, candidate)) {
189
+ return {
190
+ requested: actual.toString(),
191
+ registered: candidate.toString(),
192
+ kind: "loopback-dynamic-port"
193
+ };
194
+ }
195
+ }
196
+ throw new McpFnRedirectMismatchError(actual.toString());
197
+ }
198
+ function isReverseDomainPrivateUseScheme(protocol) {
199
+ const scheme = protocol.slice(0, -1).toLowerCase();
200
+ return /^[a-z](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/.test(
201
+ scheme
202
+ );
203
+ }
204
+ function isLoopback(url, policy) {
205
+ if (url.protocol !== "http:") return false;
206
+ const hostname = url.hostname.toLowerCase();
207
+ return hostname === "127.0.0.1" || hostname === "[::1]" || policy.allowLocalhostLoopback === true && hostname === "localhost";
208
+ }
209
+ function equalExceptPort(left, right) {
210
+ return left.protocol === right.protocol && left.hostname.toLowerCase() === right.hostname.toLowerCase() && left.pathname === right.pathname && left.search === right.search && left.hash === right.hash && left.username === right.username && left.password === right.password;
211
+ }
212
+ function redactRedirect(value) {
213
+ try {
214
+ const url = new URL(value);
215
+ url.search = url.search ? "?redacted" : "";
216
+ url.hash = "";
217
+ url.username = "";
218
+ url.password = "";
219
+ return url.toString();
220
+ } catch {
221
+ return "[invalid redirect URI]";
222
+ }
223
+ }
224
+
225
+ // src/hosted-authorization.ts
226
+ var McpFnHostedAuthorizationError = class extends Error {
227
+ code;
228
+ status;
229
+ details;
230
+ constructor(code, message, options = {}) {
231
+ super(message);
232
+ this.name = "McpFnHostedAuthorizationError";
233
+ this.code = code;
234
+ this.status = options.status ?? 400;
235
+ this.details = options.details;
236
+ }
237
+ };
238
+ function normalizeMcpClientRegistration(input) {
239
+ if (!input.clientId) {
240
+ throw new McpFnHostedAuthorizationError("invalid_client_metadata", "client_id is required");
241
+ }
242
+ let redirectUris;
243
+ try {
244
+ redirectUris = unique(
245
+ registrationStringArray(input.metadata.redirect_uris, "redirect_uris", []).map(
246
+ (value) => normalizeMcpRedirectUri(value, input.redirectPolicy)
247
+ )
248
+ );
249
+ } catch (error) {
250
+ if (error instanceof McpFnRedirectMismatchError) {
251
+ throw new McpFnHostedAuthorizationError(
252
+ "invalid_client_metadata",
253
+ "redirect_uris contains an unsafe or malformed URI"
254
+ );
255
+ }
256
+ throw error;
257
+ }
258
+ if (!redirectUris.length) {
259
+ throw new McpFnHostedAuthorizationError(
260
+ "invalid_client_metadata",
261
+ "At least one redirect_uri is required"
262
+ );
263
+ }
264
+ const responseTypes = unique(
265
+ registrationStringArray(input.metadata.response_types, "response_types", ["code"])
266
+ );
267
+ const grantTypes = unique(
268
+ registrationStringArray(input.metadata.grant_types, "grant_types", ["authorization_code"])
269
+ );
270
+ return {
271
+ clientId: input.clientId,
272
+ source: input.source,
273
+ redirectUris,
274
+ responseTypes,
275
+ grantTypes,
276
+ tokenEndpointAuthMethod: input.metadata.token_endpoint_auth_method ?? "none",
277
+ metadata: {
278
+ ...input.metadata,
279
+ redirect_uris: redirectUris,
280
+ response_types: responseTypes,
281
+ grant_types: grantTypes,
282
+ token_endpoint_auth_method: input.metadata.token_endpoint_auth_method ?? "none"
283
+ }
284
+ };
285
+ }
286
+ function registrationStringArray(value, field, fallback) {
287
+ if (value === void 0) return fallback;
288
+ if (!Array.isArray(value) || Array.from(value).some((entry) => typeof entry !== "string")) {
289
+ throw new McpFnHostedAuthorizationError(
290
+ "invalid_client_metadata",
291
+ `${field} must be an array of strings`
292
+ );
293
+ }
294
+ return value;
295
+ }
296
+ function validateMcpAuthorizationRequest(options) {
297
+ const url = new URL(options.url.toString());
298
+ const responseType = authorizationParameter(url, "response_type", true);
299
+ if (responseType !== "code" || !options.client.responseTypes.includes("code")) {
300
+ throw new McpFnHostedAuthorizationError(
301
+ "unsupported_response_type",
302
+ "This MCP authorization profile requires response_type=code"
303
+ );
304
+ }
305
+ if (!options.client.grantTypes.includes("authorization_code")) {
306
+ throw new McpFnHostedAuthorizationError(
307
+ "unauthorized_client",
308
+ "The client has no compatible authorization_code flow"
309
+ );
310
+ }
311
+ const requestedClientId = authorizationParameter(url, "client_id", true);
312
+ if (requestedClientId !== options.client.clientId) {
313
+ throw new McpFnHostedAuthorizationError("invalid_client", "client_id does not match registration");
314
+ }
315
+ const redirectUri = authorizationParameter(url, "redirect_uri", true);
316
+ if (!redirectUri) {
317
+ throw new McpFnHostedAuthorizationError("invalid_request", "redirect_uri is required");
318
+ }
319
+ const redirectMatch = validateAuthorizationRedirect(
320
+ redirectUri,
321
+ options.client.redirectUris,
322
+ options.redirectPolicy
323
+ );
324
+ const codeChallenge = validateAuthorizationPkce(url);
325
+ const resource = normalizeAuthorizationResource(
326
+ authorizationParameter(url, "resource"),
327
+ options.allowedResources
328
+ );
329
+ const scopes = unique(
330
+ (authorizationParameter(url, "scope") ?? "").split(/\s+/).filter(Boolean)
331
+ );
332
+ assertSupportedScopes(scopes, options.supportedScopes);
333
+ assertScopesWithinClientRegistration(scopes, options.client);
334
+ const state = normalizeAuthorizationState(
335
+ authorizationParameter(url, "state")
336
+ );
337
+ return {
338
+ client: options.client,
339
+ responseType: "code",
340
+ redirectUri: new URL(redirectUri).toString(),
341
+ redirectMatch: redirectMatch.kind,
342
+ codeChallenge,
343
+ codeChallengeMethod: "S256",
344
+ scopes,
345
+ ...state ? { state } : {},
346
+ ...resource ? { resource } : {},
347
+ raw: new URLSearchParams(url.searchParams)
348
+ };
349
+ }
350
+ function validateAuthorizationRedirect(redirectUri, registeredRedirectUris, policy) {
351
+ try {
352
+ return matchMcpRedirectUri(redirectUri, registeredRedirectUris, policy);
353
+ } catch (error) {
354
+ if (error instanceof McpFnRedirectMismatchError) {
355
+ throw new McpFnHostedAuthorizationError(
356
+ "invalid_request",
357
+ error.message,
358
+ { details: { phase: "redirect-validation", redirect: error.requested } }
359
+ );
360
+ }
361
+ throw error;
362
+ }
363
+ }
364
+ function validateAuthorizationPkce(url) {
365
+ const codeChallenge = authorizationParameter(url, "code_challenge", true);
366
+ if (!codeChallenge) {
367
+ throw new McpFnHostedAuthorizationError("invalid_request", "PKCE code_challenge is required");
368
+ }
369
+ if (authorizationParameter(url, "code_challenge_method", true) !== "S256") {
370
+ throw new McpFnHostedAuthorizationError(
371
+ "invalid_request",
372
+ "PKCE code_challenge_method must be S256"
373
+ );
374
+ }
375
+ if (!/^[A-Za-z0-9_-]{43}$/.test(codeChallenge)) {
376
+ throw new McpFnHostedAuthorizationError(
377
+ "invalid_request",
378
+ "PKCE S256 code_challenge must be 43 base64url characters"
379
+ );
380
+ }
381
+ return codeChallenge;
382
+ }
383
+ function authorizationParameter(url, name, required = false) {
384
+ const values = url.searchParams.getAll(name);
385
+ if (values.length > 1 || required && (values.length !== 1 || values[0]?.trim() === "")) {
386
+ throw new McpFnHostedAuthorizationError(
387
+ "invalid_request",
388
+ `${name} must be supplied exactly once`
389
+ );
390
+ }
391
+ return values[0] ?? null;
392
+ }
393
+ function normalizeAuthorizationState(value) {
394
+ if (value === null) return void 0;
395
+ if (value.length < 1 || value.length > 512 || /[\u0000-\u001f\u007f]/u.test(value)) {
396
+ throw new McpFnHostedAuthorizationError(
397
+ "invalid_request",
398
+ "state is invalid"
399
+ );
400
+ }
401
+ return value;
402
+ }
403
+ function normalizeAuthorizationResource(value, allowedResources) {
404
+ if (value === null) return void 0;
405
+ let resource;
406
+ try {
407
+ resource = new URL(value).toString();
408
+ } catch {
409
+ throw new McpFnHostedAuthorizationError(
410
+ "invalid_target",
411
+ "resource must be an absolute URL"
412
+ );
413
+ }
414
+ if (allowedResources?.length) {
415
+ const allowed = new Set(allowedResources.map((entry) => new URL(entry.toString()).toString()));
416
+ if (!allowed.has(resource)) {
417
+ throw new McpFnHostedAuthorizationError("invalid_target", "resource is not allowed");
418
+ }
419
+ }
420
+ return resource;
421
+ }
422
+ function createMcpAuthorizationCompatibilityHandler(options) {
423
+ validateClientMetadataDocumentOptions(options.clientMetadataDocuments);
424
+ const issuer = normalizeIssuer(options.issuer, options.allowInsecureLoopbackIssuer ?? false);
425
+ const rfc8414IssuerPath = issuer.pathname === "/" ? "" : issuer.pathname;
426
+ const issuerPath = issuer.pathname === "/" ? "" : trimTrailingSlashes(issuer.pathname);
427
+ const endpointPrefix = normalizeEndpointPrefix(
428
+ options.endpointPrefix ?? issuerPath
429
+ );
430
+ const tokenEndpointAuthMethods = unique(
431
+ options.capabilities?.tokenEndpointAuthMethods ?? ["none"]
432
+ );
433
+ validateHostedCapabilities(options, tokenEndpointAuthMethods);
434
+ const metadata = createMcpAuthorizationServerMetadata({
435
+ issuer: options.issuer,
436
+ allowInsecureLoopbackIssuer: options.allowInsecureLoopbackIssuer,
437
+ endpointPrefix,
438
+ dynamicRegistration: Boolean(options.clients.register),
439
+ refreshTokenGrant: Boolean(options.tokenAuthority.refreshToken),
440
+ tokenRevocation: Boolean(options.tokenAuthority.revokeToken),
441
+ tokenEndpointAuthMethods,
442
+ ...options.supportedScopes ? { supportedScopes: options.supportedScopes } : {},
443
+ clientMetadataDocuments: options.clientMetadataDocuments?.enabled === true,
444
+ ...options.extraMetadata ? { extraMetadata: options.extraMetadata } : {}
445
+ });
446
+ const routes = createHostedRoutes(rfc8414IssuerPath, issuerPath, endpointPrefix, options);
447
+ return async (request) => {
448
+ const url = new URL(request.url);
449
+ const route = routes.get(`${request.method} ${url.pathname}`);
450
+ try {
451
+ return await dispatchHostedRoute({
452
+ route,
453
+ request,
454
+ url,
455
+ metadata,
456
+ options,
457
+ tokenEndpointAuthMethods
458
+ });
459
+ } catch (error) {
460
+ const normalized = error instanceof McpFnHostedAuthorizationError ? error : new McpFnHostedAuthorizationError(
461
+ "server_error",
462
+ "MCP authorization compatibility processing failed",
463
+ { status: 500 }
464
+ );
465
+ await emit(options, inferPhase(route), "failed", normalized.code, {
466
+ message: normalized.message,
467
+ ...normalized.details
468
+ });
469
+ const retryAfter = normalized.details?.retryAfterSeconds;
470
+ const basicChallenge = (route === "token" || route === "revoke") && normalized.code === "invalid_client" && /^Basic(?:\s|$)/i.test(request.headers.get("authorization") ?? "");
471
+ return json2(
472
+ normalized.status,
473
+ {
474
+ error: normalized.code,
475
+ error_description: normalized.message
476
+ },
477
+ {
478
+ ...typeof retryAfter === "number" && Number.isFinite(retryAfter) ? { "retry-after": String(Math.max(0, Math.ceil(retryAfter))) } : {},
479
+ ...basicChallenge ? { "www-authenticate": 'Basic realm="mcp-token"' } : {}
480
+ }
481
+ );
482
+ }
483
+ };
484
+ }
485
+ function createMcpAuthorizationServerMetadata(options) {
486
+ const issuer = normalizeIssuer(options.issuer, options.allowInsecureLoopbackIssuer ?? false);
487
+ const issuerPath = issuer.pathname === "/" ? "" : trimTrailingSlashes(issuer.pathname);
488
+ const endpointPrefix = normalizeEndpointPrefix(
489
+ options.endpointPrefix ?? issuerPath
490
+ );
491
+ const endpoint = (name) => {
492
+ const url = new URL(issuer);
493
+ url.pathname = `${endpointPrefix}/${name}`;
494
+ return url.toString();
495
+ };
496
+ const tokenEndpointAuthMethods = unique(
497
+ options.tokenEndpointAuthMethods ?? ["none"]
498
+ );
499
+ if (!tokenEndpointAuthMethods.length) {
500
+ throw new TypeError(
501
+ "At least one supported token endpoint authentication method is required"
502
+ );
503
+ }
504
+ return {
505
+ ...options.extraMetadata,
506
+ issuer: issuer.pathname === "/" && !issuer.search && !issuer.hash ? issuer.origin : issuer.toString(),
507
+ authorization_endpoint: endpoint("authorize"),
508
+ token_endpoint: endpoint("token"),
509
+ ...options.dynamicRegistration ? { registration_endpoint: endpoint("register") } : {},
510
+ ...options.tokenRevocation ? { revocation_endpoint: endpoint("revoke") } : {},
511
+ response_types_supported: ["code"],
512
+ grant_types_supported: [
513
+ "authorization_code",
514
+ ...options.refreshTokenGrant ? ["refresh_token"] : []
515
+ ],
516
+ code_challenge_methods_supported: ["S256"],
517
+ token_endpoint_auth_methods_supported: tokenEndpointAuthMethods,
518
+ ...options.supportedScopes ? { scopes_supported: unique(options.supportedScopes) } : {},
519
+ client_id_metadata_document_supported: options.clientMetadataDocuments
520
+ };
521
+ }
522
+ function createHostedRoutes(rfc8414IssuerPath, issuerPath, endpointPrefix, options) {
523
+ const routes = /* @__PURE__ */ new Map([
524
+ [`GET /.well-known/oauth-authorization-server${rfc8414IssuerPath}`, "metadata"],
525
+ [`GET ${issuerPath}/.well-known/openid-configuration`, "metadata"],
526
+ [`POST ${endpointPrefix}/register`, "register"],
527
+ [`GET ${endpointPrefix}/authorize`, "authorize"],
528
+ [`POST ${endpointPrefix}/token`, "token"]
529
+ ]);
530
+ if (options.tokenAuthority.revokeToken) {
531
+ routes.set(`POST ${endpointPrefix}/revoke`, "revoke");
532
+ }
533
+ return routes;
534
+ }
535
+ async function dispatchHostedRoute(input) {
536
+ switch (input.route) {
537
+ case "metadata":
538
+ return json2(200, input.metadata, { "cache-control": "public, max-age=300" });
539
+ case "register":
540
+ return handleRegistrationRequest(input.options, input.request);
541
+ case "authorize":
542
+ return handleAuthorizationRequest(input.options, input.url, input.request);
543
+ case "token":
544
+ return handleTokenRequest(input.options, input.request, input.tokenEndpointAuthMethods);
545
+ case "revoke":
546
+ return handleRevocationRequest(input.options, input.request, input.tokenEndpointAuthMethods);
547
+ default:
548
+ return json2(404, { error: "not_found" });
549
+ }
550
+ }
551
+ async function handleRegistrationRequest(options, request) {
552
+ if (!options.clients.register) {
553
+ throw new McpFnHostedAuthorizationError(
554
+ "invalid_request",
555
+ "Dynamic client registration is disabled",
556
+ { status: 404 }
557
+ );
558
+ }
559
+ const callbackRequest = request.clone();
560
+ const raw = await readBoundedJson(request, 256e3);
561
+ const clientMetadata = normalizeClientMetadata(raw, options.redirectPolicy);
562
+ const requested = normalizeMcpClientRegistration({
563
+ clientId: "pending-dynamic-registration",
564
+ source: "dynamic",
565
+ metadata: clientMetadata,
566
+ redirectPolicy: options.redirectPolicy
567
+ });
568
+ const supportedMethods = options.capabilities?.tokenEndpointAuthMethods ?? [
569
+ "none"
570
+ ];
571
+ assertCompatibleClientRegistration(requested, supportedMethods, options.supportedScopes);
572
+ const persisted = await options.clients.register(clientMetadata, callbackRequest);
573
+ const registration = normalizeMcpClientRegistration({
574
+ clientId: persisted.clientId,
575
+ source: persisted.source,
576
+ metadata: persisted.metadata,
577
+ redirectPolicy: options.redirectPolicy
578
+ });
579
+ assertCompatibleClientRegistration(registration, supportedMethods, options.supportedScopes);
580
+ await emit(options, "client-registration", "succeeded", void 0, {
581
+ clientId: registration.clientId,
582
+ source: registration.source
583
+ });
584
+ return json2(201, {
585
+ ...registration.metadata,
586
+ client_id: registration.clientId
587
+ });
588
+ }
589
+ function assertCompatibleClientRegistration(registration, supportedMethods, supportedScopes) {
590
+ if (!supportedMethods.includes(
591
+ registration.tokenEndpointAuthMethod
592
+ )) {
593
+ throw new McpFnHostedAuthorizationError(
594
+ "invalid_client_metadata",
595
+ "token_endpoint_auth_method is not supported"
596
+ );
597
+ }
598
+ if (!registration.responseTypes.includes("code")) {
599
+ throw new McpFnHostedAuthorizationError(
600
+ "invalid_client_metadata",
601
+ "response_types must include code"
602
+ );
603
+ }
604
+ if (!registration.grantTypes.includes("authorization_code")) {
605
+ throw new McpFnHostedAuthorizationError(
606
+ "invalid_client_metadata",
607
+ "grant_types must include authorization_code"
608
+ );
609
+ }
610
+ const scopes = registeredClientScopes(registration) ?? [];
611
+ assertSupportedScopes(scopes, supportedScopes);
612
+ }
613
+ async function handleAuthorizationRequest(options, url, request) {
614
+ const clientId = authorizationParameter(url, "client_id", true);
615
+ await runBeforeClientResolution(options, clientId, "authorization", request);
616
+ const client = await resolveClient(options, clientId);
617
+ if (!client) {
618
+ throw new McpFnHostedAuthorizationError("invalid_client", "Unknown MCP client");
619
+ }
620
+ const trustedRedirect = validateAuthorizationRedirect(
621
+ authorizationParameter(url, "redirect_uri", true),
622
+ client.redirectUris,
623
+ options.redirectPolicy
624
+ ).requested;
625
+ let validated;
626
+ try {
627
+ validated = validateMcpAuthorizationRequest({
628
+ url,
629
+ client,
630
+ redirectPolicy: options.redirectPolicy,
631
+ allowedResources: options.allowedResources,
632
+ supportedScopes: options.supportedScopes
633
+ });
634
+ if ((options.capabilities?.requireState ?? true) && !validated.state) {
635
+ throw new McpFnHostedAuthorizationError(
636
+ "invalid_request",
637
+ "state is required for this MCP authorization profile"
638
+ );
639
+ }
640
+ if ((options.capabilities?.requireResource ?? Boolean(options.allowedResources?.length)) && !validated.resource) {
641
+ throw new McpFnHostedAuthorizationError(
642
+ "invalid_target",
643
+ "resource is required for this MCP authorization profile"
644
+ );
645
+ }
646
+ } catch (error) {
647
+ if (!(error instanceof McpFnHostedAuthorizationError)) throw error;
648
+ await emit(options, "authorization-request", "failed", error.code, {
649
+ clientId,
650
+ registrationSource: client.source
651
+ });
652
+ return trustedAuthorizationErrorRedirect(trustedRedirect, url, error);
653
+ }
654
+ await emit(options, "authorization-request", "succeeded", void 0, {
655
+ clientId,
656
+ registrationSource: client.source,
657
+ redirectMatch: validated.redirectMatch
658
+ });
659
+ return options.authorize(validated, request);
660
+ }
661
+ function trustedAuthorizationErrorRedirect(redirectUri, authorizationUrl, error) {
662
+ const redirect = new URL(redirectUri);
663
+ redirect.searchParams.set("error", error.code);
664
+ redirect.searchParams.set("error_description", error.message);
665
+ try {
666
+ const state = normalizeAuthorizationState(
667
+ authorizationParameter(authorizationUrl, "state")
668
+ );
669
+ if (state) redirect.searchParams.set("state", state);
670
+ } catch {
671
+ }
672
+ return new Response(null, {
673
+ status: 302,
674
+ headers: {
675
+ "cache-control": "no-store",
676
+ location: redirect.toString()
677
+ }
678
+ });
679
+ }
680
+ var refreshLocks = /* @__PURE__ */ new WeakMap();
681
+ async function handleTokenRequest(options, request, supportedMethods) {
682
+ const authenticationRequest = request.clone();
683
+ const tokenAuthorityRequest = request.clone();
684
+ try {
685
+ const form = await readBoundedForm(request, 64e3);
686
+ const grantType = singleFormValue(form, "grant_type", true);
687
+ const authentication = await authenticateHostedClient(
688
+ options,
689
+ form,
690
+ authenticationRequest,
691
+ supportedMethods,
692
+ "token"
693
+ );
694
+ const tokenSet = await issueHostedToken(
695
+ grantType,
696
+ options,
697
+ authentication,
698
+ form,
699
+ tokenAuthorityRequest
700
+ );
701
+ validateHostedTokenSet(tokenSet);
702
+ await emit(options, grantType === "refresh_token" ? "token-refresh" : "token-exchange", "succeeded", void 0, {
703
+ clientId: authentication.client.clientId,
704
+ tokenEndpointAuthMethod: authentication.method,
705
+ hasRefreshToken: Boolean(tokenSet.refresh_token)
706
+ });
707
+ return json2(200, tokenSet);
708
+ } finally {
709
+ void authenticationRequest.body?.cancel().catch(() => void 0);
710
+ void tokenAuthorityRequest.body?.cancel().catch(() => void 0);
711
+ }
712
+ }
713
+ function issueHostedToken(grantType, options, authentication, form, request) {
714
+ if (grantType === "authorization_code") {
715
+ return exchangeHostedAuthorizationCode(options, authentication, form, request);
716
+ }
717
+ if (grantType === "refresh_token") {
718
+ return refreshHostedToken(options, authentication, form, request);
719
+ }
720
+ throw new McpFnHostedAuthorizationError(
721
+ "unsupported_grant_type",
722
+ "The requested OAuth grant is not supported"
723
+ );
724
+ }
725
+ async function exchangeHostedAuthorizationCode(options, authentication, form, request) {
726
+ if (!authentication.client.grantTypes.includes("authorization_code")) {
727
+ throw new McpFnHostedAuthorizationError(
728
+ "unauthorized_client",
729
+ "The client is not registered for authorization_code"
730
+ );
731
+ }
732
+ const redirectUri = normalizeRequiredUrl(form, "redirect_uri");
733
+ const resource = normalizeOptionalResource(form, options.allowedResources);
734
+ assertRequiredTokenResource(options, resource, "authorization_code");
735
+ assertAuthorizationCodeRedirect(redirectUri, authentication.client.redirectUris, options);
736
+ const codeVerifier = singleFormValue(form, "code_verifier", true);
737
+ if (!/^[A-Za-z0-9._~-]{43,128}$/.test(codeVerifier)) {
738
+ throw new McpFnHostedAuthorizationError("invalid_grant", "PKCE code_verifier is invalid");
739
+ }
740
+ return options.tokenAuthority.exchangeAuthorizationCode({
741
+ ...authentication,
742
+ code: singleFormValue(form, "code", true),
743
+ redirectUri,
744
+ codeVerifier,
745
+ ...resource ? { resource } : {}
746
+ }, request);
747
+ }
748
+ function assertAuthorizationCodeRedirect(redirectUri, registeredRedirectUris, options) {
749
+ try {
750
+ matchMcpRedirectUri(redirectUri, registeredRedirectUris, options.redirectPolicy);
751
+ } catch (error) {
752
+ if (!(error instanceof McpFnRedirectMismatchError)) throw error;
753
+ throw new McpFnHostedAuthorizationError(
754
+ "invalid_grant",
755
+ "Authorization code redirect binding does not match the client registration"
756
+ );
757
+ }
758
+ }
759
+ async function refreshHostedToken(options, authentication, form, request) {
760
+ if (!options.tokenAuthority.refreshToken) {
761
+ throw new McpFnHostedAuthorizationError(
762
+ "unsupported_grant_type",
763
+ "refresh_token is not enabled by the token authority"
764
+ );
765
+ }
766
+ if (!authentication.client.grantTypes.includes("refresh_token")) {
767
+ throw new McpFnHostedAuthorizationError(
768
+ "unauthorized_client",
769
+ "The client is not registered for refresh_token"
770
+ );
771
+ }
772
+ const credential = singleFormValue(form, "refresh_token", true);
773
+ const scopes = unique((singleFormValue(form, "scope") ?? "").split(/\s+/).filter(Boolean));
774
+ assertSupportedScopes(scopes, options.supportedScopes);
775
+ assertScopesWithinClientRegistration(scopes, authentication.client);
776
+ const resource = normalizeOptionalResource(form, options.allowedResources);
777
+ assertRequiredTokenResource(options, resource, "refresh_token");
778
+ return withSerializedRefresh(options.tokenAuthority, credential, async () => {
779
+ const refreshed = await options.tokenAuthority.refreshToken({
780
+ ...authentication,
781
+ refreshToken: credential,
782
+ scopes,
783
+ ...resource ? { resource } : {}
784
+ }, request);
785
+ assertRefreshTokenRotated(options, credential, refreshed);
786
+ return refreshed;
787
+ });
788
+ }
789
+ function assertRefreshTokenRotated(options, credential, refreshed) {
790
+ if ((options.capabilities?.rotateRefreshTokens ?? true) && (!refreshed.refresh_token || refreshed.refresh_token === credential)) {
791
+ throw new McpFnHostedAuthorizationError(
792
+ "server_error",
793
+ "The token authority did not rotate the refresh credential",
794
+ { status: 500 }
795
+ );
796
+ }
797
+ }
798
+ async function handleRevocationRequest(options, request, supportedMethods) {
799
+ const authenticationRequest = request.clone();
800
+ const revocationRequest = request.clone();
801
+ try {
802
+ const form = await readBoundedForm(request, 64e3);
803
+ const authentication = await authenticateHostedClient(
804
+ options,
805
+ form,
806
+ authenticationRequest,
807
+ supportedMethods,
808
+ "revocation"
809
+ );
810
+ const rawHint = singleFormValue(form, "token_type_hint");
811
+ const tokenTypeHint = rawHint === "access_token" || rawHint === "refresh_token" ? rawHint : void 0;
812
+ await options.tokenAuthority.revokeToken({
813
+ ...authentication,
814
+ token: singleFormValue(form, "token", true),
815
+ ...tokenTypeHint ? { tokenTypeHint } : {}
816
+ }, revocationRequest);
817
+ await emit(options, "token-revocation", "succeeded", void 0, {
818
+ clientId: authentication.client.clientId,
819
+ tokenEndpointAuthMethod: authentication.method
820
+ });
821
+ return new Response(null, { status: 200, headers: { "cache-control": "no-store" } });
822
+ } finally {
823
+ void authenticationRequest.body?.cancel().catch(() => void 0);
824
+ void revocationRequest.body?.cancel().catch(() => void 0);
825
+ }
826
+ }
827
+ async function authenticateHostedClient(options, form, request, supportedMethods, endpoint) {
828
+ const basic = readBasicClientCredentials(request.headers.get("authorization"));
829
+ const bodyClientId = singleFormValue(form, "client_id");
830
+ const bodySecret = singleFormValue(form, "client_secret");
831
+ if (basic && (bodyClientId || bodySecret)) {
832
+ throw new McpFnHostedAuthorizationError(
833
+ "invalid_client",
834
+ "Use exactly one token endpoint client authentication method",
835
+ { status: 401 }
836
+ );
837
+ }
838
+ let method;
839
+ let clientId;
840
+ let clientSecret;
841
+ if (basic) {
842
+ method = "client_secret_basic";
843
+ clientId = basic.clientId;
844
+ clientSecret = basic.clientSecret;
845
+ } else if (bodySecret) {
846
+ method = "client_secret_post";
847
+ clientId = bodyClientId;
848
+ clientSecret = bodySecret;
849
+ } else {
850
+ method = "none";
851
+ clientId = bodyClientId;
852
+ }
853
+ if (!clientId || !supportedMethods.includes(method)) {
854
+ throw new McpFnHostedAuthorizationError(
855
+ "invalid_client",
856
+ "The token endpoint client authentication method is not supported",
857
+ { status: 401 }
858
+ );
859
+ }
860
+ await runBeforeClientResolution(options, clientId, endpoint, request);
861
+ let client;
862
+ try {
863
+ client = await resolveClient(options, clientId);
864
+ } catch (error) {
865
+ if (error instanceof McpFnHostedAuthorizationError) {
866
+ throw new McpFnHostedAuthorizationError(
867
+ "invalid_client",
868
+ "Client metadata is invalid or unavailable",
869
+ { status: 401 }
870
+ );
871
+ }
872
+ throw error;
873
+ }
874
+ if (client?.tokenEndpointAuthMethod !== method) {
875
+ throw new McpFnHostedAuthorizationError(
876
+ "invalid_client",
877
+ "Client authentication does not match the registered method",
878
+ { status: 401 }
879
+ );
880
+ }
881
+ if (method !== "none") {
882
+ const accepted = await options.tokenAuthority.authenticateClient?.({
883
+ client,
884
+ method,
885
+ clientSecret
886
+ }, request);
887
+ if (!accepted) {
888
+ throw new McpFnHostedAuthorizationError(
889
+ "invalid_client",
890
+ "Client authentication failed",
891
+ { status: 401 }
892
+ );
893
+ }
894
+ }
895
+ return { client, method };
896
+ }
897
+ async function readBoundedForm(request, maxBytes) {
898
+ const contentType = request.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
899
+ if (contentType !== "application/x-www-form-urlencoded") {
900
+ throw new McpFnHostedAuthorizationError(
901
+ "invalid_request",
902
+ "OAuth endpoint requests must use application/x-www-form-urlencoded"
903
+ );
904
+ }
905
+ return new URLSearchParams(await readBoundedText(request, maxBytes));
906
+ }
907
+ function singleFormValue(form, name, required = false) {
908
+ const values = form.getAll(name);
909
+ if (values.length > 1 || required && (!values[0] || values[0].trim() === "")) {
910
+ throw new McpFnHostedAuthorizationError(
911
+ "invalid_request",
912
+ `${name} must be supplied exactly once`
913
+ );
914
+ }
915
+ return values[0] || void 0;
916
+ }
917
+ function normalizeRequiredUrl(form, name) {
918
+ const value = singleFormValue(form, name, true);
919
+ try {
920
+ return new URL(value).toString();
921
+ } catch {
922
+ throw new McpFnHostedAuthorizationError("invalid_request", `${name} must be an absolute URL`);
923
+ }
924
+ }
925
+ function normalizeOptionalResource(form, allowedResources) {
926
+ const value = singleFormValue(form, "resource");
927
+ if (!value) return void 0;
928
+ let resource;
929
+ try {
930
+ resource = new URL(value).toString();
931
+ } catch {
932
+ throw new McpFnHostedAuthorizationError("invalid_target", "resource must be an absolute URL");
933
+ }
934
+ if (allowedResources?.length) {
935
+ const allowed = new Set(allowedResources.map((entry) => new URL(entry.toString()).toString()));
936
+ if (!allowed.has(resource)) {
937
+ throw new McpFnHostedAuthorizationError("invalid_target", "resource is not allowed");
938
+ }
939
+ }
940
+ return resource;
941
+ }
942
+ function assertSupportedScopes(scopes, supportedScopes) {
943
+ if (!supportedScopes) return;
944
+ const supported = new Set(supportedScopes);
945
+ const unsupported = scopes.filter((scope) => !supported.has(scope));
946
+ if (unsupported.length) {
947
+ throw new McpFnHostedAuthorizationError("invalid_scope", "Requested MCP scope is unsupported", {
948
+ details: { unsupportedScopes: unsupported }
949
+ });
950
+ }
951
+ }
952
+ function registeredClientScopes(client) {
953
+ const value = client.metadata.scope;
954
+ if (value === void 0) return void 0;
955
+ if (typeof value !== "string") {
956
+ throw new McpFnHostedAuthorizationError(
957
+ "invalid_client_metadata",
958
+ "scope must be a space-delimited string"
959
+ );
960
+ }
961
+ return unique(value.split(/\s+/).filter(Boolean));
962
+ }
963
+ function assertScopesWithinClientRegistration(scopes, client) {
964
+ const registeredScopes = registeredClientScopes(client);
965
+ if (!registeredScopes) return;
966
+ const registered = new Set(registeredScopes);
967
+ const unauthorized = scopes.filter((scope) => !registered.has(scope));
968
+ if (unauthorized.length) {
969
+ throw new McpFnHostedAuthorizationError(
970
+ "invalid_scope",
971
+ "Requested MCP scope exceeds the client registration",
972
+ { details: { unauthorizedScopes: unauthorized } }
973
+ );
974
+ }
975
+ }
976
+ function assertRequiredTokenResource(options, resource, grantType) {
977
+ const required = grantType === "refresh_token" ? options.capabilities?.requireRefreshResource ?? false : options.capabilities?.requireResource ?? Boolean(options.allowedResources?.length);
978
+ if (required && !resource) {
979
+ throw new McpFnHostedAuthorizationError(
980
+ "invalid_target",
981
+ "resource is required for this MCP token request"
982
+ );
983
+ }
984
+ }
985
+ function readBasicClientCredentials(authorization) {
986
+ if (!authorization) return void 0;
987
+ const match = /^Basic +(\S+) *$/i.exec(authorization);
988
+ if (!match) {
989
+ throw new McpFnHostedAuthorizationError(
990
+ "invalid_client",
991
+ "Unsupported Authorization header at the token endpoint",
992
+ { status: 401 }
993
+ );
994
+ }
995
+ try {
996
+ const decoded = atob(match[1]);
997
+ const separator = decoded.indexOf(":");
998
+ if (separator < 1) throw new Error("missing separator");
999
+ return {
1000
+ clientId: decodeFormComponent(decoded.slice(0, separator)),
1001
+ clientSecret: decodeFormComponent(decoded.slice(separator + 1))
1002
+ };
1003
+ } catch {
1004
+ throw new McpFnHostedAuthorizationError(
1005
+ "invalid_client",
1006
+ "Malformed Basic client authentication",
1007
+ { status: 401 }
1008
+ );
1009
+ }
1010
+ }
1011
+ function decodeFormComponent(value) {
1012
+ return decodeURIComponent(value.replaceAll("+", " "));
1013
+ }
1014
+ async function withSerializedRefresh(authority, credential, operation) {
1015
+ let locks = refreshLocks.get(authority);
1016
+ if (!locks) {
1017
+ locks = /* @__PURE__ */ new Map();
1018
+ refreshLocks.set(authority, locks);
1019
+ }
1020
+ const previous = locks.get(credential);
1021
+ const current = (previous ? previous.catch(() => void 0) : Promise.resolve()).then(operation);
1022
+ locks.set(credential, current);
1023
+ try {
1024
+ return await current;
1025
+ } finally {
1026
+ if (locks.get(credential) === current) locks.delete(credential);
1027
+ }
1028
+ }
1029
+ function validateHostedTokenSet(value) {
1030
+ if (!value || typeof value !== "object" || typeof value.access_token !== "string" || value.access_token.length === 0 || typeof value.token_type !== "string" || value.token_type.length === 0 || value.expires_in !== void 0 && (!Number.isFinite(value.expires_in) || value.expires_in <= 0) || value.refresh_token !== void 0 && (typeof value.refresh_token !== "string" || value.refresh_token.length === 0) || value.scope !== void 0 && typeof value.scope !== "string" || value.resource !== void 0 && typeof value.resource !== "string") {
1031
+ throw new McpFnHostedAuthorizationError(
1032
+ "server_error",
1033
+ "The token authority returned an invalid token set",
1034
+ { status: 500 }
1035
+ );
1036
+ }
1037
+ }
1038
+ function validateHostedCapabilities(options, methods) {
1039
+ const allowed = /* @__PURE__ */ new Set(["none", "client_secret_basic", "client_secret_post"]);
1040
+ if (!methods.length || methods.some((method) => !allowed.has(method))) {
1041
+ throw new TypeError("At least one supported token endpoint authentication method is required");
1042
+ }
1043
+ if (methods.some((method) => method !== "none") && !options.tokenAuthority.authenticateClient) {
1044
+ throw new TypeError("Secret-based client authentication requires tokenAuthority.authenticateClient");
1045
+ }
1046
+ }
1047
+ async function resolveClient(options, clientId) {
1048
+ const stored = await options.clients.resolve(clientId);
1049
+ if (stored) {
1050
+ const registration2 = normalizeMcpClientRegistration({
1051
+ clientId: stored.clientId,
1052
+ source: stored.source,
1053
+ metadata: stored.metadata,
1054
+ redirectPolicy: options.redirectPolicy
1055
+ });
1056
+ try {
1057
+ assertCompatibleClientRegistration(
1058
+ registration2,
1059
+ options.capabilities?.tokenEndpointAuthMethods ?? ["none"],
1060
+ options.supportedScopes
1061
+ );
1062
+ } catch (error) {
1063
+ if (error instanceof McpFnHostedAuthorizationError) return null;
1064
+ throw error;
1065
+ }
1066
+ return registration2;
1067
+ }
1068
+ if (!options.clientMetadataDocuments?.enabled) return null;
1069
+ let clientUrl;
1070
+ try {
1071
+ clientUrl = new URL(clientId);
1072
+ } catch {
1073
+ return null;
1074
+ }
1075
+ if (clientUrl.protocol !== "https:" || clientUrl.pathname === "/") return null;
1076
+ const raw = await fetchClientMetadataDocument(clientUrl, options.clientMetadataDocuments);
1077
+ const record = raw;
1078
+ if (record.client_id !== void 0 && record.client_id !== clientId) {
1079
+ throw new McpFnHostedAuthorizationError(
1080
+ "invalid_client_metadata",
1081
+ "Client ID Metadata Document client_id does not match its URL"
1082
+ );
1083
+ }
1084
+ const registration = normalizeMcpClientRegistration({
1085
+ clientId,
1086
+ source: "client-metadata-document",
1087
+ metadata: normalizeClientMetadata({
1088
+ ...record,
1089
+ token_endpoint_auth_method: record.token_endpoint_auth_method ?? "client_secret_basic"
1090
+ }, options.redirectPolicy),
1091
+ redirectPolicy: options.redirectPolicy
1092
+ });
1093
+ assertCompatibleClientRegistration(
1094
+ registration,
1095
+ options.capabilities?.tokenEndpointAuthMethods ?? ["none"],
1096
+ options.supportedScopes
1097
+ );
1098
+ return registration;
1099
+ }
1100
+ async function runBeforeClientResolution(options, clientId, endpoint, request) {
1101
+ if (!options.beforeClientResolution) return;
1102
+ const callbackRequest = request.clone();
1103
+ try {
1104
+ await options.beforeClientResolution({ clientId, endpoint, request: callbackRequest });
1105
+ } finally {
1106
+ void callbackRequest.body?.cancel().catch(() => void 0);
1107
+ }
1108
+ }
1109
+ function normalizeClientMetadata(value, redirectPolicy) {
1110
+ if (!value || typeof value !== "object") {
1111
+ throw new McpFnHostedAuthorizationError("invalid_client_metadata", "Client metadata must be an object");
1112
+ }
1113
+ try {
1114
+ return {
1115
+ ...value,
1116
+ redirect_uris: Array.isArray(value.redirect_uris) ? value.redirect_uris.map((redirect) => normalizeMcpRedirectUri(redirect, redirectPolicy)) : []
1117
+ };
1118
+ } catch (error) {
1119
+ if (error instanceof McpFnRedirectMismatchError) {
1120
+ throw new McpFnHostedAuthorizationError(
1121
+ "invalid_client_metadata",
1122
+ "redirect_uris contains an unsafe or malformed URI"
1123
+ );
1124
+ }
1125
+ throw error;
1126
+ }
1127
+ }
1128
+ async function readBoundedJson(source, maxBytes, signal) {
1129
+ const contentLength = source.headers.get("content-length");
1130
+ if (contentLength !== null) {
1131
+ const length = Number(contentLength);
1132
+ if (!/^\d+$/.test(contentLength) || !Number.isSafeInteger(length) || length > maxBytes) {
1133
+ throw new McpFnHostedAuthorizationError("invalid_request", "Metadata body is too large", {
1134
+ status: 413
1135
+ });
1136
+ }
1137
+ }
1138
+ const text = await readBoundedText(source, maxBytes, signal);
1139
+ try {
1140
+ return JSON.parse(text);
1141
+ } catch {
1142
+ throw new McpFnHostedAuthorizationError("invalid_request", "Metadata body is not valid JSON");
1143
+ }
1144
+ }
1145
+ async function fetchClientMetadataDocument(initialUrl, options) {
1146
+ const fetchImplementation = options.fetch ?? globalThis.fetch;
1147
+ if (!fetchImplementation) throw new Error("A fetch implementation is required");
1148
+ const controller = new AbortController();
1149
+ const timeout = setTimeout(
1150
+ () => controller.abort(),
1151
+ options.timeoutMs ?? 1e4
1152
+ );
1153
+ const maxRedirects = options.maxRedirects ?? 3;
1154
+ let currentUrl = new URL(initialUrl);
1155
+ try {
1156
+ for (let redirectCount = 0; ; redirectCount += 1) {
1157
+ await assertClientMetadataDocumentUrlAllowed(currentUrl, options, controller.signal);
1158
+ if (controller.signal.aborted) throw clientMetadataTimeoutError();
1159
+ const response = await fetchClientMetadataResponse(
1160
+ fetchImplementation,
1161
+ currentUrl,
1162
+ controller
1163
+ );
1164
+ const redirectUrl = await clientMetadataRedirectUrl(
1165
+ response,
1166
+ currentUrl,
1167
+ redirectCount,
1168
+ maxRedirects
1169
+ );
1170
+ if (redirectUrl) {
1171
+ currentUrl = redirectUrl;
1172
+ continue;
1173
+ }
1174
+ await assertClientMetadataResponse(response);
1175
+ return await readBoundedJson(
1176
+ response,
1177
+ options.maxBytes ?? 256e3,
1178
+ controller.signal
1179
+ );
1180
+ }
1181
+ } catch (error) {
1182
+ if (controller.signal.aborted) throw clientMetadataTimeoutError();
1183
+ throw error;
1184
+ } finally {
1185
+ clearTimeout(timeout);
1186
+ }
1187
+ }
1188
+ async function fetchClientMetadataResponse(fetchImplementation, url, controller) {
1189
+ try {
1190
+ return await withAbort(fetchImplementation(url, {
1191
+ headers: { accept: "application/json" },
1192
+ redirect: "manual",
1193
+ signal: controller.signal
1194
+ }), controller.signal);
1195
+ } catch (error) {
1196
+ if (controller.signal.aborted) throw clientMetadataTimeoutError();
1197
+ throw error;
1198
+ }
1199
+ }
1200
+ async function clientMetadataRedirectUrl(response, currentUrl, redirectCount, maxRedirects) {
1201
+ if (!isRedirectStatus(response.status)) return void 0;
1202
+ const location = response.headers.get("location");
1203
+ await response.body?.cancel().catch(() => void 0);
1204
+ if (!location || redirectCount >= maxRedirects) {
1205
+ throw new McpFnHostedAuthorizationError(
1206
+ "invalid_client",
1207
+ "Client ID Metadata Document redirect could not be followed safely"
1208
+ );
1209
+ }
1210
+ try {
1211
+ return new URL(location, currentUrl);
1212
+ } catch {
1213
+ throw new McpFnHostedAuthorizationError(
1214
+ "invalid_client",
1215
+ "Client ID Metadata Document redirect could not be followed safely"
1216
+ );
1217
+ }
1218
+ }
1219
+ async function assertClientMetadataResponse(response) {
1220
+ if (!response.ok) {
1221
+ await response.body?.cancel().catch(() => void 0);
1222
+ throw new McpFnHostedAuthorizationError(
1223
+ "invalid_client",
1224
+ "Client ID Metadata Document could not be loaded"
1225
+ );
1226
+ }
1227
+ const contentType = response.headers.get("content-type")?.toLowerCase();
1228
+ if (!contentType?.includes("application/json")) {
1229
+ await response.body?.cancel().catch(() => void 0);
1230
+ throw new McpFnHostedAuthorizationError(
1231
+ "invalid_client",
1232
+ "Client ID Metadata Document must use application/json"
1233
+ );
1234
+ }
1235
+ }
1236
+ function clientMetadataTimeoutError() {
1237
+ return new McpFnHostedAuthorizationError(
1238
+ "invalid_client",
1239
+ "Client ID Metadata Document request timed out"
1240
+ );
1241
+ }
1242
+ async function assertClientMetadataDocumentUrlAllowed(url, options, signal) {
1243
+ if (url.protocol !== "https:" || url.username !== "" || url.password !== "" || url.hash !== "" || !options.allow || !await withAbort(Promise.resolve(options.allow(new URL(url))), signal)) {
1244
+ throw new McpFnHostedAuthorizationError(
1245
+ "invalid_client",
1246
+ "Client ID Metadata Document URL is not permitted"
1247
+ );
1248
+ }
1249
+ }
1250
+ async function readBoundedText(source, maxBytes, signal) {
1251
+ if (!source.body) return "";
1252
+ const reader = source.body.getReader();
1253
+ const chunks = [];
1254
+ let total = 0;
1255
+ const onAbort = () => {
1256
+ void reader.cancel(new DOMException("aborted", "AbortError")).catch(() => void 0);
1257
+ };
1258
+ signal?.addEventListener("abort", onAbort, { once: true });
1259
+ try {
1260
+ if (signal?.aborted) throw new DOMException("aborted", "AbortError");
1261
+ while (true) {
1262
+ const { done, value } = await reader.read();
1263
+ if (signal?.aborted) throw new DOMException("aborted", "AbortError");
1264
+ if (done) break;
1265
+ total += value.byteLength;
1266
+ if (total > maxBytes) {
1267
+ await reader.cancel().catch(() => void 0);
1268
+ throw new McpFnHostedAuthorizationError("invalid_request", "Request body is too large", {
1269
+ status: 413
1270
+ });
1271
+ }
1272
+ chunks.push(value);
1273
+ }
1274
+ } finally {
1275
+ signal?.removeEventListener("abort", onAbort);
1276
+ reader.releaseLock();
1277
+ }
1278
+ const bytes = new Uint8Array(total);
1279
+ let offset = 0;
1280
+ for (const chunk of chunks) {
1281
+ bytes.set(chunk, offset);
1282
+ offset += chunk.byteLength;
1283
+ }
1284
+ return new TextDecoder().decode(bytes);
1285
+ }
1286
+ function withAbort(promise, signal) {
1287
+ if (signal.aborted) return Promise.reject(new DOMException("aborted", "AbortError"));
1288
+ return new Promise((resolve, reject) => {
1289
+ const onAbort = () => {
1290
+ cleanup();
1291
+ reject(new DOMException("aborted", "AbortError"));
1292
+ };
1293
+ const cleanup = () => signal.removeEventListener("abort", onAbort);
1294
+ signal.addEventListener("abort", onAbort, { once: true });
1295
+ promise.then(
1296
+ (value) => {
1297
+ cleanup();
1298
+ resolve(value);
1299
+ },
1300
+ (error) => {
1301
+ cleanup();
1302
+ reject(error);
1303
+ }
1304
+ );
1305
+ if (signal.aborted) onAbort();
1306
+ });
1307
+ }
1308
+ function isRedirectStatus(status) {
1309
+ return status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
1310
+ }
1311
+ function validateClientMetadataDocumentOptions(options) {
1312
+ if (!options) return;
1313
+ for (const [name, value, minimum] of [
1314
+ ["maxBytes", options.maxBytes, 1],
1315
+ ["timeoutMs", options.timeoutMs, 1],
1316
+ ["maxRedirects", options.maxRedirects, 0]
1317
+ ]) {
1318
+ if (value !== void 0 && (!Number.isInteger(value) || value < minimum)) {
1319
+ throw new TypeError(`clientMetadataDocuments.${name} must be an integer >= ${minimum}`);
1320
+ }
1321
+ }
1322
+ }
1323
+ function normalizeIssuer(value, allowInsecureLoopback) {
1324
+ const serialized = value.toString();
1325
+ const issuer = new URL(serialized);
1326
+ const loopbackHttp = allowInsecureLoopback && issuer.protocol === "http:" && (issuer.hostname === "localhost" || issuer.hostname === "127.0.0.1" || issuer.hostname === "[::1]");
1327
+ if (issuer.protocol !== "https:" && !loopbackHttp || issuer.username || issuer.password || issuer.search || issuer.hash || serialized.includes("?") || serialized.includes("#")) {
1328
+ throw new TypeError(
1329
+ "issuer must use HTTPS without userinfo, a query string, or a fragment"
1330
+ );
1331
+ }
1332
+ return issuer;
1333
+ }
1334
+ function normalizeEndpointPrefix(value) {
1335
+ if (value === "" || value === "/") return "";
1336
+ const canonicalPath = new URL(value, "https://mcpfn.invalid").pathname;
1337
+ if (!value.startsWith("/") || value.endsWith("/") || value.includes("//") || value.includes("?") || value.includes("#") || canonicalPath !== value) {
1338
+ throw new TypeError(
1339
+ "endpointPrefix must be a canonical absolute path without a trailing slash"
1340
+ );
1341
+ }
1342
+ return value;
1343
+ }
1344
+ function json2(status, body, headers = {}) {
1345
+ return Response.json(body, {
1346
+ status,
1347
+ headers: {
1348
+ "cache-control": "no-store",
1349
+ ...Object.fromEntries(new Headers(headers))
1350
+ }
1351
+ });
1352
+ }
1353
+ function unique(values) {
1354
+ return [...new Set(values)].sort(compareCodeUnits);
1355
+ }
1356
+ function compareCodeUnits(left, right) {
1357
+ if (left < right) return -1;
1358
+ if (left > right) return 1;
1359
+ return 0;
1360
+ }
1361
+ function trimTrailingSlashes(value) {
1362
+ let end = value.length;
1363
+ while (end > 0 && value[end - 1] === "/") end -= 1;
1364
+ return value.slice(0, end);
1365
+ }
1366
+ async function emit(options, phase, outcome, code, details) {
1367
+ try {
1368
+ await options.diagnostics?.(redactOAuthValue({
1369
+ phase,
1370
+ outcome,
1371
+ ...code ? { code } : {},
1372
+ ...details ? { details } : {}
1373
+ }));
1374
+ } catch {
1375
+ }
1376
+ }
1377
+ function inferPhase(route) {
1378
+ if (route === "register") return "client-registration";
1379
+ if (route === "authorize") return "authorization-request";
1380
+ if (route === "token") return "token-exchange";
1381
+ if (route === "revoke") return "token-revocation";
1382
+ return "authorization-server-discovery";
1383
+ }
1384
+ var MemoryMcpFnOAuthSessionStore = class {
1385
+ security = "memory";
1386
+ client;
1387
+ tokenSet;
1388
+ verifier;
1389
+ pendingState;
1390
+ async getClientInformation() {
1391
+ return this.client ? structuredClone(this.client) : void 0;
1392
+ }
1393
+ async setClientInformation(value) {
1394
+ this.client = structuredClone(value);
1395
+ }
1396
+ async getTokens() {
1397
+ return this.tokenSet ? structuredClone(this.tokenSet) : void 0;
1398
+ }
1399
+ async setTokens(value) {
1400
+ this.tokenSet = structuredClone(value);
1401
+ }
1402
+ async getCodeVerifier() {
1403
+ return this.verifier;
1404
+ }
1405
+ async setCodeVerifier(value) {
1406
+ this.verifier = value;
1407
+ }
1408
+ async getState() {
1409
+ return this.pendingState;
1410
+ }
1411
+ async setState(value) {
1412
+ this.pendingState = value;
1413
+ }
1414
+ async clear(scope) {
1415
+ if (scope === "all" || scope === "client") this.client = void 0;
1416
+ if (scope === "all" || scope === "tokens") this.tokenSet = void 0;
1417
+ if (scope === "all" || scope === "verifier") this.verifier = void 0;
1418
+ if (scope === "all" || scope === "state") this.pendingState = void 0;
1419
+ }
1420
+ };
1421
+ var ENCRYPTED_SESSION_ENVELOPE_KIND = "mcpfn.oauth-session-envelope";
1422
+ function createEncryptedMcpFnOAuthSessionStore(options) {
1423
+ if (!options.namespace || !options.keyRef) {
1424
+ throw new Error("Encrypted McpFn OAuth storage requires namespace and keyRef");
1425
+ }
1426
+ const key = (part) => `${options.namespace}:${part}`;
1427
+ const get = async (part) => {
1428
+ const record = await options.store.get(key(part));
1429
+ if (!record) return void 0;
1430
+ const parsed = JSON.parse(await options.cipher.decrypt(record.ciphertext, record.keyRef));
1431
+ if (parsed && typeof parsed === "object" && parsed.formatVersion === 1 && Object.hasOwn(parsed, "value") && (parsed.kind === ENCRYPTED_SESSION_ENVELOPE_KIND || isLegacyEncryptedSessionEnvelope(parsed))) {
1432
+ return parsed.value;
1433
+ }
1434
+ return parsed;
1435
+ };
1436
+ const put = async (part, value) => {
1437
+ await options.store.put(key(part), {
1438
+ ciphertext: await options.cipher.encrypt(JSON.stringify({
1439
+ kind: ENCRYPTED_SESSION_ENVELOPE_KIND,
1440
+ formatVersion: 1,
1441
+ value
1442
+ }), options.keyRef),
1443
+ keyRef: options.keyRef
1444
+ });
1445
+ };
1446
+ return {
1447
+ security: "encrypted",
1448
+ getClientInformation: () => get("client"),
1449
+ setClientInformation: (value) => put("client", value),
1450
+ getTokens: () => get("tokens"),
1451
+ setTokens: (value) => put("tokens", value),
1452
+ getCodeVerifier: () => get("verifier"),
1453
+ setCodeVerifier: (value) => put("verifier", value),
1454
+ getState: () => get("state"),
1455
+ setState: (value) => put("state", value),
1456
+ async clear(scope) {
1457
+ if (scope === "all" || scope === "client") await options.store.delete(key("client"));
1458
+ if (scope === "all" || scope === "tokens") await options.store.delete(key("tokens"));
1459
+ if (scope === "all" || scope === "verifier") await options.store.delete(key("verifier"));
1460
+ if (scope === "all" || scope === "state") await options.store.delete(key("state"));
1461
+ }
1462
+ };
1463
+ }
1464
+ function isLegacyEncryptedSessionEnvelope(value) {
1465
+ const keys = Object.keys(value);
1466
+ return keys.length === 2 && keys.includes("formatVersion") && keys.includes("value");
1467
+ }
1468
+ var McpFnOAuthClientProvider = class {
1469
+ redirectUrl;
1470
+ clientMetadata;
1471
+ clientMetadataUrl;
1472
+ addClientAuthentication;
1473
+ validateResourceURL;
1474
+ options;
1475
+ store;
1476
+ constructor(options) {
1477
+ this.options = options;
1478
+ this.redirectUrl = options.redirectUrl;
1479
+ this.clientMetadata = structuredClone(options.clientMetadata);
1480
+ this.clientMetadataUrl = options.clientMetadataUrl;
1481
+ this.store = options.store ?? new MemoryMcpFnOAuthSessionStore();
1482
+ this.addClientAuthentication = options.addClientAuthentication;
1483
+ this.validateResourceURL = options.validateResourceURL;
1484
+ if (!this.clientMetadata.redirect_uris?.length) {
1485
+ throw new Error("McpFn OAuth client metadata requires registered redirect_uris");
1486
+ }
1487
+ }
1488
+ async state() {
1489
+ const value = await (this.options.state?.() ?? generateStateId("mcpfn_state"));
1490
+ await this.store.setState(value);
1491
+ return value;
1492
+ }
1493
+ clientInformation() {
1494
+ return this.store.getClientInformation();
1495
+ }
1496
+ async saveClientInformation(value) {
1497
+ await this.emit("client-registration", "started", void 0, {
1498
+ storage: this.store.security
1499
+ });
1500
+ try {
1501
+ await this.store.setClientInformation(value);
1502
+ await this.emit("client-registration", "succeeded", void 0, {
1503
+ clientId: value.client_id,
1504
+ storage: this.store.security
1505
+ });
1506
+ } catch (error) {
1507
+ await this.emit("client-registration", "failed", readCode(error) ?? "MCPFN_OAUTH_STORAGE_FAILED", {
1508
+ message: error instanceof Error ? error.message : String(error),
1509
+ storage: this.store.security
1510
+ });
1511
+ throw error;
1512
+ }
1513
+ }
1514
+ tokens() {
1515
+ return this.store.getTokens();
1516
+ }
1517
+ async saveTokens(value) {
1518
+ let phase = "token-exchange";
1519
+ try {
1520
+ const [previous, verifier, pendingState] = await Promise.all([
1521
+ this.store.getTokens(),
1522
+ this.store.getCodeVerifier(),
1523
+ this.store.getState()
1524
+ ]);
1525
+ const completesAuthorizationCodeExchange = Boolean(verifier) && !pendingState;
1526
+ phase = previous && !completesAuthorizationCodeExchange ? "token-refresh" : "token-exchange";
1527
+ await this.emit(phase, "started", void 0, { storage: this.store.security });
1528
+ await this.store.setTokens(value);
1529
+ if (completesAuthorizationCodeExchange) {
1530
+ await this.store.clear("verifier");
1531
+ }
1532
+ await this.emit(phase, "succeeded", void 0, {
1533
+ tokenType: value.token_type,
1534
+ hasRefreshToken: Boolean(value.refresh_token),
1535
+ storage: this.store.security
1536
+ });
1537
+ } catch (error) {
1538
+ await this.emit(phase, "failed", readCode(error) ?? "MCPFN_OAUTH_STORAGE_FAILED", {
1539
+ message: error instanceof Error ? error.message : String(error),
1540
+ storage: this.store.security
1541
+ });
1542
+ throw error;
1543
+ }
1544
+ }
1545
+ async redirectToAuthorization(authorizationUrl) {
1546
+ await this.emit("authorization-request", "started");
1547
+ const requested = authorizationUrl.searchParams.get("redirect_uri");
1548
+ if (!requested) {
1549
+ await this.emit("authorization-request", "failed", "MCPFN_REDIRECT_MISSING");
1550
+ throw new Error("MCP authorization request is missing redirect_uri");
1551
+ }
1552
+ try {
1553
+ const client = await this.store.getClientInformation();
1554
+ const registered = "redirect_uris" in (client ?? {}) && Array.isArray(client.redirect_uris) ? client.redirect_uris : this.clientMetadata.redirect_uris;
1555
+ const match = matchMcpRedirectUri(requested, registered, this.options.redirectPolicy);
1556
+ await this.options.openAuthorization(authorizationUrl);
1557
+ await this.emit("authorization-request", "succeeded", void 0, {
1558
+ redirect: match,
1559
+ clientId: authorizationUrl.searchParams.get("client_id")
1560
+ });
1561
+ } catch (error) {
1562
+ await this.emit("authorization-request", "failed", readCode(error), {
1563
+ redirectOrigin: safeOrigin(requested),
1564
+ message: error instanceof Error ? error.message : String(error)
1565
+ });
1566
+ throw error;
1567
+ }
1568
+ }
1569
+ saveCodeVerifier(value) {
1570
+ return this.store.setCodeVerifier(value);
1571
+ }
1572
+ async codeVerifier() {
1573
+ const value = await this.store.getCodeVerifier();
1574
+ if (!value) throw new Error("No PKCE verifier is available for this MCP authorization session");
1575
+ return value;
1576
+ }
1577
+ async validateAuthorizationState(value) {
1578
+ const expected = await this.store.getState();
1579
+ if (!expected || !value || expected !== value) {
1580
+ await this.emit("authorization-callback", "failed", "MCPFN_STATE_MISMATCH");
1581
+ throw new Error("MCP authorization callback state does not match the pending session");
1582
+ }
1583
+ await this.store.clear("state");
1584
+ await this.emit("authorization-callback", "succeeded");
1585
+ }
1586
+ invalidateCredentials(scope) {
1587
+ return this.store.clear(scope);
1588
+ }
1589
+ async invalidatePendingAuthorization() {
1590
+ await Promise.all([
1591
+ this.store.clear("verifier"),
1592
+ this.store.clear("state")
1593
+ ]);
1594
+ }
1595
+ async revoke() {
1596
+ const tokens = await this.store.getTokens();
1597
+ if (!tokens) {
1598
+ await this.emit("token-revocation", "succeeded", "MCPFN_NO_LOCAL_TOKEN", {
1599
+ remote: false
1600
+ });
1601
+ return;
1602
+ }
1603
+ await this.emit("token-revocation", "started");
1604
+ try {
1605
+ if (!this.options.revoke) {
1606
+ const error = Object.assign(
1607
+ new Error("Remote token revocation is not configured; local credentials were retained"),
1608
+ { code: "MCPFN_REVOCATION_UNAVAILABLE" }
1609
+ );
1610
+ throw error;
1611
+ }
1612
+ await this.options.revoke(tokens);
1613
+ await this.store.clear("tokens");
1614
+ await this.emit("token-revocation", "succeeded");
1615
+ } catch (error) {
1616
+ await this.emit("token-revocation", "failed", readCode(error), {
1617
+ message: error instanceof Error ? error.message : String(error)
1618
+ });
1619
+ throw error;
1620
+ }
1621
+ }
1622
+ async emit(phase, outcome, code, details) {
1623
+ try {
1624
+ await this.options.diagnostics?.(redactOAuthValue({
1625
+ phase,
1626
+ outcome,
1627
+ ...code ? { code } : {},
1628
+ at: (this.options.clock?.() ?? /* @__PURE__ */ new Date()).toISOString(),
1629
+ ...details ? { details } : {}
1630
+ }));
1631
+ } catch {
1632
+ }
1633
+ }
1634
+ };
1635
+ function createMcpFnOAuthClientProvider(options) {
1636
+ return new McpFnOAuthClientProvider(options);
1637
+ }
1638
+ function readCode(error) {
1639
+ if (!error || typeof error !== "object") return void 0;
1640
+ const value = error.code;
1641
+ return typeof value === "string" || typeof value === "number" ? String(value) : void 0;
1642
+ }
1643
+ function safeOrigin(value) {
1644
+ try {
1645
+ return new URL(value).origin;
1646
+ } catch {
1647
+ return "invalid";
1648
+ }
1649
+ }
24
1650
 
25
1651
  // src/resource-server.ts
26
1652
  function normalizeResource(resource) {
@@ -28,8 +1654,28 @@ function normalizeResource(resource) {
28
1654
  url.hash = "";
29
1655
  return url;
30
1656
  }
31
- function unique(values) {
32
- return [...new Set(values.map((value) => new URL(value.toString()).toString()))].sort();
1657
+ function normalizeIdentifier(value, allowInsecureLoopback) {
1658
+ const serialized = value.toString();
1659
+ const url = new URL(serialized);
1660
+ const loopbackHttp = allowInsecureLoopback && url.protocol === "http:" && (url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]");
1661
+ if (url.protocol !== "https:" && !loopbackHttp || url.username || url.password || url.search || url.hash || serialized.includes("?") || serialized.includes("#")) {
1662
+ throw new TypeError(
1663
+ "OAuth authorization server identifiers must use HTTPS without userinfo, query, or fragment"
1664
+ );
1665
+ }
1666
+ return url.pathname === "/" ? url.origin : url.toString();
1667
+ }
1668
+ function compareCodeUnits2(left, right) {
1669
+ if (left < right) return -1;
1670
+ if (left > right) return 1;
1671
+ return 0;
1672
+ }
1673
+ function unique2(values, allowInsecureLoopback) {
1674
+ return [
1675
+ ...new Set(
1676
+ values.map((value) => normalizeIdentifier(value, allowInsecureLoopback))
1677
+ )
1678
+ ].sort(compareCodeUnits2);
33
1679
  }
34
1680
  function protectedResourceMetadataUrl(resource) {
35
1681
  const normalized = normalizeResource(resource);
@@ -44,14 +1690,19 @@ function createProtectedResourceMetadata(options) {
44
1690
  return {
45
1691
  ...options.extraMetadata,
46
1692
  resource: resource.toString(),
47
- authorization_servers: unique(options.authorizationServers),
48
- ...options.scopesSupported ? { scopes_supported: [...new Set(options.scopesSupported)].sort() } : {},
1693
+ authorization_servers: unique2(
1694
+ options.authorizationServers,
1695
+ options.allowInsecureLoopbackAuthorizationServers ?? false
1696
+ ),
1697
+ ...options.scopesSupported ? {
1698
+ scopes_supported: [...new Set(options.scopesSupported)].sort(compareCodeUnits2)
1699
+ } : {},
49
1700
  bearer_methods_supported: ["header"],
50
1701
  ...options.resourceName ? { resource_name: options.resourceName } : {},
51
1702
  ...options.resourceDocumentation ? { resource_documentation: new URL(options.resourceDocumentation).toString() } : {}
52
1703
  };
53
1704
  }
54
- function json(status, body, headers = {}) {
1705
+ function json3(status, body, headers = {}) {
55
1706
  return new Response(JSON.stringify(body), {
56
1707
  status,
57
1708
  headers: {
@@ -61,28 +1712,6 @@ function json(status, body, headers = {}) {
61
1712
  }
62
1713
  });
63
1714
  }
64
- function bearerChallenge(metadataUrl, details = {}) {
65
- const fields = [`resource_metadata="${metadataUrl.toString()}"`];
66
- if (details.error) fields.push(`error="${details.error}"`);
67
- if (details.description) {
68
- fields.push(`error_description="${details.description.replace(/["\\]/g, "")}"`);
69
- }
70
- if (details.scope) fields.push(`scope="${details.scope.replace(/["\\]/g, "")}"`);
71
- return `Bearer ${fields.join(", ")}`;
72
- }
73
- function authError(status, metadataUrl, details) {
74
- return json(
75
- status,
76
- { error: details.error, error_description: details.description },
77
- { "www-authenticate": bearerChallenge(metadataUrl, details) }
78
- );
79
- }
80
- function bearerToken(request) {
81
- const authorization = request.headers.get("authorization");
82
- if (!authorization) return void 0;
83
- const match = /^Bearer\s+([^\s]+)$/i.exec(authorization.trim());
84
- return match?.[1];
85
- }
86
1715
  function createOAuthResourceServerHandler(mcpHandler, options) {
87
1716
  const resource = normalizeResource(options.resource);
88
1717
  const metadata = createProtectedResourceMetadata(options);
@@ -90,11 +1719,11 @@ function createOAuthResourceServerHandler(mcpHandler, options) {
90
1719
  return async (request) => {
91
1720
  const requestUrl = new URL(request.url);
92
1721
  if (request.method === "GET" && requestUrl.origin === metadataUrl.origin && requestUrl.pathname === metadataUrl.pathname) {
93
- return json(200, metadata, { "cache-control": "public, max-age=300" });
1722
+ return json3(200, metadata, { "cache-control": "public, max-age=300" });
94
1723
  }
95
- const token = bearerToken(request);
1724
+ const token = readBearerToken(request);
96
1725
  if (!token) {
97
- return authError(401, metadataUrl, {
1726
+ return bearerChallengeResponse(401, metadataUrl, {
98
1727
  error: "invalid_token",
99
1728
  description: "A Bearer access token is required"
100
1729
  });
@@ -103,20 +1732,20 @@ function createOAuthResourceServerHandler(mcpHandler, options) {
103
1732
  try {
104
1733
  authInfo = await options.verifier.verifyAccessToken(token);
105
1734
  } catch {
106
- return authError(401, metadataUrl, {
1735
+ return bearerChallengeResponse(401, metadataUrl, {
107
1736
  error: "invalid_token",
108
1737
  description: "The access token is invalid"
109
1738
  });
110
1739
  }
111
1740
  const now = Math.floor((options.clock?.() ?? Date.now()) / 1e3);
112
1741
  if (authInfo.expiresAt !== void 0 && authInfo.expiresAt <= now) {
113
- return authError(401, metadataUrl, {
1742
+ return bearerChallengeResponse(401, metadataUrl, {
114
1743
  error: "invalid_token",
115
1744
  description: "The access token has expired"
116
1745
  });
117
1746
  }
118
1747
  if (!authInfo.resource || normalizeResource(authInfo.resource).toString() !== resource.toString()) {
119
- return authError(401, metadataUrl, {
1748
+ return bearerChallengeResponse(401, metadataUrl, {
120
1749
  error: "invalid_token",
121
1750
  description: "The access token is not bound to this resource"
122
1751
  });
@@ -135,16 +1764,151 @@ function createOAuthResourceServerHandler(mcpHandler, options) {
135
1764
  const grantedScopes = new Set(authInfo.scopes);
136
1765
  const missingScopes = requiredScopes.filter((scope) => !grantedScopes.has(scope));
137
1766
  if (missingScopes.length) {
138
- return authError(403, metadataUrl, {
1767
+ return bearerChallengeResponse(403, metadataUrl, {
139
1768
  error: "insufficient_scope",
140
1769
  description: "The access token lacks required scopes",
141
- scope: [...new Set(requiredScopes)].sort().join(" ")
1770
+ scope: [...new Set(requiredScopes)].sort(compareCodeUnits2).join(" ")
142
1771
  });
143
1772
  }
144
1773
  return mcpHandler(request, { authInfo });
145
1774
  };
146
1775
  }
147
1776
 
148
- export { MCP_ENTERPRISE_MANAGED_AUTHORIZATION_EXTENSION_ID, MCP_ID_JAG_GRANT_PROFILE, createOAuthResourceServerHandler, createProtectedResourceMetadata, enterpriseManagedAuthorizationClientMetadata, protectedResourceMetadataUrl, withEnterpriseManagedAuthorization };
1777
+ // src/provider-adapter.ts
1778
+ function compareCodeUnits3(left, right) {
1779
+ if (left < right) return -1;
1780
+ if (left > right) return 1;
1781
+ return 0;
1782
+ }
1783
+ function createMcpFnAuthProviderAdapter(options) {
1784
+ const resource = new URL(options.resource.toString());
1785
+ resource.hash = "";
1786
+ return {
1787
+ async authenticate(request) {
1788
+ const bearer = readBearerToken(request);
1789
+ if (!bearer) return null;
1790
+ const provider = options.provider;
1791
+ const session = "authenticateBearer" in provider ? await withRequestClone(request, (providerRequest) => provider.authenticateBearer(bearer, providerRequest)) : await provider.authenticate(new Request(request.url, {
1792
+ method: request.method,
1793
+ headers: { authorization: `Bearer ${bearer}` },
1794
+ credentials: "omit"
1795
+ }));
1796
+ if (!session) return null;
1797
+ const principal = options.map ? await withRequestClone(request, (mapRequest) => options.map(session, mapRequest)) : defaultPrincipal(session);
1798
+ if (options.provider.authorize && !await options.provider.authorize(session, resource.toString())) {
1799
+ return null;
1800
+ }
1801
+ if (options.authorize && !await withRequestClone(request, (authorizeRequest) => options.authorize({ principal, request: authorizeRequest }))) {
1802
+ return null;
1803
+ }
1804
+ return {
1805
+ session,
1806
+ principal,
1807
+ authInfo: {
1808
+ token: bearer,
1809
+ clientId: principal.clientId,
1810
+ scopes: [...principal.scopes],
1811
+ ...principal.expiresAt !== void 0 ? { expiresAt: principal.expiresAt } : {},
1812
+ resource,
1813
+ extra: {
1814
+ ...principal.extra,
1815
+ subject: principal.subject,
1816
+ resourceIds: [...principal.resourceIds],
1817
+ ...principal.tenantId ? { tenantId: principal.tenantId } : {},
1818
+ ...principal.regionId ? { regionId: principal.regionId } : {},
1819
+ ...principal.authMethods ? { authMethods: [...principal.authMethods] } : {}
1820
+ }
1821
+ }
1822
+ };
1823
+ }
1824
+ };
1825
+ }
1826
+ async function withRequestClone(request, callback) {
1827
+ const clone = request.clone();
1828
+ try {
1829
+ return await callback(clone);
1830
+ } finally {
1831
+ void clone.body?.cancel().catch(() => void 0);
1832
+ }
1833
+ }
1834
+ function createAuthProviderMcpHandler(mcpHandler, options) {
1835
+ const adapter = createMcpFnAuthProviderAdapter(options);
1836
+ const metadataUrl = protectedResourceMetadataUrl(options.resource);
1837
+ return async (request) => {
1838
+ let authenticationRequest;
1839
+ try {
1840
+ authenticationRequest = request.clone();
1841
+ } catch {
1842
+ return invalidTokenResponse(metadataUrl);
1843
+ }
1844
+ let authenticated;
1845
+ try {
1846
+ authenticated = await adapter.authenticate(authenticationRequest);
1847
+ } catch {
1848
+ return new Response(JSON.stringify({
1849
+ error: "temporarily_unavailable",
1850
+ error_description: "The authentication provider is unavailable"
1851
+ }), {
1852
+ status: 503,
1853
+ headers: {
1854
+ "content-type": "application/json; charset=utf-8",
1855
+ "cache-control": "no-store"
1856
+ }
1857
+ });
1858
+ } finally {
1859
+ void authenticationRequest.body?.cancel().catch(() => void 0);
1860
+ }
1861
+ if (!authenticated) {
1862
+ return invalidTokenResponse(metadataUrl);
1863
+ }
1864
+ let requiredScopes;
1865
+ if (typeof options.requiredScopes === "function") {
1866
+ const scopeRequest = request.clone();
1867
+ try {
1868
+ requiredScopes = await options.requiredScopes({
1869
+ principal: authenticated.principal,
1870
+ request: scopeRequest
1871
+ });
1872
+ } finally {
1873
+ void scopeRequest.body?.cancel().catch(() => void 0);
1874
+ }
1875
+ } else {
1876
+ requiredScopes = options.requiredScopes ?? [];
1877
+ }
1878
+ const grantedScopes = new Set(authenticated.principal.scopes);
1879
+ const missingScopes = [...new Set(requiredScopes)].filter(
1880
+ (scope) => !grantedScopes.has(scope)
1881
+ );
1882
+ if (missingScopes.length) {
1883
+ return bearerChallengeResponse(403, metadataUrl, {
1884
+ error: "insufficient_scope",
1885
+ description: "The Bearer credential lacks required scopes",
1886
+ scope: [...new Set(requiredScopes)].sort(compareCodeUnits3).join(" ")
1887
+ });
1888
+ }
1889
+ const handleOptions = { authInfo: authenticated.authInfo };
1890
+ return mcpHandler(request, handleOptions);
1891
+ };
1892
+ }
1893
+ function invalidTokenResponse(metadataUrl) {
1894
+ return bearerChallengeResponse(401, metadataUrl, {
1895
+ error: "invalid_token",
1896
+ description: "A valid Bearer access token is required"
1897
+ });
1898
+ }
1899
+ function defaultPrincipal(session) {
1900
+ return {
1901
+ subject: session.subject.actorId,
1902
+ clientId: session.id,
1903
+ scopes: [...session.scopes ?? []],
1904
+ resourceIds: [...session.resourceIds ?? []],
1905
+ ...session.expiresAt ? { expiresAt: Math.floor(session.expiresAt.getTime() / 1e3) } : {},
1906
+ ...session.subject.tenantId ? { tenantId: session.subject.tenantId } : {},
1907
+ ...session.subject.regionId ? { regionId: session.subject.regionId } : {},
1908
+ ...session.methods ? { authMethods: [...session.methods] } : {}
1909
+ };
1910
+ }
1911
+
1912
+ export { MCP_ENTERPRISE_MANAGED_AUTHORIZATION_EXTENSION_ID, MCP_ID_JAG_GRANT_PROFILE, McpFnHostedAuthorizationError, McpFnOAuthClientProvider, McpFnRedirectMismatchError, MemoryMcpFnOAuthSessionStore, bearerChallengeResponse, createAuthProviderMcpHandler, createEncryptedMcpFnOAuthSessionStore, createMcpAuthorizationCompatibilityHandler, createMcpAuthorizationServerMetadata, createMcpFnAuthProviderAdapter, createMcpFnOAuthClientProvider, createOAuthResourceServerHandler, createProtectedResourceMetadata, diagnoseMcpAuthorization, enterpriseManagedAuthorizationClientMetadata, matchMcpRedirectUri, normalizeMcpClientRegistration, normalizeMcpRedirectUri, protectedResourceMetadataUrl, readBearerToken, validateMcpAuthorizationRequest, withEnterpriseManagedAuthorization };
149
1913
  //# sourceMappingURL=index.js.map
150
1914
  //# sourceMappingURL=index.js.map