keryx 0.40.0 → 0.41.0
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/config/server/mcp.ts +24 -0
- package/initializers/mcp.ts +73 -14
- package/initializers/oauth.ts +1 -1
- package/package.json +1 -1
- package/templates/oauth-authorize.html +1 -1
- package/templates/oauth-common.css +21 -0
- package/util/mcpServer.ts +87 -1
- package/util/oauthHandlers/authorize.ts +49 -7
- package/util/oauthHandlers/cimd.ts +450 -0
- package/util/oauthHandlers/index.ts +4 -0
- package/util/oauthHandlers/metadata.ts +6 -1
- package/util/oauthTemplates.ts +57 -0
package/config/server/mcp.ts
CHANGED
|
@@ -28,6 +28,30 @@ export const configServerMcp = {
|
|
|
28
28
|
60 * 60 * 24 * 30,
|
|
29
29
|
), // 30 days, in seconds
|
|
30
30
|
oauthTrustProxy: await loadFromEnvIfSet("MCP_OAUTH_TRUST_PROXY", false),
|
|
31
|
+
// Client ID Metadata Documents (MCP 2026-07-28 / SEP-991): accept an HTTPS
|
|
32
|
+
// URL as a `client_id` and fetch the client's metadata from it, so clients
|
|
33
|
+
// need no Dynamic Client Registration round trip.
|
|
34
|
+
oauthCimdEnabled: await loadFromEnvIfSet("MCP_OAUTH_CIMD_ENABLED", true),
|
|
35
|
+
// Ceiling for how long a fetched metadata document is cached. A shorter
|
|
36
|
+
// `Cache-Control: max-age` from the client's origin wins; `no-store` /
|
|
37
|
+
// `no-cache` disables caching for that document.
|
|
38
|
+
oauthCimdCacheTtl: await loadFromEnvIfSet("MCP_OAUTH_CIMD_CACHE_TTL", 3600), // 1 hour, in seconds
|
|
39
|
+
oauthCimdFetchTimeoutMs: await loadFromEnvIfSet(
|
|
40
|
+
"MCP_OAUTH_CIMD_FETCH_TIMEOUT_MS",
|
|
41
|
+
5000,
|
|
42
|
+
),
|
|
43
|
+
oauthCimdMaxBytes: await loadFromEnvIfSet(
|
|
44
|
+
"MCP_OAUTH_CIMD_MAX_BYTES",
|
|
45
|
+
64 * 1024,
|
|
46
|
+
),
|
|
47
|
+
// Development escape hatch: allow metadata documents on loopback/private
|
|
48
|
+
// hosts (and over plain `http:`). Leave this off in production — it disables
|
|
49
|
+
// the SSRF guard that keeps the authorization server from fetching its own
|
|
50
|
+
// private network.
|
|
51
|
+
oauthCimdAllowPrivateHosts: await loadFromEnvIfSet(
|
|
52
|
+
"MCP_OAUTH_CIMD_ALLOW_PRIVATE_HOSTS",
|
|
53
|
+
false,
|
|
54
|
+
),
|
|
31
55
|
markdownDepthLimit: await loadFromEnvIfSet("MCP_MARKDOWN_DEPTH_LIMIT", 5),
|
|
32
56
|
// TTL (seconds) for the shared MCP session registry in Redis. Every MCP
|
|
33
57
|
// request refreshes it, so this is an idle timeout: a session is reclaimed
|
package/initializers/mcp.ts
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
2
|
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
|
|
3
|
-
import {
|
|
3
|
+
import {
|
|
4
|
+
isInitializeRequest,
|
|
5
|
+
LATEST_PROTOCOL_VERSION,
|
|
6
|
+
SUPPORTED_PROTOCOL_VERSIONS,
|
|
7
|
+
} from "@modelcontextprotocol/sdk/types.js";
|
|
4
8
|
import { randomUUID } from "crypto";
|
|
5
9
|
import { api, logger } from "../api";
|
|
6
10
|
import { Initializer } from "../classes/Initializer";
|
|
@@ -21,14 +25,17 @@ import {
|
|
|
21
25
|
formatToolName,
|
|
22
26
|
handleTransportRequest,
|
|
23
27
|
isMcpSessionAuthorizedForChannel,
|
|
28
|
+
MCP_JSONRPC_ERROR,
|
|
24
29
|
type McpAuthInfo,
|
|
25
30
|
type McpSessionAuth,
|
|
26
31
|
mcpJsonResponse,
|
|
32
|
+
mcpJsonRpcErrorResponse,
|
|
27
33
|
parseToolName,
|
|
28
34
|
readMcpSessionRecord,
|
|
29
35
|
refreshMcpSessionTtl,
|
|
30
36
|
sanitizeSchemaForMcp,
|
|
31
37
|
terminateMcpSession,
|
|
38
|
+
validateJsonRpcPayload,
|
|
32
39
|
writeMcpSessionRecord,
|
|
33
40
|
} from "../util/mcpServer";
|
|
34
41
|
import type { PubSubMessage } from "./pubsub";
|
|
@@ -61,18 +68,34 @@ export type OnMcpDisconnectHook = (sessionId: string) => Promise<void> | void;
|
|
|
61
68
|
const namespace = "mcp";
|
|
62
69
|
|
|
63
70
|
/**
|
|
64
|
-
*
|
|
65
|
-
*
|
|
71
|
+
* Resolve the protocol version an `initialize` request body (single message or
|
|
72
|
+
* batch) actually negotiates, so it can be stored in the shared session registry
|
|
66
73
|
* and replayed when the session is adopted on another node.
|
|
74
|
+
*
|
|
75
|
+
* This is the *negotiated* version, not the requested one: a client on a newer
|
|
76
|
+
* spec revision than the SDK supports (e.g. `2026-07-28`) is answered with the
|
|
77
|
+
* newest version the server does support, exactly as the SDK's `initialize`
|
|
78
|
+
* handler does. Persisting the raw request instead would leave the registry
|
|
79
|
+
* holding a version no node can replay, and the session would silently fall back
|
|
80
|
+
* to the 2025-03-26 default the first time it was adopted elsewhere.
|
|
81
|
+
*
|
|
82
|
+
* @param body - The parsed POST body.
|
|
83
|
+
* @returns The negotiated version, or `undefined` when the body contains no
|
|
84
|
+
* `initialize` request.
|
|
67
85
|
*/
|
|
68
|
-
function
|
|
86
|
+
function negotiateInitProtocolVersion(body: unknown): string | undefined {
|
|
69
87
|
const messages = Array.isArray(body) ? body : [body];
|
|
70
88
|
for (const message of messages) {
|
|
71
89
|
if (isInitializeRequest(message)) {
|
|
72
90
|
const protocolVersion = (
|
|
73
91
|
message as { params?: { protocolVersion?: unknown } }
|
|
74
92
|
).params?.protocolVersion;
|
|
75
|
-
if (typeof protocolVersion
|
|
93
|
+
if (typeof protocolVersion !== "string") continue;
|
|
94
|
+
return (SUPPORTED_PROTOCOL_VERSIONS as readonly string[]).includes(
|
|
95
|
+
protocolVersion,
|
|
96
|
+
)
|
|
97
|
+
? protocolVersion
|
|
98
|
+
: LATEST_PROTOCOL_VERSION;
|
|
76
99
|
}
|
|
77
100
|
}
|
|
78
101
|
return undefined;
|
|
@@ -273,17 +296,41 @@ export class McpInitializer extends Initializer {
|
|
|
273
296
|
|
|
274
297
|
const sessionId = req.headers.get("mcp-session-id");
|
|
275
298
|
|
|
299
|
+
// Validate the JSON-RPC envelope of every POST before it reaches a
|
|
300
|
+
// transport. The SDK transport answers both "not JSON" and "not a
|
|
301
|
+
// JSON-RPC message" with `-32700 Parse error`; JSON-RPC 2.0 reserves that
|
|
302
|
+
// code for unparseable input and requires `-32600 Invalid Request` for a
|
|
303
|
+
// payload that parses but isn't a valid message. Parsing here also means
|
|
304
|
+
// the body is read exactly once — the result is handed to the transport as
|
|
305
|
+
// `parsedBody`.
|
|
306
|
+
let body: unknown;
|
|
307
|
+
if (method === "POST") {
|
|
308
|
+
try {
|
|
309
|
+
body = await req.json();
|
|
310
|
+
} catch {
|
|
311
|
+
return mcpJsonRpcErrorResponse(
|
|
312
|
+
MCP_JSONRPC_ERROR.PARSE_ERROR,
|
|
313
|
+
"Parse error: body is not valid JSON",
|
|
314
|
+
400,
|
|
315
|
+
corsHeaders,
|
|
316
|
+
);
|
|
317
|
+
}
|
|
318
|
+
const invalid = validateJsonRpcPayload(body);
|
|
319
|
+
if (invalid) {
|
|
320
|
+
return mcpJsonRpcErrorResponse(
|
|
321
|
+
invalid.code,
|
|
322
|
+
invalid.message,
|
|
323
|
+
400,
|
|
324
|
+
corsHeaders,
|
|
325
|
+
);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
276
329
|
if (method === "POST" && !sessionId) {
|
|
277
330
|
// Only an `initialize` request may create a new session. Any other
|
|
278
331
|
// request without a session id is a protocol error → 400. We must gate
|
|
279
332
|
// here rather than delegating, otherwise a non-initialize POST spins up
|
|
280
333
|
// an McpServer that never initializes and leaks into `mcpServers`.
|
|
281
|
-
let body: unknown;
|
|
282
|
-
try {
|
|
283
|
-
body = await req.clone().json();
|
|
284
|
-
} catch {
|
|
285
|
-
return mcpJsonResponse({ error: "Invalid JSON" }, 400, corsHeaders);
|
|
286
|
-
}
|
|
287
334
|
const isInit = Array.isArray(body)
|
|
288
335
|
? body.some(isInitializeRequest)
|
|
289
336
|
: isInitializeRequest(body);
|
|
@@ -294,7 +341,7 @@ export class McpInitializer extends Initializer {
|
|
|
294
341
|
corsHeaders,
|
|
295
342
|
);
|
|
296
343
|
}
|
|
297
|
-
const protocolVersion =
|
|
344
|
+
const protocolVersion = negotiateInitProtocolVersion(body);
|
|
298
345
|
|
|
299
346
|
// New session — create a new McpServer + transport
|
|
300
347
|
const mcpServer = createMcpServer();
|
|
@@ -338,7 +385,13 @@ export class McpInitializer extends Initializer {
|
|
|
338
385
|
for (const hook of api.hooks.mcp.onMessageHooks) {
|
|
339
386
|
await hook(undefined);
|
|
340
387
|
}
|
|
341
|
-
return handleTransportRequest(
|
|
388
|
+
return handleTransportRequest(
|
|
389
|
+
transport,
|
|
390
|
+
req,
|
|
391
|
+
authInfo,
|
|
392
|
+
corsHeaders,
|
|
393
|
+
body,
|
|
394
|
+
);
|
|
342
395
|
}
|
|
343
396
|
|
|
344
397
|
if (sessionId) {
|
|
@@ -386,7 +439,13 @@ export class McpInitializer extends Initializer {
|
|
|
386
439
|
for (const hook of api.hooks.mcp.onMessageHooks) {
|
|
387
440
|
await hook(sessionId);
|
|
388
441
|
}
|
|
389
|
-
return handleTransportRequest(
|
|
442
|
+
return handleTransportRequest(
|
|
443
|
+
transport,
|
|
444
|
+
req,
|
|
445
|
+
authInfo,
|
|
446
|
+
corsHeaders,
|
|
447
|
+
body,
|
|
448
|
+
);
|
|
390
449
|
}
|
|
391
450
|
|
|
392
451
|
// GET/DELETE without session ID
|
package/initializers/oauth.ts
CHANGED
|
@@ -144,7 +144,7 @@ export class OAuthInitializer extends Initializer {
|
|
|
144
144
|
return appendHeaders(await handleRegister(req), corsHeaders);
|
|
145
145
|
}
|
|
146
146
|
if (path === OAUTH_PATHS.authorize && method === "GET") {
|
|
147
|
-
return handleAuthorizeGet(url, templates);
|
|
147
|
+
return await handleAuthorizeGet(url, templates);
|
|
148
148
|
}
|
|
149
149
|
if (path === OAUTH_PATHS.authorize && method === "POST") {
|
|
150
150
|
return handleAuthorizePost(req, templates, origin);
|
package/package.json
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
<body>
|
|
14
14
|
<div class="container">
|
|
15
15
|
<h2>Authorize Application</h2>
|
|
16
|
-
{{{errorHtml}}} {{#hasSignin}}{{#hasSignup}}
|
|
16
|
+
{{{errorHtml}}} {{{clientInfoHtml}}} {{#hasSignin}}{{#hasSignup}}
|
|
17
17
|
<div class="tabs">
|
|
18
18
|
<div class="tab active" onclick="switchTab('signin')">Sign In</div>
|
|
19
19
|
<div class="tab" onclick="switchTab('signup')">Sign Up</div>
|
|
@@ -36,6 +36,27 @@ h2 {
|
|
|
36
36
|
margin-bottom: 16px;
|
|
37
37
|
font-size: 14px;
|
|
38
38
|
}
|
|
39
|
+
.client-info {
|
|
40
|
+
background: color-mix(in srgb, var(--keryx-color-primary) 6%, transparent);
|
|
41
|
+
border: 1px solid var(--keryx-color-border);
|
|
42
|
+
border-radius: 6px;
|
|
43
|
+
padding: 12px 14px;
|
|
44
|
+
margin-bottom: 20px;
|
|
45
|
+
}
|
|
46
|
+
.client-info p:last-child {
|
|
47
|
+
margin-bottom: 0;
|
|
48
|
+
}
|
|
49
|
+
.client-info strong {
|
|
50
|
+
color: var(--keryx-color-text);
|
|
51
|
+
}
|
|
52
|
+
.client-detail {
|
|
53
|
+
font-size: 13px;
|
|
54
|
+
word-break: break-all;
|
|
55
|
+
}
|
|
56
|
+
.client-warning {
|
|
57
|
+
font-size: 13px;
|
|
58
|
+
color: #a15c07;
|
|
59
|
+
}
|
|
39
60
|
.tabs {
|
|
40
61
|
display: flex;
|
|
41
62
|
margin-bottom: 20px;
|
package/util/mcpServer.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/
|
|
|
6
6
|
import type { RequestHandlerExtra } from "@modelcontextprotocol/sdk/shared/protocol.js";
|
|
7
7
|
import {
|
|
8
8
|
DEFAULT_NEGOTIATED_PROTOCOL_VERSION,
|
|
9
|
+
JSONRPCMessageSchema,
|
|
9
10
|
type ServerNotification,
|
|
10
11
|
type ServerRequest,
|
|
11
12
|
SUPPORTED_PROTOCOL_VERSIONS,
|
|
@@ -137,15 +138,27 @@ export async function isMcpSessionAuthorizedForChannel(
|
|
|
137
138
|
/**
|
|
138
139
|
* Forward a request to an MCP transport and return the response with CORS headers.
|
|
139
140
|
* Handles the try/catch + error response pattern shared by new-session and existing-session paths.
|
|
141
|
+
*
|
|
142
|
+
* @param transport - The session's Streamable HTTP transport.
|
|
143
|
+
* @param req - The inbound MCP request.
|
|
144
|
+
* @param authInfo - Verified bearer-token context for the request, if any.
|
|
145
|
+
* @param corsHeaders - CORS headers to append to whatever the transport returns.
|
|
146
|
+
* @param parsedBody - The already-parsed POST body, so the transport doesn't
|
|
147
|
+
* re-read (and re-parse) a stream Keryx has already consumed while validating
|
|
148
|
+
* the JSON-RPC envelope. Omit for GET/DELETE.
|
|
140
149
|
*/
|
|
141
150
|
export async function handleTransportRequest(
|
|
142
151
|
transport: WebStandardStreamableHTTPServerTransport,
|
|
143
152
|
req: Request,
|
|
144
153
|
authInfo: McpAuthInfo | undefined,
|
|
145
154
|
corsHeaders: Record<string, string>,
|
|
155
|
+
parsedBody?: unknown,
|
|
146
156
|
): Promise<Response> {
|
|
147
157
|
try {
|
|
148
|
-
const response = await transport.handleRequest(req, {
|
|
158
|
+
const response = await transport.handleRequest(req, {
|
|
159
|
+
authInfo,
|
|
160
|
+
parsedBody,
|
|
161
|
+
});
|
|
149
162
|
return appendHeaders(response, corsHeaders);
|
|
150
163
|
} catch (e) {
|
|
151
164
|
logger.error(`MCP transport error: ${e}`);
|
|
@@ -181,6 +194,79 @@ export function mcpJsonResponse(
|
|
|
181
194
|
});
|
|
182
195
|
}
|
|
183
196
|
|
|
197
|
+
/**
|
|
198
|
+
* The JSON-RPC 2.0 error codes the MCP endpoint returns for a POST body it
|
|
199
|
+
* refuses to dispatch. `PARSE_ERROR` means the body was not JSON at all;
|
|
200
|
+
* `INVALID_REQUEST` means it was JSON but not a well-formed JSON-RPC message.
|
|
201
|
+
* The distinction matters: the MCP SDK transport reports both as `PARSE_ERROR`,
|
|
202
|
+
* which conformance checkers flag, so Keryx validates the envelope itself
|
|
203
|
+
* before handing the body to the transport.
|
|
204
|
+
*/
|
|
205
|
+
export const MCP_JSONRPC_ERROR = {
|
|
206
|
+
PARSE_ERROR: -32700,
|
|
207
|
+
INVALID_REQUEST: -32600,
|
|
208
|
+
} as const;
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Build a JSON-RPC *error response* for a message that could never be
|
|
212
|
+
* dispatched. `id` is always `null`: JSON-RPC 2.0 requires a null id when the
|
|
213
|
+
* request's id can't be determined, and the Streamable HTTP transport spec says
|
|
214
|
+
* the body of a rejected POST may carry an error response with no id.
|
|
215
|
+
*
|
|
216
|
+
* @param code - JSON-RPC error code (see {@link MCP_JSONRPC_ERROR}).
|
|
217
|
+
* @param message - Human-readable explanation, surfaced to the client verbatim.
|
|
218
|
+
* @param status - HTTP status to pair with it (400 for malformed input).
|
|
219
|
+
* @param corsHeaders - CORS headers for the MCP endpoint.
|
|
220
|
+
*/
|
|
221
|
+
export function mcpJsonRpcErrorResponse(
|
|
222
|
+
code: number,
|
|
223
|
+
message: string,
|
|
224
|
+
status: number,
|
|
225
|
+
corsHeaders: Record<string, string>,
|
|
226
|
+
): Response {
|
|
227
|
+
return mcpJsonResponse(
|
|
228
|
+
{ jsonrpc: "2.0", error: { code, message }, id: null },
|
|
229
|
+
status,
|
|
230
|
+
corsHeaders,
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Validate a parsed MCP POST body against the JSON-RPC message schema, so a
|
|
236
|
+
* structurally invalid message is rejected as `-32600 Invalid Request` rather
|
|
237
|
+
* than being mislabeled a parse error by the transport.
|
|
238
|
+
*
|
|
239
|
+
* Accepts a single request, notification, or response — and, for clients still
|
|
240
|
+
* on protocol 2025-03-26, a non-empty array of them. Every element of an array
|
|
241
|
+
* must be well-formed; one bad message rejects the whole POST, matching how the
|
|
242
|
+
* transport dispatches batches.
|
|
243
|
+
*
|
|
244
|
+
* @param body - The already-parsed JSON body of the POST.
|
|
245
|
+
* @returns `undefined` when the body is well-formed, otherwise the JSON-RPC
|
|
246
|
+
* `code`/`message` pair to return with HTTP 400.
|
|
247
|
+
*/
|
|
248
|
+
export function validateJsonRpcPayload(
|
|
249
|
+
body: unknown,
|
|
250
|
+
): { code: number; message: string } | undefined {
|
|
251
|
+
const messages = Array.isArray(body) ? body : [body];
|
|
252
|
+
if (messages.length === 0) {
|
|
253
|
+
return {
|
|
254
|
+
code: MCP_JSONRPC_ERROR.INVALID_REQUEST,
|
|
255
|
+
message: "Invalid Request: JSON-RPC batch must not be empty",
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
for (const message of messages) {
|
|
259
|
+
if (!JSONRPCMessageSchema.safeParse(message).success) {
|
|
260
|
+
return {
|
|
261
|
+
code: MCP_JSONRPC_ERROR.INVALID_REQUEST,
|
|
262
|
+
message:
|
|
263
|
+
"Invalid Request: body must be a JSON-RPC request, notification, or response",
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
return undefined;
|
|
268
|
+
}
|
|
269
|
+
|
|
184
270
|
/**
|
|
185
271
|
* A record in the shared (Redis-backed) MCP session registry. This is the
|
|
186
272
|
* cluster-wide source of truth for whether a Streamable HTTP session exists and
|
|
@@ -9,6 +9,10 @@ import {
|
|
|
9
9
|
type OAuthTemplates,
|
|
10
10
|
renderAuthPage,
|
|
11
11
|
} from "../oauthTemplates";
|
|
12
|
+
import {
|
|
13
|
+
isClientIdMetadataDocumentUrl,
|
|
14
|
+
resolveClientIdMetadataDocument,
|
|
15
|
+
} from "./cimd";
|
|
12
16
|
import { clientKey, codeKey } from "./keys";
|
|
13
17
|
import type { AuthCode, OAuthClient } from "./types";
|
|
14
18
|
|
|
@@ -32,19 +36,56 @@ function findAuthActions() {
|
|
|
32
36
|
};
|
|
33
37
|
}
|
|
34
38
|
|
|
35
|
-
/**
|
|
36
|
-
|
|
39
|
+
/**
|
|
40
|
+
* Resolve the client behind a `client_id`.
|
|
41
|
+
*
|
|
42
|
+
* A URL-formatted identifier is a Client ID Metadata Document (MCP 2026-07-28 /
|
|
43
|
+
* SEP-991) and is fetched from its own origin; anything else is looked up as a
|
|
44
|
+
* client registered through `/oauth/register` (RFC 7591).
|
|
45
|
+
*
|
|
46
|
+
* @param clientId - The raw `client_id` from the authorization request.
|
|
47
|
+
* @returns The client, or a reason it could not be resolved. The reason is safe
|
|
48
|
+
* to render on the authorization page.
|
|
49
|
+
*/
|
|
50
|
+
async function resolveClient(
|
|
51
|
+
clientId: string,
|
|
52
|
+
): Promise<{ client: OAuthClient } | { error: string }> {
|
|
53
|
+
if (isClientIdMetadataDocumentUrl(clientId)) {
|
|
54
|
+
return resolveClientIdMetadataDocument(clientId);
|
|
55
|
+
}
|
|
56
|
+
const raw = await api.redis.redis.get(clientKey(clientId));
|
|
57
|
+
if (!raw) return { error: "Unknown client" };
|
|
58
|
+
return { client: JSON.parse(raw) as OAuthClient };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Render the OAuth authorize page (GET).
|
|
63
|
+
*
|
|
64
|
+
* The client is resolved here purely so the page can name who is asking for
|
|
65
|
+
* access. Resolution failures are not surfaced: the form still renders and the
|
|
66
|
+
* POST below is what actually enforces the client and its redirect URIs, so an
|
|
67
|
+
* unresolvable `client_id` can never yield an authorization code.
|
|
68
|
+
*
|
|
69
|
+
* @param url - The full authorize URL, carrying the OAuth query parameters.
|
|
70
|
+
* @param templates - Loaded OAuth HTML templates.
|
|
71
|
+
* @returns The rendered authorization page.
|
|
72
|
+
*/
|
|
73
|
+
export async function handleAuthorizeGet(
|
|
37
74
|
url: URL,
|
|
38
75
|
templates: OAuthTemplates,
|
|
39
|
-
): Response {
|
|
76
|
+
): Promise<Response> {
|
|
77
|
+
const clientId = url.searchParams.get("client_id") ?? "";
|
|
78
|
+
const resolved = clientId ? await resolveClient(clientId) : { error: "" };
|
|
79
|
+
|
|
40
80
|
const params: AuthPageParams = {
|
|
41
|
-
clientId
|
|
81
|
+
clientId,
|
|
42
82
|
redirectUri: url.searchParams.get("redirect_uri") ?? "",
|
|
43
83
|
codeChallenge: url.searchParams.get("code_challenge") ?? "",
|
|
44
84
|
codeChallengeMethod: url.searchParams.get("code_challenge_method") ?? "",
|
|
45
85
|
responseType: url.searchParams.get("response_type") ?? "",
|
|
46
86
|
state: url.searchParams.get("state") ?? "",
|
|
47
87
|
error: "",
|
|
88
|
+
clientName: "client" in resolved ? resolved.client.client_name : undefined,
|
|
48
89
|
};
|
|
49
90
|
|
|
50
91
|
return renderAuthPage(params, templates, findAuthActions());
|
|
@@ -137,9 +178,10 @@ export async function handleAuthorizePost(
|
|
|
137
178
|
return renderAuthPage(oauthParams, templates, authActions);
|
|
138
179
|
};
|
|
139
180
|
|
|
140
|
-
const
|
|
141
|
-
if (
|
|
142
|
-
const client =
|
|
181
|
+
const resolved = await resolveClient(oauthParams.clientId);
|
|
182
|
+
if ("error" in resolved) return renderError(resolved.error);
|
|
183
|
+
const { client } = resolved;
|
|
184
|
+
oauthParams.clientName = client.client_name;
|
|
143
185
|
|
|
144
186
|
const uriMatch = client.redirect_uris.some((registered) =>
|
|
145
187
|
redirectUrisMatch(registered, oauthParams.redirectUri),
|
|
@@ -0,0 +1,450 @@
|
|
|
1
|
+
import { promises as dns } from "node:dns";
|
|
2
|
+
import { isIP } from "node:net";
|
|
3
|
+
import { api, logger } from "../../api";
|
|
4
|
+
import { config } from "../../config";
|
|
5
|
+
import { validateRedirectUri } from "../oauth";
|
|
6
|
+
import type { OAuthClient } from "./types";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Client ID Metadata Documents (CIMD) — MCP 2026-07-28 / SEP-991, based on
|
|
10
|
+
* `draft-ietf-oauth-client-id-metadata-document-00`.
|
|
11
|
+
*
|
|
12
|
+
* A client identifies itself with an HTTPS URL instead of a registered
|
|
13
|
+
* `client_id`. The authorization server fetches that URL, validates the JSON
|
|
14
|
+
* document it returns, and treats it as the client's registration for the
|
|
15
|
+
* duration of the flow. Nothing is persisted, so CIMD client IDs are portable
|
|
16
|
+
* across authorization servers and need no Dynamic Client Registration round
|
|
17
|
+
* trip (which the 2026-07-28 revision deprecates).
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/** Redis key for a cached metadata document. */
|
|
21
|
+
const cimdKey = (url: string) => `oauth:cimd:${url}`;
|
|
22
|
+
|
|
23
|
+
/** Floor applied to a `Cache-Control: max-age` before it is used as a TTL. */
|
|
24
|
+
const MIN_CACHE_TTL = 60;
|
|
25
|
+
|
|
26
|
+
/** Upper bound on a `client_id` URL, since it becomes part of a Redis key. */
|
|
27
|
+
const MAX_CLIENT_ID_LENGTH = 2048;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* IPv4 ranges that are never a legitimate CIMD host. Fetching them would turn
|
|
31
|
+
* the authorization server into an SSRF probe for its own private network
|
|
32
|
+
* (Client ID Metadata Document draft §6, "Server Side Request Forgery").
|
|
33
|
+
*/
|
|
34
|
+
const BLOCKED_IPV4_CIDRS: ReadonlyArray<readonly [string, number]> = [
|
|
35
|
+
["0.0.0.0", 8], // "this host on this network"
|
|
36
|
+
["10.0.0.0", 8], // private
|
|
37
|
+
["100.64.0.0", 10], // carrier-grade NAT
|
|
38
|
+
["127.0.0.0", 8], // loopback
|
|
39
|
+
["169.254.0.0", 16], // link-local (cloud metadata services)
|
|
40
|
+
["172.16.0.0", 12], // private
|
|
41
|
+
["192.0.0.0", 24], // IETF protocol assignments
|
|
42
|
+
["192.0.2.0", 24], // documentation
|
|
43
|
+
["192.88.99.0", 24], // 6to4 relay anycast
|
|
44
|
+
["192.168.0.0", 16], // private
|
|
45
|
+
["198.18.0.0", 15], // benchmarking
|
|
46
|
+
["198.51.100.0", 24], // documentation
|
|
47
|
+
["203.0.113.0", 24], // documentation
|
|
48
|
+
["224.0.0.0", 4], // multicast
|
|
49
|
+
["240.0.0.0", 4], // reserved + broadcast
|
|
50
|
+
];
|
|
51
|
+
|
|
52
|
+
/** Parse a dotted-quad IPv4 address into a 32-bit unsigned integer. */
|
|
53
|
+
function ipv4ToInt(ip: string): number | null {
|
|
54
|
+
const octets = ip.split(".");
|
|
55
|
+
if (octets.length !== 4) return null;
|
|
56
|
+
let value = 0;
|
|
57
|
+
for (const octet of octets) {
|
|
58
|
+
if (!/^\d{1,3}$/.test(octet)) return null;
|
|
59
|
+
const byte = Number(octet);
|
|
60
|
+
if (byte > 255) return null;
|
|
61
|
+
value = value * 256 + byte;
|
|
62
|
+
}
|
|
63
|
+
return value;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function isBlockedIpv4Int(value: number): boolean {
|
|
67
|
+
for (const [network, prefix] of BLOCKED_IPV4_CIDRS) {
|
|
68
|
+
const base = ipv4ToInt(network);
|
|
69
|
+
if (base === null) continue;
|
|
70
|
+
// `>>> 0` keeps the mask unsigned; a /0 would shift by 32 (a no-op in JS),
|
|
71
|
+
// but no entry above uses one.
|
|
72
|
+
const mask = (0xffffffff << (32 - prefix)) >>> 0;
|
|
73
|
+
if ((value & mask) >>> 0 === (base & mask) >>> 0) return true;
|
|
74
|
+
}
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Expand an IPv6 literal into its 16 bytes. Handles `::` compression, an
|
|
80
|
+
* embedded IPv4 tail (`::ffff:127.0.0.1`), and a trailing zone id.
|
|
81
|
+
*
|
|
82
|
+
* @param ip - The IPv6 literal, without surrounding brackets.
|
|
83
|
+
* @returns The 16 address bytes, or `null` if the literal is unparseable.
|
|
84
|
+
*/
|
|
85
|
+
function ipv6Bytes(ip: string): Uint8Array | null {
|
|
86
|
+
let text = ip.split("%")[0] ?? "";
|
|
87
|
+
|
|
88
|
+
// Rewrite an embedded IPv4 tail as two hex groups so the rest of the parse
|
|
89
|
+
// only has to deal with 16-bit groups.
|
|
90
|
+
if (text.includes(".")) {
|
|
91
|
+
const colon = text.lastIndexOf(":");
|
|
92
|
+
if (colon === -1) return null;
|
|
93
|
+
const v4 = text.slice(colon + 1);
|
|
94
|
+
if (isIP(v4) !== 4) return null;
|
|
95
|
+
const octets = v4.split(".").map(Number);
|
|
96
|
+
const high = ((octets[0] as number) << 8) | (octets[1] as number);
|
|
97
|
+
const low = ((octets[2] as number) << 8) | (octets[3] as number);
|
|
98
|
+
text = `${text.slice(0, colon + 1)}${high.toString(16)}:${low.toString(16)}`;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const halves = text.split("::");
|
|
102
|
+
if (halves.length > 2) return null;
|
|
103
|
+
const compressed = halves.length === 2;
|
|
104
|
+
const left = halves[0] ? (halves[0] as string).split(":") : [];
|
|
105
|
+
const right = halves[1] ? (halves[1] as string).split(":") : [];
|
|
106
|
+
const missing = 8 - left.length - right.length;
|
|
107
|
+
if (compressed ? missing < 0 : missing !== 0) return null;
|
|
108
|
+
|
|
109
|
+
const groups = [
|
|
110
|
+
...left,
|
|
111
|
+
...new Array<string>(compressed ? missing : 0).fill("0"),
|
|
112
|
+
...right,
|
|
113
|
+
];
|
|
114
|
+
if (groups.length !== 8) return null;
|
|
115
|
+
|
|
116
|
+
const bytes = new Uint8Array(16);
|
|
117
|
+
for (let i = 0; i < 8; i++) {
|
|
118
|
+
const group = groups[i] as string;
|
|
119
|
+
if (!/^[0-9a-fA-F]{1,4}$/.test(group)) return null;
|
|
120
|
+
const value = Number.parseInt(group, 16);
|
|
121
|
+
bytes[i * 2] = value >> 8;
|
|
122
|
+
bytes[i * 2 + 1] = value & 0xff;
|
|
123
|
+
}
|
|
124
|
+
return bytes;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function isBlockedIpv6(bytes: Uint8Array): boolean {
|
|
128
|
+
const v4Mapped =
|
|
129
|
+
bytes.slice(0, 10).every((byte) => byte === 0) &&
|
|
130
|
+
bytes[10] === 0xff &&
|
|
131
|
+
bytes[11] === 0xff;
|
|
132
|
+
const nat64 =
|
|
133
|
+
bytes[0] === 0x00 &&
|
|
134
|
+
bytes[1] === 0x64 &&
|
|
135
|
+
bytes[2] === 0xff &&
|
|
136
|
+
bytes[3] === 0x9b;
|
|
137
|
+
if (v4Mapped || nat64) {
|
|
138
|
+
const embedded =
|
|
139
|
+
((bytes[12] as number) << 24) |
|
|
140
|
+
((bytes[13] as number) << 16) |
|
|
141
|
+
((bytes[14] as number) << 8) |
|
|
142
|
+
(bytes[15] as number);
|
|
143
|
+
return isBlockedIpv4Int(embedded >>> 0);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
if (bytes.every((byte) => byte === 0)) return true; // ::
|
|
147
|
+
if (bytes.slice(0, 15).every((byte) => byte === 0) && bytes[15] === 1) {
|
|
148
|
+
return true; // ::1 loopback
|
|
149
|
+
}
|
|
150
|
+
if (((bytes[0] as number) & 0xfe) === 0xfc) return true; // fc00::/7 unique-local
|
|
151
|
+
if (bytes[0] === 0xfe && ((bytes[1] as number) & 0xc0) === 0x80) {
|
|
152
|
+
return true; // fe80::/10 link-local
|
|
153
|
+
}
|
|
154
|
+
if (bytes[0] === 0xff) return true; // ff00::/8 multicast
|
|
155
|
+
// 2001::/32 Teredo — tunnels to arbitrary IPv4 destinations, including private ones.
|
|
156
|
+
if (
|
|
157
|
+
bytes[0] === 0x20 &&
|
|
158
|
+
bytes[1] === 0x01 &&
|
|
159
|
+
bytes[2] === 0x00 &&
|
|
160
|
+
bytes[3] === 0x00
|
|
161
|
+
) {
|
|
162
|
+
return true;
|
|
163
|
+
}
|
|
164
|
+
return false;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** True when a literal IP address (v4 or v6) must not be fetched. */
|
|
168
|
+
function isBlockedAddress(address: string): boolean {
|
|
169
|
+
const family = isIP(address);
|
|
170
|
+
if (family === 4) {
|
|
171
|
+
const value = ipv4ToInt(address);
|
|
172
|
+
return value === null ? true : isBlockedIpv4Int(value);
|
|
173
|
+
}
|
|
174
|
+
if (family === 6) {
|
|
175
|
+
const bytes = ipv6Bytes(address);
|
|
176
|
+
return bytes === null ? true : isBlockedIpv6(bytes);
|
|
177
|
+
}
|
|
178
|
+
return true;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Resolve a hostname and confirm every address it maps to is publicly routable.
|
|
183
|
+
*
|
|
184
|
+
* A DNS name that resolves to a private address (a "DNS rebinding" style SSRF)
|
|
185
|
+
* is rejected here, before any request is made. Note that this is a
|
|
186
|
+
* check-then-fetch: a name whose records change between this lookup and the
|
|
187
|
+
* fetch below could still land on a private address. Deployments that need a
|
|
188
|
+
* hard guarantee should egress-filter the process rather than rely on this
|
|
189
|
+
* check alone.
|
|
190
|
+
*
|
|
191
|
+
* @param hostname - Hostname from the `client_id` URL. IPv6 literals may arrive
|
|
192
|
+
* bracketed (as `URL.hostname` reports them) and are unwrapped here.
|
|
193
|
+
* @returns `true` when the host is safe to fetch.
|
|
194
|
+
*/
|
|
195
|
+
async function isPubliclyRoutableHost(hostname: string): Promise<boolean> {
|
|
196
|
+
const host = hostname.startsWith("[") ? hostname.slice(1, -1) : hostname;
|
|
197
|
+
|
|
198
|
+
if (isIP(host) !== 0) return !isBlockedAddress(host);
|
|
199
|
+
|
|
200
|
+
let addresses: string[];
|
|
201
|
+
try {
|
|
202
|
+
const records = await dns.lookup(host, { all: true, verbatim: true });
|
|
203
|
+
addresses = records.map((record) => record.address);
|
|
204
|
+
} catch {
|
|
205
|
+
return false;
|
|
206
|
+
}
|
|
207
|
+
if (addresses.length === 0) return false;
|
|
208
|
+
return addresses.every((address) => !isBlockedAddress(address));
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* True when a `client_id` should be resolved as a Client ID Metadata Document
|
|
213
|
+
* rather than looked up as a registered client.
|
|
214
|
+
*
|
|
215
|
+
* Per the CIMD draft the identifier MUST be an `https:` URL with a path
|
|
216
|
+
* component (e.g. `https://app.example.com/client.json`) and MUST NOT carry a
|
|
217
|
+
* fragment. `http:` is additionally recognised when
|
|
218
|
+
* `config.server.mcp.oauthCimdAllowPrivateHosts` is on, so a metadata document
|
|
219
|
+
* served from `localhost` can be exercised in development.
|
|
220
|
+
*
|
|
221
|
+
* @param clientId - The raw `client_id` from the authorization request.
|
|
222
|
+
* @returns `true` when {@link resolveClientIdMetadataDocument} should handle it.
|
|
223
|
+
*/
|
|
224
|
+
export function isClientIdMetadataDocumentUrl(clientId: string): boolean {
|
|
225
|
+
// The identifier ends up in a Redis cache key, so cap it rather than letting
|
|
226
|
+
// a caller choose the key length. Real metadata URLs are far shorter.
|
|
227
|
+
if (clientId.length > MAX_CLIENT_ID_LENGTH) return false;
|
|
228
|
+
|
|
229
|
+
let url: URL;
|
|
230
|
+
try {
|
|
231
|
+
url = new URL(clientId);
|
|
232
|
+
} catch {
|
|
233
|
+
return false;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const httpAllowed = config.server.mcp.oauthCimdAllowPrivateHosts;
|
|
237
|
+
if (url.protocol !== "https:" && !(httpAllowed && url.protocol === "http:")) {
|
|
238
|
+
return false;
|
|
239
|
+
}
|
|
240
|
+
if (url.hash) return false;
|
|
241
|
+
if (url.pathname === "" || url.pathname === "/") return false;
|
|
242
|
+
return true;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Validate a fetched metadata document and project it onto the framework's
|
|
247
|
+
* client shape.
|
|
248
|
+
*
|
|
249
|
+
* @param clientId - The `client_id` URL the document was fetched from.
|
|
250
|
+
* @param document - The parsed JSON body.
|
|
251
|
+
* @returns The client, or the reason the document was rejected.
|
|
252
|
+
*/
|
|
253
|
+
function validateDocument(
|
|
254
|
+
clientId: string,
|
|
255
|
+
document: unknown,
|
|
256
|
+
): { client: OAuthClient } | { error: string } {
|
|
257
|
+
if (
|
|
258
|
+
typeof document !== "object" ||
|
|
259
|
+
document === null ||
|
|
260
|
+
Array.isArray(document)
|
|
261
|
+
) {
|
|
262
|
+
return { error: "Client metadata document is not a JSON object" };
|
|
263
|
+
}
|
|
264
|
+
const doc = document as Record<string, unknown>;
|
|
265
|
+
|
|
266
|
+
// The draft requires an exact match so a document cannot claim an identity it
|
|
267
|
+
// is not served from.
|
|
268
|
+
if (doc.client_id !== clientId) {
|
|
269
|
+
return { error: "Client metadata client_id does not match its URL" };
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
if (typeof doc.client_name !== "string" || doc.client_name.trim() === "") {
|
|
273
|
+
return { error: "Client metadata document is missing client_name" };
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
if (!Array.isArray(doc.redirect_uris) || doc.redirect_uris.length === 0) {
|
|
277
|
+
return { error: "Client metadata document is missing redirect_uris" };
|
|
278
|
+
}
|
|
279
|
+
for (const uri of doc.redirect_uris) {
|
|
280
|
+
if (typeof uri !== "string") {
|
|
281
|
+
return { error: "Client metadata redirect_uris must be strings" };
|
|
282
|
+
}
|
|
283
|
+
const validation = validateRedirectUri(uri);
|
|
284
|
+
if (!validation.valid) {
|
|
285
|
+
// `error` is always populated when `valid` is false; see oauth.ts
|
|
286
|
+
return { error: validation.error as string };
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
if (
|
|
291
|
+
Array.isArray(doc.grant_types) &&
|
|
292
|
+
!doc.grant_types.includes("authorization_code")
|
|
293
|
+
) {
|
|
294
|
+
return {
|
|
295
|
+
error: "Client metadata does not allow the authorization_code grant",
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
if (
|
|
299
|
+
Array.isArray(doc.response_types) &&
|
|
300
|
+
!doc.response_types.includes("code")
|
|
301
|
+
) {
|
|
302
|
+
return { error: "Client metadata does not allow the code response type" };
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
return {
|
|
306
|
+
client: {
|
|
307
|
+
client_id: clientId,
|
|
308
|
+
redirect_uris: doc.redirect_uris as string[],
|
|
309
|
+
client_name: doc.client_name,
|
|
310
|
+
grant_types: (doc.grant_types as string[]) ?? ["authorization_code"],
|
|
311
|
+
response_types: (doc.response_types as string[]) ?? ["code"],
|
|
312
|
+
token_endpoint_auth_method:
|
|
313
|
+
typeof doc.token_endpoint_auth_method === "string"
|
|
314
|
+
? doc.token_endpoint_auth_method
|
|
315
|
+
: "none",
|
|
316
|
+
},
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** Read a response body, aborting once it exceeds `maxBytes`. */
|
|
321
|
+
async function readCapped(
|
|
322
|
+
res: Response,
|
|
323
|
+
maxBytes: number,
|
|
324
|
+
): Promise<string | null> {
|
|
325
|
+
const declared = Number(res.headers.get("content-length"));
|
|
326
|
+
if (Number.isFinite(declared) && declared > maxBytes) return null;
|
|
327
|
+
|
|
328
|
+
const reader = res.body?.getReader();
|
|
329
|
+
if (!reader) return null;
|
|
330
|
+
|
|
331
|
+
const chunks: Uint8Array[] = [];
|
|
332
|
+
let total = 0;
|
|
333
|
+
while (true) {
|
|
334
|
+
const { done, value } = await reader.read();
|
|
335
|
+
if (done) break;
|
|
336
|
+
if (!value) continue;
|
|
337
|
+
total += value.byteLength;
|
|
338
|
+
if (total > maxBytes) {
|
|
339
|
+
await reader.cancel();
|
|
340
|
+
return null;
|
|
341
|
+
}
|
|
342
|
+
chunks.push(value);
|
|
343
|
+
}
|
|
344
|
+
return new TextDecoder().decode(Buffer.concat(chunks));
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* Derive a cache TTL (seconds) from the document's HTTP cache headers, or
|
|
349
|
+
* `null` when the response asks not to be stored.
|
|
350
|
+
*/
|
|
351
|
+
function cacheTtlFromHeaders(res: Response): number | null {
|
|
352
|
+
const ceiling = config.server.mcp.oauthCimdCacheTtl;
|
|
353
|
+
const cacheControl = (res.headers.get("cache-control") ?? "").toLowerCase();
|
|
354
|
+
if (cacheControl.includes("no-store") || cacheControl.includes("no-cache")) {
|
|
355
|
+
return null;
|
|
356
|
+
}
|
|
357
|
+
const maxAge = /max-age\s*=\s*(\d+)/.exec(cacheControl)?.[1];
|
|
358
|
+
if (maxAge === undefined) return ceiling;
|
|
359
|
+
const seconds = Number(maxAge);
|
|
360
|
+
if (seconds <= 0) return null;
|
|
361
|
+
return Math.min(Math.max(seconds, MIN_CACHE_TTL), ceiling);
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/**
|
|
365
|
+
* Resolve a URL-formatted `client_id` into a client by fetching and validating
|
|
366
|
+
* its Client ID Metadata Document.
|
|
367
|
+
*
|
|
368
|
+
* Successful lookups are cached in Redis so a browser round trip through
|
|
369
|
+
* `/oauth/authorize` (GET then POST) does not refetch the document, honouring
|
|
370
|
+
* the origin's `Cache-Control` up to `config.server.mcp.oauthCimdCacheTtl`.
|
|
371
|
+
* Failures are never cached.
|
|
372
|
+
*
|
|
373
|
+
* @param clientId - An HTTPS `client_id` URL, as accepted by
|
|
374
|
+
* {@link isClientIdMetadataDocumentUrl}.
|
|
375
|
+
* @returns The resolved client, or a human-readable reason it was rejected. The
|
|
376
|
+
* reason is safe to render on the authorization page.
|
|
377
|
+
*/
|
|
378
|
+
export async function resolveClientIdMetadataDocument(
|
|
379
|
+
clientId: string,
|
|
380
|
+
): Promise<{ client: OAuthClient } | { error: string }> {
|
|
381
|
+
if (!config.server.mcp.oauthCimdEnabled) {
|
|
382
|
+
return { error: "Client ID Metadata Documents are not supported" };
|
|
383
|
+
}
|
|
384
|
+
if (!isClientIdMetadataDocumentUrl(clientId)) {
|
|
385
|
+
return { error: "Invalid client_id URL" };
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
const cached = await api.redis.redis.get(cimdKey(clientId));
|
|
389
|
+
if (cached) return { client: JSON.parse(cached) as OAuthClient };
|
|
390
|
+
|
|
391
|
+
const url = new URL(clientId);
|
|
392
|
+
if (!config.server.mcp.oauthCimdAllowPrivateHosts) {
|
|
393
|
+
if (!(await isPubliclyRoutableHost(url.hostname))) {
|
|
394
|
+
return { error: "Client metadata host is not publicly routable" };
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
let res: Response;
|
|
399
|
+
try {
|
|
400
|
+
res = await fetch(url, {
|
|
401
|
+
method: "GET",
|
|
402
|
+
headers: { Accept: "application/json" },
|
|
403
|
+
// Do not follow redirects: a redirect could hop to a private address that
|
|
404
|
+
// the pre-flight host check above never saw.
|
|
405
|
+
redirect: "manual",
|
|
406
|
+
signal: AbortSignal.timeout(config.server.mcp.oauthCimdFetchTimeoutMs),
|
|
407
|
+
});
|
|
408
|
+
} catch (error) {
|
|
409
|
+
logger.debug(`CIMD fetch failed for ${clientId}: ${error}`);
|
|
410
|
+
return { error: "Could not fetch the client metadata document" };
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
if (res.status !== 200) {
|
|
414
|
+
await res.body?.cancel();
|
|
415
|
+
return {
|
|
416
|
+
error: `Client metadata document returned HTTP ${res.status}`,
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
const contentType = res.headers.get("content-type") ?? "";
|
|
421
|
+
if (!contentType.toLowerCase().includes("json")) {
|
|
422
|
+
await res.body?.cancel();
|
|
423
|
+
return { error: "Client metadata document is not served as JSON" };
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
const text = await readCapped(res, config.server.mcp.oauthCimdMaxBytes);
|
|
427
|
+
if (text === null) return { error: "Client metadata document is too large" };
|
|
428
|
+
|
|
429
|
+
let parsed: unknown;
|
|
430
|
+
try {
|
|
431
|
+
parsed = JSON.parse(text);
|
|
432
|
+
} catch {
|
|
433
|
+
return { error: "Client metadata document is not valid JSON" };
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
const result = validateDocument(clientId, parsed);
|
|
437
|
+
if ("error" in result) return result;
|
|
438
|
+
|
|
439
|
+
const ttl = cacheTtlFromHeaders(res);
|
|
440
|
+
if (ttl !== null) {
|
|
441
|
+
await api.redis.redis.set(
|
|
442
|
+
cimdKey(clientId),
|
|
443
|
+
JSON.stringify(result.client),
|
|
444
|
+
"EX",
|
|
445
|
+
ttl,
|
|
446
|
+
);
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
return result;
|
|
450
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { config } from "../../config";
|
|
1
2
|
import { jsonResponse } from "./responses";
|
|
2
3
|
import { OAUTH_PATHS } from "./types";
|
|
3
4
|
|
|
@@ -36,6 +37,10 @@ export function handleMetadata(origin: string): Response {
|
|
|
36
37
|
token_endpoint_auth_methods_supported: ["none"],
|
|
37
38
|
introspection_endpoint_auth_methods_supported: ["none"],
|
|
38
39
|
revocation_endpoint_auth_methods_supported: ["none"],
|
|
39
|
-
|
|
40
|
+
// Client ID Metadata Documents (MCP 2026-07-28 / SEP-991). Clients SHOULD
|
|
41
|
+
// prefer this over the now-deprecated Dynamic Client Registration, so
|
|
42
|
+
// advertise it whenever the resolver is enabled.
|
|
43
|
+
client_id_metadata_document_supported:
|
|
44
|
+
config.server.mcp.oauthCimdEnabled === true,
|
|
40
45
|
});
|
|
41
46
|
}
|
package/util/oauthTemplates.ts
CHANGED
|
@@ -161,8 +161,64 @@ export type AuthPageParams = {
|
|
|
161
161
|
responseType: string;
|
|
162
162
|
state: string;
|
|
163
163
|
error: string;
|
|
164
|
+
/**
|
|
165
|
+
* Display name of the requesting client, when it could be resolved. Shown on
|
|
166
|
+
* the consent form so the user can tell who is asking — required when the
|
|
167
|
+
* client identified itself with a Client ID Metadata Document, since such a
|
|
168
|
+
* client is self-asserted rather than pre-registered.
|
|
169
|
+
*/
|
|
170
|
+
clientName?: string;
|
|
164
171
|
};
|
|
165
172
|
|
|
173
|
+
/** Loopback hosts that warrant an extra warning on the consent form. */
|
|
174
|
+
const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Render the "who is asking" block above the sign-in form.
|
|
178
|
+
*
|
|
179
|
+
* The redirect URI's hostname is always shown: it is where the authorization
|
|
180
|
+
* code will be delivered, and is the only part of the request a user can
|
|
181
|
+
* meaningfully judge. Loopback redirects get an explicit warning because a
|
|
182
|
+
* Client ID Metadata Document cannot prove that a `localhost` callback belongs
|
|
183
|
+
* to the app it names (MCP 2026-07-28 authorization security considerations,
|
|
184
|
+
* "Localhost Redirect URI Risks").
|
|
185
|
+
*
|
|
186
|
+
* @param params - The OAuth parameters for the page.
|
|
187
|
+
* @returns An HTML fragment, or `""` when there is nothing meaningful to show.
|
|
188
|
+
*/
|
|
189
|
+
function renderClientInfoHtml(params: AuthPageParams): string {
|
|
190
|
+
let host = "";
|
|
191
|
+
try {
|
|
192
|
+
const redirect = new URL(params.redirectUri);
|
|
193
|
+
// A private-use scheme (e.g. `com.example.app:/callback`) has no host, so
|
|
194
|
+
// fall back to the scheme — it is still the identifying part of the target.
|
|
195
|
+
host = redirect.host || redirect.protocol;
|
|
196
|
+
} catch {
|
|
197
|
+
host = "";
|
|
198
|
+
}
|
|
199
|
+
if (!params.clientName && !host) return "";
|
|
200
|
+
|
|
201
|
+
const rows: string[] = [];
|
|
202
|
+
if (params.clientName) {
|
|
203
|
+
rows.push(
|
|
204
|
+
`<p><strong>${escapeHtml(params.clientName)}</strong> is requesting access to your account.</p>`,
|
|
205
|
+
);
|
|
206
|
+
}
|
|
207
|
+
if (host) {
|
|
208
|
+
rows.push(
|
|
209
|
+
`<p class="client-detail">Redirects to <strong>${escapeHtml(host)}</strong></p>`,
|
|
210
|
+
);
|
|
211
|
+
const hostname = host.split(":")[0] ?? "";
|
|
212
|
+
if (LOOPBACK_HOSTS.has(hostname) || LOOPBACK_HOSTS.has(host)) {
|
|
213
|
+
rows.push(
|
|
214
|
+
`<p class="client-warning">This will send your authorization to an application running on this machine. Continue only if you started this sign-in yourself.</p>`,
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
return `<div class="client-info">${rows.join("")}</div>`;
|
|
220
|
+
}
|
|
221
|
+
|
|
166
222
|
/**
|
|
167
223
|
* Render the OAuth authorization page with dynamic form fields.
|
|
168
224
|
* @param params - OAuth parameters for the page (client ID, redirect URI, error, etc.).
|
|
@@ -199,6 +255,7 @@ export function renderAuthPage(
|
|
|
199
255
|
templates.authTemplate,
|
|
200
256
|
{
|
|
201
257
|
errorHtml,
|
|
258
|
+
clientInfoHtml: renderClientInfoHtml(params),
|
|
202
259
|
hiddenFields,
|
|
203
260
|
hasSignin,
|
|
204
261
|
hasSignup,
|