@lovable.dev/mcp-js 0.21.0 → 0.21.1-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) 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-CFy5vZ5Z.d.ts → base-CoIFvAmS.d.cts} +15 -14
  4. package/dist/base-CoIFvAmS.d.ts +26 -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-B7CTXIHD.js +829 -0
  14. package/dist/cors-BebjKPrc.cjs +912 -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-CS4UL6_A.d.ts} +6 -4
  24. package/dist/io-CbbUbPY3.d.cts +15 -0
  25. package/dist/list-tools-CBCuS1Tv.cjs +57 -0
  26. package/dist/list-tools-CsWgiRy1.d.ts +8 -0
  27. package/dist/list-tools-CtZHOuPv.d.cts +8 -0
  28. package/dist/list-tools-D75RGtgs.js +46 -0
  29. package/dist/logger-2OXtfiIW.js +141 -0
  30. package/dist/logger-BqPOa_E1.cjs +194 -0
  31. package/dist/mcp-Cdj0AYst.cjs +123 -0
  32. package/dist/mcp-GngXbcqN.js +118 -0
  33. package/dist/metadata-path-CAkNcfyY.js +12 -0
  34. package/dist/metadata-path-zd7NSNoa.cjs +17 -0
  35. package/dist/package-7EUptuSJ.js +4 -0
  36. package/dist/package-BwCGVRcB.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 -740
  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 -839
  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-CXH6-zv9.js +113 -0
  52. package/dist/rest-CyV8LHeB.cjs +118 -0
  53. package/dist/stacks/supabase/index.cjs +76 -1302
  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 -1256
  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 +71 -28
  72. package/dist/authorize-BMeXd_Sh.d.ts +0 -25
  73. package/dist/chunk-6DXGZZA4.js +0 -6
  74. package/dist/chunk-6QFZYYUV.js +0 -11
  75. package/dist/chunk-CI7JYLV3.js +0 -104
  76. package/dist/chunk-E3Q3FRKQ.js +0 -6
  77. package/dist/chunk-ENJDNFEB.js +0 -79
  78. package/dist/chunk-H37EB22A.js +0 -125
  79. package/dist/chunk-LFXK3FNF.js +0 -58
  80. package/dist/chunk-MA5H6PSF.js +0 -46
  81. package/dist/chunk-QPKPYDPB.js +0 -137
  82. package/dist/chunk-UQK5UO6C.js +0 -26
  83. package/dist/chunk-XQWJN6DC.js +0 -14
  84. package/dist/chunk-Y3ZFPEQH.js +0 -8
  85. package/dist/chunk-YLU2JTHL.js +0 -739
  86. package/dist/types-qqrmJ736.d.ts +0 -321
@@ -0,0 +1,829 @@
1
+ import { c as DEFAULT_METRICS_ENDPOINT, i as log, l as resolveMetricsConfig, n as applyLogLevelFromEnv, o as parseSafeUrl, r as describeError, s as trimTrailingSlash, t as LOG_LEVEL_ENV_VAR } from "./logger-2OXtfiIW.js";
2
+ import { t as version } from "./package-7EUptuSJ.js";
3
+ import "./metadata-path-CAkNcfyY.js";
4
+ import { createLocalJWKSet, decodeProtectedHeader, jwtVerify } from "jose";
5
+ //#region src/core/http.ts
6
+ const JSON_HEADERS = { "Content-Type": "application/json" };
7
+ /** Strip the body from a built response, preserving status and headers, for HEAD. */
8
+ function headResponse(response) {
9
+ return new Response(null, {
10
+ status: response.status,
11
+ statusText: response.statusText,
12
+ headers: response.headers
13
+ });
14
+ }
15
+ function methodNotAllowed(allow) {
16
+ return new Response(JSON.stringify({ error: "method not allowed" }), {
17
+ status: 405,
18
+ headers: {
19
+ ...JSON_HEADERS,
20
+ Allow: allow
21
+ }
22
+ });
23
+ }
24
+ //#endregion
25
+ //#region src/metrics/otlp.ts
26
+ const SCOPE_NAME = "@lovable.dev/mcp-js";
27
+ const EVENT_NAME = "mcp.tool.invocation";
28
+ const SEVERITY_INFO = 9;
29
+ function strAttr(key, value) {
30
+ return {
31
+ key,
32
+ value: { stringValue: value }
33
+ };
34
+ }
35
+ function intAttr(key, value) {
36
+ return {
37
+ key,
38
+ value: { intValue: String(Math.round(value)) }
39
+ };
40
+ }
41
+ function toLogRecord(rec) {
42
+ const attributes = [
43
+ strAttr("event.name", EVENT_NAME),
44
+ strAttr("mcp.method", rec.method),
45
+ strAttr("mcp.outcome", rec.outcome),
46
+ intAttr("mcp.duration_ms", rec.durationMs)
47
+ ];
48
+ if (rec.tool !== null) attributes.push(strAttr("mcp.tool", rec.tool));
49
+ if (rec.reqBytes !== void 0) attributes.push(intAttr("mcp.request_size_bytes", rec.reqBytes));
50
+ if (rec.resBytes !== void 0) attributes.push(intAttr("mcp.response_size_bytes", rec.resBytes));
51
+ attributes.push(strAttr("mcp.stack", rec.stack));
52
+ return {
53
+ timeUnixNano: rec.timeUnixNano,
54
+ observedTimeUnixNano: rec.timeUnixNano,
55
+ severityNumber: SEVERITY_INFO,
56
+ severityText: "INFO",
57
+ body: { stringValue: EVENT_NAME },
58
+ attributes
59
+ };
60
+ }
61
+ /**
62
+ * Build an OTLP/HTTP JSON `ExportLogsServiceRequest` body for a batch of
63
+ * invocations. All records in a batch share one resource (the MCP server's
64
+ * identity); per-tenant attribution is derived server-side from the auth header,
65
+ * never from client-supplied resource attributes.
66
+ */
67
+ function buildLogsPayload(records, server) {
68
+ return JSON.stringify({ resourceLogs: [{
69
+ resource: { attributes: [
70
+ strAttr("service.name", server.name),
71
+ strAttr("service.version", server.version),
72
+ strAttr("telemetry.sdk.name", SCOPE_NAME),
73
+ strAttr("telemetry.sdk.version", version),
74
+ strAttr("telemetry.sdk.language", "webjs")
75
+ ] },
76
+ scopeLogs: [{
77
+ scope: {
78
+ name: SCOPE_NAME,
79
+ version
80
+ },
81
+ logRecords: records.map(toLogRecord)
82
+ }]
83
+ }] });
84
+ }
85
+ /** Wall-clock nanoseconds since the Unix epoch as a string, without losing
86
+ * precision to float64 (`Date.now()` ms × 1e6 would overflow 2^53). */
87
+ function nowUnixNano() {
88
+ return `${Date.now()}000000`;
89
+ }
90
+ //#endregion
91
+ //#region src/metrics/impl/base.ts
92
+ /** Monotonic-ish millisecond clock for latency timing, with a `Date.now` fallback
93
+ * for runtimes without `performance.now`. */
94
+ function nowMs() {
95
+ return typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now();
96
+ }
97
+ const NOOP_RECORDER = { async emit() {} };
98
+ function createNoopRecorder() {
99
+ return NOOP_RECORDER;
100
+ }
101
+ /** Guarded `process.env` read — the shared fallback both stacks use for local
102
+ * dev. Tolerates a missing `process` global. */
103
+ function readProcessEnv(name) {
104
+ try {
105
+ return typeof process !== "undefined" ? process.env?.[name] || void 0 : void 0;
106
+ } catch {
107
+ return;
108
+ }
109
+ }
110
+ /**
111
+ * Base per-request recorder. Owns everything stack-agnostic: log-level setup, the
112
+ * `tool.invoked` log, the single-record OTLP POST (awaited so it lands within the
113
+ * request — serverless workers kill detached work once the response returns), and
114
+ * never throwing into tool dispatch. Every invocation is reported (no sampling).
115
+ * Subclasses supply only the `stack` label and how to read env on that runtime.
116
+ *
117
+ * One instance is created per request by the stack handler and shared across
118
+ * every invocation in that request; it is never a process-wide singleton, since
119
+ * on Cloudflare the env binding isn't readable at module-init scope.
120
+ */
121
+ var BaseMetricRecorder = class {
122
+ config;
123
+ server;
124
+ deps;
125
+ doFetch;
126
+ usesLovableEndpoint;
127
+ baseHeaders;
128
+ apiKey;
129
+ lazyLogLevelApplied = false;
130
+ constructor(config, server, deps = {}) {
131
+ this.config = config;
132
+ this.server = server;
133
+ this.deps = deps;
134
+ this.doFetch = deps.fetch ?? (typeof globalThis.fetch === "function" ? globalThis.fetch.bind(globalThis) : void 0);
135
+ this.usesLovableEndpoint = config.endpoint === DEFAULT_METRICS_ENDPOINT;
136
+ const headers = {};
137
+ if (!this.usesLovableEndpoint) {
138
+ for (const [key, value] of Object.entries(config.headers)) if (key.toLowerCase() !== "content-type") headers[key] = value;
139
+ }
140
+ headers["content-type"] = "application/json";
141
+ this.baseHeaders = headers;
142
+ }
143
+ async emit(ev) {
144
+ await this.applyLazyLogLevel();
145
+ log.info("tool.invoked", {
146
+ tool: ev.tool,
147
+ method: ev.method,
148
+ outcome: ev.outcome,
149
+ durationMs: ev.durationMs,
150
+ stack: this.stack,
151
+ ...ev.errorText !== void 0 && { errorText: ev.errorText }
152
+ });
153
+ if (!this.config.enabled) return;
154
+ if (!this.doFetch) {
155
+ log.warn("metrics.disabled_no_fetch", { endpoint: this.config.endpoint });
156
+ return;
157
+ }
158
+ const headers = { ...this.baseHeaders };
159
+ if (this.usesLovableEndpoint) {
160
+ const key = await this.resolveApiKey();
161
+ if (!key) {
162
+ log.warn("metrics.disabled_no_api_key", {
163
+ envVar: this.config.apiKeyEnvVar,
164
+ endpoint: this.config.endpoint
165
+ });
166
+ return;
167
+ }
168
+ headers.authorization = `Bearer ${key}`;
169
+ }
170
+ const body = buildLogsPayload([{
171
+ ...ev,
172
+ timeUnixNano: nowUnixNano(),
173
+ stack: this.stack
174
+ }], this.server);
175
+ try {
176
+ const res = await this.doFetch(this.config.endpoint, {
177
+ method: "POST",
178
+ headers,
179
+ body,
180
+ keepalive: true
181
+ });
182
+ if (!res.ok) log.warn("metrics.rejected", {
183
+ status: res.status,
184
+ endpoint: this.config.endpoint
185
+ });
186
+ } catch (err) {
187
+ log.warn("metrics.failed", {
188
+ ...describeError(err),
189
+ endpoint: this.config.endpoint
190
+ });
191
+ }
192
+ }
193
+ async resolveApiKey() {
194
+ if (this.apiKey) return this.apiKey;
195
+ this.apiKey = this.deps.getApiKey ? this.deps.getApiKey() : await this.readEnv(this.config.apiKeyEnvVar);
196
+ return this.apiKey;
197
+ }
198
+ async applyLazyLogLevel() {
199
+ if (this.lazyLogLevelApplied) return;
200
+ this.lazyLogLevelApplied = true;
201
+ applyLogLevelFromEnv(await this.readEnv(LOG_LEVEL_ENV_VAR));
202
+ }
203
+ };
204
+ //#endregion
205
+ //#region src/metrics/impl/cloudflare.ts
206
+ let cloudflareEnvPromise;
207
+ async function readCloudflareEnv(name) {
208
+ try {
209
+ cloudflareEnvPromise ??= import(
210
+ /* @vite-ignore */
211
+ "cloudflare:workers"
212
+ ).then((m) => m.env).catch((err) => {
213
+ log.debug("metrics.cloudflare_env_import_failed", describeError(err));
214
+ });
215
+ const env = await cloudflareEnvPromise;
216
+ const raw = env?.[name];
217
+ const value = typeof raw === "string" && raw ? raw : void 0;
218
+ log.debug("metrics.read_cloudflare_env", {
219
+ name,
220
+ hasEnvBinding: !!env,
221
+ found: value !== void 0
222
+ });
223
+ return value;
224
+ } catch (err) {
225
+ log.debug("metrics.read_cloudflare_env_error", {
226
+ name,
227
+ ...describeError(err)
228
+ });
229
+ return;
230
+ }
231
+ }
232
+ /** TanStack apps deploy to Cloudflare Workers: secrets live on the `env` binding
233
+ * (read via `cloudflare:workers`), with `process.env` as the local-dev fallback. */
234
+ var TanStackMetricRecorder = class extends BaseMetricRecorder {
235
+ stack = "tanstack";
236
+ async readEnv(name) {
237
+ return readProcessEnv(name) ?? await readCloudflareEnv(name);
238
+ }
239
+ };
240
+ //#endregion
241
+ //#region src/metrics/impl/supabase.ts
242
+ function readDenoEnv(name) {
243
+ try {
244
+ const denoEnv = globalThis.Deno?.env;
245
+ const value = denoEnv?.get?.(name) || void 0;
246
+ log.debug("metrics.read_deno_env", {
247
+ name,
248
+ hasDenoEnv: !!denoEnv,
249
+ found: !!value
250
+ });
251
+ return value;
252
+ } catch (err) {
253
+ log.debug("metrics.read_deno_env_error", {
254
+ name,
255
+ ...describeError(err)
256
+ });
257
+ return;
258
+ }
259
+ }
260
+ /** Supabase Edge Functions run on Deno: secrets are in `Deno.env`, with
261
+ * `process.env` as a fallback — both synchronous, resolved into the promise. */
262
+ var SupabaseMetricRecorder = class extends BaseMetricRecorder {
263
+ stack = "supabase";
264
+ async readEnv(name) {
265
+ return readDenoEnv(name) ?? readProcessEnv(name);
266
+ }
267
+ };
268
+ //#endregion
269
+ //#region src/metrics/recorder.ts
270
+ /** Vend the recorder for a stack, in-flight per request. Returns a no-op when
271
+ * metrics are disabled (`metrics: false`); otherwise the stack-specific class,
272
+ * which still logs `tool.invoked` even if the key or endpoint is unavailable. */
273
+ function createRecorderForRuntime(mcp, opts) {
274
+ const config = resolveMetricsConfig(mcp.metrics);
275
+ const server = {
276
+ name: mcp.name,
277
+ version: mcp.version
278
+ };
279
+ if (!config.enabled) return createNoopRecorder();
280
+ return opts.stack === "tanstack" ? new TanStackMetricRecorder(config, server) : new SupabaseMetricRecorder(config, server);
281
+ }
282
+ //#endregion
283
+ //#region src/core/promise.ts
284
+ /**
285
+ * Caches only the fulfilled value: until one load resolves, concurrent callers
286
+ * each run their own `load()`; afterwards every call returns the cached value
287
+ * with no I/O. A rejection caches nothing, so the next call retries.
288
+ *
289
+ * Not single-flight by design. Sharing one in-flight promise across callers
290
+ * breaks on Cloudflare Workers, where a promise that owns pending I/O can't be
291
+ * awaited from a different request's I/O context.
292
+ */
293
+ function cachedPromise(load, label) {
294
+ let settled = false;
295
+ let value;
296
+ return async () => {
297
+ if (settled) {
298
+ if (label) log.debug(`${label}.cache_hit`);
299
+ return value;
300
+ }
301
+ if (label) log.debug(`${label}.load_start`);
302
+ try {
303
+ const loaded = await load();
304
+ settled = true;
305
+ value = loaded;
306
+ if (label) log.debug(`${label}.settled`);
307
+ return loaded;
308
+ } catch (err) {
309
+ if (label) log.debug(`${label}.load_failed`, describeError(err));
310
+ throw err;
311
+ }
312
+ };
313
+ }
314
+ //#endregion
315
+ //#region src/auth/discovery.ts
316
+ var OAuthConfigurationError = class extends Error {
317
+ constructor(message) {
318
+ super(message);
319
+ this.name = "OAuthConfigurationError";
320
+ }
321
+ };
322
+ const METADATA_FETCH_TIMEOUT_MS = 5e3;
323
+ function issuerPath(url) {
324
+ const path = trimTrailingSlash(url.pathname);
325
+ return path === "" ? void 0 : path;
326
+ }
327
+ function pathInsertedOAuthMetadataUrls(url, path) {
328
+ return [`${url.origin}/.well-known/oauth-authorization-server${path}`, `${url.origin}/.well-known/openid-configuration${path}`];
329
+ }
330
+ /**
331
+ * Spec-legal metadata URLs for the issuer, ordered by RFC precedence: RFC 8414
332
+ * path insertion first, then OIDC Discovery's issuer-relative form.
333
+ * `fetchOAuthServerMetadata` validates the published `issuer` before accepting,
334
+ * so order affects latency only, never which server verifies tokens.
335
+ */
336
+ function oauthMetadataUrlsForIssuer(issuer) {
337
+ const normalizedIssuer = trimTrailingSlash(issuer);
338
+ const url = new URL(normalizedIssuer);
339
+ const path = issuerPath(url);
340
+ if (!path) return [`${normalizedIssuer}/.well-known/oauth-authorization-server`, `${normalizedIssuer}/.well-known/openid-configuration`];
341
+ return [...pathInsertedOAuthMetadataUrls(url, path), `${normalizedIssuer}/.well-known/openid-configuration`];
342
+ }
343
+ async function fetchFirstValidOAuthServerMetadata(metadataUrls, expectedIssuer) {
344
+ const errors = [];
345
+ for (const url of metadataUrls) try {
346
+ return await fetchOAuthServerMetadata(url, expectedIssuer);
347
+ } catch (err) {
348
+ log.debug("oauth.discovery.attempt_failed", {
349
+ url,
350
+ ...describeError(err)
351
+ });
352
+ errors.push(`${url}: ${err instanceof Error ? err.message : String(err)}`);
353
+ }
354
+ log.error("oauth.discovery.exhausted", {
355
+ expectedIssuer,
356
+ urlsTried: metadataUrls,
357
+ errors
358
+ });
359
+ throw new Error(`failed to discover OAuth server metadata (${errors.join("; ")})`);
360
+ }
361
+ async function fetchOAuthServerMetadata(url, expectedIssuer) {
362
+ log.debug("oauth.discovery.fetch", { url });
363
+ const response = await fetch(url, {
364
+ signal: AbortSignal.timeout(METADATA_FETCH_TIMEOUT_MS),
365
+ redirect: "manual"
366
+ });
367
+ if (!response.ok) throw new Error(String(response.status));
368
+ const json = await response.json();
369
+ if (typeof json.issuer !== "string") throw new Error("missing issuer");
370
+ parseSafeUrl("discovered issuer", json.issuer);
371
+ if (trimTrailingSlash(json.issuer) !== expectedIssuer) {
372
+ log.warn("oauth.discovery.issuer_mismatch", {
373
+ url,
374
+ expectedIssuer,
375
+ published: json.issuer
376
+ });
377
+ throw new Error("issuer mismatch");
378
+ }
379
+ if (typeof json.jwks_uri !== "string") throw new Error("missing jwks_uri");
380
+ parseSafeUrl("discovered jwks_uri", json.jwks_uri);
381
+ return {
382
+ issuer: json.issuer,
383
+ jwks_uri: json.jwks_uri
384
+ };
385
+ }
386
+ async function fetchIssuerOAuthServerMetadata(issuer) {
387
+ try {
388
+ return await fetchFirstValidOAuthServerMetadata(oauthMetadataUrlsForIssuer(issuer), issuer);
389
+ } catch (err) {
390
+ log.error("oauth.discovery.config_error", {
391
+ issuer,
392
+ ...describeError(err),
393
+ outcome: "500 oauth configuration error"
394
+ });
395
+ throw new OAuthConfigurationError(`OAuth issuer discovery failed: ${err instanceof Error ? err.message : String(err)}`);
396
+ }
397
+ }
398
+ /** Metadata and token verification share issuer/JWKS discovery, but transient failures must not poison the runtime. */
399
+ function createOAuthDiscoveryResolver(auth) {
400
+ const configuredIssuer = trimTrailingSlash(auth.issuer);
401
+ const oauthServerMetadata = cachedPromise(() => fetchIssuerOAuthServerMetadata(configuredIssuer), "oauth.discovery.metadata");
402
+ return {
403
+ resolveIssuer: async () => configuredIssuer,
404
+ resolveJwksUri: async () => {
405
+ if (auth.jwksUri) {
406
+ log.debug("oauth.jwks.resolved", {
407
+ jwksUri: auth.jwksUri,
408
+ source: "configured"
409
+ });
410
+ return auth.jwksUri;
411
+ }
412
+ const jwksUri = (await oauthServerMetadata()).jwks_uri;
413
+ log.debug("oauth.jwks.resolved", {
414
+ jwksUri,
415
+ source: "discovered"
416
+ });
417
+ return jwksUri;
418
+ }
419
+ };
420
+ }
421
+ //#endregion
422
+ //#region src/auth/resource.ts
423
+ /**
424
+ * Defaults the protected-resource name from the request `Host` so hosted apps stay portable
425
+ * across domains. A validated config always sets `acceptedAudiences` or `resource`, so this
426
+ * default only names the advertised metadata, never the accepted JWT audience. Deployments
427
+ * behind an untrusted proxy should still pin `auth.resource` so a spoofed `Host` can't shift
428
+ * the advertised metadata URL.
429
+ */
430
+ function resolveProtectedResource(auth, request, options) {
431
+ if (auth.resource) return trimTrailingSlash(auth.resource);
432
+ const path = resolveResourcePath(options.resourcePath, request);
433
+ const resourceURL = new URL(path, request.url);
434
+ resourceURL.search = "";
435
+ resourceURL.hash = "";
436
+ return trimTrailingSlash(resourceURL.toString());
437
+ }
438
+ /**
439
+ * A bare absolute path can't anchor `resource` to another origin; `//host`, `\\host`,
440
+ * absolute URLs, and `..` segments can. WHATWG URL coerces `\` to `/` for special
441
+ * schemes, so a backslash would smuggle a `//`-style authority past the prefix check.
442
+ */
443
+ function assertResourcePathShape(resourcePath, label = "resourcePath") {
444
+ if (!resourcePath.startsWith("/") || resourcePath.startsWith("//") || resourcePath.includes("\\") || /(^|\/)\.\.(\/|$)/.test(resourcePath)) throw new Error(`@lovable.dev/mcp-js: ${label} must be an absolute path beginning with "/" without ".." segments or backslashes (got ${JSON.stringify(resourcePath)})`);
445
+ }
446
+ function resolveResourcePath(resourcePath, request) {
447
+ if (resourcePath === void 0) return new URL(request.url).pathname;
448
+ assertResourcePathShape(resourcePath);
449
+ return resourcePath;
450
+ }
451
+ //#endregion
452
+ //#region src/auth/claims.ts
453
+ function readString(value) {
454
+ return typeof value === "string" ? value : void 0;
455
+ }
456
+ function splitScopes(value) {
457
+ if (typeof value === "string") return value.split(/\s+/).filter(Boolean);
458
+ return stringClaimList(value);
459
+ }
460
+ function stringClaim(claims, name) {
461
+ return readString(claims[name]);
462
+ }
463
+ /** Normalizes a string-or-array claim from untrusted wire data, dropping non-string and empty entries. */
464
+ function stringClaimList(value) {
465
+ if (typeof value === "string") return value === "" ? [] : [value];
466
+ if (Array.isArray(value)) return value.filter((entry) => typeof entry === "string" && entry !== "");
467
+ return [];
468
+ }
469
+ //#endregion
470
+ //#region src/auth/verifier.ts
471
+ const DEFAULT_JWT_ALGORITHMS = [
472
+ "RS256",
473
+ "RS384",
474
+ "RS512",
475
+ "ES256",
476
+ "ES384",
477
+ "ES512",
478
+ "EdDSA"
479
+ ];
480
+ const DEFAULT_CLOCK_TOLERANCE_SECONDS = 30;
481
+ const DEFAULT_ACCESS_TOKEN_TYPS = ["at+jwt", "JWT"];
482
+ const JWKS_FETCH_TIMEOUT_MS = 5e3;
483
+ var OAuthTokenError = class extends Error {
484
+ status;
485
+ oauthError;
486
+ constructor(status, oauthError, message) {
487
+ super(message);
488
+ this.status = status;
489
+ this.oauthError = oauthError;
490
+ this.name = "OAuthTokenError";
491
+ }
492
+ };
493
+ function resolveAcceptedAudiences(auth, resource) {
494
+ return auth.acceptedAudiences ?? [resource];
495
+ }
496
+ function tokenHeaderFields(token) {
497
+ try {
498
+ const header = decodeProtectedHeader(token);
499
+ return {
500
+ jwtAlg: header.alg,
501
+ jwtKid: header.kid,
502
+ tokenLength: token.length
503
+ };
504
+ } catch {
505
+ return { tokenLength: token.length };
506
+ }
507
+ }
508
+ async function fetchVerificationKeySet(jwksUri) {
509
+ try {
510
+ const response = await fetch(jwksUri, {
511
+ signal: AbortSignal.timeout(JWKS_FETCH_TIMEOUT_MS),
512
+ redirect: "manual"
513
+ });
514
+ if (!response.ok) throw new Error(`JWKS endpoint returned ${response.status}`);
515
+ return createLocalJWKSet(await response.json());
516
+ } catch (err) {
517
+ log.error("oauth.jwks.fetch_failed", {
518
+ ...describeError(err),
519
+ outcome: "500 oauth configuration error"
520
+ });
521
+ throw new OAuthConfigurationError(`JWKS fetch failed: ${err instanceof Error ? err.message : String(err)}`);
522
+ }
523
+ }
524
+ function assertAccessTokenTyp(token, allowed) {
525
+ let header;
526
+ try {
527
+ header = decodeProtectedHeader(token);
528
+ } catch (err) {
529
+ log.debug("oauth.verify.bad_header", {
530
+ ...describeError(err),
531
+ outcome: "401 invalid_token"
532
+ });
533
+ throw new OAuthTokenError(401, "invalid_token", "Malformed JWT header");
534
+ }
535
+ const typ = header.typ;
536
+ if (typeof typ !== "string" || !allowed.includes(typ)) {
537
+ log.debug("oauth.verify.bad_typ", {
538
+ jwtTyp: typ,
539
+ allowed,
540
+ outcome: "401 invalid_token"
541
+ });
542
+ throw new OAuthTokenError(401, "invalid_token", "Access token typ header is not accepted");
543
+ }
544
+ }
545
+ async function verifyJwtClaims(token, keySet, issuer, auth) {
546
+ try {
547
+ const { payload } = await jwtVerify(token, keySet, {
548
+ issuer: [issuer, `${issuer}/`],
549
+ algorithms: auth.algorithms ? [...auth.algorithms] : DEFAULT_JWT_ALGORITHMS,
550
+ requiredClaims: ["sub", "exp"],
551
+ clockTolerance: auth.clockToleranceSeconds ?? DEFAULT_CLOCK_TOLERANCE_SECONDS
552
+ });
553
+ return payload;
554
+ } catch (err) {
555
+ log.debug("oauth.verify.rejected", {
556
+ ...describeError(err),
557
+ outcome: "401 invalid_token"
558
+ });
559
+ throw err;
560
+ }
561
+ }
562
+ function checkAcceptedAudience(claims, accepted, auth) {
563
+ if (claims.aud !== void 0 && !(Array.isArray(claims.aud) && claims.aud.length === 0)) {
564
+ if (stringClaimList(claims.aud).some((audience) => accepted.includes(audience))) return "aud";
565
+ log.debug("oauth.verify.bad_audience", {
566
+ tokenAud: claims.aud,
567
+ accepted,
568
+ outcome: "401 invalid_token"
569
+ });
570
+ } else if (auth.acceptResourceClaim !== false) {
571
+ const acceptedTrimmed = accepted.map(trimTrailingSlash);
572
+ if (stringClaimList(claims.resource).some((resource) => acceptedTrimmed.includes(trimTrailingSlash(resource)))) return "resource";
573
+ log.debug("oauth.verify.bad_resource", {
574
+ tokenResource: claims.resource,
575
+ accepted,
576
+ outcome: "401 invalid_token"
577
+ });
578
+ } else log.debug("oauth.verify.empty_audience", {
579
+ accepted,
580
+ outcome: "401 invalid_token"
581
+ });
582
+ throw new OAuthTokenError(401, "invalid_token", "token audience is not accepted");
583
+ }
584
+ function assertNonEmptySubject(claims) {
585
+ const sub = claims["sub"];
586
+ if (typeof sub !== "string" || sub.trim() === "") {
587
+ log.debug("oauth.verify.bad_subject", { subType: typeof sub });
588
+ throw new OAuthTokenError(401, "invalid_token", "token subject claim must be a non-empty string");
589
+ }
590
+ }
591
+ /** Rejects copied app-session JWTs that were not issued to an OAuth client. */
592
+ function assertOAuthClientClaim(auth, clientId) {
593
+ if (auth.requireOAuthClientClaim !== false && !clientId) {
594
+ log.debug("oauth.verify.missing_client_claim", { outcome: "401 invalid_token" });
595
+ throw new OAuthTokenError(401, "invalid_token", "OAuth client claim is required");
596
+ }
597
+ }
598
+ /** `token` is non-enumerable so a stray `JSON.stringify(auth)` or spread can't leak the bearer. */
599
+ function makeBearer(token) {
600
+ return Object.defineProperty({}, "token", {
601
+ value: token,
602
+ enumerable: false
603
+ });
604
+ }
605
+ function buildMcpAuthContext(args) {
606
+ const { claims } = args;
607
+ return {
608
+ type: "oauth",
609
+ principal: {
610
+ claims,
611
+ issuer: args.issuer,
612
+ resource: args.resource,
613
+ acceptedAudiences: args.acceptedAudiences,
614
+ scopes: splitScopes(claims.scope),
615
+ sub: stringClaim(claims, "sub"),
616
+ email: stringClaim(claims, "email"),
617
+ clientId: stringClaim(claims, "client_id") ?? stringClaim(claims, "azp")
618
+ },
619
+ bearer: makeBearer(args.token)
620
+ };
621
+ }
622
+ function createOAuthTokenVerifier(auth, discovery) {
623
+ const allowedTyps = auth.accessTokenTyp ?? DEFAULT_ACCESS_TOKEN_TYPS;
624
+ return async (token, request, options) => {
625
+ const resource = resolveProtectedResource(auth, request, options);
626
+ const issuer = await discovery.resolveIssuer();
627
+ const acceptedAudiences = resolveAcceptedAudiences(auth, resource);
628
+ log.debug("oauth.verify.start", {
629
+ issuer,
630
+ acceptedAudiences,
631
+ resource,
632
+ ...tokenHeaderFields(token)
633
+ });
634
+ const jwksUri = await discovery.resolveJwksUri();
635
+ log.debug("oauth.jwks.fetch", { jwksUri });
636
+ const keySet = await fetchVerificationKeySet(jwksUri);
637
+ assertAccessTokenTyp(token, allowedTyps);
638
+ const claims = await verifyJwtClaims(token, keySet, issuer, auth);
639
+ const audienceVia = checkAcceptedAudience(claims, acceptedAudiences, auth);
640
+ assertNonEmptySubject(claims);
641
+ const context = buildMcpAuthContext({
642
+ token,
643
+ claims,
644
+ issuer,
645
+ resource,
646
+ acceptedAudiences
647
+ });
648
+ assertOAuthClientClaim(auth, context.principal.clientId);
649
+ log.info("oauth.verify.ok", {
650
+ sub: context.principal.sub,
651
+ clientId: context.principal.clientId,
652
+ scopes: context.principal.scopes,
653
+ audienceVia
654
+ });
655
+ return context;
656
+ };
657
+ }
658
+ //#endregion
659
+ //#region src/auth/authorize.ts
660
+ function quoteAuthenticateParam(value) {
661
+ return `"${value.replace(/[\u0000-\u001F\u007F]/g, "").replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`;
662
+ }
663
+ function resolveProtectedResourceMetadataUrl(auth, request, options) {
664
+ if (auth.protectedResourceMetadataUrl !== void 0) return auth.protectedResourceMetadataUrl;
665
+ const base = auth.resource ?? request.url;
666
+ return new URL(options.metadataPath ?? "/.well-known/oauth-protected-resource", base).toString();
667
+ }
668
+ /** OAuth clients use the challenge to find this server's protected-resource metadata. */
669
+ function wwwAuthenticateHeader(auth, request, options, params = {}) {
670
+ const values = [`realm=${quoteAuthenticateParam("mcp")}`, `resource_metadata=${quoteAuthenticateParam(resolveProtectedResourceMetadataUrl(auth, request, options))}`];
671
+ if (auth.requiredScopes && auth.requiredScopes.length > 0) values.push(`scope=${quoteAuthenticateParam(auth.requiredScopes.join(" "))}`);
672
+ if (params.error) values.push(`error=${quoteAuthenticateParam(params.error)}`);
673
+ if (params.errorDescription) values.push(`error_description=${quoteAuthenticateParam(params.errorDescription)}`);
674
+ return `Bearer ${values.join(", ")}`;
675
+ }
676
+ function challengeResponse(auth, request, options, status, oauthError, errorDescription) {
677
+ const headers = new Headers(JSON_HEADERS);
678
+ headers.set("WWW-Authenticate", wwwAuthenticateHeader(auth, request, options, {
679
+ error: oauthError,
680
+ errorDescription
681
+ }));
682
+ headers.set("Cache-Control", "no-store");
683
+ return new Response(JSON.stringify({ error: status === 403 ? "forbidden" : "unauthorized" }), {
684
+ status,
685
+ headers
686
+ });
687
+ }
688
+ function oauthConfigurationErrorResponse() {
689
+ return new Response(JSON.stringify({ error: "oauth configuration error" }), {
690
+ status: 500,
691
+ headers: {
692
+ ...JSON_HEADERS,
693
+ "Cache-Control": "no-store"
694
+ }
695
+ });
696
+ }
697
+ function parseBearerToken(request) {
698
+ const header = request.headers.get("Authorization");
699
+ if (!header) return void 0;
700
+ const match = /^Bearer\s+(.+)$/i.exec(header.trim());
701
+ if (!match) return void 0;
702
+ const token = match[1].trim();
703
+ if (token === "" || /\s/.test(token)) return void 0;
704
+ return token;
705
+ }
706
+ /** @internal Builds the OAuth runtime (discovery + verifier) for a definition and its route options. */
707
+ function getOAuthRuntime(mcp, options = {}) {
708
+ if (options.resourcePath !== void 0) assertResourcePathShape(options.resourcePath);
709
+ if (options.metadataPath !== void 0) assertResourcePathShape(options.metadataPath, "metadataPath");
710
+ const stableOptions = {
711
+ resourcePath: options.resourcePath,
712
+ metadataPath: options.metadataPath
713
+ };
714
+ const auth = mcp.auth?.type === "oauth" ? mcp.auth : void 0;
715
+ if (!auth) return {
716
+ kind: "unconfigured",
717
+ options: stableOptions
718
+ };
719
+ if (options.metadataPath !== void 0 && auth.protectedResourceMetadataUrl !== void 0) throw new Error(`@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.`);
720
+ const discovery = createOAuthDiscoveryResolver(auth);
721
+ return {
722
+ kind: "configured",
723
+ auth,
724
+ discovery,
725
+ verify: createOAuthTokenVerifier(auth, discovery),
726
+ options: stableOptions
727
+ };
728
+ }
729
+ /**
730
+ * REST companion routes (`/.mcp/list-tools`, `/.mcp/invoke-tool/*`) are internal
731
+ * RPC the main MCP server calls, so their own request path must never become the
732
+ * advertised resource. Require `auth.resource` or a `resourcePath` so the bound
733
+ * `principal.resource` is the public MCP route, not the internal `/.mcp/*` path.
734
+ * The MCP protocol handler is exempt: its own path is the public resource.
735
+ */
736
+ function assertRestResourceBinding(mcp, options = {}) {
737
+ const auth = mcp.auth?.type === "oauth" ? mcp.auth : void 0;
738
+ if (auth && auth.resource === void 0 && options.resourcePath === void 0) throw new Error(`@lovable.dev/mcp-js: REST companion handlers require auth.resource or a resourcePath so principal.resource binds to the public MCP route, not the internal /.mcp/* request path`);
739
+ }
740
+ function missingRequiredScopes(auth, scopes) {
741
+ const requiredScopes = auth.requiredScopes ?? [];
742
+ if (requiredScopes.length === 0) return [];
743
+ const granted = new Set(scopes);
744
+ return requiredScopes.filter((scope) => !granted.has(scope));
745
+ }
746
+ function assertRequiredScopes(auth, context) {
747
+ if (missingRequiredScopes(auth, context.principal.scopes).length > 0) throw new OAuthTokenError(403, "insufficient_scope", "Additional OAuth scope is required");
748
+ }
749
+ function createRequestAuthorizer(mcp, options = {}) {
750
+ const runtime = getOAuthRuntime(mcp, options);
751
+ return { async authorize(request, recorder) {
752
+ if (runtime.kind === "unconfigured") return { ok: true };
753
+ const startedAt = nowMs();
754
+ const token = parseBearerToken(request);
755
+ if (!token) {
756
+ log.info("auth.no_bearer_token", { outcome: "401" });
757
+ return {
758
+ ok: false,
759
+ response: challengeResponse(runtime.auth, request, runtime.options, 401)
760
+ };
761
+ }
762
+ try {
763
+ const auth = await runtime.verify(token, request, runtime.options);
764
+ assertRequiredScopes(runtime.auth, auth);
765
+ return {
766
+ ok: true,
767
+ auth
768
+ };
769
+ } catch (err) {
770
+ if (err instanceof OAuthConfigurationError) {
771
+ log.error("auth.config_error", {
772
+ ...describeError(err),
773
+ outcome: "500"
774
+ });
775
+ await recorder?.emit({
776
+ tool: null,
777
+ method: "authorize",
778
+ outcome: "auth_config_error",
779
+ durationMs: nowMs() - startedAt
780
+ });
781
+ return {
782
+ ok: false,
783
+ response: oauthConfigurationErrorResponse()
784
+ };
785
+ }
786
+ if (err instanceof OAuthTokenError) {
787
+ log.info("auth.token_rejected", {
788
+ status: err.status,
789
+ oauthError: err.oauthError
790
+ });
791
+ return {
792
+ ok: false,
793
+ response: challengeResponse(runtime.auth, request, runtime.options, err.status, err.oauthError, err.message)
794
+ };
795
+ }
796
+ log.error("auth.unexpected_error", {
797
+ ...describeError(err),
798
+ outcome: "401"
799
+ });
800
+ return {
801
+ ok: false,
802
+ response: challengeResponse(runtime.auth, request, runtime.options, 401, "invalid_token", "Invalid access token")
803
+ };
804
+ }
805
+ } };
806
+ }
807
+ //#endregion
808
+ //#region src/core/cors.ts
809
+ const EXPOSE_HEADERS = "WWW-Authenticate, Mcp-Session-Id, Mcp-Protocol-Version";
810
+ const ALLOW_HEADERS = "Authorization, Content-Type, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID";
811
+ /** Add permissive CORS to a built response, preserving its other headers. */
812
+ function withCors(response) {
813
+ response.headers.set("Access-Control-Allow-Origin", "*");
814
+ response.headers.set("Access-Control-Expose-Headers", EXPOSE_HEADERS);
815
+ return response;
816
+ }
817
+ function corsPreflightResponse(allowMethods) {
818
+ return new Response(null, {
819
+ status: 204,
820
+ headers: {
821
+ "Access-Control-Allow-Origin": "*",
822
+ "Access-Control-Allow-Methods": allowMethods,
823
+ "Access-Control-Allow-Headers": ALLOW_HEADERS,
824
+ "Access-Control-Max-Age": "86400"
825
+ }
826
+ });
827
+ }
828
+ //#endregion
829
+ export { getOAuthRuntime as a, resolveProtectedResource as c, nowMs as d, JSON_HEADERS as f, createRequestAuthorizer as i, createRecorderForRuntime as l, methodNotAllowed as m, withCors as n, oauthConfigurationErrorResponse as o, headResponse as p, assertRestResourceBinding as r, assertResourcePathShape as s, corsPreflightResponse as t, createNoopRecorder as u };