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