@mcpfn/testing 0.0.1
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 +105 -0
- package/dist/auth.cjs +685 -0
- package/dist/auth.cjs.map +1 -0
- package/dist/auth.d.cts +199 -0
- package/dist/auth.d.ts +199 -0
- package/dist/auth.js +644 -0
- package/dist/auth.js.map +1 -0
- package/dist/index.cjs +1228 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +152 -0
- package/dist/index.d.ts +152 -0
- package/dist/index.js +1171 -0
- package/dist/index.js.map +1 -0
- package/dist/playwright.cjs +574 -0
- package/dist/playwright.cjs.map +1 -0
- package/dist/playwright.d.cts +75 -0
- package/dist/playwright.d.ts +75 -0
- package/dist/playwright.js +545 -0
- package/dist/playwright.js.map +1 -0
- package/package.json +64 -0
package/dist/auth.cjs
ADDED
|
@@ -0,0 +1,685 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/auth.ts
|
|
21
|
+
var auth_exports = {};
|
|
22
|
+
__export(auth_exports, {
|
|
23
|
+
MCPFN_OAUTH_EXTENSION_GRANTS: () => MCPFN_OAUTH_EXTENSION_GRANTS,
|
|
24
|
+
McpFnAuthAssertionError: () => McpFnAuthAssertionError,
|
|
25
|
+
McpFnMockOAuthAuthorizationServer: () => McpFnMockOAuthAuthorizationServer,
|
|
26
|
+
apiKeyCredential: () => apiKeyCredential,
|
|
27
|
+
assertAuthRegressionSuite: () => assertAuthRegressionSuite,
|
|
28
|
+
assertAuthorizationCodeClientMetadata: () => assertAuthorizationCodeClientMetadata,
|
|
29
|
+
assertBearerResourceChallenge: () => assertBearerResourceChallenge,
|
|
30
|
+
bearerCredential: () => bearerCredential,
|
|
31
|
+
createFetchAuthTarget: () => createFetchAuthTarget,
|
|
32
|
+
createOAuthClientMetadataFixture: () => createOAuthClientMetadataFixture,
|
|
33
|
+
createOAuthClientMetadataVariants: () => createOAuthClientMetadataVariants,
|
|
34
|
+
createPkcePair: () => createPkcePair,
|
|
35
|
+
parseBearerChallenge: () => parseBearerChallenge,
|
|
36
|
+
runAuthRegressionSuite: () => runAuthRegressionSuite,
|
|
37
|
+
startMockOAuthAuthorizationServer: () => startMockOAuthAuthorizationServer
|
|
38
|
+
});
|
|
39
|
+
module.exports = __toCommonJS(auth_exports);
|
|
40
|
+
|
|
41
|
+
// src/auth-core.ts
|
|
42
|
+
var McpFnAuthAssertionError = class extends Error {
|
|
43
|
+
constructor(message) {
|
|
44
|
+
super(message);
|
|
45
|
+
this.name = "McpFnAuthAssertionError";
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
function expectedStatus(response, expected, name) {
|
|
49
|
+
const statuses = Array.isArray(expected) ? expected : [expected];
|
|
50
|
+
if (!statuses.includes(response.status)) {
|
|
51
|
+
throw new McpFnAuthAssertionError(
|
|
52
|
+
`${name} expected HTTP ${statuses.join(" or ")}, received ${response.status}`
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
function parseBearerChallenge(header) {
|
|
57
|
+
if (!header) return void 0;
|
|
58
|
+
const matches = [...header.matchAll(/(?:^|,)\s*([A-Za-z][A-Za-z0-9_-]*)\s+/g)];
|
|
59
|
+
const selectedIndex = matches.findIndex((entry) => entry[1].toLowerCase() === "bearer");
|
|
60
|
+
if (selectedIndex < 0) return void 0;
|
|
61
|
+
const match = matches[selectedIndex];
|
|
62
|
+
const start = (match.index ?? 0) + match[0].length;
|
|
63
|
+
const end = matches[selectedIndex + 1]?.index ?? header.length;
|
|
64
|
+
const parameters = {};
|
|
65
|
+
const source = header.slice(start, end);
|
|
66
|
+
const pattern = /([A-Za-z][A-Za-z0-9_-]*)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^,\s]+))/g;
|
|
67
|
+
for (const entry of source.matchAll(pattern)) {
|
|
68
|
+
const quoted = entry[2]?.replace(/\\(["\\])/g, "$1");
|
|
69
|
+
parameters[entry[1]] = quoted ?? entry[3] ?? "";
|
|
70
|
+
}
|
|
71
|
+
return { scheme: match[1], parameters };
|
|
72
|
+
}
|
|
73
|
+
function assertBearerResourceChallenge(response, expectedMetadataUrl) {
|
|
74
|
+
const challenge = parseBearerChallenge(response.headers.get("www-authenticate"));
|
|
75
|
+
if (!challenge || challenge.scheme.toLowerCase() !== "bearer") {
|
|
76
|
+
throw new McpFnAuthAssertionError("Expected a Bearer WWW-Authenticate challenge");
|
|
77
|
+
}
|
|
78
|
+
const metadataUrl = challenge.parameters.resource_metadata;
|
|
79
|
+
if (!metadataUrl) {
|
|
80
|
+
throw new McpFnAuthAssertionError(
|
|
81
|
+
"Bearer challenge is missing the resource_metadata parameter"
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
try {
|
|
85
|
+
const parsed = new URL(metadataUrl);
|
|
86
|
+
if (!parsed.protocol || !parsed.host) throw new Error("not absolute");
|
|
87
|
+
} catch {
|
|
88
|
+
throw new McpFnAuthAssertionError(
|
|
89
|
+
`Bearer challenge has an invalid resource_metadata URL: ${metadataUrl}`
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
if (expectedMetadataUrl && metadataUrl !== expectedMetadataUrl) {
|
|
93
|
+
throw new McpFnAuthAssertionError(
|
|
94
|
+
`Expected resource_metadata=${expectedMetadataUrl}, received ${metadataUrl}`
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
return challenge;
|
|
98
|
+
}
|
|
99
|
+
function bearerCredential(token, kind = "oauth") {
|
|
100
|
+
return {
|
|
101
|
+
kind,
|
|
102
|
+
headers: { authorization: `Bearer ${token}` }
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
function apiKeyCredential(apiKey, options = {}) {
|
|
106
|
+
const headerName = options.headerName ?? "authorization";
|
|
107
|
+
const value = options.scheme === "" ? apiKey : `${options.scheme ?? "Bearer"} ${apiKey}`;
|
|
108
|
+
return { kind: "api-key", headers: { [headerName]: value } };
|
|
109
|
+
}
|
|
110
|
+
function invalidHeaders(options) {
|
|
111
|
+
return new Headers(options.invalidCredentialHeaders ?? {
|
|
112
|
+
authorization: `Bearer mcpfn-invalid-${options.kind}`
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
async function runOne(options, scenario, prepare, expected) {
|
|
116
|
+
let credential;
|
|
117
|
+
try {
|
|
118
|
+
credential = await prepare();
|
|
119
|
+
const headers = credential ? new Headers(credential.headers) : scenario.name === "invalid-credential" ? invalidHeaders(options) : new Headers();
|
|
120
|
+
const response = await options.target.request(headers, scenario);
|
|
121
|
+
expectedStatus(response, expected, scenario.name);
|
|
122
|
+
if (options.kind === "oauth" && scenario.name !== "valid-credential") {
|
|
123
|
+
assertBearerResourceChallenge(
|
|
124
|
+
response,
|
|
125
|
+
options.protectedResourceMetadataUrl
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
if (scenario.name === "valid-credential" && credential) {
|
|
129
|
+
await options.verifyAuthenticatedResponse?.(response.clone(), credential);
|
|
130
|
+
}
|
|
131
|
+
return {
|
|
132
|
+
name: scenario.name,
|
|
133
|
+
status: "passed",
|
|
134
|
+
responseStatus: response.status
|
|
135
|
+
};
|
|
136
|
+
} catch (error) {
|
|
137
|
+
return {
|
|
138
|
+
name: scenario.name,
|
|
139
|
+
status: "failed",
|
|
140
|
+
error: error instanceof Error ? error.message : String(error)
|
|
141
|
+
};
|
|
142
|
+
} finally {
|
|
143
|
+
await credential?.dispose?.();
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
async function runAuthRegressionSuite(options) {
|
|
147
|
+
const issue = (overrides = {}) => options.provider.issue({
|
|
148
|
+
kind: options.kind,
|
|
149
|
+
scopes: options.requiredScopes,
|
|
150
|
+
resource: options.resource,
|
|
151
|
+
...overrides
|
|
152
|
+
});
|
|
153
|
+
const results = [];
|
|
154
|
+
results.push(await runOne(
|
|
155
|
+
options,
|
|
156
|
+
{ name: "missing-credential", kind: options.kind },
|
|
157
|
+
async () => void 0,
|
|
158
|
+
401
|
|
159
|
+
));
|
|
160
|
+
results.push(await runOne(
|
|
161
|
+
options,
|
|
162
|
+
{ name: "invalid-credential", kind: options.kind },
|
|
163
|
+
async () => void 0,
|
|
164
|
+
401
|
|
165
|
+
));
|
|
166
|
+
results.push(await runOne(
|
|
167
|
+
options,
|
|
168
|
+
{ name: "valid-credential", kind: options.kind },
|
|
169
|
+
() => issue(),
|
|
170
|
+
options.expectedAuthenticatedStatuses ?? [200, 201, 202, 204]
|
|
171
|
+
));
|
|
172
|
+
const capabilities = options.provider.capabilities ?? {};
|
|
173
|
+
if (capabilities.scopes && options.requiredScopes?.length) {
|
|
174
|
+
results.push(await runOne(
|
|
175
|
+
options,
|
|
176
|
+
{ name: "insufficient-scope", kind: options.kind },
|
|
177
|
+
() => issue({ scopes: [] }),
|
|
178
|
+
403
|
|
179
|
+
));
|
|
180
|
+
}
|
|
181
|
+
if (capabilities.expiration) {
|
|
182
|
+
results.push(await runOne(
|
|
183
|
+
options,
|
|
184
|
+
{ name: "expired-credential", kind: options.kind },
|
|
185
|
+
() => issue({ expiresInSeconds: -60 }),
|
|
186
|
+
401
|
|
187
|
+
));
|
|
188
|
+
}
|
|
189
|
+
if (capabilities.resourceBinding && options.resource) {
|
|
190
|
+
results.push(await runOne(
|
|
191
|
+
options,
|
|
192
|
+
{ name: "missing-resource", kind: options.kind },
|
|
193
|
+
() => issue({ resource: void 0 }),
|
|
194
|
+
401
|
|
195
|
+
));
|
|
196
|
+
}
|
|
197
|
+
if (capabilities.resourceBinding && options.wrongResource) {
|
|
198
|
+
results.push(await runOne(
|
|
199
|
+
options,
|
|
200
|
+
{ name: "wrong-resource", kind: options.kind },
|
|
201
|
+
() => issue({ resource: options.wrongResource }),
|
|
202
|
+
401
|
|
203
|
+
));
|
|
204
|
+
}
|
|
205
|
+
if (capabilities.revocation && options.provider.revoke) {
|
|
206
|
+
results.push(await runOne(
|
|
207
|
+
options,
|
|
208
|
+
{ name: "revoked-credential", kind: options.kind },
|
|
209
|
+
async () => {
|
|
210
|
+
const credential = await issue();
|
|
211
|
+
await options.provider.revoke?.(credential);
|
|
212
|
+
return credential;
|
|
213
|
+
},
|
|
214
|
+
401
|
|
215
|
+
));
|
|
216
|
+
}
|
|
217
|
+
return results;
|
|
218
|
+
}
|
|
219
|
+
async function assertAuthRegressionSuite(options) {
|
|
220
|
+
const results = await runAuthRegressionSuite(options);
|
|
221
|
+
const failures = results.filter((result) => result.status === "failed");
|
|
222
|
+
if (failures.length) {
|
|
223
|
+
throw new McpFnAuthAssertionError(
|
|
224
|
+
failures.map((failure) => `${failure.name}: ${failure.error}`).join("\n")
|
|
225
|
+
);
|
|
226
|
+
}
|
|
227
|
+
return results;
|
|
228
|
+
}
|
|
229
|
+
function createFetchAuthTarget(options) {
|
|
230
|
+
const fetchImplementation = options.fetch ?? globalThis.fetch;
|
|
231
|
+
if (!fetchImplementation) {
|
|
232
|
+
throw new Error("A fetch implementation is required");
|
|
233
|
+
}
|
|
234
|
+
return {
|
|
235
|
+
async request(authHeaders, scenario) {
|
|
236
|
+
const configured = typeof options.requestInit === "function" ? options.requestInit(scenario) : options.requestInit ?? {};
|
|
237
|
+
const headers = new Headers(configured.headers);
|
|
238
|
+
headers.set("accept", "application/json, text/event-stream");
|
|
239
|
+
headers.set("content-type", "application/json");
|
|
240
|
+
authHeaders.forEach((value, name) => headers.set(name, value));
|
|
241
|
+
return fetchImplementation(options.url, {
|
|
242
|
+
method: "POST",
|
|
243
|
+
body: JSON.stringify({
|
|
244
|
+
jsonrpc: "2.0",
|
|
245
|
+
id: `mcpfn-auth-${scenario.name}`,
|
|
246
|
+
method: "initialize",
|
|
247
|
+
params: {
|
|
248
|
+
protocolVersion: "2025-11-25",
|
|
249
|
+
capabilities: {},
|
|
250
|
+
clientInfo: { name: "mcpfn-auth-test", version: "1.0.0" }
|
|
251
|
+
}
|
|
252
|
+
}),
|
|
253
|
+
...configured,
|
|
254
|
+
headers
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
var MCPFN_OAUTH_EXTENSION_GRANTS = {
|
|
260
|
+
jwtBearer: "urn:ietf:params:oauth:grant-type:jwt-bearer",
|
|
261
|
+
deviceCode: "urn:ietf:params:oauth:grant-type:device_code",
|
|
262
|
+
generic: "urn:example:params:oauth:grant-type:extension"
|
|
263
|
+
};
|
|
264
|
+
function createOAuthClientMetadataFixture(options) {
|
|
265
|
+
return {
|
|
266
|
+
...options.extraMetadata,
|
|
267
|
+
client_id: new URL(options.clientId).toString(),
|
|
268
|
+
client_name: options.clientName ?? "McpFn OAuth test client",
|
|
269
|
+
redirect_uris: [...new Set(options.redirectUris.map((uri) => new URL(uri).toString()))],
|
|
270
|
+
response_types: ["code"],
|
|
271
|
+
grant_types: [
|
|
272
|
+
"authorization_code",
|
|
273
|
+
"refresh_token",
|
|
274
|
+
...new Set(options.extraGrantTypes ?? [])
|
|
275
|
+
],
|
|
276
|
+
token_endpoint_auth_method: "none"
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
function createOAuthClientMetadataVariants(baseUrl, redirectUri = new URL("/callback", baseUrl).toString()) {
|
|
280
|
+
const base = new URL(baseUrl);
|
|
281
|
+
const fixture = (name, extraGrantTypes = []) => createOAuthClientMetadataFixture({
|
|
282
|
+
clientId: new URL(`/client-metadata/${name}`, base).toString(),
|
|
283
|
+
redirectUris: [redirectUri],
|
|
284
|
+
clientName: `McpFn ${name} client`,
|
|
285
|
+
extraGrantTypes
|
|
286
|
+
});
|
|
287
|
+
return {
|
|
288
|
+
basic: fixture("basic"),
|
|
289
|
+
jwtBearerExtension: fixture("jwt-bearer-extension", [MCPFN_OAUTH_EXTENSION_GRANTS.jwtBearer]),
|
|
290
|
+
deviceCodeExtension: fixture("device-code-extension", [MCPFN_OAUTH_EXTENSION_GRANTS.deviceCode]),
|
|
291
|
+
genericExtension: fixture("generic-extension", [MCPFN_OAUTH_EXTENSION_GRANTS.generic])
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
function assertAuthorizationCodeClientMetadata(metadata, expectedClientId) {
|
|
295
|
+
if (expectedClientId && metadata.client_id !== new URL(expectedClientId).toString()) {
|
|
296
|
+
throw new McpFnAuthAssertionError("OAuth client metadata client_id does not match its document URL");
|
|
297
|
+
}
|
|
298
|
+
if (!metadata.response_types.includes("code")) {
|
|
299
|
+
throw new McpFnAuthAssertionError("OAuth client metadata does not support response_type=code");
|
|
300
|
+
}
|
|
301
|
+
if (!metadata.grant_types.includes("authorization_code")) {
|
|
302
|
+
throw new McpFnAuthAssertionError("OAuth client metadata does not support authorization_code");
|
|
303
|
+
}
|
|
304
|
+
if (!metadata.redirect_uris.length) {
|
|
305
|
+
throw new McpFnAuthAssertionError("OAuth client metadata must declare at least one redirect URI");
|
|
306
|
+
}
|
|
307
|
+
return metadata;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
// src/mock-oauth-server.ts
|
|
311
|
+
var import_node_crypto = require("crypto");
|
|
312
|
+
var import_node_http = require("http");
|
|
313
|
+
function base64Url(value) {
|
|
314
|
+
return value.toString("base64url");
|
|
315
|
+
}
|
|
316
|
+
function createPkcePair() {
|
|
317
|
+
const verifier = base64Url((0, import_node_crypto.randomBytes)(48));
|
|
318
|
+
return {
|
|
319
|
+
verifier,
|
|
320
|
+
challenge: (0, import_node_crypto.createHash)("sha256").update(verifier).digest("base64url"),
|
|
321
|
+
method: "S256"
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
function uniqueScopes(value) {
|
|
325
|
+
return [...new Set((value ?? "").split(/\s+/).filter(Boolean))].sort();
|
|
326
|
+
}
|
|
327
|
+
function json(status, body) {
|
|
328
|
+
return Response.json(body, {
|
|
329
|
+
status,
|
|
330
|
+
headers: { "cache-control": "no-store" }
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
function oauthError(status, error, description) {
|
|
334
|
+
return json(status, { error, error_description: description });
|
|
335
|
+
}
|
|
336
|
+
function escapeHtml(value) {
|
|
337
|
+
return value.replaceAll("&", "&").replaceAll('"', """).replaceAll("<", "<").replaceAll(">", ">");
|
|
338
|
+
}
|
|
339
|
+
function formValue(form, name) {
|
|
340
|
+
const value = form.get(name);
|
|
341
|
+
return value === null || value === "" ? void 0 : value;
|
|
342
|
+
}
|
|
343
|
+
var McpFnMockOAuthAuthorizationServer = class {
|
|
344
|
+
issuer;
|
|
345
|
+
clientId;
|
|
346
|
+
redirectUris;
|
|
347
|
+
scopesSupported;
|
|
348
|
+
clientMetadata;
|
|
349
|
+
codes = /* @__PURE__ */ new Map();
|
|
350
|
+
accessTokens = /* @__PURE__ */ new Map();
|
|
351
|
+
refreshTokens = /* @__PURE__ */ new Map();
|
|
352
|
+
callbacks = [];
|
|
353
|
+
clock;
|
|
354
|
+
accessTokenLifetimeSeconds;
|
|
355
|
+
authorizationCodeLifetimeSeconds;
|
|
356
|
+
refreshTokenLifetimeSeconds;
|
|
357
|
+
constructor(options) {
|
|
358
|
+
this.issuer = new URL(options.issuer);
|
|
359
|
+
this.issuer.pathname = this.issuer.pathname.replace(/\/?$/, "/");
|
|
360
|
+
this.clientId = options.clientId ?? "mcpfn-playwright";
|
|
361
|
+
this.redirectUris = options.redirectUris?.map((uri) => new URL(uri).toString()) ?? [
|
|
362
|
+
new URL("callback", this.issuer).toString()
|
|
363
|
+
];
|
|
364
|
+
this.scopesSupported = [...new Set(options.scopesSupported ?? ["mcp:read", "mcp:write"])].sort();
|
|
365
|
+
this.clock = options.clock ?? Date.now;
|
|
366
|
+
this.accessTokenLifetimeSeconds = options.accessTokenLifetimeSeconds ?? 300;
|
|
367
|
+
this.authorizationCodeLifetimeSeconds = options.authorizationCodeLifetimeSeconds ?? 120;
|
|
368
|
+
this.refreshTokenLifetimeSeconds = options.refreshTokenLifetimeSeconds ?? 3600;
|
|
369
|
+
this.clientMetadata = createOAuthClientMetadataVariants(
|
|
370
|
+
this.issuer,
|
|
371
|
+
this.redirectUris[0]
|
|
372
|
+
);
|
|
373
|
+
}
|
|
374
|
+
get metadataUrl() {
|
|
375
|
+
return new URL(".well-known/oauth-authorization-server", this.issuer).toString();
|
|
376
|
+
}
|
|
377
|
+
get authorizationEndpoint() {
|
|
378
|
+
return new URL("authorize", this.issuer).toString();
|
|
379
|
+
}
|
|
380
|
+
get tokenEndpoint() {
|
|
381
|
+
return new URL("token", this.issuer).toString();
|
|
382
|
+
}
|
|
383
|
+
get revocationEndpoint() {
|
|
384
|
+
return new URL("revoke", this.issuer).toString();
|
|
385
|
+
}
|
|
386
|
+
get callbackUrl() {
|
|
387
|
+
return this.redirectUris[0];
|
|
388
|
+
}
|
|
389
|
+
clientMetadataUrl(variant) {
|
|
390
|
+
return this.clientMetadata[variant].client_id;
|
|
391
|
+
}
|
|
392
|
+
authorizationUrl(input) {
|
|
393
|
+
const url = new URL(this.authorizationEndpoint);
|
|
394
|
+
url.searchParams.set("response_type", "code");
|
|
395
|
+
url.searchParams.set("client_id", input.clientId ?? this.clientId);
|
|
396
|
+
url.searchParams.set("redirect_uri", input.redirectUri ?? this.callbackUrl);
|
|
397
|
+
url.searchParams.set("code_challenge", input.codeChallenge);
|
|
398
|
+
url.searchParams.set("code_challenge_method", "S256");
|
|
399
|
+
url.searchParams.set("scope", (input.scopes ?? ["mcp:read"]).join(" "));
|
|
400
|
+
if (input.state) url.searchParams.set("state", input.state);
|
|
401
|
+
if (input.resource) url.searchParams.set("resource", input.resource);
|
|
402
|
+
for (const [name, value] of Object.entries(input.extraParameters ?? {})) {
|
|
403
|
+
url.searchParams.set(name, value);
|
|
404
|
+
}
|
|
405
|
+
return url.toString();
|
|
406
|
+
}
|
|
407
|
+
latestCallback() {
|
|
408
|
+
return this.callbacks.at(-1);
|
|
409
|
+
}
|
|
410
|
+
expireAccessToken(token) {
|
|
411
|
+
const record = this.accessTokens.get(token);
|
|
412
|
+
if (record) record.expiresAt = this.nowSeconds() - 1;
|
|
413
|
+
}
|
|
414
|
+
revokeToken(token) {
|
|
415
|
+
const access = this.accessTokens.get(token);
|
|
416
|
+
if (access) access.revoked = true;
|
|
417
|
+
const refresh = this.refreshTokens.get(token);
|
|
418
|
+
if (refresh) refresh.revoked = true;
|
|
419
|
+
}
|
|
420
|
+
async verifyAccessToken(token) {
|
|
421
|
+
const record = this.accessTokens.get(token);
|
|
422
|
+
if (!record || record.revoked || record.expiresAt <= this.nowSeconds()) {
|
|
423
|
+
throw new Error("Invalid access token");
|
|
424
|
+
}
|
|
425
|
+
return {
|
|
426
|
+
token,
|
|
427
|
+
clientId: record.clientId,
|
|
428
|
+
scopes: record.scopes,
|
|
429
|
+
expiresAt: record.expiresAt,
|
|
430
|
+
...record.resource ? { resource: new URL(record.resource) } : {}
|
|
431
|
+
};
|
|
432
|
+
}
|
|
433
|
+
async handle(request) {
|
|
434
|
+
const url = new URL(request.url);
|
|
435
|
+
const path = url.pathname.replace(this.issuer.pathname.replace(/\/$/, ""), "") || "/";
|
|
436
|
+
if (request.method === "GET" && path === "/.well-known/oauth-authorization-server") {
|
|
437
|
+
return json(200, {
|
|
438
|
+
issuer: this.issuer.toString(),
|
|
439
|
+
authorization_endpoint: this.authorizationEndpoint,
|
|
440
|
+
token_endpoint: this.tokenEndpoint,
|
|
441
|
+
revocation_endpoint: this.revocationEndpoint,
|
|
442
|
+
response_types_supported: ["code"],
|
|
443
|
+
grant_types_supported: ["authorization_code", "refresh_token"],
|
|
444
|
+
code_challenge_methods_supported: ["S256"],
|
|
445
|
+
token_endpoint_auth_methods_supported: ["none"],
|
|
446
|
+
scopes_supported: this.scopesSupported
|
|
447
|
+
});
|
|
448
|
+
}
|
|
449
|
+
if (request.method === "GET" && path.startsWith("/client-metadata/")) {
|
|
450
|
+
const metadata = Object.values(this.clientMetadata).find((candidate) => new URL(candidate.client_id).pathname === url.pathname);
|
|
451
|
+
return metadata ? json(200, metadata) : json(404, { error: "not_found" });
|
|
452
|
+
}
|
|
453
|
+
if (request.method === "GET" && path === "/authorize") {
|
|
454
|
+
return this.authorize(url);
|
|
455
|
+
}
|
|
456
|
+
if (request.method === "POST" && path === "/token") {
|
|
457
|
+
return this.token(await request.text());
|
|
458
|
+
}
|
|
459
|
+
if (request.method === "POST" && path === "/revoke") {
|
|
460
|
+
return this.revoke(await request.text());
|
|
461
|
+
}
|
|
462
|
+
if (request.method === "GET" && path === "/callback") {
|
|
463
|
+
const parameters = Object.fromEntries(url.searchParams);
|
|
464
|
+
this.callbacks.push({ url: url.toString(), parameters });
|
|
465
|
+
return new Response(
|
|
466
|
+
`<!doctype html><html><body><main><h1>OAuth callback received</h1><pre>${escapeHtml(JSON.stringify(parameters, null, 2))}</pre></main></body></html>`,
|
|
467
|
+
{ headers: { "content-type": "text/html; charset=utf-8" } }
|
|
468
|
+
);
|
|
469
|
+
}
|
|
470
|
+
return json(404, { error: "not_found" });
|
|
471
|
+
}
|
|
472
|
+
nowSeconds() {
|
|
473
|
+
return Math.floor(this.clock() / 1e3);
|
|
474
|
+
}
|
|
475
|
+
resolveClient(clientId) {
|
|
476
|
+
if (clientId === this.clientId) {
|
|
477
|
+
return { clientId, redirectUris: this.redirectUris };
|
|
478
|
+
}
|
|
479
|
+
const metadata = Object.values(this.clientMetadata).find((candidate) => candidate.client_id === clientId);
|
|
480
|
+
if (!metadata) return void 0;
|
|
481
|
+
assertAuthorizationCodeClientMetadata(metadata, clientId);
|
|
482
|
+
return { clientId, redirectUris: metadata.redirect_uris };
|
|
483
|
+
}
|
|
484
|
+
authorize(url) {
|
|
485
|
+
const clientId = url.searchParams.get("client_id") ?? "";
|
|
486
|
+
const redirectUri = url.searchParams.get("redirect_uri") ?? "";
|
|
487
|
+
const client = this.resolveClient(clientId);
|
|
488
|
+
if (!client) return oauthError(400, "invalid_client", "Unknown OAuth client");
|
|
489
|
+
if (!client.redirectUris.includes(redirectUri)) {
|
|
490
|
+
return oauthError(400, "invalid_request", "redirect_uri is not registered");
|
|
491
|
+
}
|
|
492
|
+
if (url.searchParams.get("response_type") !== "code") {
|
|
493
|
+
return this.authorizationRedirect(url, redirectUri, "unsupported_response_type");
|
|
494
|
+
}
|
|
495
|
+
const codeChallenge = url.searchParams.get("code_challenge");
|
|
496
|
+
if (!codeChallenge || url.searchParams.get("code_challenge_method") !== "S256") {
|
|
497
|
+
return this.authorizationRedirect(url, redirectUri, "invalid_request", "PKCE S256 is required");
|
|
498
|
+
}
|
|
499
|
+
const requestedScopes = uniqueScopes(url.searchParams.get("scope"));
|
|
500
|
+
if (requestedScopes.some((scope) => !this.scopesSupported.includes(scope))) {
|
|
501
|
+
return this.authorizationRedirect(url, redirectUri, "invalid_scope");
|
|
502
|
+
}
|
|
503
|
+
const decision = url.searchParams.get("decision");
|
|
504
|
+
if (!decision) {
|
|
505
|
+
const hidden = [...url.searchParams].filter(([name]) => name !== "decision").map(([name, value]) => `<input type="hidden" name="${escapeHtml(name)}" value="${escapeHtml(value)}">`).join("");
|
|
506
|
+
return new Response(
|
|
507
|
+
`<!doctype html><html><body><main><h1>Authorize MCP client</h1><p>${escapeHtml(clientId)}</p><form method="get" action="${escapeHtml(this.authorizationEndpoint)}">${hidden}<button name="decision" value="approve">Approve</button><button name="decision" value="deny">Deny</button></form></main></body></html>`,
|
|
508
|
+
{ headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" } }
|
|
509
|
+
);
|
|
510
|
+
}
|
|
511
|
+
if (decision === "deny") {
|
|
512
|
+
return this.authorizationRedirect(url, redirectUri, "access_denied");
|
|
513
|
+
}
|
|
514
|
+
if (decision !== "approve") {
|
|
515
|
+
return oauthError(400, "invalid_request", "Unknown authorization decision");
|
|
516
|
+
}
|
|
517
|
+
const code = `mcpfn_code_${(0, import_node_crypto.randomUUID)()}`;
|
|
518
|
+
this.codes.set(code, {
|
|
519
|
+
clientId,
|
|
520
|
+
redirectUri,
|
|
521
|
+
codeChallenge,
|
|
522
|
+
scopes: requestedScopes,
|
|
523
|
+
resource: url.searchParams.get("resource") ?? void 0,
|
|
524
|
+
expiresAt: this.nowSeconds() + this.authorizationCodeLifetimeSeconds,
|
|
525
|
+
used: false
|
|
526
|
+
});
|
|
527
|
+
const callback = new URL(redirectUri);
|
|
528
|
+
callback.searchParams.set("code", code);
|
|
529
|
+
const state = url.searchParams.get("state");
|
|
530
|
+
if (state) callback.searchParams.set("state", state);
|
|
531
|
+
return Response.redirect(callback, 302);
|
|
532
|
+
}
|
|
533
|
+
authorizationRedirect(requestUrl, redirectUri, error, description) {
|
|
534
|
+
const callback = new URL(redirectUri);
|
|
535
|
+
callback.searchParams.set("error", error);
|
|
536
|
+
if (description) callback.searchParams.set("error_description", description);
|
|
537
|
+
const state = requestUrl.searchParams.get("state");
|
|
538
|
+
if (state) callback.searchParams.set("state", state);
|
|
539
|
+
return Response.redirect(callback, 302);
|
|
540
|
+
}
|
|
541
|
+
token(source) {
|
|
542
|
+
const form = new URLSearchParams(source);
|
|
543
|
+
const grantType = formValue(form, "grant_type");
|
|
544
|
+
if (grantType === "authorization_code") return this.exchangeAuthorizationCode(form);
|
|
545
|
+
if (grantType === "refresh_token") return this.exchangeRefreshToken(form);
|
|
546
|
+
return oauthError(400, "unsupported_grant_type", "The grant type is not supported");
|
|
547
|
+
}
|
|
548
|
+
exchangeAuthorizationCode(form) {
|
|
549
|
+
const code = formValue(form, "code");
|
|
550
|
+
const record = code ? this.codes.get(code) : void 0;
|
|
551
|
+
if (!record || record.used || record.expiresAt <= this.nowSeconds()) {
|
|
552
|
+
return oauthError(400, "invalid_grant", "Authorization code is invalid or expired");
|
|
553
|
+
}
|
|
554
|
+
if (formValue(form, "client_id") !== record.clientId || formValue(form, "redirect_uri") !== record.redirectUri) {
|
|
555
|
+
return oauthError(400, "invalid_grant", "Authorization code binding does not match");
|
|
556
|
+
}
|
|
557
|
+
const verifier = formValue(form, "code_verifier");
|
|
558
|
+
const challenge = verifier ? (0, import_node_crypto.createHash)("sha256").update(verifier).digest("base64url") : void 0;
|
|
559
|
+
if (challenge !== record.codeChallenge) {
|
|
560
|
+
return oauthError(400, "invalid_grant", "PKCE verification failed");
|
|
561
|
+
}
|
|
562
|
+
record.used = true;
|
|
563
|
+
return json(200, this.issueTokenSet(record));
|
|
564
|
+
}
|
|
565
|
+
exchangeRefreshToken(form) {
|
|
566
|
+
const refreshToken = formValue(form, "refresh_token");
|
|
567
|
+
const record = refreshToken ? this.refreshTokens.get(refreshToken) : void 0;
|
|
568
|
+
if (!record || record.revoked || record.expiresAt <= this.nowSeconds()) {
|
|
569
|
+
return oauthError(400, "invalid_grant", "Refresh token is invalid or expired");
|
|
570
|
+
}
|
|
571
|
+
if (formValue(form, "client_id") !== record.clientId) {
|
|
572
|
+
return oauthError(400, "invalid_grant", "Refresh token client binding does not match");
|
|
573
|
+
}
|
|
574
|
+
const requestedScopes = form.has("scope") ? uniqueScopes(form.get("scope")) : record.scopes;
|
|
575
|
+
if (requestedScopes.some((scope) => !record.scopes.includes(scope))) {
|
|
576
|
+
return oauthError(400, "invalid_scope", "Refresh cannot increase granted scopes");
|
|
577
|
+
}
|
|
578
|
+
record.revoked = true;
|
|
579
|
+
return json(200, this.issueTokenSet({ ...record, scopes: requestedScopes }));
|
|
580
|
+
}
|
|
581
|
+
issueTokenSet(input) {
|
|
582
|
+
const accessToken = `mcpfn_access_${(0, import_node_crypto.randomUUID)()}`;
|
|
583
|
+
const refreshToken = `mcpfn_refresh_${(0, import_node_crypto.randomUUID)()}`;
|
|
584
|
+
this.accessTokens.set(accessToken, {
|
|
585
|
+
...input,
|
|
586
|
+
expiresAt: this.nowSeconds() + this.accessTokenLifetimeSeconds,
|
|
587
|
+
revoked: false
|
|
588
|
+
});
|
|
589
|
+
this.refreshTokens.set(refreshToken, {
|
|
590
|
+
...input,
|
|
591
|
+
expiresAt: this.nowSeconds() + this.refreshTokenLifetimeSeconds,
|
|
592
|
+
revoked: false
|
|
593
|
+
});
|
|
594
|
+
return {
|
|
595
|
+
access_token: accessToken,
|
|
596
|
+
token_type: "Bearer",
|
|
597
|
+
expires_in: this.accessTokenLifetimeSeconds,
|
|
598
|
+
refresh_token: refreshToken,
|
|
599
|
+
scope: input.scopes.join(" "),
|
|
600
|
+
...input.resource ? { resource: input.resource } : {}
|
|
601
|
+
};
|
|
602
|
+
}
|
|
603
|
+
revoke(source) {
|
|
604
|
+
const token = new URLSearchParams(source).get("token");
|
|
605
|
+
if (token) this.revokeToken(token);
|
|
606
|
+
return new Response(null, { status: 200 });
|
|
607
|
+
}
|
|
608
|
+
};
|
|
609
|
+
async function toRequest(req, origin) {
|
|
610
|
+
const chunks = [];
|
|
611
|
+
for await (const chunk of req) chunks.push(Buffer.from(chunk));
|
|
612
|
+
const headers = new Headers();
|
|
613
|
+
for (const [name, value] of Object.entries(req.headers)) {
|
|
614
|
+
if (Array.isArray(value)) {
|
|
615
|
+
for (const entry of value) headers.append(name, entry);
|
|
616
|
+
} else if (value !== void 0) {
|
|
617
|
+
headers.set(name, value);
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
const body = chunks.length ? Buffer.concat(chunks) : void 0;
|
|
621
|
+
const init = {
|
|
622
|
+
method: req.method,
|
|
623
|
+
headers,
|
|
624
|
+
...body ? { body, duplex: "half" } : {}
|
|
625
|
+
};
|
|
626
|
+
return new Request(new URL(req.url ?? "/", origin), init);
|
|
627
|
+
}
|
|
628
|
+
async function writeResponse(res, response) {
|
|
629
|
+
res.statusCode = response.status;
|
|
630
|
+
response.headers.forEach((value, name) => res.setHeader(name, value));
|
|
631
|
+
res.end(Buffer.from(await response.arrayBuffer()));
|
|
632
|
+
}
|
|
633
|
+
async function startMockOAuthAuthorizationServer(options = {}) {
|
|
634
|
+
let oauth;
|
|
635
|
+
let origin = "";
|
|
636
|
+
const server = (0, import_node_http.createServer)(async (req, res) => {
|
|
637
|
+
try {
|
|
638
|
+
if (!oauth) throw new Error("Mock OAuth server is not initialized");
|
|
639
|
+
await writeResponse(res, await oauth.handle(await toRequest(req, origin)));
|
|
640
|
+
} catch {
|
|
641
|
+
res.statusCode = 500;
|
|
642
|
+
res.setHeader("content-type", "application/json");
|
|
643
|
+
res.end(JSON.stringify({
|
|
644
|
+
error: "server_error",
|
|
645
|
+
error_description: "Internal Server Error"
|
|
646
|
+
}));
|
|
647
|
+
}
|
|
648
|
+
});
|
|
649
|
+
await new Promise((resolve, reject) => {
|
|
650
|
+
server.once("error", reject);
|
|
651
|
+
server.listen(options.port ?? 0, options.hostname ?? "127.0.0.1", () => {
|
|
652
|
+
server.off("error", reject);
|
|
653
|
+
resolve();
|
|
654
|
+
});
|
|
655
|
+
});
|
|
656
|
+
const address = server.address();
|
|
657
|
+
origin = `http://${address.address.includes(":") ? `[${address.address}]` : address.address}:${address.port}`;
|
|
658
|
+
oauth = new McpFnMockOAuthAuthorizationServer({ ...options, issuer: origin });
|
|
659
|
+
return {
|
|
660
|
+
origin,
|
|
661
|
+
oauth,
|
|
662
|
+
close: () => new Promise((resolve, reject) => {
|
|
663
|
+
server.close((error) => error ? reject(error) : resolve());
|
|
664
|
+
})
|
|
665
|
+
};
|
|
666
|
+
}
|
|
667
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
668
|
+
0 && (module.exports = {
|
|
669
|
+
MCPFN_OAUTH_EXTENSION_GRANTS,
|
|
670
|
+
McpFnAuthAssertionError,
|
|
671
|
+
McpFnMockOAuthAuthorizationServer,
|
|
672
|
+
apiKeyCredential,
|
|
673
|
+
assertAuthRegressionSuite,
|
|
674
|
+
assertAuthorizationCodeClientMetadata,
|
|
675
|
+
assertBearerResourceChallenge,
|
|
676
|
+
bearerCredential,
|
|
677
|
+
createFetchAuthTarget,
|
|
678
|
+
createOAuthClientMetadataFixture,
|
|
679
|
+
createOAuthClientMetadataVariants,
|
|
680
|
+
createPkcePair,
|
|
681
|
+
parseBearerChallenge,
|
|
682
|
+
runAuthRegressionSuite,
|
|
683
|
+
startMockOAuthAuthorizationServer
|
|
684
|
+
});
|
|
685
|
+
//# sourceMappingURL=auth.cjs.map
|