tricache 0.7.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +1428 -1428
  2. package/bin/tricache.js +8 -8
  3. package/dist/cache-service-5GATUYAK.js +7 -0
  4. package/dist/{cache-service-BblHuF3i.d.ts → cache-service-D8tIXmzb.d.ts} +23 -1
  5. package/dist/{chunk-3XQUQBOZ.js → chunk-EUGYR7KR.js} +87 -41
  6. package/dist/{chunk-PFB5FMEY.js → chunk-X5AXHPVD.js} +26 -15
  7. package/dist/cli.cjs +113 -56
  8. package/dist/cli.js +3 -3
  9. package/dist/drizzle/index.cjs +114 -57
  10. package/dist/drizzle/index.d.ts +1 -1
  11. package/dist/drizzle/index.js +1 -1
  12. package/dist/http/index.cjs +149 -64
  13. package/dist/http/index.d.ts +1 -1
  14. package/dist/http/index.js +38 -10
  15. package/dist/index.cjs +112 -55
  16. package/dist/index.d.ts +2 -2
  17. package/dist/index.js +2 -2
  18. package/dist/nestjs/index.cjs +112 -55
  19. package/dist/nestjs/index.d.ts +1 -1
  20. package/dist/nestjs/index.js +2 -2
  21. package/dist/next/index.cjs +143 -63
  22. package/dist/next/index.d.ts +10 -6
  23. package/dist/next/index.js +33 -10
  24. package/dist/prisma/index.cjs +2 -1
  25. package/dist/prisma/index.d.ts +1 -1
  26. package/dist/prisma/index.js +2 -1
  27. package/dist/serialize-worker.cjs +26 -15
  28. package/dist/serialize-worker.js +1 -1
  29. package/package.json +4 -2
  30. package/src/cache-service.ts +3294 -3226
  31. package/src/cli.ts +143 -143
  32. package/src/compression.ts +56 -63
  33. package/src/disk-tier.ts +821 -821
  34. package/src/encryption.ts +513 -493
  35. package/src/http/index.ts +265 -223
  36. package/src/next/cache-handler.ts +268 -244
  37. package/src/prisma/index.ts +154 -151
  38. package/src/smart-memory-cache.ts +1026 -1024
  39. package/src/types.ts +911 -902
  40. package/dist/cache-service-AJASH5FX.js +0 -7
package/bin/tricache.js CHANGED
@@ -1,8 +1,8 @@
1
- #!/usr/bin/env node
2
-
3
- import { runCli } from '../dist/cli.js';
4
-
5
- runCli().catch((err) => {
6
- console.error(err);
7
- process.exit(1);
8
- });
1
+ #!/usr/bin/env node
2
+
3
+ import { runCli } from '../dist/cli.js';
4
+
5
+ runCli().catch((err) => {
6
+ console.error(err);
7
+ process.exit(1);
8
+ });
@@ -0,0 +1,7 @@
1
+ import {
2
+ CacheService
3
+ } from "./chunk-EUGYR7KR.js";
4
+ import "./chunk-X5AXHPVD.js";
5
+ export {
6
+ CacheService
7
+ };
@@ -338,6 +338,15 @@ interface CacheOptions {
338
338
  previousEncryptionKey?: string;
339
339
  /** Encryption mode that was used with `previousEncryptionKey`. Defaults to `encryptionMode`. */
340
340
  previousEncryptionMode?: 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
341
+ /**
342
+ * Fail closed when `encryptionKey` is present but INVALID (wrong length for the
343
+ * selected `encryptionMode`, or empty). Default: `false` — tricache logs an error
344
+ * and continues with at-rest encryption DISABLED (fail-open, backward compatible).
345
+ * Set to `true` for deployments where serving plaintext at rest is unacceptable:
346
+ * the constructor then throws instead of silently downgrading security.
347
+ * Has no effect when no key is configured at all (encryption stays off, by design).
348
+ */
349
+ strictKeyValidation?: boolean;
341
350
  /**
342
351
  * Optional compression algorithm for L2 (Redis) strings and disk-tier binary blobs.
343
352
  * - `'brotli'` (default when enabled) — superior compression ratio for JSON / text payloads.
@@ -864,6 +873,8 @@ declare class CacheEncryption {
864
873
  private _key;
865
874
  private _keyObj;
866
875
  private _mode;
876
+ /** Fail-closed on invalid key material when opted in via constructor opts. */
877
+ private readonly _strictKeyValidation;
867
878
  private _prevKey;
868
879
  private _prevKeyObj;
869
880
  private _prevMode;
@@ -887,7 +898,9 @@ declare class CacheEncryption {
887
898
  * WARNING: XOR is NOT cryptographic. It provides obfuscation only.
888
899
  */
889
900
  private _xorBuffer;
890
- constructor(keyBase64: string | undefined, loggerOrMode?: ILogger | EncryptionMode, mode?: EncryptionMode, previousKeyBase64?: string, previousMode?: EncryptionMode);
901
+ constructor(keyBase64: string | undefined, loggerOrMode?: ILogger | EncryptionMode, mode?: EncryptionMode, previousKeyBase64?: string, previousMode?: EncryptionMode, opts?: {
902
+ strictKeyValidation?: boolean;
903
+ });
891
904
  get isEnabled(): boolean;
892
905
  get mode(): EncryptionMode;
893
906
  /**
@@ -1062,6 +1075,15 @@ declare class CacheService {
1062
1075
  private createDedicatedRedisClient;
1063
1076
  private initBackplane;
1064
1077
  private _startStreamConsumer;
1078
+ /**
1079
+ * Validate + apply one XREAD stream entry. `fields` is the flat ioredis
1080
+ * shape [name, value, name, value, …]. Mirrors the schema rules of the
1081
+ * pubsub path (`_handleBackplaneMessage`): op must be a known operation,
1082
+ * key/src must be non-empty strings, tagVersion must parse to a finite
1083
+ * number. Invalid entries are logged and dropped — never applied.
1084
+ */
1085
+ /** @internal Exposed for testing. */
1086
+ _processStreamEntry(fields: string[]): void;
1065
1087
  private _applyInvalidationEvent;
1066
1088
  /** @internal Exposed for testing. Applies a raw backplane JSON message to local state. */
1067
1089
  _handleBackplaneMessage(message: string): void;
@@ -7,7 +7,7 @@ import {
7
7
  consoleLogger,
8
8
  decompressBuffer,
9
9
  decompressWithHeader
10
- } from "./chunk-PFB5FMEY.js";
10
+ } from "./chunk-X5AXHPVD.js";
11
11
 
12
12
  // src/cache-service.ts
13
13
  import { Redis as RedisClient, Cluster as RedisCluster } from "ioredis";
@@ -289,7 +289,6 @@ var WasmBloomFilter = class {
289
289
  };
290
290
 
291
291
  // src/smart-memory-cache.ts
292
- var _hit = { value: void 0, isStale: false, expiresAt: 0, ttlMs: void 0, delta: void 0, fetchedAt: 0, tagVersions: void 0, setAt: void 0 };
293
292
  var LARGE_VALUE_BYTES = 16384;
294
293
  var EVICTION_BATCH_PERCENT = 0.2;
295
294
  var EVICTION_SAMPLE = 16;
@@ -692,15 +691,17 @@ var SmartMemoryCache = class {
692
691
  entry.lastAccess = now;
693
692
  if ((entry.hits & 3) === 0) this.sketch.increment(key);
694
693
  const value = entry.value !== void 0 ? entry.value : unpack(entry.data);
695
- _hit.value = value;
696
- _hit.isStale = entry.staleAt !== void 0 && now > entry.staleAt;
697
- _hit.expiresAt = entry.expiresAt;
698
- _hit.ttlMs = entry.ttlMs;
699
- _hit.delta = entry.delta;
700
- _hit.fetchedAt = now;
701
- _hit.tagVersions = entry.tagVersions;
702
- _hit.setAt = entry.setAt;
703
- return _hit;
694
+ const hit = {
695
+ value,
696
+ isStale: entry.staleAt !== void 0 && now > entry.staleAt,
697
+ expiresAt: entry.expiresAt,
698
+ ttlMs: entry.ttlMs,
699
+ delta: entry.delta,
700
+ fetchedAt: now,
701
+ tagVersions: entry.tagVersions,
702
+ setAt: entry.setAt
703
+ };
704
+ return hit;
704
705
  }
705
706
  set(key, data, ttlMs, priority = 2, staleAt, delta, tagVersions) {
706
707
  const packed = pack(data);
@@ -1630,6 +1631,7 @@ var DiskTier = class {
1630
1631
  dec = this.decrypt(raw);
1631
1632
  } catch {
1632
1633
  fs.unlinkSync(filePath);
1634
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1633
1635
  this.fileCount = Math.max(0, this.fileCount - 1);
1634
1636
  purged++;
1635
1637
  continue;
@@ -1793,6 +1795,7 @@ var DiskTier = class {
1793
1795
  dec = this.decrypt(raw);
1794
1796
  } catch {
1795
1797
  fs.unlinkSync(filePath);
1798
+ this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
1796
1799
  this.fileCount = Math.max(0, this.fileCount - 1);
1797
1800
  purged++;
1798
1801
  continue;
@@ -1870,6 +1873,7 @@ return 0
1870
1873
  `;
1871
1874
  var SNAPSHOT_VERSION = 1;
1872
1875
  var DEFAULT_SNAPSHOT_MAX_AGE = 2 * 60 * 60 * 1e3;
1876
+ var INDEFINITE_TTL_SECONDS = 31536e3;
1873
1877
  var SNAPSHOT_MAX_FILE_BYTES = 220 * 1024 * 1024;
1874
1878
  var DEFAULT_CATEGORY_LIMITS = {
1875
1879
  "default": { maxEntries: 500, maxSizeBytes: 50 * 1024 * 1024 }
@@ -2144,7 +2148,8 @@ var CacheService = class _CacheService {
2144
2148
  logger,
2145
2149
  options.encryptionMode,
2146
2150
  options.previousEncryptionKey,
2147
- options.previousEncryptionMode
2151
+ options.previousEncryptionMode,
2152
+ { strictKeyValidation: options.strictKeyValidation ?? false }
2148
2153
  );
2149
2154
  const rawForbidden = options.forbiddenSnapshotPrefixes ?? [...DEFAULT_FORBIDDEN_PREFIXES];
2150
2155
  const forbiddenPrefixes = ns ? rawForbidden.map((p) => `${ns}:${p}`) : rawForbidden;
@@ -2166,8 +2171,14 @@ var CacheService = class _CacheService {
2166
2171
  redisHost: options.redisHost ?? process.env.REDIS_HOST ?? "",
2167
2172
  redisPort: options.redisPort ?? 6379,
2168
2173
  redisTls: options.redisTls ?? process.env.NODE_ENV === "production",
2169
- disableRedis: options.disableRedis ?? process.env.NODE_ENV !== "production",
2174
+ disableRedis: options.disableRedis ?? (() => {
2175
+ const explicitConfig = Boolean(
2176
+ options.redisHost || options.redisClusterNodes?.length || options.redisSentinel
2177
+ );
2178
+ return !explicitConfig && process.env.NODE_ENV !== "production";
2179
+ })(),
2170
2180
  encryptionKey: encKeyRaw,
2181
+ encryptionMode: options.encryptionMode,
2171
2182
  snapshotPath: options.snapshotPath ?? path2.join(
2172
2183
  os2.tmpdir(),
2173
2184
  ns ? `tricache-snapshot-${ns}.msgpack` : "tricache-snapshot.msgpack"
@@ -2273,7 +2284,6 @@ var CacheService = class _CacheService {
2273
2284
  }
2274
2285
  this._shutdownHandler = () => {
2275
2286
  if (!this._diskDisabled) this.writeSnapshot();
2276
- process.exit(0);
2277
2287
  };
2278
2288
  process.once("SIGTERM", this._shutdownHandler);
2279
2289
  process.once("SIGINT", this._shutdownHandler);
@@ -2452,7 +2462,10 @@ var CacheService = class _CacheService {
2452
2462
  disableRedis: this._redisDisabled,
2453
2463
  redisClusterNodes: o.redisClusterNodes,
2454
2464
  redisSentinel: o.redisSentinel,
2455
- encryptionKey: o.encryptionKey,
2465
+ // Never surface key material through diagnostics — a JSON.stringify of
2466
+ // this object previously leaked the raw encryption key.
2467
+ encryptionKey: o.encryptionKey ? "[REDACTED]" : void 0,
2468
+ encryptionMode: o.encryptionMode,
2456
2469
  l2WriteMode: o.l2WriteMode,
2457
2470
  instanceName: o.instanceName,
2458
2471
  frozen: o.frozen,
@@ -2657,24 +2670,7 @@ var CacheService = class _CacheService {
2657
2670
  for (const [id, fields] of entries) {
2658
2671
  this._lastStreamId = id;
2659
2672
  this.counters.streamEntriesReceived++;
2660
- let op = "";
2661
- let key = "";
2662
- let src = "";
2663
- let tagVersion;
2664
- for (let i = 0; i < fields.length; i += 2) {
2665
- const f = fields[i];
2666
- const v = fields[i + 1];
2667
- if (f === "op") op = v;
2668
- else if (f === "key") key = v;
2669
- else if (f === "src") src = v;
2670
- else if (f === "tagVersion") tagVersion = parseInt(v, 10);
2671
- }
2672
- if (src === this.instanceId) {
2673
- this.counters.invSkipped++;
2674
- continue;
2675
- }
2676
- this.counters.invReceived++;
2677
- this._applyInvalidationEvent(op, key, tagVersion);
2673
+ this._processStreamEntry(fields);
2678
2674
  }
2679
2675
  }
2680
2676
  }
@@ -2695,6 +2691,51 @@ var CacheService = class _CacheService {
2695
2691
  };
2696
2692
  void runLoop();
2697
2693
  }
2694
+ /**
2695
+ * Validate + apply one XREAD stream entry. `fields` is the flat ioredis
2696
+ * shape [name, value, name, value, …]. Mirrors the schema rules of the
2697
+ * pubsub path (`_handleBackplaneMessage`): op must be a known operation,
2698
+ * key/src must be non-empty strings, tagVersion must parse to a finite
2699
+ * number. Invalid entries are logged and dropped — never applied.
2700
+ */
2701
+ /** @internal Exposed for testing. */
2702
+ _processStreamEntry(fields) {
2703
+ let op = "";
2704
+ let key = "";
2705
+ let src = "";
2706
+ let tagVersionRaw;
2707
+ for (let i = 0; i + 1 < fields.length; i += 2) {
2708
+ const f = fields[i];
2709
+ const v = fields[i + 1];
2710
+ if (f === "op") op = v;
2711
+ else if (f === "key") key = v;
2712
+ else if (f === "src") src = v;
2713
+ else if (f === "tagVersion") tagVersionRaw = v;
2714
+ }
2715
+ const validOp = op === "del" || op === "del-glob" || op === "tag_incr";
2716
+ if (!validOp || typeof key !== "string" || !key || typeof src !== "string") {
2717
+ this.logger.warn("Backplane: rejected invalid stream entry", {
2718
+ op: String(op).slice(0, 40),
2719
+ key: typeof key === "string" ? key.slice(0, 100).replace(/[\r\n\t]/g, " ") : String(key)
2720
+ });
2721
+ return;
2722
+ }
2723
+ let tagVersion;
2724
+ if (tagVersionRaw !== void 0) {
2725
+ const parsed = parseInt(tagVersionRaw, 10);
2726
+ if (!Number.isFinite(parsed)) {
2727
+ this.logger.warn("Backplane: rejected stream entry with non-numeric tagVersion", { key });
2728
+ return;
2729
+ }
2730
+ tagVersion = parsed;
2731
+ }
2732
+ if (src === this.instanceId) {
2733
+ this.counters.invSkipped++;
2734
+ return;
2735
+ }
2736
+ this.counters.invReceived++;
2737
+ this._applyInvalidationEvent(op, key, tagVersion);
2738
+ }
2698
2739
  _applyInvalidationEvent(op, key, tagVersion) {
2699
2740
  if (op === "del") {
2700
2741
  this.l1.delete(key);
@@ -3381,7 +3422,8 @@ var CacheService = class _CacheService {
3381
3422
  async set(cacheKey, data, ttlSeconds = 300, priority, opts) {
3382
3423
  const span = this._startSpan("tricache.set");
3383
3424
  if (this.opts.tracer) span.setAttribute("cache.key_prefix", cacheKey.split(":")[0]);
3384
- const ttlMs = this._jitterTtl(ttlSeconds * 1e3);
3425
+ const effectiveTtlSeconds = ttlSeconds > 0 ? ttlSeconds : ttlSeconds === 0 ? INDEFINITE_TTL_SECONDS : ttlSeconds;
3426
+ const ttlMs = this._jitterTtl(effectiveTtlSeconds * 1e3);
3385
3427
  const p = priority ?? inferPriority(cacheKey);
3386
3428
  const k = this.nk(cacheKey);
3387
3429
  this.counters.sets++;
@@ -4223,8 +4265,9 @@ var CacheService = class _CacheService {
4223
4265
  const deadline = Date.now() + acquireTimeout;
4224
4266
  let acquired = false;
4225
4267
  if (!this._redisDisabled) {
4268
+ let client = null;
4226
4269
  try {
4227
- const client = await this.getRedis();
4270
+ client = await this.getRedis();
4228
4271
  while (Date.now() <= deadline) {
4229
4272
  const res = await client.set(lockKey, token, "EX", ttlSeconds, "NX");
4230
4273
  if (res === "OK") {
@@ -4238,6 +4281,15 @@ var CacheService = class _CacheService {
4238
4281
  if (!acquired) {
4239
4282
  throw new Error(`Failed to acquire lock for resource "${resourceKey}" within ${acquireTimeout}ms`);
4240
4283
  }
4284
+ } catch (err) {
4285
+ if (err.message.startsWith("Failed to acquire lock")) throw err;
4286
+ this.logger.debug("Distributed lock: Redis error, falling back to in-process mutex", {
4287
+ resourceKey,
4288
+ error: err.message
4289
+ });
4290
+ client = null;
4291
+ }
4292
+ if (client !== null && acquired) {
4241
4293
  try {
4242
4294
  return await fn();
4243
4295
  } finally {
@@ -4253,12 +4305,6 @@ var CacheService = class _CacheService {
4253
4305
  } catch {
4254
4306
  }
4255
4307
  }
4256
- } catch (err) {
4257
- if (err.message.startsWith("Failed to acquire lock")) throw err;
4258
- this.logger.debug("Distributed lock: Redis error, falling back to in-process mutex", {
4259
- resourceKey,
4260
- error: err.message
4261
- });
4262
4308
  }
4263
4309
  }
4264
4310
  let unlock = () => {
@@ -35,6 +35,8 @@ var CacheEncryption = class {
35
35
  _keyObj = null;
36
36
  // parsed KeyObject — used for all AES modes
37
37
  _mode;
38
+ /** Fail-closed on invalid key material when opted in via constructor opts. */
39
+ _strictKeyValidation;
38
40
  _prevKey = null;
39
41
  _prevKeyObj = null;
40
42
  _prevMode = "aes-256-gcm";
@@ -100,11 +102,12 @@ var CacheEncryption = class {
100
102
  }
101
103
  return out;
102
104
  }
103
- constructor(keyBase64, loggerOrMode = consoleLogger, mode = "aes-256-gcm", previousKeyBase64, previousMode) {
105
+ constructor(keyBase64, loggerOrMode = consoleLogger, mode = "aes-256-gcm", previousKeyBase64, previousMode, opts) {
104
106
  const logger = typeof loggerOrMode === "object" && loggerOrMode !== null ? loggerOrMode : consoleLogger;
105
107
  const resolvedMode = typeof loggerOrMode === "string" ? loggerOrMode : mode;
108
+ this._strictKeyValidation = opts?.strictKeyValidation ?? false;
106
109
  this._mode = resolvedMode;
107
- if (!keyBase64) {
110
+ if (keyBase64 === void 0 || keyBase64 === null) {
108
111
  if (process.env.NODE_ENV === "production") {
109
112
  logger.warn(
110
113
  "SECURITY: encryption key not set \u2014 cache data stored unencrypted at rest",
@@ -113,11 +116,17 @@ var CacheEncryption = class {
113
116
  }
114
117
  return;
115
118
  }
119
+ if (keyBase64 === "") {
120
+ const err = new Error("Encryption key is empty \u2014 set encryptionKey option or CACHE_ENCRYPTION_KEY");
121
+ if (this._strictKeyValidation) throw err;
122
+ logger.error("Empty encryption key \u2014 falling back to plaintext", {}, err);
123
+ return;
124
+ }
116
125
  try {
117
126
  const buf = Buffer.from(keyBase64, "base64");
118
127
  const requiredLen = resolvedMode === "aes-256-gcm" ? 32 : resolvedMode === "aes-128-gcm" || resolvedMode === "aes-128-ctr" ? 16 : 0;
119
128
  if (requiredLen > 0 && buf.length !== requiredLen) {
120
- throw new Error(`${mode} requires exactly ${requiredLen} bytes (got ${buf.length})`);
129
+ throw new Error(`${resolvedMode} requires exactly ${requiredLen} bytes (got ${buf.length})`);
121
130
  }
122
131
  if (buf.length < 1) {
123
132
  throw new Error("XOR key must be at least 1 byte");
@@ -141,6 +150,9 @@ var CacheEncryption = class {
141
150
  logger.debug(`Cache encryption enabled (${mode.toUpperCase()})`);
142
151
  }
143
152
  } catch (err) {
153
+ if (this._strictKeyValidation) {
154
+ throw err;
155
+ }
144
156
  logger.error("Invalid encryption key \u2014 falling back to plaintext", {}, err);
145
157
  }
146
158
  if (previousKeyBase64) {
@@ -422,26 +434,25 @@ function compressBuffer(buf, algorithm) {
422
434
  return buf;
423
435
  }
424
436
  function decompressBuffer(buf, algorithm = "brotli") {
425
- if (algorithm === "gzip") {
437
+ const tryBrotli = () => {
426
438
  try {
427
- return zlib.gunzipSync(buf);
439
+ return zlib.brotliDecompressSync(buf);
428
440
  } catch {
429
- try {
430
- return zlib.brotliDecompressSync(buf);
431
- } catch {
432
- return buf;
433
- }
441
+ return null;
434
442
  }
435
- }
436
- try {
437
- return zlib.brotliDecompressSync(buf);
438
- } catch {
443
+ };
444
+ const tryGzip = () => {
439
445
  try {
440
446
  return zlib.gunzipSync(buf);
441
447
  } catch {
442
- return buf;
448
+ return null;
443
449
  }
450
+ };
451
+ const result = algorithm === "gzip" ? tryGzip() ?? tryBrotli() : tryBrotli() ?? tryGzip();
452
+ if (result === null) {
453
+ throw new Error(`tricache: corrupt compressed payload (${buf.length} bytes, algorithm=${algorithm})`);
444
454
  }
455
+ return result;
445
456
  }
446
457
  function compressWithHeader(buf, algorithm) {
447
458
  if (algorithm === "none") return buf;