@selvajs/selva 4.21.0-beta.6 → 4.21.0-beta.7

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.
Files changed (45) hide show
  1. package/build/adapter-node.js +1 -1
  2. package/build/client/_app/immutable/entry/{app.DblLep9O.js → app.Cmuegtgc.js} +2 -2
  3. package/build/client/_app/immutable/entry/app.Cmuegtgc.js.br +0 -0
  4. package/build/client/_app/immutable/entry/app.Cmuegtgc.js.gz +0 -0
  5. package/build/client/_app/immutable/nodes/24.DkL5kHzA.js +3 -0
  6. package/build/client/_app/immutable/nodes/24.DkL5kHzA.js.br +0 -0
  7. package/build/client/_app/immutable/nodes/24.DkL5kHzA.js.gz +0 -0
  8. package/build/client/_app/version.json +1 -1
  9. package/build/client/_app/version.json.br +0 -0
  10. package/build/client/_app/version.json.gz +0 -0
  11. package/build/server/.vite/manifest.json +4 -7
  12. package/build/server/chunks/handlers.js +20 -16
  13. package/build/server/chunks/handlers.js.map +1 -1
  14. package/build/server/chunks/instance.js +3 -3
  15. package/build/server/chunks/internal.js +1 -1
  16. package/build/server/chunks/oauth.js +70 -24
  17. package/build/server/chunks/oauth.js.map +1 -1
  18. package/build/server/chunks/package.js +1 -1
  19. package/build/server/chunks/package.js.map +1 -1
  20. package/build/server/chunks/server2.js +2 -2
  21. package/build/server/chunks/server2.js.map +1 -1
  22. package/build/server/entries/endpoints/.well-known/oauth-authorization-server/_server.ts.js +6 -3
  23. package/build/server/entries/endpoints/.well-known/oauth-authorization-server/_server.ts.js.map +1 -1
  24. package/build/server/entries/endpoints/.well-known/oauth-protected-resource/_server.ts.js +6 -3
  25. package/build/server/entries/endpoints/.well-known/oauth-protected-resource/_server.ts.js.map +1 -1
  26. package/build/server/entries/endpoints/.well-known/oauth-protected-resource/mcp/_server.ts.js +6 -3
  27. package/build/server/entries/endpoints/.well-known/oauth-protected-resource/mcp/_server.ts.js.map +1 -1
  28. package/build/server/entries/endpoints/mcp/_server.ts.js +5 -4
  29. package/build/server/entries/endpoints/mcp/_server.ts.js.map +1 -1
  30. package/build/server/entries/endpoints/oauth/register/_server.ts.js +1 -1
  31. package/build/server/entries/endpoints/oauth/token/_server.ts.js +1 -1
  32. package/build/server/entries/pages/oauth/authorize/_page.server.ts.js +3 -2
  33. package/build/server/entries/pages/oauth/authorize/_page.server.ts.js.map +1 -1
  34. package/build/server/entries/pages/oauth/authorize/_page.svelte.js +8 -1
  35. package/build/server/entries/pages/oauth/authorize/_page.svelte.js.map +1 -1
  36. package/build/server/manifest-full.js +1 -1
  37. package/build/server/manifest.js +1 -1
  38. package/build/server/nodes/24.js +1 -1
  39. package/build/server/server.js +1 -1
  40. package/package.json +7 -7
  41. package/build/client/_app/immutable/entry/app.DblLep9O.js.br +0 -0
  42. package/build/client/_app/immutable/entry/app.DblLep9O.js.gz +0 -0
  43. package/build/client/_app/immutable/nodes/24.CPSunfJJ.js +0 -3
  44. package/build/client/_app/immutable/nodes/24.CPSunfJJ.js.br +0 -0
  45. package/build/client/_app/immutable/nodes/24.CPSunfJJ.js.gz +0 -0
@@ -213,7 +213,7 @@ function server_data_serializer(event, state) {
213
213
  let promise_id = 1;
214
214
  let max_nodes = -1;
215
215
  const iterator = create_async_iterator();
216
- const global = "__sveltekit_singpo";
216
+ const global = "__sveltekit_3oxlh6";
217
217
  /** @param {number} index */
218
218
  function get_replacer(index) {
219
219
  /** @param {any} thing */
@@ -1443,7 +1443,7 @@ async function render_response({ branch, fetched, page_config, status, error = n
1443
1443
  "crossorigin"
1444
1444
  ]);
1445
1445
  }
1446
- const global = "__sveltekit_singpo";
1446
+ const global = "__sveltekit_3oxlh6";
1447
1447
  const { data, chunks } = data_serializer.get_data(csp);
1448
1448
  if (page_config.ssr && page_config.csr) body += `\n\t\t\t${fetched.map((item) => serialize_data(item, resolve_opts.filterSerializedResponseHeaders, !!(state.prerendering || state.prerender_default === true))).join("\n ")}`;
1449
1449
  if (page_config.csr && client) {
@@ -1467,7 +1467,7 @@ async function render_response({ branch, fetched, page_config, status, error = n
1467
1467
  }
1468
1468
  }
1469
1469
  const blocks = [];
1470
- const properties = [`base: ${base_expression}`, `version: ${s("1794225011502")}`];
1470
+ const properties = [`base: ${base_expression}`, `version: ${s("1794234143315")}`];
1471
1471
  if (assets) properties.push(`assets: ${s(assets)}`);
1472
1472
  if (client.uses_env_dynamic_public) properties.push(`env: ${load_env_eagerly ? "null" : uneval$1(rendered_env)}`);
1473
1473
  if (chunks) {
@@ -2363,7 +2363,7 @@ function redirect_response(status, location) {
2363
2363
  * @param {Response} response
2364
2364
  */
2365
2365
  function with_version_header(response) {
2366
- response.headers.set("x-sveltekit-version", "1794225011502");
2366
+ response.headers.set("x-sveltekit-version", "1794234143315");
2367
2367
  return response;
2368
2368
  }
2369
2369
  /**
@@ -19,15 +19,24 @@ import { createCipheriv, createDecipheriv, createHash, createHmac, hkdfSync, ran
19
19
  var OAUTH_SCOPES = [
20
20
  "read",
21
21
  "solve",
22
+ "write",
22
23
  "upload",
23
24
  "create_projects"
24
25
  ];
25
26
  /**
26
- * All a registered (DCR or CIMD) client can be granted. Its name and redirects
27
+ * All a host may hand registered (DCR or CIMD) clients. Their name and redirects
27
28
  * are whatever the registrant chose, so `upload`, which puts code on the org's
28
- * Compute server, and `create_projects` stay with the built-in client and a
29
- * look-alike can't phish for them.
29
+ * Compute server, and `create_projects` aren't here. `write` is, but `write:all`
30
+ * covers both at `/api/v1` and can delete projects and definitions, so it is
31
+ * off by default. An allowlist: a new scope reaches registered clients only
32
+ * once it is added here.
30
33
  */
34
+ var REGISTERABLE_SCOPES = [
35
+ "read",
36
+ "solve",
37
+ "write"
38
+ ];
39
+ /** The default `registeredClientScopes`. */
31
40
  var REGISTERED_CLIENT_SCOPES = ["read", "solve"];
32
41
  var GRASSHOPPER_CLIENT = {
33
42
  clientId: "selva-grasshopper",
@@ -74,20 +83,26 @@ function mcpResourceUrl(origin) {
74
83
  function resourceMetadataUrl(origin) {
75
84
  return `${origin}/.well-known/oauth-protected-resource${MCP_PATH}`;
76
85
  }
77
- /** RFC 9728. Claude uses only the first authorization server. */
78
- function protectedResourceMetadata(origin) {
86
+ /**
87
+ * RFC 9728. Claude uses only the first authorization server. `scopes` is what a
88
+ * registered client may be granted; prefer the server's own method, which
89
+ * passes its `registeredClientScopes`.
90
+ */
91
+ function protectedResourceMetadata(origin, scopes = REGISTERED_CLIENT_SCOPES) {
79
92
  return {
80
93
  resource: mcpResourceUrl(origin),
81
94
  authorization_servers: [origin],
82
- scopes_supported: [...REGISTERED_CLIENT_SCOPES],
95
+ scopes_supported: [...scopes],
83
96
  bearer_methods_supported: ["header"]
84
97
  };
85
98
  }
86
99
  /**
87
100
  * RFC 8414. Claude picks Client ID Metadata Documents only when both
88
101
  * `client_id_metadata_document_supported` and the `none` auth method appear.
102
+ * Advertises only scopes some client can be granted: a client that asks for one
103
+ * it can never get re-authorizes in a loop. Prefer the server's own method.
89
104
  */
90
- function authorizationServerMetadata(origin) {
105
+ function authorizationServerMetadata(origin, registeredScopes = REGISTERED_CLIENT_SCOPES) {
91
106
  return {
92
107
  issuer: origin,
93
108
  authorization_endpoint: `${origin}/oauth/authorize`,
@@ -97,11 +112,21 @@ function authorizationServerMetadata(origin) {
97
112
  grant_types_supported: ["authorization_code"],
98
113
  code_challenge_methods_supported: ["S256"],
99
114
  token_endpoint_auth_methods_supported: ["none"],
100
- scopes_supported: [...OAUTH_SCOPES],
115
+ scopes_supported: OAUTH_SCOPES.filter((s) => GRASSHOPPER_CLIENT.scopes.includes(s) || registeredScopes.includes(s)),
101
116
  client_id_metadata_document_supported: true,
102
117
  authorization_response_iss_parameter_supported: true
103
118
  };
104
119
  }
120
+ /**
121
+ * The host's list, checked: a JS host or a cast gets past the type, and a list
122
+ * without `read` would leave every consent page empty with a message blaming
123
+ * the user's account.
124
+ */
125
+ function checkRegisteredScopes(scopes) {
126
+ for (const s of scopes) if (!REGISTERABLE_SCOPES.includes(s)) throw new TypeError(`registeredClientScopes: "${s}" can't be granted to a registered client.`);
127
+ if (!scopes.includes("read")) throw new TypeError("registeredClientScopes must include \"read\".");
128
+ return REGISTERABLE_SCOPES.filter((s) => scopes.includes(s));
129
+ }
105
130
  function createOAuthServer(options) {
106
131
  const { origin } = options;
107
132
  const now = options.now ?? Date.now;
@@ -111,6 +136,7 @@ function createOAuthServer(options) {
111
136
  const previousSignKey = previous ? derive(previous, "selva-oauth-client") : void 0;
112
137
  const previousCodeKey = previous ? derive(previous, `selva-oauth-code:${origin}`) : void 0;
113
138
  const redeemed = options.redeemedCodes ?? /* @__PURE__ */ new Map();
139
+ const registeredScopes = checkRegisteredScopes(options.registeredClientScopes ?? REGISTERED_CLIENT_SCOPES);
114
140
  const metadataCache = /* @__PURE__ */ new Map();
115
141
  /** RFC 7591. The client id carries the metadata, signed, so nothing is stored. */
116
142
  function register(input) {
@@ -159,7 +185,7 @@ function createOAuthServer(options) {
159
185
  name: meta.n || "An MCP client",
160
186
  redirectUris: meta.r,
161
187
  builtIn: false,
162
- scopes: REGISTERED_CLIENT_SCOPES
188
+ scopes: registeredScopes
163
189
  };
164
190
  }
165
191
  async function metadataClient(url) {
@@ -170,7 +196,7 @@ function createOAuthServer(options) {
170
196
  }
171
197
  if (!options.fetchClientMetadata) throw new OAuthError("invalid_client", "This server does not accept URL client ids.");
172
198
  try {
173
- const client = await readMetadata(url, options.fetchClientMetadata);
199
+ const client = await readMetadata(url, options.fetchClientMetadata, registeredScopes);
174
200
  remember(url, {
175
201
  at: now(),
176
202
  client
@@ -284,15 +310,17 @@ function createOAuthServer(options) {
284
310
  approve,
285
311
  deny,
286
312
  exchange,
287
- protectedResourceMetadata: () => protectedResourceMetadata(origin),
288
- authorizationServerMetadata: () => authorizationServerMetadata(origin)
313
+ /** All a registered client can be granted: the MCP 401 challenge's scopes. */
314
+ registeredScopes,
315
+ protectedResourceMetadata: () => protectedResourceMetadata(origin, registeredScopes),
316
+ authorizationServerMetadata: () => authorizationServerMetadata(origin, registeredScopes)
289
317
  };
290
318
  }
291
319
  /** OAuth scopes to the API scopes a minted token gets. */
292
320
  function apiScopesFor(scopes) {
293
321
  return scopes.map((s) => `${s}:all`);
294
322
  }
295
- async function readMetadata(url, fetchClientMetadata) {
323
+ async function readMetadata(url, fetchClientMetadata, scopes) {
296
324
  let doc;
297
325
  try {
298
326
  doc = await fetchClientMetadata(url);
@@ -305,7 +333,7 @@ async function readMetadata(url, fetchClientMetadata) {
305
333
  name: typeof doc.client_name === "string" && doc.client_name.trim() ? doc.client_name.trim().slice(0, CLIENT_NAME_MAX) : new URL(url).host,
306
334
  redirectUris: checkRedirectUris(doc.redirect_uris),
307
335
  builtIn: false,
308
- scopes: REGISTERED_CLIENT_SCOPES
336
+ scopes
309
337
  };
310
338
  }
311
339
  /**
@@ -313,34 +341,52 @@ async function readMetadata(url, fetchClientMetadata) {
313
341
  * that is dropped, not refused, so a client that asks for every advertised
314
342
  * scope still signs in with what it may have. No `scope` at all means all of
315
343
  * them. Asking only for scopes it may not have gets `read`, never more than it
316
- * asked for. `read` rides along with `solve`, which the consent page offers as
317
- * "read and run solves".
344
+ * asked for. `read` rides along with `solve` and `write`, which the consent
345
+ * page offers as "read and run solves" and "read and change".
318
346
  */
319
347
  function parseScopes(raw, allowed) {
320
348
  const requested = (raw ?? "").split(" ").filter(Boolean);
321
349
  if (!requested.length) return [...allowed];
322
350
  const asked = requested.filter((s) => allowed.includes(s));
323
351
  if (!asked.length) return allowed.includes("read") ? ["read"] : [];
324
- return allowed.filter((s) => asked.includes(s) || s === "read" && asked.includes("solve"));
352
+ const impliesRead = asked.includes("solve") || asked.includes("write");
353
+ return allowed.filter((s) => asked.includes(s) || s === "read" && impliesRead);
325
354
  }
326
355
  /**
327
- * The access levels a consent page offers for a request, narrowest first. The
328
- * user may narrow what the client asked for, never widen it. An upload request
329
- * is offered as asked: narrowing it to read would leave the client unable to
330
- * do the one thing it signed in for.
356
+ * The access levels a consent page offers for a request: `read` first, all it
357
+ * asked for last. The user may narrow what the client asked for, never widen
358
+ * it. `write` is offered with and without `solve`, so change access needn't
359
+ * spend compute budget, and a host policy that allows one can still grant it.
360
+ * An upload request is offered as asked: narrowing it to read would leave the
361
+ * client unable to do the one thing it signed in for.
331
362
  */
332
363
  function consentChoices(scopes) {
364
+ if (!scopes.length) return [];
333
365
  if (scopes.includes("upload")) return [{
334
366
  access: "upload",
335
367
  scopes: [...scopes]
336
368
  }];
369
+ const solve = scopes.includes("solve");
370
+ const write = scopes.includes("write");
337
371
  const choices = [{
338
372
  access: "read",
339
373
  scopes: ["read"]
340
374
  }];
341
- if (scopes.includes("solve")) choices.push({
375
+ if (solve) choices.push({
342
376
  access: "solve",
343
- scopes: [...scopes]
377
+ scopes: ["read", "solve"]
378
+ });
379
+ if (write) choices.push({
380
+ access: "write",
381
+ scopes: ["read", "write"]
382
+ });
383
+ if (solve && write) choices.push({
384
+ access: "write_and_solve",
385
+ scopes: [
386
+ "read",
387
+ "solve",
388
+ "write"
389
+ ]
344
390
  });
345
391
  return choices;
346
392
  }
@@ -422,6 +468,6 @@ function safeEqual(a, b) {
422
468
  const y = Buffer.from(b);
423
469
  return x.length === y.length && timingSafeEqual(x, y);
424
470
  }
425
- export { authorizationServerMetadata as a, isLoopbackRedirect as c, apiScopesFor as i, protectedResourceMetadata as l, OAuthError as n, consentChoices as o, REGISTERED_CLIENT_SCOPES as r, createOAuthServer as s, CODE_TTL_MS as t, resourceMetadataUrl as u };
471
+ export { createOAuthServer as a, consentChoices as i, OAuthError as n, isLoopbackRedirect as o, apiScopesFor as r, resourceMetadataUrl as s, CODE_TTL_MS as t };
426
472
 
427
473
  //# sourceMappingURL=oauth.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"oauth.js","names":["sign"],"sources":["../../../../server/src/oauth/index.ts"],"sourcesContent":["/**\n * OAuth 2.1 for MCP clients and the Grasshopper plugin, with this instance as\n * its own authorization server.\n *\n * The access token is an ordinary API token. The host mints it while the user is\n * signed in, at consent, through the same path as Team → API tokens; this\n * module seals the raw key into the authorization code and hands it over at the\n * token endpoint. So `/mcp` and `/api/v1` keep one credential type.\n *\n * Nothing here is stored. A registered client's id is its own signed metadata,\n * and a code is its own encrypted grant, bound to the issuing origin. The only\n * state is the set of redeemed codes, in the host's memory, so on several\n * replicas a code could be redeemed once per replica within its minute, and only\n * by whoever holds the PKCE verifier.\n */\n\nimport {\n\tcreateCipheriv,\n\tcreateDecipheriv,\n\tcreateHash,\n\tcreateHmac,\n\thkdfSync,\n\trandomBytes,\n\ttimingSafeEqual\n} from 'node:crypto';\n\n/** The scopes a grant can carry. Each maps to one org-wide API scope. */\nexport const OAUTH_SCOPES = ['read', 'solve', 'upload', 'create_projects'] as const;\nexport type OAuthScope = (typeof OAUTH_SCOPES)[number];\n\n/**\n * All a registered (DCR or CIMD) client can be granted. Its name and redirects\n * are whatever the registrant chose, so `upload`, which puts code on the org's\n * Compute server, and `create_projects` stay with the built-in client and a\n * look-alike can't phish for them.\n */\nexport const REGISTERED_CLIENT_SCOPES = ['read', 'solve'] as const satisfies readonly OAuthScope[];\n\n/** The Grasshopper plugin's client id. Built in, so it needs no registration and works air-gapped. */\nexport const GRASSHOPPER_CLIENT_ID = 'selva-grasshopper';\n\n// Loopback on any port (RFC 8252 §7.3), but only this host and path: the code\n// can only ever reach a program on the user's own machine.\nconst GRASSHOPPER_CLIENT: OAuthClient = {\n\tclientId: GRASSHOPPER_CLIENT_ID,\n\tname: 'Selva for Grasshopper',\n\tredirectUris: ['http://127.0.0.1/callback'],\n\tbuiltIn: true,\n\tscopes: ['read', 'upload', 'create_projects']\n};\n\nexport const MCP_PATH = '/mcp';\n\nexport const CODE_TTL_MS = 60_000;\nconst CLIENT_NAME_MAX = 100;\nconst REDIRECT_URIS_MAX = 10;\nconst CIMD_TTL_MS = 60 * 60_000;\n// A failing metadata URL is not refetched for this long: each fetch is outbound\n// work an anonymous caller could otherwise trigger at will.\nconst CIMD_FAILURE_TTL_MS = 60_000;\nconst CIMD_CACHE_MAX = 500;\nconst LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);\n\nexport class OAuthError extends Error {\n\tconstructor(\n\t\t/** RFC 6749 / 7591 error code. */\n\t\treadonly error: string,\n\t\tdescription: string,\n\t\treadonly status = 400\n\t) {\n\t\tsuper(description);\n\t\tthis.name = 'OAuthError';\n\t}\n\n\ttoBody(): { error: string; error_description: string } {\n\t\treturn { error: this.error, error_description: this.message };\n\t}\n}\n\nexport interface OAuthClient {\n\tclientId: string;\n\t/** Shown on the consent page. Unverified for a registered client: whatever it claimed. */\n\tname: string;\n\tredirectUris: string[];\n\t/** Shipped with this server, so its name can be trusted. */\n\tbuiltIn: boolean;\n\t/** All this client can be granted, whatever it asks for. */\n\tscopes: readonly OAuthScope[];\n}\n\n/** A validated `/oauth/authorize` request, ready for the consent page. */\nexport interface AuthorizeRequest {\n\tclient: OAuthClient;\n\tredirectUri: string;\n\tstate?: string;\n\tcodeChallenge: string;\n\tscopes: OAuthScope[];\n\tresource: string;\n}\n\n/** What the host minted at consent. `secret` is the raw API key. */\nexport interface Grant {\n\ttokenId: string;\n\tsecret: string;\n\tscopes: OAuthScope[];\n\texpiresAt: string;\n}\n\nexport interface OAuthServerOptions {\n\t/** This instance's origin, e.g. `https://selva.example.com`. */\n\torigin: string;\n\t/** `SELVA_HMAC_KEY`. Signs client ids and seals codes. */\n\tsecret: string;\n\t/** The key before the last rotation: client ids and codes it made still verify. */\n\tpreviousSecret?: string;\n\t/**\n\t * Fetches a Client ID Metadata Document. The URL comes from an unknown client,\n\t * so the host must guard it against SSRF. Without it, URL client ids are refused.\n\t */\n\tfetchClientMetadata?: (url: string) => Promise<unknown>;\n\t/**\n\t * Redeemed code hashes and their expiry. Pass one map for the process so a\n\t * rebuilt server (a new origin, a rotated secret) still refuses a replay.\n\t */\n\tredeemedCodes?: Map<string, number>;\n\t/** Called once a code is exchanged, with the token its grant carries. */\n\tonRedeemed?: (tokenId: string) => void;\n\tnow?: () => number;\n}\n\ninterface HttpResult {\n\tstatus: number;\n\tbody: Record<string, unknown>;\n}\n\n// ============================================================================\n// Discovery documents\n// ============================================================================\n\nexport function mcpResourceUrl(origin: string): string {\n\treturn origin + MCP_PATH;\n}\n\nexport function resourceMetadataUrl(origin: string): string {\n\treturn `${origin}/.well-known/oauth-protected-resource${MCP_PATH}`;\n}\n\n/** RFC 9728. Claude uses only the first authorization server. */\nexport function protectedResourceMetadata(origin: string) {\n\treturn {\n\t\tresource: mcpResourceUrl(origin),\n\t\tauthorization_servers: [origin],\n\t\tscopes_supported: [...REGISTERED_CLIENT_SCOPES],\n\t\tbearer_methods_supported: ['header']\n\t};\n}\n\n/**\n * RFC 8414. Claude picks Client ID Metadata Documents only when both\n * `client_id_metadata_document_supported` and the `none` auth method appear.\n */\nexport function authorizationServerMetadata(origin: string) {\n\treturn {\n\t\tissuer: origin,\n\t\tauthorization_endpoint: `${origin}/oauth/authorize`,\n\t\ttoken_endpoint: `${origin}/oauth/token`,\n\t\tregistration_endpoint: `${origin}/oauth/register`,\n\t\tresponse_types_supported: ['code'],\n\t\tgrant_types_supported: ['authorization_code'],\n\t\tcode_challenge_methods_supported: ['S256'],\n\t\ttoken_endpoint_auth_methods_supported: ['none'],\n\t\tscopes_supported: [...OAUTH_SCOPES],\n\t\tclient_id_metadata_document_supported: true,\n\t\tauthorization_response_iss_parameter_supported: true\n\t};\n}\n\n// ============================================================================\n// Server\n// ============================================================================\n\nexport function createOAuthServer(options: OAuthServerOptions) {\n\tconst { origin } = options;\n\tconst now = options.now ?? Date.now;\n\tconst signKey = derive(options.secret, 'selva-oauth-client');\n\tconst codeKey = derive(options.secret, `selva-oauth-code:${origin}`);\n\tconst previous = options.previousSecret;\n\tconst previousSignKey = previous ? derive(previous, 'selva-oauth-client') : undefined;\n\tconst previousCodeKey = previous ? derive(previous, `selva-oauth-code:${origin}`) : undefined;\n\tconst redeemed = options.redeemedCodes ?? new Map<string, number>();\n\tconst metadataCache = new Map<\n\t\tstring,\n\t\t{ at: number; client: OAuthClient } | { at: number; failure: OAuthError }\n\t>();\n\n\t// ==========================================================================\n\t// Clients\n\t// ==========================================================================\n\n\t/** RFC 7591. The client id carries the metadata, signed, so nothing is stored. */\n\tfunction register(input: unknown): HttpResult {\n\t\ttry {\n\t\t\tconst meta = (input ?? {}) as { client_name?: unknown; redirect_uris?: unknown };\n\t\t\tconst redirectUris = checkRedirectUris(meta.redirect_uris);\n\t\t\tconst name = typeof meta.client_name === 'string' ? meta.client_name.trim() : '';\n\t\t\tconst payload = b64(\n\t\t\t\tJSON.stringify({ n: name.slice(0, CLIENT_NAME_MAX), r: redirectUris, t: now() })\n\t\t\t);\n\t\t\tconst clientId = `dcr_${payload}.${sign(signKey, payload)}`;\n\t\t\treturn {\n\t\t\t\tstatus: 201,\n\t\t\t\tbody: {\n\t\t\t\t\tclient_id: clientId,\n\t\t\t\t\tclient_id_issued_at: Math.floor(now() / 1000),\n\t\t\t\t\tclient_name: name || undefined,\n\t\t\t\t\tredirect_uris: redirectUris,\n\t\t\t\t\tgrant_types: ['authorization_code'],\n\t\t\t\t\tresponse_types: ['code'],\n\t\t\t\t\ttoken_endpoint_auth_method: 'none'\n\t\t\t\t}\n\t\t\t};\n\t\t} catch (err) {\n\t\t\tif (err instanceof OAuthError) return { status: err.status, body: err.toBody() };\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tasync function resolveClient(clientId: string): Promise<OAuthClient> {\n\t\tif (clientId === GRASSHOPPER_CLIENT_ID) return GRASSHOPPER_CLIENT;\n\t\tif (clientId.startsWith('dcr_')) return registeredClient(clientId);\n\t\tif (clientId.startsWith('https://')) return metadataClient(clientId);\n\t\tthrow new OAuthError('invalid_client', 'Unknown client.');\n\t}\n\n\tfunction registeredClient(clientId: string): OAuthClient {\n\t\tconst [payload, signature] = clientId.slice('dcr_'.length).split('.');\n\t\tconst signedBy = (key: Buffer | undefined) =>\n\t\t\tkey !== undefined && safeEqual(signature, sign(key, payload));\n\t\tif (!payload || !signature || !(signedBy(signKey) || signedBy(previousSignKey))) {\n\t\t\tthrow new OAuthError('invalid_client', 'Unknown client.');\n\t\t}\n\t\tconst meta = JSON.parse(unb64(payload)) as { n: string; r: string[] };\n\t\treturn {\n\t\t\tclientId,\n\t\t\tname: meta.n || 'An MCP client',\n\t\t\tredirectUris: meta.r,\n\t\t\tbuiltIn: false,\n\t\t\tscopes: REGISTERED_CLIENT_SCOPES\n\t\t};\n\t}\n\n\tasync function metadataClient(url: string): Promise<OAuthClient> {\n\t\tconst cached = metadataCache.get(url);\n\t\tif (cached) {\n\t\t\tif ('client' in cached && now() - cached.at < CIMD_TTL_MS) return cached.client;\n\t\t\tif ('failure' in cached && now() - cached.at < CIMD_FAILURE_TTL_MS) throw cached.failure;\n\t\t}\n\t\tif (!options.fetchClientMetadata) {\n\t\t\tthrow new OAuthError('invalid_client', 'This server does not accept URL client ids.');\n\t\t}\n\t\ttry {\n\t\t\tconst client = await readMetadata(url, options.fetchClientMetadata);\n\t\t\tremember(url, { at: now(), client });\n\t\t\treturn client;\n\t\t} catch (err) {\n\t\t\tif (!(err instanceof OAuthError)) throw err;\n\t\t\tremember(url, { at: now(), failure: err });\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tfunction remember(url: string, entry: Parameters<typeof metadataCache.set>[1]) {\n\t\tif (metadataCache.size >= CIMD_CACHE_MAX) {\n\t\t\tmetadataCache.delete(metadataCache.keys().next().value!);\n\t\t}\n\t\tmetadataCache.set(url, entry);\n\t}\n\n\t// ==========================================================================\n\t// Authorization\n\t// ==========================================================================\n\n\t/**\n\t * Validates the query `/oauth/authorize` arrives with. An `OAuthError` from a\n\t * bad client or redirect URI must be shown, not redirected: the redirect target\n\t * is exactly what can't be trusted.\n\t */\n\tasync function parseAuthorizeRequest(query: URLSearchParams): Promise<AuthorizeRequest> {\n\t\tconst client = await resolveClient(query.get('client_id') ?? '');\n\t\tconst redirectUri = query.get('redirect_uri') ?? '';\n\t\tif (!client.redirectUris.some((r) => redirectMatches(r, redirectUri))) {\n\t\t\tthrow new OAuthError(\n\t\t\t\t'invalid_request',\n\t\t\t\t'The redirect URI is not registered for this client.'\n\t\t\t);\n\t\t}\n\t\tif (query.get('response_type') !== 'code') {\n\t\t\tthrow new OAuthError('unsupported_response_type', 'Only response_type=code is supported.');\n\t\t}\n\t\tconst codeChallenge = query.get('code_challenge') ?? '';\n\t\tif (!codeChallenge || query.get('code_challenge_method') !== 'S256') {\n\t\t\tthrow new OAuthError('invalid_request', 'PKCE with code_challenge_method=S256 is required.');\n\t\t}\n\t\tconst resource = query.get('resource') ?? mcpResourceUrl(origin);\n\t\tif (!isThisResource(resource)) {\n\t\t\tthrow new OAuthError('invalid_target', 'The resource is not this server.');\n\t\t}\n\t\treturn {\n\t\t\tclient,\n\t\t\tredirectUri,\n\t\t\tstate: query.get('state') ?? undefined,\n\t\t\tcodeChallenge,\n\t\t\tscopes: parseScopes(query.get('scope'), client.scopes),\n\t\t\tresource\n\t\t};\n\t}\n\n\t/** Where to send the browser after consent: the client's redirect URI with a code. */\n\tfunction approve(request: AuthorizeRequest, grant: Grant): string {\n\t\tconst code = seal(codeKey, {\n\t\t\tc: request.client.clientId,\n\t\t\tr: request.redirectUri,\n\t\t\tp: request.codeChallenge,\n\t\t\tx: now() + CODE_TTL_MS,\n\t\t\tg: grant\n\t\t});\n\t\treturn withParams(request.redirectUri, { code, state: request.state, iss: origin });\n\t}\n\n\tfunction deny(request: AuthorizeRequest): string {\n\t\treturn withParams(request.redirectUri, {\n\t\t\terror: 'access_denied',\n\t\t\tstate: request.state,\n\t\t\tiss: origin\n\t\t});\n\t}\n\n\t// ==========================================================================\n\t// Token endpoint\n\t// ==========================================================================\n\n\tfunction exchange(form: URLSearchParams): HttpResult {\n\t\ttry {\n\t\t\tif (form.get('grant_type') !== 'authorization_code') {\n\t\t\t\tthrow new OAuthError('unsupported_grant_type', 'Only authorization_code is supported.');\n\t\t\t}\n\t\t\tconst code = form.get('code') ?? '';\n\t\t\tconst sealed = (open(codeKey, code) ??\n\t\t\t\t(previousCodeKey ? open(previousCodeKey, code) : null)) as {\n\t\t\t\tc: string;\n\t\t\t\tr: string;\n\t\t\t\tp: string;\n\t\t\t\tx: number;\n\t\t\t\tg: Grant;\n\t\t\t} | null;\n\t\t\tif (!sealed || sealed.x < now()) {\n\t\t\t\tthrow new OAuthError('invalid_grant', 'The code is invalid or expired.');\n\t\t\t}\n\t\t\tif (sealed.c !== form.get('client_id') || sealed.r !== form.get('redirect_uri')) {\n\t\t\t\tthrow new OAuthError('invalid_grant', 'The code was issued to another client.');\n\t\t\t}\n\t\t\tconst verifier = form.get('code_verifier') ?? '';\n\t\t\tif (!safeEqual(createHash('sha256').update(verifier).digest('base64url'), sealed.p)) {\n\t\t\t\tthrow new OAuthError('invalid_grant', 'The code_verifier does not match.');\n\t\t\t}\n\t\t\tconst resource = form.get('resource');\n\t\t\tif (resource !== null && !isThisResource(resource)) {\n\t\t\t\tthrow new OAuthError('invalid_target', 'The resource is not this server.');\n\t\t\t}\n\t\t\tif (!markRedeemed(code, sealed.x)) {\n\t\t\t\tthrow new OAuthError('invalid_grant', 'The code was already used.');\n\t\t\t}\n\t\t\tconst { g } = sealed;\n\t\t\toptions.onRedeemed?.(g.tokenId);\n\t\t\treturn {\n\t\t\t\tstatus: 200,\n\t\t\t\tbody: {\n\t\t\t\t\taccess_token: g.secret,\n\t\t\t\t\ttoken_type: 'Bearer',\n\t\t\t\t\texpires_in: Math.max(0, Math.floor((Date.parse(g.expiresAt) - now()) / 1000)),\n\t\t\t\t\tscope: g.scopes.join(' ')\n\t\t\t\t}\n\t\t\t};\n\t\t} catch (err) {\n\t\t\tif (err instanceof OAuthError) return { status: err.status, body: err.toBody() };\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tfunction markRedeemed(code: string, expiresAt: number): boolean {\n\t\tconst t = now();\n\t\tfor (const [k, x] of redeemed) if (x < t) redeemed.delete(k);\n\t\tconst id = createHash('sha256').update(code).digest('base64url');\n\t\tif (redeemed.has(id)) return false;\n\t\tredeemed.set(id, expiresAt);\n\t\treturn true;\n\t}\n\n\tfunction isThisResource(resource: string): boolean {\n\t\tconst r = resource.replace(/\\/$/, '');\n\t\treturn r === origin || r === mcpResourceUrl(origin);\n\t}\n\n\treturn {\n\t\tregister,\n\t\tresolveClient,\n\t\tparseAuthorizeRequest,\n\t\tapprove,\n\t\tdeny,\n\t\texchange,\n\t\tprotectedResourceMetadata: () => protectedResourceMetadata(origin),\n\t\tauthorizationServerMetadata: () => authorizationServerMetadata(origin)\n\t};\n}\n\nexport type OAuthServer = ReturnType<typeof createOAuthServer>;\n\n/** OAuth scopes to the API scopes a minted token gets. */\nexport function apiScopesFor(scopes: readonly OAuthScope[]): string[] {\n\treturn scopes.map((s) => `${s}:all`);\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\nasync function readMetadata(\n\turl: string,\n\tfetchClientMetadata: (url: string) => Promise<unknown>\n): Promise<OAuthClient> {\n\tlet doc: { client_id?: unknown; client_name?: unknown; redirect_uris?: unknown };\n\ttry {\n\t\tdoc = (await fetchClientMetadata(url)) as typeof doc;\n\t} catch {\n\t\tthrow new OAuthError('invalid_client', 'The client metadata document could not be read.');\n\t}\n\tif (doc?.client_id !== url) {\n\t\tthrow new OAuthError('invalid_client', 'The metadata document names a different client_id.');\n\t}\n\treturn {\n\t\tclientId: url,\n\t\tname:\n\t\t\ttypeof doc.client_name === 'string' && doc.client_name.trim()\n\t\t\t\t? doc.client_name.trim().slice(0, CLIENT_NAME_MAX)\n\t\t\t\t: new URL(url).host,\n\t\tredirectUris: checkRedirectUris(doc.redirect_uris),\n\t\tbuiltIn: false,\n\t\tscopes: REGISTERED_CLIENT_SCOPES\n\t};\n}\n\n/**\n * What the request asks for, within what its client may have. A scope outside\n * that is dropped, not refused, so a client that asks for every advertised\n * scope still signs in with what it may have. No `scope` at all means all of\n * them. Asking only for scopes it may not have gets `read`, never more than it\n * asked for. `read` rides along with `solve`, which the consent page offers as\n * \"read and run solves\".\n */\nfunction parseScopes(raw: string | null, allowed: readonly OAuthScope[]): OAuthScope[] {\n\tconst requested = (raw ?? '').split(' ').filter(Boolean);\n\tif (!requested.length) return [...allowed];\n\tconst asked = requested.filter((s): s is OAuthScope =>\n\t\t(allowed as readonly string[]).includes(s)\n\t);\n\tif (!asked.length) return allowed.includes('read') ? ['read'] : [];\n\treturn allowed.filter((s) => asked.includes(s) || (s === 'read' && asked.includes('solve')));\n}\n\n/** One access level a consent page offers, and the scopes approving it grants. */\nexport interface ConsentChoice {\n\taccess: 'read' | 'solve' | 'upload';\n\tscopes: OAuthScope[];\n}\n\n/**\n * The access levels a consent page offers for a request, narrowest first. The\n * user may narrow what the client asked for, never widen it. An upload request\n * is offered as asked: narrowing it to read would leave the client unable to\n * do the one thing it signed in for.\n */\nexport function consentChoices(scopes: readonly OAuthScope[]): ConsentChoice[] {\n\tif (scopes.includes('upload')) return [{ access: 'upload', scopes: [...scopes] }];\n\tconst choices: ConsentChoice[] = [{ access: 'read', scopes: ['read'] }];\n\tif (scopes.includes('solve')) choices.push({ access: 'solve', scopes: [...scopes] });\n\treturn choices;\n}\n\nfunction checkRedirectUris(value: unknown): string[] {\n\tif (!Array.isArray(value) || !value.length || value.length > REDIRECT_URIS_MAX) {\n\t\tthrow new OAuthError('invalid_redirect_uri', 'Give between 1 and 10 redirect_uris.');\n\t}\n\tfor (const uri of value) {\n\t\tif (typeof uri !== 'string' || !isAllowedRedirect(uri)) {\n\t\t\tthrow new OAuthError(\n\t\t\t\t'invalid_redirect_uri',\n\t\t\t\t'Redirect URIs must be https, or http on a loopback address.'\n\t\t\t);\n\t\t}\n\t}\n\treturn value as string[];\n}\n\nfunction isAllowedRedirect(uri: string): boolean {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(uri);\n\t} catch {\n\t\treturn false;\n\t}\n\tif (url.hash) return false;\n\treturn (\n\t\turl.protocol === 'https:' || (url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname))\n\t);\n}\n\n/** A redirect to a program on the user's own machine, which any local process can claim. */\nexport function isLoopbackRedirect(uri: string): boolean {\n\ttry {\n\t\treturn LOOPBACK_HOSTS.has(new URL(uri).hostname);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/** Exact, except a loopback redirect matches on any port (RFC 8252 §7.3). */\nexport function redirectMatches(registered: string, requested: string): boolean {\n\tif (registered === requested) return true;\n\tlet a: URL, b: URL;\n\ttry {\n\t\ta = new URL(registered);\n\t\tb = new URL(requested);\n\t} catch {\n\t\treturn false;\n\t}\n\treturn (\n\t\ta.protocol === 'http:' &&\n\t\tb.protocol === 'http:' &&\n\t\tLOOPBACK_HOSTS.has(a.hostname) &&\n\t\ta.hostname === b.hostname &&\n\t\ta.pathname === b.pathname &&\n\t\ta.search === b.search &&\n\t\t!b.hash &&\n\t\t!b.username &&\n\t\t!b.password\n\t);\n}\n\nfunction withParams(uri: string, params: Record<string, string | undefined>): string {\n\tconst url = new URL(uri);\n\tfor (const [k, v] of Object.entries(params)) if (v !== undefined) url.searchParams.set(k, v);\n\treturn url.toString();\n}\n\nfunction derive(secret: string, info: string): Buffer {\n\treturn Buffer.from(hkdfSync('sha256', secret, '', info, 32));\n}\n\nfunction sign(key: Buffer, data: string): string {\n\treturn createHmac('sha256', key).update(data).digest('base64url');\n}\n\nfunction seal(key: Buffer, value: unknown): string {\n\tconst iv = randomBytes(12);\n\tconst cipher = createCipheriv('aes-256-gcm', key, iv);\n\tconst body = Buffer.concat([cipher.update(JSON.stringify(value)), cipher.final()]);\n\treturn Buffer.concat([iv, cipher.getAuthTag(), body]).toString('base64url');\n}\n\nfunction open(key: Buffer, sealed: string): unknown {\n\ttry {\n\t\tconst raw = Buffer.from(sealed, 'base64url');\n\t\t// Without the length, a short code is checked against however many tag bytes it has.\n\t\tconst decipher = createDecipheriv('aes-256-gcm', key, raw.subarray(0, 12), {\n\t\t\tauthTagLength: 16\n\t\t});\n\t\tdecipher.setAuthTag(raw.subarray(12, 28));\n\t\tconst body = Buffer.concat([decipher.update(raw.subarray(28)), decipher.final()]);\n\t\treturn JSON.parse(body.toString('utf8'));\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction b64(text: string): string {\n\treturn Buffer.from(text).toString('base64url');\n}\n\nfunction unb64(text: string): string {\n\treturn Buffer.from(text, 'base64url').toString('utf8');\n}\n\nfunction safeEqual(a: string, b: string): boolean {\n\tconst x = Buffer.from(a);\n\tconst y = Buffer.from(b);\n\treturn x.length === y.length && timingSafeEqual(x, y);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA2BA,IAAa,eAAe;CAAC;CAAQ;CAAS;CAAU;AAAiB;;;;;;;AASzE,IAAa,2BAA2B,CAAC,QAAQ,OAAO;AAOxD,IAAM,qBAAkC;CACvC,UAAU;CACV,MAAM;CACN,cAAc,CAAC,2BAA2B;CAC1C,SAAS;CACT,QAAQ;EAAC;EAAQ;EAAU;CAAiB;AAC7C;AAEA,IAAa,WAAW;AAExB,IAAa,cAAc;AAC3B,IAAM,kBAAkB;AACxB,IAAM,oBAAoB;AAC1B,IAAM,cAAc;AAGpB,IAAM,sBAAsB;AAC5B,IAAM,iBAAiB;AACvB,IAAM,iCAAiB,IAAI,IAAI;CAAC;CAAa;CAAa;AAAO,CAAC;AAElE,IAAa,aAAb,cAAgC,MAAM;CAG3B;CAEA;CAJV,YAEC,OACA,aACA,SAAkB,KACjB;EACD,MAAM,WAAW;EAJR,KAAA,QAAA;EAEA,KAAA,SAAA;EAGT,KAAK,OAAO;CACb;CAEA,SAAuD;EACtD,OAAO;GAAE,OAAO,KAAK;GAAO,mBAAmB,KAAK;EAAQ;CAC7D;AACD;AA8DA,SAAgB,eAAe,QAAwB;CACtD,OAAO,SAAS;AACjB;AAEA,SAAgB,oBAAoB,QAAwB;CAC3D,OAAO,GAAG,OAAO,uCAAuC;AACzD;;AAGA,SAAgB,0BAA0B,QAAgB;CACzD,OAAO;EACN,UAAU,eAAe,MAAM;EAC/B,uBAAuB,CAAC,MAAM;EAC9B,kBAAkB,CAAC,GAAG,wBAAwB;EAC9C,0BAA0B,CAAC,QA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AAI,OAAO,WAAW;EAAG;CAAI,CAAC,CAAC,CAAC,SAAS,WAAW;AAC3E;AAEA,SAAS,KAAK,KAAa,QAAyB;CACnD,IAAI;EACH,MAAM,MAAM,OAAO,KAAK,QAAQ,WAAW;EAE3C,MAAM,WAAW,iBAAiB,eAAe,KAAK,IAAI,SAAS,GAAG,EAAE,GAAG,EAC1E,eAAe,GAChB,CAAC;EACD,SAAS,WAAW,IAAI,SAAS,IAAI,EAAE,CAAC;EACxC,MAAM,OAAO,OAAO,OAAO,CAAC,SAAS,OAAO,IAAI,SAAS,EAAE,CAAC,GAAG,SAAS,MAAM,CAAC,CAAC;EAChF,OAAO,KAAK,MAAM,KAAK,SAAS,MAAM,CAAC;CACxC,QAAQ;EACP,OAAO;CACR;AACD;AAEA,SAAS,IAAI,MAAsB;CAClC,OAAO,OAAO,KAAK,IAAI,CAAC,CAAC,SAAS,WAAW;AAC9C;AAEA,SAAS,MAAM,MAAsB;CACpC,OAAO,OAAO,KAAK,MAAM,WAAW,CAAC,CAAC,SAAS,MAAM;AACtD;AAEA,SAAS,UAAU,GAAW,GAAoB;CACjD,MAAM,IAAI,OAAO,KAAK,CAAC;CACvB,MAAM,IAAI,OAAO,KAAK,CAAC;CACvB,OAAO,EAAE,WAAW,EAAE,UAAU,gBAAgB,GAAG,CAAC;AACrD"}
1
+ {"version":3,"file":"oauth.js","names":["sign"],"sources":["../../../../server/src/oauth/index.ts"],"sourcesContent":["/**\n * OAuth 2.1 for MCP clients and the Grasshopper plugin, with this instance as\n * its own authorization server.\n *\n * The access token is an ordinary API token. The host mints it while the user is\n * signed in, at consent, through the same path as Team → API tokens; this\n * module seals the raw key into the authorization code and hands it over at the\n * token endpoint. So `/mcp` and `/api/v1` keep one credential type.\n *\n * Nothing here is stored. A registered client's id is its own signed metadata,\n * and a code is its own encrypted grant, bound to the issuing origin. The only\n * state is the set of redeemed codes, in the host's memory, so on several\n * replicas a code could be redeemed once per replica within its minute, and only\n * by whoever holds the PKCE verifier.\n */\n\nimport {\n\tcreateCipheriv,\n\tcreateDecipheriv,\n\tcreateHash,\n\tcreateHmac,\n\thkdfSync,\n\trandomBytes,\n\ttimingSafeEqual\n} from 'node:crypto';\n\n/** The scopes a grant can carry. Each maps to one org-wide API scope. */\nexport const OAUTH_SCOPES = ['read', 'solve', 'write', 'upload', 'create_projects'] as const;\nexport type OAuthScope = (typeof OAUTH_SCOPES)[number];\n\n/**\n * All a host may hand registered (DCR or CIMD) clients. Their name and redirects\n * are whatever the registrant chose, so `upload`, which puts code on the org's\n * Compute server, and `create_projects` aren't here. `write` is, but `write:all`\n * covers both at `/api/v1` and can delete projects and definitions, so it is\n * off by default. An allowlist: a new scope reaches registered clients only\n * once it is added here.\n */\nexport const REGISTERABLE_SCOPES = [\n\t'read',\n\t'solve',\n\t'write'\n] as const satisfies readonly OAuthScope[];\nexport type RegisteredClientScope = (typeof REGISTERABLE_SCOPES)[number];\n\n/** The default `registeredClientScopes`. */\nexport const REGISTERED_CLIENT_SCOPES = [\n\t'read',\n\t'solve'\n] as const satisfies readonly RegisteredClientScope[];\n\n/** The Grasshopper plugin's client id. Built in, so it needs no registration and works air-gapped. */\nexport const GRASSHOPPER_CLIENT_ID = 'selva-grasshopper';\n\n// Loopback on any port (RFC 8252 §7.3), but only this host and path: the code\n// can only ever reach a program on the user's own machine.\nconst GRASSHOPPER_CLIENT: OAuthClient = {\n\tclientId: GRASSHOPPER_CLIENT_ID,\n\tname: 'Selva for Grasshopper',\n\tredirectUris: ['http://127.0.0.1/callback'],\n\tbuiltIn: true,\n\tscopes: ['read', 'upload', 'create_projects']\n};\n\nexport const MCP_PATH = '/mcp';\n\nexport const CODE_TTL_MS = 60_000;\nconst CLIENT_NAME_MAX = 100;\nconst REDIRECT_URIS_MAX = 10;\nconst CIMD_TTL_MS = 60 * 60_000;\n// A failing metadata URL is not refetched for this long: each fetch is outbound\n// work an anonymous caller could otherwise trigger at will.\nconst CIMD_FAILURE_TTL_MS = 60_000;\nconst CIMD_CACHE_MAX = 500;\nconst LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);\n\nexport class OAuthError extends Error {\n\tconstructor(\n\t\t/** RFC 6749 / 7591 error code. */\n\t\treadonly error: string,\n\t\tdescription: string,\n\t\treadonly status = 400\n\t) {\n\t\tsuper(description);\n\t\tthis.name = 'OAuthError';\n\t}\n\n\ttoBody(): { error: string; error_description: string } {\n\t\treturn { error: this.error, error_description: this.message };\n\t}\n}\n\nexport interface OAuthClient {\n\tclientId: string;\n\t/** Shown on the consent page. Unverified for a registered client: whatever it claimed. */\n\tname: string;\n\tredirectUris: string[];\n\t/** Shipped with this server, so its name can be trusted. */\n\tbuiltIn: boolean;\n\t/** All this client can be granted, whatever it asks for. */\n\tscopes: readonly OAuthScope[];\n}\n\n/** A validated `/oauth/authorize` request, ready for the consent page. */\nexport interface AuthorizeRequest {\n\tclient: OAuthClient;\n\tredirectUri: string;\n\tstate?: string;\n\tcodeChallenge: string;\n\tscopes: OAuthScope[];\n\tresource: string;\n}\n\n/** What the host minted at consent. `secret` is the raw API key. */\nexport interface Grant {\n\ttokenId: string;\n\tsecret: string;\n\tscopes: OAuthScope[];\n\texpiresAt: string;\n}\n\nexport interface OAuthServerOptions {\n\t/** This instance's origin, e.g. `https://selva.example.com`. */\n\torigin: string;\n\t/** `SELVA_HMAC_KEY`. Signs client ids and seals codes. */\n\tsecret: string;\n\t/** The key before the last rotation: client ids and codes it made still verify. */\n\tpreviousSecret?: string;\n\t/**\n\t * All a DCR or CIMD client can be granted, from {@link REGISTERABLE_SCOPES}\n\t * and including `read`. Default {@link REGISTERED_CLIENT_SCOPES}. Serve the\n\t * server's discovery documents and pass its `registeredScopes` as the MCP\n\t * 401 challenge's scopes, so clients ask for this same list.\n\t */\n\tregisteredClientScopes?: readonly RegisteredClientScope[];\n\t/**\n\t * Fetches a Client ID Metadata Document. The URL comes from an unknown client,\n\t * so the host must guard it against SSRF. Without it, URL client ids are refused.\n\t */\n\tfetchClientMetadata?: (url: string) => Promise<unknown>;\n\t/**\n\t * Redeemed code hashes and their expiry. Pass one map for the process so a\n\t * rebuilt server (a new origin, a rotated secret) still refuses a replay.\n\t */\n\tredeemedCodes?: Map<string, number>;\n\t/** Called once a code is exchanged, with the token its grant carries. */\n\tonRedeemed?: (tokenId: string) => void;\n\tnow?: () => number;\n}\n\ninterface HttpResult {\n\tstatus: number;\n\tbody: Record<string, unknown>;\n}\n\n// ============================================================================\n// Discovery documents\n// ============================================================================\n\nexport function mcpResourceUrl(origin: string): string {\n\treturn origin + MCP_PATH;\n}\n\nexport function resourceMetadataUrl(origin: string): string {\n\treturn `${origin}/.well-known/oauth-protected-resource${MCP_PATH}`;\n}\n\n/**\n * RFC 9728. Claude uses only the first authorization server. `scopes` is what a\n * registered client may be granted; prefer the server's own method, which\n * passes its `registeredClientScopes`.\n */\nexport function protectedResourceMetadata(\n\torigin: string,\n\tscopes: readonly RegisteredClientScope[] = REGISTERED_CLIENT_SCOPES\n) {\n\treturn {\n\t\tresource: mcpResourceUrl(origin),\n\t\tauthorization_servers: [origin],\n\t\tscopes_supported: [...scopes],\n\t\tbearer_methods_supported: ['header']\n\t};\n}\n\n/**\n * RFC 8414. Claude picks Client ID Metadata Documents only when both\n * `client_id_metadata_document_supported` and the `none` auth method appear.\n * Advertises only scopes some client can be granted: a client that asks for one\n * it can never get re-authorizes in a loop. Prefer the server's own method.\n */\nexport function authorizationServerMetadata(\n\torigin: string,\n\tregisteredScopes: readonly RegisteredClientScope[] = REGISTERED_CLIENT_SCOPES\n) {\n\treturn {\n\t\tissuer: origin,\n\t\tauthorization_endpoint: `${origin}/oauth/authorize`,\n\t\ttoken_endpoint: `${origin}/oauth/token`,\n\t\tregistration_endpoint: `${origin}/oauth/register`,\n\t\tresponse_types_supported: ['code'],\n\t\tgrant_types_supported: ['authorization_code'],\n\t\tcode_challenge_methods_supported: ['S256'],\n\t\ttoken_endpoint_auth_methods_supported: ['none'],\n\t\tscopes_supported: OAUTH_SCOPES.filter(\n\t\t\t(s) =>\n\t\t\t\tGRASSHOPPER_CLIENT.scopes.includes(s) ||\n\t\t\t\t(registeredScopes as readonly OAuthScope[]).includes(s)\n\t\t),\n\t\tclient_id_metadata_document_supported: true,\n\t\tauthorization_response_iss_parameter_supported: true\n\t};\n}\n\n/**\n * The host's list, checked: a JS host or a cast gets past the type, and a list\n * without `read` would leave every consent page empty with a message blaming\n * the user's account.\n */\nfunction checkRegisteredScopes(scopes: readonly string[]): RegisteredClientScope[] {\n\tfor (const s of scopes) {\n\t\tif (!(REGISTERABLE_SCOPES as readonly string[]).includes(s)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`registeredClientScopes: \"${s}\" can't be granted to a registered client.`\n\t\t\t);\n\t\t}\n\t}\n\tif (!scopes.includes('read')) throw new TypeError('registeredClientScopes must include \"read\".');\n\treturn REGISTERABLE_SCOPES.filter((s) => scopes.includes(s));\n}\n\n// ============================================================================\n// Server\n// ============================================================================\n\nexport function createOAuthServer(options: OAuthServerOptions) {\n\tconst { origin } = options;\n\tconst now = options.now ?? Date.now;\n\tconst signKey = derive(options.secret, 'selva-oauth-client');\n\tconst codeKey = derive(options.secret, `selva-oauth-code:${origin}`);\n\tconst previous = options.previousSecret;\n\tconst previousSignKey = previous ? derive(previous, 'selva-oauth-client') : undefined;\n\tconst previousCodeKey = previous ? derive(previous, `selva-oauth-code:${origin}`) : undefined;\n\tconst redeemed = options.redeemedCodes ?? new Map<string, number>();\n\tconst registeredScopes = checkRegisteredScopes(\n\t\toptions.registeredClientScopes ?? REGISTERED_CLIENT_SCOPES\n\t);\n\tconst metadataCache = new Map<\n\t\tstring,\n\t\t{ at: number; client: OAuthClient } | { at: number; failure: OAuthError }\n\t>();\n\n\t// ==========================================================================\n\t// Clients\n\t// ==========================================================================\n\n\t/** RFC 7591. The client id carries the metadata, signed, so nothing is stored. */\n\tfunction register(input: unknown): HttpResult {\n\t\ttry {\n\t\t\tconst meta = (input ?? {}) as { client_name?: unknown; redirect_uris?: unknown };\n\t\t\tconst redirectUris = checkRedirectUris(meta.redirect_uris);\n\t\t\tconst name = typeof meta.client_name === 'string' ? meta.client_name.trim() : '';\n\t\t\tconst payload = b64(\n\t\t\t\tJSON.stringify({ n: name.slice(0, CLIENT_NAME_MAX), r: redirectUris, t: now() })\n\t\t\t);\n\t\t\tconst clientId = `dcr_${payload}.${sign(signKey, payload)}`;\n\t\t\treturn {\n\t\t\t\tstatus: 201,\n\t\t\t\tbody: {\n\t\t\t\t\tclient_id: clientId,\n\t\t\t\t\tclient_id_issued_at: Math.floor(now() / 1000),\n\t\t\t\t\tclient_name: name || undefined,\n\t\t\t\t\tredirect_uris: redirectUris,\n\t\t\t\t\tgrant_types: ['authorization_code'],\n\t\t\t\t\tresponse_types: ['code'],\n\t\t\t\t\ttoken_endpoint_auth_method: 'none'\n\t\t\t\t}\n\t\t\t};\n\t\t} catch (err) {\n\t\t\tif (err instanceof OAuthError) return { status: err.status, body: err.toBody() };\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tasync function resolveClient(clientId: string): Promise<OAuthClient> {\n\t\tif (clientId === GRASSHOPPER_CLIENT_ID) return GRASSHOPPER_CLIENT;\n\t\tif (clientId.startsWith('dcr_')) return registeredClient(clientId);\n\t\tif (clientId.startsWith('https://')) return metadataClient(clientId);\n\t\tthrow new OAuthError('invalid_client', 'Unknown client.');\n\t}\n\n\tfunction registeredClient(clientId: string): OAuthClient {\n\t\tconst [payload, signature] = clientId.slice('dcr_'.length).split('.');\n\t\tconst signedBy = (key: Buffer | undefined) =>\n\t\t\tkey !== undefined && safeEqual(signature, sign(key, payload));\n\t\tif (!payload || !signature || !(signedBy(signKey) || signedBy(previousSignKey))) {\n\t\t\tthrow new OAuthError('invalid_client', 'Unknown client.');\n\t\t}\n\t\tconst meta = JSON.parse(unb64(payload)) as { n: string; r: string[] };\n\t\treturn {\n\t\t\tclientId,\n\t\t\tname: meta.n || 'An MCP client',\n\t\t\tredirectUris: meta.r,\n\t\t\tbuiltIn: false,\n\t\t\tscopes: registeredScopes\n\t\t};\n\t}\n\n\tasync function metadataClient(url: string): Promise<OAuthClient> {\n\t\tconst cached = metadataCache.get(url);\n\t\tif (cached) {\n\t\t\tif ('client' in cached && now() - cached.at < CIMD_TTL_MS) return cached.client;\n\t\t\tif ('failure' in cached && now() - cached.at < CIMD_FAILURE_TTL_MS) throw cached.failure;\n\t\t}\n\t\tif (!options.fetchClientMetadata) {\n\t\t\tthrow new OAuthError('invalid_client', 'This server does not accept URL client ids.');\n\t\t}\n\t\ttry {\n\t\t\tconst client = await readMetadata(url, options.fetchClientMetadata, registeredScopes);\n\t\t\tremember(url, { at: now(), client });\n\t\t\treturn client;\n\t\t} catch (err) {\n\t\t\tif (!(err instanceof OAuthError)) throw err;\n\t\t\tremember(url, { at: now(), failure: err });\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tfunction remember(url: string, entry: Parameters<typeof metadataCache.set>[1]) {\n\t\tif (metadataCache.size >= CIMD_CACHE_MAX) {\n\t\t\tmetadataCache.delete(metadataCache.keys().next().value!);\n\t\t}\n\t\tmetadataCache.set(url, entry);\n\t}\n\n\t// ==========================================================================\n\t// Authorization\n\t// ==========================================================================\n\n\t/**\n\t * Validates the query `/oauth/authorize` arrives with. An `OAuthError` from a\n\t * bad client or redirect URI must be shown, not redirected: the redirect target\n\t * is exactly what can't be trusted.\n\t */\n\tasync function parseAuthorizeRequest(query: URLSearchParams): Promise<AuthorizeRequest> {\n\t\tconst client = await resolveClient(query.get('client_id') ?? '');\n\t\tconst redirectUri = query.get('redirect_uri') ?? '';\n\t\tif (!client.redirectUris.some((r) => redirectMatches(r, redirectUri))) {\n\t\t\tthrow new OAuthError(\n\t\t\t\t'invalid_request',\n\t\t\t\t'The redirect URI is not registered for this client.'\n\t\t\t);\n\t\t}\n\t\tif (query.get('response_type') !== 'code') {\n\t\t\tthrow new OAuthError('unsupported_response_type', 'Only response_type=code is supported.');\n\t\t}\n\t\tconst codeChallenge = query.get('code_challenge') ?? '';\n\t\tif (!codeChallenge || query.get('code_challenge_method') !== 'S256') {\n\t\t\tthrow new OAuthError('invalid_request', 'PKCE with code_challenge_method=S256 is required.');\n\t\t}\n\t\tconst resource = query.get('resource') ?? mcpResourceUrl(origin);\n\t\tif (!isThisResource(resource)) {\n\t\t\tthrow new OAuthError('invalid_target', 'The resource is not this server.');\n\t\t}\n\t\treturn {\n\t\t\tclient,\n\t\t\tredirectUri,\n\t\t\tstate: query.get('state') ?? undefined,\n\t\t\tcodeChallenge,\n\t\t\tscopes: parseScopes(query.get('scope'), client.scopes),\n\t\t\tresource\n\t\t};\n\t}\n\n\t/** Where to send the browser after consent: the client's redirect URI with a code. */\n\tfunction approve(request: AuthorizeRequest, grant: Grant): string {\n\t\tconst code = seal(codeKey, {\n\t\t\tc: request.client.clientId,\n\t\t\tr: request.redirectUri,\n\t\t\tp: request.codeChallenge,\n\t\t\tx: now() + CODE_TTL_MS,\n\t\t\tg: grant\n\t\t});\n\t\treturn withParams(request.redirectUri, { code, state: request.state, iss: origin });\n\t}\n\n\tfunction deny(request: AuthorizeRequest): string {\n\t\treturn withParams(request.redirectUri, {\n\t\t\terror: 'access_denied',\n\t\t\tstate: request.state,\n\t\t\tiss: origin\n\t\t});\n\t}\n\n\t// ==========================================================================\n\t// Token endpoint\n\t// ==========================================================================\n\n\tfunction exchange(form: URLSearchParams): HttpResult {\n\t\ttry {\n\t\t\tif (form.get('grant_type') !== 'authorization_code') {\n\t\t\t\tthrow new OAuthError('unsupported_grant_type', 'Only authorization_code is supported.');\n\t\t\t}\n\t\t\tconst code = form.get('code') ?? '';\n\t\t\tconst sealed = (open(codeKey, code) ??\n\t\t\t\t(previousCodeKey ? open(previousCodeKey, code) : null)) as {\n\t\t\t\tc: string;\n\t\t\t\tr: string;\n\t\t\t\tp: string;\n\t\t\t\tx: number;\n\t\t\t\tg: Grant;\n\t\t\t} | null;\n\t\t\tif (!sealed || sealed.x < now()) {\n\t\t\t\tthrow new OAuthError('invalid_grant', 'The code is invalid or expired.');\n\t\t\t}\n\t\t\tif (sealed.c !== form.get('client_id') || sealed.r !== form.get('redirect_uri')) {\n\t\t\t\tthrow new OAuthError('invalid_grant', 'The code was issued to another client.');\n\t\t\t}\n\t\t\tconst verifier = form.get('code_verifier') ?? '';\n\t\t\tif (!safeEqual(createHash('sha256').update(verifier).digest('base64url'), sealed.p)) {\n\t\t\t\tthrow new OAuthError('invalid_grant', 'The code_verifier does not match.');\n\t\t\t}\n\t\t\tconst resource = form.get('resource');\n\t\t\tif (resource !== null && !isThisResource(resource)) {\n\t\t\t\tthrow new OAuthError('invalid_target', 'The resource is not this server.');\n\t\t\t}\n\t\t\tif (!markRedeemed(code, sealed.x)) {\n\t\t\t\tthrow new OAuthError('invalid_grant', 'The code was already used.');\n\t\t\t}\n\t\t\tconst { g } = sealed;\n\t\t\toptions.onRedeemed?.(g.tokenId);\n\t\t\treturn {\n\t\t\t\tstatus: 200,\n\t\t\t\tbody: {\n\t\t\t\t\taccess_token: g.secret,\n\t\t\t\t\ttoken_type: 'Bearer',\n\t\t\t\t\texpires_in: Math.max(0, Math.floor((Date.parse(g.expiresAt) - now()) / 1000)),\n\t\t\t\t\tscope: g.scopes.join(' ')\n\t\t\t\t}\n\t\t\t};\n\t\t} catch (err) {\n\t\t\tif (err instanceof OAuthError) return { status: err.status, body: err.toBody() };\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tfunction markRedeemed(code: string, expiresAt: number): boolean {\n\t\tconst t = now();\n\t\tfor (const [k, x] of redeemed) if (x < t) redeemed.delete(k);\n\t\tconst id = createHash('sha256').update(code).digest('base64url');\n\t\tif (redeemed.has(id)) return false;\n\t\tredeemed.set(id, expiresAt);\n\t\treturn true;\n\t}\n\n\tfunction isThisResource(resource: string): boolean {\n\t\tconst r = resource.replace(/\\/$/, '');\n\t\treturn r === origin || r === mcpResourceUrl(origin);\n\t}\n\n\treturn {\n\t\tregister,\n\t\tresolveClient,\n\t\tparseAuthorizeRequest,\n\t\tapprove,\n\t\tdeny,\n\t\texchange,\n\t\t/** All a registered client can be granted: the MCP 401 challenge's scopes. */\n\t\tregisteredScopes: registeredScopes as readonly RegisteredClientScope[],\n\t\tprotectedResourceMetadata: () => protectedResourceMetadata(origin, registeredScopes),\n\t\tauthorizationServerMetadata: () => authorizationServerMetadata(origin, registeredScopes)\n\t};\n}\n\nexport type OAuthServer = ReturnType<typeof createOAuthServer>;\n\n/** OAuth scopes to the API scopes a minted token gets. */\nexport function apiScopesFor(scopes: readonly OAuthScope[]): string[] {\n\treturn scopes.map((s) => `${s}:all`);\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\nasync function readMetadata(\n\turl: string,\n\tfetchClientMetadata: (url: string) => Promise<unknown>,\n\tscopes: readonly OAuthScope[]\n): Promise<OAuthClient> {\n\tlet doc: { client_id?: unknown; client_name?: unknown; redirect_uris?: unknown };\n\ttry {\n\t\tdoc = (await fetchClientMetadata(url)) as typeof doc;\n\t} catch {\n\t\tthrow new OAuthError('invalid_client', 'The client metadata document could not be read.');\n\t}\n\tif (doc?.client_id !== url) {\n\t\tthrow new OAuthError('invalid_client', 'The metadata document names a different client_id.');\n\t}\n\treturn {\n\t\tclientId: url,\n\t\tname:\n\t\t\ttypeof doc.client_name === 'string' && doc.client_name.trim()\n\t\t\t\t? doc.client_name.trim().slice(0, CLIENT_NAME_MAX)\n\t\t\t\t: new URL(url).host,\n\t\tredirectUris: checkRedirectUris(doc.redirect_uris),\n\t\tbuiltIn: false,\n\t\tscopes\n\t};\n}\n\n/**\n * What the request asks for, within what its client may have. A scope outside\n * that is dropped, not refused, so a client that asks for every advertised\n * scope still signs in with what it may have. No `scope` at all means all of\n * them. Asking only for scopes it may not have gets `read`, never more than it\n * asked for. `read` rides along with `solve` and `write`, which the consent\n * page offers as \"read and run solves\" and \"read and change\".\n */\nfunction parseScopes(raw: string | null, allowed: readonly OAuthScope[]): OAuthScope[] {\n\tconst requested = (raw ?? '').split(' ').filter(Boolean);\n\tif (!requested.length) return [...allowed];\n\tconst asked = requested.filter((s): s is OAuthScope =>\n\t\t(allowed as readonly string[]).includes(s)\n\t);\n\tif (!asked.length) return allowed.includes('read') ? ['read'] : [];\n\tconst impliesRead = asked.includes('solve') || asked.includes('write');\n\treturn allowed.filter((s) => asked.includes(s) || (s === 'read' && impliesRead));\n}\n\n/** One access level a consent page offers, and the scopes approving it grants. */\nexport interface ConsentChoice {\n\taccess: 'read' | 'solve' | 'write' | 'write_and_solve' | 'upload';\n\tscopes: OAuthScope[];\n}\n\n/**\n * The access levels a consent page offers for a request: `read` first, all it\n * asked for last. The user may narrow what the client asked for, never widen\n * it. `write` is offered with and without `solve`, so change access needn't\n * spend compute budget, and a host policy that allows one can still grant it.\n * An upload request is offered as asked: narrowing it to read would leave the\n * client unable to do the one thing it signed in for.\n */\nexport function consentChoices(scopes: readonly OAuthScope[]): ConsentChoice[] {\n\tif (!scopes.length) return [];\n\tif (scopes.includes('upload')) return [{ access: 'upload', scopes: [...scopes] }];\n\tconst solve = scopes.includes('solve');\n\tconst write = scopes.includes('write');\n\tconst choices: ConsentChoice[] = [{ access: 'read', scopes: ['read'] }];\n\tif (solve) choices.push({ access: 'solve', scopes: ['read', 'solve'] });\n\tif (write) choices.push({ access: 'write', scopes: ['read', 'write'] });\n\tif (solve && write) {\n\t\tchoices.push({ access: 'write_and_solve', scopes: ['read', 'solve', 'write'] });\n\t}\n\treturn choices;\n}\n\nfunction checkRedirectUris(value: unknown): string[] {\n\tif (!Array.isArray(value) || !value.length || value.length > REDIRECT_URIS_MAX) {\n\t\tthrow new OAuthError('invalid_redirect_uri', 'Give between 1 and 10 redirect_uris.');\n\t}\n\tfor (const uri of value) {\n\t\tif (typeof uri !== 'string' || !isAllowedRedirect(uri)) {\n\t\t\tthrow new OAuthError(\n\t\t\t\t'invalid_redirect_uri',\n\t\t\t\t'Redirect URIs must be https, or http on a loopback address.'\n\t\t\t);\n\t\t}\n\t}\n\treturn value as string[];\n}\n\nfunction isAllowedRedirect(uri: string): boolean {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(uri);\n\t} catch {\n\t\treturn false;\n\t}\n\tif (url.hash) return false;\n\treturn (\n\t\turl.protocol === 'https:' || (url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname))\n\t);\n}\n\n/** A redirect to a program on the user's own machine, which any local process can claim. */\nexport function isLoopbackRedirect(uri: string): boolean {\n\ttry {\n\t\treturn LOOPBACK_HOSTS.has(new URL(uri).hostname);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/** Exact, except a loopback redirect matches on any port (RFC 8252 §7.3). */\nexport function redirectMatches(registered: string, requested: string): boolean {\n\tif (registered === requested) return true;\n\tlet a: URL, b: URL;\n\ttry {\n\t\ta = new URL(registered);\n\t\tb = new URL(requested);\n\t} catch {\n\t\treturn false;\n\t}\n\treturn (\n\t\ta.protocol === 'http:' &&\n\t\tb.protocol === 'http:' &&\n\t\tLOOPBACK_HOSTS.has(a.hostname) &&\n\t\ta.hostname === b.hostname &&\n\t\ta.pathname === b.pathname &&\n\t\ta.search === b.search &&\n\t\t!b.hash &&\n\t\t!b.username &&\n\t\t!b.password\n\t);\n}\n\nfunction withParams(uri: string, params: Record<string, string | undefined>): string {\n\tconst url = new URL(uri);\n\tfor (const [k, v] of Object.entries(params)) if (v !== undefined) url.searchParams.set(k, v);\n\treturn url.toString();\n}\n\nfunction derive(secret: string, info: string): Buffer {\n\treturn Buffer.from(hkdfSync('sha256', secret, '', info, 32));\n}\n\nfunction sign(key: Buffer, data: string): string {\n\treturn createHmac('sha256', key).update(data).digest('base64url');\n}\n\nfunction seal(key: Buffer, value: unknown): string {\n\tconst iv = randomBytes(12);\n\tconst cipher = createCipheriv('aes-256-gcm', key, iv);\n\tconst body = Buffer.concat([cipher.update(JSON.stringify(value)), cipher.final()]);\n\treturn Buffer.concat([iv, cipher.getAuthTag(), body]).toString('base64url');\n}\n\nfunction open(key: Buffer, sealed: string): unknown {\n\ttry {\n\t\tconst raw = Buffer.from(sealed, 'base64url');\n\t\t// Without the length, a short code is checked against however many tag bytes it has.\n\t\tconst decipher = createDecipheriv('aes-256-gcm', key, raw.subarray(0, 12), {\n\t\t\tauthTagLength: 16\n\t\t});\n\t\tdecipher.setAuthTag(raw.subarray(12, 28));\n\t\tconst body = Buffer.concat([decipher.update(raw.subarray(28)), decipher.final()]);\n\t\treturn JSON.parse(body.toString('utf8'));\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction b64(text: string): string {\n\treturn Buffer.from(text).toString('base64url');\n}\n\nfunction unb64(text: string): string {\n\treturn Buffer.from(text, 'base64url').toString('utf8');\n}\n\nfunction safeEqual(a: string, b: string): boolean {\n\tconst x = Buffer.from(a);\n\tconst y = Buffer.from(b);\n\treturn x.length === y.length && timingSafeEqual(x, y);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA2BA,IAAa,eAAe;CAAC;CAAQ;CAAS;CAAS;CAAU;AAAiB;;;;;;;;;AAWlF,IAAa,sBAAsB;CAClC;CACA;CACA;AACD;;AAIA,IAAa,2BAA2B,CACvC,QACA,OACD;AAOA,IAAM,qBAAkC;CACvC,UAAU;CACV,MAAM;CACN,cAAc,CAAC,2BAA2B;CAC1C,SAAS;CACT,QAAQ;EAAC;EAAQ;EAAU;CAAiB;AAC7C;AAEA,IAAa,WAAW;AAExB,IAAa,cAAc;AAC3B,IAAM,kBAAkB;AACxB,IAAM,oBAAoB;AAC1B,IAAM,cAAc;AAGpB,IAAM,sBAAsB;AAC5B,IAAM,iBAAiB;AACvB,IAAM,iCAAiB,IAAI,IAAI;CAAC;CAAa;CAAa;AAAO,CAAC;AAElE,IAAa,aAAb,cAAgC,MAAM;CAG3B;CAEA;CAJV,YAEC,OACA,aACA,SAAkB,KACjB;EACD,MAAM,WAAW;EAJR,KAAA,QAAA;EAEA,KAAA,SAAA;EAGT,KAAK,OAAO;CACb;CAEA,SAAuD;EACtD,OAAO;GAAE,OAAO,KAAK;GAAO,mBAAmB,KAAK;EAAQ;CAC7D;AACD;AAqEA,SAAgB,e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I,SAAS,GAAG,EAAE,GAAG,EAC1E,eAAe,GAChB,CAAC;EACD,SAAS,WAAW,IAAI,SAAS,IAAI,EAAE,CAAC;EACxC,MAAM,OAAO,OAAO,OAAO,CAAC,SAAS,OAAO,IAAI,SAAS,EAAE,CAAC,GAAG,SAAS,MAAM,CAAC,CAAC;EAChF,OAAO,KAAK,MAAM,KAAK,SAAS,MAAM,CAAC;CACxC,QAAQ;EACP,OAAO;CACR;AACD;AAEA,SAAS,IAAI,MAAsB;CAClC,OAAO,OAAO,KAAK,IAAI,CAAC,CAAC,SAAS,WAAW;AAC9C;AAEA,SAAS,MAAM,MAAsB;CACpC,OAAO,OAAO,KAAK,MAAM,WAAW,CAAC,CAAC,SAAS,MAAM;AACtD;AAEA,SAAS,UAAU,GAAW,GAAoB;CACjD,MAAM,IAAI,OAAO,KAAK,CAAC;CACvB,MAAM,IAAI,OAAO,KAAK,CAAC;CACvB,OAAO,EAAE,WAAW,EAAE,UAAU,gBAAgB,GAAG,CAAC;AACrD"}
@@ -1,6 +1,6 @@
1
1
  var package_default = {
2
2
  name: "@selvajs/selva",
3
- version: "4.21.0-beta.6",
3
+ version: "4.21.0-beta.7",
4
4
  description: "Selva — self-contained Grasshopper-driven web app. Install, configure via .env, deploy.",
5
5
  license: "MIT",
6
6
  author: "VektorNode",
@@ -1 +1 @@
1
- {"version":3,"file":"package.js","names":[],"sources":["../../../package.json"],"sourcesContent":["{\n\t\"name\": \"@selvajs/selva\",\n\t\"version\": \"4.21.0-beta.6\",\n\t\"description\": \"Selva — self-contained Grasshopper-driven web app. Install, configure via .env, deploy.\",\n\t\"license\": \"MIT\",\n\t\"author\": \"VektorNode\",\n\t\"homepage\": \"https://selva.dev\",\n\t\"bugs\": \"https://github.com/VektorNode/selva/issues\",\n\t\"keywords\": [\n\t\t\"grasshopper\",\n\t\t\"rhino\",\n\t\t\"rhino-compute\",\n\t\t\"parametric-design\",\n\t\t\"web-app\",\n\t\t\"sveltekit\"\n\t],\n\t\"publishConfig\": {\n\t\t\"access\": \"public\"\n\t},\n\t\"repository\": {\n\t\t\"type\": \"git\",\n\t\t\"url\": \"git+https://github.com/VektorNode/selva.git\",\n\t\t\"directory\": \"packages/selva\"\n\t},\n\t\"type\": \"module\",\n\t\"main\": \"./build/index.js\",\n\t\"files\": [\n\t\t\"build\",\n\t\t\"templates\"\n\t],\n\t\"engines\": {\n\t\t\"node\": \">=24.0.0\"\n\t},\n\t\"scripts\": {\n\t\t\"dev\": \"vite dev\",\n\t\t\"dev:lan\": \"vite dev --host\",\n\t\t\"build\": \"rimraf build && vite build && node ./scripts/generate-templates.js && node ./scripts/write-runtime-meta.js\",\n\t\t\"preview\": \"vite preview\",\n\t\t\"start\": \"node build/index.js\",\n\t\t\"clean\": \"rimraf build templates\",\n\t\t\"prepare\": \"svelte-kit sync || echo ''\",\n\t\t\"check\": \"svelte-kit sync && svelte-check --tsconfig ./tsconfig.json\",\n\t\t\"test\": \"vitest run\",\n\t\t\"test:watch\": \"vitest\",\n\t\t\"openapi:generate\": \"node scripts/generate-openapi.js\",\n\t\t\"test:e2e\": \"playwright test\",\n\t\t\"lint\": \"eslint .\",\n\t\t\"lint:types\": \"eslint . --config eslint.typed.config.js\",\n\t\t\"generate:cli-config\": \"node scripts/generate-cli-config.js\"\n\t},\n\t\"dependencies\": {\n\t\t\"@lucide/svelte\": \"catalog:\",\n\t\t\"@supabase/supabase-js\": \"catalog:\",\n\t\t\"@sveltejs/kit\": \"catalog:\",\n\t\t\"bits-ui\": \"catalog:\",\n\t\t\"clsx\": \"catalog:\",\n\t\t\"mode-watcher\": \"catalog:\",\n\t\t\"nodemailer\": \"catalog:\",\n\t\t\"pino\": \"^10.4.0\",\n\t\t\"rhino3dm\": \"catalog:\",\n\t\t\"sharp\": \"catalog:\",\n\t\t\"tailwind-merge\": \"catalog:\",\n\t\t\"tailwind-variants\": \"catalog:\",\n\t\t\"three\": \"catalog:\",\n\t\t\"zod\": \"catalog:\"\n\t},\n\t\"optionalDependencies\": {\n\t\t\"@sentry/node\": \"^11.10.0\"\n\t},\n\t\"devDependencies\": {\n\t\t\"@playwright/test\": \"catalog:\",\n\t\t\"@selvajs/compute\": \"workspace:*\",\n\t\t\"@selvajs/config\": \"workspace:*\",\n\t\t\"@selvajs/header-auth-provider\": \"workspace:*\",\n\t\t\"@selvajs/local-provider\": \"workspace:*\",\n\t\t\"@selvajs/mcp\": \"workspace:*\",\n\t\t\"@selvajs/notifications\": \"workspace:*\",\n\t\t\"@selvajs/platform\": \"workspace:*\",\n\t\t\"@selvajs/schemas\": \"workspace:*\",\n\t\t\"@selvajs/server\": \"workspace:*\",\n\t\t\"@selvajs/solve\": \"workspace:*\",\n\t\t\"@selvajs/supabase-provider\": \"workspace:*\",\n\t\t\"@selvajs/ui\": \"workspace:*\",\n\t\t\"@selvajs/visualization\": \"workspace:*\",\n\t\t\"@sveltejs/adapter-node\": \"catalog:\",\n\t\t\"@types/nodemailer\": \"catalog:\",\n\t\t\"@types/three\": \"catalog:\",\n\t\t\"rimraf\": \"catalog:\",\n\t\t\"tw-animate-css\": \"catalog:\",\n\t\t\"vitest\": \"catalog:\"\n\t},\n\t\"imports\": {\n\t\t\"#lib/*\": \"./src/lib/*\"\n\t}\n}\n"],"mappings":""}
1
+ {"version":3,"file":"package.js","names":[],"sources":["../../../package.json"],"sourcesContent":["{\n\t\"name\": \"@selvajs/selva\",\n\t\"version\": \"4.21.0-beta.7\",\n\t\"description\": \"Selva — self-contained Grasshopper-driven web app. Install, configure via .env, deploy.\",\n\t\"license\": \"MIT\",\n\t\"author\": \"VektorNode\",\n\t\"homepage\": \"https://selva.dev\",\n\t\"bugs\": \"https://github.com/VektorNode/selva/issues\",\n\t\"keywords\": [\n\t\t\"grasshopper\",\n\t\t\"rhino\",\n\t\t\"rhino-compute\",\n\t\t\"parametric-design\",\n\t\t\"web-app\",\n\t\t\"sveltekit\"\n\t],\n\t\"publishConfig\": {\n\t\t\"access\": \"public\"\n\t},\n\t\"repository\": {\n\t\t\"type\": \"git\",\n\t\t\"url\": \"git+https://github.com/VektorNode/selva.git\",\n\t\t\"directory\": \"packages/selva\"\n\t},\n\t\"type\": \"module\",\n\t\"main\": \"./build/index.js\",\n\t\"files\": [\n\t\t\"build\",\n\t\t\"templates\"\n\t],\n\t\"engines\": {\n\t\t\"node\": \">=24.0.0\"\n\t},\n\t\"scripts\": {\n\t\t\"dev\": \"vite dev\",\n\t\t\"dev:lan\": \"vite dev --host\",\n\t\t\"build\": \"rimraf build && vite build && node ./scripts/generate-templates.js && node ./scripts/write-runtime-meta.js\",\n\t\t\"preview\": \"vite preview\",\n\t\t\"start\": \"node build/index.js\",\n\t\t\"clean\": \"rimraf build templates\",\n\t\t\"prepare\": \"svelte-kit sync || echo ''\",\n\t\t\"check\": \"svelte-kit sync && svelte-check --tsconfig ./tsconfig.json\",\n\t\t\"test\": \"vitest run\",\n\t\t\"test:watch\": \"vitest\",\n\t\t\"openapi:generate\": \"node scripts/generate-openapi.js\",\n\t\t\"test:e2e\": \"playwright test\",\n\t\t\"lint\": \"eslint .\",\n\t\t\"lint:types\": \"eslint . --config eslint.typed.config.js\",\n\t\t\"generate:cli-config\": \"node scripts/generate-cli-config.js\"\n\t},\n\t\"dependencies\": {\n\t\t\"@lucide/svelte\": \"catalog:\",\n\t\t\"@supabase/supabase-js\": \"catalog:\",\n\t\t\"@sveltejs/kit\": \"catalog:\",\n\t\t\"bits-ui\": \"catalog:\",\n\t\t\"clsx\": \"catalog:\",\n\t\t\"mode-watcher\": \"catalog:\",\n\t\t\"nodemailer\": \"catalog:\",\n\t\t\"pino\": \"^10.4.0\",\n\t\t\"rhino3dm\": \"catalog:\",\n\t\t\"sharp\": \"catalog:\",\n\t\t\"tailwind-merge\": \"catalog:\",\n\t\t\"tailwind-variants\": \"catalog:\",\n\t\t\"three\": \"catalog:\",\n\t\t\"zod\": \"catalog:\"\n\t},\n\t\"optionalDependencies\": {\n\t\t\"@sentry/node\": \"^11.10.0\"\n\t},\n\t\"devDependencies\": {\n\t\t\"@playwright/test\": \"catalog:\",\n\t\t\"@selvajs/compute\": \"workspace:*\",\n\t\t\"@selvajs/config\": \"workspace:*\",\n\t\t\"@selvajs/header-auth-provider\": \"workspace:*\",\n\t\t\"@selvajs/local-provider\": \"workspace:*\",\n\t\t\"@selvajs/mcp\": \"workspace:*\",\n\t\t\"@selvajs/notifications\": \"workspace:*\",\n\t\t\"@selvajs/platform\": \"workspace:*\",\n\t\t\"@selvajs/schemas\": \"workspace:*\",\n\t\t\"@selvajs/server\": \"workspace:*\",\n\t\t\"@selvajs/solve\": \"workspace:*\",\n\t\t\"@selvajs/supabase-provider\": \"workspace:*\",\n\t\t\"@selvajs/ui\": \"workspace:*\",\n\t\t\"@selvajs/visualization\": \"workspace:*\",\n\t\t\"@sveltejs/adapter-node\": \"catalog:\",\n\t\t\"@types/nodemailer\": \"catalog:\",\n\t\t\"@types/three\": \"catalog:\",\n\t\t\"rimraf\": \"catalog:\",\n\t\t\"tw-animate-css\": \"catalog:\",\n\t\t\"vitest\": \"catalog:\"\n\t},\n\t\"imports\": {\n\t\t\"#lib/*\": \"./src/lib/*\"\n\t}\n}\n"],"mappings":""}
@@ -1,9 +1,9 @@
1
- import { s as createOAuthServer, t as CODE_TTL_MS } from "./oauth.js";
2
1
  import { t as hmacKeys } from "./keys.server.js";
3
2
  import { t as createComputeRateLimiter } from "./rate-limit.js";
4
3
  import { t as assertSafeRemoteDefinitionUrl } from "./safe-url.js";
5
4
  import { n as readBodyWithCap } from "./remote-definition.js";
6
5
  import "./compute.js";
6
+ import { a as createOAuthServer, t as CODE_TTL_MS } from "./oauth.js";
7
7
  import "./tokens.js";
8
8
  import { json } from "@sveltejs/kit";
9
9
  // src/lib/server/oauth/server.ts
@@ -101,6 +101,6 @@ var DISCOVERY_HEADERS = {
101
101
  "Access-Control-Allow-Origin": "*",
102
102
  "Cache-Control": "public, max-age=3600"
103
103
  };
104
- export { oauthServer as a, oauthRateLimited as i, expectRedemption as n, oauthUnavailable as o, oauthConfigured as r, DISCOVERY_HEADERS as t };
104
+ export { oauthUnavailable as a, oauthServer as i, expectRedemption as n, oauthRateLimited as r, DISCOVERY_HEADERS as t };
105
105
 
106
106
  //# sourceMappingURL=server2.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"server2.js","names":[],"sources":["../../../src/lib/server/oauth/server.ts"],"sourcesContent":["/**\n * This instance's OAuth authorization server for MCP clients. The protocol lives\n * in `@selvajs/server/oauth`; this file supplies the secret, the SSRF-guarded\n * metadata fetch and the per-IP limit the endpoints share.\n */\n\nimport { json, type RequestEvent } from '@sveltejs/kit';\nimport { hmacKeys } from '#lib/server/keys.server.js';\nimport {\n\tassertSafeRemoteDefinitionUrl,\n\tcreateComputeRateLimiter,\n\treadBodyWithCap\n} from '@selvajs/server/compute';\nimport { CODE_TTL_MS, createOAuthServer, type OAuthServer } from '@selvajs/server/oauth';\nimport { MIN_TOKEN_SECRET_LENGTH } from '@selvajs/server/tokens';\n\nconst METADATA_TIMEOUT_MS = 5_000;\nconst METADATA_MAX_BYTES = 64 * 1024;\n\n// One slot, as for `/mcp`: the origin comes from the request, so a map would grow\n// with whatever hosts a caller sends. Re-keyed on the secret, like the token codecs.\nlet cached: { origin: string; secret: string; server: OAuthServer } | null = null;\n// Outlives `cached`, so rebuilding the server for another origin can't forget a redeemed code.\nconst redeemedCodes = new Map<string, number>();\n\n// The key is minted at consent, before its code is redeemed. A client that never\n// exchanges the code would leave a live key nobody holds, so it is revoked once\n// the code can no longer be redeemed. Lost on restart: best effort.\nconst ABANDON_AFTER_MS = CODE_TTL_MS + 60_000;\nconst unredeemed = new Map<string, ReturnType<typeof setTimeout>>();\n\n/** Revoke `tokenId` with `revoke` unless its code is redeemed in time. */\nexport function expectRedemption(tokenId: string, revoke: () => Promise<void>): void {\n\tconst timer = setTimeout(() => {\n\t\tunredeemed.delete(tokenId);\n\t\trevoke().catch(() => {});\n\t}, ABANDON_AFTER_MS);\n\ttimer.unref?.();\n\tunredeemed.set(tokenId, timer);\n}\n\nfunction onRedeemed(tokenId: string): void {\n\tclearTimeout(unredeemed.get(tokenId));\n\tunredeemed.delete(tokenId);\n}\n\n/** Whether `oauthServer` would build one, without building it. */\nexport function oauthConfigured(): boolean {\n\tconst secret = hmacKeys().current;\n\treturn Boolean(secret && secret.length >= MIN_TOKEN_SECRET_LENGTH);\n}\n\n/** Undefined without a usable SELVA_HMAC_KEY: the endpoints then answer 503. */\nexport function oauthServer(origin: string): OAuthServer | undefined {\n\tif (!oauthConfigured()) return undefined;\n\tconst { current, previous } = hmacKeys();\n\tconst secret = current!;\n\tconst cacheKey = `${secret}\\n${previous ?? ''}`;\n\tif (cached?.origin !== origin || cached.secret !== cacheKey) {\n\t\tcached = {\n\t\t\torigin,\n\t\t\tsecret: cacheKey,\n\t\t\tserver: createOAuthServer({\n\t\t\t\torigin,\n\t\t\t\tsecret,\n\t\t\t\t...(previous ? { previousSecret: previous } : {}),\n\t\t\t\tfetchClientMetadata,\n\t\t\t\tredeemedCodes,\n\t\t\t\tonRedeemed\n\t\t\t})\n\t\t};\n\t}\n\treturn cached.server;\n}\n\n/** The URL is an unknown client's, so it goes through the same guard as remote definitions. */\nasync function fetchClientMetadata(url: string): Promise<unknown> {\n\tawait assertSafeRemoteDefinitionUrl(url);\n\tconst controller = new AbortController();\n\tconst timer = setTimeout(() => controller.abort(), METADATA_TIMEOUT_MS);\n\ttry {\n\t\tconst res = await fetch(url, {\n\t\t\theaders: { Accept: 'application/json' },\n\t\t\tredirect: 'error',\n\t\t\tsignal: controller.signal\n\t\t});\n\t\tif (!res.ok) throw new Error(`HTTP ${res.status}`);\n\t\t// Counted while streaming: a body with no or a lying Content-Length must not buffer whole.\n\t\tconst bytes = await readBodyWithCap(res, METADATA_MAX_BYTES, controller);\n\t\treturn JSON.parse(new TextDecoder().decode(bytes));\n\t} finally {\n\t\tclearTimeout(timer);\n\t}\n}\n\n// Registration and token exchange take no credential, so the IP is the only key.\nconst limiter = createComputeRateLimiter({ windowMs: 60_000, maxPerWindow: 30 });\n\n/** A 429 response when the caller's IP is over the limit, else undefined. */\nexport function oauthRateLimited(event: RequestEvent): Response | undefined {\n\tconst verdict = limiter.check(`oauth:${event.getClientAddress()}`);\n\tif (verdict.allowed) return undefined;\n\treturn json(\n\t\t{ error: 'slow_down', error_description: 'Too many requests. Try again shortly.' },\n\t\t{ status: 429, headers: { 'Retry-After': String(verdict.retryAfter ?? 60) } }\n\t);\n}\n\nexport function oauthUnavailable(): Response {\n\treturn json(\n\t\t{ error: 'temporarily_unavailable', error_description: 'OAuth is not configured here.' },\n\t\t{ status: 503 }\n\t);\n}\n\n/** Discovery documents are read by browser-based clients too. */\nexport const DISCOVERY_HEADERS = {\n\t'Access-Control-Allow-Origin': '*',\n\t'Cache-Control': 'public, max-age=3600'\n};\n"],"mappings":";;;;;;;;;;;;;;AAgBA,IAAM,sBAAsB;AAC5B,IAAM,qBAAqB;AAI3B,IAAI,SAAyE;AAE7E,IAAM,gCAAgB,IAAI,IAAoB;AAK9C,IAAM,mBAAmB,cAAc;AACvC,IAAM,6BAAa,IAAI,IAA2C;;AAGlE,SAAgB,iBAAiB,SAAiB,QAAmC;CACpF,MAAM,QAAQ,iBAAiB;EAC9B,WAAW,OAAO,OAAO;EACzB,OAAO,CAAC,CAAC,YAAY,CAAC,CAAC;CACxB,GAAG,gBAAgB;CACnB,MAAM,QAAQ;CACd,WAAW,IAAI,SAAS,KAAK;AAC9B;AAEA,SAAS,WAAW,SAAuB;CAC1C,aAAa,WAAW,IAAI,OAAO,CAAC;CACpC,WAAW,OAAO,OAAO;AAC1B;;AAGA,SAAgB,kBAA2B;CAC1C,MAAM,SAAS,SAAS,CAAC,CAAC;CAC1B,OAAO,QAAQ,UAAU,OAAO,UAAA,EAAiC;AAClE;;AAGA,SAAgB,YAAY,QAAyC;CACpE,IAAI,CAAC,gBAAgB,GAAG,OAAO,KAAA;CAC/B,MAAM,EAAE,SAAS,aAAa,SAAS;CACvC,MAAM,SAAS;CACf,MAAM,WAAW,GAAG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{"version":3,"file":"server2.js","names":[],"sources":["../../../src/lib/server/oauth/server.ts"],"sourcesContent":["/**\n * This instance's OAuth authorization server for MCP clients. The protocol lives\n * in `@selvajs/server/oauth`; this file supplies the secret, the SSRF-guarded\n * metadata fetch and the per-IP limit the endpoints share.\n */\n\nimport { json, type RequestEvent } from '@sveltejs/kit';\nimport { hmacKeys } from '#lib/server/keys.server.js';\nimport {\n\tassertSafeRemoteDefinitionUrl,\n\tcreateComputeRateLimiter,\n\treadBodyWithCap\n} from '@selvajs/server/compute';\nimport { CODE_TTL_MS, createOAuthServer, type OAuthServer } from '@selvajs/server/oauth';\nimport { MIN_TOKEN_SECRET_LENGTH } from '@selvajs/server/tokens';\n\nconst METADATA_TIMEOUT_MS = 5_000;\nconst METADATA_MAX_BYTES = 64 * 1024;\n\n// One slot, as for `/mcp`: the origin comes from the request, so a map would grow\n// with whatever hosts a caller sends. Re-keyed on the secret, like the token codecs.\nlet cached: { origin: string; secret: string; server: OAuthServer } | null = null;\n// Outlives `cached`, so rebuilding the server for another origin can't forget a redeemed code.\nconst redeemedCodes = new Map<string, number>();\n\n// The key is minted at consent, before its code is redeemed. A client that never\n// exchanges the code would leave a live key nobody holds, so it is revoked once\n// the code can no longer be redeemed. Lost on restart: best effort.\nconst ABANDON_AFTER_MS = CODE_TTL_MS + 60_000;\nconst unredeemed = new Map<string, ReturnType<typeof setTimeout>>();\n\n/** Revoke `tokenId` with `revoke` unless its code is redeemed in time. */\nexport function expectRedemption(tokenId: string, revoke: () => Promise<void>): void {\n\tconst timer = setTimeout(() => {\n\t\tunredeemed.delete(tokenId);\n\t\trevoke().catch(() => {});\n\t}, ABANDON_AFTER_MS);\n\ttimer.unref?.();\n\tunredeemed.set(tokenId, timer);\n}\n\nfunction onRedeemed(tokenId: string): void {\n\tclearTimeout(unredeemed.get(tokenId));\n\tunredeemed.delete(tokenId);\n}\n\n/** Whether `oauthServer` would build one, without building it. */\nfunction oauthConfigured(): boolean {\n\tconst secret = hmacKeys().current;\n\treturn Boolean(secret && secret.length >= MIN_TOKEN_SECRET_LENGTH);\n}\n\n/** Undefined without a usable SELVA_HMAC_KEY: the endpoints then answer 503. */\nexport function oauthServer(origin: string): OAuthServer | undefined {\n\tif (!oauthConfigured()) return undefined;\n\tconst { current, previous } = hmacKeys();\n\tconst secret = current!;\n\tconst cacheKey = `${secret}\\n${previous ?? ''}`;\n\tif (cached?.origin !== origin || cached.secret !== cacheKey) {\n\t\tcached = {\n\t\t\torigin,\n\t\t\tsecret: cacheKey,\n\t\t\tserver: createOAuthServer({\n\t\t\t\torigin,\n\t\t\t\tsecret,\n\t\t\t\t...(previous ? { previousSecret: previous } : {}),\n\t\t\t\tfetchClientMetadata,\n\t\t\t\tredeemedCodes,\n\t\t\t\tonRedeemed\n\t\t\t})\n\t\t};\n\t}\n\treturn cached.server;\n}\n\n/** The URL is an unknown client's, so it goes through the same guard as remote definitions. */\nasync function fetchClientMetadata(url: string): Promise<unknown> {\n\tawait assertSafeRemoteDefinitionUrl(url);\n\tconst controller = new AbortController();\n\tconst timer = setTimeout(() => controller.abort(), METADATA_TIMEOUT_MS);\n\ttry {\n\t\tconst res = await fetch(url, {\n\t\t\theaders: { Accept: 'application/json' },\n\t\t\tredirect: 'error',\n\t\t\tsignal: controller.signal\n\t\t});\n\t\tif (!res.ok) throw new Error(`HTTP ${res.status}`);\n\t\t// Counted while streaming: a body with no or a lying Content-Length must not buffer whole.\n\t\tconst bytes = await readBodyWithCap(res, METADATA_MAX_BYTES, controller);\n\t\treturn JSON.parse(new TextDecoder().decode(bytes));\n\t} finally {\n\t\tclearTimeout(timer);\n\t}\n}\n\n// Registration and token exchange take no credential, so the IP is the only key.\nconst limiter = createComputeRateLimiter({ windowMs: 60_000, maxPerWindow: 30 });\n\n/** A 429 response when the caller's IP is over the limit, else undefined. */\nexport function oauthRateLimited(event: RequestEvent): Response | undefined {\n\tconst verdict = limiter.check(`oauth:${event.getClientAddress()}`);\n\tif (verdict.allowed) return undefined;\n\treturn json(\n\t\t{ error: 'slow_down', error_description: 'Too many requests. Try again shortly.' },\n\t\t{ status: 429, headers: { 'Retry-After': String(verdict.retryAfter ?? 60) } }\n\t);\n}\n\nexport function oauthUnavailable(): Response {\n\treturn json(\n\t\t{ error: 'temporarily_unavailable', error_description: 'OAuth is not configured here.' },\n\t\t{ status: 503 }\n\t);\n}\n\n/** Discovery documents are read by browser-based clients too. */\nexport const DISCOVERY_HEADERS = {\n\t'Access-Control-Allow-Origin': '*',\n\t'Cache-Control': 'public, max-age=3600'\n};\n"],"mappings":";;;;;;;;;;;;;;AAgBA,IAAM,sBAAsB;AAC5B,IAAM,qBAAqB;AAI3B,IAAI,SAAyE;AAE7E,IAAM,gCAAgB,IAAI,IAAoB;AAK9C,IAAM,mBAAmB,cAAc;AACvC,IAAM,6BAAa,IAAI,IAA2C;;AAGlE,SAAgB,iBAAiB,SAAiB,QAAmC;CACpF,MAAM,QAAQ,iBAAiB;EAC9B,WAAW,OAAO,OAAO;EACzB,OAAO,CAAC,CAAC,YAAY,CAAC,CAAC;CACxB,GAAG,gBAAgB;CACnB,MAAM,QAAQ;CACd,WAAW,IAAI,SAAS,KAAK;AAC9B;AAEA,SAAS,WAAW,SAAuB;CAC1C,aAAa,WAAW,IAAI,OAAO,CAAC;CACpC,WAAW,OAAO,OAAO;AAC1B;;AAGA,SAAS,kBAA2B;CACnC,MAAM,SAAS,SAAS,CAAC,CAAC;CAC1B,OAAO,QAAQ,UAAU,OAAO,UAAA,EAAiC;AAClE;;AAGA,SAAgB,YAAY,QAAyC;CACpE,IAAI,CAAC,gBAAgB,GAAG,OAAO,KAAA;CAC/B,MAAM,EAAE,SAAS,aAAa,SAAS;CACvC,MAAM,SAAS;CACf,MAAM,WAAW,GAAG,OAAO,IAAI,YAAY;CAC3C,IAAI,QAAQ,WAAW,UAAU,OAAO,WAAW,UAClD,SAAS;EACR;EACA,QAAQ;EACR,QAAQ,kBAAkB;GACzB;GACA;GACA,GAAI,WAAW,EAAE,gBAAgB,SAAS,IAAI,CAAC;GAC/C;GACA;GACA;EACD,CAAC;CACF;CAED,OAAO,OAAO;AACf;;AAGA,eAAe,oBAAoB,KAA+B;CACjE,MAAM,8BAA8B,GAAG;CACvC,MAAM,aAAa,IAAI,gBAAgB;CACvC,MAAM,QAAQ,iBAAiB,WAAW,MAAM,GAAG,mBAAmB;CACtE,IAAI;EACH,MAAM,MAAM,MAAM,MAAM,KAAK;GAC5B,SAAS,EAAE,QAAQ,mBAAmB;GACtC,UAAU;GACV,QAAQ,WAAW;EACpB,CAAC;EACD,IAAI,CAAC,IAAI,IAAI,MAAM,IAAI,MAAM,QAAQ,IAAI,QAAQ;EAEjD,MAAM,QAAQ,MAAM,gBAAgB,KAAK,oBAAoB,UAAU;EACvE,OAAO,KAAK,MAAM,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK,CAAC;CAClD,UAAU;EACT,aAAa,KAAK;CACnB;AACD;AAGA,IAAM,UAAU,yBAAyB;CAAE,UAAU;CAAQ,cAAc;AAAG,CAAC;;AAG/E,SAAgB,iBAAiB,OAA2C;CAC3E,MAAM,UAAU,QAAQ,MAAM,SAAS,MAAM,iBAAiB,GAAG;CACjE,IAAI,QAAQ,SAAS,OAAO,KAAA;CAC5B,OAAO,KACN;EAAE,OAAO;EAAa,mBAAmB;CAAwC,GACjF;EAAE,QAAQ;EAAK,SAAS,EAAE,eAAe,OAAO,QAAQ,cAAc,EAAE,EAAE;CAAE,CAC7E;AACD;AAEA,SAAgB,mBAA6B;CAC5C,OAAO,KACN;EAAE,OAAO;EAA2B,mBAAmB;CAAgC,GACvF,EAAE,QAAQ,IAAI,CACf;AACD;;AAGA,IAAa,oBAAoB;CAChC,+BAA+B;CAC/B,iBAAiB;AAClB"}
@@ -1,9 +1,12 @@
1
- import { a as authorizationServerMetadata } from "../../../../chunks/oauth.js";
2
- import { t as DISCOVERY_HEADERS } from "../../../../chunks/server2.js";
1
+ import { a as oauthUnavailable, i as oauthServer, t as DISCOVERY_HEADERS } from "../../../../chunks/server2.js";
3
2
  import { t as publicUrl } from "../../../../chunks/origin.js";
4
3
  import { json } from "@sveltejs/kit";
5
4
  // src/routes/.well-known/oauth-authorization-server/+server.ts
6
- var GET = ({ url }) => json(authorizationServerMetadata(publicUrl(url).origin), { headers: DISCOVERY_HEADERS });
5
+ var GET = ({ url }) => {
6
+ const oauth = oauthServer(publicUrl(url).origin);
7
+ if (!oauth) return oauthUnavailable();
8
+ return json(oauth.authorizationServerMetadata(), { headers: DISCOVERY_HEADERS });
9
+ };
7
10
  export { GET };
8
11
 
9
12
  //# sourceMappingURL=_server.ts.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"_server.ts.js","names":[],"sources":["../../../../../../src/routes/.well-known/oauth-authorization-server/+server.ts"],"sourcesContent":["import { json } from '@sveltejs/kit';\nimport { authorizationServerMetadata } from '@selvajs/server/oauth';\nimport { DISCOVERY_HEADERS } from '#lib/server/oauth/server.js';\nimport { publicUrl } from '#lib/server/origin.js';\nimport type { RequestHandler } from './$types';\n\nexport const GET: RequestHandler = ({ url }) =>\n\tjson(authorizationServerMetadata(publicUrl(url).origin), { headers: DISCOVERY_HEADERS });\n"],"mappings":";;;;;AAMA,IAAa,OAAuB,EAAE,UACrC,KAAK,4BAA4B,UAAU,GAAG,CAAC,CAAC,MAAM,GAAG,EAAE,SAAS,kBAAkB,CAAC"}
1
+ {"version":3,"file":"_server.ts.js","names":[],"sources":["../../../../../../src/routes/.well-known/oauth-authorization-server/+server.ts"],"sourcesContent":["import { json } from '@sveltejs/kit';\nimport { DISCOVERY_HEADERS, oauthServer, oauthUnavailable } from '#lib/server/oauth/server.js';\nimport { publicUrl } from '#lib/server/origin.js';\nimport type { RequestHandler } from './$types';\n\nexport const GET: RequestHandler = ({ url }) => {\n\tconst oauth = oauthServer(publicUrl(url).origin);\n\tif (!oauth) return oauthUnavailable();\n\treturn json(oauth.authorizationServerMetadata(), { headers: DISCOVERY_HEADERS });\n};\n"],"mappings":";;;;AAKA,IAAa,OAAuB,EAAE,UAAU;CAC/C,MAAM,QAAQ,YAAY,UAAU,GAAG,CAAC,CAAC,MAAM;CAC/C,IAAI,CAAC,OAAO,OAAO,iBAAiB;CACpC,OAAO,KAAK,MAAM,4BAA4B,GAAG,EAAE,SAAS,kBAAkB,CAAC;AAChF"}
@@ -1,9 +1,12 @@
1
- import { l as protectedResourceMetadata } from "../../../../chunks/oauth.js";
2
- import { t as DISCOVERY_HEADERS } from "../../../../chunks/server2.js";
1
+ import { a as oauthUnavailable, i as oauthServer, t as DISCOVERY_HEADERS } from "../../../../chunks/server2.js";
3
2
  import { t as publicUrl } from "../../../../chunks/origin.js";
4
3
  import { json } from "@sveltejs/kit";
5
4
  // src/routes/.well-known/oauth-protected-resource/+server.ts
6
- var GET = ({ url }) => json(protectedResourceMetadata(publicUrl(url).origin), { headers: DISCOVERY_HEADERS });
5
+ var GET = ({ url }) => {
6
+ const oauth = oauthServer(publicUrl(url).origin);
7
+ if (!oauth) return oauthUnavailable();
8
+ return json(oauth.protectedResourceMetadata(), { headers: DISCOVERY_HEADERS });
9
+ };
7
10
  export { GET };
8
11
 
9
12
  //# sourceMappingURL=_server.ts.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"_server.ts.js","names":[],"sources":["../../../../../../src/routes/.well-known/oauth-protected-resource/+server.ts"],"sourcesContent":["import { json } from '@sveltejs/kit';\nimport { protectedResourceMetadata } from '@selvajs/server/oauth';\nimport { DISCOVERY_HEADERS } from '#lib/server/oauth/server.js';\nimport { publicUrl } from '#lib/server/origin.js';\nimport type { RequestHandler } from './$types';\n\n// The bare path is the fallback clients probe when a 401 carries no pointer.\nexport const GET: RequestHandler = ({ url }) =>\n\tjson(protectedResourceMetadata(publicUrl(url).origin), { headers: DISCOVERY_HEADERS });\n"],"mappings":";;;;;AAOA,IAAa,OAAuB,EAAE,UACrC,KAAK,0BAA0B,UAAU,GAAG,CAAC,CAAC,MAAM,GAAG,EAAE,SAAS,kBAAkB,CAAC"}
1
+ {"version":3,"file":"_server.ts.js","names":[],"sources":["../../../../../../src/routes/.well-known/oauth-protected-resource/+server.ts"],"sourcesContent":["import { json } from '@sveltejs/kit';\nimport { DISCOVERY_HEADERS, oauthServer, oauthUnavailable } from '#lib/server/oauth/server.js';\nimport { publicUrl } from '#lib/server/origin.js';\nimport type { RequestHandler } from './$types';\n\n// The bare path is the fallback clients probe when a 401 carries no pointer.\nexport const GET: RequestHandler = ({ url }) => {\n\tconst oauth = oauthServer(publicUrl(url).origin);\n\tif (!oauth) return oauthUnavailable();\n\treturn json(oauth.protectedResourceMetadata(), { headers: DISCOVERY_HEADERS });\n};\n"],"mappings":";;;;AAMA,IAAa,OAAuB,EAAE,UAAU;CAC/C,MAAM,QAAQ,YAAY,UAAU,GAAG,CAAC,CAAC,MAAM;CAC/C,IAAI,CAAC,OAAO,OAAO,iBAAiB;CACpC,OAAO,KAAK,MAAM,0BAA0B,GAAG,EAAE,SAAS,kBAAkB,CAAC;AAC9E"}
@@ -1,9 +1,12 @@
1
- import { l as protectedResourceMetadata } from "../../../../../chunks/oauth.js";
2
- import { t as DISCOVERY_HEADERS } from "../../../../../chunks/server2.js";
1
+ import { a as oauthUnavailable, i as oauthServer, t as DISCOVERY_HEADERS } from "../../../../../chunks/server2.js";
3
2
  import { t as publicUrl } from "../../../../../chunks/origin.js";
4
3
  import { json } from "@sveltejs/kit";
5
4
  // src/routes/.well-known/oauth-protected-resource/mcp/+server.ts
6
- var GET = ({ url }) => json(protectedResourceMetadata(publicUrl(url).origin), { headers: DISCOVERY_HEADERS });
5
+ var GET = ({ url }) => {
6
+ const oauth = oauthServer(publicUrl(url).origin);
7
+ if (!oauth) return oauthUnavailable();
8
+ return json(oauth.protectedResourceMetadata(), { headers: DISCOVERY_HEADERS });
9
+ };
7
10
  export { GET };
8
11
 
9
12
  //# sourceMappingURL=_server.ts.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"_server.ts.js","names":[],"sources":["../../../../../../../src/routes/.well-known/oauth-protected-resource/mcp/+server.ts"],"sourcesContent":["import { json } from '@sveltejs/kit';\nimport { protectedResourceMetadata } from '@selvajs/server/oauth';\nimport { DISCOVERY_HEADERS } from '#lib/server/oauth/server.js';\nimport { publicUrl } from '#lib/server/origin.js';\nimport type { RequestHandler } from './$types';\n\nexport const GET: RequestHandler = ({ url }) =>\n\tjson(protectedResourceMetadata(publicUrl(url).origin), { headers: DISCOVERY_HEADERS });\n"],"mappings":";;;;;AAMA,IAAa,OAAuB,EAAE,UACrC,KAAK,0BAA0B,UAAU,GAAG,CAAC,CAAC,MAAM,GAAG,EAAE,SAAS,kBAAkB,CAAC"}
1
+ {"version":3,"file":"_server.ts.js","names":[],"sources":["../../../../../../../src/routes/.well-known/oauth-protected-resource/mcp/+server.ts"],"sourcesContent":["import { json } from '@sveltejs/kit';\nimport { DISCOVERY_HEADERS, oauthServer, oauthUnavailable } from '#lib/server/oauth/server.js';\nimport { publicUrl } from '#lib/server/origin.js';\nimport type { RequestHandler } from './$types';\n\nexport const GET: RequestHandler = ({ url }) => {\n\tconst oauth = oauthServer(publicUrl(url).origin);\n\tif (!oauth) return oauthUnavailable();\n\treturn json(oauth.protectedResourceMetadata(), { headers: DISCOVERY_HEADERS });\n};\n"],"mappings":";;;;AAKA,IAAa,OAAuB,EAAE,UAAU;CAC/C,MAAM,QAAQ,YAAY,UAAU,GAAG,CAAC,CAAC,MAAM;CAC/C,IAAI,CAAC,OAAO,OAAO,iBAAiB;CACpC,OAAO,KAAK,MAAM,0BAA0B,GAAG,EAAE,SAAS,kBAAkB,CAAC;AAC9E"}
@@ -1,10 +1,10 @@
1
1
  import { f as getLogger } from "../../../chunks/providers.server.js";
2
- import { r as REGISTERED_CLIENT_SCOPES, u as resourceMetadataUrl } from "../../../chunks/oauth.js";
3
2
  import { n as env } from "../../../chunks/previous-key.js";
4
3
  import { V as apiScopeActionCovers } from "../../../chunks/access.js";
5
4
  import { n as ApiScopeActionSchema, o as parseApiScope } from "../../../chunks/types.js";
6
5
  import { r as GuidSchema } from "../../../chunks/schemas.js";
7
- import { r as oauthConfigured } from "../../../chunks/server2.js";
6
+ import { s as resourceMetadataUrl } from "../../../chunks/oauth.js";
7
+ import { i as oauthServer } from "../../../chunks/server2.js";
8
8
  import { t as publicUrl } from "../../../chunks/origin.js";
9
9
  import { i as getInputItems } from "../../../chunks/abort-Bfrdupaj.js";
10
10
  import { t as buildOpenApiDocument } from "../../../chunks/openapi.js";
@@ -21379,9 +21379,10 @@ function trustedOrigins() {
21379
21379
  return /* @__PURE__ */ new Set([...env.ORIGIN ? [new URL(env.ORIGIN).origin] : [], ...mcpAllowedOrigins()]);
21380
21380
  }
21381
21381
  function challengeFor(origin) {
21382
- return oauthConfigured() ? {
21382
+ const oauth = oauthServer(origin);
21383
+ return oauth ? {
21383
21384
  resourceMetadataUrl: resourceMetadataUrl(origin),
21384
- scopes: [...REGISTERED_CLIENT_SCOPES]
21385
+ scopes: [...oauth.registeredScopes]
21385
21386
  } : void 0;
21386
21387
  }
21387
21388
  var MAX_CACHED_ORIGINS = 4;