@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.
- package/README.md +2 -2
- package/dist/auth/oauth-broker/as-metadata.d.ts +1 -0
- package/dist/auth/oauth-broker/as-metadata.js +5 -1
- package/dist/auth/oauth-broker/client-crypto.d.ts +12 -0
- package/dist/auth/oauth-broker/client-crypto.js +80 -0
- package/dist/auth/oauth-broker/client-directory.d.ts +39 -0
- package/dist/auth/oauth-broker/client-directory.js +104 -0
- package/dist/auth/oauth-broker/client-directory.test.d.ts +1 -0
- package/dist/auth/oauth-broker/client-directory.test.js +134 -0
- package/dist/auth/oauth-broker/lightdash-token.d.ts +8 -0
- package/dist/auth/oauth-broker/lightdash-token.js +72 -8
- package/dist/auth/oauth-broker/mcp-access-token.d.ts +3 -0
- package/dist/auth/oauth-broker/mcp-access-token.js +9 -1
- package/dist/auth/oauth-broker/pending-store.d.ts +16 -4
- package/dist/auth/oauth-broker/pending-store.js +40 -18
- package/dist/auth/oauth-broker/refresh-crypto.d.ts +19 -0
- package/dist/auth/oauth-broker/refresh-crypto.js +70 -0
- package/dist/auth/oauth-broker/refresh-crypto.test.d.ts +1 -0
- package/dist/auth/oauth-broker/refresh-crypto.test.js +40 -0
- package/dist/auth/oauth-broker/refresh-flow.test.d.ts +1 -0
- package/dist/auth/oauth-broker/refresh-flow.test.js +350 -0
- package/dist/auth/oauth-broker/refresh-grant.d.ts +46 -0
- package/dist/auth/oauth-broker/refresh-grant.js +288 -0
- package/dist/auth/oauth-broker/refresh-store.conformance.test.d.ts +1 -0
- package/dist/auth/oauth-broker/refresh-store.conformance.test.js +254 -0
- package/dist/auth/oauth-broker/refresh-store.d.ts +61 -0
- package/dist/auth/oauth-broker/refresh-store.js +124 -0
- package/dist/auth/oauth-broker/routes.d.ts +6 -4
- package/dist/auth/oauth-broker/routes.js +114 -51
- package/dist/auth/oauth-broker/routes.test.js +48 -0
- package/dist/auth/oauth-broker/stores/client-kv.d.ts +46 -0
- package/dist/auth/oauth-broker/stores/client-kv.js +182 -0
- package/dist/auth/oauth-broker/stores/firestore.d.ts +29 -0
- package/dist/auth/oauth-broker/stores/firestore.js +201 -0
- package/dist/auth/oauth-broker/stores/open-client-directory.d.ts +4 -0
- package/dist/auth/oauth-broker/stores/open-client-directory.js +30 -0
- package/dist/auth/oauth-broker/stores/open-refresh-store.d.ts +4 -0
- package/dist/auth/oauth-broker/stores/open-refresh-store.js +24 -0
- package/dist/auth/oauth-broker/stores/postgres.d.ts +13 -0
- package/dist/auth/oauth-broker/stores/postgres.js +193 -0
- package/dist/auth/oauth-broker/stores/redis.d.ts +25 -0
- package/dist/auth/oauth-broker/stores/redis.js +337 -0
- package/dist/auth/resource-server/lightdash-oauth-middleware.d.ts +1 -1
- package/dist/config/env.d.ts +13 -0
- package/dist/config/env.js +14 -1
- package/dist/config/load-mcp-config.d.ts +20 -0
- package/dist/config/load-mcp-config.js +53 -1
- package/dist/config/load-mcp-config.test.js +53 -0
- package/dist/config/oauth-store-key.d.ts +2 -0
- package/dist/config/oauth-store-key.js +17 -0
- package/dist/policy/content-developer.d.ts +4 -1
- package/dist/policy/content-developer.js +7 -3
- package/dist/policy/preview-ledger.d.ts +11 -1
- package/dist/policy/preview-ledger.js +29 -3
- package/dist/policy/rename-rejected.d.ts +9 -0
- package/dist/policy/rename-rejected.js +15 -0
- package/dist/profiles/content-developer/v1/index.js +6 -0
- package/dist/profiles/content-developer/v1/prompt-specs.d.ts +1 -1
- package/dist/profiles/content-developer/v1/resources/playbooks/core.md +15 -0
- package/dist/profiles/content-developer/v1/resources/playbooks/recovery/preview-stale.md +1 -0
- package/dist/profiles/content-reader/v1/prompt-specs.d.ts +1 -1
- package/dist/profiles/semantic-layer/v1/prompts.js +3 -3
- package/dist/profiles/semantic-layer/v1/resources/playbooks/compose-compile.md +6 -3
- package/dist/profiles/semantic-layer/v1/resources/playbooks/core.md +1 -1
- package/dist/server/capabilities.d.ts +1 -1
- package/dist/stdio.process.test.js +3 -1
- package/dist/tools/project/content.js +8 -1
- package/dist/tools/project/developer-content.js +1 -1
- package/dist/tools/project/developer-helpers.d.ts +1 -0
- package/dist/tools/project/developer-helpers.test.js +1 -0
- package/dist/tools/project/developer-rename.d.ts +13 -0
- package/dist/tools/project/developer-rename.js +319 -0
- package/dist/tools/project/developer-rename.test.d.ts +5 -0
- package/dist/tools/project/developer-rename.test.js +296 -0
- package/dist/tools/project/reader-content.js +10 -3
- package/dist/tools/project/rename-instruction.d.ts +58 -0
- package/dist/tools/project/rename-instruction.js +104 -0
- package/dist/tools/query/reader-tool-helpers.d.ts +1 -1
- package/dist/tools/query/reader-tool-helpers.js +4 -0
- package/dist/tools/registry.d.ts +1 -1
- package/dist/tools/semantic/explore-helpers.d.ts +6 -0
- package/dist/tools/semantic/explore-helpers.js +43 -0
- package/dist/tools/semantic/explore-helpers.test.js +17 -0
- package/dist/tools/semantic/query.js +9 -19
- package/dist/tools/semantic/query.test.js +71 -0
- package/dist/transports/streamable-http.js +33 -7
- package/package.json +13 -9
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.digestOfRefreshToken = digestOfRefreshToken;
|
|
4
|
+
exports.attachRefreshToken = attachRefreshToken;
|
|
5
|
+
exports.handleRefreshTokenGrant = handleRefreshTokenGrant;
|
|
6
|
+
exports.cappedExpiryMs = cappedExpiryMs;
|
|
7
|
+
exports.invalidGrant = invalidGrant;
|
|
8
|
+
exports.unavailable = unavailable;
|
|
9
|
+
exports.unsupportedGrantType = unsupportedGrantType;
|
|
10
|
+
const node_crypto_1 = require("node:crypto");
|
|
11
|
+
const oauth_store_key_js_1 = require("../../config/oauth-store-key.js");
|
|
12
|
+
const lightdash_token_js_1 = require("./lightdash-token.js");
|
|
13
|
+
const mcp_access_token_js_1 = require("./mcp-access-token.js");
|
|
14
|
+
const refresh_crypto_js_1 = require("./refresh-crypto.js");
|
|
15
|
+
const refresh_store_js_1 = require("./refresh-store.js");
|
|
16
|
+
const REFRESH_PREFIX = 'ldmcpr1';
|
|
17
|
+
function stop(error) {
|
|
18
|
+
return { ok: false, error };
|
|
19
|
+
}
|
|
20
|
+
function mintRefreshHandle() {
|
|
21
|
+
const handle = (0, node_crypto_1.randomBytes)(32).toString('base64url');
|
|
22
|
+
return { token: `${REFRESH_PREFIX}.${handle}`, digest: digestHandle(handle) };
|
|
23
|
+
}
|
|
24
|
+
/** Returns the store key for an `ldmcpr1` token, or undefined when the token is malformed. */
|
|
25
|
+
function digestOfRefreshToken(token) {
|
|
26
|
+
const dot = token.indexOf('.');
|
|
27
|
+
if (dot <= 0)
|
|
28
|
+
return undefined;
|
|
29
|
+
const prefix = token.slice(0, dot);
|
|
30
|
+
const handle = token.slice(dot + 1);
|
|
31
|
+
if (prefix !== REFRESH_PREFIX || handle.length === 0 || handle.includes('.'))
|
|
32
|
+
return undefined;
|
|
33
|
+
return digestHandle(handle);
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Stores the upstream refresh token from a code exchange and returns the MCP handle.
|
|
37
|
+
* `ok: false` means the store was unavailable and the authorization code should be restored.
|
|
38
|
+
*/
|
|
39
|
+
async function attachRefreshToken(input) {
|
|
40
|
+
const refresh = input.config.oauthRefresh;
|
|
41
|
+
const upstream = input.issued.lightdashRefreshToken;
|
|
42
|
+
if (!refresh || !upstream) {
|
|
43
|
+
if (refresh && !upstream) {
|
|
44
|
+
console.warn('Lightdash token response did not include a refresh_token; MCP refresh was not issued');
|
|
45
|
+
}
|
|
46
|
+
return { ok: true };
|
|
47
|
+
}
|
|
48
|
+
const minted = mintRefreshHandle();
|
|
49
|
+
try {
|
|
50
|
+
const familyId = (0, node_crypto_1.randomUUID)();
|
|
51
|
+
await input.refreshStore.put(minted.digest, newRecord(input.issued, refresh, upstream, {
|
|
52
|
+
handleDigest: minted.digest,
|
|
53
|
+
familyId,
|
|
54
|
+
firstIssuedAtMs: input.nowMs,
|
|
55
|
+
}));
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
if (error instanceof refresh_store_js_1.RefreshStoreError)
|
|
59
|
+
return { ok: false };
|
|
60
|
+
throw error;
|
|
61
|
+
}
|
|
62
|
+
return { ok: true, refreshToken: minted.token };
|
|
63
|
+
}
|
|
64
|
+
async function handleRefreshTokenGrant(input) {
|
|
65
|
+
var _a;
|
|
66
|
+
const refresh = input.config.oauthRefresh;
|
|
67
|
+
if (!refresh)
|
|
68
|
+
return unsupportedGrantType();
|
|
69
|
+
const digest = digestOfRefreshToken(input.refreshToken);
|
|
70
|
+
if (!digest)
|
|
71
|
+
return invalidGrant('Invalid refresh token');
|
|
72
|
+
const nowMs = (_a = input.nowMs) !== null && _a !== void 0 ? _a : Date.now();
|
|
73
|
+
const taken = await takeUsableRecord(input.refreshStore, digest, refresh, {
|
|
74
|
+
resource: input.resource,
|
|
75
|
+
clientId: input.clientId,
|
|
76
|
+
isResourceAllowed: input.isResourceAllowed,
|
|
77
|
+
}, nowMs);
|
|
78
|
+
if (!taken.ok)
|
|
79
|
+
return taken.error;
|
|
80
|
+
return rotateRefreshGrant({
|
|
81
|
+
config: input.config,
|
|
82
|
+
store: input.refreshStore,
|
|
83
|
+
digest,
|
|
84
|
+
record: taken.value.record,
|
|
85
|
+
upstreamRefresh: taken.value.upstreamRefresh,
|
|
86
|
+
refresh,
|
|
87
|
+
nowMs,
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
function mismatchReason(record, match) {
|
|
91
|
+
if (match.clientId !== undefined && record.clientId !== match.clientId) {
|
|
92
|
+
return 'client_id mismatch';
|
|
93
|
+
}
|
|
94
|
+
if (match.resource !== undefined && record.resource !== match.resource) {
|
|
95
|
+
return 'resource mismatch';
|
|
96
|
+
}
|
|
97
|
+
if (match.resource === undefined &&
|
|
98
|
+
match.isResourceAllowed !== undefined &&
|
|
99
|
+
!match.isResourceAllowed(record.resource)) {
|
|
100
|
+
return 'resource mismatch';
|
|
101
|
+
}
|
|
102
|
+
return undefined;
|
|
103
|
+
}
|
|
104
|
+
async function takeUsableRecord(store, digest, refresh, match, nowMs) {
|
|
105
|
+
const consumed = await consumeOrUnavailable(store, digest);
|
|
106
|
+
if (!consumed)
|
|
107
|
+
return stop(unavailable('Refresh store is unavailable'));
|
|
108
|
+
if (consumed.status === 'missing')
|
|
109
|
+
return stop(invalidGrant('Invalid or expired refresh token'));
|
|
110
|
+
const record = consumed.record;
|
|
111
|
+
const upstreamRefresh = decryptStoredRefresh(refresh, digest, record);
|
|
112
|
+
if (upstreamRefresh === undefined) {
|
|
113
|
+
console.warn('OAuth refresh token could not be decrypted');
|
|
114
|
+
await (0, refresh_store_js_1.ignoreRefreshStoreError)(store.delete(digest));
|
|
115
|
+
return stop(invalidGrant('Invalid refresh token'));
|
|
116
|
+
}
|
|
117
|
+
if (consumed.status === 'reused') {
|
|
118
|
+
return revokeAndReject(store, record.familyId, `OAuth refresh token reuse; revoking family ${record.familyId}`, 'Refresh token has already been used');
|
|
119
|
+
}
|
|
120
|
+
if (nowMs > (0, refresh_store_js_1.sessionEndMs)(record.firstIssuedAtMs, refresh.maxSessionSeconds)) {
|
|
121
|
+
return revokeAndReject(store, record.familyId, `OAuth refresh session exceeded; revoking family ${record.familyId}`, 'Session expired. Log in again.');
|
|
122
|
+
}
|
|
123
|
+
const mismatch = mismatchReason(record, match);
|
|
124
|
+
if (mismatch !== undefined) {
|
|
125
|
+
await (0, refresh_store_js_1.ignoreRefreshStoreError)(store.release(digest));
|
|
126
|
+
return stop(invalidGrant(mismatch));
|
|
127
|
+
}
|
|
128
|
+
return { ok: true, value: { record, upstreamRefresh } };
|
|
129
|
+
}
|
|
130
|
+
function decryptStoredRefresh(refresh, digest, record) {
|
|
131
|
+
try {
|
|
132
|
+
return (0, refresh_crypto_js_1.decryptRefreshToken)((0, oauth_store_key_js_1.decodeStoreKey)(refresh.key.expose()), record.encryptedRefreshToken, cipherContext(digest, record));
|
|
133
|
+
}
|
|
134
|
+
catch (error) {
|
|
135
|
+
if (!(error instanceof refresh_crypto_js_1.RefreshCryptoError))
|
|
136
|
+
throw error;
|
|
137
|
+
return undefined;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
async function rotateRefreshGrant(input) {
|
|
141
|
+
const rotated = await refreshUpstream(input.config, input.store, input.digest, input.upstreamRefresh);
|
|
142
|
+
if (!rotated.ok)
|
|
143
|
+
return rotated.error;
|
|
144
|
+
if (!rotated.value.refresh_token) {
|
|
145
|
+
await (0, refresh_store_js_1.ignoreRefreshStoreError)(input.store.delete(input.digest));
|
|
146
|
+
return invalidGrant('Upstream refresh did not rotate the refresh token');
|
|
147
|
+
}
|
|
148
|
+
const minted = mintRotatedAccessToken(input, rotated.value);
|
|
149
|
+
if (!minted) {
|
|
150
|
+
await (0, refresh_store_js_1.ignoreRefreshStoreError)(input.store.delete(input.digest));
|
|
151
|
+
return invalidGrant('Upstream Lightdash credential expired before broker token issuance');
|
|
152
|
+
}
|
|
153
|
+
const next = mintRefreshHandle();
|
|
154
|
+
const stored = await storeRotatedHandle(input, rotated.value.refresh_token, next.digest);
|
|
155
|
+
if (!stored.ok)
|
|
156
|
+
return stored.error;
|
|
157
|
+
return {
|
|
158
|
+
status: 200,
|
|
159
|
+
body: {
|
|
160
|
+
access_token: minted.accessToken,
|
|
161
|
+
token_type: 'Bearer',
|
|
162
|
+
expires_in: minted.expiresIn,
|
|
163
|
+
refresh_token: next.token,
|
|
164
|
+
scope: input.record.scope,
|
|
165
|
+
},
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
function cappedExpiryMs(nowMs, firstIssuedAtMs, refresh, upstreamExpiresIn) {
|
|
169
|
+
const upstreamEnd = nowMs + (upstreamExpiresIn !== null && upstreamExpiresIn !== void 0 ? upstreamExpiresIn : 3600) * 1000;
|
|
170
|
+
return Math.min(upstreamEnd, (0, refresh_store_js_1.sessionEndMs)(firstIssuedAtMs, refresh.maxSessionSeconds));
|
|
171
|
+
}
|
|
172
|
+
async function consumeOrUnavailable(store, digest) {
|
|
173
|
+
try {
|
|
174
|
+
return await store.consume(digest);
|
|
175
|
+
}
|
|
176
|
+
catch (error) {
|
|
177
|
+
if (error instanceof refresh_store_js_1.RefreshStoreError)
|
|
178
|
+
return undefined;
|
|
179
|
+
throw error;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
async function refreshUpstream(config, store, digest, upstreamRefresh) {
|
|
183
|
+
try {
|
|
184
|
+
return { ok: true, value: await (0, lightdash_token_js_1.refreshLightdashAccessToken)(config, upstreamRefresh) };
|
|
185
|
+
}
|
|
186
|
+
catch (error) {
|
|
187
|
+
if ((0, lightdash_token_js_1.isRetryableLightdashTokenError)(error)) {
|
|
188
|
+
await (0, refresh_store_js_1.ignoreRefreshStoreError)(store.release(digest));
|
|
189
|
+
return stop(unavailable('Upstream token refresh is unavailable'));
|
|
190
|
+
}
|
|
191
|
+
if (error instanceof lightdash_token_js_1.LightdashTokenRequestError) {
|
|
192
|
+
await (0, refresh_store_js_1.ignoreRefreshStoreError)(store.delete(digest));
|
|
193
|
+
return stop(invalidGrant('Upstream refresh was rejected'));
|
|
194
|
+
}
|
|
195
|
+
throw error;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
function mintRotatedAccessToken(input, rotated) {
|
|
199
|
+
try {
|
|
200
|
+
return (0, mcp_access_token_js_1.mintMcpAccessToken)(input.config, {
|
|
201
|
+
lightdashAccessToken: rotated.access_token,
|
|
202
|
+
clientId: input.record.clientId,
|
|
203
|
+
resource: input.record.resource,
|
|
204
|
+
scope: input.record.scope,
|
|
205
|
+
expiresAtMs: cappedExpiryMs(input.nowMs, input.record.firstIssuedAtMs, input.refresh, rotated.expires_in),
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
catch (error) {
|
|
209
|
+
if (!(error instanceof mcp_access_token_js_1.McpAccessTokenExpiredError))
|
|
210
|
+
throw error;
|
|
211
|
+
return undefined;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
async function storeRotatedHandle(input, upstreamRefreshToken, digest) {
|
|
215
|
+
try {
|
|
216
|
+
await input.store.put(digest, newRecord({
|
|
217
|
+
clientId: input.record.clientId,
|
|
218
|
+
resource: input.record.resource,
|
|
219
|
+
scope: input.record.scope,
|
|
220
|
+
}, input.refresh, upstreamRefreshToken, {
|
|
221
|
+
handleDigest: digest,
|
|
222
|
+
familyId: input.record.familyId,
|
|
223
|
+
firstIssuedAtMs: input.record.firstIssuedAtMs,
|
|
224
|
+
}));
|
|
225
|
+
return { ok: true, value: undefined };
|
|
226
|
+
}
|
|
227
|
+
catch (error) {
|
|
228
|
+
if (!(error instanceof refresh_store_js_1.RefreshStoreError))
|
|
229
|
+
throw error;
|
|
230
|
+
console.error(`Rotated Lightdash refresh token could not be stored; family ${input.record.familyId} must sign in again`);
|
|
231
|
+
return stop(invalidGrant('Refresh token could not be stored'));
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
function newRecord(issued, refresh, upstreamRefreshToken, stored) {
|
|
235
|
+
return {
|
|
236
|
+
familyId: stored.familyId,
|
|
237
|
+
firstIssuedAtMs: stored.firstIssuedAtMs,
|
|
238
|
+
clientId: issued.clientId,
|
|
239
|
+
resource: issued.resource,
|
|
240
|
+
scope: issued.scope,
|
|
241
|
+
encryptedRefreshToken: (0, refresh_crypto_js_1.encryptRefreshToken)((0, oauth_store_key_js_1.decodeStoreKey)(refresh.key.expose()), upstreamRefreshToken, cipherContext(stored.handleDigest, {
|
|
242
|
+
familyId: stored.familyId,
|
|
243
|
+
clientId: issued.clientId,
|
|
244
|
+
resource: issued.resource,
|
|
245
|
+
scope: issued.scope,
|
|
246
|
+
firstIssuedAtMs: stored.firstIssuedAtMs,
|
|
247
|
+
})),
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
function cipherContext(handleDigest, fields) {
|
|
251
|
+
return Object.assign({ handleDigest }, fields);
|
|
252
|
+
}
|
|
253
|
+
function digestHandle(handle) {
|
|
254
|
+
return (0, node_crypto_1.createHash)('sha256').update(handle).digest('hex');
|
|
255
|
+
}
|
|
256
|
+
function invalidGrant(description) {
|
|
257
|
+
return { status: 400, body: { error: 'invalid_grant', error_description: description } };
|
|
258
|
+
}
|
|
259
|
+
function unavailable(description) {
|
|
260
|
+
return {
|
|
261
|
+
status: 503,
|
|
262
|
+
body: { error: 'temporarily_unavailable', error_description: description },
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
function unsupportedGrantType(refreshEnabled = false) {
|
|
266
|
+
return {
|
|
267
|
+
status: 400,
|
|
268
|
+
body: {
|
|
269
|
+
error: 'unsupported_grant_type',
|
|
270
|
+
error_description: refreshEnabled
|
|
271
|
+
? 'Only authorization_code and refresh_token are supported'
|
|
272
|
+
: 'Only authorization_code is supported',
|
|
273
|
+
},
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
/** A store error asks the client to retry. A completed revoke is `invalid_grant`. */
|
|
277
|
+
async function revokeAndReject(store, familyId, warning, description) {
|
|
278
|
+
console.warn(warning);
|
|
279
|
+
try {
|
|
280
|
+
await store.revokeFamily(familyId);
|
|
281
|
+
}
|
|
282
|
+
catch (error) {
|
|
283
|
+
if (error instanceof refresh_store_js_1.RefreshStoreError)
|
|
284
|
+
return stop(unavailable('Refresh store is unavailable'));
|
|
285
|
+
throw error;
|
|
286
|
+
}
|
|
287
|
+
return stop(invalidGrant(description));
|
|
288
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const pglite_1 = require("@electric-sql/pglite");
|
|
4
|
+
const vitest_1 = require("vitest");
|
|
5
|
+
const refresh_store_js_1 = require("./refresh-store.js");
|
|
6
|
+
const firestore_js_1 = require("./stores/firestore.js");
|
|
7
|
+
const postgres_js_1 = require("./stores/postgres.js");
|
|
8
|
+
const redis_js_1 = require("./stores/redis.js");
|
|
9
|
+
const LONG_SESSION_SECONDS = 3153600000;
|
|
10
|
+
function sample(familyId, token = 'cipher') {
|
|
11
|
+
return {
|
|
12
|
+
familyId,
|
|
13
|
+
firstIssuedAtMs: 1700000000000,
|
|
14
|
+
clientId: 'client',
|
|
15
|
+
resource: 'https://mcp.example.com/semantic-layer/v1/mcp',
|
|
16
|
+
encryptedRefreshToken: token,
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
function exerciseRefreshStore(openStore) {
|
|
20
|
+
(0, vitest_1.it)('consumes a handle once and reports reuse', async () => {
|
|
21
|
+
const store = await openStore();
|
|
22
|
+
await store.put('digest-a', sample('family-a'));
|
|
23
|
+
const first = await store.consume('digest-a');
|
|
24
|
+
(0, vitest_1.expect)(first).toMatchObject({ status: 'ok', record: { familyId: 'family-a' } });
|
|
25
|
+
const second = await store.consume('digest-a');
|
|
26
|
+
(0, vitest_1.expect)(second).toMatchObject({ status: 'reused', record: { familyId: 'family-a' } });
|
|
27
|
+
});
|
|
28
|
+
(0, vitest_1.it)('reports a missing handle', async () => {
|
|
29
|
+
const store = await openStore();
|
|
30
|
+
(0, vitest_1.expect)(await store.consume('missing')).toEqual({ status: 'missing' });
|
|
31
|
+
});
|
|
32
|
+
(0, vitest_1.it)('lets only one of two concurrent consumes succeed', async () => {
|
|
33
|
+
const store = await openStore();
|
|
34
|
+
await store.put('digest-race', sample('family-race'));
|
|
35
|
+
const results = await Promise.all([store.consume('digest-race'), store.consume('digest-race')]);
|
|
36
|
+
const ok = results.filter((result) => result.status === 'ok');
|
|
37
|
+
const reused = results.filter((result) => result.status === 'reused');
|
|
38
|
+
(0, vitest_1.expect)(ok).toHaveLength(1);
|
|
39
|
+
(0, vitest_1.expect)(reused).toMatchObject([{ status: 'reused', record: { familyId: 'family-race' } }]);
|
|
40
|
+
});
|
|
41
|
+
(0, vitest_1.it)('releases a consume so the same handle can be retried', async () => {
|
|
42
|
+
const store = await openStore();
|
|
43
|
+
await store.put('digest-release', sample('family-release'));
|
|
44
|
+
(0, vitest_1.expect)((await store.consume('digest-release')).status).toBe('ok');
|
|
45
|
+
await store.release('digest-release');
|
|
46
|
+
(0, vitest_1.expect)((await store.consume('digest-release')).status).toBe('ok');
|
|
47
|
+
});
|
|
48
|
+
(0, vitest_1.it)('revokeFamily removes every handle in the family', async () => {
|
|
49
|
+
const store = await openStore();
|
|
50
|
+
await store.put('digest-1', sample('family-revoke', 'one'));
|
|
51
|
+
await store.put('digest-2', sample('family-revoke', 'two'));
|
|
52
|
+
await store.revokeFamily('family-revoke');
|
|
53
|
+
(0, vitest_1.expect)(await store.consume('digest-1')).toEqual({ status: 'missing' });
|
|
54
|
+
(0, vitest_1.expect)(await store.consume('digest-2')).toEqual({ status: 'missing' });
|
|
55
|
+
});
|
|
56
|
+
(0, vitest_1.it)('delete removes one handle', async () => {
|
|
57
|
+
const store = await openStore();
|
|
58
|
+
await store.put('digest-delete', sample('family-delete'));
|
|
59
|
+
await store.delete('digest-delete');
|
|
60
|
+
(0, vitest_1.expect)(await store.consume('digest-delete')).toEqual({ status: 'missing' });
|
|
61
|
+
});
|
|
62
|
+
(0, vitest_1.it)('does not store a handle after revokeFamily', async () => {
|
|
63
|
+
const store = await openStore();
|
|
64
|
+
await store.put('digest-old', sample('family-dead'));
|
|
65
|
+
await store.revokeFamily('family-dead');
|
|
66
|
+
await (0, vitest_1.expect)(store.put('digest-new', sample('family-dead'))).rejects.toBeInstanceOf(refresh_store_js_1.RefreshStoreError);
|
|
67
|
+
(0, vitest_1.expect)(await store.consume('digest-new')).toEqual({ status: 'missing' });
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
async function expectPastCapHandle(openStore) {
|
|
71
|
+
vitest_1.vi.useFakeTimers({ toFake: ['Date'] });
|
|
72
|
+
const issuedAt = Date.parse('2026-01-01T00:00:00Z');
|
|
73
|
+
vitest_1.vi.setSystemTime(issuedAt);
|
|
74
|
+
try {
|
|
75
|
+
const store = await openStore();
|
|
76
|
+
await store.put('digest-cap', Object.assign(Object.assign({}, sample('family-cap')), { firstIssuedAtMs: issuedAt }));
|
|
77
|
+
vitest_1.vi.setSystemTime(issuedAt + 61000);
|
|
78
|
+
await (0, vitest_1.expect)(store.consume('digest-cap')).resolves.toMatchObject({
|
|
79
|
+
status: 'ok',
|
|
80
|
+
record: { familyId: 'family-cap' },
|
|
81
|
+
});
|
|
82
|
+
await (0, vitest_1.expect)(store.put('digest-late', Object.assign(Object.assign({}, sample('family-cap')), { firstIssuedAtMs: issuedAt }))).rejects.toBeInstanceOf(refresh_store_js_1.RefreshStoreError);
|
|
83
|
+
}
|
|
84
|
+
finally {
|
|
85
|
+
vitest_1.vi.useRealTimers();
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
(0, vitest_1.describe)('in-memory refresh store', () => {
|
|
89
|
+
exerciseRefreshStore(async () => new refresh_store_js_1.InMemoryRefreshStore());
|
|
90
|
+
});
|
|
91
|
+
(0, vitest_1.describe)('postgres refresh store', () => {
|
|
92
|
+
let db;
|
|
93
|
+
let sql;
|
|
94
|
+
(0, vitest_1.beforeAll)(async () => {
|
|
95
|
+
db = new pglite_1.PGlite();
|
|
96
|
+
await db.waitReady;
|
|
97
|
+
sql = {
|
|
98
|
+
query: async (text, params) => {
|
|
99
|
+
const result = await db.query(text, params);
|
|
100
|
+
return { rows: result.rows };
|
|
101
|
+
},
|
|
102
|
+
};
|
|
103
|
+
}, 30000);
|
|
104
|
+
(0, vitest_1.afterAll)(async () => {
|
|
105
|
+
await db.close();
|
|
106
|
+
});
|
|
107
|
+
exerciseRefreshStore(() => (0, postgres_js_1.createPostgresRefreshStore)(sql, { maxSessionSeconds: LONG_SESSION_SECONDS }));
|
|
108
|
+
(0, vitest_1.it)('returns a handle past the session cap and refuses a later put', async () => {
|
|
109
|
+
await expectPastCapHandle(() => (0, postgres_js_1.createPostgresRefreshStore)(sql, { maxSessionSeconds: 60 }));
|
|
110
|
+
});
|
|
111
|
+
});
|
|
112
|
+
function createMemoryRedis() {
|
|
113
|
+
const strings = new Map();
|
|
114
|
+
const sets = new Map();
|
|
115
|
+
const generation = new Map();
|
|
116
|
+
let watched = new Map();
|
|
117
|
+
function bump(key) {
|
|
118
|
+
var _a;
|
|
119
|
+
generation.set(key, ((_a = generation.get(key)) !== null && _a !== void 0 ? _a : 0) + 1);
|
|
120
|
+
}
|
|
121
|
+
return {
|
|
122
|
+
async watch(...keys) {
|
|
123
|
+
var _a;
|
|
124
|
+
for (const key of keys)
|
|
125
|
+
watched.set(key, (_a = generation.get(key)) !== null && _a !== void 0 ? _a : 0);
|
|
126
|
+
},
|
|
127
|
+
async unwatch() {
|
|
128
|
+
watched = new Map();
|
|
129
|
+
},
|
|
130
|
+
async get(key) {
|
|
131
|
+
var _a;
|
|
132
|
+
return (_a = strings.get(key)) !== null && _a !== void 0 ? _a : null;
|
|
133
|
+
},
|
|
134
|
+
async smembers(key) {
|
|
135
|
+
var _a;
|
|
136
|
+
return [...((_a = sets.get(key)) !== null && _a !== void 0 ? _a : [])];
|
|
137
|
+
},
|
|
138
|
+
multi() {
|
|
139
|
+
const ops = [];
|
|
140
|
+
const api = {
|
|
141
|
+
set(key, value) {
|
|
142
|
+
ops.push(() => {
|
|
143
|
+
strings.set(key, value);
|
|
144
|
+
bump(key);
|
|
145
|
+
});
|
|
146
|
+
return api;
|
|
147
|
+
},
|
|
148
|
+
sadd(key, member) {
|
|
149
|
+
ops.push(() => {
|
|
150
|
+
var _a;
|
|
151
|
+
const members = (_a = sets.get(key)) !== null && _a !== void 0 ? _a : new Set();
|
|
152
|
+
members.add(member);
|
|
153
|
+
sets.set(key, members);
|
|
154
|
+
bump(key);
|
|
155
|
+
});
|
|
156
|
+
return api;
|
|
157
|
+
},
|
|
158
|
+
srem(key, member) {
|
|
159
|
+
ops.push(() => {
|
|
160
|
+
var _a;
|
|
161
|
+
(_a = sets.get(key)) === null || _a === void 0 ? void 0 : _a.delete(member);
|
|
162
|
+
bump(key);
|
|
163
|
+
});
|
|
164
|
+
return api;
|
|
165
|
+
},
|
|
166
|
+
expire() {
|
|
167
|
+
return api;
|
|
168
|
+
},
|
|
169
|
+
del(...keys) {
|
|
170
|
+
ops.push(() => {
|
|
171
|
+
for (const key of keys) {
|
|
172
|
+
strings.delete(key);
|
|
173
|
+
sets.delete(key);
|
|
174
|
+
bump(key);
|
|
175
|
+
}
|
|
176
|
+
});
|
|
177
|
+
return api;
|
|
178
|
+
},
|
|
179
|
+
async exec() {
|
|
180
|
+
var _a;
|
|
181
|
+
for (const [key, seen] of watched) {
|
|
182
|
+
if (((_a = generation.get(key)) !== null && _a !== void 0 ? _a : 0) !== seen) {
|
|
183
|
+
watched = new Map();
|
|
184
|
+
return null;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
for (const op of ops)
|
|
188
|
+
op();
|
|
189
|
+
watched = new Map();
|
|
190
|
+
return ops.map(() => [null, 'OK']);
|
|
191
|
+
},
|
|
192
|
+
};
|
|
193
|
+
return api;
|
|
194
|
+
},
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
(0, vitest_1.describe)('redis refresh store', () => {
|
|
198
|
+
exerciseRefreshStore(async () => (0, redis_js_1.createRedisRefreshStore)(createMemoryRedis(), { maxSessionSeconds: LONG_SESSION_SECONDS }));
|
|
199
|
+
(0, vitest_1.it)('returns a handle past the session cap and refuses a later put', async () => {
|
|
200
|
+
await expectPastCapHandle(async () => (0, redis_js_1.createRedisRefreshStore)(createMemoryRedis(), { maxSessionSeconds: 60 }));
|
|
201
|
+
});
|
|
202
|
+
(0, vitest_1.it)('throws RefreshStoreError when a Redis MULTI command fails inside EXEC', async () => {
|
|
203
|
+
const base = createMemoryRedis();
|
|
204
|
+
const failing = Object.assign(Object.assign({}, base), { multi() {
|
|
205
|
+
const inner = base.multi();
|
|
206
|
+
return Object.assign(Object.assign({}, inner), { async exec() {
|
|
207
|
+
return [[new Error('OOM command not allowed'), null]];
|
|
208
|
+
} });
|
|
209
|
+
} });
|
|
210
|
+
const store = (0, redis_js_1.createRedisRefreshStore)(failing, { maxSessionSeconds: LONG_SESSION_SECONDS });
|
|
211
|
+
await (0, vitest_1.expect)(store.put('digest-oom', sample('family-oom'))).rejects.toBeInstanceOf(refresh_store_js_1.RefreshStoreError);
|
|
212
|
+
});
|
|
213
|
+
});
|
|
214
|
+
function createSerialDocumentStore() {
|
|
215
|
+
const docs = new Map();
|
|
216
|
+
let chain = Promise.resolve();
|
|
217
|
+
return {
|
|
218
|
+
async runTransaction(fn) {
|
|
219
|
+
const run = chain.then(() => fn({
|
|
220
|
+
async get(id) {
|
|
221
|
+
const doc = docs.get(id);
|
|
222
|
+
return doc ? Object.assign({}, doc) : undefined;
|
|
223
|
+
},
|
|
224
|
+
async set(id, doc) {
|
|
225
|
+
docs.set(id, Object.assign({}, doc));
|
|
226
|
+
},
|
|
227
|
+
async delete(id) {
|
|
228
|
+
docs.delete(id);
|
|
229
|
+
},
|
|
230
|
+
async idsByFamily(familyId) {
|
|
231
|
+
return [...docs.entries()]
|
|
232
|
+
.filter(([, doc]) => doc.familyId === familyId)
|
|
233
|
+
.map(([id]) => id);
|
|
234
|
+
},
|
|
235
|
+
}));
|
|
236
|
+
chain = run.then(() => undefined, () => undefined);
|
|
237
|
+
return run;
|
|
238
|
+
},
|
|
239
|
+
async deleteExpired(beforeMs) {
|
|
240
|
+
for (const [id, doc] of docs) {
|
|
241
|
+
if (doc.firstIssuedAtMs < beforeMs)
|
|
242
|
+
docs.delete(id);
|
|
243
|
+
}
|
|
244
|
+
},
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
(0, vitest_1.describe)('firestore refresh store', () => {
|
|
248
|
+
exerciseRefreshStore(async () => (0, firestore_js_1.createFirestoreRefreshStore)(createSerialDocumentStore(), {
|
|
249
|
+
maxSessionSeconds: LONG_SESSION_SECONDS,
|
|
250
|
+
}));
|
|
251
|
+
(0, vitest_1.it)('returns a handle past the session cap and refuses a later put', async () => {
|
|
252
|
+
await expectPastCapHandle(async () => (0, firestore_js_1.createFirestoreRefreshStore)(createSerialDocumentStore(), { maxSessionSeconds: 60 }));
|
|
253
|
+
});
|
|
254
|
+
});
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Server-side Lightdash refresh-token store (ADR-0037).
|
|
3
|
+
*
|
|
4
|
+
* `consume` is single-use. A second consume of the same handle is `reused`
|
|
5
|
+
* so the broker can revoke the family. `release` undoes a consume when the
|
|
6
|
+
* upstream call did not finish.
|
|
7
|
+
*/
|
|
8
|
+
export declare class RefreshStoreError extends Error {
|
|
9
|
+
readonly cause?: unknown;
|
|
10
|
+
constructor(message: string, options?: {
|
|
11
|
+
cause?: unknown;
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
/** Fields stored next to the encrypted upstream refresh token. */
|
|
15
|
+
export interface RefreshStoreRecord {
|
|
16
|
+
familyId: string;
|
|
17
|
+
firstIssuedAtMs: number;
|
|
18
|
+
clientId: string;
|
|
19
|
+
resource: string;
|
|
20
|
+
scope?: string;
|
|
21
|
+
encryptedRefreshToken: string;
|
|
22
|
+
}
|
|
23
|
+
export type ConsumeResult = {
|
|
24
|
+
status: 'missing';
|
|
25
|
+
} | {
|
|
26
|
+
status: 'ok';
|
|
27
|
+
record: RefreshStoreRecord;
|
|
28
|
+
} | {
|
|
29
|
+
status: 'reused';
|
|
30
|
+
record: RefreshStoreRecord;
|
|
31
|
+
};
|
|
32
|
+
export interface RefreshStore {
|
|
33
|
+
put(handleDigest: string, record: RefreshStoreRecord): Promise<void>;
|
|
34
|
+
consume(handleDigest: string): Promise<ConsumeResult>;
|
|
35
|
+
/** Clears a consume so the same handle can be presented again. */
|
|
36
|
+
release(handleDigest: string): Promise<void>;
|
|
37
|
+
revokeFamily(familyId: string): Promise<void>;
|
|
38
|
+
delete(handleDigest: string): Promise<void>;
|
|
39
|
+
close?(): Promise<void>;
|
|
40
|
+
}
|
|
41
|
+
/** Attaches a backend `close` without repeating the five store methods. */
|
|
42
|
+
export declare function withClose(store: RefreshStore, close: () => Promise<void>): RefreshStore;
|
|
43
|
+
/** Wraps a backend failure. An existing `RefreshStoreError` is rethrown as-is. */
|
|
44
|
+
export declare function wrapStoreError<T>(message: string, fn: () => Promise<T>): Promise<T>;
|
|
45
|
+
/** Store cleanup after the OAuth result is already decided. Other errors propagate. */
|
|
46
|
+
export declare function ignoreRefreshStoreError(work: Promise<void>): Promise<void>;
|
|
47
|
+
/** Absolute end of a refresh family, shared by the grant and every store. */
|
|
48
|
+
export declare function sessionEndMs(firstIssuedAtMs: number, maxSessionSeconds: number): number;
|
|
49
|
+
export declare function storeErrorCode(error: unknown): string;
|
|
50
|
+
/** Process-local store used by tests and as the conformance reference. */
|
|
51
|
+
export declare class InMemoryRefreshStore implements RefreshStore {
|
|
52
|
+
private readonly rows;
|
|
53
|
+
private readonly revoked;
|
|
54
|
+
private chain;
|
|
55
|
+
put(handleDigest: string, record: RefreshStoreRecord): Promise<void>;
|
|
56
|
+
consume(handleDigest: string): Promise<ConsumeResult>;
|
|
57
|
+
release(handleDigest: string): Promise<void>;
|
|
58
|
+
revokeFamily(familyId: string): Promise<void>;
|
|
59
|
+
delete(handleDigest: string): Promise<void>;
|
|
60
|
+
private exclusive;
|
|
61
|
+
}
|