tricache 0.7.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +89 -1371
  3. package/dashboards/prometheus-scrape.yml +18 -0
  4. package/dashboards/tricache-alerts.yaml +54 -0
  5. package/dashboards/tricache-grafana.json +548 -0
  6. package/dist/cache-service-DVvroyqA.d.ts +886 -0
  7. package/dist/cache-service-KI5ACF3F.js +12 -0
  8. package/dist/chunk-7RV5ZVBB.js +1023 -0
  9. package/dist/chunk-BQRURGGD.js +60 -0
  10. package/dist/chunk-IITRFWHY.js +196 -0
  11. package/dist/{chunk-X5AXHPVD.js → chunk-LJ5QJB5O.js} +90 -5
  12. package/dist/{chunk-EUGYR7KR.js → chunk-PL5J3ZNT.js} +3184 -514
  13. package/dist/chunk-QNU7B43J.js +687 -0
  14. package/dist/chunk-UGD4VEPD.js +138 -0
  15. package/dist/chunk-XZL45ABR.js +108 -0
  16. package/dist/cli.cjs +3122 -495
  17. package/dist/cli.d.ts +1 -0
  18. package/dist/cli.js +121 -5
  19. package/dist/dashboard/index.cjs +1065 -0
  20. package/dist/dashboard/index.d.ts +183 -0
  21. package/dist/dashboard/index.js +22 -0
  22. package/dist/drizzle/index.cjs +2846 -494
  23. package/dist/drizzle/index.d.ts +3 -1
  24. package/dist/drizzle/index.js +1 -1
  25. package/dist/edge/index.cjs +1559 -0
  26. package/dist/edge/index.d.ts +127 -0
  27. package/dist/edge/index.js +1109 -0
  28. package/dist/hono/index.cjs +7760 -0
  29. package/dist/hono/index.d.ts +91 -0
  30. package/dist/hono/index.js +185 -0
  31. package/dist/hono-VA9A1m0I.d.ts +371 -0
  32. package/dist/http/index.cjs +3281 -587
  33. package/dist/http/index.d.ts +85 -23
  34. package/dist/http/index.js +176 -78
  35. package/dist/index.cjs +7212 -2505
  36. package/dist/index.d.ts +547 -30
  37. package/dist/index.js +104 -5
  38. package/dist/murmur3-CMGw9PbV.d.ts +98 -0
  39. package/dist/nestjs/index.cjs +2787 -487
  40. package/dist/nestjs/index.d.ts +3 -1
  41. package/dist/nestjs/index.js +6 -3
  42. package/dist/next/index.cjs +2804 -501
  43. package/dist/next/index.d.ts +4 -2
  44. package/dist/next/index.js +14 -10
  45. package/dist/prisma/index.d.ts +3 -1
  46. package/dist/serialize-worker.cjs +5 -4
  47. package/dist/serialize-worker.js +1 -1
  48. package/dist/{cache-service-D8tIXmzb.d.ts → types-B_QkVwJ7.d.ts} +622 -662
  49. package/dist/utils-CEsU_Z0s.d.ts +27 -0
  50. package/package.json +48 -10
  51. package/src/adapters/auto-pipeliner.ts +206 -0
  52. package/src/adapters/node-redis.ts +370 -0
  53. package/src/cache-service.ts +1619 -415
  54. package/src/cli.ts +137 -2
  55. package/src/codec.ts +72 -0
  56. package/src/cross-region.ts +245 -0
  57. package/src/dashboard/handler.ts +392 -0
  58. package/src/dashboard/html.ts +594 -0
  59. package/src/dashboard/index.ts +195 -0
  60. package/src/dashboard/types.ts +96 -0
  61. package/src/disk-tier.ts +449 -47
  62. package/src/drizzle/index.ts +86 -86
  63. package/src/edge/adapters/cloudflare-do.ts +130 -0
  64. package/src/edge/adapters/cloudflare-kv.ts +115 -0
  65. package/src/edge/adapters/upstash.ts +143 -0
  66. package/src/edge/cache.ts +797 -0
  67. package/src/edge/crypto.ts +182 -0
  68. package/src/edge/hono.ts +284 -0
  69. package/src/edge/index.ts +37 -0
  70. package/src/edge/types.ts +230 -0
  71. package/src/edge/utils/base64.ts +63 -0
  72. package/src/edge/utils/murmur3.ts +179 -0
  73. package/src/encryption.ts +127 -5
  74. package/src/hono/index.ts +316 -0
  75. package/src/http/express.ts +195 -0
  76. package/src/http/fastify.ts +260 -0
  77. package/src/http/index.ts +44 -258
  78. package/src/http/utils.ts +92 -0
  79. package/src/index.ts +149 -47
  80. package/src/ipc-telemetry.ts +509 -0
  81. package/src/latency-watchdog.ts +282 -0
  82. package/src/nestjs/decorators.ts +161 -161
  83. package/src/nestjs/index.ts +23 -23
  84. package/src/nestjs/tricache.module.ts +104 -104
  85. package/src/nestjs/tricache.store.ts +97 -97
  86. package/src/nestjs/types.ts +79 -79
  87. package/src/next/cache-handler.ts +12 -9
  88. package/src/next/index.ts +37 -37
  89. package/src/next/isr-handler.ts +105 -105
  90. package/src/next/types.ts +130 -130
  91. package/src/remote-snapshot.ts +153 -0
  92. package/src/serialize-worker.ts +120 -120
  93. package/src/sigv4-snapshot-adapter.ts +260 -0
  94. package/src/smart-memory-cache.ts +91 -8
  95. package/src/types.ts +315 -2
  96. package/src/utils/cgroup.ts +100 -0
  97. package/src/utils/tracing.ts +54 -0
  98. package/src/wasm/bloom-filter-wasm.ts +109 -102
  99. package/src/worker-pool.ts +299 -299
  100. package/src/wtiny-lfu.ts +624 -0
  101. package/dist/cache-service-5GATUYAK.js +0 -7
  102. package/dist/chunk-UBSR5UYA.js +0 -0
@@ -0,0 +1,230 @@
1
+ import type { ICacheTracer } from '../types';
2
+
3
+ /**
4
+ * Pluggable asynchronous key-value storage adapter for Edge runtimes (L2 tier).
5
+ */
6
+ export interface IEdgeRemoteStorage {
7
+ /** Fetch a stored value by key. Returns null on miss. */
8
+ get(key: string): Promise<string | null>;
9
+
10
+ /** Store a value with an optional TTL in seconds. */
11
+ set(key: string, value: string, ttlSeconds?: number): Promise<void>;
12
+
13
+ /** Delete a key. */
14
+ delete(key: string): Promise<void>;
15
+
16
+ /** Optional batch read. Returns array matching keys order (null for missing). */
17
+ mget?(keys: string[]): Promise<(string | null)[]>;
18
+
19
+ /** Optional batch write. */
20
+ mset?(entries: Record<string, string>, ttlSeconds?: number): Promise<void>;
21
+
22
+ /** Optional clear by prefix or all keys. */
23
+ clear?(prefix?: string): Promise<void>;
24
+
25
+ /** Optional atomic or monotonic tag version increment for generational tag invalidation. */
26
+ incrementTagVersion?(tag: string): Promise<number>;
27
+
28
+ /** Optional tag version retrieval. */
29
+ getTagVersion?(tag: string): Promise<number>;
30
+
31
+ /** Optional batch tag version retrieval. */
32
+ batchGetTagVersions?(tags: string[]): Promise<Record<string, number>>;
33
+ }
34
+
35
+ /**
36
+ * Options for cache read operations in Edge environments.
37
+ */
38
+ export interface EdgeGetOptions {
39
+ /** Cache tags associated with this entry for bulk invalidation. */
40
+ tags?: string[];
41
+
42
+ /**
43
+ * Stale-While-Revalidate window in seconds.
44
+ * If entry is older than TTL but within (TTL + swr), stale data is returned
45
+ * immediately while a background fetcher runs to refresh the cache.
46
+ */
47
+ swr?: number;
48
+
49
+ /**
50
+ * Execution context provided by Edge platforms (Cloudflare Workers, Vercel Edge).
51
+ * Critical: In edge isolates, background tasks spawned without ctx.waitUntil()
52
+ * are terminated as soon as the HTTP response terminates.
53
+ */
54
+ ctx?: {
55
+ waitUntil: (promise: Promise<unknown>) => void;
56
+ };
57
+ }
58
+
59
+ /**
60
+ * Options for configuring the EdgeCacheService.
61
+ */
62
+ export interface EdgeCacheOptions {
63
+ /**
64
+ * Maximum number of keys held in L1 in-memory LRU. Default: 10,000.
65
+ */
66
+ maxKeys?: number;
67
+
68
+ /**
69
+ * Approximate maximum memory in bytes for L1 cache (calculated via UTF-8 length * 2).
70
+ * Default: 32 MB (33,554,432 bytes).
71
+ */
72
+ maxBytes?: number;
73
+
74
+ /** Default TTL in seconds when not specified on get/set. Default: 300 (5 min). */
75
+ defaultTtlSeconds?: number;
76
+
77
+ /** Optional remote L2 storage adapter (Upstash, Cloudflare KV, Cloudflare DO). */
78
+ remoteStorage?: IEdgeRemoteStorage;
79
+
80
+ /** Optional at-rest encryption configuration via Web Crypto (AES-GCM). */
81
+ encryption?: {
82
+ keyBase64: string;
83
+ prevKeyBase64?: string;
84
+ mode?: 'aes-256-gcm' | 'aes-128-gcm';
85
+ };
86
+
87
+ /** Multi-tenant key namespace prefix. */
88
+ namespace?: string;
89
+
90
+ /** OpenTelemetry-compatible tracer for distributed tracing. */
91
+ tracer?: ICacheTracer;
92
+
93
+ /**
94
+ * Optional Bloom filter to defend against remote storage penetration on guaranteed misses.
95
+ * - `true`: automatically instantiates a default `WasmBloomFilter` (or `Murmur3BloomFilter` fallback).
96
+ * - `IEdgeBloomFilter`: a custom or configured `WasmBloomFilter` or `Murmur3BloomFilter` instance.
97
+ */
98
+ bloomFilter?: boolean | IEdgeBloomFilter;
99
+ }
100
+
101
+ /**
102
+ * Common contract for Edge-compatible Bloom filters (WASM or pure TypeScript Murmur3).
103
+ */
104
+ export interface IEdgeBloomFilter {
105
+ add(key: string): void;
106
+ mightContain(key: string): boolean;
107
+ reset(): void;
108
+ rebuild?(keys: Iterable<string>): void;
109
+ readonly insertions?: number;
110
+ readonly maxCapacity?: number;
111
+ readonly stats?: { bitsSet: number; fillFactor: number };
112
+ }
113
+
114
+ /**
115
+ * Configuration for Upstash REST Redis adapter.
116
+ */
117
+ export interface UpstashRedisOptions {
118
+ /** Upstash REST URL (e.g. "https://us1-clean-slug-12345.upstash.io"). */
119
+ url: string;
120
+
121
+ /** Upstash REST bearer token. */
122
+ token: string;
123
+
124
+ /** Optional custom fetch implementation (defaults to globalThis.fetch). */
125
+ fetch?: typeof globalThis.fetch;
126
+ }
127
+
128
+ /**
129
+ * Minimal interface representing Cloudflare Workers KVNamespace binding.
130
+ */
131
+ export interface CloudflareKVNamespace {
132
+ get(key: string, options?: { type?: 'text' | 'json' | 'arrayBuffer' | 'stream'; cacheTtl?: number }): Promise<string | null>;
133
+ put(key: string, value: string, options?: { expirationTtl?: number; metadata?: unknown }): Promise<void>;
134
+ delete(key: string): Promise<void>;
135
+ list?(options?: { prefix?: string; limit?: number; cursor?: string }): Promise<{
136
+ keys: Array<{ name: string; expiration?: number; metadata?: unknown }>;
137
+ list_complete: boolean;
138
+ cursor?: string;
139
+ }>;
140
+ }
141
+
142
+ /**
143
+ * Minimal interface representing Cloudflare Durable Objects storage binding (state.storage).
144
+ */
145
+ export interface CloudflareDOStorage {
146
+ get<T = unknown>(key: string): Promise<T | undefined>;
147
+ get<T = unknown>(keys: string[]): Promise<Map<string, T>>;
148
+ put<T = unknown>(key: string, value: T): Promise<void>;
149
+ put<T = unknown>(entries: Record<string, T>): Promise<void>;
150
+ delete(key: string): Promise<boolean>;
151
+ delete(keys: string[]): Promise<number>;
152
+ list?<T = unknown>(options?: { prefix?: string; limit?: number }): Promise<Map<string, T>>;
153
+ }
154
+
155
+ /**
156
+ * Minimal interface representing a Cloudflare R2 object returned by R2Bucket.get().
157
+ */
158
+ export interface CloudflareR2Object {
159
+ text(): Promise<string>;
160
+ arrayBuffer(): Promise<ArrayBuffer>;
161
+ json?<T = unknown>(): Promise<T>;
162
+ }
163
+
164
+ /**
165
+ * Minimal interface representing Cloudflare R2 Bucket binding (env.MY_BUCKET).
166
+ */
167
+ export interface CloudflareR2Bucket {
168
+ get(key: string): Promise<CloudflareR2Object | null>;
169
+ put(key: string, value: string | ArrayBuffer | ArrayBufferView | Blob | ReadableStream, options?: unknown): Promise<unknown>;
170
+ delete?(key: string | string[]): Promise<void>;
171
+ }
172
+
173
+ /**
174
+ * Generic source for edge snapshot hydration (R2 bucket binding, custom loader object, raw string, or ArrayBuffer).
175
+ */
176
+ export type EdgeSnapshotSource =
177
+ | CloudflareR2Bucket
178
+ | { get(key: string): Promise<CloudflareR2Object | string | ArrayBuffer | Uint8Array | null> }
179
+ | string
180
+ | ArrayBuffer
181
+ | Uint8Array;
182
+
183
+ /**
184
+ * Configuration options for EdgeCacheService.hydrate().
185
+ */
186
+ export interface EdgeHydrateOptions {
187
+ /**
188
+ * Object key or filename in the R2 bucket. Default: 'tricache-edge.snap'
189
+ */
190
+ key?: string;
191
+
192
+ /**
193
+ * Maximum acceptable age of snapshot in milliseconds before rejecting as stale.
194
+ * Default: 7,200,000 ms (2 hours).
195
+ */
196
+ maxAgeMs?: number;
197
+
198
+ /**
199
+ * Acceptable clock skew tolerance in milliseconds for future timestamps.
200
+ * Default: 250 ms.
201
+ */
202
+ clockSkewToleranceMs?: number;
203
+ }
204
+
205
+ /**
206
+ * Configuration options for EdgeCacheService.exportSnapshot().
207
+ */
208
+ export interface EdgeExportSnapshotOptions {
209
+ /**
210
+ * Whether to encrypt the exported snapshot using the configured Web Crypto AEAD key.
211
+ * Default: true (when encryption is configured).
212
+ */
213
+ encrypt?: boolean;
214
+ }
215
+
216
+ /**
217
+ * Serialized representation of edge cache snapshot payload.
218
+ */
219
+ export interface EdgeSnapshotPayload {
220
+ version: number;
221
+ writtenAt: number;
222
+ entries: Array<{
223
+ key: string;
224
+ value: unknown;
225
+ expiresAt: number;
226
+ staleUntil: number;
227
+ tags?: string[];
228
+ tagVersions?: Record<string, number>;
229
+ }>;
230
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Zero-dependency Base64 <-> Uint8Array utilities designed for pure Edge isolates
3
+ * (Cloudflare Workers without nodejs_compat, Deno, Fastly Compute, browsers).
4
+ *
5
+ * Avoids call stack overflow (RangeError: Maximum call stack size exceeded)
6
+ * on payloads > 64 KB by chunking binary data into safe 8 KB slices.
7
+ */
8
+
9
+ const CHUNK_SIZE = 8192;
10
+
11
+ /**
12
+ * Converts a Uint8Array to a standard Base64 string safely across all JS runtimes.
13
+ */
14
+ export function uint8ArrayToBase64(bytes: Uint8Array): string {
15
+ // 1. Modern TC39 stage 3 Uint8Array.prototype.toBase64 support
16
+ const modernBytes = bytes as unknown as { toBase64?: () => string };
17
+ if (typeof modernBytes.toBase64 === 'function') {
18
+ return modernBytes.toBase64();
19
+ }
20
+
21
+ // 2. Fallback using chunked String.fromCharCode + btoa
22
+ let binary = '';
23
+ const len = bytes.length;
24
+ for (let i = 0; i < len; i += CHUNK_SIZE) {
25
+ const chunk = bytes.subarray(i, Math.min(i + CHUNK_SIZE, len));
26
+ binary += String.fromCharCode(...chunk);
27
+ }
28
+ return globalThis.btoa(binary);
29
+ }
30
+
31
+ /**
32
+ * Converts a Base64 string to a Uint8Array safely across all JS runtimes.
33
+ */
34
+ export function base64ToUint8Array(base64: string): Uint8Array {
35
+ // 1. Modern TC39 stage 3 Uint8Array.fromBase64 support
36
+ const modernU8 = Uint8Array as unknown as { fromBase64?: (s: string) => Uint8Array };
37
+ if (typeof modernU8.fromBase64 === 'function') {
38
+ return modernU8.fromBase64(base64);
39
+ }
40
+
41
+ // 2. Universal atob fallback
42
+ const binary = globalThis.atob(base64);
43
+ const len = binary.length;
44
+ const bytes = new Uint8Array(len);
45
+ for (let i = 0; i < len; i++) {
46
+ bytes[i] = binary.charCodeAt(i);
47
+ }
48
+ return bytes;
49
+ }
50
+
51
+ /**
52
+ * Encodes a UTF-8 string to a Uint8Array using standard TextEncoder.
53
+ */
54
+ export function utf8ToUint8Array(str: string): Uint8Array {
55
+ return new TextEncoder().encode(str);
56
+ }
57
+
58
+ /**
59
+ * Decodes a Uint8Array to a UTF-8 string using standard TextDecoder.
60
+ */
61
+ export function uint8ArrayToUtf8(bytes: Uint8Array): string {
62
+ return new TextDecoder().decode(bytes);
63
+ }
@@ -0,0 +1,179 @@
1
+ /**
2
+ * Standard 32-bit MurmurHash3 (x86_32) implementation.
3
+ * Pure TypeScript, zero external dependencies, zero Node.js Buffer dependencies.
4
+ *
5
+ * Fully compatible with V8 Edge Isolates (Cloudflare Workers, Fastly Compute,
6
+ * Vercel Edge, Deno, Bun, and modern browsers).
7
+ */
8
+
9
+ /**
10
+ * Computes the 32-bit MurmurHash3 of a string with an optional seed.
11
+ * Uses 32-bit unsigned arithmetic (>>> 0).
12
+ */
13
+ export function murmur3_32(key: string, seed = 0): number {
14
+ const c1 = 0xcc9e2d51;
15
+ const c2 = 0x1b873593;
16
+
17
+ let h1 = seed >>> 0;
18
+ const len = key.length;
19
+
20
+ // Process 2-character (4-byte in UTF-16 code units / 2-char chunks) blocks
21
+ const remainder = len & 1;
22
+ const bytes = len - remainder;
23
+
24
+ for (let i = 0; i < bytes; i += 2) {
25
+ let k1 = (key.charCodeAt(i) & 0xffff) | ((key.charCodeAt(i + 1) & 0xffff) << 16);
26
+
27
+ k1 = Math.imul(k1, c1);
28
+ k1 = (k1 << 15) | (k1 >>> 17);
29
+ k1 = Math.imul(k1, c2);
30
+
31
+ h1 ^= k1;
32
+ h1 = (h1 << 13) | (h1 >>> 19);
33
+ h1 = (Math.imul(h1, 5) + 0xe6546b64) >>> 0;
34
+ }
35
+
36
+ if (remainder === 1) {
37
+ let k1 = key.charCodeAt(bytes) & 0xffff;
38
+ k1 = Math.imul(k1, c1);
39
+ k1 = (k1 << 15) | (k1 >>> 17);
40
+ k1 = Math.imul(k1, c2);
41
+ h1 ^= k1;
42
+ }
43
+
44
+ // Finalization avalanche mix (fmix32)
45
+ h1 ^= len;
46
+ h1 ^= h1 >>> 16;
47
+ h1 = Math.imul(h1, 0x85ebca6b);
48
+ h1 ^= h1 >>> 13;
49
+ h1 = Math.imul(h1, 0xc2b2ae35);
50
+ h1 ^= h1 >>> 16;
51
+
52
+ return h1 >>> 0;
53
+ }
54
+
55
+ export interface BloomFilterStats {
56
+ bitsSet: number;
57
+ fillFactor: number;
58
+ }
59
+
60
+ /**
61
+ * Pure TypeScript Bloom filter backed by a Uint8Array bitset.
62
+ * Uses Murmur3 double-hashing (Kirsch-Mitzenmacher technique):
63
+ * h_i(x) = (h1(x) + i * h2(x)) % m
64
+ *
65
+ * Zero Buffer dependency — runs identically in Node.js, Edge Isolates, and Browsers.
66
+ */
67
+ export class Murmur3BloomFilter {
68
+ private readonly bits: Uint8Array;
69
+ readonly numBits: number;
70
+ readonly k: number;
71
+ private readonly _maxCapacity: number;
72
+ private _insertionCount = 0;
73
+
74
+ /**
75
+ * @param numBits Total bits in the filter (default: 100,000 bits = 12.5 KB)
76
+ * @param k Number of hash probes per key (default: 7, targeting ~1% FPR at 2,000 items)
77
+ */
78
+ constructor(numBits = 100_000, k = 7) {
79
+ this.numBits = Math.max(64, numBits);
80
+ this.k = Math.max(1, k);
81
+ this.bits = new Uint8Array(Math.ceil(this.numBits / 8));
82
+ const p = 0.01;
83
+ this._maxCapacity = Math.floor(-this.numBits * Math.log(1 - Math.pow(p, 1 / this.k)) / this.k);
84
+ }
85
+
86
+ private setBit(bitIndex: number): void {
87
+ const byteIndex = bitIndex >>> 3;
88
+ this.bits[byteIndex] |= 1 << (bitIndex & 7);
89
+ }
90
+
91
+ private getBit(bitIndex: number): boolean {
92
+ const byteIndex = bitIndex >>> 3;
93
+ return (this.bits[byteIndex] & (1 << (bitIndex & 7))) !== 0;
94
+ }
95
+
96
+ /**
97
+ * Adds a key to the Bloom filter.
98
+ */
99
+ add(key: string): void {
100
+ if (key.length === 0) return;
101
+ const h1 = murmur3_32(key, 0);
102
+ const h2 = murmur3_32(key, 0x9747b28c) || 1; // ensure non-zero step
103
+ const m = this.numBits;
104
+
105
+ for (let i = 0; i < this.k; i++) {
106
+ const bit = ((h1 + Math.imul(i, h2)) >>> 0) % m;
107
+ this.setBit(bit);
108
+ }
109
+ this._insertionCount++;
110
+ }
111
+
112
+ /**
113
+ * Tests whether a key might be in the set.
114
+ * Returns `false` for guaranteed misses, `true` for possible hits.
115
+ */
116
+ mightContain(key: string): boolean {
117
+ if (key.length === 0) return true;
118
+ const h1 = murmur3_32(key, 0);
119
+ const h2 = murmur3_32(key, 0x9747b28c) || 1;
120
+ const m = this.numBits;
121
+
122
+ for (let i = 0; i < this.k; i++) {
123
+ const bit = ((h1 + Math.imul(i, h2)) >>> 0) % m;
124
+ if (!this.getBit(bit)) return false;
125
+ }
126
+ return true;
127
+ }
128
+
129
+ /**
130
+ * Clears all set bits in the filter.
131
+ */
132
+ reset(): void {
133
+ this.bits.fill(0);
134
+ this._insertionCount = 0;
135
+ }
136
+
137
+ /**
138
+ * Rebuilds the filter from a collection of keys.
139
+ */
140
+ rebuild(keys: Iterable<string>): void {
141
+ this.reset();
142
+ for (const key of keys) {
143
+ this.add(key);
144
+ }
145
+ }
146
+
147
+ /**
148
+ * Total add() calls since creation or last reset.
149
+ */
150
+ get insertions(): number {
151
+ return this._insertionCount;
152
+ }
153
+
154
+ /**
155
+ * Maximum safe insertions before false positive rate exceeds target ~1%.
156
+ */
157
+ get maxCapacity(): number {
158
+ return this._maxCapacity;
159
+ }
160
+
161
+ /**
162
+ * Returns current bit saturation metrics.
163
+ */
164
+ get stats(): BloomFilterStats {
165
+ let bitsSet = 0;
166
+ const len = this.bits.length;
167
+ for (let i = 0; i < len; i++) {
168
+ let b = this.bits[i];
169
+ while (b) {
170
+ bitsSet++;
171
+ b &= b - 1;
172
+ }
173
+ }
174
+ return {
175
+ bitsSet,
176
+ fillFactor: bitsSet / this.numBits,
177
+ };
178
+ }
179
+ }
package/src/encryption.ts CHANGED
@@ -33,7 +33,17 @@
33
33
  * TRIC1XOR | key⊕data[N] ← XOR
34
34
  */
35
35
 
36
- import { createCipheriv, createDecipheriv, createSecretKey, randomFillSync, type KeyObject } from 'crypto';
36
+ import {
37
+ createCipheriv,
38
+ createDecipheriv,
39
+ createSecretKey,
40
+ randomFillSync,
41
+ constants,
42
+ publicEncrypt,
43
+ privateDecrypt,
44
+ randomBytes,
45
+ type KeyObject,
46
+ } from 'crypto';
37
47
  import { type ILogger, consoleLogger } from './types';
38
48
 
39
49
  // ── Public type ───────────────────────────────────────────────────────────────
@@ -201,20 +211,20 @@ export class CacheEncryption {
201
211
  throw new Error('XOR key must be at least 1 byte');
202
212
  }
203
213
  this._key = buf;
204
- if (mode !== 'xor') {
214
+ if (resolvedMode !== 'xor') {
205
215
  this._keyObj = createSecretKey(buf);
206
216
  // Pre-warm OpenSSL's lazy key-schedule cache: first use of a KeyObject is slower
207
217
  // because OpenSSL initialises internal state on demand. Paying that cost now
208
218
  // (at construction) guarantees every production encrypt/decrypt call is fast.
209
219
  const _wc = createCipheriv(
210
- mode,
220
+ resolvedMode,
211
221
  this._keyObj,
212
- Buffer.alloc(mode === 'aes-128-ctr' ? CTR_IV_BYTES : IV_BYTES),
222
+ Buffer.alloc(resolvedMode === 'aes-128-ctr' ? CTR_IV_BYTES : IV_BYTES),
213
223
  );
214
224
  _wc.update(Buffer.alloc(0));
215
225
  _wc.final();
216
226
  }
217
- if (mode === 'xor') {
227
+ if (resolvedMode === 'xor') {
218
228
  logger.warn(
219
229
  'Cache obfuscation enabled (XOR). WARNING: XOR is NOT cryptographic — use only for dev or non-sensitive data.',
220
230
  );
@@ -511,3 +521,115 @@ export class CacheEncryption {
511
521
  return plain;
512
522
  }
513
523
  }
524
+
525
+ // ── Envelope Encryption (Asymmetric RSA-OAEP / KMS) ───────────────────────────
526
+
527
+ /** "TRICENV1" — Asymmetric Envelope Encrypted blob */
528
+ export const MAGIC_ENVELOPE = Buffer.from([0x54, 0x52, 0x49, 0x43, 0x45, 0x4e, 0x56, 0x31]);
529
+
530
+ export interface EnvelopeEncryptionOptions {
531
+ /** RSA public key (PEM string, KeyObject, or Buffer) for encrypting ephemeral snapshot DEKs via RSA-OAEP (SHA-256) */
532
+ publicKey?: string | KeyObject | Buffer;
533
+ /** RSA private key (PEM string, KeyObject, or Buffer) for decrypting ephemeral snapshot DEKs via RSA-OAEP (SHA-256) */
534
+ privateKey?: string | KeyObject | Buffer;
535
+ /** Optional custom KMS encrypt hook for cloud HSM / KMS integration */
536
+ kmsEncrypt?: (dek: Buffer) => Promise<Buffer> | Buffer;
537
+ /** Optional custom KMS decrypt hook for cloud HSM / KMS integration */
538
+ kmsDecrypt?: (encryptedDek: Buffer) => Promise<Buffer> | Buffer;
539
+ }
540
+
541
+ /**
542
+ * EnvelopeEncryption — Asymmetric envelope encryption for remote snapshots and cold backups.
543
+ *
544
+ * Encrypts payload with an ephemeral 256-bit AES-GCM data encryption key (DEK),
545
+ * then wraps the DEK using asymmetric RSA-OAEP (SHA-256) or a custom KMS hook.
546
+ *
547
+ * Storage format:
548
+ * [MAGIC "TRICENV1" (8B)] | [keyLen (4B BE)] | [encryptedDEK (N bytes)] | [iv (12B)] | [tag (16B)] | [ciphertext (M bytes)]
549
+ */
550
+ export class EnvelopeEncryption {
551
+ static isEnvelope(data: Buffer): boolean {
552
+ return data.length >= MAGIC_LEN && data.subarray(0, MAGIC_LEN).equals(MAGIC_ENVELOPE);
553
+ }
554
+
555
+ static async encrypt(data: Buffer, options: EnvelopeEncryptionOptions): Promise<Buffer> {
556
+ const dek = randomBytes(32);
557
+ let encryptedKey: Buffer;
558
+
559
+ if (options.kmsEncrypt) {
560
+ encryptedKey = await options.kmsEncrypt(dek);
561
+ } else if (options.publicKey) {
562
+ encryptedKey = publicEncrypt(
563
+ {
564
+ key: options.publicKey as any,
565
+ padding: constants.RSA_PKCS1_OAEP_PADDING,
566
+ oaepHash: 'sha256',
567
+ },
568
+ dek,
569
+ );
570
+ } else {
571
+ throw new Error('EnvelopeEncryption: either publicKey or kmsEncrypt must be provided to encrypt');
572
+ }
573
+
574
+ const iv = randomBytes(IV_BYTES);
575
+ const cipher = createCipheriv('aes-256-gcm', dek, iv);
576
+ const ct = cipher.update(data);
577
+ cipher.final();
578
+ const tag = cipher.getAuthTag();
579
+
580
+ const keyLen = encryptedKey.length;
581
+ const out = Buffer.allocUnsafe(MAGIC_LEN + 4 + keyLen + IV_BYTES + TAG_BYTES + ct.length);
582
+
583
+ MAGIC_ENVELOPE.copy(out, 0);
584
+ out.writeUInt32BE(keyLen, MAGIC_LEN);
585
+ encryptedKey.copy(out, MAGIC_LEN + 4);
586
+ iv.copy(out, MAGIC_LEN + 4 + keyLen);
587
+ tag.copy(out, MAGIC_LEN + 4 + keyLen + IV_BYTES);
588
+ ct.copy(out, MAGIC_LEN + 4 + keyLen + IV_BYTES + TAG_BYTES);
589
+
590
+ return out;
591
+ }
592
+
593
+ static async decrypt(data: Buffer, options: EnvelopeEncryptionOptions): Promise<Buffer> {
594
+ if (!this.isEnvelope(data)) {
595
+ throw new Error('EnvelopeEncryption: invalid header, expected TRICENV1');
596
+ }
597
+
598
+ if (data.length < MAGIC_LEN + 4 + IV_BYTES + TAG_BYTES) {
599
+ throw new Error('EnvelopeEncryption: truncated envelope buffer');
600
+ }
601
+
602
+ const keyLen = data.readUInt32BE(MAGIC_LEN);
603
+ const minExpected = MAGIC_LEN + 4 + keyLen + IV_BYTES + TAG_BYTES;
604
+ if (data.length < minExpected) {
605
+ throw new Error('EnvelopeEncryption: truncated envelope buffer (key length mismatch)');
606
+ }
607
+
608
+ const encryptedKey = data.subarray(MAGIC_LEN + 4, MAGIC_LEN + 4 + keyLen);
609
+ const iv = data.subarray(MAGIC_LEN + 4 + keyLen, MAGIC_LEN + 4 + keyLen + IV_BYTES);
610
+ const tag = data.subarray(MAGIC_LEN + 4 + keyLen + IV_BYTES, MAGIC_LEN + 4 + keyLen + IV_BYTES + TAG_BYTES);
611
+ const ct = data.subarray(MAGIC_LEN + 4 + keyLen + IV_BYTES + TAG_BYTES);
612
+
613
+ let dek: Buffer;
614
+ if (options.kmsDecrypt) {
615
+ dek = await options.kmsDecrypt(encryptedKey);
616
+ } else if (options.privateKey) {
617
+ dek = privateDecrypt(
618
+ {
619
+ key: options.privateKey as any,
620
+ padding: constants.RSA_PKCS1_OAEP_PADDING,
621
+ oaepHash: 'sha256',
622
+ },
623
+ encryptedKey,
624
+ );
625
+ } else {
626
+ throw new Error('EnvelopeEncryption: either privateKey or kmsDecrypt must be provided to decrypt');
627
+ }
628
+
629
+ const decipher = createDecipheriv('aes-256-gcm', dek, iv);
630
+ decipher.setAuthTag(tag);
631
+ const pt = decipher.update(ct);
632
+ decipher.final();
633
+ return pt;
634
+ }
635
+ }