keryx 0.40.1 → 0.41.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.
@@ -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
@@ -1,6 +1,6 @@
1
1
  import fs from "node:fs";
2
2
  import { unlink } from "node:fs/promises";
3
- import { $ } from "bun";
3
+ import { $, Glob } from "bun";
4
4
  import { type Config as DrizzleMigrateConfig } from "drizzle-kit";
5
5
  import { DefaultLogger, type LogWriter, sql } from "drizzle-orm";
6
6
  import { drizzle } from "drizzle-orm/node-postgres";
@@ -18,6 +18,29 @@ import {
18
18
 
19
19
  const namespace = "db";
20
20
 
21
+ const SCHEMA_DIR = "schema";
22
+
23
+ /**
24
+ * Check whether the project has any drizzle schema files to generate migrations from.
25
+ * A freshly-scaffolded project (or one whose last schema file was deleted) has an
26
+ * empty `schema/` directory, which `drizzle-kit generate` treats as a fatal error.
27
+ *
28
+ * @param schemaDir - Absolute path to the project's `schema/` directory. A missing
29
+ * directory counts as empty rather than an error.
30
+ * @returns `true` when at least one non-dotfile `.ts`/`.tsx`/`.js` file exists in the tree.
31
+ */
32
+ async function hasSchemaFiles(schemaDir: string) {
33
+ if (!fs.existsSync(schemaDir)) return false;
34
+
35
+ const glob = new Glob("**/*.{ts,tsx,js,mjs,cjs}");
36
+ for await (const file of glob.scan(schemaDir)) {
37
+ if (path.basename(file).startsWith(".")) continue;
38
+ return true;
39
+ }
40
+
41
+ return false;
42
+ }
43
+
21
44
  declare module "keryx" {
22
45
  export interface API {
23
46
  [namespace]: Awaited<ReturnType<DB["initialize"]>>;
@@ -107,32 +130,52 @@ export class DB extends Initializer {
107
130
  /**
108
131
  * Generate migrations for the database schema.
109
132
  * Learn more @ https://orm.drizzle.team/kit-docs/overview
133
+ *
134
+ * An empty `schema/` directory is a legitimate state for a new project, so this
135
+ * is a no-op (rather than an error) when there is nothing to generate from.
136
+ *
137
+ * @throws {TypedError} With `ErrorType.SERVER_INITIALIZATION` if `drizzle-kit generate` fails.
110
138
  */
111
139
  async generateMigrations() {
140
+ const schemaDir = path.join(api.rootDir, SCHEMA_DIR);
141
+ const migrationsDir = path.join(api.rootDir, "drizzle");
142
+
143
+ if (!(await hasSchemaFiles(schemaDir))) {
144
+ logger.info(
145
+ `no schema files found in ${SCHEMA_DIR}/ - nothing to generate`,
146
+ );
147
+ return;
148
+ }
149
+
150
+ // Paths stay relative — drizzle-kit concatenates `out` onto "./" when reading
151
+ // existing snapshots, so an absolute path breaks on any non-empty migrations
152
+ // folder. The child process is run with cwd set to the project root instead.
112
153
  const migrationConfig: DrizzleMigrateConfig = {
113
154
  dialect: "postgresql" as const,
114
- schema: path.join("schema", "*"),
155
+ schema: path.join(SCHEMA_DIR, "*"),
115
156
  dbCredentials: {
116
157
  url: config.database.connectionString,
117
158
  },
118
- out: path.join("drizzle"),
159
+ out: "drizzle",
119
160
  };
120
161
 
121
162
  const fileContent = `export default ${JSON.stringify(migrationConfig, null, 2)}`;
122
- const tmpfilePath = path.join(api.rootDir, "drizzle", "config.tmp.ts");
163
+ const tmpfilePath = path.join(migrationsDir, "config.tmp.ts");
123
164
 
124
165
  try {
125
166
  await Bun.write(tmpfilePath, fileContent);
167
+ // .nothrow() so a failing drizzle-kit surfaces as a TypedError with its
168
+ // stderr, rather than a bare ShellError from the tagged template.
126
169
  const { exitCode, stdout, stderr } =
127
- await $`bun drizzle-kit generate --config ${tmpfilePath}`;
170
+ await $`bun drizzle-kit generate --config ${tmpfilePath}`
171
+ .cwd(api.rootDir)
172
+ .nothrow();
128
173
  logger.trace(stdout.toString());
129
174
  if (exitCode !== 0) {
130
- {
131
- throw new TypedError({
132
- message: `Failed to generate migrations: ${stderr.toString()}`,
133
- type: ErrorType.SERVER_INITIALIZATION,
134
- });
135
- }
175
+ throw new TypedError({
176
+ message: `Failed to generate migrations: ${stderr.toString()}`,
177
+ type: ErrorType.SERVER_INITIALIZATION,
178
+ });
136
179
  }
137
180
  } finally {
138
181
  const filePointer = Bun.file(tmpfilePath);
@@ -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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keryx",
3
- "version": "0.40.1",
3
+ "version": "0.41.1",
4
4
  "module": "index.ts",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -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;
@@ -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
- /** Render the OAuth authorize page (GET). */
36
- export function handleAuthorizeGet(
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: url.searchParams.get("client_id") ?? "",
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 clientRaw = await api.redis.redis.get(clientKey(oauthParams.clientId));
141
- if (!clientRaw) return renderError("Unknown client");
142
- const client = JSON.parse(clientRaw) as OAuthClient;
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,4 +1,8 @@
1
1
  export { handleAuthorizeGet, handleAuthorizePost } from "./authorize";
2
+ export {
3
+ isClientIdMetadataDocumentUrl,
4
+ resolveClientIdMetadataDocument,
5
+ } from "./cimd";
2
6
  export { handleIntrospect } from "./introspect";
3
7
  export {
4
8
  handleMetadata,
@@ -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
- client_id_metadata_document_supported: false,
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
  }
@@ -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,