@lightdash-tools/mcp 0.14.0 → 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 (126) hide show
  1. package/README.md +43 -14
  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/lightdash-token.d.ts +6 -5
  9. package/dist/auth/oauth-broker/lightdash-token.js +6 -10
  10. package/dist/auth/oauth-broker/mcp-access-token.d.ts +31 -0
  11. package/dist/auth/oauth-broker/mcp-access-token.js +109 -0
  12. package/dist/auth/oauth-broker/mcp-access-token.test.d.ts +1 -0
  13. package/dist/auth/oauth-broker/mcp-access-token.test.js +61 -0
  14. package/dist/auth/oauth-broker/pending-store.d.ts +9 -3
  15. package/dist/auth/oauth-broker/pending-store.js +5 -3
  16. package/dist/auth/oauth-broker/pending-store.test.js +28 -44
  17. package/dist/auth/oauth-broker/routes.d.ts +2 -1
  18. package/dist/auth/oauth-broker/routes.js +124 -48
  19. package/dist/auth/oauth-broker/routes.test.js +191 -16
  20. package/dist/auth/resource-server/lightdash-oauth-middleware.d.ts +3 -1
  21. package/dist/auth/resource-server/lightdash-oauth-middleware.js +65 -41
  22. package/dist/auth/resource-server/lightdash-oauth-middleware.test.js +95 -59
  23. package/dist/auth/resource-server/oauth-protected-resource.d.ts +2 -2
  24. package/dist/auth/resource-server/oauth-protected-resource.js +8 -11
  25. package/dist/auth/resource-server/www-authenticate.test.js +3 -3
  26. package/dist/bin.js +33 -7
  27. package/dist/config/env.d.ts +10 -0
  28. package/dist/config/env.js +11 -1
  29. package/dist/config/load-mcp-config.d.ts +14 -1
  30. package/dist/config/load-mcp-config.js +35 -8
  31. package/dist/config/load-mcp-config.test.js +49 -0
  32. package/dist/config/prompt-context-policy.d.ts +18 -0
  33. package/dist/config/prompt-context-policy.js +40 -0
  34. package/dist/config/prompt-context-policy.test.d.ts +4 -0
  35. package/dist/config/prompt-context-policy.test.js +35 -0
  36. package/dist/config/test-mcp-http-config.js +1 -1
  37. package/dist/governance/mcp-post-factory-context.d.ts +2 -0
  38. package/dist/http.d.ts +7 -1
  39. package/dist/http.integration.helpers.d.ts +50 -0
  40. package/dist/http.integration.helpers.js +190 -0
  41. package/dist/http.integration.test.js +81 -187
  42. package/dist/http.invoke-origin.integration.test.d.ts +1 -0
  43. package/dist/http.invoke-origin.integration.test.js +108 -0
  44. package/dist/http.js +10 -1
  45. package/dist/index.d.ts +6 -1
  46. package/dist/index.js +6 -3
  47. package/dist/policy/content-developer.d.ts +5 -0
  48. package/dist/policy/content-developer.js +25 -1
  49. package/dist/policy/content-developer.test.js +29 -0
  50. package/dist/profiles/ai-agent-ops/v1/invariants.d.ts +27 -0
  51. package/dist/profiles/ai-agent-ops/v1/invariants.js +39 -0
  52. package/dist/profiles/ai-agent-ops/v1/prompts.d.ts +3 -2
  53. package/dist/profiles/ai-agent-ops/v1/prompts.js +67 -41
  54. package/dist/profiles/ai-agent-ops/v1/resources/playbooks.d.ts +2 -1
  55. package/dist/profiles/ai-agent-ops/v1/resources/playbooks.js +10 -3
  56. package/dist/profiles/content-developer/v1/invariants.d.ts +69 -0
  57. package/dist/profiles/content-developer/v1/invariants.js +95 -0
  58. package/dist/profiles/content-developer/v1/prompt-specs.d.ts +32 -0
  59. package/dist/profiles/content-developer/v1/prompt-specs.js +56 -0
  60. package/dist/profiles/content-developer/v1/prompts.d.ts +4 -3
  61. package/dist/profiles/content-developer/v1/prompts.js +65 -71
  62. package/dist/profiles/content-developer/v1/prompts.test.js +61 -7
  63. package/dist/profiles/content-developer/v1/resources/playbooks/core.md +1 -0
  64. package/dist/profiles/content-developer/v1/resources/playbooks/index.md +11 -8
  65. package/dist/profiles/content-developer/v1/resources/playbooks/recovery/dashboard-diff.md +15 -0
  66. package/dist/profiles/content-developer/v1/resources/playbooks/recovery/preview-required.md +14 -0
  67. package/dist/profiles/content-developer/v1/resources/playbooks/recovery/preview-stale.md +21 -0
  68. package/dist/profiles/content-developer/v1/resources/playbooks.d.ts +3 -2
  69. package/dist/profiles/content-developer/v1/resources/playbooks.js +35 -22
  70. package/dist/profiles/content-governance/v1/invariants.d.ts +27 -0
  71. package/dist/profiles/content-governance/v1/invariants.js +39 -0
  72. package/dist/profiles/content-governance/v1/prompts.d.ts +4 -2
  73. package/dist/profiles/content-governance/v1/prompts.js +31 -19
  74. package/dist/profiles/content-governance/v1/resources/playbooks.d.ts +2 -1
  75. package/dist/profiles/content-governance/v1/resources/playbooks.js +8 -9
  76. package/dist/profiles/content-reader/v1/invariants.d.ts +33 -0
  77. package/dist/profiles/content-reader/v1/invariants.js +47 -0
  78. package/dist/profiles/content-reader/v1/prompt-specs.d.ts +18 -0
  79. package/dist/profiles/content-reader/v1/prompt-specs.js +33 -0
  80. package/dist/profiles/content-reader/v1/prompts.d.ts +3 -2
  81. package/dist/profiles/content-reader/v1/prompts.js +69 -76
  82. package/dist/profiles/content-reader/v1/resources/playbooks.d.ts +2 -1
  83. package/dist/profiles/content-reader/v1/resources/playbooks.js +10 -11
  84. package/dist/profiles/data-analyst/v1/invariants.d.ts +21 -0
  85. package/dist/profiles/data-analyst/v1/invariants.js +31 -0
  86. package/dist/profiles/data-analyst/v1/prompts.d.ts +3 -2
  87. package/dist/profiles/data-analyst/v1/prompts.js +17 -9
  88. package/dist/profiles/data-analyst/v1/resources/playbooks.d.ts +2 -1
  89. package/dist/profiles/data-analyst/v1/resources/playbooks.js +6 -7
  90. package/dist/profiles/lib/playbook-resources.d.ts +16 -34
  91. package/dist/profiles/lib/playbook-resources.js +55 -76
  92. package/dist/profiles/lib/prompt-context.d.ts +71 -0
  93. package/dist/profiles/lib/prompt-context.js +205 -0
  94. package/dist/profiles/lib/prompt-context.test.d.ts +4 -0
  95. package/dist/profiles/lib/prompt-context.test.js +154 -0
  96. package/dist/profiles/lib/prompt-invariants.d.ts +20 -0
  97. package/dist/profiles/lib/prompt-invariants.js +54 -0
  98. package/dist/profiles/organization-audit/v1/invariants.d.ts +24 -0
  99. package/dist/profiles/organization-audit/v1/invariants.js +35 -0
  100. package/dist/profiles/organization-audit/v1/prompts.d.ts +3 -2
  101. package/dist/profiles/organization-audit/v1/prompts.js +44 -28
  102. package/dist/profiles/organization-audit/v1/resources/playbooks.d.ts +2 -1
  103. package/dist/profiles/organization-audit/v1/resources/playbooks.js +10 -3
  104. package/dist/profiles/semantic-layer/v1/invariants.d.ts +27 -0
  105. package/dist/profiles/semantic-layer/v1/invariants.js +39 -0
  106. package/dist/profiles/semantic-layer/v1/prompts.d.ts +3 -2
  107. package/dist/profiles/semantic-layer/v1/prompts.js +37 -26
  108. package/dist/profiles/semantic-layer/v1/resources/playbooks.d.ts +2 -4
  109. package/dist/profiles/semantic-layer/v1/resources/playbooks.js +8 -7
  110. package/dist/profiles/test-support/prompt-context-budget.test.d.ts +5 -0
  111. package/dist/profiles/test-support/prompt-context-budget.test.js +72 -0
  112. package/dist/profiles/types.d.ts +6 -1
  113. package/dist/server/capabilities.d.ts +3 -0
  114. package/dist/server/capabilities.js +4 -2
  115. package/dist/tools/lib/schema-fields.d.ts +4 -0
  116. package/dist/tools/lib/schema-fields.js +8 -1
  117. package/dist/tools/project/developer-content-preview.js +1 -1
  118. package/dist/tools/project/developer-content.js +2 -2
  119. package/dist/tools/query/reader-tool-helpers.d.ts +2 -2
  120. package/dist/tools/query/reader-tool-helpers.js +2 -2
  121. package/dist/tools/query/reader-tool-helpers.test.js +1 -0
  122. package/dist/tools/shared.d.ts +6 -1
  123. package/dist/tools/shared.js +12 -2
  124. package/dist/transports/streamable-http.js +13 -4
  125. package/dist/transports/streamable-http.test.js +8 -3
  126. package/package.json +3 -3
@@ -7,9 +7,11 @@ const vitest_1 = require("vitest");
7
7
  const test_mcp_http_config_js_1 = require("../../config/test-mcp-http-config.js");
8
8
  const as_metadata_js_1 = require("./as-metadata.js");
9
9
  const lightdash_token_js_1 = require("./lightdash-token.js");
10
+ const mcp_access_token_js_1 = require("./mcp-access-token.js");
10
11
  const pending_store_js_1 = require("./pending-store.js");
11
12
  const pkce_js_1 = require("./pkce.js");
12
13
  const routes_js_1 = require("./routes.js");
14
+ const RESOURCE = 'https://mcp.example.com/semantic-layer/v1/mcp';
13
15
  function baseConfig(overrides = {}) {
14
16
  return (0, test_mcp_http_config_js_1.makeTestMcpHttpConfig)(Object.assign({ host: '0.0.0.0', oauthClientId: 'ld-client', oauthClientSecret: new client_1.SecretString('ld-secret'), maxBodyBytes: 1024 * 1024, requiredScopes: [], scopesSupported: [], tokenValidationCacheTtlMs: 10000 }, overrides));
15
17
  }
@@ -49,11 +51,11 @@ function mockRes() {
49
51
  };
50
52
  return res;
51
53
  }
52
- function mockReq(method, url, body, contentType = 'application/x-www-form-urlencoded') {
54
+ function mockReq(method, url, body, contentType = 'application/x-www-form-urlencoded', extraHeaders) {
53
55
  const req = new node_events_1.EventEmitter();
54
56
  req.method = method;
55
57
  req.url = url;
56
- 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);
57
59
  queueMicrotask(() => {
58
60
  if (body !== undefined) {
59
61
  req.emit('data', Buffer.from(body, 'utf8'));
@@ -62,29 +64,55 @@ function mockReq(method, url, body, contentType = 'application/x-www-form-urlenc
62
64
  });
63
65
  return req;
64
66
  }
67
+ function authorizeUrl(clientId, redirectUri, challenge) {
68
+ return (`/oauth/authorize?response_type=code&client_id=${encodeURIComponent(clientId)}` +
69
+ `&redirect_uri=${encodeURIComponent(redirectUri)}` +
70
+ `&code_challenge=${encodeURIComponent(challenge)}&code_challenge_method=S256` +
71
+ `&resource=${encodeURIComponent(RESOURCE)}`);
72
+ }
65
73
  (0, vitest_1.describe)('oauth broker helpers', () => {
66
74
  (0, vitest_1.afterEach)(() => {
67
75
  vitest_1.vi.restoreAllMocks();
68
76
  });
69
- (0, vitest_1.it)('builds Lightdash authorize URL with fixed server callback', () => {
70
- const url = (0, lightdash_token_js_1.buildLightdashAuthorizeUrl)(baseConfig(), {
71
- state: 'broker-state',
72
- resource: 'https://mcp.example.com/semantic-layer/v1/mcp',
73
- });
77
+ (0, vitest_1.it)('builds downstream Lightdash authorize URL without MCP resource/scope passthrough', () => {
78
+ const url = (0, lightdash_token_js_1.buildLightdashAuthorizeUrl)(baseConfig(), { state: 'broker-state' });
74
79
  const parsed = new URL(url);
75
80
  (0, vitest_1.expect)(parsed.origin + parsed.pathname).toBe('https://app.lightdash.cloud/api/v1/oauth/authorize');
76
81
  (0, vitest_1.expect)(parsed.searchParams.get('client_id')).toBe('ld-client');
77
82
  (0, vitest_1.expect)(parsed.searchParams.get('redirect_uri')).toBe('https://mcp.example.com/oauth/callback');
78
83
  (0, vitest_1.expect)(parsed.searchParams.get('state')).toBe('broker-state');
79
84
  (0, vitest_1.expect)(parsed.searchParams.get('code_challenge')).toBeNull();
85
+ (0, vitest_1.expect)(parsed.searchParams.get('resource')).toBeNull();
86
+ (0, vitest_1.expect)(parsed.searchParams.get('scope')).toBeNull();
80
87
  });
81
88
  (0, vitest_1.it)('publishes AS metadata pointing at broker endpoints', () => {
82
- const metadata = (0, as_metadata_js_1.buildBrokerAuthorizationServerMetadata)(baseConfig());
89
+ const metadata = (0, as_metadata_js_1.buildBrokerAuthorizationServerMetadata)(baseConfig(), 'https://mcp.example.com');
83
90
  (0, vitest_1.expect)(metadata.issuer).toBe('https://mcp.example.com');
84
91
  (0, vitest_1.expect)(metadata.authorization_endpoint).toBe('https://mcp.example.com/oauth/authorize');
85
92
  (0, vitest_1.expect)(metadata.token_endpoint).toBe('https://mcp.example.com/oauth/token');
86
93
  (0, vitest_1.expect)(metadata.registration_endpoint).toBe('https://mcp.example.com/oauth/register');
87
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
+ });
88
116
  (0, vitest_1.it)('verifies S256 PKCE and rejects PLAIN', () => {
89
117
  const verifier = 'test-verifier-value-1234567890';
90
118
  const challenge = (0, node_crypto_1.createHash)('sha256').update(verifier).digest('base64url');
@@ -101,6 +129,7 @@ function mockReq(method, url, body, contentType = 'application/x-www-form-urlenc
101
129
  redirectUri: 'http://127.0.0.1:9999/callback',
102
130
  codeChallenge: 'challenge',
103
131
  codeChallengeMethod: 'S256',
132
+ resource: RESOURCE,
104
133
  });
105
134
  (0, vitest_1.expect)(pending).toBeDefined();
106
135
  (0, vitest_1.expect)((_a = (await store.takePending(pending.brokerState))) === null || _a === void 0 ? void 0 : _a.clientId).toBe('client-a');
@@ -110,6 +139,7 @@ function mockReq(method, url, body, contentType = 'application/x-www-form-urlenc
110
139
  redirectUri: 'http://127.0.0.1:9999/callback',
111
140
  codeChallenge: 'challenge',
112
141
  codeChallengeMethod: 'S256',
142
+ resource: RESOURCE,
113
143
  });
114
144
  (0, vitest_1.expect)(pending2).toBeDefined();
115
145
  const issued = await store.issueCode(pending2, { accessToken: 'atok' });
@@ -117,6 +147,7 @@ function mockReq(method, url, body, contentType = 'application/x-www-form-urlenc
117
147
  (0, vitest_1.expect)(issued).not.toHaveProperty('refreshToken');
118
148
  const taken = await store.takeCode(issued.code);
119
149
  (0, vitest_1.expect)(taken === null || taken === void 0 ? void 0 : taken.accessToken).toBe('atok');
150
+ (0, vitest_1.expect)(taken === null || taken === void 0 ? void 0 : taken.resource).toBe(RESOURCE);
120
151
  (0, vitest_1.expect)(await store.takeCode(issued.code)).toBeUndefined();
121
152
  });
122
153
  (0, vitest_1.it)('registers clients and binds exact redirect URIs', async () => {
@@ -137,6 +168,7 @@ function mockReq(method, url, body, contentType = 'application/x-www-form-urlenc
137
168
  redirectUri: 'http://localhost:8787/callback',
138
169
  codeChallenge: challenge,
139
170
  codeChallengeMethod: 'S256',
171
+ resource: RESOURCE,
140
172
  });
141
173
  (0, vitest_1.expect)(pending).toBeDefined();
142
174
  const issued = await store.issueCode(pending, { accessToken: 'atok' });
@@ -181,11 +213,13 @@ function mockReq(method, url, body, contentType = 'application/x-www-form-urlenc
181
213
  (0, vitest_1.expect)(registered.redirect_uris).toEqual([redirectUri]);
182
214
  const challenge = (0, node_crypto_1.createHash)('sha256').update('verifier').digest('base64url');
183
215
  const okRes = mockRes();
184
- await broker.handle(mockReq('GET', `/oauth/authorize?response_type=code&client_id=${encodeURIComponent(registered.client_id)}&redirect_uri=${encodeURIComponent(redirectUri)}&code_challenge=${challenge}&code_challenge_method=S256`), okRes, '/oauth/authorize');
216
+ await broker.handle(mockReq('GET', authorizeUrl(registered.client_id, redirectUri, challenge)), okRes, '/oauth/authorize');
185
217
  (0, vitest_1.expect)(okRes.statusCode).toBe(302);
186
- (0, vitest_1.expect)(String(okRes.headers.Location)).toContain('/api/v1/oauth/authorize');
218
+ const upstream = new URL(String(okRes.headers.Location));
219
+ (0, vitest_1.expect)(upstream.pathname).toContain('/api/v1/oauth/authorize');
220
+ (0, vitest_1.expect)(upstream.searchParams.get('resource')).toBeNull();
187
221
  const badRes = mockRes();
188
- await broker.handle(mockReq('GET', `/oauth/authorize?response_type=code&client_id=${encodeURIComponent(registered.client_id)}&redirect_uri=${encodeURIComponent('https://attacker.example/cb')}&code_challenge=${challenge}&code_challenge_method=S256`), badRes, '/oauth/authorize');
222
+ await broker.handle(mockReq('GET', authorizeUrl(registered.client_id, 'https://attacker.example/cb', challenge)), badRes, '/oauth/authorize');
189
223
  (0, vitest_1.expect)(badRes.statusCode).toBe(400);
190
224
  (0, vitest_1.expect)(badRes.body.error).toBe('invalid_request');
191
225
  });
@@ -193,23 +227,127 @@ function mockReq(method, url, body, contentType = 'application/x-www-form-urlenc
193
227
  const broker = (0, routes_js_1.createOAuthBroker)(baseConfig());
194
228
  const challenge = (0, node_crypto_1.createHash)('sha256').update('verifier').digest('base64url');
195
229
  const res = mockRes();
196
- await broker.handle(mockReq('GET', `/oauth/authorize?response_type=code&client_id=unknown&redirect_uri=${encodeURIComponent('https://app.example/cb')}&code_challenge=${challenge}&code_challenge_method=S256`), res, '/oauth/authorize');
230
+ await broker.handle(mockReq('GET', authorizeUrl('unknown', 'https://app.example/cb', challenge)), res, '/oauth/authorize');
197
231
  (0, vitest_1.expect)(res.statusCode).toBe(400);
198
232
  (0, vitest_1.expect)(res.body.error).toBe('invalid_client');
199
233
  });
200
- (0, vitest_1.it)('token response omits refresh_token even when upstream issued one', async () => {
234
+ (0, vitest_1.it)('requires a valid enabled MCP resource at authorize', async () => {
201
235
  const broker = (0, routes_js_1.createOAuthBroker)(baseConfig());
202
236
  const redirectUri = 'http://127.0.0.1:8787/callback';
237
+ const registerRes = mockRes();
238
+ await broker.handle(mockReq('POST', '/oauth/register', `redirect_uris=${encodeURIComponent(redirectUri)}`), registerRes, '/oauth/register');
239
+ const { client_id: clientId } = registerRes.body;
240
+ const challenge = (0, node_crypto_1.createHash)('sha256').update('verifier').digest('base64url');
241
+ const missingRes = mockRes();
242
+ await broker.handle(mockReq('GET', `/oauth/authorize?response_type=code&client_id=${encodeURIComponent(clientId)}&redirect_uri=${encodeURIComponent(redirectUri)}&code_challenge=${challenge}&code_challenge_method=S256`), missingRes, '/oauth/authorize');
243
+ (0, vitest_1.expect)(missingRes.statusCode).toBe(400);
244
+ (0, vitest_1.expect)(missingRes.body.error).toBe('invalid_request');
245
+ const wrongRes = mockRes();
246
+ await broker.handle(mockReq('GET', authorizeUrl(clientId, redirectUri, challenge).replace(encodeURIComponent(RESOURCE), encodeURIComponent('https://attacker.example/mcp'))), wrongRes, '/oauth/authorize');
247
+ (0, vitest_1.expect)(wrongRes.statusCode).toBe(400);
248
+ (0, vitest_1.expect)(wrongRes.body.error).toBe('invalid_target');
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';
203
292
  const verifier = 'test-verifier-value-1234567890';
204
293
  const challenge = (0, node_crypto_1.createHash)('sha256').update(verifier).digest('base64url');
205
294
  const registerRes = mockRes();
206
295
  await broker.handle(mockReq('POST', '/oauth/register', `redirect_uris=${encodeURIComponent(redirectUri)}`), registerRes, '/oauth/register');
207
296
  const { client_id: clientId } = registerRes.body;
208
297
  const authorizeRes = mockRes();
209
- await broker.handle(mockReq('GET', `/oauth/authorize?response_type=code&client_id=${encodeURIComponent(clientId)}&redirect_uri=${encodeURIComponent(redirectUri)}&code_challenge=${challenge}&code_challenge_method=S256`), authorizeRes, '/oauth/authorize');
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);
210
300
  const ldAuthorize = new URL(String(authorizeRes.headers.Location));
211
301
  const brokerState = ldAuthorize.searchParams.get('state');
212
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
+ });
336
+ (0, vitest_1.it)('returns an MCP-issued resource-bound token and never exposes Lightdash tokens', async () => {
337
+ const config = baseConfig();
338
+ const broker = (0, routes_js_1.createOAuthBroker)(config);
339
+ const redirectUri = 'http://127.0.0.1:8787/callback';
340
+ const verifier = 'test-verifier-value-1234567890';
341
+ const challenge = (0, node_crypto_1.createHash)('sha256').update(verifier).digest('base64url');
342
+ const registerRes = mockRes();
343
+ await broker.handle(mockReq('POST', '/oauth/register', `redirect_uris=${encodeURIComponent(redirectUri)}`), registerRes, '/oauth/register');
344
+ const { client_id: clientId } = registerRes.body;
345
+ const authorizeRes = mockRes();
346
+ await broker.handle(mockReq('GET', authorizeUrl(clientId, redirectUri, challenge)), authorizeRes, '/oauth/authorize');
347
+ const ldAuthorize = new URL(String(authorizeRes.headers.Location));
348
+ const brokerState = ldAuthorize.searchParams.get('state');
349
+ (0, vitest_1.expect)(brokerState).toBeTruthy();
350
+ (0, vitest_1.expect)(ldAuthorize.searchParams.get('resource')).toBeNull();
213
351
  vitest_1.vi.stubGlobal('fetch', vitest_1.vi.fn().mockResolvedValue({
214
352
  ok: true,
215
353
  json: async () => ({
@@ -217,7 +355,7 @@ function mockReq(method, url, body, contentType = 'application/x-www-form-urlenc
217
355
  refresh_token: 'ld-refresh-should-not-leak',
218
356
  expires_in: 3600,
219
357
  token_type: 'Bearer',
220
- scope: 'openid',
358
+ scope: 'lightdash-upstream-scope-must-not-become-mcp-scope',
221
359
  }),
222
360
  }));
223
361
  const callbackRes = mockRes();
@@ -233,10 +371,47 @@ function mockReq(method, url, body, contentType = 'application/x-www-form-urlenc
233
371
  redirect_uri: redirectUri,
234
372
  client_id: clientId,
235
373
  code_verifier: verifier,
374
+ resource: RESOURCE,
236
375
  }).toString()), tokenRes, '/oauth/token');
237
376
  (0, vitest_1.expect)(tokenRes.statusCode).toBe(200);
238
377
  const tokenBody = tokenRes.body;
239
- (0, vitest_1.expect)(tokenBody.access_token).toBe('ld-access');
378
+ (0, vitest_1.expect)(tokenBody.access_token).not.toBe('ld-access');
379
+ (0, vitest_1.expect)(String(tokenBody.access_token)).toMatch(/^ldmcp1\./);
380
+ (0, vitest_1.expect)(String(tokenBody.access_token)).not.toContain('ld-access');
240
381
  (0, vitest_1.expect)(tokenBody).not.toHaveProperty('refresh_token');
382
+ (0, vitest_1.expect)(tokenBody.scope).toBeUndefined();
383
+ const decrypted = (0, mcp_access_token_js_1.verifyMcpAccessToken)(config, String(tokenBody.access_token), RESOURCE);
384
+ (0, vitest_1.expect)(decrypted).toMatchObject({
385
+ lightdashAccessToken: 'ld-access',
386
+ clientId,
387
+ resource: RESOURCE,
388
+ });
389
+ });
390
+ (0, vitest_1.it)('binds the token request to the same resource as the authorization request', async () => {
391
+ const store = new pending_store_js_1.InMemoryOAuthBrokerStore();
392
+ const verifier = 'test-verifier-value-1234567890';
393
+ const challenge = (0, node_crypto_1.createHash)('sha256').update(verifier).digest('base64url');
394
+ const pending = await store.createPending({
395
+ clientId: 'client-a',
396
+ redirectUri: 'http://127.0.0.1:8787/callback',
397
+ codeChallenge: challenge,
398
+ codeChallengeMethod: 'S256',
399
+ resource: RESOURCE,
400
+ });
401
+ const issued = await store.issueCode(pending, { accessToken: 'ld-access', expiresIn: 3600 });
402
+ const broker = (0, routes_js_1.createOAuthBroker)(baseConfig(), store);
403
+ const res = mockRes();
404
+ await broker.handle(mockReq('POST', '/oauth/token', new URLSearchParams({
405
+ grant_type: 'authorization_code',
406
+ code: issued.code,
407
+ redirect_uri: pending.redirectUri,
408
+ client_id: pending.clientId,
409
+ code_verifier: verifier,
410
+ resource: 'https://mcp.example.com/content-governance/v1/mcp',
411
+ }).toString()), res, '/oauth/token');
412
+ (0, vitest_1.expect)(res.statusCode).toBe(400);
413
+ (0, vitest_1.expect)(res.body.error).toBe('invalid_grant');
414
+ (0, vitest_1.expect)(res.body.error_description).toBe('resource mismatch');
415
+ (0, vitest_1.expect)(await store.getCode(issued.code)).toBeDefined();
241
416
  });
242
417
  });
@@ -3,8 +3,10 @@ import type { McpHttpConfig } from '../../config/load-mcp-config.js';
3
3
  import type { IncomingMessage, ServerResponse } from 'node:http';
4
4
  export interface OAuthAuthSuccess {
5
5
  ok: true;
6
+ /** Server-held downstream Lightdash credential. Never sourced directly from the MCP bearer. */
6
7
  accessToken: string;
7
8
  user: ValidatedLightdashUser;
9
+ /** MCP authorization scopes carried by the broker-issued token. */
8
10
  scopes: string[] | undefined;
9
11
  }
10
12
  export interface OAuthAuthFailure {
@@ -16,6 +18,6 @@ export interface OAuthAuthFailure {
16
18
  }
17
19
  export type OAuthAuthResult = OAuthAuthFailure | OAuthAuthSuccess;
18
20
  /** Builds the standard missing-Bearer challenge for a profile MCP path. */
19
- export declare function buildBearerRequiredFailure(config: McpHttpConfig, mcpPath: string): OAuthAuthFailure;
21
+ export declare function buildBearerRequiredFailure(config: McpHttpConfig, mcpPath: string, resourceOrigin: string): OAuthAuthFailure;
20
22
  export declare function authenticateLightdashOAuth(req: IncomingMessage, config: McpHttpConfig, mcpPath: string): Promise<OAuthAuthResult>;
21
23
  export declare function writeOAuthAuthFailure(res: ServerResponse, failure: OAuthAuthFailure): void;
@@ -3,16 +3,19 @@ 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");
10
+ const mcp_access_token_js_1 = require("../oauth-broker/mcp-access-token.js");
8
11
  const lightdash_token_validation_js_1 = require("./lightdash-token-validation.js");
9
12
  const oauth_protected_resource_js_1 = require("./oauth-protected-resource.js");
10
13
  const token_scopes_js_1 = require("./token-scopes.js");
11
14
  const token_validation_error_js_1 = require("./token-validation-error.js");
12
15
  const www_authenticate_js_1 = require("./www-authenticate.js");
13
16
  /** Builds the standard missing-Bearer challenge for a profile MCP path. */
14
- function buildBearerRequiredFailure(config, mcpPath) {
15
- 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);
16
19
  const scope = config.requiredScopes.join(' ');
17
20
  return {
18
21
  ok: false,
@@ -24,37 +27,71 @@ function buildBearerRequiredFailure(config, mcpPath) {
24
27
  wwwAuthenticate: (0, www_authenticate_js_1.buildWwwAuthenticateHeader)({ resourceMetadataUrl, scope }),
25
28
  };
26
29
  }
30
+ function parseBrokerScopes(scope) {
31
+ if (!scope)
32
+ return undefined;
33
+ const scopes = scope.split(/\s+/).filter(Boolean);
34
+ return scopes.length > 0 ? scopes : undefined;
35
+ }
36
+ function invalidMcpTokenFailure(resourceMetadataUrl, scope) {
37
+ const description = 'Invalid, expired, or wrong-audience MCP access token';
38
+ return {
39
+ ok: false,
40
+ status: 401,
41
+ body: {
42
+ error: 'invalid_token',
43
+ error_description: description,
44
+ },
45
+ wwwAuthenticate: (0, www_authenticate_js_1.buildWwwAuthenticateHeader)({
46
+ resourceMetadataUrl,
47
+ scope,
48
+ error: 'invalid_token',
49
+ errorDescription: description,
50
+ }),
51
+ };
52
+ }
27
53
  async function authenticateLightdashOAuth(req, config, mcpPath) {
28
- const resourceMetadataUrl = (0, oauth_protected_resource_js_1.getProtectedResourceMetadataPathUrl)(config, mcpPath);
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;
29
57
  const scope = config.requiredScopes.join(' ');
30
58
  const token = (0, bearer_js_1.extractBearerToken)(req);
31
59
  if (!token) {
32
- return buildBearerRequiredFailure(config, mcpPath);
60
+ return buildBearerRequiredFailure(config, mcpPath, resourceOrigin);
61
+ }
62
+ // The MCP resource server accepts only tokens minted by its co-located authorization
63
+ // server and bound to this exact profile resource. Raw Lightdash tokens fail here and
64
+ // are never passed through to the downstream API.
65
+ const brokerToken = (0, mcp_access_token_js_1.verifyMcpAccessToken)(config, token, expectedResource);
66
+ if (!brokerToken) {
67
+ return invalidMcpTokenFailure(resourceMetadataUrl, scope);
68
+ }
69
+ const scopes = parseBrokerScopes(brokerToken.scope);
70
+ if (config.requiredScopes.length > 0 && !(0, token_scopes_js_1.hasRequiredScopes)(scopes !== null && scopes !== void 0 ? scopes : [], config.requiredScopes)) {
71
+ const missingScopes = config.requiredScopes.filter((requiredScope) => !(scopes !== null && scopes !== void 0 ? scopes : []).includes(requiredScope));
72
+ return {
73
+ ok: false,
74
+ status: 403,
75
+ body: {
76
+ error: 'insufficient_scope',
77
+ error_description: `Missing required OAuth scopes: ${missingScopes.join(', ')}`,
78
+ },
79
+ wwwAuthenticate: (0, www_authenticate_js_1.buildWwwAuthenticateHeader)({
80
+ resourceMetadataUrl,
81
+ scope: config.requiredScopes.join(' '),
82
+ error: 'insufficient_scope',
83
+ errorDescription: `Missing required OAuth scopes: ${missingScopes.join(', ')}`,
84
+ }),
85
+ };
33
86
  }
34
87
  try {
35
- const user = await (0, lightdash_token_validation_js_1.validateLightdashAccessToken)(config, token);
36
- const scopes = (0, token_scopes_js_1.extractTokenScopes)(token, config.scopesSupported, {
37
- grantAllWhenUnknown: false,
38
- });
39
- if (config.requiredScopes.length > 0 &&
40
- !(0, token_scopes_js_1.hasRequiredScopes)(scopes !== null && scopes !== void 0 ? scopes : [], config.requiredScopes)) {
41
- const missingScopes = config.requiredScopes.filter((scope) => !(scopes !== null && scopes !== void 0 ? scopes : []).includes(scope));
42
- return {
43
- ok: false,
44
- status: 403,
45
- body: {
46
- error: 'insufficient_scope',
47
- error_description: `Missing required OAuth scopes: ${missingScopes.join(', ')}`,
48
- },
49
- wwwAuthenticate: (0, www_authenticate_js_1.buildWwwAuthenticateHeader)({
50
- resourceMetadataUrl,
51
- scope: config.requiredScopes.join(' '),
52
- error: 'insufficient_scope',
53
- errorDescription: `Missing required OAuth scopes: ${missingScopes.join(', ')}`,
54
- }),
55
- };
56
- }
57
- return { ok: true, accessToken: token, user, scopes };
88
+ const user = await (0, lightdash_token_validation_js_1.validateLightdashAccessToken)(config, brokerToken.lightdashAccessToken);
89
+ return {
90
+ ok: true,
91
+ accessToken: brokerToken.lightdashAccessToken,
92
+ user,
93
+ scopes,
94
+ };
58
95
  }
59
96
  catch (error) {
60
97
  if (error instanceof token_validation_error_js_1.TokenValidationError && error.reason === 'upstream_unavailable') {
@@ -71,20 +108,7 @@ async function authenticateLightdashOAuth(req, config, mcpPath) {
71
108
  headers,
72
109
  };
73
110
  }
74
- return {
75
- ok: false,
76
- status: 401,
77
- body: {
78
- error: 'invalid_token',
79
- error_description: 'Invalid or expired Lightdash access token',
80
- },
81
- wwwAuthenticate: (0, www_authenticate_js_1.buildWwwAuthenticateHeader)({
82
- resourceMetadataUrl,
83
- scope,
84
- error: 'invalid_token',
85
- errorDescription: 'Invalid or expired Lightdash access token',
86
- }),
87
- };
111
+ return invalidMcpTokenFailure(resourceMetadataUrl, scope);
88
112
  }
89
113
  }
90
114
  function writeOAuthAuthFailure(res, failure) {