@lightdash-tools/mcp 0.23.0 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/README.md +2 -2
  2. package/dist/auth/oauth-broker/as-metadata.d.ts +1 -0
  3. package/dist/auth/oauth-broker/as-metadata.js +5 -1
  4. package/dist/auth/oauth-broker/client-crypto.d.ts +12 -0
  5. package/dist/auth/oauth-broker/client-crypto.js +80 -0
  6. package/dist/auth/oauth-broker/client-directory.d.ts +39 -0
  7. package/dist/auth/oauth-broker/client-directory.js +104 -0
  8. package/dist/auth/oauth-broker/client-directory.test.d.ts +1 -0
  9. package/dist/auth/oauth-broker/client-directory.test.js +134 -0
  10. package/dist/auth/oauth-broker/lightdash-token.d.ts +8 -0
  11. package/dist/auth/oauth-broker/lightdash-token.js +72 -8
  12. package/dist/auth/oauth-broker/mcp-access-token.d.ts +3 -0
  13. package/dist/auth/oauth-broker/mcp-access-token.js +9 -1
  14. package/dist/auth/oauth-broker/pending-store.d.ts +16 -4
  15. package/dist/auth/oauth-broker/pending-store.js +40 -18
  16. package/dist/auth/oauth-broker/refresh-crypto.d.ts +19 -0
  17. package/dist/auth/oauth-broker/refresh-crypto.js +70 -0
  18. package/dist/auth/oauth-broker/refresh-crypto.test.d.ts +1 -0
  19. package/dist/auth/oauth-broker/refresh-crypto.test.js +40 -0
  20. package/dist/auth/oauth-broker/refresh-flow.test.d.ts +1 -0
  21. package/dist/auth/oauth-broker/refresh-flow.test.js +350 -0
  22. package/dist/auth/oauth-broker/refresh-grant.d.ts +46 -0
  23. package/dist/auth/oauth-broker/refresh-grant.js +288 -0
  24. package/dist/auth/oauth-broker/refresh-store.conformance.test.d.ts +1 -0
  25. package/dist/auth/oauth-broker/refresh-store.conformance.test.js +254 -0
  26. package/dist/auth/oauth-broker/refresh-store.d.ts +61 -0
  27. package/dist/auth/oauth-broker/refresh-store.js +124 -0
  28. package/dist/auth/oauth-broker/routes.d.ts +6 -4
  29. package/dist/auth/oauth-broker/routes.js +114 -51
  30. package/dist/auth/oauth-broker/routes.test.js +48 -0
  31. package/dist/auth/oauth-broker/stores/client-kv.d.ts +46 -0
  32. package/dist/auth/oauth-broker/stores/client-kv.js +182 -0
  33. package/dist/auth/oauth-broker/stores/firestore.d.ts +29 -0
  34. package/dist/auth/oauth-broker/stores/firestore.js +201 -0
  35. package/dist/auth/oauth-broker/stores/open-client-directory.d.ts +4 -0
  36. package/dist/auth/oauth-broker/stores/open-client-directory.js +30 -0
  37. package/dist/auth/oauth-broker/stores/open-refresh-store.d.ts +4 -0
  38. package/dist/auth/oauth-broker/stores/open-refresh-store.js +24 -0
  39. package/dist/auth/oauth-broker/stores/postgres.d.ts +13 -0
  40. package/dist/auth/oauth-broker/stores/postgres.js +193 -0
  41. package/dist/auth/oauth-broker/stores/redis.d.ts +25 -0
  42. package/dist/auth/oauth-broker/stores/redis.js +337 -0
  43. package/dist/auth/resource-server/lightdash-oauth-middleware.d.ts +1 -1
  44. package/dist/config/env.d.ts +13 -0
  45. package/dist/config/env.js +14 -1
  46. package/dist/config/load-mcp-config.d.ts +20 -0
  47. package/dist/config/load-mcp-config.js +53 -1
  48. package/dist/config/load-mcp-config.test.js +53 -0
  49. package/dist/config/oauth-store-key.d.ts +2 -0
  50. package/dist/config/oauth-store-key.js +17 -0
  51. package/dist/policy/content-developer.d.ts +4 -1
  52. package/dist/policy/content-developer.js +7 -3
  53. package/dist/policy/preview-ledger.d.ts +11 -1
  54. package/dist/policy/preview-ledger.js +29 -3
  55. package/dist/policy/rename-rejected.d.ts +9 -0
  56. package/dist/policy/rename-rejected.js +15 -0
  57. package/dist/profiles/content-developer/v1/index.js +6 -0
  58. package/dist/profiles/content-developer/v1/prompt-specs.d.ts +1 -1
  59. package/dist/profiles/content-developer/v1/resources/playbooks/core.md +15 -0
  60. package/dist/profiles/content-developer/v1/resources/playbooks/recovery/preview-stale.md +1 -0
  61. package/dist/profiles/content-reader/v1/prompt-specs.d.ts +1 -1
  62. package/dist/profiles/semantic-layer/v1/prompts.js +3 -3
  63. package/dist/profiles/semantic-layer/v1/resources/playbooks/compose-compile.md +6 -3
  64. package/dist/profiles/semantic-layer/v1/resources/playbooks/core.md +1 -1
  65. package/dist/server/capabilities.d.ts +1 -1
  66. package/dist/stdio.process.test.js +3 -1
  67. package/dist/tools/project/content.js +8 -1
  68. package/dist/tools/project/developer-content.js +1 -1
  69. package/dist/tools/project/developer-helpers.d.ts +1 -0
  70. package/dist/tools/project/developer-helpers.test.js +1 -0
  71. package/dist/tools/project/developer-rename.d.ts +13 -0
  72. package/dist/tools/project/developer-rename.js +319 -0
  73. package/dist/tools/project/developer-rename.test.d.ts +5 -0
  74. package/dist/tools/project/developer-rename.test.js +296 -0
  75. package/dist/tools/project/reader-content.js +10 -3
  76. package/dist/tools/project/rename-instruction.d.ts +58 -0
  77. package/dist/tools/project/rename-instruction.js +104 -0
  78. package/dist/tools/query/reader-tool-helpers.d.ts +1 -1
  79. package/dist/tools/query/reader-tool-helpers.js +4 -0
  80. package/dist/tools/registry.d.ts +1 -1
  81. package/dist/tools/semantic/explore-helpers.d.ts +6 -0
  82. package/dist/tools/semantic/explore-helpers.js +43 -0
  83. package/dist/tools/semantic/explore-helpers.test.js +17 -0
  84. package/dist/tools/semantic/query.js +9 -19
  85. package/dist/tools/semantic/query.test.js +71 -0
  86. package/dist/transports/streamable-http.js +33 -7
  87. package/package.json +13 -9
package/README.md CHANGED
@@ -81,7 +81,7 @@ HTTP process probes (unauthenticated, not MCP tools; always mounted even when `L
81
81
  - Hosted OAuth (Cursor URL-only): [docs/operators/cursor-claude.md](../../docs/operators/cursor-claude.md)
82
82
  - Operator guide: [docs/operators/mcp-oauth.md](../../docs/operators/mcp-oauth.md)
83
83
 
84
- Local Compose smoke: `docker compose -f docker-compose.dev.yml up --build` → `http://localhost:8080/semantic-layer/v1/mcp` (Compose healthcheck is `GET /health/live`).
84
+ Local Compose smoke: `docker compose -f docker-compose.dev.yml up --build` → `http://localhost:8080/semantic-layer/v1/mcp` (Compose healthcheck is `GET /health/live`). Optional refresh stores use profiles `postgres`, `redis`, or `firestore` ([Local Compose](../../docs/operators/mcp-oauth.md#local-compose)).
85
85
 
86
86
  ## Configuration
87
87
 
@@ -212,7 +212,7 @@ Project-scoped discovery, metadata, bounded `run_chart` / `run_dashboard_tile`,
212
212
 
213
213
  ### `content-developer`
214
214
 
215
- Author charts (as-code) and dashboards behind preview → `confirm_preview` → apply with HMAC `previewToken`. No warehouse execution or hard delete. Server name: `lightdash-mcp-cdev`.
215
+ Author charts (as-code) and dashboards behind preview → `confirm_preview` → apply with HMAC `previewToken`. No warehouse execution or hard delete. Server name: `lightdash-mcp-cdev`. Five rename tools repair a missing field or model behind the same gate with `resourceKind` `rename`. They are `list_rename_fields`, `preview_rename`, `rename_chart`, `rename_dashboard_filter`, and `rename_project` (ADR-0036).
216
216
 
217
217
  ### `content-governance`
218
218
 
@@ -10,6 +10,7 @@ export interface AuthorizationServerMetadata {
10
10
  token_endpoint_auth_methods_supported: string[];
11
11
  scopes_supported: string[];
12
12
  }
13
+ export declare function brokerGrantTypes(config: McpHttpConfig): string[];
13
14
  /**
14
15
  * RFC 8414 metadata for the MCP-hosted OAuth broker (issuer = PUBLIC_URL).
15
16
  * On an extra invoke origin, token/DCR URLs move to that origin; issuer and
@@ -1,8 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.brokerGrantTypes = brokerGrantTypes;
3
4
  exports.buildBrokerAuthorizationServerMetadata = buildBrokerAuthorizationServerMetadata;
4
5
  const env_js_1 = require("../../config/env.js");
5
6
  const public_url_js_1 = require("../../config/public-url.js");
7
+ function brokerGrantTypes(config) {
8
+ return config.oauthRefresh ? ['authorization_code', 'refresh_token'] : ['authorization_code'];
9
+ }
6
10
  /**
7
11
  * RFC 8414 metadata for the MCP-hosted OAuth broker (issuer = PUBLIC_URL).
8
12
  * On an extra invoke origin, token/DCR URLs move to that origin; issuer and
@@ -16,7 +20,7 @@ function buildBrokerAuthorizationServerMetadata(config, tokenOrigin) {
16
20
  token_endpoint: `${tokenOrigin}${env_js_1.OAUTH_TOKEN_PATH}`,
17
21
  registration_endpoint: `${tokenOrigin}${env_js_1.OAUTH_REGISTER_PATH}`,
18
22
  response_types_supported: ['code'],
19
- grant_types_supported: ['authorization_code'],
23
+ grant_types_supported: brokerGrantTypes(config),
20
24
  code_challenge_methods_supported: ['S256'],
21
25
  token_endpoint_auth_methods_supported: ['none'],
22
26
  scopes_supported: config.scopesSupported,
@@ -0,0 +1,12 @@
1
+ export declare class ClientCryptoError extends Error {
2
+ constructor(message: string);
3
+ }
4
+ export interface ClientRecordContext {
5
+ clientId: string;
6
+ redirectUris: readonly string[];
7
+ createdAt: number;
8
+ }
9
+ /** The tag fails if client id, redirects, or createdAt change. The body is not a second copy of them. */
10
+ export declare function encryptClientRecord(key: Buffer, context: ClientRecordContext): string;
11
+ /** Throws when the tag does not match the stored client id and redirect set. */
12
+ export declare function decryptClientRecord(key: Buffer, payload: string, context: ClientRecordContext): void;
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ClientCryptoError = void 0;
4
+ exports.encryptClientRecord = encryptClientRecord;
5
+ exports.decryptClientRecord = decryptClientRecord;
6
+ const node_crypto_1 = require("node:crypto");
7
+ const ALGORITHM = 'aes-256-gcm';
8
+ const IV_LENGTH = 12;
9
+ const TAG_LENGTH = 16;
10
+ const KEY_LENGTH = 32;
11
+ /** Distinct from the refresh-token AAD. Binds client id and the redirect set. */
12
+ const AAD_PREFIX = 'lightdash-tools:oauth-client:v1';
13
+ const MALFORMED_RECORD = 'Malformed client record';
14
+ class ClientCryptoError extends Error {
15
+ constructor(message) {
16
+ super(message);
17
+ this.name = 'ClientCryptoError';
18
+ }
19
+ }
20
+ exports.ClientCryptoError = ClientCryptoError;
21
+ /** Stable order so the tag does not depend on registration order. */
22
+ function canonicalRedirectUris(redirectUris) {
23
+ return [...redirectUris].sort();
24
+ }
25
+ function lengthPrefixed(value) {
26
+ return `${Buffer.byteLength(value, 'utf8')}:${value}`;
27
+ }
28
+ function additionalData(context) {
29
+ const fields = [
30
+ AAD_PREFIX,
31
+ context.clientId,
32
+ String(context.createdAt),
33
+ ...canonicalRedirectUris(context.redirectUris),
34
+ ];
35
+ return Buffer.from(fields.map((field) => lengthPrefixed(field)).join('\0'), 'utf8');
36
+ }
37
+ const SEALED_BODY = Buffer.from('ok');
38
+ /** The tag fails if client id, redirects, or createdAt change. The body is not a second copy of them. */
39
+ function encryptClientRecord(key, context) {
40
+ assertKey(key);
41
+ const iv = (0, node_crypto_1.randomBytes)(IV_LENGTH);
42
+ const cipher = (0, node_crypto_1.createCipheriv)(ALGORITHM, key, iv);
43
+ cipher.setAAD(additionalData(context));
44
+ const ciphertext = Buffer.concat([cipher.update(SEALED_BODY), cipher.final()]);
45
+ const tag = cipher.getAuthTag();
46
+ return [iv, ciphertext, tag].map((part) => part.toString('base64url')).join('.');
47
+ }
48
+ /** Throws when the tag does not match the stored client id and redirect set. */
49
+ function decryptClientRecord(key, payload, context) {
50
+ assertKey(key);
51
+ const parts = payload.split('.');
52
+ if (parts.length !== 3) {
53
+ throw new ClientCryptoError(MALFORMED_RECORD);
54
+ }
55
+ const [ivPart, cipherPart, tagPart] = parts;
56
+ if (!ivPart || !cipherPart || !tagPart) {
57
+ throw new ClientCryptoError(MALFORMED_RECORD);
58
+ }
59
+ const iv = Buffer.from(ivPart, 'base64url');
60
+ const ciphertext = Buffer.from(cipherPart, 'base64url');
61
+ const tag = Buffer.from(tagPart, 'base64url');
62
+ if (iv.length !== IV_LENGTH || tag.length !== TAG_LENGTH) {
63
+ throw new ClientCryptoError(MALFORMED_RECORD);
64
+ }
65
+ const decipher = (0, node_crypto_1.createDecipheriv)(ALGORITHM, key, iv);
66
+ decipher.setAAD(additionalData(context));
67
+ decipher.setAuthTag(tag);
68
+ try {
69
+ decipher.update(ciphertext);
70
+ decipher.final();
71
+ }
72
+ catch (_a) {
73
+ throw new ClientCryptoError('Client record authentication failed');
74
+ }
75
+ }
76
+ function assertKey(key) {
77
+ if (key.length !== KEY_LENGTH) {
78
+ throw new ClientCryptoError('Store key must be 32 bytes');
79
+ }
80
+ }
@@ -0,0 +1,39 @@
1
+ /** A restarted process must not revive a client the in-memory map would already have dropped. */
2
+ export declare const CLIENT_DIRECTORY_TTL_MS: number;
3
+ /** Dynamic client registration row. Redirect URIs are not secret; the tag protects them. */
4
+ export interface StoredClient {
5
+ clientId: string;
6
+ redirectUris: readonly string[];
7
+ createdAt: number;
8
+ }
9
+ /**
10
+ * Durable DCR clients. Separate from `RefreshStore`: these rows are not single-use handles.
11
+ * Absent when `LIGHTDASH_TOOLS_OAUTH_STORE` is unset.
12
+ */
13
+ export interface ClientDirectory {
14
+ put(client: StoredClient): Promise<void>;
15
+ /** Returns undefined on a miss, expiry, or a row whose authentication tag fails. */
16
+ get(clientId: string): Promise<StoredClient | undefined>;
17
+ delete(clientId: string): Promise<void>;
18
+ close?(): Promise<void>;
19
+ }
20
+ /** Byte store used by the Redis, Postgres, and Firestore adapters. */
21
+ export interface ClientKv {
22
+ put(id: string, body: string, ttlSeconds: number): Promise<void>;
23
+ get(id: string): Promise<string | undefined>;
24
+ delete(id: string): Promise<void>;
25
+ }
26
+ export interface SealedClientDirectoryOptions {
27
+ key: Buffer;
28
+ ttlMs?: number;
29
+ now?: () => number;
30
+ }
31
+ /** Authenticates each row with the store key. A bad tag deletes the row and returns a miss. */
32
+ export declare function createSealedClientDirectory(kv: ClientKv, options: SealedClientDirectoryOptions): ClientDirectory;
33
+ /** In-memory `ClientKv` for sealed-directory tests. */
34
+ export declare class InMemoryClientKv implements ClientKv {
35
+ readonly rows: Map<string, string>;
36
+ put(id: string, body: string, _ttlSeconds: number): Promise<void>;
37
+ get(id: string): Promise<string | undefined>;
38
+ delete(id: string): Promise<void>;
39
+ }
@@ -0,0 +1,104 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.InMemoryClientKv = exports.CLIENT_DIRECTORY_TTL_MS = void 0;
4
+ exports.createSealedClientDirectory = createSealedClientDirectory;
5
+ const node_crypto_1 = require("node:crypto");
6
+ const client_crypto_js_1 = require("./client-crypto.js");
7
+ /** A restarted process must not revive a client the in-memory map would already have dropped. */
8
+ exports.CLIENT_DIRECTORY_TTL_MS = 24 * 60 * 60 * 1000;
9
+ function clientKeyDigest(clientId) {
10
+ return (0, node_crypto_1.createHash)('sha256').update(clientId, 'utf8').digest('hex');
11
+ }
12
+ /** Authenticates each row with the store key. A bad tag deletes the row and returns a miss. */
13
+ function createSealedClientDirectory(kv, options) {
14
+ var _a, _b;
15
+ const ttlMs = (_a = options.ttlMs) !== null && _a !== void 0 ? _a : exports.CLIENT_DIRECTORY_TTL_MS;
16
+ const now = (_b = options.now) !== null && _b !== void 0 ? _b : Date.now;
17
+ return {
18
+ async put(client) {
19
+ const redirectUris = [...client.redirectUris].sort();
20
+ const context = {
21
+ clientId: client.clientId,
22
+ redirectUris,
23
+ createdAt: client.createdAt,
24
+ };
25
+ const body = JSON.stringify({
26
+ createdAt: client.createdAt,
27
+ redirectUris,
28
+ sealed: (0, client_crypto_js_1.encryptClientRecord)(options.key, context),
29
+ });
30
+ const remainingMs = client.createdAt + ttlMs - now();
31
+ const ttlSeconds = Math.max(1, Math.ceil(remainingMs / 1000));
32
+ await kv.put(clientKeyDigest(client.clientId), body, ttlSeconds);
33
+ },
34
+ async get(clientId) {
35
+ const id = clientKeyDigest(clientId);
36
+ const raw = await kv.get(id);
37
+ if (raw === undefined)
38
+ return undefined;
39
+ const parsed = parseBlob(raw);
40
+ if (!parsed || parsed.createdAt + ttlMs <= now()) {
41
+ await kv.delete(id);
42
+ return undefined;
43
+ }
44
+ try {
45
+ (0, client_crypto_js_1.decryptClientRecord)(options.key, parsed.sealed, {
46
+ clientId,
47
+ redirectUris: parsed.redirectUris,
48
+ createdAt: parsed.createdAt,
49
+ });
50
+ }
51
+ catch (error) {
52
+ if (!(error instanceof client_crypto_js_1.ClientCryptoError))
53
+ throw error;
54
+ await kv.delete(id);
55
+ return undefined;
56
+ }
57
+ return { clientId, redirectUris: parsed.redirectUris, createdAt: parsed.createdAt };
58
+ },
59
+ async delete(clientId) {
60
+ await kv.delete(clientKeyDigest(clientId));
61
+ },
62
+ };
63
+ }
64
+ function parseBlob(raw) {
65
+ let value;
66
+ try {
67
+ value = JSON.parse(raw);
68
+ }
69
+ catch (_a) {
70
+ return undefined;
71
+ }
72
+ if (typeof value !== 'object' || value === null)
73
+ return undefined;
74
+ const blob = value;
75
+ if (typeof blob.createdAt !== 'number' || !Number.isSafeInteger(blob.createdAt))
76
+ return undefined;
77
+ if (typeof blob.sealed !== 'string')
78
+ return undefined;
79
+ if (!Array.isArray(blob.redirectUris))
80
+ return undefined;
81
+ if (!blob.redirectUris.every((uri) => typeof uri === 'string'))
82
+ return undefined;
83
+ return {
84
+ createdAt: blob.createdAt,
85
+ redirectUris: blob.redirectUris,
86
+ sealed: blob.sealed,
87
+ };
88
+ }
89
+ /** In-memory `ClientKv` for sealed-directory tests. */
90
+ class InMemoryClientKv {
91
+ constructor() {
92
+ this.rows = new Map();
93
+ }
94
+ async put(id, body, _ttlSeconds) {
95
+ this.rows.set(id, body);
96
+ }
97
+ async get(id) {
98
+ return this.rows.get(id);
99
+ }
100
+ async delete(id) {
101
+ this.rows.delete(id);
102
+ }
103
+ }
104
+ exports.InMemoryClientKv = InMemoryClientKv;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const node_crypto_1 = require("node:crypto");
4
+ const pglite_1 = require("@electric-sql/pglite");
5
+ const vitest_1 = require("vitest");
6
+ const client_directory_js_1 = require("./client-directory.js");
7
+ const pending_store_js_1 = require("./pending-store.js");
8
+ const client_kv_js_1 = require("./stores/client-kv.js");
9
+ const KEY = (0, node_crypto_1.randomBytes)(32);
10
+ function sample() {
11
+ return {
12
+ clientId: 'client-1',
13
+ redirectUris: ['https://app.example/other', 'https://app.example/cb'],
14
+ createdAt: 1700000000000,
15
+ };
16
+ }
17
+ async function roundTrip(kv) {
18
+ const directory = (0, client_directory_js_1.createSealedClientDirectory)(kv, { key: KEY, now: () => sample().createdAt });
19
+ const client = sample();
20
+ await directory.put(client);
21
+ const loaded = await directory.get(client.clientId);
22
+ (0, vitest_1.expect)(loaded === null || loaded === void 0 ? void 0 : loaded.clientId).toBe(client.clientId);
23
+ (0, vitest_1.expect)(loaded === null || loaded === void 0 ? void 0 : loaded.redirectUris).toEqual([...client.redirectUris].sort());
24
+ (0, vitest_1.expect)(loaded === null || loaded === void 0 ? void 0 : loaded.createdAt).toBe(client.createdAt);
25
+ }
26
+ (0, vitest_1.describe)('sealed client directory', () => {
27
+ (0, vitest_1.it)('drops a client older than 24 hours and deletes the row', async () => {
28
+ let now = 1000;
29
+ const kv = new client_directory_js_1.InMemoryClientKv();
30
+ const directory = (0, client_directory_js_1.createSealedClientDirectory)(kv, { key: KEY, now: () => now });
31
+ await directory.put({
32
+ clientId: 'old',
33
+ redirectUris: ['https://app.example/cb'],
34
+ createdAt: now,
35
+ });
36
+ now += client_directory_js_1.CLIENT_DIRECTORY_TTL_MS + 1;
37
+ (0, vitest_1.expect)(await directory.get('old')).toBeUndefined();
38
+ (0, vitest_1.expect)(kv.rows.size).toBe(0);
39
+ });
40
+ (0, vitest_1.it)('writes registrations only, not pending authorizations or codes', async () => {
41
+ const puts = [];
42
+ const store = new pending_store_js_1.InMemoryOAuthBrokerStore({
43
+ clientDirectory: {
44
+ async put(client) {
45
+ puts.push(client.clientId);
46
+ },
47
+ async get() {
48
+ return undefined;
49
+ },
50
+ async delete() {
51
+ return undefined;
52
+ },
53
+ },
54
+ });
55
+ const client = await store.registerClient(['https://app.example/cb']);
56
+ const pending = await store.createPending({
57
+ clientId: client.clientId,
58
+ redirectUri: 'https://app.example/cb',
59
+ codeChallenge: 'challenge',
60
+ codeChallengeMethod: 'S256',
61
+ resource: 'https://mcp.example/mcp',
62
+ });
63
+ await store.issueCode(pending, { accessToken: 'access' });
64
+ (0, vitest_1.expect)(puts).toEqual([client.clientId]);
65
+ });
66
+ });
67
+ (0, vitest_1.describe)('redis client directory', () => {
68
+ (0, vitest_1.it)('round-trips a client under the client key prefix with an expiry', async () => {
69
+ var _a, _b;
70
+ const strings = new Map();
71
+ const ttls = new Map();
72
+ await roundTrip((0, client_kv_js_1.createRedisClientKv)(memoryRedis(strings, ttls)));
73
+ const keys = [...strings.keys()];
74
+ (0, vitest_1.expect)(keys).toHaveLength(1);
75
+ (0, vitest_1.expect)((_a = keys[0]) === null || _a === void 0 ? void 0 : _a.startsWith(client_kv_js_1.OAUTH_CLIENT_REDIS_PREFIX)).toBe(true);
76
+ (0, vitest_1.expect)((_b = keys[0]) === null || _b === void 0 ? void 0 : _b.includes('oauth-refresh')).toBe(false);
77
+ (0, vitest_1.expect)(ttls.get(keys[0])).toBe(client_directory_js_1.CLIENT_DIRECTORY_TTL_MS / 1000);
78
+ });
79
+ });
80
+ (0, vitest_1.describe)('postgres client directory', () => {
81
+ let db;
82
+ let sql;
83
+ (0, vitest_1.beforeAll)(async () => {
84
+ db = new pglite_1.PGlite();
85
+ await db.waitReady;
86
+ sql = {
87
+ query: async (text, params) => {
88
+ const result = await db.query(text, params);
89
+ return { rows: result.rows };
90
+ },
91
+ };
92
+ }, 30000);
93
+ (0, vitest_1.afterAll)(async () => {
94
+ await db.close();
95
+ });
96
+ (0, vitest_1.it)('round-trips a client in its own table', async () => {
97
+ await roundTrip(await (0, client_kv_js_1.createPostgresClientKv)(sql));
98
+ const tables = await db.query(`SELECT table_name FROM information_schema.tables WHERE table_name LIKE 'lightdash_tools_oauth%'`);
99
+ (0, vitest_1.expect)(tables.rows.map((row) => row.table_name)).toEqual(['lightdash_tools_oauth_client']);
100
+ });
101
+ });
102
+ (0, vitest_1.describe)('firestore client directory', () => {
103
+ (0, vitest_1.it)('keeps clients in a sibling collection', () => {
104
+ (0, vitest_1.expect)((0, client_kv_js_1.oauthClientFirestoreCollection)('oauth_refresh')).toBe('oauth_refresh_clients');
105
+ });
106
+ (0, vitest_1.it)('round-trips a client document', async () => {
107
+ const docs = new Map();
108
+ await roundTrip((0, client_kv_js_1.createFirestoreClientKv)({
109
+ async get(id) {
110
+ return docs.get(id);
111
+ },
112
+ async set(id, doc) {
113
+ docs.set(id, doc);
114
+ },
115
+ async delete(id) {
116
+ docs.delete(id);
117
+ },
118
+ }));
119
+ (0, vitest_1.expect)(docs.size).toBe(1);
120
+ });
121
+ });
122
+ function memoryRedis(strings, ttls) {
123
+ return {
124
+ get: async (key) => { var _a; return (_a = strings.get(key)) !== null && _a !== void 0 ? _a : null; },
125
+ set: async (key, value, expirySeconds) => {
126
+ strings.set(key, value);
127
+ ttls.set(key, expirySeconds);
128
+ },
129
+ del: async (key) => {
130
+ strings.delete(key);
131
+ ttls.delete(key);
132
+ },
133
+ };
134
+ }
@@ -6,8 +6,16 @@ export interface LightdashTokenResponse {
6
6
  refresh_token?: string;
7
7
  scope?: string;
8
8
  }
9
+ export declare class LightdashTokenRequestError extends Error {
10
+ readonly status: number;
11
+ constructor(status: number, message: string);
12
+ }
13
+ /** True when the refresh should be retried and the stored handle kept. */
14
+ export declare function isRetryableLightdashTokenError(error: unknown): boolean;
9
15
  /** Exchanges an authorization code at Lightdash using the server-held confidential client. */
10
16
  export declare function exchangeLightdashAuthorizationCode(config: McpHttpConfig, code: string): Promise<LightdashTokenResponse>;
17
+ /** Exchanges a Lightdash refresh token. The refresh token rotates on success. */
18
+ export declare function refreshLightdashAccessToken(config: McpHttpConfig, refreshToken: string): Promise<LightdashTokenResponse>;
11
19
  /**
12
20
  * Builds the downstream Lightdash authorize URL for the server-held confidential client.
13
21
  *
@@ -1,6 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LightdashTokenRequestError = void 0;
4
+ exports.isRetryableLightdashTokenError = isRetryableLightdashTokenError;
3
5
  exports.exchangeLightdashAuthorizationCode = exchangeLightdashAuthorizationCode;
6
+ exports.refreshLightdashAccessToken = refreshLightdashAccessToken;
4
7
  exports.buildLightdashAuthorizeUrl = buildLightdashAuthorizeUrl;
5
8
  const load_mcp_config_js_1 = require("../../config/load-mcp-config.js");
6
9
  const lightdash_oauth_upstream_contract_js_1 = require("../lightdash-oauth-upstream-contract.js");
@@ -20,19 +23,59 @@ function parseLightdashTokenResponse(body) {
20
23
  scope: typeof record.scope === 'string' ? record.scope : undefined,
21
24
  };
22
25
  }
26
+ class LightdashTokenRequestError extends Error {
27
+ constructor(status, message) {
28
+ super(message);
29
+ this.name = 'LightdashTokenRequestError';
30
+ this.status = status;
31
+ }
32
+ }
33
+ exports.LightdashTokenRequestError = LightdashTokenRequestError;
34
+ const LIGHTDASH_TOKEN_TIMEOUT_MS = 30000;
35
+ const OAUTH_ERROR_CODE_RE = /^[A-Za-z0-9_-]{1,64}$/;
36
+ /** True when the refresh should be retried and the stored handle kept. */
37
+ function isRetryableLightdashTokenError(error) {
38
+ if (error instanceof LightdashTokenRequestError) {
39
+ return error.status >= 500 || error.status === 429;
40
+ }
41
+ // `fetch` reports a network failure as TypeError and a timeout as TimeoutError/AbortError.
42
+ return (error instanceof TypeError ||
43
+ (error instanceof Error && (error.name === 'TimeoutError' || error.name === 'AbortError')));
44
+ }
23
45
  /** Exchanges an authorization code at Lightdash using the server-held confidential client. */
24
46
  async function exchangeLightdashAuthorizationCode(config, code) {
25
- if (!config.oauthClientId || !config.oauthClientSecret) {
26
- throw new Error('OAuth client credentials are required for token exchange');
27
- }
28
- const tokenUrl = `${config.lightdashUrl}${lightdash_oauth_upstream_contract_js_1.LIGHTDASH_OAUTH_TOKEN_ENDPOINT}`;
47
+ const credentials = requireClientCredentials(config);
29
48
  const body = new URLSearchParams({
30
49
  grant_type: 'authorization_code',
31
50
  code,
32
51
  redirect_uri: (0, load_mcp_config_js_1.getOAuthCallbackUrl)(config),
33
- client_id: config.oauthClientId,
34
- client_secret: config.oauthClientSecret.expose(),
52
+ client_id: credentials.clientId,
53
+ client_secret: credentials.clientSecret,
54
+ });
55
+ return postLightdashToken(config, body);
56
+ }
57
+ /** Exchanges a Lightdash refresh token. The refresh token rotates on success. */
58
+ async function refreshLightdashAccessToken(config, refreshToken) {
59
+ const credentials = requireClientCredentials(config);
60
+ const body = new URLSearchParams({
61
+ grant_type: 'refresh_token',
62
+ refresh_token: refreshToken,
63
+ client_id: credentials.clientId,
64
+ client_secret: credentials.clientSecret,
35
65
  });
66
+ return postLightdashToken(config, body);
67
+ }
68
+ function requireClientCredentials(config) {
69
+ if (!config.oauthClientId || !config.oauthClientSecret) {
70
+ throw new Error('OAuth client credentials are required for token exchange');
71
+ }
72
+ return {
73
+ clientId: config.oauthClientId,
74
+ clientSecret: config.oauthClientSecret.expose(),
75
+ };
76
+ }
77
+ async function postLightdashToken(config, body) {
78
+ const tokenUrl = `${config.lightdashUrl}${lightdash_oauth_upstream_contract_js_1.LIGHTDASH_OAUTH_TOKEN_ENDPOINT}`;
36
79
  const headers = {
37
80
  'Content-Type': 'application/x-www-form-urlencoded',
38
81
  Accept: 'application/json',
@@ -44,12 +87,33 @@ async function exchangeLightdashAuthorizationCode(config, code) {
44
87
  method: 'POST',
45
88
  headers,
46
89
  body,
90
+ signal: AbortSignal.timeout(LIGHTDASH_TOKEN_TIMEOUT_MS),
47
91
  });
48
92
  if (!response.ok) {
49
93
  const text = await response.text().catch(() => '');
50
- throw new Error(`Lightdash token exchange failed (${response.status}): ${text.slice(0, 200)}`);
94
+ const code = readOAuthErrorCode(text);
95
+ throw new LightdashTokenRequestError(response.status, code
96
+ ? `Lightdash token exchange failed (${response.status}: ${code})`
97
+ : `Lightdash token exchange failed (${response.status})`);
98
+ }
99
+ try {
100
+ return parseLightdashTokenResponse(await response.json());
101
+ }
102
+ catch (_a) {
103
+ throw new LightdashTokenRequestError(502, 'Lightdash token response was not a token');
104
+ }
105
+ }
106
+ function readOAuthErrorCode(body) {
107
+ try {
108
+ const parsed = JSON.parse(body);
109
+ if (typeof parsed.error === 'string' && OAUTH_ERROR_CODE_RE.test(parsed.error)) {
110
+ return parsed.error;
111
+ }
112
+ }
113
+ catch (_a) {
114
+ // Non-JSON upstream error body; omit raw text from error logs.
51
115
  }
52
- return parseLightdashTokenResponse(await response.json());
116
+ return undefined;
53
117
  }
54
118
  /**
55
119
  * Builds the downstream Lightdash authorize URL for the server-held confidential client.
@@ -14,6 +14,9 @@ export interface McpAccessTokenPayload {
14
14
  /** Unix timestamp in seconds. */
15
15
  exp: number;
16
16
  }
17
+ export declare class McpAccessTokenExpiredError extends Error {
18
+ constructor();
19
+ }
17
20
  export declare function mintMcpAccessToken(config: McpHttpConfig, input: {
18
21
  lightdashAccessToken: string;
19
22
  clientId: string;
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.McpAccessTokenExpiredError = void 0;
3
4
  exports.mintMcpAccessToken = mintMcpAccessToken;
4
5
  exports.verifyMcpAccessToken = verifyMcpAccessToken;
5
6
  const node_crypto_1 = require("node:crypto");
@@ -9,6 +10,13 @@ const AAD = Buffer.from(KEY_CONTEXT, 'utf8');
9
10
  const IV_BYTES = 12;
10
11
  const AUTH_TAG_BYTES = 16;
11
12
  const MAX_TOKEN_LENGTH = 16 * 1024;
13
+ class McpAccessTokenExpiredError extends Error {
14
+ constructor() {
15
+ super('Upstream Lightdash access token is already expired');
16
+ this.name = 'McpAccessTokenExpiredError';
17
+ }
18
+ }
19
+ exports.McpAccessTokenExpiredError = McpAccessTokenExpiredError;
12
20
  function deriveEncryptionKey(config) {
13
21
  if (!config.oauthClientSecret) {
14
22
  throw new Error('OAuth client secret is required to protect MCP access tokens');
@@ -43,7 +51,7 @@ function mintMcpAccessToken(config, input, nowMs = Date.now()) {
43
51
  const exp = Math.floor(input.expiresAtMs / 1000);
44
52
  const expiresIn = exp - nowSeconds;
45
53
  if (expiresIn <= 0) {
46
- throw new Error('Upstream Lightdash access token is already expired');
54
+ throw new McpAccessTokenExpiredError();
47
55
  }
48
56
  const payload = {
49
57
  v: 1,
@@ -1,10 +1,12 @@
1
1
  /**
2
2
  * OAuth broker pending / codes / DCR clients (ADR-0007 / ADR-0019).
3
3
  *
4
- * All values are JSON-serializable. Backend: in-memory only — process-local.
5
- * Multi-instance OAuth authorization/code exchange needs sticky `/oauth/*` or a single replica.
4
+ * Pending authorizations and authorization codes stay process-local.
5
+ * Client registrations are write-through to `ClientDirectory` when the OAuth store is on.
6
+ * Multi-instance authorization-code exchange still needs sticky `/oauth/*` or a single replica.
6
7
  * Issued MCP access tokens are self-contained and do not depend on this store after exchange.
7
8
  */
9
+ import { type ClientDirectory } from './client-directory.js';
8
10
  export interface PendingAuthorization {
9
11
  /** Broker state sent to Lightdash (opaque). */
10
12
  brokerState: string;
@@ -32,6 +34,11 @@ export interface IssuedAuthorizationCode {
32
34
  accessToken: string;
33
35
  expiresIn?: number;
34
36
  tokenType: string;
37
+ /**
38
+ * Upstream Lightdash refresh token, held only until `/oauth/token` stores it.
39
+ * Absent when refresh storage is off.
40
+ */
41
+ lightdashRefreshToken?: string;
35
42
  /** Exact RFC 8707 MCP protected-resource URI bound during authorization. */
36
43
  resource: string;
37
44
  /** MCP authorization scope. */
@@ -47,7 +54,7 @@ export interface RegisteredClient {
47
54
  export declare const DEFAULT_PENDING_TTL_MS: number;
48
55
  /** Issued broker authorization code TTL (RFC 6749 recommends ≤10m; keep short). */
49
56
  export declare const DEFAULT_CODE_TTL_MS: number;
50
- /** Registered DCR clients TTL (long enough for interactive OAuth). */
57
+ /** Registered DCR clients TTL. Matches the durable directory so a restart cannot revive a dropped client. */
51
58
  export declare const DEFAULT_CLIENT_TTL_MS: number;
52
59
  export declare const DEFAULT_MAX_PENDING = 10000;
53
60
  export declare const DEFAULT_MAX_CODES = 10000;
@@ -59,9 +66,11 @@ export type OAuthBrokerStoreOptions = {
59
66
  maxPending?: number;
60
67
  maxCodes?: number;
61
68
  maxClients?: number;
69
+ /** When set, register writes through and getClient reads through after a memory miss. */
70
+ clientDirectory?: ClientDirectory;
62
71
  };
63
72
  /**
64
- * OAuth broker ephemeral store (ADR-0019). In-memory only (process-local).
73
+ * OAuth broker ephemeral store (ADR-0019). Pending and codes stay process-local.
65
74
  * Async methods keep call sites await-uniform for future backends if needed.
66
75
  */
67
76
  export interface OAuthBrokerStore {
@@ -74,6 +83,7 @@ export interface OAuthBrokerStore {
74
83
  accessToken: string;
75
84
  expiresIn?: number;
76
85
  tokenType?: string;
86
+ lightdashRefreshToken?: string;
77
87
  }): Promise<IssuedAuthorizationCode | undefined>;
78
88
  /** Atomic get+delete for one-time code consume. */
79
89
  takeCode(code: string): Promise<IssuedAuthorizationCode | undefined>;
@@ -97,6 +107,7 @@ export declare class InMemoryOAuthBrokerStore implements OAuthBrokerStore {
97
107
  private readonly maxPending;
98
108
  private readonly maxCodes;
99
109
  private readonly maxClients;
110
+ private readonly clientDirectory;
100
111
  constructor(options?: OAuthBrokerStoreOptions);
101
112
  /**
102
113
  * Registers a public MCP client with exact redirect URIs, or returns undefined
@@ -116,6 +127,7 @@ export declare class InMemoryOAuthBrokerStore implements OAuthBrokerStore {
116
127
  accessToken: string;
117
128
  expiresIn?: number;
118
129
  tokenType?: string;
130
+ lightdashRefreshToken?: string;
119
131
  }): Promise<IssuedAuthorizationCode | undefined>;
120
132
  /** Atomic get+delete of an issued authorization code. */
121
133
  takeCode(code: string): Promise<IssuedAuthorizationCode | undefined>;