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