@lightdash-tools/mcp 0.16.1 → 0.17.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 (29) hide show
  1. package/README.md +13 -3
  2. package/dist/auth/oauth-broker/as-metadata.d.ts +6 -2
  3. package/dist/auth/oauth-broker/as-metadata.js +8 -4
  4. package/dist/auth/oauth-broker/invoke-origins.d.ts +16 -0
  5. package/dist/auth/oauth-broker/invoke-origins.js +112 -0
  6. package/dist/auth/oauth-broker/invoke-origins.test.d.ts +1 -0
  7. package/dist/auth/oauth-broker/invoke-origins.test.js +82 -0
  8. package/dist/auth/oauth-broker/routes.js +33 -9
  9. package/dist/auth/oauth-broker/routes.test.js +110 -3
  10. package/dist/auth/resource-server/lightdash-oauth-middleware.d.ts +1 -1
  11. package/dist/auth/resource-server/lightdash-oauth-middleware.js +8 -5
  12. package/dist/auth/resource-server/lightdash-oauth-middleware.test.js +36 -2
  13. package/dist/auth/resource-server/oauth-protected-resource.d.ts +2 -2
  14. package/dist/auth/resource-server/oauth-protected-resource.js +8 -11
  15. package/dist/auth/resource-server/www-authenticate.test.js +3 -3
  16. package/dist/config/env.d.ts +5 -0
  17. package/dist/config/env.js +6 -1
  18. package/dist/config/load-mcp-config.d.ts +2 -0
  19. package/dist/config/load-mcp-config.js +18 -0
  20. package/dist/config/load-mcp-config.test.js +29 -0
  21. package/dist/config/test-mcp-http-config.js +1 -1
  22. package/dist/http.integration.helpers.d.ts +50 -0
  23. package/dist/http.integration.helpers.js +190 -0
  24. package/dist/http.integration.test.js +57 -198
  25. package/dist/http.invoke-origin.integration.test.d.ts +1 -0
  26. package/dist/http.invoke-origin.integration.test.js +108 -0
  27. package/dist/transports/streamable-http.js +3 -1
  28. package/dist/transports/streamable-http.test.js +8 -3
  29. package/package.json +3 -3
package/README.md CHANGED
@@ -96,14 +96,24 @@ Do **not** set OAuth client secrets for stdio. MCP ignores CLI `SAFETY_MODE` / `
96
96
 
97
97
  ### HTTP OAuth (primary)
98
98
 
99
- | Required | Common optional |
100
- | :-------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------ |
101
- | `LIGHTDASH_URL`, `LIGHTDASH_TOOLS_MCP_PUBLIC_URL`, `LIGHTDASH_TOOLS_OAUTH_CLIENT_ID`, `LIGHTDASH_TOOLS_OAUTH_CLIENT_SECRET` | port, `ALLOWED_ORIGINS`, [`LIGHTDASH_TOOLS_ALLOWED_PROJECT_UUIDS`](#project-allowlist), [`LIGHTDASH_TOOLS_MCP_PROFILES`](#profile-allowlist), token cache TTL |
99
+ | Required | Common optional |
100
+ | :-------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
101
+ | `LIGHTDASH_URL`, `LIGHTDASH_TOOLS_MCP_PUBLIC_URL`, `LIGHTDASH_TOOLS_OAUTH_CLIENT_ID`, `LIGHTDASH_TOOLS_OAUTH_CLIENT_SECRET` | port, `ALLOWED_ORIGINS`, [`LIGHTDASH_TOOLS_MCP_INVOKE_ORIGINS`](#extra-invoke-origins), [`LIGHTDASH_TOOLS_ALLOWED_PROJECT_UUIDS`](#project-allowlist), [`LIGHTDASH_TOOLS_MCP_PROFILES`](#profile-allowlist), token cache TTL |
102
102
 
103
103
  On Cloud Run / hosted HTTP, leave `LIGHTDASH_TOOLS_AUDIT_LOG` unset — tool audits are stderr JSON (`channel: "audit"`) → Cloud Logging. See [cloud-run.md](../../docs/operators/cloud-run.md).
104
104
 
105
105
  Register Lightdash redirect URI: `{PUBLIC_URL}/oauth/callback`. Clients connect with URL only to a profile path above. Protocol: [MCP Authorization 2026-07-28](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization).
106
106
 
107
+ ### Extra invoke origins
108
+
109
+ Optional private-network hostnames (internal LB, internal DNS) that should advertise their own PRM and token/DCR while Google authorize/callback stay on `PUBLIC_URL`. See [mcp-oauth.md](../../docs/operators/mcp-oauth.md#extra-invoke-origins-private-load-balancer--internal-dns) and [ADR-0027](../../docs/adr/0027-mcp-oauth-extra-invoke-origins.md).
110
+
111
+ ```bash
112
+ export LIGHTDASH_TOOLS_MCP_INVOKE_ORIGINS="http://mcp.ilb.internal"
113
+ ```
114
+
115
+ On those Hosts, leave the client Resource URL empty. Do not point `@modelcontextprotocol/client` v2 at an HTTP extra origin — use public HTTPS.
116
+
107
117
  ### Content-developer / content-governance signing
108
118
 
109
119
  | Required (non-test) | Notes |
@@ -10,5 +10,9 @@ export interface AuthorizationServerMetadata {
10
10
  token_endpoint_auth_methods_supported: string[];
11
11
  scopes_supported: string[];
12
12
  }
13
- /** RFC 8414 metadata for the MCP-hosted OAuth broker (issuer = PUBLIC_URL). */
14
- export declare function buildBrokerAuthorizationServerMetadata(config: McpHttpConfig): AuthorizationServerMetadata;
13
+ /**
14
+ * RFC 8414 metadata for the MCP-hosted OAuth broker (issuer = PUBLIC_URL).
15
+ * On an extra invoke origin, token/DCR URLs move to that origin; issuer and
16
+ * authorize stay on PUBLIC_URL (intentional RFC 8414 split).
17
+ */
18
+ export declare function buildBrokerAuthorizationServerMetadata(config: McpHttpConfig, tokenOrigin: string): AuthorizationServerMetadata;
@@ -3,14 +3,18 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.buildBrokerAuthorizationServerMetadata = buildBrokerAuthorizationServerMetadata;
4
4
  const env_js_1 = require("../../config/env.js");
5
5
  const public_url_js_1 = require("../../config/public-url.js");
6
- /** RFC 8414 metadata for the MCP-hosted OAuth broker (issuer = PUBLIC_URL). */
7
- function buildBrokerAuthorizationServerMetadata(config) {
6
+ /**
7
+ * RFC 8414 metadata for the MCP-hosted OAuth broker (issuer = PUBLIC_URL).
8
+ * On an extra invoke origin, token/DCR URLs move to that origin; issuer and
9
+ * authorize stay on PUBLIC_URL (intentional RFC 8414 split).
10
+ */
11
+ function buildBrokerAuthorizationServerMetadata(config, tokenOrigin) {
8
12
  const issuer = (0, public_url_js_1.requirePublicUrl)(config, 'authorization server metadata');
9
13
  return {
10
14
  issuer,
11
15
  authorization_endpoint: `${issuer}${env_js_1.OAUTH_AUTHORIZE_PATH}`,
12
- token_endpoint: `${issuer}${env_js_1.OAUTH_TOKEN_PATH}`,
13
- registration_endpoint: `${issuer}${env_js_1.OAUTH_REGISTER_PATH}`,
16
+ token_endpoint: `${tokenOrigin}${env_js_1.OAUTH_TOKEN_PATH}`,
17
+ registration_endpoint: `${tokenOrigin}${env_js_1.OAUTH_REGISTER_PATH}`,
14
18
  response_types_supported: ['code'],
15
19
  grant_types_supported: ['authorization_code'],
16
20
  code_challenge_methods_supported: ['S256'],
@@ -0,0 +1,16 @@
1
+ import type { IncomingMessage } from 'node:http';
2
+ /**
3
+ * Request scheme for origin matching. `X-Forwarded-Proto` wins (first value),
4
+ * then TLS socket, otherwise http. Non-https is treated as http.
5
+ */
6
+ export declare function requestProtocol(req: IncomingMessage): 'http' | 'https';
7
+ export declare function originFromHostHeader(hostHeader: string | undefined, protocol: string): URL | undefined;
8
+ /**
9
+ * Extra MCP invoke origins (private load balancer, internal DNS, etc.).
10
+ * Duplicates of `publicUrl` are skipped.
11
+ */
12
+ export declare function parseInvokeOrigins(raw: string | undefined, publicUrl?: string): URL[];
13
+ export declare function matchInvokeOrigin(hostHeader: string | undefined, protocol: string, invokeOrigins: readonly URL[]): URL | undefined;
14
+ export declare function allowedResourceOrigins(publicUrl: string, invokeOrigins: readonly URL[]): string[];
15
+ /** Public URL, or a matching extra invoke origin, with no trailing slash. */
16
+ export declare function resourceOriginForRequest(req: IncomingMessage, invokeOrigins: readonly URL[], publicUrl: string): string;
@@ -0,0 +1,112 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.requestProtocol = requestProtocol;
4
+ exports.originFromHostHeader = originFromHostHeader;
5
+ exports.parseInvokeOrigins = parseInvokeOrigins;
6
+ exports.matchInvokeOrigin = matchInvokeOrigin;
7
+ exports.allowedResourceOrigins = allowedResourceOrigins;
8
+ exports.resourceOriginForRequest = resourceOriginForRequest;
9
+ const env_js_1 = require("../../config/env.js");
10
+ const INVOKE_ORIGIN_ABSOLUTE_ERROR = `${env_js_1.ENV_LIGHTDASH_TOOLS_MCP_INVOKE_ORIGINS} entries must be absolute http(s) origins`;
11
+ function parseOneInvokeOrigin(raw) {
12
+ let parsed;
13
+ try {
14
+ parsed = new URL(raw);
15
+ }
16
+ catch (_a) {
17
+ throw new Error(`${INVOKE_ORIGIN_ABSOLUTE_ERROR} (got ${raw})`);
18
+ }
19
+ if ((parsed.protocol !== 'http:' && parsed.protocol !== 'https:') ||
20
+ parsed.username !== '' ||
21
+ parsed.password !== '') {
22
+ throw new Error(`${INVOKE_ORIGIN_ABSOLUTE_ERROR} (got ${raw})`);
23
+ }
24
+ if (parsed.pathname !== '/' || parsed.search !== '' || parsed.hash !== '') {
25
+ throw new Error(`${env_js_1.ENV_LIGHTDASH_TOOLS_MCP_INVOKE_ORIGINS} entries must be origins without a path, query, or fragment (got ${raw})`);
26
+ }
27
+ return new URL(parsed.origin);
28
+ }
29
+ function firstForwardedProto(req) {
30
+ var _a;
31
+ const raw = req.headers['x-forwarded-proto'];
32
+ const value = Array.isArray(raw) ? raw[0] : raw;
33
+ if (value === undefined || value.length === 0) {
34
+ return undefined;
35
+ }
36
+ return (_a = value.split(',')[0]) === null || _a === void 0 ? void 0 : _a.trim().toLowerCase();
37
+ }
38
+ /**
39
+ * Request scheme for origin matching. `X-Forwarded-Proto` wins (first value),
40
+ * then TLS socket, otherwise http. Non-https is treated as http.
41
+ */
42
+ function requestProtocol(req) {
43
+ const forwarded = firstForwardedProto(req);
44
+ if (forwarded === 'https') {
45
+ return 'https';
46
+ }
47
+ if (forwarded === 'http') {
48
+ return 'http';
49
+ }
50
+ return 'encrypted' in req.socket && req.socket.encrypted === true ? 'https' : 'http';
51
+ }
52
+ function originFromHostHeader(hostHeader, protocol) {
53
+ if (hostHeader === undefined || hostHeader.length === 0) {
54
+ return undefined;
55
+ }
56
+ try {
57
+ return new URL(`${protocol === 'https' ? 'https' : 'http'}://${hostHeader}`);
58
+ }
59
+ catch (_a) {
60
+ return undefined;
61
+ }
62
+ }
63
+ /**
64
+ * Extra MCP invoke origins (private load balancer, internal DNS, etc.).
65
+ * Duplicates of `publicUrl` are skipped.
66
+ */
67
+ function parseInvokeOrigins(raw, publicUrl) {
68
+ if (raw === undefined || raw.trim() === '') {
69
+ return [];
70
+ }
71
+ const seen = new Set();
72
+ if (publicUrl !== undefined && publicUrl.length > 0) {
73
+ seen.add(new URL(publicUrl).origin);
74
+ }
75
+ const parsed = [];
76
+ for (const part of raw
77
+ .split(',')
78
+ .map((entry) => entry.trim())
79
+ .filter(Boolean)) {
80
+ const origin = parseOneInvokeOrigin(part);
81
+ if (seen.has(origin.origin)) {
82
+ continue;
83
+ }
84
+ seen.add(origin.origin);
85
+ parsed.push(origin);
86
+ }
87
+ return parsed;
88
+ }
89
+ function matchInvokeOrigin(hostHeader, protocol, invokeOrigins) {
90
+ if (invokeOrigins.length === 0) {
91
+ return undefined;
92
+ }
93
+ const fromHost = originFromHostHeader(hostHeader, protocol);
94
+ if (fromHost === undefined) {
95
+ return undefined;
96
+ }
97
+ return invokeOrigins.find((origin) => origin.origin === fromHost.origin);
98
+ }
99
+ function matchInvokeOriginFromRequest(req, invokeOrigins) {
100
+ return matchInvokeOrigin(req.headers.host, requestProtocol(req), invokeOrigins);
101
+ }
102
+ function allowedResourceOrigins(publicUrl, invokeOrigins) {
103
+ return [new URL(publicUrl).origin, ...invokeOrigins.map((origin) => origin.origin)];
104
+ }
105
+ /** Public URL, or a matching extra invoke origin, with no trailing slash. */
106
+ function resourceOriginForRequest(req, invokeOrigins, publicUrl) {
107
+ const invoke = matchInvokeOriginFromRequest(req, invokeOrigins);
108
+ if (invoke !== undefined) {
109
+ return invoke.origin;
110
+ }
111
+ return new URL(publicUrl).origin;
112
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const vitest_1 = require("vitest");
4
+ const invoke_origins_js_1 = require("./invoke-origins.js");
5
+ const ILB = 'http://mcp.ilb.internal';
6
+ (0, vitest_1.describe)('parseInvokeOrigins', () => {
7
+ (0, vitest_1.it)('returns empty when unset or blank', () => {
8
+ (0, vitest_1.expect)((0, invoke_origins_js_1.parseInvokeOrigins)(undefined, 'https://mcp.example.com')).toEqual([]);
9
+ (0, vitest_1.expect)((0, invoke_origins_js_1.parseInvokeOrigins)(' ', 'https://mcp.example.com')).toEqual([]);
10
+ });
11
+ (0, vitest_1.it)('parses comma-separated http(s) origins and skips the public URL', () => {
12
+ const parsed = (0, invoke_origins_js_1.parseInvokeOrigins)(` ${ILB}, https://mcp.example.com, http://other.internal:8080 `, 'https://mcp.example.com');
13
+ (0, vitest_1.expect)(parsed.map((origin) => origin.origin)).toEqual([
14
+ 'http://mcp.ilb.internal',
15
+ 'http://other.internal:8080',
16
+ ]);
17
+ });
18
+ (0, vitest_1.it)('strips default ports so http://host:80 matches http://host', () => {
19
+ const parsed = (0, invoke_origins_js_1.parseInvokeOrigins)('http://mcp.ilb.internal:80', 'https://mcp.example.com');
20
+ (0, vitest_1.expect)(parsed).toHaveLength(1);
21
+ (0, vitest_1.expect)(parsed[0].origin).toBe(ILB);
22
+ });
23
+ (0, vitest_1.it)('rejects a path, query, fragment, or non-http scheme', () => {
24
+ (0, vitest_1.expect)(() => (0, invoke_origins_js_1.parseInvokeOrigins)('http://mcp.ilb.internal/v1', 'https://mcp.example.com')).toThrow(/without a path/);
25
+ (0, vitest_1.expect)(() => (0, invoke_origins_js_1.parseInvokeOrigins)('not-a-url', 'https://mcp.example.com')).toThrow(/absolute http\(s\) origins/);
26
+ (0, vitest_1.expect)(() => (0, invoke_origins_js_1.parseInvokeOrigins)('ftp://mcp.ilb.internal', 'https://mcp.example.com')).toThrow(/absolute http\(s\) origins/);
27
+ });
28
+ });
29
+ (0, vitest_1.describe)('originFromHostHeader / matchInvokeOrigin', () => {
30
+ const invokeOrigins = (0, invoke_origins_js_1.parseInvokeOrigins)(ILB, 'https://mcp.example.com');
31
+ (0, vitest_1.it)('matches Host + http scheme to the listed origin', () => {
32
+ var _a;
33
+ (0, vitest_1.expect)((_a = (0, invoke_origins_js_1.matchInvokeOrigin)('mcp.ilb.internal', 'http', invokeOrigins)) === null || _a === void 0 ? void 0 : _a.origin).toBe(ILB);
34
+ });
35
+ (0, vitest_1.it)('does not match the same hostname on a different port', () => {
36
+ (0, vitest_1.expect)((0, invoke_origins_js_1.matchInvokeOrigin)('mcp.ilb.internal:9999', 'http', invokeOrigins)).toBeUndefined();
37
+ });
38
+ (0, vitest_1.it)('does not match https when the listed origin is http', () => {
39
+ (0, vitest_1.expect)((0, invoke_origins_js_1.matchInvokeOrigin)('mcp.ilb.internal', 'https', invokeOrigins)).toBeUndefined();
40
+ });
41
+ (0, vitest_1.it)('does not match the public hostname', () => {
42
+ (0, vitest_1.expect)((0, invoke_origins_js_1.matchInvokeOrigin)('mcp.example.com', 'https', invokeOrigins)).toBeUndefined();
43
+ });
44
+ (0, vitest_1.it)('does not parse Host when the extra-origin list is empty', () => {
45
+ (0, vitest_1.expect)((0, invoke_origins_js_1.matchInvokeOrigin)('mcp.ilb.internal', 'http', [])).toBeUndefined();
46
+ });
47
+ (0, vitest_1.it)('treats non-https protocol as http', () => {
48
+ var _a, _b;
49
+ (0, vitest_1.expect)((_a = (0, invoke_origins_js_1.originFromHostHeader)('mcp.ilb.internal', 'http')) === null || _a === void 0 ? void 0 : _a.origin).toBe(ILB);
50
+ (0, vitest_1.expect)((_b = (0, invoke_origins_js_1.originFromHostHeader)('mcp.ilb.internal', 'bogus')) === null || _b === void 0 ? void 0 : _b.origin).toBe(ILB);
51
+ });
52
+ });
53
+ (0, vitest_1.describe)('requestProtocol', () => {
54
+ (0, vitest_1.it)('prefers the first X-Forwarded-Proto value', () => {
55
+ (0, vitest_1.expect)((0, invoke_origins_js_1.requestProtocol)({
56
+ headers: { 'x-forwarded-proto': 'https, http' },
57
+ socket: {},
58
+ })).toBe('https');
59
+ (0, vitest_1.expect)((0, invoke_origins_js_1.requestProtocol)({
60
+ headers: { 'x-forwarded-proto': 'http' },
61
+ socket: { encrypted: true },
62
+ })).toBe('http');
63
+ });
64
+ (0, vitest_1.it)('falls back to TLS then http', () => {
65
+ (0, vitest_1.expect)((0, invoke_origins_js_1.requestProtocol)({
66
+ headers: {},
67
+ socket: { encrypted: true },
68
+ })).toBe('https');
69
+ (0, vitest_1.expect)((0, invoke_origins_js_1.requestProtocol)({
70
+ headers: {},
71
+ socket: {},
72
+ })).toBe('http');
73
+ });
74
+ });
75
+ (0, vitest_1.describe)('allowedResourceOrigins / resourceOriginForRequest', () => {
76
+ (0, vitest_1.it)('strips a default port from the configured public URL', () => {
77
+ (0, vitest_1.expect)((0, invoke_origins_js_1.allowedResourceOrigins)('https://mcp.example.com:443', [])).toEqual([
78
+ 'https://mcp.example.com',
79
+ ]);
80
+ (0, vitest_1.expect)((0, invoke_origins_js_1.resourceOriginForRequest)({ headers: { host: 'mcp.example.com' }, socket: {} }, [], 'https://mcp.example.com:443')).toBe('https://mcp.example.com');
81
+ });
82
+ });
@@ -9,6 +9,7 @@ const public_url_js_1 = require("../../config/public-url.js");
9
9
  const http_body_js_1 = require("../../transports/http-body.js");
10
10
  const http_response_js_1 = require("../../transports/http-response.js");
11
11
  const as_metadata_js_1 = require("./as-metadata.js");
12
+ const invoke_origins_js_1 = require("./invoke-origins.js");
12
13
  const lightdash_token_js_1 = require("./lightdash-token.js");
13
14
  const mcp_access_token_js_1 = require("./mcp-access-token.js");
14
15
  const pending_store_js_1 = require("./pending-store.js");
@@ -97,9 +98,31 @@ function isAllowedClientRedirectUri(redirectUri) {
97
98
  return false;
98
99
  }
99
100
  }
100
- function isAllowedMcpResource(config, resource) {
101
- const publicUrl = (0, public_url_js_1.requirePublicUrl)(config, 'OAuth resource validation');
102
- return (0, enabled_profiles_js_1.listEnabledProfilePaths)(config.enabledProfiles).some((profilePath) => resource === `${publicUrl}${profilePath}`);
101
+ function canonicalProfileResource(resource) {
102
+ try {
103
+ const url = new URL(resource);
104
+ if ((url.protocol !== 'http:' && url.protocol !== 'https:') ||
105
+ url.username !== '' ||
106
+ url.password !== '' ||
107
+ url.search !== '' ||
108
+ url.hash !== '') {
109
+ return undefined;
110
+ }
111
+ return `${url.origin}${url.pathname}`;
112
+ }
113
+ catch (_a) {
114
+ return undefined;
115
+ }
116
+ }
117
+ function allowedMcpResource(config, resource) {
118
+ const canonical = canonicalProfileResource(resource);
119
+ if (canonical === undefined) {
120
+ return undefined;
121
+ }
122
+ const profilePaths = (0, enabled_profiles_js_1.listEnabledProfilePaths)(config.enabledProfiles);
123
+ const origins = (0, invoke_origins_js_1.allowedResourceOrigins)((0, public_url_js_1.requirePublicUrl)(config, 'OAuth resource validation'), config.invokeOrigins);
124
+ const allowed = origins.some((origin) => profilePaths.some((profilePath) => canonical === `${origin}${profilePath}`));
125
+ return allowed ? canonical : undefined;
103
126
  }
104
127
  async function parseRegisteredClientRedirect(query, store) {
105
128
  const clientId = query.get('client_id');
@@ -187,7 +210,8 @@ async function parseAuthorizeRequest(query, config, store) {
187
210
  };
188
211
  }
189
212
  const resource = resources[0];
190
- if (!isAllowedMcpResource(config, resource)) {
213
+ const allowedResource = allowedMcpResource(config, resource);
214
+ if (allowedResource === undefined) {
191
215
  return {
192
216
  ok: false,
193
217
  status: 400,
@@ -204,7 +228,7 @@ async function parseAuthorizeRequest(query, config, store) {
204
228
  redirectUri: registered.redirectUri,
205
229
  clientState: (_c = query.get('state')) !== null && _c !== void 0 ? _c : undefined,
206
230
  codeChallenge,
207
- resource,
231
+ resource: allowedResource,
208
232
  scope: (_d = query.get('scope')) !== null && _d !== void 0 ? _d : undefined,
209
233
  },
210
234
  };
@@ -359,7 +383,7 @@ async function validateTokenGrant(params, store) {
359
383
  if (candidate.clientId !== request.clientId) {
360
384
  return restoreInvalidGrant(store, candidate, 'client_id mismatch');
361
385
  }
362
- if (candidate.resource !== request.resource) {
386
+ if (candidate.resource !== canonicalProfileResource(request.resource)) {
363
387
  return restoreInvalidGrant(store, candidate, 'resource mismatch');
364
388
  }
365
389
  if (!(0, pkce_js_1.verifyPkce)(request.codeVerifier, candidate.codeChallenge, candidate.codeChallengeMethod)) {
@@ -449,8 +473,8 @@ async function handleRegister(req, res, config, store) {
449
473
  client_name: (_a = params.get('client_name')) !== null && _a !== void 0 ? _a : 'MCP Client',
450
474
  });
451
475
  }
452
- function handleAsMetadata(res, config) {
453
- (0, http_response_js_1.sendJson)(res, 200, (0, as_metadata_js_1.buildBrokerAuthorizationServerMetadata)(config));
476
+ function handleAsMetadata(req, res, config) {
477
+ (0, http_response_js_1.sendJson)(res, 200, (0, as_metadata_js_1.buildBrokerAuthorizationServerMetadata)(config, (0, invoke_origins_js_1.resourceOriginForRequest)(req, config.invokeOrigins, (0, public_url_js_1.requirePublicUrl)(config, 'OAuth resource origin'))));
454
478
  }
455
479
  const BROKER_PATHS = new Set([
456
480
  env_js_1.OAUTH_AUTHORIZATION_SERVER_METADATA_PATH,
@@ -479,7 +503,7 @@ function createOAuthBroker(config, store = new pending_store_js_1.InMemoryOAuthB
479
503
  return true;
480
504
  }
481
505
  if (path === env_js_1.OAUTH_AUTHORIZATION_SERVER_METADATA_PATH && req.method === 'GET') {
482
- handleAsMetadata(res, config);
506
+ handleAsMetadata(req, res, config);
483
507
  return true;
484
508
  }
485
509
  if (path === env_js_1.OAUTH_AUTHORIZE_PATH) {
@@ -51,11 +51,11 @@ function mockRes() {
51
51
  };
52
52
  return res;
53
53
  }
54
- function mockReq(method, url, body, contentType = 'application/x-www-form-urlencoded') {
54
+ function mockReq(method, url, body, contentType = 'application/x-www-form-urlencoded', extraHeaders) {
55
55
  const req = new node_events_1.EventEmitter();
56
56
  req.method = method;
57
57
  req.url = url;
58
- req.headers = Object.assign({ host: 'mcp.example.com' }, (body !== undefined ? { 'content-type': contentType } : {}));
58
+ req.headers = Object.assign(Object.assign({ host: 'mcp.example.com' }, (body !== undefined ? { 'content-type': contentType } : {})), extraHeaders);
59
59
  queueMicrotask(() => {
60
60
  if (body !== undefined) {
61
61
  req.emit('data', Buffer.from(body, 'utf8'));
@@ -86,12 +86,33 @@ function authorizeUrl(clientId, redirectUri, challenge) {
86
86
  (0, vitest_1.expect)(parsed.searchParams.get('scope')).toBeNull();
87
87
  });
88
88
  (0, vitest_1.it)('publishes AS metadata pointing at broker endpoints', () => {
89
- const metadata = (0, as_metadata_js_1.buildBrokerAuthorizationServerMetadata)(baseConfig());
89
+ const metadata = (0, as_metadata_js_1.buildBrokerAuthorizationServerMetadata)(baseConfig(), 'https://mcp.example.com');
90
90
  (0, vitest_1.expect)(metadata.issuer).toBe('https://mcp.example.com');
91
91
  (0, vitest_1.expect)(metadata.authorization_endpoint).toBe('https://mcp.example.com/oauth/authorize');
92
92
  (0, vitest_1.expect)(metadata.token_endpoint).toBe('https://mcp.example.com/oauth/token');
93
93
  (0, vitest_1.expect)(metadata.registration_endpoint).toBe('https://mcp.example.com/oauth/register');
94
94
  });
95
+ (0, vitest_1.it)('moves token and DCR onto an extra invoke origin while issuer stays public', () => {
96
+ const metadata = (0, as_metadata_js_1.buildBrokerAuthorizationServerMetadata)(baseConfig(), 'http://mcp.ilb.internal');
97
+ (0, vitest_1.expect)(metadata.issuer).toBe('https://mcp.example.com');
98
+ (0, vitest_1.expect)(metadata.authorization_endpoint).toBe('https://mcp.example.com/oauth/authorize');
99
+ (0, vitest_1.expect)(metadata.token_endpoint).toBe('http://mcp.ilb.internal/oauth/token');
100
+ (0, vitest_1.expect)(metadata.registration_endpoint).toBe('http://mcp.ilb.internal/oauth/register');
101
+ });
102
+ (0, vitest_1.it)('serves host-aware AS metadata when Host matches an extra invoke origin', async () => {
103
+ const broker = (0, routes_js_1.createOAuthBroker)(baseConfig({ invokeOrigins: [new URL('http://mcp.ilb.internal')] }));
104
+ const res = mockRes();
105
+ await broker.handle(mockReq('GET', '/.well-known/oauth-authorization-server', undefined, undefined, {
106
+ host: 'mcp.ilb.internal',
107
+ 'x-forwarded-proto': 'http',
108
+ }), res, '/.well-known/oauth-authorization-server');
109
+ (0, vitest_1.expect)(res.statusCode).toBe(200);
110
+ const body = res.body;
111
+ (0, vitest_1.expect)(body.issuer).toBe('https://mcp.example.com');
112
+ (0, vitest_1.expect)(body.authorization_endpoint).toBe('https://mcp.example.com/oauth/authorize');
113
+ (0, vitest_1.expect)(body.token_endpoint).toBe('http://mcp.ilb.internal/oauth/token');
114
+ (0, vitest_1.expect)(body.registration_endpoint).toBe('http://mcp.ilb.internal/oauth/register');
115
+ });
95
116
  (0, vitest_1.it)('verifies S256 PKCE and rejects PLAIN', () => {
96
117
  const verifier = 'test-verifier-value-1234567890';
97
118
  const challenge = (0, node_crypto_1.createHash)('sha256').update(verifier).digest('base64url');
@@ -226,6 +247,92 @@ function authorizeUrl(clientId, redirectUri, challenge) {
226
247
  (0, vitest_1.expect)(wrongRes.statusCode).toBe(400);
227
248
  (0, vitest_1.expect)(wrongRes.body.error).toBe('invalid_target');
228
249
  });
250
+ (0, vitest_1.it)('accepts an extra invoke-origin profile resource at authorize', async () => {
251
+ const invokeResource = 'http://mcp.ilb.internal/semantic-layer/v1/mcp';
252
+ const broker = (0, routes_js_1.createOAuthBroker)(baseConfig({ invokeOrigins: [new URL('http://mcp.ilb.internal')] }));
253
+ const redirectUri = 'http://127.0.0.1:8787/callback';
254
+ const registerRes = mockRes();
255
+ await broker.handle(mockReq('POST', '/oauth/register', `redirect_uris=${encodeURIComponent(redirectUri)}`), registerRes, '/oauth/register');
256
+ const { client_id: clientId } = registerRes.body;
257
+ const challenge = (0, node_crypto_1.createHash)('sha256').update('verifier').digest('base64url');
258
+ const authorizeRes = mockRes();
259
+ await broker.handle(mockReq('GET', authorizeUrl(clientId, redirectUri, challenge).replace(encodeURIComponent(RESOURCE), encodeURIComponent(invokeResource))), authorizeRes, '/oauth/authorize');
260
+ (0, vitest_1.expect)(authorizeRes.statusCode).toBe(302);
261
+ (0, vitest_1.expect)(String(authorizeRes.headers.Location)).toContain('/api/v1/oauth/authorize');
262
+ });
263
+ (0, vitest_1.it)('accepts a public profile resource when PUBLIC_URL includes a default port', async () => {
264
+ const broker = (0, routes_js_1.createOAuthBroker)(baseConfig({ publicUrl: 'https://mcp.example.com:443' }));
265
+ const redirectUri = 'http://127.0.0.1:8787/callback';
266
+ const registerRes = mockRes();
267
+ await broker.handle(mockReq('POST', '/oauth/register', `redirect_uris=${encodeURIComponent(redirectUri)}`), registerRes, '/oauth/register');
268
+ const { client_id: clientId } = registerRes.body;
269
+ const challenge = (0, node_crypto_1.createHash)('sha256').update('verifier').digest('base64url');
270
+ const authorizeRes = mockRes();
271
+ await broker.handle(mockReq('GET', authorizeUrl(clientId, redirectUri, challenge)), authorizeRes, '/oauth/authorize');
272
+ (0, vitest_1.expect)(authorizeRes.statusCode).toBe(302);
273
+ });
274
+ (0, vitest_1.it)('accepts an extra invoke-origin resource that includes a default port', async () => {
275
+ const invokeResource = 'http://mcp.ilb.internal:80/semantic-layer/v1/mcp';
276
+ const broker = (0, routes_js_1.createOAuthBroker)(baseConfig({ invokeOrigins: [new URL('http://mcp.ilb.internal')] }));
277
+ const redirectUri = 'http://127.0.0.1:8787/callback';
278
+ const registerRes = mockRes();
279
+ await broker.handle(mockReq('POST', '/oauth/register', `redirect_uris=${encodeURIComponent(redirectUri)}`), registerRes, '/oauth/register');
280
+ const { client_id: clientId } = registerRes.body;
281
+ const challenge = (0, node_crypto_1.createHash)('sha256').update('verifier').digest('base64url');
282
+ const authorizeRes = mockRes();
283
+ await broker.handle(mockReq('GET', authorizeUrl(clientId, redirectUri, challenge).replace(encodeURIComponent(RESOURCE), encodeURIComponent(invokeResource))), authorizeRes, '/oauth/authorize');
284
+ (0, vitest_1.expect)(authorizeRes.statusCode).toBe(302);
285
+ });
286
+ (0, vitest_1.it)('mints a portless audience when authorize and token use a default-port invoke resource', async () => {
287
+ const portedResource = 'http://mcp.ilb.internal:80/semantic-layer/v1/mcp';
288
+ const canonicalResource = 'http://mcp.ilb.internal/semantic-layer/v1/mcp';
289
+ const config = baseConfig({ invokeOrigins: [new URL('http://mcp.ilb.internal')] });
290
+ const broker = (0, routes_js_1.createOAuthBroker)(config);
291
+ const redirectUri = 'http://127.0.0.1:8787/callback';
292
+ const verifier = 'test-verifier-value-1234567890';
293
+ const challenge = (0, node_crypto_1.createHash)('sha256').update(verifier).digest('base64url');
294
+ const registerRes = mockRes();
295
+ await broker.handle(mockReq('POST', '/oauth/register', `redirect_uris=${encodeURIComponent(redirectUri)}`), registerRes, '/oauth/register');
296
+ const { client_id: clientId } = registerRes.body;
297
+ const authorizeRes = mockRes();
298
+ await broker.handle(mockReq('GET', authorizeUrl(clientId, redirectUri, challenge).replace(encodeURIComponent(RESOURCE), encodeURIComponent(portedResource))), authorizeRes, '/oauth/authorize');
299
+ (0, vitest_1.expect)(authorizeRes.statusCode).toBe(302);
300
+ const ldAuthorize = new URL(String(authorizeRes.headers.Location));
301
+ const brokerState = ldAuthorize.searchParams.get('state');
302
+ (0, vitest_1.expect)(brokerState).toBeTruthy();
303
+ vitest_1.vi.stubGlobal('fetch', vitest_1.vi.fn().mockResolvedValue({
304
+ ok: true,
305
+ json: async () => ({
306
+ access_token: 'ld-access',
307
+ refresh_token: 'ld-refresh',
308
+ token_type: 'Bearer',
309
+ expires_in: 3600,
310
+ scope: 'mcp:read',
311
+ }),
312
+ }));
313
+ const callbackRes = mockRes();
314
+ await broker.handle(mockReq('GET', `/oauth/callback?code=ld-code&state=${encodeURIComponent(brokerState)}`), callbackRes, '/oauth/callback');
315
+ (0, vitest_1.expect)(callbackRes.statusCode).toBe(302);
316
+ const callbackLocation = new URL(String(callbackRes.headers.Location));
317
+ const code = callbackLocation.searchParams.get('code');
318
+ (0, vitest_1.expect)(code).toBeTruthy();
319
+ const tokenRes = mockRes();
320
+ await broker.handle(mockReq('POST', '/oauth/token', new URLSearchParams({
321
+ grant_type: 'authorization_code',
322
+ code: code,
323
+ redirect_uri: redirectUri,
324
+ client_id: clientId,
325
+ code_verifier: verifier,
326
+ resource: portedResource,
327
+ }).toString()), tokenRes, '/oauth/token');
328
+ (0, vitest_1.expect)(tokenRes.statusCode).toBe(200);
329
+ const body = tokenRes.body;
330
+ (0, vitest_1.expect)(String(body.access_token)).toMatch(/^ldmcp1\./);
331
+ (0, vitest_1.expect)((0, mcp_access_token_js_1.verifyMcpAccessToken)(config, body.access_token, portedResource)).toBeUndefined();
332
+ (0, vitest_1.expect)((0, mcp_access_token_js_1.verifyMcpAccessToken)(config, body.access_token, canonicalResource)).toMatchObject({
333
+ resource: canonicalResource,
334
+ });
335
+ });
229
336
  (0, vitest_1.it)('returns an MCP-issued resource-bound token and never exposes Lightdash tokens', async () => {
230
337
  const config = baseConfig();
231
338
  const broker = (0, routes_js_1.createOAuthBroker)(config);
@@ -18,6 +18,6 @@ export interface OAuthAuthFailure {
18
18
  }
19
19
  export type OAuthAuthResult = OAuthAuthFailure | OAuthAuthSuccess;
20
20
  /** Builds the standard missing-Bearer challenge for a profile MCP path. */
21
- export declare function buildBearerRequiredFailure(config: McpHttpConfig, mcpPath: string): OAuthAuthFailure;
21
+ export declare function buildBearerRequiredFailure(config: McpHttpConfig, mcpPath: string, resourceOrigin: string): OAuthAuthFailure;
22
22
  export declare function authenticateLightdashOAuth(req: IncomingMessage, config: McpHttpConfig, mcpPath: string): Promise<OAuthAuthResult>;
23
23
  export declare function writeOAuthAuthFailure(res: ServerResponse, failure: OAuthAuthFailure): void;
@@ -3,8 +3,10 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.buildBearerRequiredFailure = buildBearerRequiredFailure;
4
4
  exports.authenticateLightdashOAuth = authenticateLightdashOAuth;
5
5
  exports.writeOAuthAuthFailure = writeOAuthAuthFailure;
6
+ const public_url_js_1 = require("../../config/public-url.js");
6
7
  const http_response_js_1 = require("../../transports/http-response.js");
7
8
  const bearer_js_1 = require("../bearer.js");
9
+ const invoke_origins_js_1 = require("../oauth-broker/invoke-origins.js");
8
10
  const mcp_access_token_js_1 = require("../oauth-broker/mcp-access-token.js");
9
11
  const lightdash_token_validation_js_1 = require("./lightdash-token-validation.js");
10
12
  const oauth_protected_resource_js_1 = require("./oauth-protected-resource.js");
@@ -12,8 +14,8 @@ const token_scopes_js_1 = require("./token-scopes.js");
12
14
  const token_validation_error_js_1 = require("./token-validation-error.js");
13
15
  const www_authenticate_js_1 = require("./www-authenticate.js");
14
16
  /** Builds the standard missing-Bearer challenge for a profile MCP path. */
15
- function buildBearerRequiredFailure(config, mcpPath) {
16
- const resourceMetadataUrl = (0, oauth_protected_resource_js_1.getProtectedResourceMetadataPathUrl)(config, mcpPath);
17
+ function buildBearerRequiredFailure(config, mcpPath, resourceOrigin) {
18
+ const resourceMetadataUrl = (0, oauth_protected_resource_js_1.getProtectedResourceMetadataPathUrl)(config, mcpPath, resourceOrigin);
17
19
  const scope = config.requiredScopes.join(' ');
18
20
  return {
19
21
  ok: false,
@@ -49,12 +51,13 @@ function invalidMcpTokenFailure(resourceMetadataUrl, scope) {
49
51
  };
50
52
  }
51
53
  async function authenticateLightdashOAuth(req, config, mcpPath) {
52
- const resourceMetadataUrl = (0, oauth_protected_resource_js_1.getProtectedResourceMetadataPathUrl)(config, mcpPath);
53
- const expectedResource = (0, oauth_protected_resource_js_1.buildOAuthProtectedResourceMetadata)(config, mcpPath).resource;
54
+ const resourceOrigin = (0, invoke_origins_js_1.resourceOriginForRequest)(req, config.invokeOrigins, (0, public_url_js_1.requirePublicUrl)(config, 'OAuth resource origin'));
55
+ const resourceMetadataUrl = (0, oauth_protected_resource_js_1.getProtectedResourceMetadataPathUrl)(config, mcpPath, resourceOrigin);
56
+ const expectedResource = (0, oauth_protected_resource_js_1.buildOAuthProtectedResourceMetadata)(config, mcpPath, resourceOrigin).resource;
54
57
  const scope = config.requiredScopes.join(' ');
55
58
  const token = (0, bearer_js_1.extractBearerToken)(req);
56
59
  if (!token) {
57
- return buildBearerRequiredFailure(config, mcpPath);
60
+ return buildBearerRequiredFailure(config, mcpPath, resourceOrigin);
58
61
  }
59
62
  // The MCP resource server accepts only tokens minted by its co-located authorization
60
63
  // server and bound to this exact profile resource. Raw Lightdash tokens fail here and
@@ -17,9 +17,10 @@ const baseConfig = (0, test_mcp_http_config_js_1.makeTestMcpHttpConfig)({
17
17
  oauthClientSecret: new client_1.SecretString('test-lightdash-confidential-client-secret'),
18
18
  requiredScopes: [],
19
19
  });
20
- function createRequest(authorization) {
20
+ function createRequest(authorization, headers) {
21
21
  return {
22
- headers: authorization ? { authorization } : {},
22
+ headers: Object.assign(Object.assign({}, (authorization ? { authorization } : {})), headers),
23
+ socket: {},
23
24
  };
24
25
  }
25
26
  function resourceFor(path) {
@@ -168,6 +169,39 @@ function mcpToken(options = {}) {
168
169
  return;
169
170
  (0, vitest_1.expect)(result.accessToken).toBe('ld-upstream-token');
170
171
  });
172
+ (0, vitest_1.it)('challenges and verifies against an extra invoke-origin resource when Host matches', async () => {
173
+ const invokeOrigin = new URL('http://mcp.ilb.internal');
174
+ const invokeConfig = (0, test_mcp_http_config_js_1.makeTestMcpHttpConfig)({
175
+ oauthClientId: 'ld-client',
176
+ oauthClientSecret: new client_1.SecretString('test-lightdash-confidential-client-secret'),
177
+ requiredScopes: [],
178
+ invokeOrigins: [invokeOrigin],
179
+ });
180
+ const invokeHeaders = {
181
+ host: 'mcp.ilb.internal',
182
+ 'x-forwarded-proto': 'http',
183
+ };
184
+ const invokeResource = `http://mcp.ilb.internal${index_js_2.SEMANTIC_LAYER_PROFILE_PATH}`;
185
+ const challenge = await (0, lightdash_oauth_middleware_js_1.authenticateLightdashOAuth)(createRequest(undefined, invokeHeaders), invokeConfig, index_js_2.SEMANTIC_LAYER_PROFILE_PATH);
186
+ (0, vitest_1.expect)(challenge.ok).toBe(false);
187
+ if (challenge.ok)
188
+ return;
189
+ (0, vitest_1.expect)(challenge.wwwAuthenticate).toContain('http://mcp.ilb.internal/.well-known/oauth-protected-resource/semantic-layer/v1/mcp');
190
+ vitest_1.vi.mocked(lightdash_token_validation_js_1.validateLightdashAccessToken).mockResolvedValue({
191
+ userUuid: 'user-1',
192
+ email: 'user@example.com',
193
+ });
194
+ const invokeToken = (0, mcp_access_token_js_1.mintMcpAccessToken)(invokeConfig, {
195
+ lightdashAccessToken: 'ld-upstream-token',
196
+ clientId: 'mcp-client-1',
197
+ resource: invokeResource,
198
+ expiresAtMs: Date.now() + 60000,
199
+ }).accessToken;
200
+ const ok = await (0, lightdash_oauth_middleware_js_1.authenticateLightdashOAuth)(createRequest(`Bearer ${invokeToken}`, invokeHeaders), invokeConfig, index_js_2.SEMANTIC_LAYER_PROFILE_PATH);
201
+ (0, vitest_1.expect)(ok.ok).toBe(true);
202
+ const publicHostRejectsInvokeToken = await (0, lightdash_oauth_middleware_js_1.authenticateLightdashOAuth)(createRequest(`Bearer ${invokeToken}`, { host: 'mcp.example.com' }), invokeConfig, index_js_2.SEMANTIC_LAYER_PROFILE_PATH);
203
+ (0, vitest_1.expect)(publicHostRejectsInvokeToken.ok).toBe(false);
204
+ });
171
205
  });
172
206
  (0, vitest_1.describe)('writeOAuthAuthFailure', () => {
173
207
  (0, vitest_1.it)('writes JSON body and WWW-Authenticate header', () => {
@@ -11,10 +11,10 @@ export interface OAuthProtectedResourceMetadata {
11
11
  * Builds MCP OAuth protected-resource metadata for a profile MCP path.
12
12
  * Callers must pass an explicit profile path (root PRM uses `config.mcpPath`).
13
13
  */
14
- export declare function buildOAuthProtectedResourceMetadata(config: McpHttpConfig, mcpPath: string): OAuthProtectedResourceMetadata;
14
+ export declare function buildOAuthProtectedResourceMetadata(config: McpHttpConfig, mcpPath: string, resourceOrigin: string): OAuthProtectedResourceMetadata;
15
15
  export declare function getProtectedResourceMetadataUrl(config: McpHttpConfig): string;
16
16
  /** Path-specific PRM URL for a profile MCP endpoint. */
17
- export declare function getProtectedResourceMetadataPathUrl(config: McpHttpConfig, mcpPath: string): string;
17
+ export declare function getProtectedResourceMetadataPathUrl(config: McpHttpConfig, mcpPath: string, resourceOrigin: string): string;
18
18
  /**
19
19
  * Resolves the profile MCP path for a PRM well-known request.
20
20
  * Root PRM maps to `config.mcpPath`; path-specific PRM is served only for