@lovable.dev/mcp-js 0.22.1 → 0.22.2-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/dist/authorize-CumVyk7p.d.cts +27 -0
  2. package/dist/authorize-D6p4-9_D.d.ts +27 -0
  3. package/dist/base-DCe0kP79.d.cts +29 -0
  4. package/dist/base-DCe0kP79.d.ts +29 -0
  5. package/dist/cli/extract-manifest.cjs +116 -201
  6. package/dist/cli/extract-manifest.d.cts +1 -1
  7. package/dist/cli/extract-manifest.d.ts +1 -1
  8. package/dist/cli/extract-manifest.js +117 -156
  9. package/dist/content-D5LJAHyM.js +12 -0
  10. package/dist/content-NCYIGgOb.cjs +17 -0
  11. package/dist/context-BweeEcoA.cjs +56 -0
  12. package/dist/context-CIpPzN7P.js +51 -0
  13. package/dist/cors-CSDhBjFd.cjs +913 -0
  14. package/dist/cors-rWp_tbLZ.js +830 -0
  15. package/dist/forwarded--h4efJy-.js +43 -0
  16. package/dist/forwarded-Pi8Hs5Ps.cjs +48 -0
  17. package/dist/fs-errors-CWNzOV75.cjs +11 -0
  18. package/dist/fs-errors-PA2t1TIp.js +6 -0
  19. package/dist/index.cjs +129 -329
  20. package/dist/index.d.cts +26 -26
  21. package/dist/index.d.ts +26 -26
  22. package/dist/index.js +118 -177
  23. package/dist/{io-D4srzRKc.d.ts → io-CfSPxeBN.d.ts} +6 -4
  24. package/dist/io-DPYvBqET.d.cts +15 -0
  25. package/dist/list-tools-B4TTPEl1.d.cts +8 -0
  26. package/dist/list-tools-CFUX-uo-.cjs +57 -0
  27. package/dist/list-tools-DVJrjtmH.js +46 -0
  28. package/dist/list-tools-bh6-eqZM.d.ts +8 -0
  29. package/dist/logger-2OXtfiIW.js +141 -0
  30. package/dist/logger-BqPOa_E1.cjs +194 -0
  31. package/dist/mcp-BNcpj8o7.cjs +128 -0
  32. package/dist/mcp-Bx3bJHzH.js +123 -0
  33. package/dist/metadata-path-CAkNcfyY.js +12 -0
  34. package/dist/metadata-path-zd7NSNoa.cjs +17 -0
  35. package/dist/package-CgwD4Ywz.js +4 -0
  36. package/dist/package-DzstF8Ih.cjs +9 -0
  37. package/dist/paths-IS65L6TA.js +7 -0
  38. package/dist/paths-OP318a6c.cjs +18 -0
  39. package/dist/protocols/mcp/index.cjs +3 -750
  40. package/dist/protocols/mcp/index.d.cts +6 -7
  41. package/dist/protocols/mcp/index.d.ts +6 -7
  42. package/dist/protocols/mcp/index.js +2 -12
  43. package/dist/protocols/oauth-metadata.cjs +48 -539
  44. package/dist/protocols/oauth-metadata.d.cts +5 -6
  45. package/dist/protocols/oauth-metadata.d.ts +5 -6
  46. package/dist/protocols/oauth-metadata.js +52 -10
  47. package/dist/protocols/rest/index.cjs +5 -843
  48. package/dist/protocols/rest/index.d.cts +7 -10
  49. package/dist/protocols/rest/index.d.ts +7 -10
  50. package/dist/protocols/rest/index.js +3 -16
  51. package/dist/rest-BRshnow2.js +117 -0
  52. package/dist/rest-C4ZEGSIV.cjs +122 -0
  53. package/dist/stacks/supabase/index.cjs +76 -1318
  54. package/dist/stacks/supabase/index.d.cts +29 -30
  55. package/dist/stacks/supabase/index.d.ts +29 -30
  56. package/dist/stacks/supabase/index.js +73 -89
  57. package/dist/stacks/supabase/vite.cjs +258 -287
  58. package/dist/stacks/supabase/vite.d.cts +24 -24
  59. package/dist/stacks/supabase/vite.d.ts +24 -24
  60. package/dist/stacks/supabase/vite.js +252 -252
  61. package/dist/stacks/tanstack/index.cjs +42 -1272
  62. package/dist/stacks/tanstack/index.d.cts +8 -9
  63. package/dist/stacks/tanstack/index.d.ts +8 -9
  64. package/dist/stacks/tanstack/index.js +36 -41
  65. package/dist/stacks/tanstack/vite.cjs +223 -312
  66. package/dist/stacks/tanstack/vite.d.cts +80 -81
  67. package/dist/stacks/tanstack/vite.d.ts +80 -81
  68. package/dist/stacks/tanstack/vite.js +216 -282
  69. package/dist/types-BYdYYTjk.d.cts +321 -0
  70. package/dist/types-BYdYYTjk.d.ts +321 -0
  71. package/package.json +4 -4
  72. package/dist/authorize-BMeXd_Sh.d.ts +0 -25
  73. package/dist/base-CM-KCpp6.d.ts +0 -28
  74. package/dist/chunk-5HVSJCKE.js +0 -114
  75. package/dist/chunk-6DXGZZA4.js +0 -6
  76. package/dist/chunk-6QFZYYUV.js +0 -11
  77. package/dist/chunk-6SZOFKGH.js +0 -58
  78. package/dist/chunk-H37EB22A.js +0 -125
  79. package/dist/chunk-IFDWUM7L.js +0 -741
  80. package/dist/chunk-IXZIFYO6.js +0 -79
  81. package/dist/chunk-MA5H6PSF.js +0 -46
  82. package/dist/chunk-TJN33K5U.js +0 -141
  83. package/dist/chunk-UQK5UO6C.js +0 -26
  84. package/dist/chunk-XQWJN6DC.js +0 -14
  85. package/dist/chunk-Y3ZFPEQH.js +0 -8
  86. package/dist/chunk-ZQXSWTPU.js +0 -6
  87. package/dist/types-qqrmJ736.d.ts +0 -321
@@ -1,8 +1,7 @@
1
- import { M as McpRuntimeOptions } from '../../authorize-BMeXd_Sh.js';
2
- import { d as McpDefinition } from '../../types-qqrmJ736.js';
3
- import { M as MetricsRecorder } from '../../base-CM-KCpp6.js';
4
- import 'zod';
5
-
1
+ import { c as McpDefinition } from "../../types-BYdYYTjk.cjs";
2
+ import { t as MetricsRecorder } from "../../base-DCe0kP79.cjs";
3
+ import { t as McpRuntimeOptions } from "../../authorize-CumVyk7p.cjs";
4
+ //#region src/protocols/mcp/protocol.d.ts
6
5
  type McpProtocolHandler = (request: Request, recorder?: MetricsRecorder) => Promise<Response>;
7
6
  /**
8
7
  * Build a Web-Standard request handler that serves the MCP protocol over
@@ -12,5 +11,5 @@ type McpProtocolHandler = (request: Request, recorder?: MetricsRecorder) => Prom
12
11
  * caller (the stack handler) so telemetry reads the runtime env in-flight.
13
12
  */
14
13
  declare function createMcpProtocolHandler(mcp: McpDefinition, options?: McpRuntimeOptions): McpProtocolHandler;
15
-
16
- export { type McpProtocolHandler, createMcpProtocolHandler };
14
+ //#endregion
15
+ export { type McpProtocolHandler, createMcpProtocolHandler };
@@ -1,8 +1,7 @@
1
- import { M as McpRuntimeOptions } from '../../authorize-BMeXd_Sh.js';
2
- import { d as McpDefinition } from '../../types-qqrmJ736.js';
3
- import { M as MetricsRecorder } from '../../base-CM-KCpp6.js';
4
- import 'zod';
5
-
1
+ import { c as McpDefinition } from "../../types-BYdYYTjk.js";
2
+ import { t as MetricsRecorder } from "../../base-DCe0kP79.js";
3
+ import { t as McpRuntimeOptions } from "../../authorize-D6p4-9_D.js";
4
+ //#region src/protocols/mcp/protocol.d.ts
6
5
  type McpProtocolHandler = (request: Request, recorder?: MetricsRecorder) => Promise<Response>;
7
6
  /**
8
7
  * Build a Web-Standard request handler that serves the MCP protocol over
@@ -12,5 +11,5 @@ type McpProtocolHandler = (request: Request, recorder?: MetricsRecorder) => Prom
12
11
  * caller (the stack handler) so telemetry reads the runtime env in-flight.
13
12
  */
14
13
  declare function createMcpProtocolHandler(mcp: McpDefinition, options?: McpRuntimeOptions): McpProtocolHandler;
15
-
16
- export { type McpProtocolHandler, createMcpProtocolHandler };
14
+ //#endregion
15
+ export { type McpProtocolHandler, createMcpProtocolHandler };
@@ -1,12 +1,2 @@
1
- import {
2
- createMcpProtocolHandler
3
- } from "../../chunk-5HVSJCKE.js";
4
- import "../../chunk-6QFZYYUV.js";
5
- import "../../chunk-MA5H6PSF.js";
6
- import "../../chunk-IFDWUM7L.js";
7
- import "../../chunk-H37EB22A.js";
8
- import "../../chunk-6DXGZZA4.js";
9
- import "../../chunk-ZQXSWTPU.js";
10
- export {
11
- createMcpProtocolHandler
12
- };
1
+ import { t as createMcpProtocolHandler } from "../../mcp-Bx3bJHzH.js";
2
+ export { createMcpProtocolHandler };
@@ -1,544 +1,53 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/protocols/oauth-metadata.ts
21
- var oauth_metadata_exports = {};
22
- __export(oauth_metadata_exports, {
23
- createOAuthProtectedResourceMetadataHandler: () => createOAuthProtectedResourceMetadataHandler
24
- });
25
- module.exports = __toCommonJS(oauth_metadata_exports);
26
-
27
- // src/core/http.ts
28
- var JSON_HEADERS = { "Content-Type": "application/json" };
29
- function headResponse(response) {
30
- return new Response(null, { status: response.status, statusText: response.statusText, headers: response.headers });
31
- }
32
- function methodNotAllowed(allow) {
33
- return new Response(JSON.stringify({ error: "method not allowed" }), {
34
- status: 405,
35
- headers: { ...JSON_HEADERS, Allow: allow }
36
- });
37
- }
38
-
39
- // src/core/logger.ts
40
- var LEVEL_RANK = { silent: 0, error: 1, warn: 2, info: 3, debug: 4 };
41
- function isLogLevel(value) {
42
- return typeof value === "string" && value in LEVEL_RANK;
43
- }
44
- var LOG_LEVEL_ENV_VAR = "LOVABLE_MCP_LOG_LEVEL";
45
- function readEnvLevel() {
46
- try {
47
- const raw = typeof process !== "undefined" ? process.env?.[LOG_LEVEL_ENV_VAR] : void 0;
48
- const normalized = raw?.trim().toLowerCase();
49
- return isLogLevel(normalized) ? normalized : void 0;
50
- } catch {
51
- return void 0;
52
- }
53
- }
54
- var currentLevel = readEnvLevel() ?? "debug";
55
- function enabled(level) {
56
- return LEVEL_RANK[level] <= LEVEL_RANK[currentLevel];
57
- }
58
- function emit(level, method, event, fields) {
59
- if (!enabled(level))
60
- return;
61
- const message = `[mcp-js] ${event}`;
62
- if (fields)
63
- console[method](message, fields);
64
- else
65
- console[method](message);
66
- }
67
- var log = {
68
- error: (event, fields) => emit("error", "error", event, fields),
69
- warn: (event, fields) => emit("warn", "warn", event, fields),
70
- info: (event, fields) => emit("info", "info", event, fields),
71
- debug: (event, fields) => emit("debug", "debug", event, fields)
72
- };
73
- function describeError(err) {
74
- if (err instanceof Error) {
75
- const code = err.code;
76
- return { name: err.name, message: err.message, ...typeof code === "string" ? { code } : {} };
77
- }
78
- return { value: String(err) };
79
- }
80
-
81
- // src/core/promise.ts
82
- function cachedPromise(load, label) {
83
- let settled = false;
84
- let value;
85
- return async () => {
86
- if (settled) {
87
- if (label)
88
- log.debug(`${label}.cache_hit`);
89
- return value;
90
- }
91
- if (label)
92
- log.debug(`${label}.load_start`);
93
- try {
94
- const loaded = await load();
95
- settled = true;
96
- value = loaded;
97
- if (label)
98
- log.debug(`${label}.settled`);
99
- return loaded;
100
- } catch (err) {
101
- if (label)
102
- log.debug(`${label}.load_failed`, describeError(err));
103
- throw err;
104
- }
105
- };
106
- }
107
-
108
- // src/core/url.ts
109
- function trimTrailingSlash(value) {
110
- return value.replace(/\/+$/, "");
111
- }
112
- function isLocalHTTPHost(hostname) {
113
- return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
114
- }
115
- function urlSafetyProblem(url) {
116
- const isAllowedHTTP = url.protocol === "http:" && isLocalHTTPHost(url.hostname);
117
- if (url.protocol !== "https:" && !isAllowedHTTP) {
118
- return "must use https://, except localhost development URLs";
119
- }
120
- if (url.username || url.password) {
121
- return "must not include credentials";
122
- }
123
- if (url.search || url.hash) {
124
- return "must not include query or fragment";
125
- }
126
- return void 0;
127
- }
128
-
129
- // src/core/validation.ts
130
- function parseSafeUrl(subject, raw, ErrorClass = Error) {
131
- let url;
132
- try {
133
- url = new URL(raw);
134
- } catch {
135
- throw new ErrorClass(`${subject} must be an absolute URL`);
136
- }
137
- const problem = urlSafetyProblem(url);
138
- if (problem) {
139
- throw new ErrorClass(`${subject} ${problem}`);
140
- }
141
- return url;
142
- }
143
-
144
- // src/auth/discovery.ts
145
- var OAuthConfigurationError = class extends Error {
146
- constructor(message) {
147
- super(message);
148
- this.name = "OAuthConfigurationError";
149
- }
150
- };
151
- var METADATA_FETCH_TIMEOUT_MS = 5e3;
152
- function issuerPath(url) {
153
- const path = trimTrailingSlash(url.pathname);
154
- return path === "" ? void 0 : path;
155
- }
156
- function pathInsertedOAuthMetadataUrls(url, path) {
157
- return [
158
- `${url.origin}/.well-known/oauth-authorization-server${path}`,
159
- `${url.origin}/.well-known/openid-configuration${path}`
160
- ];
161
- }
162
- function oauthMetadataUrlsForIssuer(issuer) {
163
- const normalizedIssuer = trimTrailingSlash(issuer);
164
- const url = new URL(normalizedIssuer);
165
- const path = issuerPath(url);
166
- if (!path) {
167
- return [
168
- `${normalizedIssuer}/.well-known/oauth-authorization-server`,
169
- `${normalizedIssuer}/.well-known/openid-configuration`
170
- ];
171
- }
172
- return [...pathInsertedOAuthMetadataUrls(url, path), `${normalizedIssuer}/.well-known/openid-configuration`];
173
- }
174
- async function fetchFirstValidOAuthServerMetadata(metadataUrls, expectedIssuer) {
175
- const errors = [];
176
- for (const url of metadataUrls) {
177
- try {
178
- return await fetchOAuthServerMetadata(url, expectedIssuer);
179
- } catch (err) {
180
- log.debug("oauth.discovery.attempt_failed", { url, ...describeError(err) });
181
- errors.push(`${url}: ${err instanceof Error ? err.message : String(err)}`);
182
- }
183
- }
184
- log.error("oauth.discovery.exhausted", { expectedIssuer, urlsTried: metadataUrls, errors });
185
- throw new Error(`failed to discover OAuth server metadata (${errors.join("; ")})`);
186
- }
187
- async function fetchOAuthServerMetadata(url, expectedIssuer) {
188
- log.debug("oauth.discovery.fetch", { url });
189
- const response = await fetch(url, { signal: AbortSignal.timeout(METADATA_FETCH_TIMEOUT_MS), redirect: "manual" });
190
- if (!response.ok) {
191
- throw new Error(String(response.status));
192
- }
193
- const json = await response.json();
194
- if (typeof json.issuer !== "string") {
195
- throw new Error("missing issuer");
196
- }
197
- parseSafeUrl("discovered issuer", json.issuer);
198
- if (trimTrailingSlash(json.issuer) !== expectedIssuer) {
199
- log.warn("oauth.discovery.issuer_mismatch", { url, expectedIssuer, published: json.issuer });
200
- throw new Error("issuer mismatch");
201
- }
202
- if (typeof json.jwks_uri !== "string") {
203
- throw new Error("missing jwks_uri");
204
- }
205
- parseSafeUrl("discovered jwks_uri", json.jwks_uri);
206
- return { issuer: json.issuer, jwks_uri: json.jwks_uri };
207
- }
208
- async function fetchIssuerOAuthServerMetadata(issuer) {
209
- try {
210
- return await fetchFirstValidOAuthServerMetadata(oauthMetadataUrlsForIssuer(issuer), issuer);
211
- } catch (err) {
212
- log.error("oauth.discovery.config_error", {
213
- issuer,
214
- ...describeError(err),
215
- outcome: "500 oauth configuration error"
216
- });
217
- throw new OAuthConfigurationError(
218
- `OAuth issuer discovery failed: ${err instanceof Error ? err.message : String(err)}`
219
- );
220
- }
221
- }
222
- function createOAuthDiscoveryResolver(auth) {
223
- const configuredIssuer = trimTrailingSlash(auth.issuer);
224
- const oauthServerMetadata = cachedPromise(
225
- () => fetchIssuerOAuthServerMetadata(configuredIssuer),
226
- "oauth.discovery.metadata"
227
- );
228
- return {
229
- resolveIssuer: async () => configuredIssuer,
230
- resolveJwksUri: async () => {
231
- if (auth.jwksUri) {
232
- log.debug("oauth.jwks.resolved", { jwksUri: auth.jwksUri, source: "configured" });
233
- return auth.jwksUri;
234
- }
235
- const jwksUri = (await oauthServerMetadata()).jwks_uri;
236
- log.debug("oauth.jwks.resolved", { jwksUri, source: "discovered" });
237
- return jwksUri;
238
- }
239
- };
240
- }
241
-
242
- // src/auth/resource.ts
243
- function resolveProtectedResource(auth, request, options) {
244
- if (auth.resource)
245
- return trimTrailingSlash(auth.resource);
246
- const path = resolveResourcePath(options.resourcePath, request);
247
- const resourceURL = new URL(path, request.url);
248
- resourceURL.search = "";
249
- resourceURL.hash = "";
250
- return trimTrailingSlash(resourceURL.toString());
251
- }
252
- function assertResourcePathShape(resourcePath, label = "resourcePath") {
253
- if (!resourcePath.startsWith("/") || resourcePath.startsWith("//") || resourcePath.includes("\\") || /(^|\/)\.\.(\/|$)/.test(resourcePath)) {
254
- throw new Error(
255
- `@lovable.dev/mcp-js: ${label} must be an absolute path beginning with "/" without ".." segments or backslashes (got ${JSON.stringify(resourcePath)})`
256
- );
257
- }
258
- }
259
- function resolveResourcePath(resourcePath, request) {
260
- if (resourcePath === void 0)
261
- return new URL(request.url).pathname;
262
- assertResourcePathShape(resourcePath);
263
- return resourcePath;
264
- }
265
-
266
- // src/auth/verifier.ts
267
- var import_jose = require("jose");
268
-
269
- // src/auth/claims.ts
270
- function readString(value) {
271
- return typeof value === "string" ? value : void 0;
272
- }
273
- function splitScopes(value) {
274
- if (typeof value === "string")
275
- return value.split(/\s+/).filter(Boolean);
276
- return stringClaimList(value);
277
- }
278
- function stringClaim(claims, name) {
279
- return readString(claims[name]);
280
- }
281
- function stringClaimList(value) {
282
- if (typeof value === "string")
283
- return value === "" ? [] : [value];
284
- if (Array.isArray(value))
285
- return value.filter((entry) => typeof entry === "string" && entry !== "");
286
- return [];
287
- }
288
-
289
- // src/auth/verifier.ts
290
- var DEFAULT_JWT_ALGORITHMS = ["RS256", "RS384", "RS512", "ES256", "ES384", "ES512", "EdDSA"];
291
- var DEFAULT_CLOCK_TOLERANCE_SECONDS = 30;
292
- var DEFAULT_ACCESS_TOKEN_TYPS = ["at+jwt", "JWT"];
293
- var JWKS_FETCH_TIMEOUT_MS = 5e3;
294
- var OAuthTokenError = class extends Error {
295
- constructor(status, oauthError, message) {
296
- super(message);
297
- this.status = status;
298
- this.oauthError = oauthError;
299
- this.name = "OAuthTokenError";
300
- }
301
- };
302
- function resolveAcceptedAudiences(auth, resource) {
303
- return auth.acceptedAudiences ?? [resource];
304
- }
305
- function tokenHeaderFields(token) {
306
- try {
307
- const header = (0, import_jose.decodeProtectedHeader)(token);
308
- return { jwtAlg: header.alg, jwtKid: header.kid, tokenLength: token.length };
309
- } catch {
310
- return { tokenLength: token.length };
311
- }
312
- }
313
- async function fetchVerificationKeySet(jwksUri) {
314
- try {
315
- const response = await fetch(jwksUri, { signal: AbortSignal.timeout(JWKS_FETCH_TIMEOUT_MS), redirect: "manual" });
316
- if (!response.ok)
317
- throw new Error(`JWKS endpoint returned ${response.status}`);
318
- const json = await response.json();
319
- return (0, import_jose.createLocalJWKSet)(json);
320
- } catch (err) {
321
- log.error("oauth.jwks.fetch_failed", { ...describeError(err), outcome: "500 oauth configuration error" });
322
- throw new OAuthConfigurationError(`JWKS fetch failed: ${err instanceof Error ? err.message : String(err)}`);
323
- }
324
- }
325
- function assertAccessTokenTyp(token, allowed) {
326
- let header;
327
- try {
328
- header = (0, import_jose.decodeProtectedHeader)(token);
329
- } catch (err) {
330
- log.debug("oauth.verify.bad_header", { ...describeError(err), outcome: "401 invalid_token" });
331
- throw new OAuthTokenError(401, "invalid_token", "Malformed JWT header");
332
- }
333
- const typ = header.typ;
334
- if (typeof typ !== "string" || !allowed.includes(typ)) {
335
- log.debug("oauth.verify.bad_typ", { jwtTyp: typ, allowed, outcome: "401 invalid_token" });
336
- throw new OAuthTokenError(401, "invalid_token", "Access token typ header is not accepted");
337
- }
338
- }
339
- async function verifyJwtClaims(token, keySet, issuer, auth) {
340
- try {
341
- const { payload } = await (0, import_jose.jwtVerify)(token, keySet, {
342
- // `issuer` is trimmed of any trailing slash; accept both forms so a token whose
343
- // `iss` carries the slash the AS publishes still verifies.
344
- issuer: [issuer, `${issuer}/`],
345
- algorithms: auth.algorithms ? [...auth.algorithms] : DEFAULT_JWT_ALGORITHMS,
346
- requiredClaims: ["sub", "exp"],
347
- clockTolerance: auth.clockToleranceSeconds ?? DEFAULT_CLOCK_TOLERANCE_SECONDS
348
- });
349
- return payload;
350
- } catch (err) {
351
- log.debug("oauth.verify.rejected", { ...describeError(err), outcome: "401 invalid_token" });
352
- throw err;
353
- }
354
- }
355
- function checkAcceptedAudience(claims, accepted, auth) {
356
- const audPopulated = claims.aud !== void 0 && !(Array.isArray(claims.aud) && claims.aud.length === 0);
357
- if (audPopulated) {
358
- if (stringClaimList(claims.aud).some((audience) => accepted.includes(audience)))
359
- return "aud";
360
- log.debug("oauth.verify.bad_audience", { tokenAud: claims.aud, accepted, outcome: "401 invalid_token" });
361
- } else if (auth.acceptResourceClaim !== false) {
362
- const acceptedTrimmed = accepted.map(trimTrailingSlash);
363
- if (stringClaimList(claims.resource).some((resource) => acceptedTrimmed.includes(trimTrailingSlash(resource))))
364
- return "resource";
365
- log.debug("oauth.verify.bad_resource", { tokenResource: claims.resource, accepted, outcome: "401 invalid_token" });
366
- } else {
367
- log.debug("oauth.verify.empty_audience", { accepted, outcome: "401 invalid_token" });
368
- }
369
- throw new OAuthTokenError(401, "invalid_token", "token audience is not accepted");
370
- }
371
- function assertNonEmptySubject(claims) {
372
- const sub = claims["sub"];
373
- if (typeof sub !== "string" || sub.trim() === "") {
374
- log.debug("oauth.verify.bad_subject", { subType: typeof sub });
375
- throw new OAuthTokenError(401, "invalid_token", "token subject claim must be a non-empty string");
376
- }
377
- }
378
- function assertOAuthClientClaim(auth, clientId) {
379
- if (auth.requireOAuthClientClaim !== false && !clientId) {
380
- log.debug("oauth.verify.missing_client_claim", { outcome: "401 invalid_token" });
381
- throw new OAuthTokenError(401, "invalid_token", "OAuth client claim is required");
382
- }
383
- }
384
- function makeBearer(token) {
385
- return Object.defineProperty({}, "token", { value: token, enumerable: false });
386
- }
387
- function buildMcpAuthContext(args) {
388
- const { claims } = args;
389
- return {
390
- type: "oauth",
391
- principal: {
392
- claims,
393
- issuer: args.issuer,
394
- resource: args.resource,
395
- acceptedAudiences: args.acceptedAudiences,
396
- scopes: splitScopes(claims.scope),
397
- sub: stringClaim(claims, "sub"),
398
- email: stringClaim(claims, "email"),
399
- clientId: stringClaim(claims, "client_id") ?? stringClaim(claims, "azp")
400
- },
401
- bearer: makeBearer(args.token)
402
- };
403
- }
404
- function createOAuthTokenVerifier(auth, discovery) {
405
- const allowedTyps = auth.accessTokenTyp ?? DEFAULT_ACCESS_TOKEN_TYPS;
406
- return async (token, request, options) => {
407
- const resource = resolveProtectedResource(auth, request, options);
408
- const issuer = await discovery.resolveIssuer();
409
- const acceptedAudiences = resolveAcceptedAudiences(auth, resource);
410
- log.debug("oauth.verify.start", { issuer, acceptedAudiences, resource, ...tokenHeaderFields(token) });
411
- const jwksUri = await discovery.resolveJwksUri();
412
- log.debug("oauth.jwks.fetch", { jwksUri });
413
- const keySet = await fetchVerificationKeySet(jwksUri);
414
- assertAccessTokenTyp(token, allowedTyps);
415
- const claims = await verifyJwtClaims(token, keySet, issuer, auth);
416
- const audienceVia = checkAcceptedAudience(claims, acceptedAudiences, auth);
417
- assertNonEmptySubject(claims);
418
- const context = buildMcpAuthContext({ token, claims, issuer, resource, acceptedAudiences });
419
- assertOAuthClientClaim(auth, context.principal.clientId);
420
- log.info("oauth.verify.ok", {
421
- sub: context.principal.sub,
422
- clientId: context.principal.clientId,
423
- scopes: context.principal.scopes,
424
- audienceVia
425
- });
426
- return context;
427
- };
428
- }
429
-
430
- // src/auth/authorize.ts
431
- function oauthConfigurationErrorResponse() {
432
- return new Response(JSON.stringify({ error: "oauth configuration error" }), {
433
- status: 500,
434
- headers: { ...JSON_HEADERS, "Cache-Control": "no-store" }
435
- });
436
- }
437
- function getOAuthRuntime(mcp, options = {}) {
438
- if (options.resourcePath !== void 0)
439
- assertResourcePathShape(options.resourcePath);
440
- if (options.metadataPath !== void 0)
441
- assertResourcePathShape(options.metadataPath, "metadataPath");
442
- const stableOptions = { resourcePath: options.resourcePath, metadataPath: options.metadataPath };
443
- const auth = mcp.auth?.type === "oauth" ? mcp.auth : void 0;
444
- if (!auth)
445
- return { kind: "unconfigured", options: stableOptions };
446
- if (options.metadataPath !== void 0 && auth.protectedResourceMetadataUrl !== void 0) {
447
- throw new Error(
448
- `@lovable.dev/mcp-js: the Vite plugin generates protected-resource metadata (metadataPath set), so auth.protectedResourceMetadataUrl must not also be set. Drop protectedResourceMetadataUrl, or set protectedResourceMetadataRoute: false in mcpPlugin(...) to host the document yourself.`
449
- );
450
- }
451
- const discovery = createOAuthDiscoveryResolver(auth);
452
- return {
453
- kind: "configured",
454
- auth,
455
- discovery,
456
- verify: createOAuthTokenVerifier(auth, discovery),
457
- options: stableOptions
458
- };
459
- }
460
-
461
- // src/core/cors.ts
462
- var EXPOSE_HEADERS = "WWW-Authenticate, Mcp-Session-Id, Mcp-Protocol-Version";
463
- var ALLOW_HEADERS = "Authorization, Content-Type, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID";
464
- function withCors(response) {
465
- response.headers.set("Access-Control-Allow-Origin", "*");
466
- response.headers.set("Access-Control-Expose-Headers", EXPOSE_HEADERS);
467
- return response;
468
- }
469
- function corsPreflightResponse(allowMethods) {
470
- return new Response(null, {
471
- status: 204,
472
- headers: {
473
- "Access-Control-Allow-Origin": "*",
474
- "Access-Control-Allow-Methods": allowMethods,
475
- "Access-Control-Allow-Headers": ALLOW_HEADERS,
476
- "Access-Control-Max-Age": "86400"
477
- }
478
- });
479
- }
480
-
481
- // src/protocols/oauth-metadata.ts
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_logger = require("../logger-BqPOa_E1.cjs");
3
+ const require_cors = require("../cors-CSDhBjFd.cjs");
4
+ //#region src/protocols/oauth-metadata.ts
482
5
  function notFound() {
483
- return withCors(
484
- new Response(JSON.stringify({ error: "not found" }), {
485
- status: 404,
486
- // `no-store` so a 404 (OAuth unconfigured) isn't heuristically cached and
487
- // then served past a later deploy that enables OAuth and starts returning 200.
488
- headers: { ...JSON_HEADERS, "Cache-Control": "no-store" }
489
- })
490
- );
6
+ return require_cors.withCors(new Response(JSON.stringify({ error: "not found" }), {
7
+ status: 404,
8
+ headers: {
9
+ ...require_cors.JSON_HEADERS,
10
+ "Cache-Control": "no-store"
11
+ }
12
+ }));
491
13
  }
492
14
  async function buildProtectedResourceMetadata(mcp, auth, request, options, discovery) {
493
- const issuer = await discovery.resolveIssuer();
494
- const body = {
495
- resource: resolveProtectedResource(auth, request, options),
496
- authorization_servers: [issuer],
497
- bearer_methods_supported: ["header"],
498
- resource_name: auth.resourceName ?? mcp.title,
499
- resource_documentation: auth.resourceDocumentation
500
- };
501
- if (auth.requiredScopes && auth.requiredScopes.length > 0)
502
- body.scopes_supported = auth.requiredScopes;
503
- return body;
15
+ const issuer = await discovery.resolveIssuer();
16
+ const body = {
17
+ resource: require_cors.resolveProtectedResource(auth, request, options),
18
+ authorization_servers: [issuer],
19
+ bearer_methods_supported: ["header"],
20
+ resource_name: auth.resourceName ?? mcp.title,
21
+ resource_documentation: auth.resourceDocumentation
22
+ };
23
+ if (auth.requiredScopes && auth.requiredScopes.length > 0) body.scopes_supported = auth.requiredScopes;
24
+ return body;
504
25
  }
505
26
  function createOAuthProtectedResourceMetadataHandler(mcp, options = {}) {
506
- const runtime = getOAuthRuntime(mcp, options);
507
- if (runtime.kind === "configured" && runtime.auth.protectedResourceMetadataUrl === void 0 && runtime.auth.resource === void 0 && runtime.options.resourcePath === void 0) {
508
- throw new Error(
509
- `@lovable.dev/mcp-js: auth.resource or a resourcePath is required so the protected-resource metadata doesn't advertise the well-known URL as the resource`
510
- );
511
- }
512
- return async (request) => {
513
- if (runtime.kind !== "configured" || runtime.auth.protectedResourceMetadataUrl !== void 0)
514
- return notFound();
515
- if (request.method === "OPTIONS")
516
- return corsPreflightResponse("GET, HEAD, OPTIONS");
517
- if (request.method !== "GET" && request.method !== "HEAD")
518
- return withCors(methodNotAllowed("GET, HEAD, OPTIONS"));
519
- const headers = {
520
- ...JSON_HEADERS,
521
- "Cache-Control": "public, max-age=300",
522
- Vary: "Host"
523
- };
524
- try {
525
- const metadata = await buildProtectedResourceMetadata(
526
- mcp,
527
- runtime.auth,
528
- request,
529
- runtime.options,
530
- runtime.discovery
531
- );
532
- const response = withCors(Response.json(metadata, { headers }));
533
- return request.method === "HEAD" ? headResponse(response) : response;
534
- } catch (err) {
535
- log.error("oauth.metadata.config_error", { ...describeError(err), outcome: "500 oauth configuration error" });
536
- const response = withCors(oauthConfigurationErrorResponse());
537
- return request.method === "HEAD" ? headResponse(response) : response;
538
- }
539
- };
540
- }
541
- // Annotate the CommonJS export names for ESM import in node:
542
- 0 && (module.exports = {
543
- createOAuthProtectedResourceMetadataHandler
544
- });
27
+ const runtime = require_cors.getOAuthRuntime(mcp, options);
28
+ if (runtime.kind === "configured" && runtime.auth.protectedResourceMetadataUrl === void 0 && runtime.auth.resource === void 0 && runtime.options.resourcePath === void 0) throw new Error(`@lovable.dev/mcp-js: auth.resource or a resourcePath is required so the protected-resource metadata doesn't advertise the well-known URL as the resource`);
29
+ return async (request) => {
30
+ if (runtime.kind !== "configured" || runtime.auth.protectedResourceMetadataUrl !== void 0) return notFound();
31
+ if (request.method === "OPTIONS") return require_cors.corsPreflightResponse("GET, HEAD, OPTIONS");
32
+ if (request.method !== "GET" && request.method !== "HEAD") return require_cors.withCors(require_cors.methodNotAllowed("GET, HEAD, OPTIONS"));
33
+ const headers = {
34
+ ...require_cors.JSON_HEADERS,
35
+ "Cache-Control": "public, max-age=300",
36
+ Vary: "Host"
37
+ };
38
+ try {
39
+ const metadata = await buildProtectedResourceMetadata(mcp, runtime.auth, request, runtime.options, runtime.discovery);
40
+ const response = require_cors.withCors(Response.json(metadata, { headers }));
41
+ return request.method === "HEAD" ? require_cors.headResponse(response) : response;
42
+ } catch (err) {
43
+ require_logger.log.error("oauth.metadata.config_error", {
44
+ ...require_logger.describeError(err),
45
+ outcome: "500 oauth configuration error"
46
+ });
47
+ const response = require_cors.withCors(require_cors.oauthConfigurationErrorResponse());
48
+ return request.method === "HEAD" ? require_cors.headResponse(response) : response;
49
+ }
50
+ };
51
+ }
52
+ //#endregion
53
+ exports.createOAuthProtectedResourceMetadataHandler = createOAuthProtectedResourceMetadataHandler;
@@ -1,8 +1,7 @@
1
- import { M as McpRuntimeOptions } from '../authorize-BMeXd_Sh.js';
2
- import { d as McpDefinition } from '../types-qqrmJ736.js';
3
- import 'zod';
4
-
1
+ import { c as McpDefinition } from "../types-BYdYYTjk.cjs";
2
+ import { t as McpRuntimeOptions } from "../authorize-CumVyk7p.cjs";
3
+ //#region src/protocols/oauth-metadata.d.ts
5
4
  type OAuthProtectedResourceMetadataHandler = (request: Request) => Promise<Response>;
6
5
  declare function createOAuthProtectedResourceMetadataHandler(mcp: McpDefinition, options?: McpRuntimeOptions): OAuthProtectedResourceMetadataHandler;
7
-
8
- export { type OAuthProtectedResourceMetadataHandler, createOAuthProtectedResourceMetadataHandler };
6
+ //#endregion
7
+ export { OAuthProtectedResourceMetadataHandler, createOAuthProtectedResourceMetadataHandler };