@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
@@ -0,0 +1,182 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.OAUTH_CLIENT_POSTGRES_TABLE = exports.OAUTH_CLIENT_REDIS_PREFIX = void 0;
7
+ exports.oauthClientFirestoreCollection = oauthClientFirestoreCollection;
8
+ exports.createRedisClientKv = createRedisClientKv;
9
+ exports.createPostgresClientKv = createPostgresClientKv;
10
+ exports.createFirestoreClientKv = createFirestoreClientKv;
11
+ exports.openRedisClientKv = openRedisClientKv;
12
+ exports.openPostgresClientKv = openPostgresClientKv;
13
+ exports.openFirestoreClientKv = openFirestoreClientKv;
14
+ const firestore_1 = require("@google-cloud/firestore");
15
+ const ioredis_1 = __importDefault(require("ioredis"));
16
+ const pg_1 = require("pg");
17
+ const refresh_store_js_1 = require("../refresh-store.js");
18
+ /** Distinct from `lightdash-tools:oauth-refresh:`. */
19
+ exports.OAUTH_CLIENT_REDIS_PREFIX = 'lightdash-tools:oauth-client:';
20
+ /** Distinct from `lightdash_tools_oauth_refresh`. */
21
+ exports.OAUTH_CLIENT_POSTGRES_TABLE = 'lightdash_tools_oauth_client';
22
+ /** Sibling of the refresh collection so client documents never share it. */
23
+ function oauthClientFirestoreCollection(refreshCollection) {
24
+ return `${refreshCollection}_clients`;
25
+ }
26
+ function createRedisClientKv(client) {
27
+ return {
28
+ async put(id, body, ttlSeconds) {
29
+ await client.set(exports.OAUTH_CLIENT_REDIS_PREFIX + id, body, ttlSeconds);
30
+ },
31
+ async get(id) {
32
+ const value = await client.get(exports.OAUTH_CLIENT_REDIS_PREFIX + id);
33
+ return value !== null && value !== void 0 ? value : undefined;
34
+ },
35
+ async delete(id) {
36
+ await client.del(exports.OAUTH_CLIENT_REDIS_PREFIX + id);
37
+ },
38
+ };
39
+ }
40
+ async function createPostgresClientKv(db) {
41
+ await db.query(`CREATE TABLE IF NOT EXISTS ${exports.OAUTH_CLIENT_POSTGRES_TABLE} (
42
+ client_digest text PRIMARY KEY,
43
+ body text NOT NULL,
44
+ expires_at timestamptz NOT NULL
45
+ )`);
46
+ return {
47
+ async put(id, body, ttlSeconds) {
48
+ const expiresAtMs = Date.now() + ttlSeconds * 1000;
49
+ await db.query(`INSERT INTO ${exports.OAUTH_CLIENT_POSTGRES_TABLE} (client_digest, body, expires_at)
50
+ VALUES ($1, $2, to_timestamp($3::double precision / 1000))
51
+ ON CONFLICT (client_digest) DO UPDATE
52
+ SET body = EXCLUDED.body, expires_at = EXCLUDED.expires_at`, [id, body, expiresAtMs]);
53
+ },
54
+ async get(id) {
55
+ const result = await db.query(`SELECT body FROM ${exports.OAUTH_CLIENT_POSTGRES_TABLE}
56
+ WHERE client_digest = $1 AND expires_at > now()`, [id]);
57
+ const row = result.rows[0];
58
+ if (row)
59
+ return row.body;
60
+ await db.query(`DELETE FROM ${exports.OAUTH_CLIENT_POSTGRES_TABLE}
61
+ WHERE client_digest = $1 AND expires_at <= now()`, [id]);
62
+ return undefined;
63
+ },
64
+ async delete(id) {
65
+ await db.query(`DELETE FROM ${exports.OAUTH_CLIENT_POSTGRES_TABLE} WHERE client_digest = $1`, [id]);
66
+ },
67
+ };
68
+ }
69
+ function createFirestoreClientKv(store, now = Date.now) {
70
+ return {
71
+ async put(id, body, ttlSeconds) {
72
+ await store.set(id, { body, expiresAtMs: now() + ttlSeconds * 1000 });
73
+ },
74
+ async get(id) {
75
+ const doc = await store.get(id);
76
+ if (!doc)
77
+ return undefined;
78
+ if (doc.expiresAtMs <= now()) {
79
+ await store.delete(id);
80
+ return undefined;
81
+ }
82
+ return doc.body;
83
+ },
84
+ async delete(id) {
85
+ await store.delete(id);
86
+ },
87
+ };
88
+ }
89
+ async function openRedisClientKv(config) {
90
+ const client = new ioredis_1.default(config.redisUrl.expose(), {
91
+ lazyConnect: true,
92
+ maxRetriesPerRequest: 2,
93
+ enableOfflineQueue: false,
94
+ });
95
+ client.on('error', (error) => {
96
+ console.error(`Redis client directory error (${(0, refresh_store_js_1.storeErrorCode)(error)})`);
97
+ });
98
+ try {
99
+ await client.connect();
100
+ await client.ping();
101
+ }
102
+ catch (error) {
103
+ client.disconnect();
104
+ console.error(`Redis client directory connection failed (${(0, refresh_store_js_1.storeErrorCode)(error)})`);
105
+ throw new Error('Redis client directory is unavailable');
106
+ }
107
+ return {
108
+ kv: createRedisClientKv({
109
+ get: (key) => client.get(key),
110
+ set: (key, value, expirySeconds) => client.set(key, value, 'EX', expirySeconds),
111
+ del: (key) => client.del(key),
112
+ }),
113
+ close: async () => {
114
+ await client.quit();
115
+ },
116
+ };
117
+ }
118
+ async function openPostgresClientKv(config) {
119
+ const pool = new pg_1.Pool({ connectionString: config.postgresUrl.expose() });
120
+ pool.on('error', (error) => {
121
+ console.error(`Postgres client directory pool error (${(0, refresh_store_js_1.storeErrorCode)(error)})`);
122
+ });
123
+ const db = {
124
+ query: async (sql, params) => {
125
+ const result = await pool.query(sql, params);
126
+ return { rows: result.rows };
127
+ },
128
+ };
129
+ try {
130
+ const kv = await createPostgresClientKv(db);
131
+ return { kv, close: () => pool.end() };
132
+ }
133
+ catch (error) {
134
+ await pool.end().catch(() => undefined);
135
+ console.error(`Postgres client directory connection failed (${(0, refresh_store_js_1.storeErrorCode)(error)})`);
136
+ throw new Error('Postgres client directory is unavailable');
137
+ }
138
+ }
139
+ async function openFirestoreClientKv(config) {
140
+ const db = new firestore_1.Firestore({ projectId: config.firestoreProjectId });
141
+ const collectionName = oauthClientFirestoreCollection(config.firestoreCollection);
142
+ try {
143
+ await db.collection(collectionName).limit(1).get();
144
+ }
145
+ catch (error) {
146
+ await db.terminate().catch(() => undefined);
147
+ const name = error instanceof Error ? error.name : 'Error';
148
+ console.error(`Firestore client directory connection failed (${name})`);
149
+ throw new Error('Firestore client directory is unavailable');
150
+ }
151
+ const collection = db.collection(collectionName);
152
+ const kv = createFirestoreClientKv({
153
+ async get(id) {
154
+ const snap = await collection.doc(id).get();
155
+ if (!snap.exists)
156
+ return undefined;
157
+ const parsed = parseClientDocument(snap.data());
158
+ if (!parsed) {
159
+ await collection.doc(id).delete();
160
+ return undefined;
161
+ }
162
+ return parsed;
163
+ },
164
+ async set(id, doc) {
165
+ await collection.doc(id).set(doc);
166
+ },
167
+ async delete(id) {
168
+ await collection.doc(id).delete();
169
+ },
170
+ });
171
+ return { kv, close: () => db.terminate() };
172
+ }
173
+ function parseClientDocument(value) {
174
+ if (typeof value !== 'object' || value === null)
175
+ return undefined;
176
+ const doc = value;
177
+ if (typeof doc.body !== 'string' || typeof doc.expiresAtMs !== 'number')
178
+ return undefined;
179
+ if (!Number.isSafeInteger(doc.expiresAtMs))
180
+ return undefined;
181
+ return { body: doc.body, expiresAtMs: doc.expiresAtMs };
182
+ }
@@ -0,0 +1,29 @@
1
+ import type { OAuthRefreshConfig } from '../../../config/load-mcp-config.js';
2
+ import type { RefreshStore } from '../refresh-store.js';
3
+ export interface RefreshDocument {
4
+ familyId: string;
5
+ firstIssuedAtMs: number;
6
+ clientId: string;
7
+ resource: string;
8
+ scope: string | null;
9
+ encryptedRefreshToken: string;
10
+ consumedAtMs: number | null;
11
+ }
12
+ /** Transactional document API. Firestore and the conformance double both implement it. */
13
+ export interface RefreshDocTransaction {
14
+ get(id: string): Promise<RefreshDocument | undefined>;
15
+ set(id: string, doc: RefreshDocument): Promise<void>;
16
+ delete(id: string): Promise<void>;
17
+ idsByFamily(familyId: string): Promise<string[]>;
18
+ }
19
+ export interface RefreshDocumentStore {
20
+ runTransaction<T>(fn: (tx: RefreshDocTransaction) => Promise<T>): Promise<T>;
21
+ /** Deletes handle documents whose session start is before `beforeMs`. */
22
+ deleteExpired(beforeMs: number): Promise<void>;
23
+ }
24
+ export declare function createFirestoreRefreshStore(documents: RefreshDocumentStore, options: {
25
+ maxSessionSeconds: number;
26
+ }): RefreshStore;
27
+ export declare function openFirestoreRefreshStore(config: Extract<OAuthRefreshConfig, {
28
+ kind: 'firestore';
29
+ }>): Promise<RefreshStore>;
@@ -0,0 +1,201 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createFirestoreRefreshStore = createFirestoreRefreshStore;
4
+ exports.openFirestoreRefreshStore = openFirestoreRefreshStore;
5
+ const firestore_1 = require("@google-cloud/firestore");
6
+ const refresh_store_js_1 = require("../refresh-store.js");
7
+ const REVOKED_PREFIX = 'revoked:';
8
+ const REVOKE_BATCH = 400;
9
+ function createFirestoreRefreshStore(documents, options) {
10
+ return new FirestoreRefreshStore(documents, options.maxSessionSeconds);
11
+ }
12
+ async function openFirestoreRefreshStore(config) {
13
+ const db = new firestore_1.Firestore({ projectId: config.firestoreProjectId });
14
+ try {
15
+ await db.collection(config.firestoreCollection).limit(1).get();
16
+ }
17
+ catch (error) {
18
+ await db.terminate().catch(() => undefined);
19
+ const name = error instanceof Error ? error.name : 'Error';
20
+ console.error(`Firestore refresh store connection failed (${name})`);
21
+ throw new Error('Firestore refresh store is unavailable');
22
+ }
23
+ const store = createFirestoreRefreshStore(createFirestoreDocumentStore(db, config.firestoreCollection), { maxSessionSeconds: config.maxSessionSeconds });
24
+ return (0, refresh_store_js_1.withClose)(store, () => db.terminate());
25
+ }
26
+ function createFirestoreDocumentStore(db, collectionName) {
27
+ const collection = db.collection(collectionName);
28
+ return {
29
+ async runTransaction(fn) {
30
+ return db.runTransaction(async (tx) => fn({
31
+ async get(id) {
32
+ const snap = await tx.get(collection.doc(id));
33
+ if (!snap.exists)
34
+ return undefined;
35
+ return parseDocument(snap.data());
36
+ },
37
+ async set(id, doc) {
38
+ tx.set(collection.doc(id), doc);
39
+ },
40
+ async delete(id) {
41
+ tx.delete(collection.doc(id));
42
+ },
43
+ async idsByFamily(familyId) {
44
+ const snap = await tx.get(collection.where('familyId', '==', familyId).limit(REVOKE_BATCH));
45
+ return snap.docs.map((doc) => doc.id);
46
+ },
47
+ }));
48
+ },
49
+ async deleteExpired(beforeMs) {
50
+ const snap = await collection
51
+ .where('firstIssuedAtMs', '<', beforeMs)
52
+ .limit(REVOKE_BATCH)
53
+ .get();
54
+ if (snap.empty)
55
+ return;
56
+ const batch = db.batch();
57
+ for (const doc of snap.docs)
58
+ batch.delete(doc.ref);
59
+ await batch.commit();
60
+ },
61
+ };
62
+ }
63
+ class FirestoreRefreshStore {
64
+ constructor(documents, maxSessionSeconds) {
65
+ this.documents = documents;
66
+ this.maxSessionSeconds = maxSessionSeconds;
67
+ }
68
+ async put(handleDigest, record) {
69
+ if (Date.now() > (0, refresh_store_js_1.sessionEndMs)(record.firstIssuedAtMs, this.maxSessionSeconds)) {
70
+ throw new refresh_store_js_1.RefreshStoreError('Refresh session has ended');
71
+ }
72
+ await (0, refresh_store_js_1.ignoreRefreshStoreError)(this.sweep());
73
+ await this.failAsStore(async () => {
74
+ await this.documents.runTransaction(async (tx) => {
75
+ const revoked = await tx.get(revokedDocId(record.familyId));
76
+ if (revoked)
77
+ throw new refresh_store_js_1.RefreshStoreError('Refresh family is revoked');
78
+ await tx.set(handleDigest, toDocument(record, null));
79
+ });
80
+ });
81
+ }
82
+ async consume(handleDigest) {
83
+ return this.failAsStore(async () => {
84
+ const result = await this.documents.runTransaction(async (tx) => {
85
+ const doc = await tx.get(handleDigest);
86
+ if (!doc)
87
+ return { status: 'missing' };
88
+ const revoked = await tx.get(revokedDocId(doc.familyId));
89
+ if (revoked) {
90
+ await tx.delete(handleDigest);
91
+ return { status: 'reused', record: toRecord(doc) };
92
+ }
93
+ if (doc.consumedAtMs !== null) {
94
+ return { status: 'reused', record: toRecord(doc) };
95
+ }
96
+ await tx.set(handleDigest, Object.assign(Object.assign({}, doc), { consumedAtMs: Date.now() }));
97
+ return { status: 'ok', record: toRecord(doc) };
98
+ });
99
+ await (0, refresh_store_js_1.ignoreRefreshStoreError)(this.sweep());
100
+ return result;
101
+ });
102
+ }
103
+ async release(handleDigest) {
104
+ await this.failAsStore(() => this.documents.runTransaction(async (tx) => {
105
+ const doc = await tx.get(handleDigest);
106
+ if (!doc)
107
+ return;
108
+ await tx.set(handleDigest, Object.assign(Object.assign({}, doc), { consumedAtMs: null }));
109
+ }));
110
+ }
111
+ async revokeFamily(familyId) {
112
+ await this.failAsStore(async () => {
113
+ await this.documents.runTransaction(async (tx) => {
114
+ await tx.set(revokedDocId(familyId), tombstone(familyId));
115
+ });
116
+ for (;;) {
117
+ const deleted = await this.documents.runTransaction(async (tx) => {
118
+ const ids = await tx.idsByFamily(familyId);
119
+ const batch = ids.slice(0, REVOKE_BATCH);
120
+ for (const id of batch)
121
+ await tx.delete(id);
122
+ return batch.length;
123
+ });
124
+ if (deleted === 0)
125
+ break;
126
+ }
127
+ });
128
+ await (0, refresh_store_js_1.ignoreRefreshStoreError)(this.sweep());
129
+ }
130
+ async delete(handleDigest) {
131
+ await this.failAsStore(() => this.documents.runTransaction(async (tx) => {
132
+ await tx.delete(handleDigest);
133
+ }));
134
+ }
135
+ failAsStore(fn) {
136
+ return (0, refresh_store_js_1.wrapStoreError)('Firestore refresh store request failed', fn);
137
+ }
138
+ sweep() {
139
+ const cutoff = Date.now() - this.maxSessionSeconds * 1000;
140
+ return (0, refresh_store_js_1.wrapStoreError)('Firestore refresh sweep failed', () => this.documents.deleteExpired(cutoff));
141
+ }
142
+ }
143
+ function revokedDocId(familyId) {
144
+ return `${REVOKED_PREFIX}${familyId}`;
145
+ }
146
+ function tombstone(familyId) {
147
+ return {
148
+ familyId: revokedDocId(familyId),
149
+ firstIssuedAtMs: Date.now(),
150
+ clientId: '',
151
+ resource: '',
152
+ scope: null,
153
+ encryptedRefreshToken: '',
154
+ consumedAtMs: null,
155
+ };
156
+ }
157
+ function toDocument(record, consumedAtMs) {
158
+ var _a;
159
+ return {
160
+ familyId: record.familyId,
161
+ firstIssuedAtMs: record.firstIssuedAtMs,
162
+ clientId: record.clientId,
163
+ resource: record.resource,
164
+ scope: (_a = record.scope) !== null && _a !== void 0 ? _a : null,
165
+ encryptedRefreshToken: record.encryptedRefreshToken,
166
+ consumedAtMs,
167
+ };
168
+ }
169
+ function toRecord(doc) {
170
+ var _a;
171
+ return {
172
+ familyId: doc.familyId,
173
+ firstIssuedAtMs: doc.firstIssuedAtMs,
174
+ clientId: doc.clientId,
175
+ resource: doc.resource,
176
+ scope: (_a = doc.scope) !== null && _a !== void 0 ? _a : undefined,
177
+ encryptedRefreshToken: doc.encryptedRefreshToken,
178
+ };
179
+ }
180
+ function parseDocument(value) {
181
+ if (!isRefreshDocument(value)) {
182
+ throw new refresh_store_js_1.RefreshStoreError('Invalid Firestore refresh document');
183
+ }
184
+ return value;
185
+ }
186
+ function isOptionalTimestamp(value) {
187
+ return value === null || (typeof value === 'number' && Number.isSafeInteger(value));
188
+ }
189
+ function isRefreshDocument(value) {
190
+ if (typeof value !== 'object' || value === null)
191
+ return false;
192
+ const doc = value;
193
+ return (typeof doc.familyId === 'string' &&
194
+ typeof doc.firstIssuedAtMs === 'number' &&
195
+ Number.isSafeInteger(doc.firstIssuedAtMs) &&
196
+ typeof doc.clientId === 'string' &&
197
+ typeof doc.resource === 'string' &&
198
+ (doc.scope === null || typeof doc.scope === 'string') &&
199
+ typeof doc.encryptedRefreshToken === 'string' &&
200
+ isOptionalTimestamp(doc.consumedAtMs));
201
+ }
@@ -0,0 +1,4 @@
1
+ import type { McpHttpConfig } from '../../../config/load-mcp-config.js';
2
+ import type { ClientDirectory } from '../client-directory.js';
3
+ /** Opens the DCR directory for the same store as refresh. Undefined when refresh is off. */
4
+ export declare function openClientDirectory(config: McpHttpConfig): Promise<ClientDirectory | undefined>;
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.openClientDirectory = openClientDirectory;
4
+ const oauth_store_key_js_1 = require("../../../config/oauth-store-key.js");
5
+ const client_directory_js_1 = require("../client-directory.js");
6
+ const client_kv_js_1 = require("./client-kv.js");
7
+ /** Opens the DCR directory for the same store as refresh. Undefined when refresh is off. */
8
+ async function openClientDirectory(config) {
9
+ const refresh = config.oauthRefresh;
10
+ if (!refresh)
11
+ return undefined;
12
+ const key = (0, oauth_store_key_js_1.decodeStoreKey)(refresh.key.expose());
13
+ const opened = await openKv(refresh);
14
+ const directory = (0, client_directory_js_1.createSealedClientDirectory)(opened.kv, { key });
15
+ return Object.assign(Object.assign({}, directory), { close: opened.close });
16
+ }
17
+ async function openKv(refresh) {
18
+ switch (refresh.kind) {
19
+ case 'postgres':
20
+ return (0, client_kv_js_1.openPostgresClientKv)(refresh);
21
+ case 'redis':
22
+ return (0, client_kv_js_1.openRedisClientKv)(refresh);
23
+ case 'firestore':
24
+ return (0, client_kv_js_1.openFirestoreClientKv)(refresh);
25
+ default: {
26
+ const unreachable = refresh;
27
+ return unreachable;
28
+ }
29
+ }
30
+ }
@@ -0,0 +1,4 @@
1
+ import type { McpHttpConfig } from '../../../config/load-mcp-config.js';
2
+ import type { RefreshStore } from '../refresh-store.js';
3
+ /** Opens the configured refresh store. Returns undefined when refresh is off. */
4
+ export declare function openRefreshStore(config: McpHttpConfig): Promise<RefreshStore | undefined>;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.openRefreshStore = openRefreshStore;
4
+ const firestore_js_1 = require("./firestore.js");
5
+ const postgres_js_1 = require("./postgres.js");
6
+ const redis_js_1 = require("./redis.js");
7
+ /** Opens the configured refresh store. Returns undefined when refresh is off. */
8
+ async function openRefreshStore(config) {
9
+ const refresh = config.oauthRefresh;
10
+ if (!refresh)
11
+ return undefined;
12
+ switch (refresh.kind) {
13
+ case 'postgres':
14
+ return (0, postgres_js_1.openPostgresRefreshStore)(refresh);
15
+ case 'redis':
16
+ return (0, redis_js_1.openRedisRefreshStore)(refresh);
17
+ case 'firestore':
18
+ return (0, firestore_js_1.openFirestoreRefreshStore)(refresh);
19
+ default: {
20
+ const unreachable = refresh;
21
+ return unreachable;
22
+ }
23
+ }
24
+ }
@@ -0,0 +1,13 @@
1
+ import type { OAuthRefreshConfig } from '../../../config/load-mcp-config.js';
2
+ import type { RefreshStore } from '../refresh-store.js';
3
+ export interface SqlQueryable {
4
+ query<Row extends Record<string, unknown>>(sql: string, params?: unknown[]): Promise<{
5
+ rows: Row[];
6
+ }>;
7
+ }
8
+ export declare function createPostgresRefreshStore(db: SqlQueryable, options: {
9
+ maxSessionSeconds: number;
10
+ }): Promise<RefreshStore>;
11
+ export declare function openPostgresRefreshStore(config: Extract<OAuthRefreshConfig, {
12
+ kind: 'postgres';
13
+ }>): Promise<RefreshStore>;
@@ -0,0 +1,193 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createPostgresRefreshStore = createPostgresRefreshStore;
4
+ exports.openPostgresRefreshStore = openPostgresRefreshStore;
5
+ const pg_1 = require("pg");
6
+ const refresh_store_js_1 = require("../refresh-store.js");
7
+ const TABLE = 'lightdash_tools_oauth_refresh';
8
+ const FAMILY = 'lightdash_tools_oauth_refresh_family';
9
+ const SWEEP_BATCH = 400;
10
+ /** One statement: a failed read rolls the consume mark back with the update. */
11
+ const CONSUME_SQL = `WITH marked AS (
12
+ UPDATE ${TABLE}
13
+ SET consumed_at = now()
14
+ WHERE handle_digest = $1 AND consumed_at IS NULL
15
+ AND NOT EXISTS (
16
+ SELECT 1 FROM ${FAMILY} AS family_row
17
+ WHERE family_row.family_id = ${TABLE}.family_id
18
+ AND family_row.revoked
19
+ )
20
+ RETURNING family_id, first_issued_at_ms, client_id, resource, scope, encrypted_refresh_token
21
+ )
22
+ SELECT 'ok' AS outcome, family_id, first_issued_at_ms,
23
+ client_id, resource, scope, encrypted_refresh_token
24
+ FROM marked
25
+ UNION ALL
26
+ SELECT 'reused', family_id, first_issued_at_ms,
27
+ client_id, resource, scope, encrypted_refresh_token
28
+ FROM ${TABLE}
29
+ WHERE handle_digest = $1
30
+ AND NOT EXISTS (SELECT 1 FROM marked)`;
31
+ async function createPostgresRefreshStore(db, options) {
32
+ await ensureRefreshTable(db);
33
+ return new PostgresRefreshStore(db, options.maxSessionSeconds);
34
+ }
35
+ async function openPostgresRefreshStore(config) {
36
+ const pool = new pg_1.Pool({ connectionString: config.postgresUrl.expose() });
37
+ pool.on('error', (error) => {
38
+ console.error(`Postgres refresh pool error (${(0, refresh_store_js_1.storeErrorCode)(error)})`);
39
+ });
40
+ const db = {
41
+ query: async (sql, params) => {
42
+ const result = await pool.query(sql, params);
43
+ return { rows: result.rows };
44
+ },
45
+ };
46
+ try {
47
+ const store = await createPostgresRefreshStore(db, {
48
+ maxSessionSeconds: config.maxSessionSeconds,
49
+ });
50
+ return (0, refresh_store_js_1.withClose)(store, () => pool.end());
51
+ }
52
+ catch (error) {
53
+ await pool.end().catch(() => undefined);
54
+ console.error(`Postgres refresh store connection failed (${(0, refresh_store_js_1.storeErrorCode)(error)}). Check LIGHTDASH_TOOLS_OAUTH_STORE_POSTGRES_URL.`);
55
+ throw new Error('Postgres refresh store is unavailable');
56
+ }
57
+ }
58
+ async function ensureRefreshTable(db) {
59
+ await db.query(`CREATE TABLE IF NOT EXISTS ${TABLE} (
60
+ handle_digest text PRIMARY KEY,
61
+ family_id text NOT NULL,
62
+ first_issued_at_ms bigint NOT NULL,
63
+ client_id text NOT NULL,
64
+ resource text NOT NULL,
65
+ scope text,
66
+ encrypted_refresh_token text NOT NULL,
67
+ consumed_at timestamptz
68
+ )`);
69
+ await db.query(`CREATE INDEX IF NOT EXISTS ${TABLE}_family_idx ON ${TABLE} (family_id)`);
70
+ await db.query(`CREATE INDEX IF NOT EXISTS ${TABLE}_issued_idx ON ${TABLE} (first_issued_at_ms)`);
71
+ await db.query(`CREATE TABLE IF NOT EXISTS ${FAMILY} (
72
+ family_id text PRIMARY KEY,
73
+ revoked boolean NOT NULL,
74
+ expires_at_ms bigint NOT NULL
75
+ )`);
76
+ await db.query(`CREATE INDEX IF NOT EXISTS ${FAMILY}_expires_idx ON ${FAMILY} (expires_at_ms)`);
77
+ }
78
+ class PostgresRefreshStore {
79
+ constructor(db, maxSessionSeconds) {
80
+ this.db = db;
81
+ this.maxSessionSeconds = maxSessionSeconds;
82
+ }
83
+ async put(handleDigest, record) {
84
+ this.assertSessionOpen(record.firstIssuedAtMs);
85
+ await (0, refresh_store_js_1.ignoreRefreshStoreError)(this.sweep());
86
+ await this.failAsStore(async () => {
87
+ var _a;
88
+ const inserted = await this.db.query(`WITH family_row AS (
89
+ INSERT INTO ${FAMILY} (family_id, revoked, expires_at_ms)
90
+ VALUES ($1, false, $2)
91
+ ON CONFLICT (family_id) DO UPDATE SET family_id = EXCLUDED.family_id
92
+ RETURNING revoked
93
+ )
94
+ INSERT INTO ${TABLE} (
95
+ handle_digest, family_id, first_issued_at_ms,
96
+ client_id, resource, scope, encrypted_refresh_token
97
+ )
98
+ SELECT $3, $1, $4, $5, $6, $7, $8
99
+ FROM family_row
100
+ WHERE revoked = false
101
+ RETURNING handle_digest`, [
102
+ record.familyId,
103
+ this.expiresAt(record.firstIssuedAtMs),
104
+ handleDigest,
105
+ record.firstIssuedAtMs,
106
+ record.clientId,
107
+ record.resource,
108
+ (_a = record.scope) !== null && _a !== void 0 ? _a : null,
109
+ record.encryptedRefreshToken,
110
+ ]);
111
+ if (!inserted.rows[0]) {
112
+ throw new refresh_store_js_1.RefreshStoreError('Refresh family is revoked');
113
+ }
114
+ });
115
+ }
116
+ async consume(handleDigest) {
117
+ return this.failAsStore(async () => {
118
+ const decided = await this.db.query(CONSUME_SQL, [handleDigest]);
119
+ await (0, refresh_store_js_1.ignoreRefreshStoreError)(this.sweep());
120
+ const row = decided.rows[0];
121
+ if (!row)
122
+ return { status: 'missing' };
123
+ if (row.outcome === 'reused')
124
+ return { status: 'reused', record: mapRow(row) };
125
+ return { status: 'ok', record: mapRow(row) };
126
+ });
127
+ }
128
+ async release(handleDigest) {
129
+ await this.failAsStore(async () => {
130
+ await this.db.query(`UPDATE ${TABLE} SET consumed_at = NULL WHERE handle_digest = $1`, [
131
+ handleDigest,
132
+ ]);
133
+ });
134
+ }
135
+ async revokeFamily(familyId) {
136
+ await this.failAsStore(async () => {
137
+ await this.db.query(`INSERT INTO ${FAMILY} (family_id, revoked, expires_at_ms)
138
+ VALUES ($1, true, $2)
139
+ ON CONFLICT (family_id) DO UPDATE SET revoked = true`, [familyId, this.expiresAt(Date.now())]);
140
+ await this.db.query(`DELETE FROM ${TABLE} WHERE family_id = $1`, [familyId]);
141
+ });
142
+ await (0, refresh_store_js_1.ignoreRefreshStoreError)(this.sweep());
143
+ }
144
+ async delete(handleDigest) {
145
+ await this.failAsStore(async () => {
146
+ await this.db.query(`DELETE FROM ${TABLE} WHERE handle_digest = $1`, [handleDigest]);
147
+ });
148
+ }
149
+ failAsStore(fn) {
150
+ return (0, refresh_store_js_1.wrapStoreError)('Postgres refresh store request failed', fn);
151
+ }
152
+ /** Drops at most 400 expired rows after the presented handle has been read. */
153
+ sweep() {
154
+ const now = Date.now();
155
+ const cutoff = now - this.maxSessionSeconds * 1000;
156
+ return (0, refresh_store_js_1.wrapStoreError)('Postgres refresh sweep failed', async () => {
157
+ await this.db.query(`DELETE FROM ${TABLE}
158
+ WHERE ctid IN (
159
+ SELECT ctid FROM ${TABLE} WHERE first_issued_at_ms < $1 ORDER BY ctid LIMIT ${SWEEP_BATCH}
160
+ )`, [cutoff]);
161
+ await this.db.query(`DELETE FROM ${FAMILY}
162
+ WHERE ctid IN (
163
+ SELECT ctid FROM ${FAMILY} WHERE expires_at_ms < $1 ORDER BY ctid LIMIT ${SWEEP_BATCH}
164
+ )`, [now]);
165
+ });
166
+ }
167
+ assertSessionOpen(firstIssuedAtMs) {
168
+ if (Date.now() > (0, refresh_store_js_1.sessionEndMs)(firstIssuedAtMs, this.maxSessionSeconds)) {
169
+ throw new refresh_store_js_1.RefreshStoreError('Refresh session has ended');
170
+ }
171
+ }
172
+ expiresAt(firstIssuedAtMs) {
173
+ return (0, refresh_store_js_1.sessionEndMs)(firstIssuedAtMs, this.maxSessionSeconds);
174
+ }
175
+ }
176
+ function mapRow(row) {
177
+ var _a;
178
+ return {
179
+ familyId: row.family_id,
180
+ firstIssuedAtMs: asSafeInteger(row.first_issued_at_ms),
181
+ clientId: row.client_id,
182
+ resource: row.resource,
183
+ scope: (_a = row.scope) !== null && _a !== void 0 ? _a : undefined,
184
+ encryptedRefreshToken: row.encrypted_refresh_token,
185
+ };
186
+ }
187
+ function asSafeInteger(value) {
188
+ const parsed = typeof value === 'number' ? value : Number(value);
189
+ if (!Number.isSafeInteger(parsed)) {
190
+ throw new refresh_store_js_1.RefreshStoreError('Invalid refresh-store timestamp');
191
+ }
192
+ return parsed;
193
+ }