@frontmcp/plugin-cache 1.7.2 → 1.8.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/cache.plugin.d.ts +19 -0
- package/cache.plugin.d.ts.map +1 -1
- package/cache.types.d.ts +14 -0
- package/cache.types.d.ts.map +1 -1
- package/esm/index.mjs +3659 -79
- package/esm/package.json +3 -2
- package/index.js +3637 -76
- package/package.json +3 -2
package/esm/index.mjs
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
|
+
var __create = Object.create;
|
|
1
2
|
var __defProp = Object.defineProperty;
|
|
2
3
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
3
7
|
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
4
8
|
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
5
9
|
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
@@ -7,6 +11,29 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
|
|
|
7
11
|
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
8
12
|
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
9
13
|
});
|
|
14
|
+
var __commonJS = (cb, mod) => function __require3() {
|
|
15
|
+
try {
|
|
16
|
+
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
17
|
+
} catch (e) {
|
|
18
|
+
throw mod = 0, e;
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
var __copyProps = (to, from, except, desc) => {
|
|
22
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
23
|
+
for (let key of __getOwnPropNames(from))
|
|
24
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
25
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
26
|
+
}
|
|
27
|
+
return to;
|
|
28
|
+
};
|
|
29
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
30
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
31
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
32
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
33
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
34
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
35
|
+
mod
|
|
36
|
+
));
|
|
10
37
|
var __decorateClass = (decorators, target, key, kind) => {
|
|
11
38
|
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
|
|
12
39
|
for (var i = decorators.length - 1, decorator; i >= 0; i--)
|
|
@@ -17,81 +44,3545 @@ var __decorateClass = (decorators, target, key, kind) => {
|
|
|
17
44
|
};
|
|
18
45
|
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
19
46
|
|
|
47
|
+
// libs/utils/dist/event-emitter/node-event-emitter.js
|
|
48
|
+
var require_node_event_emitter = __commonJS({
|
|
49
|
+
"libs/utils/dist/event-emitter/node-event-emitter.js"(exports, module) {
|
|
50
|
+
"use strict";
|
|
51
|
+
var __defProp3 = Object.defineProperty;
|
|
52
|
+
var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
|
|
53
|
+
var __getOwnPropNames3 = Object.getOwnPropertyNames;
|
|
54
|
+
var __hasOwnProp2 = Object.prototype.hasOwnProperty;
|
|
55
|
+
var __export2 = (target, all) => {
|
|
56
|
+
for (var name in all)
|
|
57
|
+
__defProp3(target, name, { get: all[name], enumerable: true });
|
|
58
|
+
};
|
|
59
|
+
var __copyProps2 = (to, from, except, desc) => {
|
|
60
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
61
|
+
for (let key of __getOwnPropNames3(from))
|
|
62
|
+
if (!__hasOwnProp2.call(to, key) && key !== except)
|
|
63
|
+
__defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
|
|
64
|
+
}
|
|
65
|
+
return to;
|
|
66
|
+
};
|
|
67
|
+
var __toCommonJS = (mod) => __copyProps2(__defProp3({}, "__esModule", { value: true }), mod);
|
|
68
|
+
var node_event_emitter_exports = {};
|
|
69
|
+
__export2(node_event_emitter_exports, {
|
|
70
|
+
EventEmitter: () => import_events.EventEmitter
|
|
71
|
+
});
|
|
72
|
+
module.exports = __toCommonJS(node_event_emitter_exports);
|
|
73
|
+
var import_events = __require("events");
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
// libs/utils/dist/crypto/node.js
|
|
78
|
+
var require_node = __commonJS({
|
|
79
|
+
"libs/utils/dist/crypto/node.js"(exports, module) {
|
|
80
|
+
"use strict";
|
|
81
|
+
var __create2 = Object.create;
|
|
82
|
+
var __defProp3 = Object.defineProperty;
|
|
83
|
+
var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
|
|
84
|
+
var __getOwnPropNames3 = Object.getOwnPropertyNames;
|
|
85
|
+
var __getProtoOf2 = Object.getPrototypeOf;
|
|
86
|
+
var __hasOwnProp2 = Object.prototype.hasOwnProperty;
|
|
87
|
+
var __export2 = (target, all) => {
|
|
88
|
+
for (var name in all)
|
|
89
|
+
__defProp3(target, name, { get: all[name], enumerable: true });
|
|
90
|
+
};
|
|
91
|
+
var __copyProps2 = (to, from, except, desc) => {
|
|
92
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
93
|
+
for (let key of __getOwnPropNames3(from))
|
|
94
|
+
if (!__hasOwnProp2.call(to, key) && key !== except)
|
|
95
|
+
__defProp3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
|
|
96
|
+
}
|
|
97
|
+
return to;
|
|
98
|
+
};
|
|
99
|
+
var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2(
|
|
100
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
101
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
102
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
103
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
104
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp3(target, "default", { value: mod, enumerable: true }) : target,
|
|
105
|
+
mod
|
|
106
|
+
));
|
|
107
|
+
var __toCommonJS = (mod) => __copyProps2(__defProp3({}, "__esModule", { value: true }), mod);
|
|
108
|
+
var node_exports2 = {};
|
|
109
|
+
__export2(node_exports2, {
|
|
110
|
+
createSignedJwt: () => createSignedJwt2,
|
|
111
|
+
cryptoProvider: () => nodeCrypto2,
|
|
112
|
+
generateRsaKeyPair: () => generateRsaKeyPair2,
|
|
113
|
+
isRsaPssAlg: () => isRsaPssAlg2,
|
|
114
|
+
jwtAlgToNodeAlg: () => jwtAlgToNodeAlg2,
|
|
115
|
+
nodeCrypto: () => nodeCrypto2,
|
|
116
|
+
pemToPublicJwk: () => pemToPublicJwk2,
|
|
117
|
+
rsaSign: () => rsaSign2,
|
|
118
|
+
rsaSignBase64Url: () => rsaSignBase64Url2,
|
|
119
|
+
rsaVerify: () => rsaVerify2,
|
|
120
|
+
rsaVerifySync: () => rsaVerifySync2
|
|
121
|
+
});
|
|
122
|
+
module.exports = __toCommonJS(node_exports2);
|
|
123
|
+
var import_node_crypto2 = __toESM2(__require("node:crypto"));
|
|
124
|
+
var JWT_ALG_TO_NODE_DIGEST2 = {
|
|
125
|
+
RS256: "RSA-SHA256",
|
|
126
|
+
RS384: "RSA-SHA384",
|
|
127
|
+
RS512: "RSA-SHA512",
|
|
128
|
+
// For RSA-PSS, Node's crypto.sign/verify uses the digest algorithm + explicit PSS padding options.
|
|
129
|
+
PS256: "RSA-SHA256",
|
|
130
|
+
PS384: "RSA-SHA384",
|
|
131
|
+
PS512: "RSA-SHA512"
|
|
132
|
+
};
|
|
133
|
+
function jwtAlgToNodeAlg2(jwtAlg) {
|
|
134
|
+
const nodeAlg = JWT_ALG_TO_NODE_DIGEST2[jwtAlg];
|
|
135
|
+
if (!nodeAlg) {
|
|
136
|
+
throw new Error(`Unsupported JWT algorithm: ${jwtAlg}`);
|
|
137
|
+
}
|
|
138
|
+
return nodeAlg;
|
|
139
|
+
}
|
|
140
|
+
function isRsaPssAlg2(jwtAlg) {
|
|
141
|
+
return jwtAlg.startsWith("PS");
|
|
142
|
+
}
|
|
143
|
+
function toUint8Array2(buf) {
|
|
144
|
+
return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
145
|
+
}
|
|
146
|
+
function toBuffer2(data) {
|
|
147
|
+
if (typeof data === "string") {
|
|
148
|
+
return Buffer.from(data, "utf8");
|
|
149
|
+
}
|
|
150
|
+
return Buffer.from(data);
|
|
151
|
+
}
|
|
152
|
+
var nodeCrypto2 = {
|
|
153
|
+
randomUUID() {
|
|
154
|
+
return import_node_crypto2.default.randomUUID();
|
|
155
|
+
},
|
|
156
|
+
randomBytes(length) {
|
|
157
|
+
return toUint8Array2(import_node_crypto2.default.randomBytes(length));
|
|
158
|
+
},
|
|
159
|
+
sha256(data) {
|
|
160
|
+
const hash = import_node_crypto2.default.createHash("sha256").update(toBuffer2(data)).digest();
|
|
161
|
+
return toUint8Array2(hash);
|
|
162
|
+
},
|
|
163
|
+
sha256Hex(data) {
|
|
164
|
+
return import_node_crypto2.default.createHash("sha256").update(toBuffer2(data)).digest("hex");
|
|
165
|
+
},
|
|
166
|
+
hmacSha256(key, data) {
|
|
167
|
+
const hmac2 = import_node_crypto2.default.createHmac("sha256", Buffer.from(key)).update(Buffer.from(data)).digest();
|
|
168
|
+
return toUint8Array2(hmac2);
|
|
169
|
+
},
|
|
170
|
+
hkdfSha256(ikm, salt, info, length) {
|
|
171
|
+
const ikmBuf = Buffer.from(ikm);
|
|
172
|
+
const saltBuf = salt.length > 0 ? Buffer.from(salt) : Buffer.alloc(32);
|
|
173
|
+
const prk = import_node_crypto2.default.createHmac("sha256", saltBuf).update(ikmBuf).digest();
|
|
174
|
+
const hashLen = 32;
|
|
175
|
+
const n = Math.ceil(length / hashLen);
|
|
176
|
+
const chunks = [];
|
|
177
|
+
let prev = Buffer.alloc(0);
|
|
178
|
+
for (let i = 1; i <= n; i++) {
|
|
179
|
+
prev = import_node_crypto2.default.createHmac("sha256", prk).update(Buffer.concat([prev, Buffer.from(info), Buffer.from([i])])).digest();
|
|
180
|
+
chunks.push(prev);
|
|
181
|
+
}
|
|
182
|
+
return toUint8Array2(Buffer.concat(chunks).subarray(0, length));
|
|
183
|
+
},
|
|
184
|
+
encryptAesGcm(key, plaintext, iv) {
|
|
185
|
+
const cipher = import_node_crypto2.default.createCipheriv("aes-256-gcm", Buffer.from(key), Buffer.from(iv));
|
|
186
|
+
const encrypted = Buffer.concat([cipher.update(Buffer.from(plaintext)), cipher.final()]);
|
|
187
|
+
const tag = cipher.getAuthTag();
|
|
188
|
+
return {
|
|
189
|
+
ciphertext: toUint8Array2(encrypted),
|
|
190
|
+
tag: toUint8Array2(tag)
|
|
191
|
+
};
|
|
192
|
+
},
|
|
193
|
+
decryptAesGcm(key, ciphertext, iv, tag) {
|
|
194
|
+
const decipher = import_node_crypto2.default.createDecipheriv("aes-256-gcm", Buffer.from(key), Buffer.from(iv));
|
|
195
|
+
decipher.setAuthTag(Buffer.from(tag));
|
|
196
|
+
const decrypted = Buffer.concat([decipher.update(Buffer.from(ciphertext)), decipher.final()]);
|
|
197
|
+
return toUint8Array2(decrypted);
|
|
198
|
+
},
|
|
199
|
+
timingSafeEqual(a, b) {
|
|
200
|
+
if (a.length !== b.length) return false;
|
|
201
|
+
return import_node_crypto2.default.timingSafeEqual(Buffer.from(a), Buffer.from(b));
|
|
202
|
+
}
|
|
203
|
+
};
|
|
204
|
+
function generateRsaKeyPair2(modulusLength = 2048, alg = "RS256") {
|
|
205
|
+
const kid = `rsa-key-${Date.now()}-${import_node_crypto2.default.randomBytes(8).toString("hex")}`;
|
|
206
|
+
const { privateKey, publicKey } = import_node_crypto2.default.generateKeyPairSync("rsa", {
|
|
207
|
+
modulusLength
|
|
208
|
+
});
|
|
209
|
+
const exported = publicKey.export({ format: "jwk" });
|
|
210
|
+
const publicJwk = {
|
|
211
|
+
...exported,
|
|
212
|
+
kid,
|
|
213
|
+
alg,
|
|
214
|
+
use: "sig",
|
|
215
|
+
kty: "RSA"
|
|
216
|
+
};
|
|
217
|
+
return { privateKey, publicKey, publicJwk };
|
|
218
|
+
}
|
|
219
|
+
function rsaSign2(algorithm, data, privateKey, options) {
|
|
220
|
+
const signingKey = options ? { key: privateKey, ...options } : privateKey;
|
|
221
|
+
return import_node_crypto2.default.sign(algorithm, data, signingKey);
|
|
222
|
+
}
|
|
223
|
+
function rsaVerify2(jwtAlg, data, publicJwk, signature) {
|
|
224
|
+
const publicKey = import_node_crypto2.default.createPublicKey({ key: publicJwk, format: "jwk" });
|
|
225
|
+
const nodeAlgorithm = jwtAlgToNodeAlg2(jwtAlg);
|
|
226
|
+
const verifyKey = isRsaPssAlg2(jwtAlg) ? {
|
|
227
|
+
key: publicKey,
|
|
228
|
+
padding: import_node_crypto2.default.constants.RSA_PKCS1_PSS_PADDING,
|
|
229
|
+
saltLength: import_node_crypto2.default.constants.RSA_PSS_SALTLEN_DIGEST
|
|
230
|
+
} : publicKey;
|
|
231
|
+
return import_node_crypto2.default.verify(nodeAlgorithm, data, verifyKey, signature);
|
|
232
|
+
}
|
|
233
|
+
function rsaSignBase64Url2(jwtAlg, data, privateJwk) {
|
|
234
|
+
const privateKey = import_node_crypto2.default.createPrivateKey({ key: privateJwk, format: "jwk" });
|
|
235
|
+
const nodeAlgorithm = jwtAlgToNodeAlg2(jwtAlg);
|
|
236
|
+
const buf = Buffer.isBuffer(data) ? data : Buffer.from(data);
|
|
237
|
+
const sig = isRsaPssAlg2(jwtAlg) ? rsaSign2(nodeAlgorithm, buf, privateKey, {
|
|
238
|
+
padding: import_node_crypto2.default.constants.RSA_PKCS1_PSS_PADDING,
|
|
239
|
+
saltLength: import_node_crypto2.default.constants.RSA_PSS_SALTLEN_DIGEST
|
|
240
|
+
}) : rsaSign2(nodeAlgorithm, buf, privateKey);
|
|
241
|
+
return sig.toString("base64url");
|
|
242
|
+
}
|
|
243
|
+
function rsaVerifySync2(jwtAlg, data, publicJwk, signature) {
|
|
244
|
+
try {
|
|
245
|
+
const publicKey = import_node_crypto2.default.createPublicKey({ key: publicJwk, format: "jwk" });
|
|
246
|
+
const dataBuf = Buffer.isBuffer(data) ? data : Buffer.from(data);
|
|
247
|
+
const sigBuf = Buffer.isBuffer(signature) ? signature : Buffer.from(signature);
|
|
248
|
+
if (jwtAlg === "EdDSA") {
|
|
249
|
+
return import_node_crypto2.default.verify(null, dataBuf, publicKey, sigBuf);
|
|
250
|
+
}
|
|
251
|
+
const nodeAlgorithm = jwtAlgToNodeAlg2(jwtAlg);
|
|
252
|
+
const verifyKey = isRsaPssAlg2(jwtAlg) ? {
|
|
253
|
+
key: publicKey,
|
|
254
|
+
padding: import_node_crypto2.default.constants.RSA_PKCS1_PSS_PADDING,
|
|
255
|
+
saltLength: import_node_crypto2.default.constants.RSA_PSS_SALTLEN_DIGEST
|
|
256
|
+
} : publicKey;
|
|
257
|
+
return import_node_crypto2.default.verify(nodeAlgorithm, dataBuf, verifyKey, sigBuf);
|
|
258
|
+
} catch {
|
|
259
|
+
return false;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
function pemToPublicJwk2(pem) {
|
|
263
|
+
const key = import_node_crypto2.default.createPublicKey({ key: pem, format: "pem" });
|
|
264
|
+
return key.export({ format: "jwk" });
|
|
265
|
+
}
|
|
266
|
+
function createSignedJwt2(payload, privateKey, kid, alg = "RS256") {
|
|
267
|
+
const header = { alg, typ: "JWT", kid };
|
|
268
|
+
const headerB64 = Buffer.from(JSON.stringify(header)).toString("base64url");
|
|
269
|
+
const payloadB64 = Buffer.from(JSON.stringify(payload)).toString("base64url");
|
|
270
|
+
const signatureInput = `${headerB64}.${payloadB64}`;
|
|
271
|
+
const nodeAlgorithm = jwtAlgToNodeAlg2(alg);
|
|
272
|
+
const signature = rsaSign2(
|
|
273
|
+
nodeAlgorithm,
|
|
274
|
+
Buffer.from(signatureInput),
|
|
275
|
+
privateKey,
|
|
276
|
+
isRsaPssAlg2(alg) ? {
|
|
277
|
+
padding: import_node_crypto2.default.constants.RSA_PKCS1_PSS_PADDING,
|
|
278
|
+
saltLength: import_node_crypto2.default.constants.RSA_PSS_SALTLEN_DIGEST
|
|
279
|
+
} : void 0
|
|
280
|
+
);
|
|
281
|
+
const signatureB64 = signature.toString("base64url");
|
|
282
|
+
return `${headerB64}.${payloadB64}.${signatureB64}`;
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
});
|
|
286
|
+
|
|
20
287
|
// plugins/plugin-cache/src/cache.plugin.ts
|
|
21
288
|
import {
|
|
22
289
|
DynamicPlugin,
|
|
23
|
-
Plugin,
|
|
24
|
-
ToolHook,
|
|
25
290
|
FrontMcpConfig,
|
|
291
|
+
FrontMcpContextStorage,
|
|
26
292
|
getGlobalStoreConfig,
|
|
27
293
|
isVercelKvProvider,
|
|
28
|
-
|
|
294
|
+
Plugin,
|
|
295
|
+
ToolHook
|
|
29
296
|
} from "@frontmcp/sdk";
|
|
30
297
|
|
|
31
|
-
//
|
|
32
|
-
import
|
|
33
|
-
import {
|
|
34
|
-
var
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
298
|
+
// libs/utils/dist/esm/index.mjs
|
|
299
|
+
import { createRequire as __frontmcpCreateRequire } from "module";
|
|
300
|
+
import { z } from "@frontmcp/lazy-zod";
|
|
301
|
+
var import_event_emitter = __toESM(require_node_event_emitter(), 1);
|
|
302
|
+
import { z as z2 } from "@frontmcp/lazy-zod";
|
|
303
|
+
var import_crypto_provider = __toESM(require_node(), 1);
|
|
304
|
+
import crypto2 from "node:crypto";
|
|
305
|
+
import { sha256 as sha256Hash } from "@noble/hashes/sha2.js";
|
|
306
|
+
import { hmac } from "@noble/hashes/hmac.js";
|
|
307
|
+
import { hkdf } from "@noble/hashes/hkdf.js";
|
|
308
|
+
import { randomBytes as nobleRandomBytes } from "@noble/hashes/utils.js";
|
|
309
|
+
import { gcm } from "@noble/ciphers/aes.js";
|
|
310
|
+
import { analyzeForReDoS, REDOS_THRESHOLDS } from "@enclave-vm/ast";
|
|
311
|
+
import { z as z3 } from "@frontmcp/lazy-zod";
|
|
312
|
+
var require2 = __frontmcpCreateRequire(import.meta.url || "file:///");
|
|
313
|
+
var __defProp2 = Object.defineProperty;
|
|
314
|
+
var __getOwnPropNames2 = Object.getOwnPropertyNames;
|
|
315
|
+
var __require2 = /* @__PURE__ */ ((x) => typeof require2 !== "undefined" ? require2 : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
316
|
+
get: (a, b) => (typeof require2 !== "undefined" ? require2 : a)[b]
|
|
317
|
+
}) : x)(function(x) {
|
|
318
|
+
if (typeof require2 !== "undefined") return require2.apply(this, arguments);
|
|
319
|
+
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
320
|
+
});
|
|
321
|
+
var __esm = (fn, res, err) => function __init() {
|
|
322
|
+
if (err) throw err[0];
|
|
323
|
+
try {
|
|
324
|
+
return fn && (res = (0, fn[__getOwnPropNames2(fn)[0]])(fn = 0)), res;
|
|
325
|
+
} catch (e) {
|
|
326
|
+
throw err = [e], e;
|
|
327
|
+
}
|
|
328
|
+
};
|
|
329
|
+
var __export = (target, all) => {
|
|
330
|
+
for (var name in all)
|
|
331
|
+
__defProp2(target, name, { get: all[name], enumerable: true });
|
|
332
|
+
};
|
|
333
|
+
function isNode() {
|
|
334
|
+
return typeof process !== "undefined" && !!process.versions?.node;
|
|
335
|
+
}
|
|
336
|
+
function assertNode(feature) {
|
|
337
|
+
if (!isNode()) {
|
|
338
|
+
throw new Error(`${feature} is not supported in the browser. Requires Node.js.`);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
var init_runtime = __esm({
|
|
342
|
+
"libs/utils/src/crypto/runtime.ts"() {
|
|
343
|
+
"use strict";
|
|
344
|
+
}
|
|
345
|
+
});
|
|
346
|
+
function getFsp() {
|
|
347
|
+
if (!_fsp) {
|
|
348
|
+
assertNode("File system operations");
|
|
349
|
+
_fsp = __require2("fs").promises;
|
|
350
|
+
}
|
|
351
|
+
return _fsp;
|
|
352
|
+
}
|
|
353
|
+
async function writeFile(p, content, options) {
|
|
354
|
+
const fsp = getFsp();
|
|
355
|
+
await fsp.writeFile(p, content, { encoding: "utf8", mode: options?.mode });
|
|
356
|
+
}
|
|
357
|
+
async function mkdir(p, options) {
|
|
358
|
+
const fsp = getFsp();
|
|
359
|
+
await fsp.mkdir(p, options);
|
|
360
|
+
}
|
|
361
|
+
async function rename(oldPath, newPath) {
|
|
362
|
+
const fsp = getFsp();
|
|
363
|
+
await fsp.rename(oldPath, newPath);
|
|
364
|
+
}
|
|
365
|
+
async function unlink(p) {
|
|
366
|
+
const fsp = getFsp();
|
|
367
|
+
await fsp.unlink(p);
|
|
368
|
+
}
|
|
369
|
+
async function fileExists(p) {
|
|
370
|
+
try {
|
|
371
|
+
const fsp = getFsp();
|
|
372
|
+
await fsp.access(p, F_OK);
|
|
373
|
+
return true;
|
|
374
|
+
} catch {
|
|
375
|
+
return false;
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
async function readJSON(jsonPath) {
|
|
379
|
+
try {
|
|
380
|
+
const fsp = getFsp();
|
|
381
|
+
const buf = await fsp.readFile(jsonPath, "utf8");
|
|
382
|
+
return JSON.parse(buf);
|
|
383
|
+
} catch {
|
|
384
|
+
return null;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
async function ensureDir(p) {
|
|
388
|
+
const fsp = getFsp();
|
|
389
|
+
await fsp.mkdir(p, { recursive: true });
|
|
390
|
+
}
|
|
391
|
+
async function readdir(p) {
|
|
392
|
+
const fsp = getFsp();
|
|
393
|
+
return fsp.readdir(p);
|
|
394
|
+
}
|
|
395
|
+
var _fsp;
|
|
396
|
+
var _fs;
|
|
397
|
+
var _spawn;
|
|
398
|
+
var F_OK;
|
|
399
|
+
var init_fs = __esm({
|
|
400
|
+
"libs/utils/src/fs/fs.ts"() {
|
|
401
|
+
"use strict";
|
|
402
|
+
init_runtime();
|
|
403
|
+
_fsp = null;
|
|
404
|
+
_fs = null;
|
|
405
|
+
_spawn = null;
|
|
406
|
+
F_OK = 0;
|
|
407
|
+
}
|
|
408
|
+
});
|
|
409
|
+
var init_fs2 = __esm({
|
|
410
|
+
"libs/utils/src/fs/index.ts"() {
|
|
411
|
+
"use strict";
|
|
412
|
+
init_fs();
|
|
413
|
+
}
|
|
414
|
+
});
|
|
415
|
+
function jwtAlgToNodeAlg(jwtAlg) {
|
|
416
|
+
const nodeAlg = JWT_ALG_TO_NODE_DIGEST[jwtAlg];
|
|
417
|
+
if (!nodeAlg) {
|
|
418
|
+
throw new Error(`Unsupported JWT algorithm: ${jwtAlg}`);
|
|
419
|
+
}
|
|
420
|
+
return nodeAlg;
|
|
421
|
+
}
|
|
422
|
+
function isRsaPssAlg(jwtAlg) {
|
|
423
|
+
return jwtAlg.startsWith("PS");
|
|
424
|
+
}
|
|
425
|
+
function jwtAlgToWebCryptoAlg(jwtAlg) {
|
|
426
|
+
const webAlg = JWT_ALG_TO_WEB_CRYPTO[jwtAlg];
|
|
427
|
+
if (!webAlg) {
|
|
428
|
+
throw new Error(`Unsupported JWT algorithm for WebCrypto: ${jwtAlg}`);
|
|
429
|
+
}
|
|
430
|
+
return webAlg;
|
|
431
|
+
}
|
|
432
|
+
var JWT_ALG_TO_NODE_DIGEST;
|
|
433
|
+
var JWT_ALG_TO_WEB_CRYPTO;
|
|
434
|
+
var init_jwt_alg = __esm({
|
|
435
|
+
"libs/utils/src/crypto/jwt-alg.ts"() {
|
|
436
|
+
"use strict";
|
|
437
|
+
JWT_ALG_TO_NODE_DIGEST = {
|
|
438
|
+
RS256: "RSA-SHA256",
|
|
439
|
+
RS384: "RSA-SHA384",
|
|
440
|
+
RS512: "RSA-SHA512",
|
|
441
|
+
// For RSA-PSS, Node's crypto.sign/verify uses the digest algorithm + explicit PSS padding options.
|
|
442
|
+
PS256: "RSA-SHA256",
|
|
443
|
+
PS384: "RSA-SHA384",
|
|
444
|
+
PS512: "RSA-SHA512"
|
|
445
|
+
};
|
|
446
|
+
JWT_ALG_TO_WEB_CRYPTO = {
|
|
447
|
+
RS256: "SHA-256",
|
|
448
|
+
RS384: "SHA-384",
|
|
449
|
+
RS512: "SHA-512",
|
|
450
|
+
PS256: "SHA-256",
|
|
451
|
+
PS384: "SHA-384",
|
|
452
|
+
PS512: "SHA-512"
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
});
|
|
456
|
+
var textEncoder;
|
|
457
|
+
var textDecoder;
|
|
458
|
+
var EncryptedBlobError;
|
|
459
|
+
var init_encrypted_blob = __esm({
|
|
460
|
+
"libs/utils/src/crypto/encrypted-blob.ts"() {
|
|
461
|
+
"use strict";
|
|
462
|
+
init_crypto();
|
|
463
|
+
textEncoder = new TextEncoder();
|
|
464
|
+
textDecoder = new TextDecoder();
|
|
465
|
+
EncryptedBlobError = class extends Error {
|
|
466
|
+
constructor(message) {
|
|
467
|
+
super(message);
|
|
468
|
+
this.name = "EncryptedBlobError";
|
|
469
|
+
}
|
|
470
|
+
};
|
|
471
|
+
}
|
|
472
|
+
});
|
|
473
|
+
var MIN_CODE_VERIFIER_LENGTH;
|
|
474
|
+
var MAX_CODE_VERIFIER_LENGTH;
|
|
475
|
+
var DEFAULT_CODE_VERIFIER_LENGTH;
|
|
476
|
+
var PkceError;
|
|
477
|
+
var init_pkce = __esm({
|
|
478
|
+
"libs/utils/src/crypto/pkce/pkce.ts"() {
|
|
479
|
+
"use strict";
|
|
480
|
+
init_crypto();
|
|
481
|
+
MIN_CODE_VERIFIER_LENGTH = 43;
|
|
482
|
+
MAX_CODE_VERIFIER_LENGTH = 128;
|
|
483
|
+
DEFAULT_CODE_VERIFIER_LENGTH = 64;
|
|
484
|
+
PkceError = class extends Error {
|
|
485
|
+
constructor(message) {
|
|
486
|
+
super(message);
|
|
487
|
+
this.name = "PkceError";
|
|
488
|
+
}
|
|
489
|
+
};
|
|
490
|
+
}
|
|
491
|
+
});
|
|
492
|
+
var init_pkce2 = __esm({
|
|
493
|
+
"libs/utils/src/crypto/pkce/index.ts"() {
|
|
494
|
+
"use strict";
|
|
495
|
+
init_pkce();
|
|
496
|
+
}
|
|
497
|
+
});
|
|
498
|
+
var secretDataSchema;
|
|
499
|
+
var MAX_CLOCK_DRIFT_MS;
|
|
500
|
+
var MAX_SECRET_AGE_MS;
|
|
501
|
+
var init_schema = __esm({
|
|
502
|
+
"libs/utils/src/crypto/secret-persistence/schema.ts"() {
|
|
503
|
+
"use strict";
|
|
504
|
+
secretDataSchema = z.object({
|
|
505
|
+
secret: z.string().base64url().length(43),
|
|
506
|
+
// base64url of 32 bytes is exactly 43 chars
|
|
507
|
+
createdAt: z.number().positive().int(),
|
|
508
|
+
version: z.number().positive().int()
|
|
509
|
+
}).strict();
|
|
510
|
+
MAX_CLOCK_DRIFT_MS = 6e4;
|
|
511
|
+
MAX_SECRET_AGE_MS = 100 * 365 * 24 * 60 * 60 * 1e3;
|
|
512
|
+
}
|
|
513
|
+
});
|
|
514
|
+
var DEFAULT_SECRET_BYTES;
|
|
515
|
+
var DEFAULT_SECRET_DIR;
|
|
516
|
+
var noop;
|
|
517
|
+
var secretCache;
|
|
518
|
+
var generationPromises;
|
|
519
|
+
var init_persistence = __esm({
|
|
520
|
+
"libs/utils/src/crypto/secret-persistence/persistence.ts"() {
|
|
521
|
+
"use strict";
|
|
522
|
+
init_fs2();
|
|
523
|
+
init_crypto();
|
|
524
|
+
init_schema();
|
|
525
|
+
DEFAULT_SECRET_BYTES = 32;
|
|
526
|
+
DEFAULT_SECRET_DIR = ".frontmcp";
|
|
527
|
+
noop = () => {
|
|
528
|
+
};
|
|
529
|
+
secretCache = /* @__PURE__ */ new Map();
|
|
530
|
+
generationPromises = /* @__PURE__ */ new Map();
|
|
531
|
+
}
|
|
532
|
+
});
|
|
533
|
+
var init_secret_persistence = __esm({
|
|
534
|
+
"libs/utils/src/crypto/secret-persistence/index.ts"() {
|
|
535
|
+
"use strict";
|
|
536
|
+
init_schema();
|
|
537
|
+
init_persistence();
|
|
538
|
+
}
|
|
539
|
+
});
|
|
540
|
+
var init_hmac_signing = __esm({
|
|
541
|
+
"libs/utils/src/crypto/hmac-signing.ts"() {
|
|
542
|
+
"use strict";
|
|
543
|
+
init_crypto();
|
|
544
|
+
init_crypto();
|
|
545
|
+
init_crypto();
|
|
546
|
+
}
|
|
547
|
+
});
|
|
548
|
+
function validateKeyData(data) {
|
|
549
|
+
const result = anyKeyDataSchema.safeParse(data);
|
|
550
|
+
if (!result.success) {
|
|
551
|
+
return {
|
|
552
|
+
valid: false,
|
|
553
|
+
error: result.error.issues[0]?.message ?? "Invalid key structure"
|
|
554
|
+
};
|
|
555
|
+
}
|
|
556
|
+
const parsed = result.data;
|
|
557
|
+
const now = Date.now();
|
|
558
|
+
if (parsed.createdAt > now + MAX_CLOCK_DRIFT_MS2) {
|
|
559
|
+
return { valid: false, error: "createdAt is in the future" };
|
|
560
|
+
}
|
|
561
|
+
if (parsed.createdAt < now - MAX_KEY_AGE_MS) {
|
|
562
|
+
return { valid: false, error: "createdAt is too old" };
|
|
563
|
+
}
|
|
564
|
+
return { valid: true, data: parsed };
|
|
565
|
+
}
|
|
566
|
+
function isSecretKeyData(data) {
|
|
567
|
+
return data.type === "secret";
|
|
568
|
+
}
|
|
569
|
+
function isAsymmetricKeyData(data) {
|
|
570
|
+
return data.type === "asymmetric";
|
|
571
|
+
}
|
|
572
|
+
var MAX_CLOCK_DRIFT_MS2;
|
|
573
|
+
var MAX_KEY_AGE_MS;
|
|
574
|
+
var asymmetricAlgSchema;
|
|
575
|
+
var baseKeyDataSchema;
|
|
576
|
+
var jsonWebKeySchema;
|
|
577
|
+
var secretKeyDataSchema;
|
|
578
|
+
var asymmetricKeyDataSchema;
|
|
579
|
+
var anyKeyDataSchema;
|
|
580
|
+
var init_schemas = __esm({
|
|
581
|
+
"libs/utils/src/crypto/key-persistence/schemas.ts"() {
|
|
582
|
+
"use strict";
|
|
583
|
+
MAX_CLOCK_DRIFT_MS2 = 6e4;
|
|
584
|
+
MAX_KEY_AGE_MS = 100 * 365 * 24 * 60 * 60 * 1e3;
|
|
585
|
+
asymmetricAlgSchema = z2.enum(["RS256", "RS384", "RS512", "ES256", "ES384", "ES512"]);
|
|
586
|
+
baseKeyDataSchema = z2.object({
|
|
587
|
+
kid: z2.string().min(1),
|
|
588
|
+
createdAt: z2.number().positive().int(),
|
|
589
|
+
version: z2.number().positive().int()
|
|
48
590
|
});
|
|
49
|
-
|
|
50
|
-
|
|
591
|
+
jsonWebKeySchema = z2.object({
|
|
592
|
+
kty: z2.string().optional(),
|
|
593
|
+
use: z2.string().optional(),
|
|
594
|
+
alg: z2.string().optional(),
|
|
595
|
+
kid: z2.string().optional(),
|
|
596
|
+
n: z2.string().optional(),
|
|
597
|
+
e: z2.string().optional(),
|
|
598
|
+
d: z2.string().optional(),
|
|
599
|
+
p: z2.string().optional(),
|
|
600
|
+
q: z2.string().optional(),
|
|
601
|
+
dp: z2.string().optional(),
|
|
602
|
+
dq: z2.string().optional(),
|
|
603
|
+
qi: z2.string().optional(),
|
|
604
|
+
x: z2.string().optional(),
|
|
605
|
+
y: z2.string().optional(),
|
|
606
|
+
crv: z2.string().optional()
|
|
607
|
+
}).passthrough();
|
|
608
|
+
secretKeyDataSchema = baseKeyDataSchema.extend({
|
|
609
|
+
type: z2.literal("secret"),
|
|
610
|
+
secret: z2.string().min(1),
|
|
611
|
+
bytes: z2.number().positive().int()
|
|
612
|
+
});
|
|
613
|
+
asymmetricKeyDataSchema = baseKeyDataSchema.extend({
|
|
614
|
+
type: z2.literal("asymmetric"),
|
|
615
|
+
alg: asymmetricAlgSchema,
|
|
616
|
+
privateKey: jsonWebKeySchema,
|
|
617
|
+
publicJwk: z2.object({
|
|
618
|
+
keys: z2.array(jsonWebKeySchema).min(1)
|
|
619
|
+
})
|
|
620
|
+
});
|
|
621
|
+
anyKeyDataSchema = z2.discriminatedUnion("type", [secretKeyDataSchema, asymmetricKeyDataSchema]);
|
|
622
|
+
}
|
|
623
|
+
});
|
|
624
|
+
var KeyPersistence;
|
|
625
|
+
var init_key_persistence = __esm({
|
|
626
|
+
"libs/utils/src/crypto/key-persistence/key-persistence.ts"() {
|
|
627
|
+
"use strict";
|
|
628
|
+
init_crypto();
|
|
629
|
+
init_schemas();
|
|
630
|
+
KeyPersistence = class {
|
|
631
|
+
storage;
|
|
632
|
+
cache = /* @__PURE__ */ new Map();
|
|
633
|
+
enableCache;
|
|
634
|
+
throwOnInvalid;
|
|
635
|
+
constructor(options) {
|
|
636
|
+
this.storage = options.storage;
|
|
637
|
+
this.enableCache = options.enableCache ?? true;
|
|
638
|
+
this.throwOnInvalid = options.throwOnInvalid ?? false;
|
|
639
|
+
}
|
|
640
|
+
/**
|
|
641
|
+
* Get a key by ID.
|
|
642
|
+
*
|
|
643
|
+
* @param kid - Key identifier
|
|
644
|
+
* @returns Key data or null if not found
|
|
645
|
+
*/
|
|
646
|
+
async get(kid) {
|
|
647
|
+
if (this.enableCache) {
|
|
648
|
+
const cached4 = this.cache.get(kid);
|
|
649
|
+
if (cached4) return cached4;
|
|
650
|
+
}
|
|
651
|
+
const raw = await this.storage.get(kid);
|
|
652
|
+
if (!raw) return null;
|
|
653
|
+
let parsed;
|
|
654
|
+
try {
|
|
655
|
+
parsed = JSON.parse(raw);
|
|
656
|
+
} catch {
|
|
657
|
+
if (this.throwOnInvalid) {
|
|
658
|
+
throw new Error(`Invalid JSON for key "${kid}"`);
|
|
659
|
+
}
|
|
660
|
+
return null;
|
|
661
|
+
}
|
|
662
|
+
const validation = validateKeyData(parsed);
|
|
663
|
+
if (!validation.valid) {
|
|
664
|
+
if (this.throwOnInvalid) {
|
|
665
|
+
throw new Error(`Invalid key data for "${kid}": ${validation.error}`);
|
|
666
|
+
}
|
|
667
|
+
return null;
|
|
668
|
+
}
|
|
669
|
+
const key = validation.data;
|
|
670
|
+
if (this.enableCache) {
|
|
671
|
+
this.cache.set(kid, key);
|
|
672
|
+
}
|
|
673
|
+
return key;
|
|
674
|
+
}
|
|
675
|
+
/**
|
|
676
|
+
* Get a secret key by ID.
|
|
677
|
+
*
|
|
678
|
+
* @param kid - Key identifier
|
|
679
|
+
* @returns Secret key data or null if not found or wrong type
|
|
680
|
+
*/
|
|
681
|
+
async getSecret(kid) {
|
|
682
|
+
const key = await this.get(kid);
|
|
683
|
+
if (!key || !isSecretKeyData(key)) return null;
|
|
684
|
+
return key;
|
|
685
|
+
}
|
|
686
|
+
/**
|
|
687
|
+
* Get an asymmetric key by ID.
|
|
688
|
+
*
|
|
689
|
+
* @param kid - Key identifier
|
|
690
|
+
* @returns Asymmetric key data or null if not found or wrong type
|
|
691
|
+
*/
|
|
692
|
+
async getAsymmetric(kid) {
|
|
693
|
+
const key = await this.get(kid);
|
|
694
|
+
if (!key || !isAsymmetricKeyData(key)) return null;
|
|
695
|
+
return key;
|
|
696
|
+
}
|
|
697
|
+
/**
|
|
698
|
+
* Store a key.
|
|
699
|
+
*
|
|
700
|
+
* @param key - Key data to store
|
|
701
|
+
*/
|
|
702
|
+
async set(key) {
|
|
703
|
+
const validation = validateKeyData(key);
|
|
704
|
+
if (!validation.valid) {
|
|
705
|
+
throw new Error(`Invalid key data: ${validation.error}`);
|
|
706
|
+
}
|
|
707
|
+
await this.storage.set(key.kid, JSON.stringify(key, null, 2));
|
|
708
|
+
if (this.enableCache) {
|
|
709
|
+
this.cache.set(key.kid, key);
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
/**
|
|
713
|
+
* Delete a key.
|
|
714
|
+
*
|
|
715
|
+
* @param kid - Key identifier
|
|
716
|
+
* @returns true if key existed and was deleted
|
|
717
|
+
*/
|
|
718
|
+
async delete(kid) {
|
|
719
|
+
this.cache.delete(kid);
|
|
720
|
+
return this.storage.delete(kid);
|
|
721
|
+
}
|
|
722
|
+
/**
|
|
723
|
+
* Check if a key exists.
|
|
724
|
+
*
|
|
725
|
+
* @param kid - Key identifier
|
|
726
|
+
* @returns true if key exists
|
|
727
|
+
*/
|
|
728
|
+
async has(kid) {
|
|
729
|
+
if (this.enableCache && this.cache.has(kid)) {
|
|
730
|
+
return true;
|
|
731
|
+
}
|
|
732
|
+
return this.storage.exists(kid);
|
|
733
|
+
}
|
|
734
|
+
/**
|
|
735
|
+
* List all key IDs.
|
|
736
|
+
*
|
|
737
|
+
* @returns Array of key identifiers
|
|
738
|
+
*/
|
|
739
|
+
async list() {
|
|
740
|
+
return this.storage.keys();
|
|
741
|
+
}
|
|
742
|
+
/**
|
|
743
|
+
* Get or create a secret key.
|
|
744
|
+
*
|
|
745
|
+
* If a key with the given ID exists and is a valid secret key,
|
|
746
|
+
* it is returned. Otherwise, a new secret key is generated.
|
|
747
|
+
*
|
|
748
|
+
* @param kid - Key identifier
|
|
749
|
+
* @param options - Options for key creation
|
|
750
|
+
* @returns Secret key data
|
|
751
|
+
*
|
|
752
|
+
* @example
|
|
753
|
+
* ```typescript
|
|
754
|
+
* const secret = await keys.getOrCreateSecret('encryption-key');
|
|
755
|
+
* const bytes = base64urlDecode(secret.secret);
|
|
756
|
+
* ```
|
|
757
|
+
*/
|
|
758
|
+
async getOrCreateSecret(kid, options) {
|
|
759
|
+
const existing = await this.getSecret(kid);
|
|
760
|
+
if (existing) {
|
|
761
|
+
return existing;
|
|
762
|
+
}
|
|
763
|
+
const bytes = options?.bytes ?? 32;
|
|
764
|
+
const secret = {
|
|
765
|
+
type: "secret",
|
|
766
|
+
kid,
|
|
767
|
+
secret: base64urlEncode(randomBytes(bytes)),
|
|
768
|
+
bytes,
|
|
769
|
+
createdAt: Date.now(),
|
|
770
|
+
version: 1
|
|
771
|
+
};
|
|
772
|
+
await this.set(secret);
|
|
773
|
+
return secret;
|
|
774
|
+
}
|
|
775
|
+
/**
|
|
776
|
+
* Clear the in-memory cache.
|
|
777
|
+
*
|
|
778
|
+
* Useful when you want to force a reload from storage.
|
|
779
|
+
*/
|
|
780
|
+
clearCache() {
|
|
781
|
+
this.cache.clear();
|
|
782
|
+
}
|
|
783
|
+
/**
|
|
784
|
+
* Clear cache for a specific key.
|
|
785
|
+
*
|
|
786
|
+
* @param kid - Key identifier
|
|
787
|
+
*/
|
|
788
|
+
clearCacheFor(kid) {
|
|
789
|
+
this.cache.delete(kid);
|
|
790
|
+
}
|
|
791
|
+
/**
|
|
792
|
+
* Check if a key is in the cache.
|
|
793
|
+
*
|
|
794
|
+
* @param kid - Key identifier
|
|
795
|
+
* @returns true if key is cached
|
|
796
|
+
*/
|
|
797
|
+
isCached(kid) {
|
|
798
|
+
return this.cache.has(kid);
|
|
799
|
+
}
|
|
800
|
+
/**
|
|
801
|
+
* Get the underlying storage adapter.
|
|
802
|
+
*
|
|
803
|
+
* Use with caution - direct storage access bypasses validation.
|
|
804
|
+
*/
|
|
805
|
+
getAdapter() {
|
|
806
|
+
return this.storage;
|
|
807
|
+
}
|
|
808
|
+
};
|
|
809
|
+
}
|
|
810
|
+
});
|
|
811
|
+
var StorageError;
|
|
812
|
+
var StorageConnectionError;
|
|
813
|
+
var StorageOperationError;
|
|
814
|
+
var StorageNotSupportedError;
|
|
815
|
+
var StorageConfigError;
|
|
816
|
+
var StorageTTLError;
|
|
817
|
+
var StoragePatternError;
|
|
818
|
+
var StorageNotConnectedError;
|
|
819
|
+
var EncryptedStorageError;
|
|
820
|
+
var init_errors = __esm({
|
|
821
|
+
"libs/utils/src/storage/errors.ts"() {
|
|
822
|
+
"use strict";
|
|
823
|
+
StorageError = class extends Error {
|
|
824
|
+
cause;
|
|
825
|
+
constructor(message, cause) {
|
|
826
|
+
super(message);
|
|
827
|
+
this.cause = cause;
|
|
828
|
+
this.name = "StorageError";
|
|
829
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
830
|
+
if (Error.captureStackTrace) {
|
|
831
|
+
Error.captureStackTrace(this, this.constructor);
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
};
|
|
835
|
+
StorageConnectionError = class extends StorageError {
|
|
836
|
+
constructor(message, cause, backend) {
|
|
837
|
+
const fullMessage = cause ? `${message}: ${cause.message}` : message;
|
|
838
|
+
super(fullMessage, cause);
|
|
839
|
+
this.backend = backend;
|
|
840
|
+
this.name = "StorageConnectionError";
|
|
841
|
+
}
|
|
842
|
+
backend;
|
|
843
|
+
};
|
|
844
|
+
StorageOperationError = class extends StorageError {
|
|
845
|
+
constructor(operation, key, message, cause) {
|
|
846
|
+
super(`${operation} failed for key "${key}": ${message}`, cause);
|
|
847
|
+
this.operation = operation;
|
|
848
|
+
this.key = key;
|
|
849
|
+
this.name = "StorageOperationError";
|
|
850
|
+
}
|
|
851
|
+
operation;
|
|
852
|
+
key;
|
|
853
|
+
};
|
|
854
|
+
StorageNotSupportedError = class extends StorageError {
|
|
855
|
+
constructor(operation, backend, suggestion) {
|
|
856
|
+
const msg = suggestion ? `${operation} is not supported by ${backend}. ${suggestion}` : `${operation} is not supported by ${backend}`;
|
|
857
|
+
super(msg);
|
|
858
|
+
this.operation = operation;
|
|
859
|
+
this.backend = backend;
|
|
860
|
+
this.name = "StorageNotSupportedError";
|
|
861
|
+
}
|
|
862
|
+
operation;
|
|
863
|
+
backend;
|
|
864
|
+
};
|
|
865
|
+
StorageConfigError = class extends StorageError {
|
|
866
|
+
constructor(backend, message) {
|
|
867
|
+
super(`Invalid ${backend} configuration: ${message}`);
|
|
868
|
+
this.backend = backend;
|
|
869
|
+
this.name = "StorageConfigError";
|
|
870
|
+
}
|
|
871
|
+
backend;
|
|
872
|
+
};
|
|
873
|
+
StorageTTLError = class extends StorageError {
|
|
874
|
+
constructor(ttl, message) {
|
|
875
|
+
super(message ?? `Invalid TTL value: ${ttl}. TTL must be a positive integer.`);
|
|
876
|
+
this.ttl = ttl;
|
|
877
|
+
this.name = "StorageTTLError";
|
|
878
|
+
}
|
|
879
|
+
ttl;
|
|
880
|
+
};
|
|
881
|
+
StoragePatternError = class extends StorageError {
|
|
882
|
+
constructor(pattern, message) {
|
|
883
|
+
super(`Invalid pattern "${pattern}": ${message}`);
|
|
884
|
+
this.pattern = pattern;
|
|
885
|
+
this.name = "StoragePatternError";
|
|
886
|
+
}
|
|
887
|
+
pattern;
|
|
888
|
+
};
|
|
889
|
+
StorageNotConnectedError = class extends StorageError {
|
|
890
|
+
constructor(backend) {
|
|
891
|
+
super(`Storage backend "${backend}" is not connected. Call connect() first.`);
|
|
892
|
+
this.backend = backend;
|
|
893
|
+
this.name = "StorageNotConnectedError";
|
|
894
|
+
}
|
|
895
|
+
backend;
|
|
896
|
+
};
|
|
897
|
+
EncryptedStorageError = class extends StorageError {
|
|
898
|
+
constructor(message) {
|
|
899
|
+
super(message);
|
|
900
|
+
this.name = "EncryptedStorageError";
|
|
901
|
+
}
|
|
902
|
+
};
|
|
903
|
+
}
|
|
904
|
+
});
|
|
905
|
+
function validateTTL(ttlSeconds) {
|
|
906
|
+
if (typeof ttlSeconds !== "number") {
|
|
907
|
+
throw new StorageTTLError(ttlSeconds, `TTL must be a number, got ${typeof ttlSeconds}`);
|
|
908
|
+
}
|
|
909
|
+
if (!Number.isFinite(ttlSeconds)) {
|
|
910
|
+
throw new StorageTTLError(ttlSeconds, "TTL must be a finite number");
|
|
911
|
+
}
|
|
912
|
+
if (!Number.isInteger(ttlSeconds)) {
|
|
913
|
+
throw new StorageTTLError(ttlSeconds, `TTL must be an integer, got ${ttlSeconds}`);
|
|
914
|
+
}
|
|
915
|
+
if (ttlSeconds <= 0) {
|
|
916
|
+
throw new StorageTTLError(ttlSeconds, `TTL must be positive, got ${ttlSeconds}`);
|
|
917
|
+
}
|
|
918
|
+
if (ttlSeconds > MAX_TTL_SECONDS) {
|
|
919
|
+
throw new StorageTTLError(ttlSeconds, `TTL exceeds maximum of ${MAX_TTL_SECONDS} seconds`);
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
function validateOptionalTTL(ttlSeconds) {
|
|
923
|
+
if (ttlSeconds !== void 0) {
|
|
924
|
+
validateTTL(ttlSeconds);
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
function ttlToExpiresAt(ttlSeconds) {
|
|
928
|
+
return Date.now() + ttlSeconds * 1e3;
|
|
929
|
+
}
|
|
930
|
+
function expiresAtToTTL(expiresAt) {
|
|
931
|
+
const remaining = Math.ceil((expiresAt - Date.now()) / 1e3);
|
|
932
|
+
return Math.max(0, remaining);
|
|
933
|
+
}
|
|
934
|
+
function isExpired(expiresAt) {
|
|
935
|
+
if (expiresAt === void 0) return false;
|
|
936
|
+
return Date.now() >= expiresAt;
|
|
937
|
+
}
|
|
938
|
+
var MAX_TTL_SECONDS;
|
|
939
|
+
var init_ttl = __esm({
|
|
940
|
+
"libs/utils/src/storage/utils/ttl.ts"() {
|
|
941
|
+
"use strict";
|
|
942
|
+
init_errors();
|
|
943
|
+
MAX_TTL_SECONDS = 31536e5;
|
|
944
|
+
}
|
|
945
|
+
});
|
|
946
|
+
var BaseStorageAdapter;
|
|
947
|
+
var init_base = __esm({
|
|
948
|
+
"libs/utils/src/storage/adapters/base.ts"() {
|
|
949
|
+
"use strict";
|
|
950
|
+
init_errors();
|
|
951
|
+
init_ttl();
|
|
952
|
+
BaseStorageAdapter = class {
|
|
953
|
+
/**
|
|
954
|
+
* Whether the adapter is currently connected.
|
|
955
|
+
*/
|
|
956
|
+
connected = false;
|
|
957
|
+
/**
|
|
958
|
+
* Ensure adapter is connected before operations.
|
|
959
|
+
* @throws StorageNotConnectedError if not connected
|
|
960
|
+
*/
|
|
961
|
+
ensureConnected() {
|
|
962
|
+
if (!this.connected) {
|
|
963
|
+
throw new StorageNotConnectedError(this.backendName);
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
/**
|
|
967
|
+
* Set with validation.
|
|
968
|
+
*/
|
|
969
|
+
async set(key, value, options) {
|
|
970
|
+
this.ensureConnected();
|
|
971
|
+
this.validateSetOptions(options);
|
|
972
|
+
return this.doSet(key, value, options);
|
|
973
|
+
}
|
|
974
|
+
// ============================================
|
|
975
|
+
// Batch Operations (default implementations)
|
|
976
|
+
// ============================================
|
|
977
|
+
/**
|
|
978
|
+
* Default mget: sequential gets.
|
|
979
|
+
* Override for more efficient implementations.
|
|
980
|
+
*/
|
|
981
|
+
async mget(keys) {
|
|
982
|
+
this.ensureConnected();
|
|
983
|
+
return Promise.all(keys.map((k) => this.get(k)));
|
|
984
|
+
}
|
|
985
|
+
/**
|
|
986
|
+
* Default mset: sequential sets.
|
|
987
|
+
* Override for atomic/pipelined implementations.
|
|
988
|
+
*/
|
|
989
|
+
async mset(entries) {
|
|
990
|
+
this.ensureConnected();
|
|
991
|
+
for (const entry of entries) {
|
|
992
|
+
this.validateSetOptions(entry.options);
|
|
993
|
+
}
|
|
994
|
+
await Promise.all(entries.map((e) => this.doSet(e.key, e.value, e.options)));
|
|
995
|
+
}
|
|
996
|
+
/**
|
|
997
|
+
* Default mdelete: sequential deletes.
|
|
998
|
+
* Override for more efficient implementations.
|
|
999
|
+
*/
|
|
1000
|
+
async mdelete(keys) {
|
|
1001
|
+
this.ensureConnected();
|
|
1002
|
+
const results = await Promise.all(keys.map((k) => this.delete(k)));
|
|
1003
|
+
return results.filter(Boolean).length;
|
|
1004
|
+
}
|
|
1005
|
+
/**
|
|
1006
|
+
* Default count: keys().length.
|
|
1007
|
+
* Override for more efficient implementations.
|
|
1008
|
+
*/
|
|
1009
|
+
async count(pattern = "*") {
|
|
1010
|
+
const matchedKeys = await this.keys(pattern);
|
|
1011
|
+
return matchedKeys.length;
|
|
1012
|
+
}
|
|
1013
|
+
// ============================================
|
|
1014
|
+
// Pub/Sub (default: not supported)
|
|
1015
|
+
// ============================================
|
|
1016
|
+
/**
|
|
1017
|
+
* Default: pub/sub not supported.
|
|
1018
|
+
* Override in adapters that support it.
|
|
1019
|
+
*/
|
|
1020
|
+
supportsPubSub() {
|
|
1021
|
+
return false;
|
|
1022
|
+
}
|
|
1023
|
+
/**
|
|
1024
|
+
* Default: throw not supported error.
|
|
1025
|
+
* Override in adapters that support pub/sub.
|
|
1026
|
+
*/
|
|
1027
|
+
async publish(_channel, _message) {
|
|
1028
|
+
throw new StorageNotSupportedError("publish", this.backendName, this.getPubSubSuggestion());
|
|
1029
|
+
}
|
|
1030
|
+
/**
|
|
1031
|
+
* Default: throw not supported error.
|
|
1032
|
+
* Override in adapters that support pub/sub.
|
|
1033
|
+
*/
|
|
1034
|
+
async subscribe(_channel, _handler) {
|
|
1035
|
+
throw new StorageNotSupportedError("subscribe", this.backendName, this.getPubSubSuggestion());
|
|
1036
|
+
}
|
|
1037
|
+
/**
|
|
1038
|
+
* Get suggestion message for pub/sub not supported error.
|
|
1039
|
+
* Override in specific adapters.
|
|
1040
|
+
*/
|
|
1041
|
+
getPubSubSuggestion() {
|
|
1042
|
+
return "Use Redis or Upstash adapter for pub/sub support.";
|
|
1043
|
+
}
|
|
1044
|
+
// ============================================
|
|
1045
|
+
// Validation Helpers
|
|
1046
|
+
// ============================================
|
|
1047
|
+
/**
|
|
1048
|
+
* Validate set options.
|
|
1049
|
+
*/
|
|
1050
|
+
validateSetOptions(options) {
|
|
1051
|
+
if (!options) return;
|
|
1052
|
+
validateOptionalTTL(options.ttlSeconds);
|
|
1053
|
+
if (options.ifNotExists && options.ifExists) {
|
|
1054
|
+
throw new Error("ifNotExists and ifExists are mutually exclusive");
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
};
|
|
1058
|
+
}
|
|
1059
|
+
});
|
|
1060
|
+
function globToRegex(pattern) {
|
|
1061
|
+
if (pattern.length > MAX_PATTERN_LENGTH) {
|
|
1062
|
+
throw new StoragePatternError(
|
|
1063
|
+
pattern.substring(0, 50) + "...",
|
|
1064
|
+
`Pattern exceeds maximum length of ${MAX_PATTERN_LENGTH} characters`
|
|
1065
|
+
);
|
|
1066
|
+
}
|
|
1067
|
+
const wildcardCount = (pattern.match(/[*?]/g) || []).length;
|
|
1068
|
+
if (wildcardCount > MAX_WILDCARDS) {
|
|
1069
|
+
throw new StoragePatternError(pattern, `Pattern has too many wildcards (max: ${MAX_WILDCARDS})`);
|
|
1070
|
+
}
|
|
1071
|
+
if (pattern === "" || pattern === "*") {
|
|
1072
|
+
return /^.*$/;
|
|
1073
|
+
}
|
|
1074
|
+
let regexStr = "^";
|
|
1075
|
+
let prevChar = "";
|
|
1076
|
+
for (let i = 0; i < pattern.length; i++) {
|
|
1077
|
+
const char = pattern[i];
|
|
1078
|
+
switch (char) {
|
|
1079
|
+
case "*":
|
|
1080
|
+
if (prevChar !== "*") {
|
|
1081
|
+
regexStr += ".*";
|
|
1082
|
+
}
|
|
1083
|
+
break;
|
|
1084
|
+
case "?":
|
|
1085
|
+
regexStr += ".";
|
|
1086
|
+
break;
|
|
1087
|
+
default:
|
|
1088
|
+
regexStr += char.replace(REGEX_SPECIAL_CHARS, "\\$&");
|
|
1089
|
+
}
|
|
1090
|
+
prevChar = char;
|
|
1091
|
+
}
|
|
1092
|
+
regexStr += "$";
|
|
1093
|
+
try {
|
|
1094
|
+
return new RegExp(regexStr);
|
|
1095
|
+
} catch {
|
|
1096
|
+
throw new StoragePatternError(pattern, "Failed to compile pattern to regex");
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
function matchesPattern(key, pattern) {
|
|
1100
|
+
const regex = globToRegex(pattern);
|
|
1101
|
+
return regex.test(key);
|
|
1102
|
+
}
|
|
1103
|
+
var MAX_PATTERN_LENGTH;
|
|
1104
|
+
var MAX_WILDCARDS;
|
|
1105
|
+
var REGEX_SPECIAL_CHARS;
|
|
1106
|
+
var init_pattern = __esm({
|
|
1107
|
+
"libs/utils/src/storage/utils/pattern.ts"() {
|
|
1108
|
+
"use strict";
|
|
1109
|
+
init_errors();
|
|
1110
|
+
MAX_PATTERN_LENGTH = 500;
|
|
1111
|
+
MAX_WILDCARDS = 20;
|
|
1112
|
+
REGEX_SPECIAL_CHARS = /[.+^${}()|[\]\\]/g;
|
|
1113
|
+
}
|
|
1114
|
+
});
|
|
1115
|
+
var DEFAULT_SWEEP_INTERVAL_SECONDS;
|
|
1116
|
+
var MAX_TIMEOUT_MS;
|
|
1117
|
+
var MemoryStorageAdapter;
|
|
1118
|
+
var init_memory = __esm({
|
|
1119
|
+
"libs/utils/src/storage/adapters/memory.ts"() {
|
|
1120
|
+
"use strict";
|
|
1121
|
+
init_base();
|
|
1122
|
+
init_errors();
|
|
1123
|
+
init_pattern();
|
|
1124
|
+
init_ttl();
|
|
1125
|
+
DEFAULT_SWEEP_INTERVAL_SECONDS = 60;
|
|
1126
|
+
MAX_TIMEOUT_MS = 2147483647;
|
|
1127
|
+
MemoryStorageAdapter = class extends BaseStorageAdapter {
|
|
1128
|
+
backendName = "memory";
|
|
1129
|
+
store = /* @__PURE__ */ new Map();
|
|
1130
|
+
emitter = new import_event_emitter.EventEmitter();
|
|
1131
|
+
sweepInterval;
|
|
1132
|
+
options;
|
|
1133
|
+
// LRU tracking (simple linked list via insertion order in Map)
|
|
1134
|
+
accessOrder = [];
|
|
1135
|
+
constructor(options = {}) {
|
|
1136
|
+
super();
|
|
1137
|
+
this.options = {
|
|
1138
|
+
enableSweeper: options.enableSweeper ?? true,
|
|
1139
|
+
sweepIntervalSeconds: options.sweepIntervalSeconds ?? DEFAULT_SWEEP_INTERVAL_SECONDS,
|
|
1140
|
+
maxEntries: options.maxEntries ?? 0
|
|
1141
|
+
// 0 = unlimited
|
|
1142
|
+
};
|
|
1143
|
+
this.emitter.setMaxListeners(1e3);
|
|
1144
|
+
}
|
|
1145
|
+
// ============================================
|
|
1146
|
+
// Connection Lifecycle
|
|
1147
|
+
// ============================================
|
|
1148
|
+
async connect() {
|
|
1149
|
+
if (this.connected) return;
|
|
1150
|
+
this.connected = true;
|
|
1151
|
+
if (this.options.enableSweeper && this.options.sweepIntervalSeconds > 0) {
|
|
1152
|
+
this.startSweeper();
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
async disconnect() {
|
|
1156
|
+
if (!this.connected) return;
|
|
1157
|
+
this.stopSweeper();
|
|
1158
|
+
this.clearAllTimeouts();
|
|
1159
|
+
this.store.clear();
|
|
1160
|
+
this.accessOrder = [];
|
|
1161
|
+
this.emitter.removeAllListeners();
|
|
1162
|
+
this.connected = false;
|
|
1163
|
+
}
|
|
1164
|
+
async ping() {
|
|
1165
|
+
return this.connected;
|
|
1166
|
+
}
|
|
1167
|
+
// ============================================
|
|
1168
|
+
// Core Operations
|
|
1169
|
+
// ============================================
|
|
1170
|
+
async get(key) {
|
|
1171
|
+
this.ensureConnected();
|
|
1172
|
+
const entry = this.store.get(key);
|
|
1173
|
+
if (!entry) return null;
|
|
1174
|
+
if (isExpired(entry.expiresAt)) {
|
|
1175
|
+
this.deleteEntry(key);
|
|
1176
|
+
return null;
|
|
1177
|
+
}
|
|
1178
|
+
this.touchLRU(key);
|
|
1179
|
+
return entry.value;
|
|
1180
|
+
}
|
|
1181
|
+
async doSet(key, value, options) {
|
|
1182
|
+
const existingEntry = this.store.get(key);
|
|
1183
|
+
const exists = existingEntry !== void 0 && !isExpired(existingEntry.expiresAt);
|
|
1184
|
+
if (options?.ifNotExists && exists) {
|
|
1185
|
+
return;
|
|
1186
|
+
}
|
|
1187
|
+
if (options?.ifExists && !exists) {
|
|
1188
|
+
return;
|
|
1189
|
+
}
|
|
1190
|
+
this.clearEntryTimeout(key);
|
|
1191
|
+
const entry = { value };
|
|
1192
|
+
if (options?.ttlSeconds) {
|
|
1193
|
+
entry.expiresAt = ttlToExpiresAt(options.ttlSeconds);
|
|
1194
|
+
const ttlMs = options.ttlSeconds * 1e3;
|
|
1195
|
+
if (ttlMs < MAX_TIMEOUT_MS) {
|
|
1196
|
+
entry.timeout = setTimeout(() => {
|
|
1197
|
+
this.deleteEntry(key);
|
|
1198
|
+
}, ttlMs);
|
|
1199
|
+
if (entry.timeout.unref) {
|
|
1200
|
+
entry.timeout.unref();
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
if (this.options.maxEntries > 0 && !this.store.has(key)) {
|
|
1205
|
+
while (this.store.size >= this.options.maxEntries) {
|
|
1206
|
+
this.evictOldest();
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
this.store.set(key, entry);
|
|
1210
|
+
this.touchLRU(key);
|
|
1211
|
+
}
|
|
1212
|
+
async delete(key) {
|
|
1213
|
+
this.ensureConnected();
|
|
1214
|
+
return this.deleteEntry(key);
|
|
1215
|
+
}
|
|
1216
|
+
async exists(key) {
|
|
1217
|
+
this.ensureConnected();
|
|
1218
|
+
const entry = this.store.get(key);
|
|
1219
|
+
if (!entry) return false;
|
|
1220
|
+
if (isExpired(entry.expiresAt)) {
|
|
1221
|
+
this.deleteEntry(key);
|
|
1222
|
+
return false;
|
|
1223
|
+
}
|
|
1224
|
+
return true;
|
|
1225
|
+
}
|
|
1226
|
+
// ============================================
|
|
1227
|
+
// TTL Operations
|
|
1228
|
+
// ============================================
|
|
1229
|
+
async expire(key, ttlSeconds) {
|
|
1230
|
+
this.ensureConnected();
|
|
1231
|
+
validateTTL(ttlSeconds);
|
|
1232
|
+
const entry = this.store.get(key);
|
|
1233
|
+
if (!entry || isExpired(entry.expiresAt)) {
|
|
1234
|
+
return false;
|
|
1235
|
+
}
|
|
1236
|
+
this.clearEntryTimeout(key);
|
|
1237
|
+
entry.expiresAt = ttlToExpiresAt(ttlSeconds);
|
|
1238
|
+
const ttlMs = ttlSeconds * 1e3;
|
|
1239
|
+
if (ttlMs < MAX_TIMEOUT_MS) {
|
|
1240
|
+
entry.timeout = setTimeout(() => {
|
|
1241
|
+
this.deleteEntry(key);
|
|
1242
|
+
}, ttlMs);
|
|
1243
|
+
if (entry.timeout.unref) {
|
|
1244
|
+
entry.timeout.unref();
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
return true;
|
|
1248
|
+
}
|
|
1249
|
+
async ttl(key) {
|
|
1250
|
+
this.ensureConnected();
|
|
1251
|
+
const entry = this.store.get(key);
|
|
1252
|
+
if (!entry) return null;
|
|
1253
|
+
if (isExpired(entry.expiresAt)) {
|
|
1254
|
+
this.deleteEntry(key);
|
|
1255
|
+
return null;
|
|
1256
|
+
}
|
|
1257
|
+
if (entry.expiresAt === void 0) {
|
|
1258
|
+
return -1;
|
|
1259
|
+
}
|
|
1260
|
+
return expiresAtToTTL(entry.expiresAt);
|
|
1261
|
+
}
|
|
1262
|
+
// ============================================
|
|
1263
|
+
// Key Enumeration
|
|
1264
|
+
// ============================================
|
|
1265
|
+
async keys(pattern = "*") {
|
|
1266
|
+
this.ensureConnected();
|
|
1267
|
+
const regex = globToRegex(pattern);
|
|
1268
|
+
const result = [];
|
|
1269
|
+
for (const [key, entry] of this.store) {
|
|
1270
|
+
if (isExpired(entry.expiresAt)) {
|
|
1271
|
+
this.deleteEntry(key);
|
|
1272
|
+
continue;
|
|
1273
|
+
}
|
|
1274
|
+
if (regex.test(key)) {
|
|
1275
|
+
result.push(key);
|
|
1276
|
+
}
|
|
1277
|
+
}
|
|
1278
|
+
return result;
|
|
1279
|
+
}
|
|
1280
|
+
// ============================================
|
|
1281
|
+
// Atomic Operations
|
|
1282
|
+
// ============================================
|
|
1283
|
+
async incr(key) {
|
|
1284
|
+
return this.incrBy(key, 1);
|
|
1285
|
+
}
|
|
1286
|
+
async decr(key) {
|
|
1287
|
+
return this.incrBy(key, -1);
|
|
1288
|
+
}
|
|
1289
|
+
async incrBy(key, amount) {
|
|
1290
|
+
this.ensureConnected();
|
|
1291
|
+
const entry = this.store.get(key);
|
|
1292
|
+
let currentValue = 0;
|
|
1293
|
+
if (entry && !isExpired(entry.expiresAt)) {
|
|
1294
|
+
const parsed = parseInt(entry.value, 10);
|
|
1295
|
+
if (isNaN(parsed)) {
|
|
1296
|
+
throw new StorageOperationError("incrBy", key, "Value is not an integer");
|
|
1297
|
+
}
|
|
1298
|
+
currentValue = parsed;
|
|
1299
|
+
}
|
|
1300
|
+
const newValue = currentValue + amount;
|
|
1301
|
+
const newEntry = { value: String(newValue) };
|
|
1302
|
+
if (entry?.expiresAt && !isExpired(entry.expiresAt)) {
|
|
1303
|
+
newEntry.expiresAt = entry.expiresAt;
|
|
1304
|
+
const remainingMs = entry.expiresAt - Date.now();
|
|
1305
|
+
if (remainingMs > 0 && remainingMs < MAX_TIMEOUT_MS) {
|
|
1306
|
+
this.clearEntryTimeout(key);
|
|
1307
|
+
newEntry.timeout = setTimeout(() => {
|
|
1308
|
+
this.deleteEntry(key);
|
|
1309
|
+
}, remainingMs);
|
|
1310
|
+
if (newEntry.timeout.unref) {
|
|
1311
|
+
newEntry.timeout.unref();
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1315
|
+
this.store.set(key, newEntry);
|
|
1316
|
+
this.touchLRU(key);
|
|
1317
|
+
return newValue;
|
|
1318
|
+
}
|
|
1319
|
+
// ============================================
|
|
1320
|
+
// Pub/Sub
|
|
1321
|
+
// ============================================
|
|
1322
|
+
supportsPubSub() {
|
|
1323
|
+
return true;
|
|
1324
|
+
}
|
|
1325
|
+
async publish(channel, message) {
|
|
1326
|
+
this.ensureConnected();
|
|
1327
|
+
return this.emitter.listenerCount(channel) > 0 ? (this.emitter.emit(channel, message, channel), this.emitter.listenerCount(channel)) : 0;
|
|
1328
|
+
}
|
|
1329
|
+
async subscribe(channel, handler) {
|
|
1330
|
+
this.ensureConnected();
|
|
1331
|
+
const wrappedHandler = (message, ch) => {
|
|
1332
|
+
handler(message, ch);
|
|
1333
|
+
};
|
|
1334
|
+
this.emitter.on(channel, wrappedHandler);
|
|
1335
|
+
return async () => {
|
|
1336
|
+
this.emitter.off(channel, wrappedHandler);
|
|
1337
|
+
};
|
|
1338
|
+
}
|
|
1339
|
+
// ============================================
|
|
1340
|
+
// Internal Helpers
|
|
1341
|
+
// ============================================
|
|
1342
|
+
/**
|
|
1343
|
+
* Delete an entry and clear its timeout.
|
|
1344
|
+
*/
|
|
1345
|
+
deleteEntry(key) {
|
|
1346
|
+
const entry = this.store.get(key);
|
|
1347
|
+
if (!entry) return false;
|
|
1348
|
+
this.clearEntryTimeout(key);
|
|
1349
|
+
this.store.delete(key);
|
|
1350
|
+
this.removeLRU(key);
|
|
1351
|
+
return true;
|
|
1352
|
+
}
|
|
1353
|
+
/**
|
|
1354
|
+
* Clear timeout for an entry.
|
|
1355
|
+
*/
|
|
1356
|
+
clearEntryTimeout(key) {
|
|
1357
|
+
const entry = this.store.get(key);
|
|
1358
|
+
if (entry?.timeout) {
|
|
1359
|
+
clearTimeout(entry.timeout);
|
|
1360
|
+
entry.timeout = void 0;
|
|
1361
|
+
}
|
|
1362
|
+
}
|
|
1363
|
+
/**
|
|
1364
|
+
* Clear all timeouts.
|
|
1365
|
+
*/
|
|
1366
|
+
clearAllTimeouts() {
|
|
1367
|
+
for (const [key] of this.store) {
|
|
1368
|
+
this.clearEntryTimeout(key);
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
1371
|
+
/**
|
|
1372
|
+
* Update LRU access order.
|
|
1373
|
+
*/
|
|
1374
|
+
touchLRU(key) {
|
|
1375
|
+
if (this.options.maxEntries <= 0) return;
|
|
1376
|
+
const idx = this.accessOrder.indexOf(key);
|
|
1377
|
+
if (idx !== -1) {
|
|
1378
|
+
this.accessOrder.splice(idx, 1);
|
|
1379
|
+
}
|
|
1380
|
+
this.accessOrder.push(key);
|
|
1381
|
+
}
|
|
1382
|
+
/**
|
|
1383
|
+
* Remove key from LRU tracking.
|
|
1384
|
+
*/
|
|
1385
|
+
removeLRU(key) {
|
|
1386
|
+
if (this.options.maxEntries <= 0) return;
|
|
1387
|
+
const idx = this.accessOrder.indexOf(key);
|
|
1388
|
+
if (idx !== -1) {
|
|
1389
|
+
this.accessOrder.splice(idx, 1);
|
|
1390
|
+
}
|
|
1391
|
+
}
|
|
1392
|
+
/**
|
|
1393
|
+
* Evict oldest entry (LRU).
|
|
1394
|
+
*/
|
|
1395
|
+
evictOldest() {
|
|
1396
|
+
if (this.accessOrder.length === 0) return;
|
|
1397
|
+
const oldestKey = this.accessOrder.shift();
|
|
1398
|
+
if (oldestKey) {
|
|
1399
|
+
this.deleteEntry(oldestKey);
|
|
1400
|
+
}
|
|
1401
|
+
}
|
|
1402
|
+
/**
|
|
1403
|
+
* Start background sweeper.
|
|
1404
|
+
*/
|
|
1405
|
+
startSweeper() {
|
|
1406
|
+
this.sweepInterval = setInterval(() => {
|
|
1407
|
+
this.sweep();
|
|
1408
|
+
}, this.options.sweepIntervalSeconds * 1e3);
|
|
1409
|
+
if (this.sweepInterval.unref) {
|
|
1410
|
+
this.sweepInterval.unref();
|
|
1411
|
+
}
|
|
1412
|
+
}
|
|
1413
|
+
/**
|
|
1414
|
+
* Stop background sweeper.
|
|
1415
|
+
*/
|
|
1416
|
+
stopSweeper() {
|
|
1417
|
+
if (this.sweepInterval) {
|
|
1418
|
+
clearInterval(this.sweepInterval);
|
|
1419
|
+
this.sweepInterval = void 0;
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
/**
|
|
1423
|
+
* Sweep expired entries.
|
|
1424
|
+
*/
|
|
1425
|
+
sweep() {
|
|
1426
|
+
const now = Date.now();
|
|
1427
|
+
for (const [key, entry] of this.store) {
|
|
1428
|
+
if (entry.expiresAt && now >= entry.expiresAt) {
|
|
1429
|
+
this.deleteEntry(key);
|
|
1430
|
+
}
|
|
1431
|
+
}
|
|
1432
|
+
}
|
|
1433
|
+
// ============================================
|
|
1434
|
+
// Stats (for debugging)
|
|
1435
|
+
// ============================================
|
|
1436
|
+
/**
|
|
1437
|
+
* Get storage statistics.
|
|
1438
|
+
*/
|
|
1439
|
+
getStats() {
|
|
1440
|
+
return {
|
|
1441
|
+
size: this.store.size,
|
|
1442
|
+
maxEntries: this.options.maxEntries,
|
|
1443
|
+
sweeperActive: this.sweepInterval !== void 0
|
|
1444
|
+
};
|
|
1445
|
+
}
|
|
1446
|
+
};
|
|
1447
|
+
}
|
|
1448
|
+
});
|
|
1449
|
+
var filesystem_exports = {};
|
|
1450
|
+
__export(filesystem_exports, {
|
|
1451
|
+
FileSystemStorageAdapter: () => FileSystemStorageAdapter
|
|
1452
|
+
});
|
|
1453
|
+
var FileSystemStorageAdapter;
|
|
1454
|
+
var init_filesystem = __esm({
|
|
1455
|
+
"libs/utils/src/storage/adapters/filesystem.ts"() {
|
|
1456
|
+
"use strict";
|
|
1457
|
+
init_base();
|
|
1458
|
+
init_errors();
|
|
1459
|
+
init_pattern();
|
|
1460
|
+
init_fs2();
|
|
1461
|
+
init_crypto();
|
|
1462
|
+
FileSystemStorageAdapter = class extends BaseStorageAdapter {
|
|
1463
|
+
backendName = "filesystem";
|
|
1464
|
+
baseDir;
|
|
1465
|
+
extension;
|
|
1466
|
+
dirMode;
|
|
1467
|
+
fileMode;
|
|
1468
|
+
constructor(options) {
|
|
1469
|
+
super();
|
|
1470
|
+
this.baseDir = options.baseDir;
|
|
1471
|
+
this.extension = options.extension ?? ".json";
|
|
1472
|
+
this.dirMode = options.dirMode ?? 448;
|
|
1473
|
+
this.fileMode = options.fileMode ?? 384;
|
|
1474
|
+
}
|
|
1475
|
+
// ============================================
|
|
1476
|
+
// Connection Lifecycle
|
|
1477
|
+
// ============================================
|
|
1478
|
+
async connect() {
|
|
1479
|
+
if (this.connected) return;
|
|
1480
|
+
await ensureDir(this.baseDir);
|
|
1481
|
+
try {
|
|
1482
|
+
await mkdir(this.baseDir, { recursive: true, mode: this.dirMode });
|
|
1483
|
+
} catch {
|
|
1484
|
+
}
|
|
1485
|
+
this.connected = true;
|
|
1486
|
+
}
|
|
1487
|
+
async disconnect() {
|
|
1488
|
+
if (!this.connected) return;
|
|
1489
|
+
this.connected = false;
|
|
1490
|
+
}
|
|
1491
|
+
async ping() {
|
|
1492
|
+
if (!this.connected) return false;
|
|
1493
|
+
try {
|
|
1494
|
+
return await fileExists(this.baseDir);
|
|
1495
|
+
} catch {
|
|
1496
|
+
return false;
|
|
1497
|
+
}
|
|
1498
|
+
}
|
|
1499
|
+
// ============================================
|
|
1500
|
+
// Core Operations
|
|
1501
|
+
// ============================================
|
|
1502
|
+
async get(key) {
|
|
1503
|
+
this.ensureConnected();
|
|
1504
|
+
const filePath = this.keyToPath(key);
|
|
1505
|
+
try {
|
|
1506
|
+
const entry = await readJSON(filePath);
|
|
1507
|
+
if (!entry) return null;
|
|
1508
|
+
if (entry.expiresAt && Date.now() >= entry.expiresAt) {
|
|
1509
|
+
await this.deleteFile(filePath);
|
|
1510
|
+
return null;
|
|
1511
|
+
}
|
|
1512
|
+
return entry.value;
|
|
1513
|
+
} catch (e) {
|
|
1514
|
+
const error = e;
|
|
1515
|
+
if (error.code === "ENOENT") {
|
|
1516
|
+
return null;
|
|
1517
|
+
}
|
|
1518
|
+
throw e;
|
|
1519
|
+
}
|
|
1520
|
+
}
|
|
1521
|
+
async doSet(key, value, options) {
|
|
1522
|
+
const filePath = this.keyToPath(key);
|
|
1523
|
+
const existingEntry = await this.readEntry(filePath);
|
|
1524
|
+
const exists = existingEntry !== null && !this.isExpired(existingEntry);
|
|
1525
|
+
if (options?.ifNotExists && exists) {
|
|
1526
|
+
return;
|
|
1527
|
+
}
|
|
1528
|
+
if (options?.ifExists && !exists) {
|
|
1529
|
+
return;
|
|
1530
|
+
}
|
|
1531
|
+
const entry = { value };
|
|
1532
|
+
if (options?.ttlSeconds) {
|
|
1533
|
+
entry.expiresAt = Date.now() + options.ttlSeconds * 1e3;
|
|
1534
|
+
}
|
|
1535
|
+
await this.atomicWrite(filePath, entry);
|
|
1536
|
+
}
|
|
1537
|
+
async delete(key) {
|
|
1538
|
+
this.ensureConnected();
|
|
1539
|
+
const filePath = this.keyToPath(key);
|
|
1540
|
+
return this.deleteFile(filePath);
|
|
1541
|
+
}
|
|
1542
|
+
async exists(key) {
|
|
1543
|
+
this.ensureConnected();
|
|
1544
|
+
const filePath = this.keyToPath(key);
|
|
1545
|
+
try {
|
|
1546
|
+
const entry = await this.readEntry(filePath);
|
|
1547
|
+
if (!entry) return false;
|
|
1548
|
+
if (this.isExpired(entry)) {
|
|
1549
|
+
await this.deleteFile(filePath);
|
|
1550
|
+
return false;
|
|
1551
|
+
}
|
|
1552
|
+
return true;
|
|
1553
|
+
} catch {
|
|
1554
|
+
return false;
|
|
1555
|
+
}
|
|
1556
|
+
}
|
|
1557
|
+
// ============================================
|
|
1558
|
+
// TTL Operations
|
|
1559
|
+
// ============================================
|
|
1560
|
+
async expire(key, ttlSeconds) {
|
|
1561
|
+
this.ensureConnected();
|
|
1562
|
+
const filePath = this.keyToPath(key);
|
|
1563
|
+
const entry = await this.readEntry(filePath);
|
|
1564
|
+
if (!entry || this.isExpired(entry)) {
|
|
1565
|
+
return false;
|
|
1566
|
+
}
|
|
1567
|
+
entry.expiresAt = Date.now() + ttlSeconds * 1e3;
|
|
1568
|
+
await this.atomicWrite(filePath, entry);
|
|
1569
|
+
return true;
|
|
1570
|
+
}
|
|
1571
|
+
async ttl(key) {
|
|
1572
|
+
this.ensureConnected();
|
|
1573
|
+
const filePath = this.keyToPath(key);
|
|
1574
|
+
const entry = await this.readEntry(filePath);
|
|
1575
|
+
if (!entry) return null;
|
|
1576
|
+
if (this.isExpired(entry)) {
|
|
1577
|
+
await this.deleteFile(filePath);
|
|
1578
|
+
return null;
|
|
1579
|
+
}
|
|
1580
|
+
if (entry.expiresAt === void 0) {
|
|
1581
|
+
return -1;
|
|
1582
|
+
}
|
|
1583
|
+
return Math.max(0, Math.ceil((entry.expiresAt - Date.now()) / 1e3));
|
|
1584
|
+
}
|
|
1585
|
+
// ============================================
|
|
1586
|
+
// Key Enumeration
|
|
1587
|
+
// ============================================
|
|
1588
|
+
async keys(pattern = "*") {
|
|
1589
|
+
this.ensureConnected();
|
|
1590
|
+
const regex = globToRegex(pattern);
|
|
1591
|
+
const result = [];
|
|
1592
|
+
try {
|
|
1593
|
+
const files = await readdir(this.baseDir);
|
|
1594
|
+
for (const file of files) {
|
|
1595
|
+
if (!file.endsWith(this.extension)) continue;
|
|
1596
|
+
const key = this.pathToKey(file);
|
|
1597
|
+
if (!regex.test(key)) continue;
|
|
1598
|
+
const filePath = this.keyToPath(key);
|
|
1599
|
+
const entry = await this.readEntry(filePath);
|
|
1600
|
+
if (entry && !this.isExpired(entry)) {
|
|
1601
|
+
result.push(key);
|
|
1602
|
+
} else if (entry && this.isExpired(entry)) {
|
|
1603
|
+
await this.deleteFile(filePath);
|
|
1604
|
+
}
|
|
1605
|
+
}
|
|
1606
|
+
} catch (e) {
|
|
1607
|
+
const error = e;
|
|
1608
|
+
if (error.code === "ENOENT") {
|
|
1609
|
+
return [];
|
|
1610
|
+
}
|
|
1611
|
+
throw e;
|
|
1612
|
+
}
|
|
1613
|
+
return result;
|
|
1614
|
+
}
|
|
1615
|
+
// ============================================
|
|
1616
|
+
// Atomic Operations
|
|
1617
|
+
// ============================================
|
|
1618
|
+
async incr(key) {
|
|
1619
|
+
return this.incrBy(key, 1);
|
|
1620
|
+
}
|
|
1621
|
+
async decr(key) {
|
|
1622
|
+
return this.incrBy(key, -1);
|
|
1623
|
+
}
|
|
1624
|
+
async incrBy(key, amount) {
|
|
1625
|
+
this.ensureConnected();
|
|
1626
|
+
const filePath = this.keyToPath(key);
|
|
1627
|
+
const entry = await this.readEntry(filePath);
|
|
1628
|
+
let currentValue = 0;
|
|
1629
|
+
if (entry && !this.isExpired(entry)) {
|
|
1630
|
+
const parsed = parseInt(entry.value, 10);
|
|
1631
|
+
if (isNaN(parsed)) {
|
|
1632
|
+
throw new StorageOperationError("incrBy", key, "Value is not an integer");
|
|
1633
|
+
}
|
|
1634
|
+
currentValue = parsed;
|
|
1635
|
+
}
|
|
1636
|
+
const newValue = currentValue + amount;
|
|
1637
|
+
const newEntry = { value: String(newValue) };
|
|
1638
|
+
if (entry?.expiresAt && !this.isExpired(entry)) {
|
|
1639
|
+
newEntry.expiresAt = entry.expiresAt;
|
|
1640
|
+
}
|
|
1641
|
+
await this.atomicWrite(filePath, newEntry);
|
|
1642
|
+
return newValue;
|
|
1643
|
+
}
|
|
1644
|
+
// ============================================
|
|
1645
|
+
// Internal Helpers
|
|
1646
|
+
// ============================================
|
|
1647
|
+
/**
|
|
1648
|
+
* Convert a storage key to a file path.
|
|
1649
|
+
* Sanitizes the key to be filesystem-safe.
|
|
1650
|
+
*/
|
|
1651
|
+
keyToPath(key) {
|
|
1652
|
+
const safeKey = this.encodeKey(key);
|
|
1653
|
+
return `${this.baseDir}/${safeKey}${this.extension}`;
|
|
1654
|
+
}
|
|
1655
|
+
/**
|
|
1656
|
+
* Convert a filename back to a storage key.
|
|
1657
|
+
*/
|
|
1658
|
+
pathToKey(filename) {
|
|
1659
|
+
const safeKey = filename.slice(0, -this.extension.length);
|
|
1660
|
+
return this.decodeKey(safeKey);
|
|
1661
|
+
}
|
|
1662
|
+
/**
|
|
1663
|
+
* Encode a key to be filesystem-safe.
|
|
1664
|
+
* Uses URL encoding to handle special characters.
|
|
1665
|
+
*/
|
|
1666
|
+
encodeKey(key) {
|
|
1667
|
+
return encodeURIComponent(key).replace(/\./g, "%2E");
|
|
1668
|
+
}
|
|
1669
|
+
/**
|
|
1670
|
+
* Decode a filesystem-safe key back to original.
|
|
1671
|
+
*/
|
|
1672
|
+
decodeKey(encoded) {
|
|
1673
|
+
return decodeURIComponent(encoded);
|
|
1674
|
+
}
|
|
1675
|
+
/**
|
|
1676
|
+
* Read an entry from a file.
|
|
1677
|
+
*/
|
|
1678
|
+
async readEntry(filePath) {
|
|
1679
|
+
try {
|
|
1680
|
+
return await readJSON(filePath);
|
|
1681
|
+
} catch {
|
|
1682
|
+
return null;
|
|
1683
|
+
}
|
|
1684
|
+
}
|
|
1685
|
+
/**
|
|
1686
|
+
* Check if an entry is expired.
|
|
1687
|
+
*/
|
|
1688
|
+
isExpired(entry) {
|
|
1689
|
+
return entry.expiresAt !== void 0 && Date.now() >= entry.expiresAt;
|
|
1690
|
+
}
|
|
1691
|
+
/**
|
|
1692
|
+
* Delete a file, returning true if it existed.
|
|
1693
|
+
*/
|
|
1694
|
+
async deleteFile(filePath) {
|
|
1695
|
+
try {
|
|
1696
|
+
await unlink(filePath);
|
|
1697
|
+
return true;
|
|
1698
|
+
} catch (e) {
|
|
1699
|
+
const error = e;
|
|
1700
|
+
if (error.code === "ENOENT") {
|
|
1701
|
+
return false;
|
|
1702
|
+
}
|
|
1703
|
+
throw e;
|
|
1704
|
+
}
|
|
1705
|
+
}
|
|
1706
|
+
/**
|
|
1707
|
+
* Atomic write: write to temp file then rename.
|
|
1708
|
+
* This ensures we don't corrupt the file if write is interrupted.
|
|
1709
|
+
*/
|
|
1710
|
+
async atomicWrite(filePath, entry) {
|
|
1711
|
+
const tempSuffix = bytesToHex(randomBytes(8));
|
|
1712
|
+
const tempPath = `${filePath}.${tempSuffix}.tmp`;
|
|
1713
|
+
try {
|
|
1714
|
+
const content = JSON.stringify(entry, null, 2);
|
|
1715
|
+
await writeFile(tempPath, content, { mode: this.fileMode });
|
|
1716
|
+
await rename(tempPath, filePath);
|
|
1717
|
+
} catch (e) {
|
|
1718
|
+
try {
|
|
1719
|
+
await unlink(tempPath);
|
|
1720
|
+
} catch {
|
|
1721
|
+
}
|
|
1722
|
+
throw e;
|
|
1723
|
+
}
|
|
1724
|
+
}
|
|
1725
|
+
/**
|
|
1726
|
+
* Get suggestion message for pub/sub not supported error.
|
|
1727
|
+
*/
|
|
1728
|
+
getPubSubSuggestion() {
|
|
1729
|
+
return "FileSystem adapter does not support pub/sub. Use Redis or Memory adapter for pub/sub support.";
|
|
1730
|
+
}
|
|
1731
|
+
};
|
|
1732
|
+
}
|
|
1733
|
+
});
|
|
1734
|
+
var indexeddb_exports = {};
|
|
1735
|
+
__export(indexeddb_exports, {
|
|
1736
|
+
IndexedDBStorageAdapter: () => IndexedDBStorageAdapter
|
|
1737
|
+
});
|
|
1738
|
+
var IndexedDBStorageAdapter;
|
|
1739
|
+
var init_indexeddb = __esm({
|
|
1740
|
+
"libs/utils/src/storage/adapters/indexeddb.ts"() {
|
|
1741
|
+
"use strict";
|
|
1742
|
+
init_base();
|
|
1743
|
+
init_pattern();
|
|
1744
|
+
IndexedDBStorageAdapter = class extends BaseStorageAdapter {
|
|
1745
|
+
backendName = "indexeddb";
|
|
1746
|
+
dbName;
|
|
1747
|
+
storeName;
|
|
1748
|
+
prefix;
|
|
1749
|
+
db = null;
|
|
1750
|
+
constructor(options) {
|
|
1751
|
+
super();
|
|
1752
|
+
this.dbName = options?.dbName ?? "frontmcp";
|
|
1753
|
+
this.storeName = options?.storeName ?? "kv";
|
|
1754
|
+
this.prefix = options?.prefix ?? "frontmcp:";
|
|
1755
|
+
}
|
|
1756
|
+
assertAvailable() {
|
|
1757
|
+
if (typeof indexedDB === "undefined") {
|
|
1758
|
+
throw new Error("IndexedDB is not available in this environment");
|
|
1759
|
+
}
|
|
1760
|
+
}
|
|
1761
|
+
key(k) {
|
|
1762
|
+
return `${this.prefix}${k}`;
|
|
1763
|
+
}
|
|
1764
|
+
stripPrefix(fullKey) {
|
|
1765
|
+
return fullKey.slice(this.prefix.length);
|
|
1766
|
+
}
|
|
1767
|
+
// ============================================
|
|
1768
|
+
// Connection Lifecycle
|
|
1769
|
+
// ============================================
|
|
1770
|
+
async connect() {
|
|
1771
|
+
this.assertAvailable();
|
|
1772
|
+
if (this.db) {
|
|
1773
|
+
this.connected = true;
|
|
1774
|
+
return;
|
|
1775
|
+
}
|
|
1776
|
+
this.db = await new Promise((resolve2, reject) => {
|
|
1777
|
+
const request = indexedDB.open(this.dbName, 1);
|
|
1778
|
+
request.onupgradeneeded = () => {
|
|
1779
|
+
const db = request.result;
|
|
1780
|
+
if (!db.objectStoreNames.contains(this.storeName)) {
|
|
1781
|
+
db.createObjectStore(this.storeName, { keyPath: "k" });
|
|
1782
|
+
}
|
|
1783
|
+
};
|
|
1784
|
+
request.onsuccess = () => resolve2(request.result);
|
|
1785
|
+
request.onerror = () => reject(request.error);
|
|
1786
|
+
});
|
|
1787
|
+
this.connected = true;
|
|
1788
|
+
}
|
|
1789
|
+
async disconnect() {
|
|
1790
|
+
if (this.db) {
|
|
1791
|
+
this.db.close();
|
|
1792
|
+
this.db = null;
|
|
1793
|
+
}
|
|
1794
|
+
this.connected = false;
|
|
1795
|
+
}
|
|
1796
|
+
async ping() {
|
|
1797
|
+
return this.db !== null && this.connected;
|
|
1798
|
+
}
|
|
1799
|
+
// ============================================
|
|
1800
|
+
// Internal Helpers
|
|
1801
|
+
// ============================================
|
|
1802
|
+
getStore(mode) {
|
|
1803
|
+
if (!this.db) {
|
|
1804
|
+
throw new Error("IndexedDB adapter is not connected. Call connect() first.");
|
|
1805
|
+
}
|
|
1806
|
+
const tx = this.db.transaction(this.storeName, mode);
|
|
1807
|
+
return tx.objectStore(this.storeName);
|
|
1808
|
+
}
|
|
1809
|
+
idbRequest(request) {
|
|
1810
|
+
return new Promise((resolve2, reject) => {
|
|
1811
|
+
request.onsuccess = () => resolve2(request.result);
|
|
1812
|
+
request.onerror = () => reject(request.error);
|
|
1813
|
+
});
|
|
1814
|
+
}
|
|
1815
|
+
idbTransaction(store) {
|
|
1816
|
+
return new Promise((resolve2, reject) => {
|
|
1817
|
+
const tx = store.transaction;
|
|
1818
|
+
tx.oncomplete = () => resolve2();
|
|
1819
|
+
tx.onerror = () => reject(tx.error);
|
|
1820
|
+
});
|
|
1821
|
+
}
|
|
1822
|
+
// ============================================
|
|
1823
|
+
// Core Operations
|
|
1824
|
+
// ============================================
|
|
1825
|
+
async get(key) {
|
|
1826
|
+
this.ensureConnected();
|
|
1827
|
+
const store = this.getStore("readonly");
|
|
1828
|
+
const entry = await this.idbRequest(store.get(this.key(key)));
|
|
1829
|
+
if (!entry) return null;
|
|
1830
|
+
if (entry.e && entry.e < Date.now()) {
|
|
1831
|
+
const writeStore = this.getStore("readwrite");
|
|
1832
|
+
writeStore.delete(this.key(key));
|
|
1833
|
+
return null;
|
|
1834
|
+
}
|
|
1835
|
+
return entry.v;
|
|
1836
|
+
}
|
|
1837
|
+
async doSet(key, value, options) {
|
|
1838
|
+
if (options?.ifNotExists) {
|
|
1839
|
+
const existing = await this.get(key);
|
|
1840
|
+
if (existing !== null) return;
|
|
1841
|
+
}
|
|
1842
|
+
if (options?.ifExists) {
|
|
1843
|
+
const existing = await this.get(key);
|
|
1844
|
+
if (existing === null) return;
|
|
1845
|
+
}
|
|
1846
|
+
const entry = { k: this.key(key), v: value };
|
|
1847
|
+
if (options?.ttlSeconds) {
|
|
1848
|
+
entry.e = Date.now() + options.ttlSeconds * 1e3;
|
|
1849
|
+
}
|
|
1850
|
+
const store = this.getStore("readwrite");
|
|
1851
|
+
await this.idbRequest(store.put(entry));
|
|
1852
|
+
}
|
|
1853
|
+
async delete(key) {
|
|
1854
|
+
this.ensureConnected();
|
|
1855
|
+
const existing = await this.get(key);
|
|
1856
|
+
if (existing === null) return false;
|
|
1857
|
+
const store = this.getStore("readwrite");
|
|
1858
|
+
await this.idbRequest(store.delete(this.key(key)));
|
|
1859
|
+
return true;
|
|
1860
|
+
}
|
|
1861
|
+
async exists(key) {
|
|
1862
|
+
return await this.get(key) !== null;
|
|
1863
|
+
}
|
|
1864
|
+
// ============================================
|
|
1865
|
+
// TTL Operations
|
|
1866
|
+
// ============================================
|
|
1867
|
+
async expire(key, ttlSeconds) {
|
|
1868
|
+
this.ensureConnected();
|
|
1869
|
+
const value = await this.get(key);
|
|
1870
|
+
if (value === null) return false;
|
|
1871
|
+
await this.doSet(key, value, { ttlSeconds });
|
|
1872
|
+
return true;
|
|
1873
|
+
}
|
|
1874
|
+
async ttl(key) {
|
|
1875
|
+
this.ensureConnected();
|
|
1876
|
+
const store = this.getStore("readonly");
|
|
1877
|
+
const entry = await this.idbRequest(store.get(this.key(key)));
|
|
1878
|
+
if (!entry) return null;
|
|
1879
|
+
if (entry.e) {
|
|
1880
|
+
const remaining = Math.ceil((entry.e - Date.now()) / 1e3);
|
|
1881
|
+
return remaining > 0 ? remaining : null;
|
|
1882
|
+
}
|
|
1883
|
+
return -1;
|
|
1884
|
+
}
|
|
1885
|
+
// ============================================
|
|
1886
|
+
// Key Enumeration
|
|
1887
|
+
// ============================================
|
|
1888
|
+
async keys(pattern) {
|
|
1889
|
+
this.ensureConnected();
|
|
1890
|
+
const store = this.getStore("readonly");
|
|
1891
|
+
const allKeys = await this.idbRequest(store.getAllKeys());
|
|
1892
|
+
const now = Date.now();
|
|
1893
|
+
const result = [];
|
|
1894
|
+
for (const fullKey of allKeys) {
|
|
1895
|
+
const keyStr = String(fullKey);
|
|
1896
|
+
if (!keyStr.startsWith(this.prefix)) continue;
|
|
1897
|
+
const key = this.stripPrefix(keyStr);
|
|
1898
|
+
if (pattern && pattern !== "*" && !this.matchPattern(key, pattern)) continue;
|
|
1899
|
+
const entry = await this.idbRequest(store.get(keyStr));
|
|
1900
|
+
if (entry && (!entry.e || entry.e >= now)) {
|
|
1901
|
+
result.push(key);
|
|
1902
|
+
}
|
|
1903
|
+
}
|
|
1904
|
+
return result;
|
|
1905
|
+
}
|
|
1906
|
+
// ============================================
|
|
1907
|
+
// Atomic Operations
|
|
1908
|
+
// ============================================
|
|
1909
|
+
async incr(key) {
|
|
1910
|
+
return this.incrBy(key, 1);
|
|
1911
|
+
}
|
|
1912
|
+
async decr(key) {
|
|
1913
|
+
return this.incrBy(key, -1);
|
|
1914
|
+
}
|
|
1915
|
+
/**
|
|
1916
|
+
* Increment by amount. NOT atomic — uses read-then-write which can race
|
|
1917
|
+
* under concurrent access (e.g., multiple browser tabs).
|
|
1918
|
+
*/
|
|
1919
|
+
async incrBy(key, amount) {
|
|
1920
|
+
this.ensureConnected();
|
|
1921
|
+
const current = await this.get(key);
|
|
1922
|
+
const value = current !== null ? parseInt(current, 10) + amount : amount;
|
|
1923
|
+
if (Number.isNaN(value)) {
|
|
1924
|
+
throw new Error(`Value at "${key}" is not an integer`);
|
|
1925
|
+
}
|
|
1926
|
+
await this.doSet(key, String(value));
|
|
1927
|
+
return value;
|
|
1928
|
+
}
|
|
1929
|
+
// ============================================
|
|
1930
|
+
// Pattern Matching
|
|
1931
|
+
// ============================================
|
|
1932
|
+
matchPattern(key, pattern) {
|
|
1933
|
+
return matchesPattern(key, pattern);
|
|
1934
|
+
}
|
|
1935
|
+
};
|
|
1936
|
+
}
|
|
1937
|
+
});
|
|
1938
|
+
var localstorage_exports = {};
|
|
1939
|
+
__export(localstorage_exports, {
|
|
1940
|
+
LocalStorageAdapter: () => LocalStorageAdapter
|
|
1941
|
+
});
|
|
1942
|
+
var LocalStorageAdapter;
|
|
1943
|
+
var init_localstorage = __esm({
|
|
1944
|
+
"libs/utils/src/storage/adapters/localstorage.ts"() {
|
|
1945
|
+
"use strict";
|
|
1946
|
+
init_base();
|
|
1947
|
+
init_crypto();
|
|
1948
|
+
init_pattern();
|
|
1949
|
+
LocalStorageAdapter = class extends BaseStorageAdapter {
|
|
1950
|
+
backendName = "localstorage";
|
|
1951
|
+
prefix;
|
|
1952
|
+
encryptionKey;
|
|
1953
|
+
allowPlaintext;
|
|
1954
|
+
encoder = new TextEncoder();
|
|
1955
|
+
decoder = new TextDecoder();
|
|
1956
|
+
constructor(options) {
|
|
1957
|
+
super();
|
|
1958
|
+
this.prefix = options?.prefix ?? "frontmcp:";
|
|
1959
|
+
this.allowPlaintext = options?.allowPlaintext ?? true;
|
|
1960
|
+
if (options?.encryptionKey) {
|
|
1961
|
+
if (options.encryptionKey.length !== 32) {
|
|
1962
|
+
throw new Error(`encryptionKey must be exactly 32 bytes, got ${options.encryptionKey.length}`);
|
|
1963
|
+
}
|
|
1964
|
+
this.encryptionKey = options.encryptionKey;
|
|
1965
|
+
}
|
|
1966
|
+
}
|
|
1967
|
+
assertAvailable() {
|
|
1968
|
+
if (typeof localStorage === "undefined") {
|
|
1969
|
+
throw new Error("localStorage is not available in this environment");
|
|
1970
|
+
}
|
|
1971
|
+
}
|
|
1972
|
+
key(k) {
|
|
1973
|
+
return `${this.prefix}${k}`;
|
|
1974
|
+
}
|
|
1975
|
+
stripPrefix(fullKey) {
|
|
1976
|
+
return fullKey.slice(this.prefix.length);
|
|
1977
|
+
}
|
|
1978
|
+
async connect() {
|
|
1979
|
+
this.assertAvailable();
|
|
1980
|
+
const probeKey = this.key("__probe__");
|
|
1981
|
+
try {
|
|
1982
|
+
localStorage.setItem(probeKey, "1");
|
|
1983
|
+
const read = localStorage.getItem(probeKey);
|
|
1984
|
+
if (read !== "1") {
|
|
1985
|
+
throw new Error("localStorage probe: read-back mismatch");
|
|
1986
|
+
}
|
|
1987
|
+
} catch (err) {
|
|
1988
|
+
throw new Error(`localStorage is not writable: ${err instanceof Error ? err.message : String(err)}`);
|
|
1989
|
+
} finally {
|
|
1990
|
+
try {
|
|
1991
|
+
localStorage.removeItem(probeKey);
|
|
1992
|
+
} catch {
|
|
1993
|
+
}
|
|
1994
|
+
}
|
|
1995
|
+
this.connected = true;
|
|
1996
|
+
}
|
|
1997
|
+
async disconnect() {
|
|
1998
|
+
this.connected = false;
|
|
1999
|
+
}
|
|
2000
|
+
async ping() {
|
|
2001
|
+
const probeKey = this.key("__probe__");
|
|
2002
|
+
try {
|
|
2003
|
+
this.assertAvailable();
|
|
2004
|
+
localStorage.setItem(probeKey, "1");
|
|
2005
|
+
return localStorage.getItem(probeKey) === "1";
|
|
2006
|
+
} catch {
|
|
2007
|
+
return false;
|
|
2008
|
+
} finally {
|
|
2009
|
+
try {
|
|
2010
|
+
localStorage.removeItem(probeKey);
|
|
2011
|
+
} catch {
|
|
2012
|
+
}
|
|
2013
|
+
}
|
|
2014
|
+
}
|
|
2015
|
+
async get(key) {
|
|
2016
|
+
const raw = localStorage.getItem(this.key(key));
|
|
2017
|
+
if (raw === null) return null;
|
|
2018
|
+
try {
|
|
2019
|
+
const entry = JSON.parse(raw);
|
|
2020
|
+
if (entry.e && entry.e < Date.now()) {
|
|
2021
|
+
localStorage.removeItem(this.key(key));
|
|
2022
|
+
return null;
|
|
2023
|
+
}
|
|
2024
|
+
if (entry._enc) {
|
|
2025
|
+
if (!this.encryptionKey) return null;
|
|
2026
|
+
const iv = base64urlDecode(entry._enc.iv);
|
|
2027
|
+
const tag = base64urlDecode(entry._enc.tag);
|
|
2028
|
+
const ciphertext = base64urlDecode(entry._enc.data);
|
|
2029
|
+
const plainBytes = decryptAesGcm(this.encryptionKey, ciphertext, iv, tag);
|
|
2030
|
+
return this.decoder.decode(plainBytes);
|
|
2031
|
+
}
|
|
2032
|
+
return entry.v;
|
|
2033
|
+
} catch {
|
|
2034
|
+
return null;
|
|
2035
|
+
}
|
|
2036
|
+
}
|
|
2037
|
+
async set(key, value, options) {
|
|
2038
|
+
if (options?.ifNotExists) {
|
|
2039
|
+
const existing = await this.get(key);
|
|
2040
|
+
if (existing !== null) return;
|
|
2041
|
+
}
|
|
2042
|
+
if (options?.ifExists) {
|
|
2043
|
+
const existing = await this.get(key);
|
|
2044
|
+
if (existing === null) return;
|
|
2045
|
+
}
|
|
2046
|
+
await this.doSet(key, value, options);
|
|
2047
|
+
}
|
|
2048
|
+
async doSet(key, value, options) {
|
|
2049
|
+
const entry = { v: "" };
|
|
2050
|
+
if (options?.ttlSeconds) {
|
|
2051
|
+
entry.e = Date.now() + options.ttlSeconds * 1e3;
|
|
2052
|
+
}
|
|
2053
|
+
if (this.encryptionKey) {
|
|
2054
|
+
const iv = randomBytes(12);
|
|
2055
|
+
const plainBytes = this.encoder.encode(value);
|
|
2056
|
+
const { ciphertext, tag } = encryptAesGcm(this.encryptionKey, plainBytes, iv);
|
|
2057
|
+
entry._enc = {
|
|
2058
|
+
alg: "A256GCM",
|
|
2059
|
+
iv: base64urlEncode(iv),
|
|
2060
|
+
tag: base64urlEncode(tag),
|
|
2061
|
+
data: base64urlEncode(ciphertext)
|
|
2062
|
+
};
|
|
2063
|
+
} else {
|
|
2064
|
+
if (!this.allowPlaintext) {
|
|
2065
|
+
throw new Error("Plaintext storage is disabled. Provide an encryptionKey or set allowPlaintext: true.");
|
|
2066
|
+
}
|
|
2067
|
+
entry.v = value;
|
|
2068
|
+
}
|
|
2069
|
+
localStorage.setItem(this.key(key), JSON.stringify(entry));
|
|
2070
|
+
}
|
|
2071
|
+
async delete(key) {
|
|
2072
|
+
const existed = await this.get(key) !== null;
|
|
2073
|
+
localStorage.removeItem(this.key(key));
|
|
2074
|
+
return existed;
|
|
2075
|
+
}
|
|
2076
|
+
async exists(key) {
|
|
2077
|
+
return await this.get(key) !== null;
|
|
2078
|
+
}
|
|
2079
|
+
async mget(keys) {
|
|
2080
|
+
return Promise.all(keys.map((k) => this.get(k)));
|
|
2081
|
+
}
|
|
2082
|
+
async mset(entries) {
|
|
2083
|
+
for (const entry of entries) {
|
|
2084
|
+
await this.set(entry.key, entry.value, entry.options);
|
|
2085
|
+
}
|
|
2086
|
+
}
|
|
2087
|
+
async mdelete(keys) {
|
|
2088
|
+
let count = 0;
|
|
2089
|
+
for (const key of keys) {
|
|
2090
|
+
if (await this.delete(key)) count++;
|
|
2091
|
+
}
|
|
2092
|
+
return count;
|
|
2093
|
+
}
|
|
2094
|
+
async expire(key, ttlSeconds) {
|
|
2095
|
+
const value = await this.get(key);
|
|
2096
|
+
if (value === null) return false;
|
|
2097
|
+
await this.set(key, value, { ttlSeconds });
|
|
2098
|
+
return true;
|
|
2099
|
+
}
|
|
2100
|
+
async ttl(key) {
|
|
2101
|
+
const raw = localStorage.getItem(this.key(key));
|
|
2102
|
+
if (raw === null) return null;
|
|
2103
|
+
try {
|
|
2104
|
+
const entry = JSON.parse(raw);
|
|
2105
|
+
if (!entry.e) return -1;
|
|
2106
|
+
const remaining = Math.ceil((entry.e - Date.now()) / 1e3);
|
|
2107
|
+
return remaining > 0 ? remaining : null;
|
|
2108
|
+
} catch {
|
|
2109
|
+
return null;
|
|
2110
|
+
}
|
|
2111
|
+
}
|
|
2112
|
+
async keys(pattern) {
|
|
2113
|
+
const result = [];
|
|
2114
|
+
const candidates = [];
|
|
2115
|
+
for (let i = 0; i < localStorage.length; i++) {
|
|
2116
|
+
const fullKey = localStorage.key(i);
|
|
2117
|
+
if (fullKey && fullKey.startsWith(this.prefix)) {
|
|
2118
|
+
candidates.push(this.stripPrefix(fullKey));
|
|
2119
|
+
}
|
|
2120
|
+
}
|
|
2121
|
+
for (const key of candidates) {
|
|
2122
|
+
if (!pattern || pattern === "*" || this.matchPattern(key, pattern)) {
|
|
2123
|
+
if (await this.get(key) !== null) {
|
|
2124
|
+
result.push(key);
|
|
2125
|
+
}
|
|
2126
|
+
}
|
|
2127
|
+
}
|
|
2128
|
+
return result;
|
|
2129
|
+
}
|
|
2130
|
+
async count(pattern) {
|
|
2131
|
+
return (await this.keys(pattern)).length;
|
|
2132
|
+
}
|
|
2133
|
+
async incr(key) {
|
|
2134
|
+
return this.incrBy(key, 1);
|
|
2135
|
+
}
|
|
2136
|
+
async decr(key) {
|
|
2137
|
+
return this.incrBy(key, -1);
|
|
2138
|
+
}
|
|
2139
|
+
async incrBy(key, amount) {
|
|
2140
|
+
if (!Number.isInteger(amount)) {
|
|
2141
|
+
throw new Error(`amount must be an integer, got ${amount}`);
|
|
2142
|
+
}
|
|
2143
|
+
const current = await this.get(key);
|
|
2144
|
+
if (current !== null && !/^-?\d+$/.test(current)) {
|
|
2145
|
+
throw new Error(`Value at "${key}" is not an integer`);
|
|
2146
|
+
}
|
|
2147
|
+
const value = current !== null ? parseInt(current, 10) + amount : amount;
|
|
2148
|
+
await this.set(key, String(value));
|
|
2149
|
+
return value;
|
|
2150
|
+
}
|
|
2151
|
+
async publish() {
|
|
2152
|
+
throw new Error("LocalStorage adapter does not support pub/sub");
|
|
2153
|
+
}
|
|
2154
|
+
async subscribe(_channel, _handler) {
|
|
2155
|
+
throw new Error("LocalStorage adapter does not support pub/sub");
|
|
2156
|
+
}
|
|
2157
|
+
supportsPubSub() {
|
|
2158
|
+
return false;
|
|
2159
|
+
}
|
|
2160
|
+
matchPattern(key, pattern) {
|
|
2161
|
+
return matchesPattern(key, pattern);
|
|
2162
|
+
}
|
|
2163
|
+
};
|
|
2164
|
+
}
|
|
2165
|
+
});
|
|
2166
|
+
var DEFAULT_BASE_DIR;
|
|
2167
|
+
var LS_HKDF_IKM;
|
|
2168
|
+
var INSTALL_SALT_KEY;
|
|
2169
|
+
var LEGACY_SALT_KEY;
|
|
2170
|
+
var init_factory = __esm({
|
|
2171
|
+
"libs/utils/src/crypto/key-persistence/factory.ts"() {
|
|
2172
|
+
"use strict";
|
|
2173
|
+
init_runtime();
|
|
2174
|
+
init_memory();
|
|
2175
|
+
init_key_persistence();
|
|
2176
|
+
init_crypto();
|
|
2177
|
+
DEFAULT_BASE_DIR = ".frontmcp/keys";
|
|
2178
|
+
LS_HKDF_IKM = new TextEncoder().encode("frontmcp:localstorage:v1");
|
|
2179
|
+
INSTALL_SALT_KEY = "__frontmcp_internal__:install_salt";
|
|
2180
|
+
LEGACY_SALT_KEY = "frontmcp:_install_salt";
|
|
2181
|
+
}
|
|
2182
|
+
});
|
|
2183
|
+
var init_key_persistence2 = __esm({
|
|
2184
|
+
"libs/utils/src/crypto/key-persistence/index.ts"() {
|
|
2185
|
+
"use strict";
|
|
2186
|
+
init_schemas();
|
|
2187
|
+
init_key_persistence();
|
|
2188
|
+
init_factory();
|
|
2189
|
+
}
|
|
2190
|
+
});
|
|
2191
|
+
var node_exports = {};
|
|
2192
|
+
__export(node_exports, {
|
|
2193
|
+
createSignedJwt: () => createSignedJwt,
|
|
2194
|
+
cryptoProvider: () => nodeCrypto,
|
|
2195
|
+
generateRsaKeyPair: () => generateRsaKeyPair,
|
|
2196
|
+
isRsaPssAlg: () => isRsaPssAlg,
|
|
2197
|
+
jwtAlgToNodeAlg: () => jwtAlgToNodeAlg,
|
|
2198
|
+
nodeCrypto: () => nodeCrypto,
|
|
2199
|
+
pemToPublicJwk: () => pemToPublicJwk,
|
|
2200
|
+
rsaSign: () => rsaSign,
|
|
2201
|
+
rsaSignBase64Url: () => rsaSignBase64Url,
|
|
2202
|
+
rsaVerify: () => rsaVerify,
|
|
2203
|
+
rsaVerifySync: () => rsaVerifySync
|
|
2204
|
+
});
|
|
2205
|
+
function toUint8Array(buf) {
|
|
2206
|
+
return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
2207
|
+
}
|
|
2208
|
+
function toBuffer(data) {
|
|
2209
|
+
if (typeof data === "string") {
|
|
2210
|
+
return Buffer.from(data, "utf8");
|
|
2211
|
+
}
|
|
2212
|
+
return Buffer.from(data);
|
|
2213
|
+
}
|
|
2214
|
+
function generateRsaKeyPair(modulusLength = 2048, alg = "RS256") {
|
|
2215
|
+
const kid = `rsa-key-${Date.now()}-${crypto2.randomBytes(8).toString("hex")}`;
|
|
2216
|
+
const { privateKey, publicKey } = crypto2.generateKeyPairSync("rsa", {
|
|
2217
|
+
modulusLength
|
|
2218
|
+
});
|
|
2219
|
+
const exported = publicKey.export({ format: "jwk" });
|
|
2220
|
+
const publicJwk = {
|
|
2221
|
+
...exported,
|
|
2222
|
+
kid,
|
|
2223
|
+
alg,
|
|
2224
|
+
use: "sig",
|
|
2225
|
+
kty: "RSA"
|
|
2226
|
+
};
|
|
2227
|
+
return { privateKey, publicKey, publicJwk };
|
|
2228
|
+
}
|
|
2229
|
+
function rsaSign(algorithm, data, privateKey, options) {
|
|
2230
|
+
const signingKey = options ? { key: privateKey, ...options } : privateKey;
|
|
2231
|
+
return crypto2.sign(algorithm, data, signingKey);
|
|
2232
|
+
}
|
|
2233
|
+
function rsaVerify(jwtAlg, data, publicJwk, signature) {
|
|
2234
|
+
const publicKey = crypto2.createPublicKey({ key: publicJwk, format: "jwk" });
|
|
2235
|
+
const nodeAlgorithm = jwtAlgToNodeAlg(jwtAlg);
|
|
2236
|
+
const verifyKey = isRsaPssAlg(jwtAlg) ? {
|
|
2237
|
+
key: publicKey,
|
|
2238
|
+
padding: crypto2.constants.RSA_PKCS1_PSS_PADDING,
|
|
2239
|
+
saltLength: crypto2.constants.RSA_PSS_SALTLEN_DIGEST
|
|
2240
|
+
} : publicKey;
|
|
2241
|
+
return crypto2.verify(nodeAlgorithm, data, verifyKey, signature);
|
|
2242
|
+
}
|
|
2243
|
+
function rsaSignBase64Url(jwtAlg, data, privateJwk) {
|
|
2244
|
+
const privateKey = crypto2.createPrivateKey({ key: privateJwk, format: "jwk" });
|
|
2245
|
+
const nodeAlgorithm = jwtAlgToNodeAlg(jwtAlg);
|
|
2246
|
+
const buf = Buffer.isBuffer(data) ? data : Buffer.from(data);
|
|
2247
|
+
const sig = isRsaPssAlg(jwtAlg) ? rsaSign(nodeAlgorithm, buf, privateKey, {
|
|
2248
|
+
padding: crypto2.constants.RSA_PKCS1_PSS_PADDING,
|
|
2249
|
+
saltLength: crypto2.constants.RSA_PSS_SALTLEN_DIGEST
|
|
2250
|
+
}) : rsaSign(nodeAlgorithm, buf, privateKey);
|
|
2251
|
+
return sig.toString("base64url");
|
|
2252
|
+
}
|
|
2253
|
+
function rsaVerifySync(jwtAlg, data, publicJwk, signature) {
|
|
2254
|
+
try {
|
|
2255
|
+
const publicKey = crypto2.createPublicKey({ key: publicJwk, format: "jwk" });
|
|
2256
|
+
const dataBuf = Buffer.isBuffer(data) ? data : Buffer.from(data);
|
|
2257
|
+
const sigBuf = Buffer.isBuffer(signature) ? signature : Buffer.from(signature);
|
|
2258
|
+
if (jwtAlg === "EdDSA") {
|
|
2259
|
+
return crypto2.verify(null, dataBuf, publicKey, sigBuf);
|
|
2260
|
+
}
|
|
2261
|
+
const nodeAlgorithm = jwtAlgToNodeAlg(jwtAlg);
|
|
2262
|
+
const verifyKey = isRsaPssAlg(jwtAlg) ? {
|
|
2263
|
+
key: publicKey,
|
|
2264
|
+
padding: crypto2.constants.RSA_PKCS1_PSS_PADDING,
|
|
2265
|
+
saltLength: crypto2.constants.RSA_PSS_SALTLEN_DIGEST
|
|
2266
|
+
} : publicKey;
|
|
2267
|
+
return crypto2.verify(nodeAlgorithm, dataBuf, verifyKey, sigBuf);
|
|
2268
|
+
} catch {
|
|
2269
|
+
return false;
|
|
2270
|
+
}
|
|
2271
|
+
}
|
|
2272
|
+
function pemToPublicJwk(pem) {
|
|
2273
|
+
const key = crypto2.createPublicKey({ key: pem, format: "pem" });
|
|
2274
|
+
return key.export({ format: "jwk" });
|
|
2275
|
+
}
|
|
2276
|
+
function createSignedJwt(payload, privateKey, kid, alg = "RS256") {
|
|
2277
|
+
const header = { alg, typ: "JWT", kid };
|
|
2278
|
+
const headerB64 = Buffer.from(JSON.stringify(header)).toString("base64url");
|
|
2279
|
+
const payloadB64 = Buffer.from(JSON.stringify(payload)).toString("base64url");
|
|
2280
|
+
const signatureInput = `${headerB64}.${payloadB64}`;
|
|
2281
|
+
const nodeAlgorithm = jwtAlgToNodeAlg(alg);
|
|
2282
|
+
const signature = rsaSign(
|
|
2283
|
+
nodeAlgorithm,
|
|
2284
|
+
Buffer.from(signatureInput),
|
|
2285
|
+
privateKey,
|
|
2286
|
+
isRsaPssAlg(alg) ? {
|
|
2287
|
+
padding: crypto2.constants.RSA_PKCS1_PSS_PADDING,
|
|
2288
|
+
saltLength: crypto2.constants.RSA_PSS_SALTLEN_DIGEST
|
|
2289
|
+
} : void 0
|
|
2290
|
+
);
|
|
2291
|
+
const signatureB64 = signature.toString("base64url");
|
|
2292
|
+
return `${headerB64}.${payloadB64}.${signatureB64}`;
|
|
2293
|
+
}
|
|
2294
|
+
var nodeCrypto;
|
|
2295
|
+
var init_node = __esm({
|
|
2296
|
+
"libs/utils/src/crypto/node.ts"() {
|
|
2297
|
+
"use strict";
|
|
2298
|
+
init_jwt_alg();
|
|
2299
|
+
init_jwt_alg();
|
|
2300
|
+
nodeCrypto = {
|
|
2301
|
+
randomUUID() {
|
|
2302
|
+
return crypto2.randomUUID();
|
|
2303
|
+
},
|
|
2304
|
+
randomBytes(length) {
|
|
2305
|
+
return toUint8Array(crypto2.randomBytes(length));
|
|
2306
|
+
},
|
|
2307
|
+
sha256(data) {
|
|
2308
|
+
const hash = crypto2.createHash("sha256").update(toBuffer(data)).digest();
|
|
2309
|
+
return toUint8Array(hash);
|
|
2310
|
+
},
|
|
2311
|
+
sha256Hex(data) {
|
|
2312
|
+
return crypto2.createHash("sha256").update(toBuffer(data)).digest("hex");
|
|
2313
|
+
},
|
|
2314
|
+
hmacSha256(key, data) {
|
|
2315
|
+
const hmac2 = crypto2.createHmac("sha256", Buffer.from(key)).update(Buffer.from(data)).digest();
|
|
2316
|
+
return toUint8Array(hmac2);
|
|
2317
|
+
},
|
|
2318
|
+
hkdfSha256(ikm, salt, info, length) {
|
|
2319
|
+
const ikmBuf = Buffer.from(ikm);
|
|
2320
|
+
const saltBuf = salt.length > 0 ? Buffer.from(salt) : Buffer.alloc(32);
|
|
2321
|
+
const prk = crypto2.createHmac("sha256", saltBuf).update(ikmBuf).digest();
|
|
2322
|
+
const hashLen = 32;
|
|
2323
|
+
const n = Math.ceil(length / hashLen);
|
|
2324
|
+
const chunks = [];
|
|
2325
|
+
let prev = Buffer.alloc(0);
|
|
2326
|
+
for (let i = 1; i <= n; i++) {
|
|
2327
|
+
prev = crypto2.createHmac("sha256", prk).update(Buffer.concat([prev, Buffer.from(info), Buffer.from([i])])).digest();
|
|
2328
|
+
chunks.push(prev);
|
|
2329
|
+
}
|
|
2330
|
+
return toUint8Array(Buffer.concat(chunks).subarray(0, length));
|
|
2331
|
+
},
|
|
2332
|
+
encryptAesGcm(key, plaintext, iv) {
|
|
2333
|
+
const cipher = crypto2.createCipheriv("aes-256-gcm", Buffer.from(key), Buffer.from(iv));
|
|
2334
|
+
const encrypted = Buffer.concat([cipher.update(Buffer.from(plaintext)), cipher.final()]);
|
|
2335
|
+
const tag = cipher.getAuthTag();
|
|
2336
|
+
return {
|
|
2337
|
+
ciphertext: toUint8Array(encrypted),
|
|
2338
|
+
tag: toUint8Array(tag)
|
|
2339
|
+
};
|
|
2340
|
+
},
|
|
2341
|
+
decryptAesGcm(key, ciphertext, iv, tag) {
|
|
2342
|
+
const decipher = crypto2.createDecipheriv("aes-256-gcm", Buffer.from(key), Buffer.from(iv));
|
|
2343
|
+
decipher.setAuthTag(Buffer.from(tag));
|
|
2344
|
+
const decrypted = Buffer.concat([decipher.update(Buffer.from(ciphertext)), decipher.final()]);
|
|
2345
|
+
return toUint8Array(decrypted);
|
|
2346
|
+
},
|
|
2347
|
+
timingSafeEqual(a, b) {
|
|
2348
|
+
if (a.length !== b.length) return false;
|
|
2349
|
+
return crypto2.timingSafeEqual(Buffer.from(a), Buffer.from(b));
|
|
2350
|
+
}
|
|
2351
|
+
};
|
|
2352
|
+
}
|
|
2353
|
+
});
|
|
2354
|
+
var browser_exports = {};
|
|
2355
|
+
__export(browser_exports, {
|
|
2356
|
+
browserCrypto: () => browserCrypto,
|
|
2357
|
+
cryptoProvider: () => browserCrypto,
|
|
2358
|
+
isRsaPssAlg: () => isRsaPssAlg,
|
|
2359
|
+
jwtAlgToWebCryptoAlg: () => jwtAlgToWebCryptoAlg,
|
|
2360
|
+
rsaVerifyBrowser: () => rsaVerifyBrowser
|
|
2361
|
+
});
|
|
2362
|
+
function toBytes(data) {
|
|
2363
|
+
if (typeof data === "string") {
|
|
2364
|
+
return new TextEncoder().encode(data);
|
|
2365
|
+
}
|
|
2366
|
+
return data;
|
|
2367
|
+
}
|
|
2368
|
+
function toHex(bytes) {
|
|
2369
|
+
return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
2370
|
+
}
|
|
2371
|
+
function generateUUID() {
|
|
2372
|
+
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
|
|
2373
|
+
return crypto.randomUUID();
|
|
2374
|
+
}
|
|
2375
|
+
const bytes = nobleRandomBytes(16);
|
|
2376
|
+
bytes[6] = bytes[6] & 15 | 64;
|
|
2377
|
+
bytes[8] = bytes[8] & 63 | 128;
|
|
2378
|
+
const hex = toHex(bytes);
|
|
2379
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
2380
|
+
}
|
|
2381
|
+
function constantTimeEqual(a, b) {
|
|
2382
|
+
if (a.length !== b.length) return false;
|
|
2383
|
+
let result = 0;
|
|
2384
|
+
for (let i = 0; i < a.length; i++) {
|
|
2385
|
+
result |= a[i] ^ b[i];
|
|
2386
|
+
}
|
|
2387
|
+
return result === 0;
|
|
2388
|
+
}
|
|
2389
|
+
async function rsaVerifyBrowser(jwtAlg, data, publicJwk, signature) {
|
|
2390
|
+
if (typeof globalThis.crypto?.subtle === "undefined") {
|
|
2391
|
+
throw new Error("WebCrypto API (crypto.subtle) is not available in this environment");
|
|
2392
|
+
}
|
|
2393
|
+
const webAlg = jwtAlgToWebCryptoAlg(jwtAlg);
|
|
2394
|
+
const isPss = isRsaPssAlg(jwtAlg);
|
|
2395
|
+
const algorithm = {
|
|
2396
|
+
name: isPss ? "RSA-PSS" : "RSASSA-PKCS1-v1_5",
|
|
2397
|
+
hash: { name: webAlg }
|
|
2398
|
+
};
|
|
2399
|
+
const key = await globalThis.crypto.subtle.importKey("jwk", publicJwk, algorithm, false, ["verify"]);
|
|
2400
|
+
const verifyAlgorithm = isPss ? { name: "RSA-PSS", saltLength: getSaltLength(jwtAlg) } : { name: "RSASSA-PKCS1-v1_5" };
|
|
2401
|
+
const sigBuf = new Uint8Array(signature).buffer;
|
|
2402
|
+
const dataBuf = new Uint8Array(data).buffer;
|
|
2403
|
+
return globalThis.crypto.subtle.verify(verifyAlgorithm, key, sigBuf, dataBuf);
|
|
2404
|
+
}
|
|
2405
|
+
function getSaltLength(jwtAlg) {
|
|
2406
|
+
switch (jwtAlg) {
|
|
2407
|
+
case "PS256":
|
|
2408
|
+
return 32;
|
|
2409
|
+
// SHA-256 digest length
|
|
2410
|
+
case "PS384":
|
|
2411
|
+
return 48;
|
|
2412
|
+
// SHA-384 digest length
|
|
2413
|
+
case "PS512":
|
|
2414
|
+
return 64;
|
|
2415
|
+
// SHA-512 digest length
|
|
2416
|
+
default:
|
|
2417
|
+
return 32;
|
|
2418
|
+
}
|
|
2419
|
+
}
|
|
2420
|
+
var browserCrypto;
|
|
2421
|
+
var init_browser = __esm({
|
|
2422
|
+
"libs/utils/src/crypto/browser.ts"() {
|
|
2423
|
+
"use strict";
|
|
2424
|
+
init_jwt_alg();
|
|
2425
|
+
init_jwt_alg();
|
|
2426
|
+
browserCrypto = {
|
|
2427
|
+
randomUUID() {
|
|
2428
|
+
return generateUUID();
|
|
2429
|
+
},
|
|
2430
|
+
randomBytes(length) {
|
|
2431
|
+
return nobleRandomBytes(length);
|
|
2432
|
+
},
|
|
2433
|
+
sha256(data) {
|
|
2434
|
+
return sha256Hash(toBytes(data));
|
|
2435
|
+
},
|
|
2436
|
+
sha256Hex(data) {
|
|
2437
|
+
return toHex(sha256Hash(toBytes(data)));
|
|
2438
|
+
},
|
|
2439
|
+
hmacSha256(key, data) {
|
|
2440
|
+
return hmac(sha256Hash, key, data);
|
|
2441
|
+
},
|
|
2442
|
+
hkdfSha256(ikm, salt, info, length) {
|
|
2443
|
+
const effectiveSalt = salt.length > 0 ? salt : new Uint8Array(32);
|
|
2444
|
+
return hkdf(sha256Hash, ikm, effectiveSalt, info, length);
|
|
2445
|
+
},
|
|
2446
|
+
encryptAesGcm(key, plaintext, iv) {
|
|
2447
|
+
const cipher = gcm(key, iv);
|
|
2448
|
+
const sealed = cipher.encrypt(plaintext);
|
|
2449
|
+
const ciphertext = sealed.slice(0, -16);
|
|
2450
|
+
const tag = sealed.slice(-16);
|
|
2451
|
+
return { ciphertext, tag };
|
|
2452
|
+
},
|
|
2453
|
+
decryptAesGcm(key, ciphertext, iv, tag) {
|
|
2454
|
+
const cipher = gcm(key, iv);
|
|
2455
|
+
const sealed = new Uint8Array(ciphertext.length + tag.length);
|
|
2456
|
+
sealed.set(ciphertext);
|
|
2457
|
+
sealed.set(tag, ciphertext.length);
|
|
2458
|
+
return cipher.decrypt(sealed);
|
|
2459
|
+
},
|
|
2460
|
+
timingSafeEqual(a, b) {
|
|
2461
|
+
return constantTimeEqual(a, b);
|
|
2462
|
+
}
|
|
2463
|
+
};
|
|
2464
|
+
}
|
|
2465
|
+
});
|
|
2466
|
+
function getCrypto() {
|
|
2467
|
+
return import_crypto_provider.cryptoProvider;
|
|
2468
|
+
}
|
|
2469
|
+
function randomUUID() {
|
|
2470
|
+
return getCrypto().randomUUID();
|
|
2471
|
+
}
|
|
2472
|
+
function randomBytes(length) {
|
|
2473
|
+
if (!Number.isInteger(length) || length <= 0) {
|
|
2474
|
+
throw new Error(`randomBytes length must be a positive integer, got ${length}`);
|
|
2475
|
+
}
|
|
2476
|
+
return getCrypto().randomBytes(length);
|
|
2477
|
+
}
|
|
2478
|
+
function sha256Hex(data) {
|
|
2479
|
+
return getCrypto().sha256Hex(data);
|
|
2480
|
+
}
|
|
2481
|
+
function encryptAesGcm(key, plaintext, iv) {
|
|
2482
|
+
if (key.length !== 32) {
|
|
2483
|
+
throw new Error(`AES-256-GCM requires a 32-byte key, got ${key.length} bytes`);
|
|
2484
|
+
}
|
|
2485
|
+
if (iv.length !== 12) {
|
|
2486
|
+
throw new Error(`AES-GCM requires a 12-byte IV, got ${iv.length} bytes`);
|
|
2487
|
+
}
|
|
2488
|
+
return getCrypto().encryptAesGcm(key, plaintext, iv);
|
|
2489
|
+
}
|
|
2490
|
+
function decryptAesGcm(key, ciphertext, iv, tag) {
|
|
2491
|
+
if (key.length !== 32) {
|
|
2492
|
+
throw new Error(`AES-256-GCM requires a 32-byte key, got ${key.length} bytes`);
|
|
2493
|
+
}
|
|
2494
|
+
if (iv.length !== 12) {
|
|
2495
|
+
throw new Error(`AES-GCM requires a 12-byte IV, got ${iv.length} bytes`);
|
|
2496
|
+
}
|
|
2497
|
+
if (tag.length !== 16) {
|
|
2498
|
+
throw new Error(`AES-GCM requires a 16-byte authentication tag, got ${tag.length} bytes`);
|
|
2499
|
+
}
|
|
2500
|
+
return getCrypto().decryptAesGcm(key, ciphertext, iv, tag);
|
|
2501
|
+
}
|
|
2502
|
+
function bytesToHex(data) {
|
|
2503
|
+
return Array.from(data).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
2504
|
+
}
|
|
2505
|
+
function base64urlEncode(data) {
|
|
2506
|
+
let base64;
|
|
2507
|
+
if (typeof Buffer !== "undefined") {
|
|
2508
|
+
base64 = Buffer.from(data).toString("base64");
|
|
2509
|
+
} else {
|
|
2510
|
+
const binString = Array.from(data, (byte) => String.fromCodePoint(byte)).join("");
|
|
2511
|
+
base64 = btoa(binString);
|
|
2512
|
+
}
|
|
2513
|
+
const result = base64.replace(/\+/g, "-").replace(/\//g, "_");
|
|
2514
|
+
let end = result.length;
|
|
2515
|
+
while (end > 0 && result[end - 1] === "=") {
|
|
2516
|
+
end--;
|
|
2517
|
+
}
|
|
2518
|
+
return result.slice(0, end);
|
|
2519
|
+
}
|
|
2520
|
+
function base64urlDecode(data) {
|
|
2521
|
+
let base64 = data.replace(/-/g, "+").replace(/_/g, "/");
|
|
2522
|
+
const pad = base64.length % 4;
|
|
2523
|
+
if (pad) {
|
|
2524
|
+
base64 += "=".repeat(4 - pad);
|
|
2525
|
+
}
|
|
2526
|
+
if (typeof Buffer !== "undefined") {
|
|
2527
|
+
return new Uint8Array(Buffer.from(base64, "base64"));
|
|
2528
|
+
} else {
|
|
2529
|
+
const binString = atob(base64);
|
|
2530
|
+
return Uint8Array.from(binString, (c) => c.codePointAt(0) ?? 0);
|
|
2531
|
+
}
|
|
2532
|
+
}
|
|
2533
|
+
var HKDF_SHA256_MAX_LENGTH;
|
|
2534
|
+
var init_crypto = __esm({
|
|
2535
|
+
"libs/utils/src/crypto/index.ts"() {
|
|
2536
|
+
"use strict";
|
|
2537
|
+
init_runtime();
|
|
2538
|
+
init_jwt_alg();
|
|
2539
|
+
init_runtime();
|
|
2540
|
+
init_encrypted_blob();
|
|
2541
|
+
init_pkce2();
|
|
2542
|
+
init_secret_persistence();
|
|
2543
|
+
init_hmac_signing();
|
|
2544
|
+
init_key_persistence2();
|
|
2545
|
+
HKDF_SHA256_MAX_LENGTH = 255 * 32;
|
|
2546
|
+
}
|
|
2547
|
+
});
|
|
2548
|
+
var init_utils = __esm({
|
|
2549
|
+
"libs/utils/src/storage/utils/index.ts"() {
|
|
2550
|
+
"use strict";
|
|
2551
|
+
init_ttl();
|
|
2552
|
+
}
|
|
2553
|
+
});
|
|
2554
|
+
var redis_exports = {};
|
|
2555
|
+
__export(redis_exports, {
|
|
2556
|
+
RedisStorageAdapter: () => RedisStorageAdapter
|
|
2557
|
+
});
|
|
2558
|
+
function getRedisClass() {
|
|
2559
|
+
try {
|
|
2560
|
+
return __require2("ioredis").default || __require2("ioredis");
|
|
2561
|
+
} catch (error) {
|
|
2562
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
2563
|
+
if (msg.includes("Dynamic require") || msg.includes("require is not defined")) {
|
|
2564
|
+
throw new Error(
|
|
2565
|
+
`Failed to load ioredis: ${msg}. This typically happens with ESM bundlers (esbuild, Vite). Ensure your bundler externalizes ioredis or use CJS mode.`
|
|
2566
|
+
);
|
|
2567
|
+
}
|
|
2568
|
+
throw new Error("ioredis is required for Redis storage adapter. Install it with: npm install ioredis");
|
|
2569
|
+
}
|
|
2570
|
+
}
|
|
2571
|
+
var RedisStorageAdapter;
|
|
2572
|
+
var init_redis = __esm({
|
|
2573
|
+
"libs/utils/src/storage/adapters/redis.ts"() {
|
|
2574
|
+
"use strict";
|
|
2575
|
+
init_base();
|
|
2576
|
+
init_errors();
|
|
2577
|
+
init_utils();
|
|
2578
|
+
RedisStorageAdapter = class extends BaseStorageAdapter {
|
|
2579
|
+
backendName = "redis";
|
|
2580
|
+
client;
|
|
2581
|
+
subscriber;
|
|
2582
|
+
options;
|
|
2583
|
+
ownsClient;
|
|
2584
|
+
keyPrefix;
|
|
2585
|
+
subscriptionHandlers = /* @__PURE__ */ new Map();
|
|
2586
|
+
constructor(options = {}) {
|
|
2587
|
+
super();
|
|
2588
|
+
const hasClient = options.client !== void 0;
|
|
2589
|
+
const hasConfig = options.config !== void 0 || options.url !== void 0;
|
|
2590
|
+
if (hasClient && hasConfig) {
|
|
2591
|
+
throw new StorageConfigError("redis", 'Cannot specify both "client" and "config"/"url". Use one or the other.');
|
|
2592
|
+
}
|
|
2593
|
+
if (!hasClient && !hasConfig) {
|
|
2594
|
+
const envUrl = process.env["REDIS_URL"] || process.env["REDIS_HOST"];
|
|
2595
|
+
if (envUrl) {
|
|
2596
|
+
options = { ...options, url: envUrl };
|
|
2597
|
+
} else {
|
|
2598
|
+
throw new StorageConfigError(
|
|
2599
|
+
"redis",
|
|
2600
|
+
'Either "client", "config", "url", or REDIS_URL environment variable must be provided.'
|
|
2601
|
+
);
|
|
2602
|
+
}
|
|
2603
|
+
}
|
|
2604
|
+
this.options = options;
|
|
2605
|
+
this.ownsClient = !hasClient;
|
|
2606
|
+
this.keyPrefix = options.keyPrefix ?? "";
|
|
2607
|
+
}
|
|
2608
|
+
// ============================================
|
|
2609
|
+
// Connection Lifecycle
|
|
2610
|
+
// ============================================
|
|
2611
|
+
async connect() {
|
|
2612
|
+
if (this.connected) return;
|
|
2613
|
+
try {
|
|
2614
|
+
if (this.options.client) {
|
|
2615
|
+
this.client = this.options.client;
|
|
2616
|
+
} else {
|
|
2617
|
+
const RedisClass = getRedisClass();
|
|
2618
|
+
if (this.options.url) {
|
|
2619
|
+
this.client = new RedisClass(this.options.url, this.buildRedisOptions());
|
|
2620
|
+
} else {
|
|
2621
|
+
this.client = new RedisClass(this.buildRedisOptions());
|
|
2622
|
+
}
|
|
2623
|
+
}
|
|
2624
|
+
await this.client.ping();
|
|
2625
|
+
this.connected = true;
|
|
2626
|
+
} catch (e) {
|
|
2627
|
+
throw new StorageConnectionError("Failed to connect to Redis", e instanceof Error ? e : void 0, "redis");
|
|
2628
|
+
}
|
|
2629
|
+
}
|
|
2630
|
+
async disconnect() {
|
|
2631
|
+
if (!this.connected) return;
|
|
2632
|
+
if (this.subscriber) {
|
|
2633
|
+
await this.subscriber.quit();
|
|
2634
|
+
this.subscriber = void 0;
|
|
2635
|
+
}
|
|
2636
|
+
if (this.ownsClient && this.client) {
|
|
2637
|
+
await this.client.quit();
|
|
2638
|
+
}
|
|
2639
|
+
this.client = void 0;
|
|
2640
|
+
this.connected = false;
|
|
2641
|
+
this.subscriptionHandlers.clear();
|
|
2642
|
+
}
|
|
2643
|
+
async ping() {
|
|
2644
|
+
if (!this.client) return false;
|
|
2645
|
+
try {
|
|
2646
|
+
const result = await this.client.ping();
|
|
2647
|
+
return result === "PONG";
|
|
2648
|
+
} catch {
|
|
2649
|
+
return false;
|
|
2650
|
+
}
|
|
2651
|
+
}
|
|
2652
|
+
// ============================================
|
|
2653
|
+
// Connection Helpers
|
|
2654
|
+
// ============================================
|
|
2655
|
+
/**
|
|
2656
|
+
* Get the connected Redis client, throwing if not connected.
|
|
2657
|
+
*/
|
|
2658
|
+
getConnectedClient() {
|
|
2659
|
+
this.ensureConnected();
|
|
2660
|
+
if (!this.client) {
|
|
2661
|
+
throw new StorageConnectionError("Redis client not connected", void 0, "redis");
|
|
2662
|
+
}
|
|
2663
|
+
return this.client;
|
|
2664
|
+
}
|
|
2665
|
+
/**
|
|
2666
|
+
* Get the connected Redis subscriber, throwing if not created.
|
|
2667
|
+
*/
|
|
2668
|
+
getConnectedSubscriber() {
|
|
2669
|
+
if (!this.subscriber) {
|
|
2670
|
+
throw new StorageConnectionError("Redis subscriber not created", void 0, "redis");
|
|
2671
|
+
}
|
|
2672
|
+
return this.subscriber;
|
|
2673
|
+
}
|
|
2674
|
+
// ============================================
|
|
2675
|
+
// Core Operations
|
|
2676
|
+
// ============================================
|
|
2677
|
+
async get(key) {
|
|
2678
|
+
return this.getConnectedClient().get(this.prefixKey(key));
|
|
2679
|
+
}
|
|
2680
|
+
async doSet(key, value, options) {
|
|
2681
|
+
const client = this.getConnectedClient();
|
|
2682
|
+
const prefixedKey = this.prefixKey(key);
|
|
2683
|
+
if (options?.ttlSeconds) {
|
|
2684
|
+
if (options.ifNotExists) {
|
|
2685
|
+
await client.set(prefixedKey, value, "EX", options.ttlSeconds, "NX");
|
|
2686
|
+
} else if (options.ifExists) {
|
|
2687
|
+
await client.set(prefixedKey, value, "EX", options.ttlSeconds, "XX");
|
|
2688
|
+
} else {
|
|
2689
|
+
await client.set(prefixedKey, value, "EX", options.ttlSeconds);
|
|
2690
|
+
}
|
|
2691
|
+
} else if (options?.ifNotExists) {
|
|
2692
|
+
await client.set(prefixedKey, value, "NX");
|
|
2693
|
+
} else if (options?.ifExists) {
|
|
2694
|
+
await client.set(prefixedKey, value, "XX");
|
|
2695
|
+
} else {
|
|
2696
|
+
await client.set(prefixedKey, value);
|
|
2697
|
+
}
|
|
2698
|
+
}
|
|
2699
|
+
async delete(key) {
|
|
2700
|
+
const result = await this.getConnectedClient().del(this.prefixKey(key));
|
|
2701
|
+
return result > 0;
|
|
2702
|
+
}
|
|
2703
|
+
async exists(key) {
|
|
2704
|
+
const result = await this.getConnectedClient().exists(this.prefixKey(key));
|
|
2705
|
+
return result > 0;
|
|
2706
|
+
}
|
|
2707
|
+
// ============================================
|
|
2708
|
+
// Batch Operations (pipelined)
|
|
2709
|
+
// ============================================
|
|
2710
|
+
async mget(keys) {
|
|
2711
|
+
if (keys.length === 0) return [];
|
|
2712
|
+
const prefixedKeys = keys.map((k) => this.prefixKey(k));
|
|
2713
|
+
return this.getConnectedClient().mget(...prefixedKeys);
|
|
2714
|
+
}
|
|
2715
|
+
async mset(entries) {
|
|
2716
|
+
if (entries.length === 0) return;
|
|
2717
|
+
for (const entry of entries) {
|
|
2718
|
+
this.validateSetOptions(entry.options);
|
|
2719
|
+
}
|
|
2720
|
+
const pipeline = this.getConnectedClient().pipeline();
|
|
2721
|
+
for (const entry of entries) {
|
|
2722
|
+
const prefixedKey = this.prefixKey(entry.key);
|
|
2723
|
+
if (entry.options?.ttlSeconds) {
|
|
2724
|
+
if (entry.options.ifNotExists) {
|
|
2725
|
+
pipeline.set(prefixedKey, entry.value, "EX", entry.options.ttlSeconds, "NX");
|
|
2726
|
+
} else if (entry.options.ifExists) {
|
|
2727
|
+
pipeline.set(prefixedKey, entry.value, "EX", entry.options.ttlSeconds, "XX");
|
|
2728
|
+
} else {
|
|
2729
|
+
pipeline.set(prefixedKey, entry.value, "EX", entry.options.ttlSeconds);
|
|
2730
|
+
}
|
|
2731
|
+
} else if (entry.options?.ifNotExists) {
|
|
2732
|
+
pipeline.set(prefixedKey, entry.value, "NX");
|
|
2733
|
+
} else if (entry.options?.ifExists) {
|
|
2734
|
+
pipeline.set(prefixedKey, entry.value, "XX");
|
|
2735
|
+
} else {
|
|
2736
|
+
pipeline.set(prefixedKey, entry.value);
|
|
2737
|
+
}
|
|
2738
|
+
}
|
|
2739
|
+
await pipeline.exec();
|
|
2740
|
+
}
|
|
2741
|
+
async mdelete(keys) {
|
|
2742
|
+
if (keys.length === 0) return 0;
|
|
2743
|
+
const prefixedKeys = keys.map((k) => this.prefixKey(k));
|
|
2744
|
+
return this.getConnectedClient().del(...prefixedKeys);
|
|
2745
|
+
}
|
|
2746
|
+
// ============================================
|
|
2747
|
+
// TTL Operations
|
|
2748
|
+
// ============================================
|
|
2749
|
+
async expire(key, ttlSeconds) {
|
|
2750
|
+
validateTTL(ttlSeconds);
|
|
2751
|
+
const result = await this.getConnectedClient().expire(this.prefixKey(key), ttlSeconds);
|
|
2752
|
+
return result === 1;
|
|
2753
|
+
}
|
|
2754
|
+
async ttl(key) {
|
|
2755
|
+
const result = await this.getConnectedClient().ttl(this.prefixKey(key));
|
|
2756
|
+
if (result === -2) return null;
|
|
2757
|
+
return result;
|
|
2758
|
+
}
|
|
2759
|
+
// ============================================
|
|
2760
|
+
// Key Enumeration (SCAN)
|
|
2761
|
+
// ============================================
|
|
2762
|
+
async keys(pattern = "*") {
|
|
2763
|
+
const client = this.getConnectedClient();
|
|
2764
|
+
const prefixedPattern = this.prefixKey(pattern);
|
|
2765
|
+
const result = [];
|
|
2766
|
+
let cursor = "0";
|
|
2767
|
+
do {
|
|
2768
|
+
const [nextCursor, keys] = await client.scan(cursor, "MATCH", prefixedPattern, "COUNT", 100);
|
|
2769
|
+
cursor = nextCursor;
|
|
2770
|
+
for (const key of keys) {
|
|
2771
|
+
result.push(this.unprefixKey(key));
|
|
2772
|
+
}
|
|
2773
|
+
} while (cursor !== "0");
|
|
2774
|
+
return result;
|
|
2775
|
+
}
|
|
2776
|
+
// ============================================
|
|
2777
|
+
// Atomic Operations
|
|
2778
|
+
// ============================================
|
|
2779
|
+
async incr(key) {
|
|
2780
|
+
return this.getConnectedClient().incr(this.prefixKey(key));
|
|
2781
|
+
}
|
|
2782
|
+
async decr(key) {
|
|
2783
|
+
return this.getConnectedClient().decr(this.prefixKey(key));
|
|
2784
|
+
}
|
|
2785
|
+
async incrBy(key, amount) {
|
|
2786
|
+
return this.getConnectedClient().incrby(this.prefixKey(key), amount);
|
|
2787
|
+
}
|
|
2788
|
+
// ============================================
|
|
2789
|
+
// Pub/Sub
|
|
2790
|
+
// ============================================
|
|
2791
|
+
supportsPubSub() {
|
|
2792
|
+
return true;
|
|
2793
|
+
}
|
|
2794
|
+
async publish(channel, message) {
|
|
2795
|
+
const prefixedChannel = this.prefixKey(channel);
|
|
2796
|
+
return this.getConnectedClient().publish(prefixedChannel, message);
|
|
2797
|
+
}
|
|
2798
|
+
async subscribe(channel, handler) {
|
|
2799
|
+
this.ensureConnected();
|
|
2800
|
+
const prefixedChannel = this.prefixKey(channel);
|
|
2801
|
+
if (!this.subscriber) {
|
|
2802
|
+
await this.createSubscriber();
|
|
2803
|
+
}
|
|
2804
|
+
const subscriber = this.getConnectedSubscriber();
|
|
2805
|
+
if (!this.subscriptionHandlers.has(prefixedChannel)) {
|
|
2806
|
+
this.subscriptionHandlers.set(prefixedChannel, /* @__PURE__ */ new Set());
|
|
2807
|
+
await subscriber.subscribe(prefixedChannel);
|
|
2808
|
+
}
|
|
2809
|
+
const handlers = this.subscriptionHandlers.get(prefixedChannel);
|
|
2810
|
+
if (handlers) {
|
|
2811
|
+
handlers.add(handler);
|
|
2812
|
+
}
|
|
2813
|
+
return async () => {
|
|
2814
|
+
const handlers2 = this.subscriptionHandlers.get(prefixedChannel);
|
|
2815
|
+
if (handlers2) {
|
|
2816
|
+
handlers2.delete(handler);
|
|
2817
|
+
if (handlers2.size === 0) {
|
|
2818
|
+
this.subscriptionHandlers.delete(prefixedChannel);
|
|
2819
|
+
await this.subscriber?.unsubscribe(prefixedChannel);
|
|
2820
|
+
}
|
|
2821
|
+
}
|
|
2822
|
+
};
|
|
2823
|
+
}
|
|
2824
|
+
// ============================================
|
|
2825
|
+
// Internal Helpers
|
|
2826
|
+
// ============================================
|
|
2827
|
+
/**
|
|
2828
|
+
* Build Redis options from config.
|
|
2829
|
+
*/
|
|
2830
|
+
buildRedisOptions() {
|
|
2831
|
+
if (this.options.url) {
|
|
2832
|
+
return {
|
|
2833
|
+
lazyConnect: false,
|
|
2834
|
+
maxRetriesPerRequest: 3
|
|
2835
|
+
};
|
|
2836
|
+
}
|
|
2837
|
+
const config = this.options.config;
|
|
2838
|
+
if (!config) {
|
|
2839
|
+
throw new StorageConfigError("redis", "Redis config is required when URL is not provided");
|
|
2840
|
+
}
|
|
2841
|
+
return {
|
|
2842
|
+
host: config.host,
|
|
2843
|
+
port: config.port ?? 6379,
|
|
2844
|
+
password: config.password,
|
|
2845
|
+
db: config.db ?? 0,
|
|
2846
|
+
tls: config.tls ? {} : void 0,
|
|
2847
|
+
lazyConnect: false,
|
|
2848
|
+
maxRetriesPerRequest: 3
|
|
2849
|
+
};
|
|
2850
|
+
}
|
|
2851
|
+
/**
|
|
2852
|
+
* Create subscriber connection.
|
|
2853
|
+
*/
|
|
2854
|
+
async createSubscriber() {
|
|
2855
|
+
const RedisClass = getRedisClass();
|
|
2856
|
+
let subscriber;
|
|
2857
|
+
if (this.options.url) {
|
|
2858
|
+
subscriber = new RedisClass(this.options.url);
|
|
2859
|
+
} else if (this.options.config) {
|
|
2860
|
+
subscriber = new RedisClass(this.buildRedisOptions());
|
|
2861
|
+
} else if (this.options.client) {
|
|
2862
|
+
subscriber = this.options.client.duplicate();
|
|
2863
|
+
} else {
|
|
2864
|
+
throw new StorageConfigError("redis", "Cannot create subscriber without url, config, or client");
|
|
2865
|
+
}
|
|
2866
|
+
subscriber.on("message", (channel, message) => {
|
|
2867
|
+
const handlers = this.subscriptionHandlers.get(channel);
|
|
2868
|
+
if (handlers) {
|
|
2869
|
+
const unprefixedChannel = this.unprefixKey(channel);
|
|
2870
|
+
for (const handler of handlers) {
|
|
2871
|
+
try {
|
|
2872
|
+
handler(message, unprefixedChannel);
|
|
2873
|
+
} catch {
|
|
2874
|
+
}
|
|
2875
|
+
}
|
|
2876
|
+
}
|
|
2877
|
+
});
|
|
2878
|
+
this.subscriber = subscriber;
|
|
2879
|
+
}
|
|
2880
|
+
/**
|
|
2881
|
+
* Add prefix to a key.
|
|
2882
|
+
*/
|
|
2883
|
+
prefixKey(key) {
|
|
2884
|
+
return this.keyPrefix + key;
|
|
2885
|
+
}
|
|
2886
|
+
/**
|
|
2887
|
+
* Remove prefix from a key.
|
|
2888
|
+
*/
|
|
2889
|
+
unprefixKey(key) {
|
|
2890
|
+
if (this.keyPrefix && key.startsWith(this.keyPrefix)) {
|
|
2891
|
+
return key.slice(this.keyPrefix.length);
|
|
2892
|
+
}
|
|
2893
|
+
return key;
|
|
2894
|
+
}
|
|
2895
|
+
/**
|
|
2896
|
+
* Get the underlying Redis client (for advanced use).
|
|
2897
|
+
*/
|
|
2898
|
+
getClient() {
|
|
2899
|
+
return this.client;
|
|
2900
|
+
}
|
|
2901
|
+
};
|
|
51
2902
|
}
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
2903
|
+
});
|
|
2904
|
+
var vercel_kv_exports = {};
|
|
2905
|
+
__export(vercel_kv_exports, {
|
|
2906
|
+
VercelKvStorageAdapter: () => VercelKvStorageAdapter
|
|
2907
|
+
});
|
|
2908
|
+
function getVercelKv() {
|
|
2909
|
+
try {
|
|
2910
|
+
return __require2("@vercel/kv");
|
|
2911
|
+
} catch {
|
|
2912
|
+
throw new Error("@vercel/kv is required for Vercel KV storage adapter. Install it with: npm install @vercel/kv");
|
|
60
2913
|
}
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
2914
|
+
}
|
|
2915
|
+
var VercelKvStorageAdapter;
|
|
2916
|
+
var init_vercel_kv = __esm({
|
|
2917
|
+
"libs/utils/src/storage/adapters/vercel-kv.ts"() {
|
|
2918
|
+
"use strict";
|
|
2919
|
+
init_base();
|
|
2920
|
+
init_errors();
|
|
2921
|
+
init_ttl();
|
|
2922
|
+
VercelKvStorageAdapter = class extends BaseStorageAdapter {
|
|
2923
|
+
backendName = "vercel-kv";
|
|
2924
|
+
client;
|
|
2925
|
+
options;
|
|
2926
|
+
keyPrefix;
|
|
2927
|
+
constructor(options = {}) {
|
|
2928
|
+
super();
|
|
2929
|
+
const url = options.url ?? process.env["KV_REST_API_URL"];
|
|
2930
|
+
const token = options.token ?? process.env["KV_REST_API_TOKEN"];
|
|
2931
|
+
if (!url || !token) {
|
|
2932
|
+
throw new StorageConfigError(
|
|
2933
|
+
"vercel-kv",
|
|
2934
|
+
"KV_REST_API_URL and KV_REST_API_TOKEN must be provided via options or environment variables."
|
|
2935
|
+
);
|
|
2936
|
+
}
|
|
2937
|
+
this.options = { ...options, url, token };
|
|
2938
|
+
this.keyPrefix = options.keyPrefix ?? "";
|
|
2939
|
+
}
|
|
2940
|
+
// ============================================
|
|
2941
|
+
// Connection Lifecycle
|
|
2942
|
+
// ============================================
|
|
2943
|
+
async connect() {
|
|
2944
|
+
if (this.connected) return;
|
|
2945
|
+
try {
|
|
2946
|
+
const { createClient, kv } = getVercelKv();
|
|
2947
|
+
if (this.options.url === process.env["KV_REST_API_URL"]) {
|
|
2948
|
+
this.client = kv;
|
|
2949
|
+
} else {
|
|
2950
|
+
const url = this.options.url;
|
|
2951
|
+
const token = this.options.token;
|
|
2952
|
+
if (!url || !token) {
|
|
2953
|
+
throw new StorageConfigError("vercel-kv", "URL and token are required");
|
|
2954
|
+
}
|
|
2955
|
+
this.client = createClient({ url, token });
|
|
2956
|
+
}
|
|
2957
|
+
await this.client.exists("__healthcheck__");
|
|
2958
|
+
this.connected = true;
|
|
2959
|
+
} catch (e) {
|
|
2960
|
+
throw new StorageConnectionError(
|
|
2961
|
+
"Failed to connect to Vercel KV",
|
|
2962
|
+
e instanceof Error ? e : void 0,
|
|
2963
|
+
"vercel-kv"
|
|
2964
|
+
);
|
|
2965
|
+
}
|
|
2966
|
+
}
|
|
2967
|
+
async disconnect() {
|
|
2968
|
+
this.client = void 0;
|
|
2969
|
+
this.connected = false;
|
|
2970
|
+
}
|
|
2971
|
+
async ping() {
|
|
2972
|
+
if (!this.client) return false;
|
|
2973
|
+
try {
|
|
2974
|
+
await this.client.exists("__healthcheck__");
|
|
2975
|
+
return true;
|
|
2976
|
+
} catch {
|
|
2977
|
+
return false;
|
|
2978
|
+
}
|
|
2979
|
+
}
|
|
2980
|
+
// ============================================
|
|
2981
|
+
// Connection Helpers
|
|
2982
|
+
// ============================================
|
|
2983
|
+
/**
|
|
2984
|
+
* Get the connected Vercel KV client, throwing if not connected.
|
|
2985
|
+
*/
|
|
2986
|
+
getConnectedClient() {
|
|
2987
|
+
this.ensureConnected();
|
|
2988
|
+
if (!this.client) {
|
|
2989
|
+
throw new StorageConnectionError("Vercel KV client not connected", void 0, "vercel-kv");
|
|
2990
|
+
}
|
|
2991
|
+
return this.client;
|
|
2992
|
+
}
|
|
2993
|
+
// ============================================
|
|
2994
|
+
// Core Operations
|
|
2995
|
+
// ============================================
|
|
2996
|
+
async get(key) {
|
|
2997
|
+
const result = await this.getConnectedClient().get(this.prefixKey(key));
|
|
2998
|
+
return result;
|
|
2999
|
+
}
|
|
3000
|
+
async doSet(key, value, options) {
|
|
3001
|
+
const client = this.getConnectedClient();
|
|
3002
|
+
const prefixedKey = this.prefixKey(key);
|
|
3003
|
+
const setOptions = {};
|
|
3004
|
+
if (options?.ttlSeconds) {
|
|
3005
|
+
setOptions.ex = options.ttlSeconds;
|
|
3006
|
+
}
|
|
3007
|
+
if (options?.ifNotExists) {
|
|
3008
|
+
setOptions.nx = true;
|
|
3009
|
+
} else if (options?.ifExists) {
|
|
3010
|
+
setOptions.xx = true;
|
|
3011
|
+
}
|
|
3012
|
+
await client.set(prefixedKey, value, Object.keys(setOptions).length > 0 ? setOptions : void 0);
|
|
3013
|
+
}
|
|
3014
|
+
async delete(key) {
|
|
3015
|
+
const result = await this.getConnectedClient().del(this.prefixKey(key));
|
|
3016
|
+
return result > 0;
|
|
3017
|
+
}
|
|
3018
|
+
async exists(key) {
|
|
3019
|
+
const result = await this.getConnectedClient().exists(this.prefixKey(key));
|
|
3020
|
+
return result > 0;
|
|
3021
|
+
}
|
|
3022
|
+
// ============================================
|
|
3023
|
+
// Batch Operations
|
|
3024
|
+
// ============================================
|
|
3025
|
+
async mget(keys) {
|
|
3026
|
+
if (keys.length === 0) return [];
|
|
3027
|
+
const prefixedKeys = keys.map((k) => this.prefixKey(k));
|
|
3028
|
+
return this.getConnectedClient().mget(...prefixedKeys);
|
|
3029
|
+
}
|
|
3030
|
+
async mdelete(keys) {
|
|
3031
|
+
if (keys.length === 0) return 0;
|
|
3032
|
+
const prefixedKeys = keys.map((k) => this.prefixKey(k));
|
|
3033
|
+
return this.getConnectedClient().del(...prefixedKeys);
|
|
3034
|
+
}
|
|
3035
|
+
// ============================================
|
|
3036
|
+
// TTL Operations
|
|
3037
|
+
// ============================================
|
|
3038
|
+
async expire(key, ttlSeconds) {
|
|
3039
|
+
validateTTL(ttlSeconds);
|
|
3040
|
+
const result = await this.getConnectedClient().expire(this.prefixKey(key), ttlSeconds);
|
|
3041
|
+
return result === 1;
|
|
3042
|
+
}
|
|
3043
|
+
async ttl(key) {
|
|
3044
|
+
const result = await this.getConnectedClient().ttl(this.prefixKey(key));
|
|
3045
|
+
if (result === -2) return null;
|
|
3046
|
+
return result;
|
|
3047
|
+
}
|
|
3048
|
+
// ============================================
|
|
3049
|
+
// Key Enumeration
|
|
3050
|
+
// ============================================
|
|
3051
|
+
async keys(pattern = "*") {
|
|
3052
|
+
const client = this.getConnectedClient();
|
|
3053
|
+
const prefixedPattern = this.prefixKey(pattern);
|
|
3054
|
+
try {
|
|
3055
|
+
const result = [];
|
|
3056
|
+
let cursor = 0;
|
|
3057
|
+
do {
|
|
3058
|
+
const [nextCursor, keys] = await client.scan(cursor, {
|
|
3059
|
+
match: prefixedPattern,
|
|
3060
|
+
count: 100
|
|
3061
|
+
});
|
|
3062
|
+
const parsedCursor = typeof nextCursor === "string" ? parseInt(nextCursor, 10) : nextCursor;
|
|
3063
|
+
cursor = Number.isNaN(parsedCursor) ? 0 : parsedCursor;
|
|
3064
|
+
for (const key of keys) {
|
|
3065
|
+
result.push(this.unprefixKey(key));
|
|
3066
|
+
}
|
|
3067
|
+
} while (cursor !== 0);
|
|
3068
|
+
return result;
|
|
3069
|
+
} catch {
|
|
3070
|
+
const allKeys = await client.keys(prefixedPattern);
|
|
3071
|
+
return allKeys.map((k) => this.unprefixKey(k));
|
|
3072
|
+
}
|
|
3073
|
+
}
|
|
3074
|
+
// ============================================
|
|
3075
|
+
// Atomic Operations
|
|
3076
|
+
// ============================================
|
|
3077
|
+
async incr(key) {
|
|
3078
|
+
return this.getConnectedClient().incr(this.prefixKey(key));
|
|
3079
|
+
}
|
|
3080
|
+
async decr(key) {
|
|
3081
|
+
return this.getConnectedClient().decr(this.prefixKey(key));
|
|
3082
|
+
}
|
|
3083
|
+
async incrBy(key, amount) {
|
|
3084
|
+
return this.getConnectedClient().incrby(this.prefixKey(key), amount);
|
|
3085
|
+
}
|
|
3086
|
+
// ============================================
|
|
3087
|
+
// Pub/Sub (NOT SUPPORTED)
|
|
3088
|
+
// ============================================
|
|
3089
|
+
supportsPubSub() {
|
|
3090
|
+
return false;
|
|
3091
|
+
}
|
|
3092
|
+
getPubSubSuggestion() {
|
|
3093
|
+
return "Vercel KV is REST-based and does not support pub/sub. Use Upstash adapter for pub/sub support.";
|
|
3094
|
+
}
|
|
3095
|
+
// ============================================
|
|
3096
|
+
// Internal Helpers
|
|
3097
|
+
// ============================================
|
|
3098
|
+
/**
|
|
3099
|
+
* Add prefix to a key.
|
|
3100
|
+
*/
|
|
3101
|
+
prefixKey(key) {
|
|
3102
|
+
return this.keyPrefix + key;
|
|
3103
|
+
}
|
|
3104
|
+
/**
|
|
3105
|
+
* Remove prefix from a key.
|
|
3106
|
+
*/
|
|
3107
|
+
unprefixKey(key) {
|
|
3108
|
+
if (this.keyPrefix && key.startsWith(this.keyPrefix)) {
|
|
3109
|
+
return key.slice(this.keyPrefix.length);
|
|
3110
|
+
}
|
|
3111
|
+
return key;
|
|
3112
|
+
}
|
|
3113
|
+
};
|
|
70
3114
|
}
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
3115
|
+
});
|
|
3116
|
+
var upstash_exports = {};
|
|
3117
|
+
__export(upstash_exports, {
|
|
3118
|
+
UpstashStorageAdapter: () => UpstashStorageAdapter
|
|
3119
|
+
});
|
|
3120
|
+
function getUpstashRedis() {
|
|
3121
|
+
try {
|
|
3122
|
+
return __require2("@upstash/redis");
|
|
3123
|
+
} catch {
|
|
3124
|
+
throw new Error(
|
|
3125
|
+
"@upstash/redis is required for Upstash storage adapter. Install it with: npm install @upstash/redis"
|
|
3126
|
+
);
|
|
74
3127
|
}
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
3128
|
+
}
|
|
3129
|
+
var PUBSUB_POLL_INTERVAL_MS;
|
|
3130
|
+
var UpstashStorageAdapter;
|
|
3131
|
+
var init_upstash = __esm({
|
|
3132
|
+
"libs/utils/src/storage/adapters/upstash.ts"() {
|
|
3133
|
+
"use strict";
|
|
3134
|
+
init_base();
|
|
3135
|
+
init_errors();
|
|
3136
|
+
init_ttl();
|
|
3137
|
+
PUBSUB_POLL_INTERVAL_MS = 100;
|
|
3138
|
+
UpstashStorageAdapter = class extends BaseStorageAdapter {
|
|
3139
|
+
backendName = "upstash";
|
|
3140
|
+
client;
|
|
3141
|
+
options;
|
|
3142
|
+
keyPrefix;
|
|
3143
|
+
pubSubEnabled;
|
|
3144
|
+
// Pub/sub state
|
|
3145
|
+
subscriptionHandlers = /* @__PURE__ */ new Map();
|
|
3146
|
+
pollingIntervals = /* @__PURE__ */ new Map();
|
|
3147
|
+
constructor(options = {}) {
|
|
3148
|
+
super();
|
|
3149
|
+
const url = options.url ?? process.env["UPSTASH_REDIS_REST_URL"];
|
|
3150
|
+
const token = options.token ?? process.env["UPSTASH_REDIS_REST_TOKEN"];
|
|
3151
|
+
if (!url || !token) {
|
|
3152
|
+
throw new StorageConfigError(
|
|
3153
|
+
"upstash",
|
|
3154
|
+
"UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN must be provided via options or environment variables."
|
|
3155
|
+
);
|
|
3156
|
+
}
|
|
3157
|
+
this.options = { ...options, url, token };
|
|
3158
|
+
this.keyPrefix = options.keyPrefix ?? "";
|
|
3159
|
+
this.pubSubEnabled = options.enablePubSub ?? false;
|
|
3160
|
+
}
|
|
3161
|
+
// ============================================
|
|
3162
|
+
// Connection Lifecycle
|
|
3163
|
+
// ============================================
|
|
3164
|
+
async connect() {
|
|
3165
|
+
if (this.connected) return;
|
|
3166
|
+
try {
|
|
3167
|
+
const { Redis: Redis2 } = getUpstashRedis();
|
|
3168
|
+
const url = this.options.url;
|
|
3169
|
+
const token = this.options.token;
|
|
3170
|
+
if (!url || !token) {
|
|
3171
|
+
throw new StorageConfigError("upstash", "URL and token are required");
|
|
3172
|
+
}
|
|
3173
|
+
this.client = new Redis2({ url, token });
|
|
3174
|
+
await this.client.exists("__healthcheck__");
|
|
3175
|
+
this.connected = true;
|
|
3176
|
+
} catch (e) {
|
|
3177
|
+
throw new StorageConnectionError(
|
|
3178
|
+
"Failed to connect to Upstash Redis",
|
|
3179
|
+
e instanceof Error ? e : void 0,
|
|
3180
|
+
"upstash"
|
|
3181
|
+
);
|
|
3182
|
+
}
|
|
3183
|
+
}
|
|
3184
|
+
async disconnect() {
|
|
3185
|
+
if (!this.connected) return;
|
|
3186
|
+
for (const interval of this.pollingIntervals.values()) {
|
|
3187
|
+
clearInterval(interval);
|
|
3188
|
+
}
|
|
3189
|
+
this.pollingIntervals.clear();
|
|
3190
|
+
this.subscriptionHandlers.clear();
|
|
3191
|
+
this.client = void 0;
|
|
3192
|
+
this.connected = false;
|
|
3193
|
+
}
|
|
3194
|
+
async ping() {
|
|
3195
|
+
if (!this.client) return false;
|
|
3196
|
+
try {
|
|
3197
|
+
await this.client.exists("__healthcheck__");
|
|
3198
|
+
return true;
|
|
3199
|
+
} catch {
|
|
3200
|
+
return false;
|
|
3201
|
+
}
|
|
3202
|
+
}
|
|
3203
|
+
// ============================================
|
|
3204
|
+
// Connection Helpers
|
|
3205
|
+
// ============================================
|
|
3206
|
+
/**
|
|
3207
|
+
* Get the connected Upstash client, throwing if not connected.
|
|
3208
|
+
*/
|
|
3209
|
+
getConnectedClient() {
|
|
3210
|
+
this.ensureConnected();
|
|
3211
|
+
if (!this.client) {
|
|
3212
|
+
throw new StorageConnectionError("Upstash client not connected", void 0, "upstash");
|
|
3213
|
+
}
|
|
3214
|
+
return this.client;
|
|
3215
|
+
}
|
|
3216
|
+
// ============================================
|
|
3217
|
+
// Core Operations
|
|
3218
|
+
// ============================================
|
|
3219
|
+
async get(key) {
|
|
3220
|
+
const result = await this.getConnectedClient().get(this.prefixKey(key));
|
|
3221
|
+
return result;
|
|
3222
|
+
}
|
|
3223
|
+
async doSet(key, value, options) {
|
|
3224
|
+
const client = this.getConnectedClient();
|
|
3225
|
+
const prefixedKey = this.prefixKey(key);
|
|
3226
|
+
const setOptions = {};
|
|
3227
|
+
if (options?.ttlSeconds) {
|
|
3228
|
+
setOptions.ex = options.ttlSeconds;
|
|
3229
|
+
}
|
|
3230
|
+
if (options?.ifNotExists) {
|
|
3231
|
+
setOptions.nx = true;
|
|
3232
|
+
} else if (options?.ifExists) {
|
|
3233
|
+
setOptions.xx = true;
|
|
3234
|
+
}
|
|
3235
|
+
await client.set(prefixedKey, value, Object.keys(setOptions).length > 0 ? setOptions : void 0);
|
|
3236
|
+
}
|
|
3237
|
+
async delete(key) {
|
|
3238
|
+
const result = await this.getConnectedClient().del(this.prefixKey(key));
|
|
3239
|
+
return result > 0;
|
|
3240
|
+
}
|
|
3241
|
+
async exists(key) {
|
|
3242
|
+
const result = await this.getConnectedClient().exists(this.prefixKey(key));
|
|
3243
|
+
return result > 0;
|
|
3244
|
+
}
|
|
3245
|
+
// ============================================
|
|
3246
|
+
// Batch Operations
|
|
3247
|
+
// ============================================
|
|
3248
|
+
async mget(keys) {
|
|
3249
|
+
if (keys.length === 0) return [];
|
|
3250
|
+
const prefixedKeys = keys.map((k) => this.prefixKey(k));
|
|
3251
|
+
return this.getConnectedClient().mget(...prefixedKeys);
|
|
3252
|
+
}
|
|
3253
|
+
async mdelete(keys) {
|
|
3254
|
+
if (keys.length === 0) return 0;
|
|
3255
|
+
const prefixedKeys = keys.map((k) => this.prefixKey(k));
|
|
3256
|
+
return this.getConnectedClient().del(...prefixedKeys);
|
|
3257
|
+
}
|
|
3258
|
+
// ============================================
|
|
3259
|
+
// TTL Operations
|
|
3260
|
+
// ============================================
|
|
3261
|
+
async expire(key, ttlSeconds) {
|
|
3262
|
+
validateTTL(ttlSeconds);
|
|
3263
|
+
const result = await this.getConnectedClient().expire(this.prefixKey(key), ttlSeconds);
|
|
3264
|
+
return result === 1;
|
|
3265
|
+
}
|
|
3266
|
+
async ttl(key) {
|
|
3267
|
+
const result = await this.getConnectedClient().ttl(this.prefixKey(key));
|
|
3268
|
+
if (result === -2) return null;
|
|
3269
|
+
return result;
|
|
3270
|
+
}
|
|
3271
|
+
// ============================================
|
|
3272
|
+
// Key Enumeration
|
|
3273
|
+
// ============================================
|
|
3274
|
+
async keys(pattern = "*") {
|
|
3275
|
+
const client = this.getConnectedClient();
|
|
3276
|
+
const prefixedPattern = this.prefixKey(pattern);
|
|
3277
|
+
const result = [];
|
|
3278
|
+
let cursor = 0;
|
|
3279
|
+
do {
|
|
3280
|
+
const [nextCursor, keys] = await client.scan(cursor, {
|
|
3281
|
+
match: prefixedPattern,
|
|
3282
|
+
count: 100
|
|
3283
|
+
});
|
|
3284
|
+
const parsedCursor = typeof nextCursor === "string" ? parseInt(nextCursor, 10) : nextCursor;
|
|
3285
|
+
cursor = Number.isNaN(parsedCursor) ? 0 : parsedCursor;
|
|
3286
|
+
for (const key of keys) {
|
|
3287
|
+
result.push(this.unprefixKey(key));
|
|
3288
|
+
}
|
|
3289
|
+
} while (cursor !== 0);
|
|
3290
|
+
return result;
|
|
3291
|
+
}
|
|
3292
|
+
// ============================================
|
|
3293
|
+
// Atomic Operations
|
|
3294
|
+
// ============================================
|
|
3295
|
+
async incr(key) {
|
|
3296
|
+
return this.getConnectedClient().incr(this.prefixKey(key));
|
|
3297
|
+
}
|
|
3298
|
+
async decr(key) {
|
|
3299
|
+
return this.getConnectedClient().decr(this.prefixKey(key));
|
|
3300
|
+
}
|
|
3301
|
+
async incrBy(key, amount) {
|
|
3302
|
+
return this.getConnectedClient().incrby(this.prefixKey(key), amount);
|
|
3303
|
+
}
|
|
3304
|
+
// ============================================
|
|
3305
|
+
// Pub/Sub (via list-based polling)
|
|
3306
|
+
// ============================================
|
|
3307
|
+
supportsPubSub() {
|
|
3308
|
+
return this.pubSubEnabled;
|
|
3309
|
+
}
|
|
3310
|
+
async publish(channel, message) {
|
|
3311
|
+
if (!this.pubSubEnabled) {
|
|
3312
|
+
return super.publish(channel, message);
|
|
3313
|
+
}
|
|
3314
|
+
const prefixedChannel = this.prefixKey(`__pubsub__:${channel}`);
|
|
3315
|
+
const listKey = `${prefixedChannel}:queue`;
|
|
3316
|
+
await this.getConnectedClient().lpush(listKey, message);
|
|
3317
|
+
return 1;
|
|
3318
|
+
}
|
|
3319
|
+
async subscribe(channel, handler) {
|
|
3320
|
+
const client = this.getConnectedClient();
|
|
3321
|
+
if (!this.pubSubEnabled) {
|
|
3322
|
+
return super.subscribe(channel, handler);
|
|
3323
|
+
}
|
|
3324
|
+
const prefixedChannel = this.prefixKey(`__pubsub__:${channel}`);
|
|
3325
|
+
if (!this.subscriptionHandlers.has(prefixedChannel)) {
|
|
3326
|
+
this.subscriptionHandlers.set(prefixedChannel, /* @__PURE__ */ new Set());
|
|
3327
|
+
const listKey = `${prefixedChannel}:queue`;
|
|
3328
|
+
const interval = setInterval(async () => {
|
|
3329
|
+
try {
|
|
3330
|
+
const message = await client.rpop(listKey);
|
|
3331
|
+
if (message) {
|
|
3332
|
+
const handlers2 = this.subscriptionHandlers.get(prefixedChannel);
|
|
3333
|
+
if (handlers2) {
|
|
3334
|
+
for (const h of handlers2) {
|
|
3335
|
+
try {
|
|
3336
|
+
h(message, channel);
|
|
3337
|
+
} catch {
|
|
3338
|
+
}
|
|
3339
|
+
}
|
|
3340
|
+
}
|
|
3341
|
+
}
|
|
3342
|
+
} catch {
|
|
3343
|
+
}
|
|
3344
|
+
}, PUBSUB_POLL_INTERVAL_MS);
|
|
3345
|
+
if (interval.unref) {
|
|
3346
|
+
interval.unref();
|
|
3347
|
+
}
|
|
3348
|
+
this.pollingIntervals.set(prefixedChannel, interval);
|
|
3349
|
+
}
|
|
3350
|
+
const handlers = this.subscriptionHandlers.get(prefixedChannel);
|
|
3351
|
+
if (handlers) {
|
|
3352
|
+
handlers.add(handler);
|
|
3353
|
+
}
|
|
3354
|
+
return async () => {
|
|
3355
|
+
const handlers2 = this.subscriptionHandlers.get(prefixedChannel);
|
|
3356
|
+
if (handlers2) {
|
|
3357
|
+
handlers2.delete(handler);
|
|
3358
|
+
if (handlers2.size === 0) {
|
|
3359
|
+
this.subscriptionHandlers.delete(prefixedChannel);
|
|
3360
|
+
const interval = this.pollingIntervals.get(prefixedChannel);
|
|
3361
|
+
if (interval) {
|
|
3362
|
+
clearInterval(interval);
|
|
3363
|
+
this.pollingIntervals.delete(prefixedChannel);
|
|
3364
|
+
}
|
|
3365
|
+
}
|
|
3366
|
+
}
|
|
3367
|
+
};
|
|
3368
|
+
}
|
|
3369
|
+
/**
|
|
3370
|
+
* Publish using list-based approach (for polling subscribers).
|
|
3371
|
+
* This is an alternative to native PUBLISH when subscribers are polling.
|
|
3372
|
+
*/
|
|
3373
|
+
async publishToQueue(channel, message) {
|
|
3374
|
+
const prefixedChannel = this.prefixKey(`__pubsub__:${channel}`);
|
|
3375
|
+
const listKey = `${prefixedChannel}:queue`;
|
|
3376
|
+
await this.getConnectedClient().lpush(listKey, message);
|
|
3377
|
+
}
|
|
3378
|
+
getPubSubSuggestion() {
|
|
3379
|
+
return "Enable pub/sub by setting enablePubSub: true in the adapter options.";
|
|
3380
|
+
}
|
|
3381
|
+
// ============================================
|
|
3382
|
+
// Internal Helpers
|
|
3383
|
+
// ============================================
|
|
3384
|
+
/**
|
|
3385
|
+
* Add prefix to a key.
|
|
3386
|
+
*/
|
|
3387
|
+
prefixKey(key) {
|
|
3388
|
+
return this.keyPrefix + key;
|
|
3389
|
+
}
|
|
3390
|
+
/**
|
|
3391
|
+
* Remove prefix from a key.
|
|
3392
|
+
*/
|
|
3393
|
+
unprefixKey(key) {
|
|
3394
|
+
if (this.keyPrefix && key.startsWith(this.keyPrefix)) {
|
|
3395
|
+
return key.slice(this.keyPrefix.length);
|
|
3396
|
+
}
|
|
3397
|
+
return key;
|
|
3398
|
+
}
|
|
3399
|
+
};
|
|
78
3400
|
}
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
3401
|
+
});
|
|
3402
|
+
var cloudflare_kv_exports = {};
|
|
3403
|
+
__export(cloudflare_kv_exports, {
|
|
3404
|
+
CloudflareKvStorageAdapter: () => CloudflareKvStorageAdapter
|
|
3405
|
+
});
|
|
3406
|
+
function literalPrefix(pattern) {
|
|
3407
|
+
const star = pattern.indexOf("*");
|
|
3408
|
+
const q = pattern.indexOf("?");
|
|
3409
|
+
const idx = star === -1 ? q : q === -1 ? star : Math.min(star, q);
|
|
3410
|
+
return idx === -1 ? pattern : pattern.slice(0, idx);
|
|
3411
|
+
}
|
|
3412
|
+
var CF_KV_MIN_TTL_SECONDS;
|
|
3413
|
+
var CloudflareKvStorageAdapter;
|
|
3414
|
+
var init_cloudflare_kv = __esm({
|
|
3415
|
+
"libs/utils/src/storage/adapters/cloudflare-kv.ts"() {
|
|
3416
|
+
"use strict";
|
|
3417
|
+
init_errors();
|
|
3418
|
+
init_pattern();
|
|
3419
|
+
init_ttl();
|
|
3420
|
+
init_base();
|
|
3421
|
+
CF_KV_MIN_TTL_SECONDS = 60;
|
|
3422
|
+
CloudflareKvStorageAdapter = class extends BaseStorageAdapter {
|
|
3423
|
+
backendName = "cloudflare-kv";
|
|
3424
|
+
kv;
|
|
3425
|
+
keyPrefix;
|
|
3426
|
+
constructor(options) {
|
|
3427
|
+
super();
|
|
3428
|
+
if (!options?.namespace) {
|
|
3429
|
+
throw new Error("CloudflareKvStorageAdapter: a bound KV `namespace` is required (resolve it from the Worker `env`).");
|
|
3430
|
+
}
|
|
3431
|
+
this.kv = options.namespace;
|
|
3432
|
+
this.keyPrefix = options.keyPrefix ?? "";
|
|
3433
|
+
}
|
|
3434
|
+
// ── Lifecycle ──────────────────────────────────────────────────────────
|
|
3435
|
+
// A KV binding is always available; "connection" is just a readiness flag.
|
|
3436
|
+
async connect() {
|
|
3437
|
+
this.connected = true;
|
|
3438
|
+
}
|
|
3439
|
+
async disconnect() {
|
|
3440
|
+
this.connected = false;
|
|
3441
|
+
}
|
|
3442
|
+
async ping() {
|
|
3443
|
+
if (!this.connected) return false;
|
|
3444
|
+
try {
|
|
3445
|
+
await this.kv.list({ limit: 1 });
|
|
3446
|
+
return true;
|
|
3447
|
+
} catch {
|
|
3448
|
+
return false;
|
|
3449
|
+
}
|
|
3450
|
+
}
|
|
3451
|
+
// ── Core ───────────────────────────────────────────────────────────────
|
|
3452
|
+
async get(key) {
|
|
3453
|
+
this.ensureConnected();
|
|
3454
|
+
return this.kv.get(this.prefixKey(key), "text");
|
|
3455
|
+
}
|
|
3456
|
+
async doSet(key, value, options) {
|
|
3457
|
+
if (options?.ifNotExists || options?.ifExists) {
|
|
3458
|
+
throw new StorageNotSupportedError(
|
|
3459
|
+
"conditional set (ifNotExists/ifExists)",
|
|
3460
|
+
this.backendName,
|
|
3461
|
+
"Cloudflare KV has no compare-and-set; use a Durable Object for atomic conditional writes."
|
|
3462
|
+
);
|
|
3463
|
+
}
|
|
3464
|
+
const putOptions = options?.ttlSeconds !== void 0 ? { expirationTtl: this.toExpirationTtl(options.ttlSeconds, key) } : void 0;
|
|
3465
|
+
await this.kv.put(this.prefixKey(key), value, putOptions);
|
|
3466
|
+
}
|
|
3467
|
+
async delete(key) {
|
|
3468
|
+
this.ensureConnected();
|
|
3469
|
+
const existed = await this.exists(key);
|
|
3470
|
+
await this.kv.delete(this.prefixKey(key));
|
|
3471
|
+
return existed;
|
|
3472
|
+
}
|
|
3473
|
+
async exists(key) {
|
|
3474
|
+
this.ensureConnected();
|
|
3475
|
+
return await this.kv.get(this.prefixKey(key), "text") !== null;
|
|
3476
|
+
}
|
|
3477
|
+
// ── TTL ────────────────────────────────────────────────────────────────
|
|
3478
|
+
async expire(key, ttlSeconds) {
|
|
3479
|
+
this.ensureConnected();
|
|
3480
|
+
const ttl = this.toExpirationTtl(ttlSeconds, key);
|
|
3481
|
+
const value = await this.kv.get(this.prefixKey(key), "text");
|
|
3482
|
+
if (value === null) return false;
|
|
3483
|
+
await this.kv.put(this.prefixKey(key), value, { expirationTtl: ttl });
|
|
3484
|
+
return true;
|
|
3485
|
+
}
|
|
3486
|
+
async ttl(_key) {
|
|
3487
|
+
throw new StorageNotSupportedError(
|
|
3488
|
+
"ttl",
|
|
3489
|
+
this.backendName,
|
|
3490
|
+
"Cloudflare KV does not expose a key's remaining TTL. Track expiry alongside the value if you need it."
|
|
3491
|
+
);
|
|
3492
|
+
}
|
|
3493
|
+
// ── Enumeration ──────────────────────────────────────────────────────────
|
|
3494
|
+
async keys(pattern = "*") {
|
|
3495
|
+
this.ensureConnected();
|
|
3496
|
+
const prefixedPattern = this.prefixKey(pattern);
|
|
3497
|
+
const listPrefix = literalPrefix(prefixedPattern);
|
|
3498
|
+
const out = [];
|
|
3499
|
+
let cursor;
|
|
3500
|
+
do {
|
|
3501
|
+
const page = await this.kv.list({ prefix: listPrefix || void 0, cursor });
|
|
3502
|
+
for (const { name } of page.keys) {
|
|
3503
|
+
if (matchesPattern(name, prefixedPattern)) out.push(this.unprefixKey(name));
|
|
3504
|
+
}
|
|
3505
|
+
cursor = page.list_complete ? void 0 : page.cursor;
|
|
3506
|
+
} while (cursor);
|
|
3507
|
+
return out;
|
|
3508
|
+
}
|
|
3509
|
+
// ── Atomic (unsupported on KV) ───────────────────────────────────────────
|
|
3510
|
+
async incr(key) {
|
|
3511
|
+
return this.incrBy(key, 1);
|
|
3512
|
+
}
|
|
3513
|
+
async decr(key) {
|
|
3514
|
+
return this.incrBy(key, -1);
|
|
3515
|
+
}
|
|
3516
|
+
async incrBy(_key, _amount) {
|
|
3517
|
+
throw new StorageNotSupportedError(
|
|
3518
|
+
"incr/decr/incrBy",
|
|
3519
|
+
this.backendName,
|
|
3520
|
+
"Cloudflare KV has no atomic increment (a get+put is racy under eventual consistency). Use a Durable Object for atomic counters."
|
|
3521
|
+
);
|
|
3522
|
+
}
|
|
3523
|
+
// ── Pub/Sub (unsupported) ────────────────────────────────────────────────
|
|
3524
|
+
getPubSubSuggestion() {
|
|
3525
|
+
return "Cloudflare KV does not support pub/sub. Use a Durable Object (or Queues) for fan-out.";
|
|
3526
|
+
}
|
|
3527
|
+
// ── Helpers ──────────────────────────────────────────────────────────────
|
|
3528
|
+
/** Validate + enforce KV's 60s minimum `expirationTtl`. */
|
|
3529
|
+
toExpirationTtl(ttlSeconds, key) {
|
|
3530
|
+
validateTTL(ttlSeconds);
|
|
3531
|
+
if (ttlSeconds < CF_KV_MIN_TTL_SECONDS) {
|
|
3532
|
+
throw new StorageOperationError(
|
|
3533
|
+
"set",
|
|
3534
|
+
key,
|
|
3535
|
+
`cloudflare-kv: expirationTtl must be >= ${CF_KV_MIN_TTL_SECONDS}s (Cloudflare KV minimum); got ${ttlSeconds}s.`
|
|
3536
|
+
);
|
|
3537
|
+
}
|
|
3538
|
+
return ttlSeconds;
|
|
3539
|
+
}
|
|
3540
|
+
prefixKey(key) {
|
|
3541
|
+
return this.keyPrefix + key;
|
|
3542
|
+
}
|
|
3543
|
+
unprefixKey(key) {
|
|
3544
|
+
return this.keyPrefix && key.startsWith(this.keyPrefix) ? key.slice(this.keyPrefix.length) : key;
|
|
3545
|
+
}
|
|
3546
|
+
};
|
|
82
3547
|
}
|
|
83
|
-
};
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
3548
|
+
});
|
|
3549
|
+
init_runtime();
|
|
3550
|
+
init_fs2();
|
|
3551
|
+
init_crypto();
|
|
3552
|
+
var entryAvailabilitySchema = z3.object({
|
|
3553
|
+
os: z3.array(z3.string().min(1)).optional(),
|
|
3554
|
+
platform: z3.array(z3.string().min(1)).optional(),
|
|
3555
|
+
runtime: z3.array(z3.string().min(1)).optional(),
|
|
3556
|
+
deployment: z3.array(z3.string().min(1)).optional(),
|
|
3557
|
+
provider: z3.array(z3.string().min(1)).optional(),
|
|
3558
|
+
target: z3.array(z3.string().min(1)).optional(),
|
|
3559
|
+
surface: z3.array(z3.enum(["mcp", "cli", "http-trigger", "job", "agent"])).optional(),
|
|
3560
|
+
env: z3.array(z3.string().min(1)).optional()
|
|
3561
|
+
}).strict();
|
|
3562
|
+
init_errors();
|
|
3563
|
+
init_memory();
|
|
3564
|
+
init_errors();
|
|
3565
|
+
init_crypto();
|
|
3566
|
+
init_errors();
|
|
3567
|
+
var textEncoder2 = new TextEncoder();
|
|
3568
|
+
var textDecoder2 = new TextDecoder();
|
|
3569
|
+
init_base();
|
|
3570
|
+
init_memory();
|
|
3571
|
+
init_redis();
|
|
3572
|
+
init_vercel_kv();
|
|
3573
|
+
init_upstash();
|
|
3574
|
+
init_filesystem();
|
|
3575
|
+
init_pattern();
|
|
3576
|
+
init_ttl();
|
|
3577
|
+
init_crypto();
|
|
3578
|
+
init_runtime();
|
|
3579
|
+
|
|
3580
|
+
// plugins/plugin-cache/src/cache.symbol.ts
|
|
3581
|
+
var CacheStoreToken = /* @__PURE__ */ Symbol("plugin:cache:store");
|
|
91
3582
|
|
|
92
3583
|
// plugins/plugin-cache/src/providers/cache-memory.provider.ts
|
|
93
|
-
import { Provider
|
|
94
|
-
var
|
|
3584
|
+
import { Provider, ProviderScope } from "@frontmcp/sdk";
|
|
3585
|
+
var MAX_TIMEOUT_MS2 = 2 ** 31 - 1;
|
|
95
3586
|
var CacheMemoryProvider = class {
|
|
96
3587
|
memory = /* @__PURE__ */ new Map();
|
|
97
3588
|
sweeper;
|
|
@@ -108,7 +3599,7 @@ var CacheMemoryProvider = class {
|
|
|
108
3599
|
if (ttlSeconds && ttlSeconds > 0) {
|
|
109
3600
|
const ttlMs = ttlSeconds * 1e3;
|
|
110
3601
|
entry.expiresAt = Date.now() + ttlMs;
|
|
111
|
-
if (ttlMs <=
|
|
3602
|
+
if (ttlMs <= MAX_TIMEOUT_MS2) {
|
|
112
3603
|
entry.timeout = setTimeout(() => {
|
|
113
3604
|
const e = this.memory.get(key);
|
|
114
3605
|
if (e && e.expiresAt && e.expiresAt <= Date.now()) {
|
|
@@ -175,13 +3666,74 @@ var CacheMemoryProvider = class {
|
|
|
175
3666
|
}
|
|
176
3667
|
};
|
|
177
3668
|
CacheMemoryProvider = __decorateClass([
|
|
178
|
-
|
|
3669
|
+
Provider({
|
|
179
3670
|
name: "provider:cache:memory",
|
|
180
3671
|
description: "Memory-based cache provider",
|
|
181
|
-
scope:
|
|
3672
|
+
scope: ProviderScope.GLOBAL
|
|
182
3673
|
})
|
|
183
3674
|
], CacheMemoryProvider);
|
|
184
3675
|
|
|
3676
|
+
// plugins/plugin-cache/src/providers/cache-redis.provider.ts
|
|
3677
|
+
import Redis from "ioredis";
|
|
3678
|
+
import { Provider as Provider2, ProviderScope as ProviderScope2 } from "@frontmcp/sdk";
|
|
3679
|
+
var CacheRedisProvider = class {
|
|
3680
|
+
client;
|
|
3681
|
+
constructor(options) {
|
|
3682
|
+
if (options.type !== "redis" && options.type !== "redis-client") {
|
|
3683
|
+
throw new Error("Invalid cache provider type");
|
|
3684
|
+
}
|
|
3685
|
+
if (options.type === "redis-client") {
|
|
3686
|
+
this.client = options.client;
|
|
3687
|
+
return;
|
|
3688
|
+
}
|
|
3689
|
+
this.client = new Redis({
|
|
3690
|
+
lazyConnect: false,
|
|
3691
|
+
maxRetriesPerRequest: 3,
|
|
3692
|
+
...options.config
|
|
3693
|
+
});
|
|
3694
|
+
this.client.on("connect", () => console.log("[Redis] Connected"));
|
|
3695
|
+
this.client.on("error", (err) => console.error("[Redis] Error:", err));
|
|
3696
|
+
}
|
|
3697
|
+
/** Set a value (auto-stringifies objects) */
|
|
3698
|
+
async setValue(key, value, ttlSeconds) {
|
|
3699
|
+
const strValue = typeof value === "string" ? value : JSON.stringify(value);
|
|
3700
|
+
if (ttlSeconds && ttlSeconds > 0) {
|
|
3701
|
+
await this.client.set(key, strValue, "EX", ttlSeconds);
|
|
3702
|
+
} else {
|
|
3703
|
+
await this.client.set(key, strValue);
|
|
3704
|
+
}
|
|
3705
|
+
}
|
|
3706
|
+
/** Get a value and automatically parse JSON if possible */
|
|
3707
|
+
async getValue(key, defaultValue) {
|
|
3708
|
+
const raw = await this.client.get(key);
|
|
3709
|
+
if (raw === null) return defaultValue;
|
|
3710
|
+
try {
|
|
3711
|
+
return JSON.parse(raw);
|
|
3712
|
+
} catch {
|
|
3713
|
+
return raw;
|
|
3714
|
+
}
|
|
3715
|
+
}
|
|
3716
|
+
/** Delete a key */
|
|
3717
|
+
async delete(key) {
|
|
3718
|
+
await this.client.del(key);
|
|
3719
|
+
}
|
|
3720
|
+
/** Check if a key exists */
|
|
3721
|
+
async exists(key) {
|
|
3722
|
+
return await this.client.exists(key) === 1;
|
|
3723
|
+
}
|
|
3724
|
+
/** Gracefully close the Redis connection */
|
|
3725
|
+
async close() {
|
|
3726
|
+
await this.client.quit();
|
|
3727
|
+
}
|
|
3728
|
+
};
|
|
3729
|
+
CacheRedisProvider = __decorateClass([
|
|
3730
|
+
Provider2({
|
|
3731
|
+
name: "provider:cache:redis",
|
|
3732
|
+
description: "Redis-based cache provider",
|
|
3733
|
+
scope: ProviderScope2.GLOBAL
|
|
3734
|
+
})
|
|
3735
|
+
], CacheRedisProvider);
|
|
3736
|
+
|
|
185
3737
|
// plugins/plugin-cache/src/providers/cache-vercel-kv.provider.ts
|
|
186
3738
|
import { Provider as Provider3, ProviderScope as ProviderScope3 } from "@frontmcp/sdk";
|
|
187
3739
|
var CacheVercelKvProvider = class {
|
|
@@ -254,9 +3806,6 @@ CacheVercelKvProvider = __decorateClass([
|
|
|
254
3806
|
})
|
|
255
3807
|
], CacheVercelKvProvider);
|
|
256
3808
|
|
|
257
|
-
// plugins/plugin-cache/src/cache.symbol.ts
|
|
258
|
-
var CacheStoreToken = /* @__PURE__ */ Symbol("plugin:cache:store");
|
|
259
|
-
|
|
260
3809
|
// plugins/plugin-cache/src/cache.plugin.ts
|
|
261
3810
|
var DEFAULT_BYPASS_HEADER = "x-frontmcp-disable-cache";
|
|
262
3811
|
function matchesToolPattern(toolName, patterns) {
|
|
@@ -325,7 +3874,7 @@ var CachePlugin = class extends DynamicPlugin {
|
|
|
325
3874
|
return;
|
|
326
3875
|
}
|
|
327
3876
|
const cacheStore = this.get(CacheStoreToken);
|
|
328
|
-
const hash =
|
|
3877
|
+
const hash = this.buildCacheKey(tool.fullName, toolContext);
|
|
329
3878
|
const cached = await cacheStore.getValue(hash);
|
|
330
3879
|
if (cached !== void 0 && cached !== null) {
|
|
331
3880
|
const cacheConfig = typeof cache === "object" ? cache : void 0;
|
|
@@ -369,9 +3918,41 @@ var CachePlugin = class extends DynamicPlugin {
|
|
|
369
3918
|
}
|
|
370
3919
|
const cacheStore = this.get(CacheStoreToken);
|
|
371
3920
|
const ttl = this.getTtl(cache);
|
|
372
|
-
const hash =
|
|
3921
|
+
const hash = this.buildCacheKey(tool.fullName, toolContext);
|
|
373
3922
|
await cacheStore.setValue(hash, toolContext.output, ttl);
|
|
374
3923
|
}
|
|
3924
|
+
/**
|
|
3925
|
+
* The identity a cache entry belongs to (GHSA-r6v6-p4r8-p936).
|
|
3926
|
+
*
|
|
3927
|
+
* Most caches sit in front of tools whose output depends on who is asking. Without this the
|
|
3928
|
+
* key was the tool plus its arguments, so the first caller's response was served to every
|
|
3929
|
+
* later one: `getProfile({})` is the same key for everybody.
|
|
3930
|
+
*
|
|
3931
|
+
* The session is the last resort rather than the first choice, because an authenticated
|
|
3932
|
+
* caller can hold several sessions and should share their own cached entries across them.
|
|
3933
|
+
*/
|
|
3934
|
+
resolveCallerIdentity(toolContext) {
|
|
3935
|
+
const ctx = toolContext;
|
|
3936
|
+
const requestContext = ctx.tryGetContext?.();
|
|
3937
|
+
const authInfo = ctx.authInfo ?? requestContext?.authInfo;
|
|
3938
|
+
const subject = authInfo?.extra?.["sub"] ?? authInfo?.extra?.["userId"];
|
|
3939
|
+
if (typeof subject === "string" && subject) return `user:${subject}`;
|
|
3940
|
+
if (authInfo?.clientId) return `client:${authInfo.clientId}`;
|
|
3941
|
+
const sessionId = requestContext?.sessionId;
|
|
3942
|
+
if (sessionId) return `session:${sessionId}`;
|
|
3943
|
+
return `anonymous:${randomUUID()}`;
|
|
3944
|
+
}
|
|
3945
|
+
/**
|
|
3946
|
+
* Build the storage key for a tool call.
|
|
3947
|
+
*
|
|
3948
|
+
* Read and write both go through here. They used to build the key at two separate call
|
|
3949
|
+
* sites, and a key that differs between them silently disables the cache rather than
|
|
3950
|
+
* failing visibly.
|
|
3951
|
+
*/
|
|
3952
|
+
buildCacheKey(toolFullName, toolContext) {
|
|
3953
|
+
const identity = this.options.keyByIdentity === false ? "shared" : this.resolveCallerIdentity(toolContext);
|
|
3954
|
+
return sha256Hex(JSON.stringify({ identity, tool: toolFullName, input: stableValue(toolContext.input) }));
|
|
3955
|
+
}
|
|
375
3956
|
/**
|
|
376
3957
|
* Check if a tool is cacheable based on metadata or tools list.
|
|
377
3958
|
* This can be used by other plugins or flows to determine cacheability.
|
|
@@ -454,19 +4035,18 @@ CachePlugin = __decorateClass([
|
|
|
454
4035
|
]
|
|
455
4036
|
})
|
|
456
4037
|
], CachePlugin);
|
|
457
|
-
function
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
acc
|
|
466
|
-
}
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
}, "");
|
|
4038
|
+
function stableValue(value) {
|
|
4039
|
+
if (Array.isArray(value)) {
|
|
4040
|
+
return value.map(stableValue);
|
|
4041
|
+
}
|
|
4042
|
+
if (typeof value === "object" && value !== null) {
|
|
4043
|
+
const source = value;
|
|
4044
|
+
return Object.keys(source).sort().reduce((acc, key) => {
|
|
4045
|
+
acc[key] = stableValue(source[key]);
|
|
4046
|
+
return acc;
|
|
4047
|
+
}, {});
|
|
4048
|
+
}
|
|
4049
|
+
return value;
|
|
470
4050
|
}
|
|
471
4051
|
export {
|
|
472
4052
|
CachePlugin,
|