@lightdash-tools/mcp 0.6.0 → 0.7.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 (271) hide show
  1. package/README.md +133 -58
  2. package/dist/audit/audit.d.ts +5 -0
  3. package/dist/{audit.js → audit/audit.js} +1 -2
  4. package/dist/audit/tool-audit-context.d.ts +6 -0
  5. package/dist/audit/tool-audit-context.js +12 -0
  6. package/dist/audit/tool-audit-context.test.d.ts +1 -0
  7. package/dist/audit/tool-audit-context.test.js +19 -0
  8. package/dist/auth/auth-mode.d.ts +4 -0
  9. package/dist/auth/auth-mode.js +6 -0
  10. package/dist/auth/bearer.d.ts +3 -0
  11. package/dist/auth/bearer.js +13 -0
  12. package/dist/auth/lightdash-oauth-upstream-contract.d.ts +22 -0
  13. package/dist/auth/lightdash-oauth-upstream-contract.js +36 -0
  14. package/dist/auth/lightdash-oauth-upstream-contract.test.d.ts +1 -0
  15. package/dist/auth/lightdash-oauth-upstream-contract.test.js +56 -0
  16. package/dist/auth/oauth-broker/as-metadata.d.ts +14 -0
  17. package/dist/auth/oauth-broker/as-metadata.js +20 -0
  18. package/dist/auth/oauth-broker/lightdash-token.d.ts +20 -0
  19. package/dist/auth/oauth-broker/lightdash-token.js +76 -0
  20. package/dist/auth/oauth-broker/pending-store.d.ts +76 -0
  21. package/dist/auth/oauth-broker/pending-store.js +124 -0
  22. package/dist/auth/oauth-broker/pkce.d.ts +2 -0
  23. package/dist/auth/oauth-broker/pkce.js +17 -0
  24. package/dist/auth/oauth-broker/routes.d.ts +9 -0
  25. package/dist/auth/oauth-broker/routes.js +447 -0
  26. package/dist/auth/oauth-broker/routes.test.d.ts +1 -0
  27. package/dist/auth/oauth-broker/routes.test.js +237 -0
  28. package/dist/auth/providers/bearer-context-provider.d.ts +24 -0
  29. package/dist/auth/providers/bearer-context-provider.js +52 -0
  30. package/dist/auth/providers/env-context-provider.d.ts +13 -0
  31. package/dist/auth/providers/env-context-provider.js +19 -0
  32. package/dist/auth/resource-server/lightdash-oauth-middleware.d.ts +23 -0
  33. package/dist/auth/resource-server/lightdash-oauth-middleware.js +115 -0
  34. package/dist/auth/resource-server/lightdash-oauth-middleware.test.d.ts +1 -0
  35. package/dist/auth/resource-server/lightdash-oauth-middleware.test.js +202 -0
  36. package/dist/auth/resource-server/lightdash-token-validation.d.ts +14 -0
  37. package/dist/auth/resource-server/lightdash-token-validation.js +82 -0
  38. package/dist/auth/resource-server/lightdash-token-validation.test.d.ts +1 -0
  39. package/dist/auth/resource-server/lightdash-token-validation.test.js +177 -0
  40. package/dist/auth/resource-server/oauth-protected-resource.d.ts +25 -0
  41. package/dist/auth/resource-server/oauth-protected-resource.js +67 -0
  42. package/dist/auth/resource-server/shared-key-middleware.d.ts +13 -0
  43. package/dist/auth/resource-server/shared-key-middleware.js +24 -0
  44. package/dist/auth/resource-server/token-scopes.d.ts +15 -0
  45. package/dist/auth/resource-server/token-scopes.js +76 -0
  46. package/dist/auth/resource-server/token-scopes.test.d.ts +1 -0
  47. package/dist/auth/resource-server/token-scopes.test.js +51 -0
  48. package/dist/auth/resource-server/token-validation-cache.d.ts +15 -0
  49. package/dist/auth/resource-server/token-validation-cache.js +44 -0
  50. package/dist/auth/resource-server/token-validation-cache.test.d.ts +1 -0
  51. package/dist/auth/resource-server/token-validation-cache.test.js +41 -0
  52. package/dist/auth/resource-server/token-validation-error.d.ts +6 -0
  53. package/dist/auth/resource-server/token-validation-error.js +13 -0
  54. package/dist/auth/resource-server/www-authenticate.d.ts +8 -0
  55. package/dist/auth/resource-server/www-authenticate.js +24 -0
  56. package/dist/auth/resource-server/www-authenticate.test.d.ts +1 -0
  57. package/dist/auth/resource-server/www-authenticate.test.js +64 -0
  58. package/dist/auth/token-hash.d.ts +2 -0
  59. package/dist/auth/token-hash.js +8 -0
  60. package/dist/bin.d.ts +0 -4
  61. package/dist/bin.js +41 -33
  62. package/dist/config/env.d.ts +50 -0
  63. package/dist/config/env.js +53 -0
  64. package/dist/config/load-mcp-config.d.ts +30 -0
  65. package/dist/config/load-mcp-config.js +282 -0
  66. package/dist/config/load-mcp-config.test.d.ts +1 -0
  67. package/dist/config/load-mcp-config.test.js +195 -0
  68. package/dist/config/normalize-url.d.ts +13 -0
  69. package/dist/config/normalize-url.js +52 -0
  70. package/dist/config/normalize-url.test.d.ts +1 -0
  71. package/dist/config/normalize-url.test.js +41 -0
  72. package/dist/config/public-url.d.ts +3 -0
  73. package/dist/config/public-url.js +10 -0
  74. package/dist/config/runtime.d.ts +15 -0
  75. package/dist/config/runtime.js +48 -0
  76. package/dist/config/runtime.test.d.ts +1 -0
  77. package/dist/config/runtime.test.js +69 -0
  78. package/dist/config/test-mcp-http-config.d.ts +3 -0
  79. package/dist/config/test-mcp-http-config.js +7 -0
  80. package/dist/governance/project-pin.d.ts +14 -0
  81. package/dist/governance/project-pin.js +44 -0
  82. package/dist/governance/project-pin.test.d.ts +1 -0
  83. package/dist/governance/project-pin.test.js +35 -0
  84. package/dist/http.d.ts +1 -2
  85. package/dist/http.integration.test.d.ts +1 -0
  86. package/dist/http.integration.test.js +688 -0
  87. package/dist/http.js +3 -170
  88. package/dist/http.test.d.ts +4 -0
  89. package/dist/http.test.js +131 -0
  90. package/dist/index.d.ts +2 -0
  91. package/dist/index.integration.test.js +73 -30
  92. package/dist/index.js +28 -27
  93. package/dist/index.test.js +3 -3
  94. package/dist/logging/structured.d.ts +27 -0
  95. package/dist/logging/structured.js +32 -0
  96. package/dist/logging/structured.test.d.ts +1 -0
  97. package/dist/logging/structured.test.js +33 -0
  98. package/dist/personas/index.d.ts +19 -0
  99. package/dist/personas/index.js +57 -0
  100. package/dist/personas/index.test.d.ts +1 -0
  101. package/dist/personas/index.test.js +58 -0
  102. package/dist/personas/organization-audit/v1/index.d.ts +8 -0
  103. package/dist/personas/organization-audit/v1/index.js +42 -0
  104. package/dist/personas/organization-audit/v1/prompts.d.ts +5 -0
  105. package/dist/personas/organization-audit/v1/prompts.js +111 -0
  106. package/dist/personas/organization-audit/v1/prompts.test.d.ts +4 -0
  107. package/dist/personas/organization-audit/v1/prompts.test.js +25 -0
  108. package/dist/personas/organization-audit/v1/resources/playbook.d.ts +11 -0
  109. package/dist/personas/organization-audit/v1/resources/playbook.js +40 -0
  110. package/dist/personas/organization-audit/v1/resources/playbook.md +52 -0
  111. package/dist/personas/semantic-layer/v1/index.d.ts +8 -0
  112. package/dist/personas/semantic-layer/v1/index.js +32 -0
  113. package/dist/personas/semantic-layer/v1/prompts.d.ts +5 -0
  114. package/dist/personas/semantic-layer/v1/prompts.js +107 -0
  115. package/dist/personas/semantic-layer/v1/resources/playbook.d.ts +12 -0
  116. package/dist/personas/semantic-layer/v1/resources/playbook.js +42 -0
  117. package/dist/personas/semantic-layer/v1/resources/playbook.md +153 -0
  118. package/dist/personas/types.d.ts +19 -0
  119. package/dist/personas/types.js +5 -0
  120. package/dist/protocol-contract.test.d.ts +1 -0
  121. package/dist/protocol-contract.test.js +42 -0
  122. package/dist/server/capabilities.d.ts +15 -0
  123. package/dist/server/capabilities.js +19 -0
  124. package/dist/server/capabilities.test.d.ts +1 -0
  125. package/dist/server/capabilities.test.js +39 -0
  126. package/dist/server/errors.test.d.ts +1 -0
  127. package/dist/server/errors.test.js +53 -0
  128. package/dist/server/request-context.d.ts +13 -0
  129. package/dist/server/request-context.js +2 -0
  130. package/dist/server/server.d.ts +4 -0
  131. package/dist/server/server.js +17 -0
  132. package/dist/server/server.test.d.ts +1 -0
  133. package/dist/server/server.test.js +15 -0
  134. package/dist/server/version.d.ts +1 -0
  135. package/dist/server/version.js +7 -0
  136. package/dist/server/version.test.d.ts +1 -0
  137. package/dist/server/version.test.js +9 -0
  138. package/dist/stdio.process.test.d.ts +1 -0
  139. package/dist/stdio.process.test.js +126 -0
  140. package/dist/tools/index.d.ts +2 -4
  141. package/dist/tools/index.js +4 -30
  142. package/dist/tools/index.test.d.ts +1 -0
  143. package/dist/tools/index.test.js +72 -0
  144. package/dist/tools/lib/api-errors.d.ts +9 -0
  145. package/dist/tools/lib/api-errors.js +22 -0
  146. package/dist/tools/lib/api-shape.d.ts +16 -0
  147. package/dist/tools/lib/api-shape.js +47 -0
  148. package/dist/tools/lib/assert-safe.d.ts +13 -0
  149. package/dist/tools/lib/assert-safe.js +21 -0
  150. package/dist/tools/lib/assert-safe.test.d.ts +4 -0
  151. package/dist/tools/lib/assert-safe.test.js +32 -0
  152. package/dist/tools/lib/concurrency.d.ts +4 -0
  153. package/dist/tools/lib/concurrency.js +24 -0
  154. package/dist/tools/lib/contracts.d.ts +34 -0
  155. package/dist/tools/lib/contracts.js +30 -0
  156. package/dist/tools/lib/redaction.d.ts +107 -0
  157. package/dist/tools/lib/redaction.js +299 -0
  158. package/dist/tools/lib/redaction.test.d.ts +4 -0
  159. package/dist/tools/lib/redaction.test.js +216 -0
  160. package/dist/tools/lib/register-org-audit.d.ts +9 -0
  161. package/dist/tools/lib/register-org-audit.js +20 -0
  162. package/dist/tools/lib/schema-fields.d.ts +9 -0
  163. package/dist/tools/lib/schema-fields.js +19 -0
  164. package/dist/tools/organization/binding.d.ts +14 -0
  165. package/dist/tools/organization/binding.js +31 -0
  166. package/dist/tools/organization/invariants.test.d.ts +4 -0
  167. package/dist/tools/organization/invariants.test.js +28 -0
  168. package/dist/tools/organization/inventory.d.ts +10 -0
  169. package/dist/tools/organization/inventory.js +189 -0
  170. package/dist/tools/organization/roles.d.ts +10 -0
  171. package/dist/tools/organization/roles.js +213 -0
  172. package/dist/tools/project/content.d.ts +9 -0
  173. package/dist/tools/project/content.js +192 -0
  174. package/dist/tools/project/projects.d.ts +7 -0
  175. package/dist/tools/project/projects.js +42 -0
  176. package/dist/tools/project/projects.test.d.ts +1 -0
  177. package/dist/tools/project/projects.test.js +117 -0
  178. package/dist/tools/project/schedulers.d.ts +7 -0
  179. package/dist/tools/project/schedulers.js +115 -0
  180. package/dist/tools/registry.d.ts +104 -0
  181. package/dist/tools/registry.js +59 -0
  182. package/dist/tools/semantic/explore-helpers.d.ts +56 -0
  183. package/dist/tools/semantic/explore-helpers.js +115 -0
  184. package/dist/tools/semantic/explore-helpers.test.d.ts +1 -0
  185. package/dist/tools/semantic/explore-helpers.test.js +170 -0
  186. package/dist/tools/semantic/explores.d.ts +9 -0
  187. package/dist/tools/semantic/explores.js +80 -0
  188. package/dist/tools/semantic/metrics.d.ts +7 -0
  189. package/dist/tools/semantic/metrics.js +53 -0
  190. package/dist/tools/semantic/query.d.ts +6 -0
  191. package/dist/tools/semantic/query.js +42 -0
  192. package/dist/tools/semantic/schema-fields.d.ts +3 -0
  193. package/dist/tools/semantic/schema-fields.js +7 -0
  194. package/dist/tools/shared.d.ts +26 -13
  195. package/dist/tools/shared.js +112 -157
  196. package/dist/tools/shared.test.js +132 -183
  197. package/dist/tools/space/access.d.ts +66 -0
  198. package/dist/tools/space/access.js +322 -0
  199. package/dist/tools/space/access.test.d.ts +4 -0
  200. package/dist/tools/space/access.test.js +90 -0
  201. package/dist/transports/http-body.d.ts +5 -0
  202. package/dist/transports/http-body.js +50 -0
  203. package/dist/transports/http-request-utils.d.ts +2 -0
  204. package/dist/transports/http-request-utils.js +13 -0
  205. package/dist/transports/http-response.d.ts +6 -0
  206. package/dist/transports/http-response.js +56 -0
  207. package/dist/transports/session-store.d.ts +40 -0
  208. package/dist/transports/session-store.js +88 -0
  209. package/dist/transports/session-store.test.d.ts +1 -0
  210. package/dist/transports/session-store.test.js +111 -0
  211. package/dist/transports/streamable-http.d.ts +9 -0
  212. package/dist/transports/streamable-http.js +454 -0
  213. package/dist/transports/streamable-http.test.d.ts +1 -0
  214. package/dist/transports/streamable-http.test.js +95 -0
  215. package/package.json +25 -10
  216. package/dist/audit.d.ts +0 -6
  217. package/dist/config.d.ts +0 -47
  218. package/dist/config.js +0 -82
  219. package/dist/tools/ai-agents.d.ts +0 -6
  220. package/dist/tools/ai-agents.js +0 -388
  221. package/dist/tools/charts.d.ts +0 -6
  222. package/dist/tools/charts.js +0 -55
  223. package/dist/tools/content.d.ts +0 -6
  224. package/dist/tools/content.js +0 -37
  225. package/dist/tools/dashboards.d.ts +0 -6
  226. package/dist/tools/dashboards.js +0 -28
  227. package/dist/tools/explores.d.ts +0 -6
  228. package/dist/tools/explores.js +0 -65
  229. package/dist/tools/groups.d.ts +0 -6
  230. package/dist/tools/groups.js +0 -121
  231. package/dist/tools/metrics.d.ts +0 -6
  232. package/dist/tools/metrics.js +0 -45
  233. package/dist/tools/projects.d.ts +0 -6
  234. package/dist/tools/projects.js +0 -58
  235. package/dist/tools/query.d.ts +0 -6
  236. package/dist/tools/query.js +0 -34
  237. package/dist/tools/schedulers.d.ts +0 -6
  238. package/dist/tools/schedulers.js +0 -45
  239. package/dist/tools/spaces.d.ts +0 -6
  240. package/dist/tools/spaces.js +0 -128
  241. package/dist/tools/tags.d.ts +0 -6
  242. package/dist/tools/tags.js +0 -28
  243. package/dist/tools/users.d.ts +0 -6
  244. package/dist/tools/users.js +0 -50
  245. package/src/audit.ts +0 -6
  246. package/src/bin.ts +0 -58
  247. package/src/config.ts +0 -83
  248. package/src/errors.ts +0 -27
  249. package/src/http.ts +0 -187
  250. package/src/index.integration.test.ts +0 -57
  251. package/src/index.test.ts +0 -8
  252. package/src/index.ts +0 -31
  253. package/src/tools/ai-agents.ts +0 -759
  254. package/src/tools/charts.ts +0 -85
  255. package/src/tools/content.ts +0 -44
  256. package/src/tools/dashboards.ts +0 -25
  257. package/src/tools/explores.ts +0 -98
  258. package/src/tools/groups.ts +0 -180
  259. package/src/tools/index.ts +0 -35
  260. package/src/tools/metrics.ts +0 -42
  261. package/src/tools/projects.ts +0 -74
  262. package/src/tools/query.ts +0 -47
  263. package/src/tools/schedulers.ts +0 -42
  264. package/src/tools/shared.test.ts +0 -365
  265. package/src/tools/shared.ts +0 -274
  266. package/src/tools/spaces.ts +0 -217
  267. package/src/tools/tags.ts +0 -25
  268. package/src/tools/users.ts +0 -64
  269. package/tsconfig.json +0 -13
  270. /package/dist/{errors.d.ts → server/errors.d.ts} +0 -0
  271. /package/dist/{errors.js → server/errors.js} +0 -0
@@ -0,0 +1,76 @@
1
+ export interface PendingAuthorization {
2
+ /** Broker state sent to Lightdash (opaque). */
3
+ brokerState: string;
4
+ /** MCP client's OAuth client_id (from DCR). */
5
+ clientId: string;
6
+ /** MCP client's redirect_uri (must match token exchange). */
7
+ redirectUri: string;
8
+ /** Optional MCP client state to echo back. */
9
+ clientState?: string;
10
+ codeChallenge: string;
11
+ codeChallengeMethod: string;
12
+ scope?: string;
13
+ createdAt: number;
14
+ }
15
+ export interface IssuedAuthorizationCode {
16
+ code: string;
17
+ clientId: string;
18
+ redirectUri: string;
19
+ codeChallenge: string;
20
+ codeChallengeMethod: string;
21
+ accessToken: string;
22
+ expiresIn?: number;
23
+ tokenType: string;
24
+ scope?: string;
25
+ createdAt: number;
26
+ }
27
+ export interface RegisteredClient {
28
+ clientId: string;
29
+ redirectUris: ReadonlySet<string>;
30
+ createdAt: number;
31
+ }
32
+ /** In-memory pending OAuth broker state (single-instance / sticky routing). */
33
+ export declare class OAuthBrokerStore {
34
+ private readonly pendingByBrokerState;
35
+ private readonly codes;
36
+ private readonly clients;
37
+ private readonly pendingTtlMs;
38
+ private readonly codeTtlMs;
39
+ private readonly clientTtlMs;
40
+ private readonly maxPending;
41
+ private readonly maxCodes;
42
+ private readonly maxClients;
43
+ constructor(options?: {
44
+ pendingTtlMs?: number;
45
+ codeTtlMs?: number;
46
+ clientTtlMs?: number;
47
+ maxPending?: number;
48
+ maxCodes?: number;
49
+ maxClients?: number;
50
+ });
51
+ /**
52
+ * Registers a public MCP client with exact redirect URIs, or returns undefined
53
+ * when the in-memory client cap is reached (after TTL cleanup).
54
+ */
55
+ registerClient(redirectUris: readonly string[]): RegisteredClient | undefined;
56
+ getClient(clientId: string): RegisteredClient | undefined;
57
+ /** True when clientId is registered and redirectUri is an exact registered URI. */
58
+ isRedirectAllowedForClient(clientId: string, redirectUri: string): boolean;
59
+ /**
60
+ * Creates pending state, or returns undefined when the in-memory cap is reached
61
+ * (after TTL cleanup).
62
+ */
63
+ createPending(input: Omit<PendingAuthorization, 'brokerState' | 'createdAt'>): PendingAuthorization | undefined;
64
+ takePending(brokerState: string): PendingAuthorization | undefined;
65
+ issueCode(pending: PendingAuthorization, tokens: {
66
+ accessToken: string;
67
+ expiresIn?: number;
68
+ tokenType?: string;
69
+ scope?: string;
70
+ }): IssuedAuthorizationCode | undefined;
71
+ /** Peek at an issued code without consuming it (for pre-consume validation). */
72
+ getCode(code: string): IssuedAuthorizationCode | undefined;
73
+ /** Drop a previously peeked code after successful validation. */
74
+ deleteCode(code: string): void;
75
+ private cleanup;
76
+ }
@@ -0,0 +1,124 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.OAuthBrokerStore = void 0;
4
+ const node_crypto_1 = require("node:crypto");
5
+ /** Pending authorize→callback state TTL. */
6
+ const DEFAULT_PENDING_TTL_MS = 10 * 60 * 1000;
7
+ /** Issued broker authorization code TTL (RFC 6749 recommends ≤10m; keep short). */
8
+ const DEFAULT_CODE_TTL_MS = 60 * 1000;
9
+ /** Registered DCR clients TTL (long enough for interactive OAuth). */
10
+ const DEFAULT_CLIENT_TTL_MS = 24 * 60 * 60 * 1000;
11
+ const DEFAULT_MAX_PENDING = 10000;
12
+ const DEFAULT_MAX_CODES = 10000;
13
+ const DEFAULT_MAX_CLIENTS = 10000;
14
+ /** In-memory pending OAuth broker state (single-instance / sticky routing). */
15
+ class OAuthBrokerStore {
16
+ constructor(options = {}) {
17
+ var _a, _b, _c, _d, _e, _f;
18
+ this.pendingByBrokerState = new Map();
19
+ this.codes = new Map();
20
+ this.clients = new Map();
21
+ this.pendingTtlMs = (_a = options.pendingTtlMs) !== null && _a !== void 0 ? _a : DEFAULT_PENDING_TTL_MS;
22
+ this.codeTtlMs = (_b = options.codeTtlMs) !== null && _b !== void 0 ? _b : DEFAULT_CODE_TTL_MS;
23
+ this.clientTtlMs = (_c = options.clientTtlMs) !== null && _c !== void 0 ? _c : DEFAULT_CLIENT_TTL_MS;
24
+ this.maxPending = (_d = options.maxPending) !== null && _d !== void 0 ? _d : DEFAULT_MAX_PENDING;
25
+ this.maxCodes = (_e = options.maxCodes) !== null && _e !== void 0 ? _e : DEFAULT_MAX_CODES;
26
+ this.maxClients = (_f = options.maxClients) !== null && _f !== void 0 ? _f : DEFAULT_MAX_CLIENTS;
27
+ }
28
+ /**
29
+ * Registers a public MCP client with exact redirect URIs, or returns undefined
30
+ * when the in-memory client cap is reached (after TTL cleanup).
31
+ */
32
+ registerClient(redirectUris) {
33
+ this.cleanup();
34
+ if (this.clients.size >= this.maxClients) {
35
+ return undefined;
36
+ }
37
+ const client = {
38
+ clientId: (0, node_crypto_1.randomBytes)(16).toString('base64url'),
39
+ redirectUris: new Set(redirectUris),
40
+ createdAt: Date.now(),
41
+ };
42
+ this.clients.set(client.clientId, client);
43
+ return client;
44
+ }
45
+ getClient(clientId) {
46
+ this.cleanup();
47
+ return this.clients.get(clientId);
48
+ }
49
+ /** True when clientId is registered and redirectUri is an exact registered URI. */
50
+ isRedirectAllowedForClient(clientId, redirectUri) {
51
+ const client = this.getClient(clientId);
52
+ return client !== undefined && client.redirectUris.has(redirectUri);
53
+ }
54
+ /**
55
+ * Creates pending state, or returns undefined when the in-memory cap is reached
56
+ * (after TTL cleanup).
57
+ */
58
+ createPending(input) {
59
+ this.cleanup();
60
+ if (this.pendingByBrokerState.size >= this.maxPending) {
61
+ return undefined;
62
+ }
63
+ const pending = Object.assign(Object.assign({}, input), { brokerState: (0, node_crypto_1.randomBytes)(24).toString('base64url'), createdAt: Date.now() });
64
+ this.pendingByBrokerState.set(pending.brokerState, pending);
65
+ return pending;
66
+ }
67
+ takePending(brokerState) {
68
+ this.cleanup();
69
+ const pending = this.pendingByBrokerState.get(brokerState);
70
+ if (!pending)
71
+ return undefined;
72
+ this.pendingByBrokerState.delete(brokerState);
73
+ return pending;
74
+ }
75
+ issueCode(pending, tokens) {
76
+ var _a, _b;
77
+ this.cleanup();
78
+ if (this.codes.size >= this.maxCodes) {
79
+ return undefined;
80
+ }
81
+ const issued = {
82
+ code: (0, node_crypto_1.randomBytes)(32).toString('base64url'),
83
+ clientId: pending.clientId,
84
+ redirectUri: pending.redirectUri,
85
+ codeChallenge: pending.codeChallenge,
86
+ codeChallengeMethod: pending.codeChallengeMethod,
87
+ accessToken: tokens.accessToken,
88
+ expiresIn: tokens.expiresIn,
89
+ tokenType: (_a = tokens.tokenType) !== null && _a !== void 0 ? _a : 'Bearer',
90
+ scope: (_b = tokens.scope) !== null && _b !== void 0 ? _b : pending.scope,
91
+ createdAt: Date.now(),
92
+ };
93
+ this.codes.set(issued.code, issued);
94
+ return issued;
95
+ }
96
+ /** Peek at an issued code without consuming it (for pre-consume validation). */
97
+ getCode(code) {
98
+ this.cleanup();
99
+ return this.codes.get(code);
100
+ }
101
+ /** Drop a previously peeked code after successful validation. */
102
+ deleteCode(code) {
103
+ this.codes.delete(code);
104
+ }
105
+ cleanup() {
106
+ const now = Date.now();
107
+ for (const [key, value] of this.pendingByBrokerState) {
108
+ if (now - value.createdAt > this.pendingTtlMs) {
109
+ this.pendingByBrokerState.delete(key);
110
+ }
111
+ }
112
+ for (const [key, value] of this.codes) {
113
+ if (now - value.createdAt > this.codeTtlMs) {
114
+ this.codes.delete(key);
115
+ }
116
+ }
117
+ for (const [key, value] of this.clients) {
118
+ if (now - value.createdAt > this.clientTtlMs) {
119
+ this.clients.delete(key);
120
+ }
121
+ }
122
+ }
123
+ }
124
+ exports.OAuthBrokerStore = OAuthBrokerStore;
@@ -0,0 +1,2 @@
1
+ /** Verifies S256 PKCE code_verifier against stored challenge (PLAIN is not supported). */
2
+ export declare function verifyPkce(codeVerifier: string | undefined, codeChallenge: string, codeChallengeMethod: string): boolean;
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.verifyPkce = verifyPkce;
4
+ const node_crypto_1 = require("node:crypto");
5
+ const http_response_js_1 = require("../../transports/http-response.js");
6
+ /** Verifies S256 PKCE code_verifier against stored challenge (PLAIN is not supported). */
7
+ function verifyPkce(codeVerifier, codeChallenge, codeChallengeMethod) {
8
+ if (!codeVerifier) {
9
+ return false;
10
+ }
11
+ // AS metadata advertises S256 only — reject PLAIN and unknown methods.
12
+ if (codeChallengeMethod.toUpperCase() !== 'S256') {
13
+ return false;
14
+ }
15
+ const computed = (0, node_crypto_1.createHash)('sha256').update(codeVerifier).digest('base64url');
16
+ return (0, http_response_js_1.timingSafeEqualString)(computed, codeChallenge);
17
+ }
@@ -0,0 +1,9 @@
1
+ import type { McpHttpConfig } from '../../config/load-mcp-config.js';
2
+ import type { IncomingMessage, ServerResponse } from 'node:http';
3
+ export interface OAuthBroker {
4
+ handle: (req: IncomingMessage, res: ServerResponse, path: string) => Promise<boolean>;
5
+ }
6
+ /** True for co-located OAuth AS / broker paths (CORS may reflect any Origin). */
7
+ export declare function isOAuthBrokerPath(path: string): boolean;
8
+ /** Creates the OAuth broker request handler for co-located AS façade routes. */
9
+ export declare function createOAuthBroker(config: McpHttpConfig): OAuthBroker;
@@ -0,0 +1,447 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isOAuthBrokerPath = isOAuthBrokerPath;
4
+ exports.createOAuthBroker = createOAuthBroker;
5
+ const env_js_1 = require("../../config/env.js");
6
+ const normalize_url_js_1 = require("../../config/normalize-url.js");
7
+ const http_body_js_1 = require("../../transports/http-body.js");
8
+ const http_response_js_1 = require("../../transports/http-response.js");
9
+ const as_metadata_js_1 = require("./as-metadata.js");
10
+ const lightdash_token_js_1 = require("./lightdash-token.js");
11
+ const pending_store_js_1 = require("./pending-store.js");
12
+ const pkce_js_1 = require("./pkce.js");
13
+ /** Schemes that must never be used as OAuth redirect targets. */
14
+ const BLOCKED_REDIRECT_SCHEMES = new Set(['javascript:', 'data:', 'vbscript:', 'file:']);
15
+ const AS_BUSY = {
16
+ error: 'temporarily_unavailable',
17
+ error_description: 'Authorization server busy; retry later',
18
+ };
19
+ function redirect(res, location) {
20
+ res.writeHead(302, { Location: location }).end();
21
+ }
22
+ function readQuery(req) {
23
+ var _a, _b;
24
+ const host = (_a = req.headers.host) !== null && _a !== void 0 ? _a : 'localhost';
25
+ const url = new URL((_b = req.url) !== null && _b !== void 0 ? _b : '/', `http://${host}`);
26
+ return url.searchParams;
27
+ }
28
+ function appendJsonValueToParams(params, key, value) {
29
+ if (typeof value === 'string') {
30
+ params.set(key, value);
31
+ return;
32
+ }
33
+ if (typeof value === 'number' || typeof value === 'boolean') {
34
+ params.set(key, String(value));
35
+ return;
36
+ }
37
+ if (!Array.isArray(value)) {
38
+ return;
39
+ }
40
+ for (const item of value) {
41
+ if (typeof item === 'string') {
42
+ params.append(key, item);
43
+ }
44
+ }
45
+ }
46
+ function jsonObjectToSearchParams(parsed) {
47
+ const params = new URLSearchParams();
48
+ for (const [key, value] of Object.entries(parsed)) {
49
+ appendJsonValueToParams(params, key, value);
50
+ }
51
+ return params;
52
+ }
53
+ function readJsonFormParams(res, rawBuf) {
54
+ try {
55
+ const parsed = (0, http_body_js_1.parseJsonBody)(rawBuf);
56
+ if (parsed === undefined)
57
+ return new URLSearchParams();
58
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
59
+ (0, http_response_js_1.sendJson)(res, 400, { error: 'invalid_request', error_description: 'Invalid JSON body' });
60
+ return undefined;
61
+ }
62
+ return jsonObjectToSearchParams(parsed);
63
+ }
64
+ catch (_a) {
65
+ (0, http_response_js_1.sendJson)(res, 400, { error: 'invalid_request', error_description: 'Invalid JSON body' });
66
+ return undefined;
67
+ }
68
+ }
69
+ async function readFormOrJson(req, res, maxBodyBytes) {
70
+ var _a;
71
+ const rawBuf = await (0, http_body_js_1.readBody)(req, res, maxBodyBytes);
72
+ if (rawBuf === undefined)
73
+ return undefined;
74
+ if (rawBuf.length === 0)
75
+ return new URLSearchParams();
76
+ const contentType = (_a = req.headers['content-type']) !== null && _a !== void 0 ? _a : '';
77
+ if (contentType.includes('application/json')) {
78
+ return readJsonFormParams(res, rawBuf);
79
+ }
80
+ return new URLSearchParams(rawBuf.toString('utf8'));
81
+ }
82
+ function isAllowedClientRedirectUri(redirectUri) {
83
+ try {
84
+ const url = new URL(redirectUri);
85
+ if (url.protocol === 'https:')
86
+ return true;
87
+ if (url.protocol === 'http:')
88
+ return (0, normalize_url_js_1.isLocalHttpOrigin)(redirectUri);
89
+ // Desktop / native custom schemes (cursor://, vscode://, …) — block dangerous ones.
90
+ const scheme = url.protocol.toLowerCase();
91
+ return !BLOCKED_REDIRECT_SCHEMES.has(scheme);
92
+ }
93
+ catch (_a) {
94
+ return false;
95
+ }
96
+ }
97
+ function parseRegisteredClientRedirect(query, store) {
98
+ const clientId = query.get('client_id');
99
+ if (!clientId) {
100
+ return {
101
+ ok: false,
102
+ status: 400,
103
+ body: {
104
+ error: 'invalid_request',
105
+ error_description: 'client_id is required (register via /oauth/register first)',
106
+ },
107
+ };
108
+ }
109
+ if (!store.getClient(clientId)) {
110
+ return {
111
+ ok: false,
112
+ status: 400,
113
+ body: {
114
+ error: 'invalid_client',
115
+ error_description: 'Unknown client_id; register via /oauth/register first',
116
+ },
117
+ };
118
+ }
119
+ const redirectUri = query.get('redirect_uri');
120
+ if (!redirectUri || !isAllowedClientRedirectUri(redirectUri)) {
121
+ return {
122
+ ok: false,
123
+ status: 400,
124
+ body: {
125
+ error: 'invalid_request',
126
+ error_description: 'redirect_uri is required and must be https, localhost http, or a custom scheme',
127
+ },
128
+ };
129
+ }
130
+ if (!store.isRedirectAllowedForClient(clientId, redirectUri)) {
131
+ return {
132
+ ok: false,
133
+ status: 400,
134
+ body: {
135
+ error: 'invalid_request',
136
+ error_description: 'redirect_uri is not registered for this client_id',
137
+ },
138
+ };
139
+ }
140
+ return { ok: true, clientId, redirectUri };
141
+ }
142
+ function parseAuthorizeRequest(query, store) {
143
+ var _a, _b, _c, _d, _e;
144
+ const responseType = query.get('response_type');
145
+ if (responseType !== 'code') {
146
+ return {
147
+ ok: false,
148
+ status: 400,
149
+ body: {
150
+ error: 'unsupported_response_type',
151
+ error_description: 'Only response_type=code is supported',
152
+ },
153
+ };
154
+ }
155
+ const registered = parseRegisteredClientRedirect(query, store);
156
+ if (!registered.ok) {
157
+ return registered;
158
+ }
159
+ const codeChallenge = (_a = query.get('code_challenge')) !== null && _a !== void 0 ? _a : undefined;
160
+ const method = ((_b = query.get('code_challenge_method')) !== null && _b !== void 0 ? _b : 'S256').toUpperCase();
161
+ if (!codeChallenge || method !== 'S256') {
162
+ return {
163
+ ok: false,
164
+ status: 400,
165
+ body: {
166
+ error: 'invalid_request',
167
+ error_description: 'code_challenge with code_challenge_method=S256 is required',
168
+ },
169
+ };
170
+ }
171
+ return {
172
+ ok: true,
173
+ value: {
174
+ clientId: registered.clientId,
175
+ redirectUri: registered.redirectUri,
176
+ clientState: (_c = query.get('state')) !== null && _c !== void 0 ? _c : undefined,
177
+ codeChallenge,
178
+ resource: (_d = query.get('resource')) !== null && _d !== void 0 ? _d : undefined,
179
+ scope: (_e = query.get('scope')) !== null && _e !== void 0 ? _e : undefined,
180
+ },
181
+ };
182
+ }
183
+ function handleAuthorize(req, res, config, store) {
184
+ if (req.method !== 'GET') {
185
+ res.writeHead(405, { Allow: 'GET' }).end();
186
+ return;
187
+ }
188
+ const parsed = parseAuthorizeRequest(readQuery(req), store);
189
+ if (!parsed.ok) {
190
+ (0, http_response_js_1.sendJson)(res, parsed.status, parsed.body);
191
+ return;
192
+ }
193
+ const { clientId, redirectUri, clientState, codeChallenge, resource, scope } = parsed.value;
194
+ const pending = store.createPending({
195
+ clientId,
196
+ redirectUri,
197
+ clientState,
198
+ codeChallenge,
199
+ codeChallengeMethod: 'S256',
200
+ scope,
201
+ });
202
+ if (!pending) {
203
+ (0, http_response_js_1.sendJson)(res, 503, Object.assign({}, AS_BUSY));
204
+ return;
205
+ }
206
+ redirect(res, (0, lightdash_token_js_1.buildLightdashAuthorizeUrl)(config, {
207
+ state: pending.brokerState,
208
+ scope,
209
+ resource,
210
+ }));
211
+ }
212
+ function redirectToClient(res, redirectUri, params) {
213
+ const target = new URL(redirectUri);
214
+ for (const [key, value] of Object.entries(params)) {
215
+ if (value !== undefined) {
216
+ target.searchParams.set(key, value);
217
+ }
218
+ }
219
+ redirect(res, target.toString());
220
+ }
221
+ async function handleCallback(req, res, config, store) {
222
+ var _a;
223
+ if (req.method !== 'GET') {
224
+ res.writeHead(405, { Allow: 'GET' }).end();
225
+ return;
226
+ }
227
+ const query = readQuery(req);
228
+ const brokerState = query.get('state');
229
+ if (!brokerState) {
230
+ (0, http_response_js_1.sendJson)(res, 400, { error: 'invalid_request', error_description: 'Missing state' });
231
+ return;
232
+ }
233
+ const pending = store.takePending(brokerState);
234
+ if (!pending) {
235
+ (0, http_response_js_1.sendJson)(res, 400, { error: 'invalid_request', error_description: 'Unknown or expired state' });
236
+ return;
237
+ }
238
+ const upstreamError = query.get('error');
239
+ if (upstreamError) {
240
+ redirectToClient(res, pending.redirectUri, {
241
+ error: upstreamError,
242
+ error_description: (_a = query.get('error_description')) !== null && _a !== void 0 ? _a : undefined,
243
+ state: pending.clientState,
244
+ });
245
+ return;
246
+ }
247
+ const code = query.get('code');
248
+ if (!code) {
249
+ (0, http_response_js_1.sendJson)(res, 400, { error: 'invalid_request', error_description: 'Missing code' });
250
+ return;
251
+ }
252
+ try {
253
+ const tokens = await (0, lightdash_token_js_1.exchangeLightdashAuthorizationCode)(config, code);
254
+ // Do not persist/return refresh_token: broker only supports authorization_code.
255
+ const issued = store.issueCode(pending, {
256
+ accessToken: tokens.access_token,
257
+ expiresIn: tokens.expires_in,
258
+ tokenType: tokens.token_type,
259
+ scope: tokens.scope,
260
+ });
261
+ if (!issued) {
262
+ redirectToClient(res, pending.redirectUri, Object.assign(Object.assign({}, AS_BUSY), { state: pending.clientState }));
263
+ return;
264
+ }
265
+ redirectToClient(res, pending.redirectUri, {
266
+ code: issued.code,
267
+ state: pending.clientState,
268
+ });
269
+ }
270
+ catch (err) {
271
+ console.error('OAuth broker callback token exchange failed:', err);
272
+ redirectToClient(res, pending.redirectUri, {
273
+ error: 'server_error',
274
+ error_description: 'Upstream token exchange failed',
275
+ state: pending.clientState,
276
+ });
277
+ }
278
+ }
279
+ function validateTokenGrant(params, store) {
280
+ var _a;
281
+ const grantType = params.get('grant_type');
282
+ if (grantType !== 'authorization_code') {
283
+ return {
284
+ status: 400,
285
+ body: {
286
+ error: 'unsupported_grant_type',
287
+ error_description: 'Only authorization_code is supported',
288
+ },
289
+ };
290
+ }
291
+ const code = params.get('code');
292
+ const redirectUri = params.get('redirect_uri');
293
+ const clientId = params.get('client_id');
294
+ const codeVerifier = (_a = params.get('code_verifier')) !== null && _a !== void 0 ? _a : undefined;
295
+ if (!code || !redirectUri || !clientId) {
296
+ return {
297
+ status: 400,
298
+ body: {
299
+ error: 'invalid_request',
300
+ error_description: 'code, redirect_uri, and client_id are required',
301
+ },
302
+ };
303
+ }
304
+ // Validate before consume so a bad verifier / redirect does not burn a one-time code.
305
+ const candidate = store.getCode(code);
306
+ if (!candidate) {
307
+ return {
308
+ status: 400,
309
+ body: { error: 'invalid_grant', error_description: 'Invalid or expired code' },
310
+ };
311
+ }
312
+ if (candidate.redirectUri !== redirectUri) {
313
+ return {
314
+ status: 400,
315
+ body: { error: 'invalid_grant', error_description: 'redirect_uri mismatch' },
316
+ };
317
+ }
318
+ if (candidate.clientId !== clientId) {
319
+ return {
320
+ status: 400,
321
+ body: { error: 'invalid_grant', error_description: 'client_id mismatch' },
322
+ };
323
+ }
324
+ if (!(0, pkce_js_1.verifyPkce)(codeVerifier, candidate.codeChallenge, candidate.codeChallengeMethod)) {
325
+ return {
326
+ status: 400,
327
+ body: { error: 'invalid_grant', error_description: 'PKCE verification failed' },
328
+ };
329
+ }
330
+ store.deleteCode(code);
331
+ return { issued: candidate };
332
+ }
333
+ async function handleToken(req, res, config, store) {
334
+ var _a;
335
+ if (req.method !== 'POST') {
336
+ res.writeHead(405, { Allow: 'POST' }).end();
337
+ return;
338
+ }
339
+ const params = await readFormOrJson(req, res, config.maxBodyBytes);
340
+ if (!params)
341
+ return;
342
+ const grant = validateTokenGrant(params, store);
343
+ if ('status' in grant) {
344
+ (0, http_response_js_1.sendJson)(res, grant.status, grant.body);
345
+ return;
346
+ }
347
+ const { issued } = grant;
348
+ (0, http_response_js_1.sendJson)(res, 200, {
349
+ access_token: issued.accessToken,
350
+ token_type: issued.tokenType,
351
+ expires_in: (_a = issued.expiresIn) !== null && _a !== void 0 ? _a : 3600,
352
+ scope: issued.scope,
353
+ });
354
+ }
355
+ async function handleRegister(req, res, config, store) {
356
+ var _a;
357
+ if (req.method !== 'POST') {
358
+ res.writeHead(405, { Allow: 'POST' }).end();
359
+ return;
360
+ }
361
+ const params = await readFormOrJson(req, res, config.maxBodyBytes);
362
+ if (!params)
363
+ return;
364
+ // Public MCP client DCR; confidential Lightdash credentials stay server-side.
365
+ // JSON bodies expand array redirect_uris via readFormOrJson; form bodies use repeated keys.
366
+ const redirectUris = params.getAll('redirect_uris');
367
+ if (redirectUris.length === 0) {
368
+ (0, http_response_js_1.sendJson)(res, 400, {
369
+ error: 'invalid_client_metadata',
370
+ error_description: 'redirect_uris is required',
371
+ });
372
+ return;
373
+ }
374
+ for (const uri of redirectUris) {
375
+ if (!isAllowedClientRedirectUri(uri)) {
376
+ (0, http_response_js_1.sendJson)(res, 400, {
377
+ error: 'invalid_redirect_uri',
378
+ error_description: 'Each redirect_uri must be https, localhost http, or a non-dangerous custom scheme',
379
+ });
380
+ return;
381
+ }
382
+ }
383
+ const registered = store.registerClient(redirectUris);
384
+ if (!registered) {
385
+ (0, http_response_js_1.sendJson)(res, 503, Object.assign({}, AS_BUSY));
386
+ return;
387
+ }
388
+ (0, http_response_js_1.sendJson)(res, 201, {
389
+ client_id: registered.clientId,
390
+ client_id_issued_at: Math.floor(registered.createdAt / 1000),
391
+ redirect_uris: [...registered.redirectUris],
392
+ grant_types: ['authorization_code'],
393
+ response_types: ['code'],
394
+ token_endpoint_auth_method: 'none',
395
+ client_name: (_a = params.get('client_name')) !== null && _a !== void 0 ? _a : 'MCP Client',
396
+ });
397
+ }
398
+ function handleAsMetadata(res, config) {
399
+ (0, http_response_js_1.sendJson)(res, 200, (0, as_metadata_js_1.buildBrokerAuthorizationServerMetadata)(config));
400
+ }
401
+ const BROKER_PATHS = new Set([
402
+ env_js_1.OAUTH_AUTHORIZATION_SERVER_METADATA_PATH,
403
+ env_js_1.OAUTH_AUTHORIZE_PATH,
404
+ env_js_1.OAUTH_CALLBACK_PATH,
405
+ env_js_1.OAUTH_TOKEN_PATH,
406
+ env_js_1.OAUTH_REGISTER_PATH,
407
+ ]);
408
+ /** True for co-located OAuth AS / broker paths (CORS may reflect any Origin). */
409
+ function isOAuthBrokerPath(path) {
410
+ return BROKER_PATHS.has(path);
411
+ }
412
+ /** Creates the OAuth broker request handler for co-located AS façade routes. */
413
+ function createOAuthBroker(config) {
414
+ const store = new pending_store_js_1.OAuthBrokerStore();
415
+ return {
416
+ async handle(req, res, path) {
417
+ if (!isOAuthBrokerPath(path)) {
418
+ return false;
419
+ }
420
+ if (req.method === 'OPTIONS') {
421
+ res.writeHead(204, { Allow: 'GET, POST, OPTIONS' }).end();
422
+ return true;
423
+ }
424
+ if (path === env_js_1.OAUTH_AUTHORIZATION_SERVER_METADATA_PATH && req.method === 'GET') {
425
+ handleAsMetadata(res, config);
426
+ return true;
427
+ }
428
+ if (path === env_js_1.OAUTH_AUTHORIZE_PATH) {
429
+ handleAuthorize(req, res, config, store);
430
+ return true;
431
+ }
432
+ if (path === env_js_1.OAUTH_CALLBACK_PATH) {
433
+ await handleCallback(req, res, config, store);
434
+ return true;
435
+ }
436
+ if (path === env_js_1.OAUTH_TOKEN_PATH) {
437
+ await handleToken(req, res, config, store);
438
+ return true;
439
+ }
440
+ if (path === env_js_1.OAUTH_REGISTER_PATH) {
441
+ await handleRegister(req, res, config, store);
442
+ return true;
443
+ }
444
+ return false;
445
+ },
446
+ };
447
+ }
@@ -0,0 +1 @@
1
+ export {};