tricache 0.7.0 → 0.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.
Files changed (100) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +144 -1428
  3. package/bin/tricache.js +8 -8
  4. package/dashboards/tricache-alerts.yaml +54 -0
  5. package/dashboards/tricache-grafana.json +548 -0
  6. package/dist/cache-service-5MZXFIGK.js +12 -0
  7. package/dist/cache-service-CyLdpo77.d.ts +871 -0
  8. package/dist/{chunk-3XQUQBOZ.js → chunk-6PQ5MOWR.js} +2950 -523
  9. package/dist/chunk-7RV5ZVBB.js +1023 -0
  10. package/dist/{chunk-PFB5FMEY.js → chunk-LJ5QJB5O.js} +116 -20
  11. package/dist/chunk-QNU7B43J.js +687 -0
  12. package/dist/chunk-UGD4VEPD.js +138 -0
  13. package/dist/chunk-XZL45ABR.js +108 -0
  14. package/dist/chunk-ZTSWCFYO.js +135 -0
  15. package/dist/cli.cjs +2894 -518
  16. package/dist/cli.d.ts +1 -0
  17. package/dist/cli.js +103 -5
  18. package/dist/dashboard/index.cjs +1065 -0
  19. package/dist/dashboard/index.d.ts +183 -0
  20. package/dist/dashboard/index.js +22 -0
  21. package/dist/drizzle/index.cjs +2648 -508
  22. package/dist/drizzle/index.d.ts +3 -1
  23. package/dist/drizzle/index.js +1 -1
  24. package/dist/edge/index.cjs +1498 -0
  25. package/dist/edge/index.d.ts +127 -0
  26. package/dist/edge/index.js +1109 -0
  27. package/dist/hono-DQRS1Xd7.d.ts +370 -0
  28. package/dist/http/index.cjs +3038 -589
  29. package/dist/http/index.d.ts +109 -23
  30. package/dist/http/index.js +238 -62
  31. package/dist/index.cjs +6962 -2487
  32. package/dist/index.d.ts +547 -30
  33. package/dist/index.js +104 -5
  34. package/dist/murmur3-CMGw9PbV.d.ts +98 -0
  35. package/dist/nestjs/index.cjs +2586 -498
  36. package/dist/nestjs/index.d.ts +3 -1
  37. package/dist/nestjs/index.js +6 -3
  38. package/dist/next/index.cjs +2633 -519
  39. package/dist/next/index.d.ts +13 -7
  40. package/dist/next/index.js +45 -18
  41. package/dist/prisma/index.cjs +2 -1
  42. package/dist/prisma/index.d.ts +3 -1
  43. package/dist/prisma/index.js +2 -1
  44. package/dist/serialize-worker.cjs +31 -19
  45. package/dist/serialize-worker.js +1 -1
  46. package/dist/{cache-service-BblHuF3i.d.ts → types-B6krw64X.d.ts} +605 -646
  47. package/package.json +37 -7
  48. package/src/adapters/auto-pipeliner.ts +206 -0
  49. package/src/adapters/node-redis.ts +370 -0
  50. package/src/cache-service.ts +4231 -3226
  51. package/src/cli.ts +261 -143
  52. package/src/codec.ts +72 -0
  53. package/src/compression.ts +56 -63
  54. package/src/cross-region.ts +245 -0
  55. package/src/dashboard/handler.ts +392 -0
  56. package/src/dashboard/html.ts +594 -0
  57. package/src/dashboard/index.ts +195 -0
  58. package/src/dashboard/types.ts +96 -0
  59. package/src/disk-tier.ts +1223 -821
  60. package/src/drizzle/index.ts +86 -86
  61. package/src/edge/adapters/cloudflare-do.ts +130 -0
  62. package/src/edge/adapters/cloudflare-kv.ts +115 -0
  63. package/src/edge/adapters/upstash.ts +143 -0
  64. package/src/edge/cache.ts +797 -0
  65. package/src/edge/crypto.ts +182 -0
  66. package/src/edge/hono.ts +203 -0
  67. package/src/edge/index.ts +37 -0
  68. package/src/edge/types.ts +230 -0
  69. package/src/edge/utils/base64.ts +63 -0
  70. package/src/edge/utils/murmur3.ts +179 -0
  71. package/src/encryption.ts +635 -493
  72. package/src/http/express.ts +195 -0
  73. package/src/http/fastify.ts +260 -0
  74. package/src/http/index.ts +46 -223
  75. package/src/http/utils.ts +92 -0
  76. package/src/index.ts +149 -47
  77. package/src/ipc-telemetry.ts +481 -0
  78. package/src/latency-watchdog.ts +282 -0
  79. package/src/nestjs/decorators.ts +161 -161
  80. package/src/nestjs/index.ts +23 -23
  81. package/src/nestjs/tricache.module.ts +104 -104
  82. package/src/nestjs/tricache.store.ts +97 -97
  83. package/src/nestjs/types.ts +79 -79
  84. package/src/next/cache-handler.ts +271 -244
  85. package/src/next/index.ts +37 -37
  86. package/src/next/isr-handler.ts +105 -105
  87. package/src/next/types.ts +130 -130
  88. package/src/prisma/index.ts +154 -151
  89. package/src/remote-snapshot.ts +153 -0
  90. package/src/serialize-worker.ts +120 -120
  91. package/src/sigv4-snapshot-adapter.ts +260 -0
  92. package/src/smart-memory-cache.ts +1109 -1024
  93. package/src/types.ts +1199 -902
  94. package/src/utils/cgroup.ts +100 -0
  95. package/src/utils/tracing.ts +54 -0
  96. package/src/wasm/bloom-filter-wasm.ts +109 -102
  97. package/src/worker-pool.ts +299 -299
  98. package/src/wtiny-lfu.ts +624 -0
  99. package/dist/cache-service-AJASH5FX.js +0 -7
  100. package/dist/chunk-UBSR5UYA.js +0 -0
package/src/encryption.ts CHANGED
@@ -1,493 +1,635 @@
1
- /**
2
- * Encryption / obfuscation for L2 (Redis) values and disk snapshots at rest.
3
- *
4
- * Four modes are supported via the `encryptionMode` CacheOption:
5
- *
6
- * ┌──────────────┬────────────┬──────────────────────────────────────────────────────────────┐
7
- * │ Mode │ Key bytes │ Notes │
8
- * ├──────────────┼────────────┼──────────────────────────────────────────────────────────────┤
9
- * │ aes-256-gcm │ 32 │ Default. Authenticated encryption (AEAD). │
10
- * │ aes-128-gcm │ 16 │ ~15% faster than AES-256. AEAD. │
11
- * │ aes-128-ctr │ 16 │ Fastest cipher. AES-NI keystream, no auth tag. │
12
- * │ │ │ Use when integrity is guaranteed elsewhere (TLS, HMAC, etc.). │
13
- * │ xor │ any (≥ 1) │ XOR obfuscation ONLY — NOT cryptographic. │
14
- * │ │ │ Use only for dev or non-sensitive data. │
15
- * └──────────────┴────────────┴──────────────────────────────────────────────────────────────┘
16
- *
17
- * Key generation:
18
- * AES-256 (32 B): node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
19
- * AES-128 (16 B): node -e "console.log(require('crypto').randomBytes(16).toString('base64'))"
20
- * CTR (16 B): node -e "console.log(require('crypto').randomBytes(16).toString('base64'))"
21
- * XOR (any len): node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
22
- *
23
- * Redis envelope formats:
24
- * enc:v1:<base64(IV[12]|Tag[16]|CT)> ← AES-256-GCM
25
- * a128:v1:<base64(IV[12]|Tag[16]|CT)> ← AES-128-GCM
26
- * ctr:v1:<base64(IV[16]|CT)> ← AES-128-CTR (no auth tag)
27
- * xor:v1:<base64(key⊕data)> ← XOR (self-inverse)
28
- *
29
- * Disk envelope formats:
30
- * TRIC1ENC | IV[12] | Tag[16] | CT[N] ← AES-256-GCM
31
- * TRIC1128 | IV[12] | Tag[16] | CT[N] ← AES-128-GCM
32
- * TRIC1CTR | IV[16] | CT[N] ← AES-128-CTR (no auth tag)
33
- * TRIC1XOR | key⊕data[N] ← XOR
34
- */
35
-
36
- import { createCipheriv, createDecipheriv, createSecretKey, randomFillSync, type KeyObject } from 'crypto';
37
- import { type ILogger, consoleLogger } from './types';
38
-
39
- // ── Public type ───────────────────────────────────────────────────────────────
40
- /** Encryption algorithm used for L2 (Redis) values and disk-tier files. */
41
- export type EncryptionMode = 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
42
-
43
- // ── GCM constants ─────────────────────────────────────────────────────────────
44
- const IV_BYTES = 12; // 96-bit IV (NIST recommended for GCM)
45
- const TAG_BYTES = 16; // 128-bit auth tag
46
-
47
- // ── Redis prefixes ────────────────────────────────────────────────────────────
48
- const PREFIX_256 = 'enc:v1:'; // AES-256-GCM (legacy-compatible)
49
- const PREFIX_128 = 'a128:v1:'; // AES-128-GCM
50
- const PREFIX_XOR = 'xor:v1:'; // XOR obfuscation
51
-
52
- // ── Binary magic headers (8 bytes each) ──────────────────────────────────────
53
- /** "TRIC1ENC" — AES-256-GCM disk blob */
54
- const MAGIC_256 = Buffer.from([0x54, 0x52, 0x49, 0x43, 0x31, 0x45, 0x4e, 0x43]);
55
- /** "TRIC1128" — AES-128-GCM disk blob */
56
- const MAGIC_128 = Buffer.from([0x54, 0x52, 0x49, 0x43, 0x31, 0x31, 0x32, 0x38]);
57
- /** "TRIC1XOR" — XOR-obfuscated disk blob */
58
- const MAGIC_XOR = Buffer.from([0x54, 0x52, 0x49, 0x43, 0x31, 0x58, 0x4f, 0x52]);
59
- /** "TRIC1CTR" — AES-128-CTR disk blob */
60
- const MAGIC_CTR = Buffer.from([0x54, 0x52, 0x49, 0x43, 0x31, 0x43, 0x54, 0x52]);
61
-
62
- const MAGIC_LEN = 8;
63
-
64
- // ── CTR constants ─────────────────────────────────────────────────────────────
65
- /** AES-128-CTR IV is the full 128-bit AES block used as the initial counter block. */
66
- const CTR_IV_BYTES = 16;
67
- const PREFIX_CTR = 'ctr:v1:'; // AES-128-CTR (no auth tag)
68
-
69
- // ── IV pool ───────────────────────────────────────────────────────────────────
70
- // randomFillSync() fills the existing Buffer in-place — no allocation on refill.
71
- const IV_POOL_COUNT = 64;
72
-
73
- export class CacheEncryption {
74
- private _key: Buffer | null = null; // raw bytes — used only for XOR
75
- private _keyObj: KeyObject | null = null; // parsed KeyObject — used for all AES modes
76
- private _mode: EncryptionMode;
77
- private _prevKey: Buffer | null = null;
78
- private _prevKeyObj: KeyObject | null = null;
79
- private _prevMode: EncryptionMode = 'aes-256-gcm';
80
-
81
- // Pre-allocated GCM IV pool — 12-byte IVs (96-bit, NIST recommended).
82
- private readonly _ivPool = Buffer.allocUnsafe(IV_BYTES * IV_POOL_COUNT);
83
- private _ivOffset = IV_BYTES * IV_POOL_COUNT; // start exhausted → fill on first use
84
-
85
- /** Return the next unique 12-byte IV slice from the pre-allocated GCM pool. */
86
- private _nextIV(): Buffer {
87
- if (this._ivOffset >= this._ivPool.length) {
88
- randomFillSync(this._ivPool); // fills existing Buffer in-place — zero allocation
89
- this._ivOffset = 0;
90
- }
91
- const iv = this._ivPool.subarray(this._ivOffset, this._ivOffset + IV_BYTES); // Buffer (not Uint8Array)
92
- this._ivOffset += IV_BYTES;
93
- return iv;
94
- }
95
-
96
- // Pre-allocated CTR IV pool — 16-byte IVs (full AES block = initial counter block).
97
- private readonly _ctrIvPool = Buffer.allocUnsafe(CTR_IV_BYTES * IV_POOL_COUNT);
98
- private _ctrIvOffset = CTR_IV_BYTES * IV_POOL_COUNT;
99
-
100
- /** Return the next unique 16-byte IV slice from the pre-allocated CTR pool. */
101
- private _nextCtrIV(): Buffer {
102
- if (this._ctrIvOffset >= this._ctrIvPool.length) {
103
- randomFillSync(this._ctrIvPool);
104
- this._ctrIvOffset = 0;
105
- }
106
- const iv = this._ctrIvPool.subarray(this._ctrIvOffset, this._ctrIvOffset + CTR_IV_BYTES);
107
- this._ctrIvOffset += CTR_IV_BYTES;
108
- return iv;
109
- }
110
-
111
- /**
112
- * XOR `data` with the key, cycling through key bytes.
113
- * Self-inverse: _xorBuffer(_xorBuffer(x)) === x.
114
- *
115
- * Fast path: Uint32Array views over the existing Buffer memory — zero copy,
116
- * no method-call overhead. V8 JITs `out32[i] = data32[i] ^ key32[...]`
117
- * to a single `XOR r32, r32` instruction. Requires 4-byte-aligned byteOffsets,
118
- * which Node.js guarantees (pool rounds up to 8 bytes; direct allocs to page).
119
- *
120
- * WARNING: XOR is NOT cryptographic. It provides obfuscation only.
121
- */
122
- private _xorBuffer(data: Buffer): Buffer {
123
- const key = this._key!;
124
- const klen = key.length;
125
- const len = data.length;
126
- const out = Buffer.allocUnsafe(len);
127
-
128
- if (
129
- klen % 4 === 0 &&
130
- len >= 4 &&
131
- data.byteOffset % 4 === 0 &&
132
- out.byteOffset % 4 === 0 &&
133
- key.byteOffset % 4 === 0
134
- ) {
135
- const wordCount = len >>> 2;
136
- const data32 = new Uint32Array(data.buffer, data.byteOffset, wordCount);
137
- const out32 = new Uint32Array(out.buffer, out.byteOffset, wordCount);
138
- const key32 = new Uint32Array(key.buffer, key.byteOffset, klen >>> 2);
139
- const kLen32 = key32.length;
140
- for (let i = 0; i < wordCount; i++) {
141
- out32[i] = data32[i] ^ key32[i % kLen32];
142
- }
143
- // 0–3 trailing bytes
144
- for (let i = wordCount << 2; i < len; i++) {
145
- out[i] = data[i] ^ key[i % klen];
146
- }
147
- return out;
148
- }
149
-
150
- // Fallback: buffer not 4-byte-aligned or key length not a multiple of 4
151
- for (let i = 0; i < len; i++) {
152
- out[i] = data[i] ^ key[i % klen];
153
- }
154
- return out;
155
- }
156
-
157
- constructor(
158
- keyBase64: string | undefined,
159
- loggerOrMode: ILogger | EncryptionMode = consoleLogger,
160
- mode: EncryptionMode = 'aes-256-gcm',
161
- previousKeyBase64?: string,
162
- previousMode?: EncryptionMode,
163
- ) {
164
- const logger: ILogger = (typeof loggerOrMode === 'object' && loggerOrMode !== null)
165
- ? loggerOrMode
166
- : consoleLogger;
167
- const resolvedMode: EncryptionMode = typeof loggerOrMode === 'string'
168
- ? loggerOrMode
169
- : mode;
170
-
171
- this._mode = resolvedMode;
172
- if (!keyBase64) {
173
- if (process.env.NODE_ENV === 'production') {
174
- logger.warn(
175
- 'SECURITY: encryption key not set — cache data stored unencrypted at rest',
176
- { hint: 'Set encryptionKey option or CACHE_ENCRYPTION_KEY env var' },
177
- );
178
- }
179
- return;
180
- }
181
- try {
182
- const buf = Buffer.from(keyBase64, 'base64');
183
- const requiredLen = resolvedMode === 'aes-256-gcm' ? 32 : (resolvedMode === 'aes-128-gcm' || resolvedMode === 'aes-128-ctr') ? 16 : 0;
184
- if (requiredLen > 0 && buf.length !== requiredLen) {
185
- throw new Error(`${mode} requires exactly ${requiredLen} bytes (got ${buf.length})`);
186
- }
187
- if (buf.length < 1) {
188
- throw new Error('XOR key must be at least 1 byte');
189
- }
190
- this._key = buf;
191
- if (mode !== 'xor') {
192
- this._keyObj = createSecretKey(buf);
193
- // Pre-warm OpenSSL's lazy key-schedule cache: first use of a KeyObject is slower
194
- // because OpenSSL initialises internal state on demand. Paying that cost now
195
- // (at construction) guarantees every production encrypt/decrypt call is fast.
196
- const _wc = createCipheriv(
197
- mode,
198
- this._keyObj,
199
- Buffer.alloc(mode === 'aes-128-ctr' ? CTR_IV_BYTES : IV_BYTES),
200
- );
201
- _wc.update(Buffer.alloc(0));
202
- _wc.final();
203
- }
204
- if (mode === 'xor') {
205
- logger.warn(
206
- 'Cache obfuscation enabled (XOR). WARNING: XOR is NOT cryptographic — use only for dev or non-sensitive data.',
207
- );
208
- } else {
209
- logger.debug(`Cache encryption enabled (${mode.toUpperCase()})`);
210
- }
211
- } catch (err) {
212
- logger.error('Invalid encryption key — falling back to plaintext', {}, err as Error);
213
- }
214
-
215
- if (previousKeyBase64) {
216
- try {
217
- this._prevMode = previousMode ?? mode;
218
- this._prevKey = Buffer.from(previousKeyBase64, 'base64');
219
- if (this._prevMode !== 'xor') {
220
- this._prevKeyObj = createSecretKey(this._prevKey);
221
- const _wc = createCipheriv(
222
- this._prevMode,
223
- this._prevKeyObj,
224
- Buffer.alloc(this._prevMode === 'aes-128-ctr' ? CTR_IV_BYTES : IV_BYTES),
225
- );
226
- _wc.update(Buffer.alloc(0));
227
- _wc.final();
228
- }
229
- logger.debug('Previous encryption key loaded for key rotation fallback');
230
- } catch (err) {
231
- logger.warn('Invalid previousEncryptionKey — rotation fallback disabled', { error: (err as Error).message });
232
- }
233
- }
234
- }
235
-
236
- get isEnabled(): boolean { return this._key !== null; }
237
- get mode(): EncryptionMode { return this._mode; }
238
-
239
- /**
240
- * Snapshot the key material needed to spin up an off-main-thread worker pool.
241
- * Replaces the previously-used `as unknown as { _key, _mode, … }` private-field
242
- * cast in cache-service.ts — the worker pool reads these via this accessor
243
- * instead of reaching into underscore-prefixed internals.
244
- */
245
- toWorkerInit(): {
246
- keyBase64: string;
247
- mode: EncryptionMode;
248
- prevKeyBase64: string | undefined;
249
- prevMode: EncryptionMode;
250
- } {
251
- return {
252
- keyBase64: this._key ? this._key.toString('base64') : '',
253
- mode: this._mode,
254
- prevKeyBase64: this._prevKey ? this._prevKey.toString('base64') : undefined,
255
- prevMode: this._prevMode,
256
- };
257
- }
258
-
259
- /**
260
- * Rotate the active encryption key dynamically at runtime.
261
- * Promotes the current primary key to previousEncryptionKey for zero-downtime
262
- * fallback decryption of existing cache entries in L2/Disk, and installs
263
- * the new key as primary for all subsequent writes.
264
- */
265
- rotateKey(newKeyBase64: string, newMode?: EncryptionMode): void {
266
- if (!newKeyBase64) {
267
- throw new Error('rotateKey requires a valid non-empty base64 key');
268
- }
269
- const mode = newMode ?? this._mode;
270
- const buf = Buffer.from(newKeyBase64, 'base64');
271
- const requiredLen = mode === 'aes-256-gcm' ? 32 : (mode === 'aes-128-gcm' || mode === 'aes-128-ctr') ? 16 : 0;
272
- if (requiredLen > 0 && buf.length !== requiredLen) {
273
- throw new Error(`${mode} requires exactly ${requiredLen} bytes (got ${buf.length})`);
274
- }
275
- if (buf.length < 1) {
276
- throw new Error('XOR key must be at least 1 byte');
277
- }
278
-
279
- let newKeyObj: KeyObject | null = null;
280
- if (mode !== 'xor') {
281
- newKeyObj = createSecretKey(buf);
282
- const _wc = createCipheriv(
283
- mode,
284
- newKeyObj,
285
- Buffer.alloc(mode === 'aes-128-ctr' ? CTR_IV_BYTES : IV_BYTES),
286
- );
287
- _wc.update(Buffer.alloc(0));
288
- _wc.final();
289
- }
290
-
291
- // Shift current primary to previous key
292
- this._prevKey = this._key;
293
- this._prevKeyObj = this._keyObj;
294
- this._prevMode = this._mode;
295
-
296
- // Set new primary key
297
- this._key = buf;
298
- this._keyObj = newKeyObj;
299
- this._mode = mode;
300
- }
301
-
302
- // ── String (Redis) ────────────────────────────────────────────────────────
303
-
304
- /**
305
- * Encrypt a string for Redis storage.
306
- * Returns a mode-prefixed base64 string when a key is configured;
307
- * otherwise returns the original string unchanged (backward-compatible).
308
- */
309
- encrypt(plaintext: string): string {
310
- if (!this._key) return plaintext;
311
- if (this._mode === 'xor') {
312
- // WARNING: XOR is NOT cryptographic — obfuscation only.
313
- const masked = this._xorBuffer(Buffer.from(plaintext, 'utf8'));
314
- return PREFIX_XOR + masked.toString('base64');
315
- }
316
- if (this._mode === 'aes-128-ctr') {
317
- const iv = this._nextCtrIV();
318
- const c = createCipheriv('aes-128-ctr', this._keyObj!, iv);
319
- const enc = c.update(plaintext, 'utf8');
320
- const fin = c.final(); // CTR: almost always empty — captured defensively
321
- const out = Buffer.allocUnsafe(CTR_IV_BYTES + enc.length + fin.length);
322
- iv.copy(out, 0);
323
- enc.copy(out, CTR_IV_BYTES);
324
- if (fin.length > 0) fin.copy(out, CTR_IV_BYTES + enc.length);
325
- return PREFIX_CTR + out.toString('base64');
326
- }
327
- const algo = this._mode === 'aes-128-gcm' ? 'aes-128-gcm' : 'aes-256-gcm';
328
- const prefix = this._mode === 'aes-128-gcm' ? PREFIX_128 : PREFIX_256;
329
- const iv = this._nextIV();
330
- const c = createCipheriv(algo, this._keyObj!, iv);
331
- const enc = c.update(plaintext, 'utf8'); // GCM: final() emits no bytes
332
- c.final(); // finalise — makes auth tag available
333
- const out = Buffer.allocUnsafe(IV_BYTES + TAG_BYTES + enc.length);
334
- iv.copy(out, 0);
335
- c.getAuthTag().copy(out, IV_BYTES);
336
- enc.copy(out, IV_BYTES + TAG_BYTES);
337
- return prefix + out.toString('base64');
338
- }
339
-
340
- /**
341
- * Decrypt a Redis value.
342
- * Auto-detects the envelope prefix; returns plaintext unchanged if no prefix matches.
343
- * Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
344
- */
345
- decrypt(value: string): string {
346
- try {
347
- return this._decryptWithKey(value, this._key, this._keyObj);
348
- } catch (primaryErr) {
349
- if (this._prevKey) {
350
- try {
351
- return this._decryptWithKey(value, this._prevKey, this._prevKeyObj);
352
- } catch { /* ignore — fall through to re-throw primary */ }
353
- }
354
- throw primaryErr;
355
- }
356
- }
357
-
358
- private _decryptWithKey(value: string, key: Buffer | null, keyObj: KeyObject | null): string {
359
- if (value.startsWith(PREFIX_XOR)) {
360
- if (!key) throw new Error('Cannot decrypt: encryption key is not set');
361
- // WARNING: XOR is NOT cryptographic — obfuscation only.
362
- const masked = Buffer.from(value.slice(PREFIX_XOR.length), 'base64');
363
- // XOR is self-inverse; use the provided key regardless of mode
364
- const klen = key.length;
365
- const len = masked.length;
366
- const out = Buffer.allocUnsafe(len);
367
- for (let i = 0; i < len; i++) out[i] = masked[i] ^ key[i % klen];
368
- return out.toString('utf8');
369
- }
370
- if (value.startsWith(PREFIX_CTR)) {
371
- if (!keyObj) throw new Error('Cannot decrypt: encryption key is not set');
372
- const combined = Buffer.from(value.slice(PREFIX_CTR.length), 'base64');
373
- const iv = combined.subarray(0, CTR_IV_BYTES);
374
- const ct = combined.subarray(CTR_IV_BYTES);
375
- const d = createDecipheriv('aes-128-ctr', keyObj, iv);
376
- const plain = d.update(ct);
377
- const fin = d.final(); // CTR: almost always empty — concat before UTF-8 decode to avoid split-sequence corruption
378
- return (fin.length > 0 ? Buffer.concat([plain, fin]) : plain).toString('utf8');
379
- }
380
- const is256 = value.startsWith(PREFIX_256);
381
- const is128 = value.startsWith(PREFIX_128);
382
- if (!is256 && !is128) return value;
383
- if (!keyObj) throw new Error('Cannot decrypt: encryption key is not set');
384
- const prefix = is128 ? PREFIX_128 : PREFIX_256;
385
- const algo = is128 ? 'aes-128-gcm' : 'aes-256-gcm';
386
- const combined = Buffer.from(value.slice(prefix.length), 'base64');
387
- const iv = combined.subarray(0, IV_BYTES);
388
- const tag = combined.subarray(IV_BYTES, IV_BYTES + TAG_BYTES);
389
- const ct = combined.subarray(IV_BYTES + TAG_BYTES);
390
- const d = createDecipheriv(algo, keyObj, iv);
391
- d.setAuthTag(tag);
392
- const plain = d.update(ct); // GCM: final() emits no bytes
393
- d.final(); // verifies auth tag — throws on tamper
394
- return plain.toString('utf8');
395
- }
396
-
397
- // ── Buffer (disk / snapshot) ──────────────────────────────────────────────
398
-
399
- /** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
400
- encryptBuffer(data: Buffer): Buffer {
401
- if (!this._key) return data;
402
- if (this._mode === 'xor') {
403
- // WARNING: XOR is NOT cryptographic — obfuscation only.
404
- const masked = this._xorBuffer(data);
405
- const out = Buffer.allocUnsafe(MAGIC_LEN + masked.length);
406
- MAGIC_XOR.copy(out, 0);
407
- masked.copy(out, MAGIC_LEN);
408
- return out;
409
- }
410
- if (this._mode === 'aes-128-ctr') {
411
- const iv = this._nextCtrIV();
412
- const c = createCipheriv('aes-128-ctr', this._keyObj!, iv);
413
- const enc = c.update(data);
414
- const fin = c.final(); // CTR: almost always empty — captured defensively
415
- // Single pre-allocated output buffer: magic(8) | iv(16) | ciphertext(N)
416
- const out = Buffer.allocUnsafe(MAGIC_LEN + CTR_IV_BYTES + enc.length + fin.length);
417
- MAGIC_CTR.copy(out, 0);
418
- iv.copy(out, MAGIC_LEN);
419
- enc.copy(out, MAGIC_LEN + CTR_IV_BYTES);
420
- if (fin.length > 0) fin.copy(out, MAGIC_LEN + CTR_IV_BYTES + enc.length);
421
- return out;
422
- }
423
- const magic = this._mode === 'aes-128-gcm' ? MAGIC_128 : MAGIC_256;
424
- const algo = this._mode === 'aes-128-gcm' ? 'aes-128-gcm' : 'aes-256-gcm';
425
- const iv = this._nextIV();
426
- const c = createCipheriv(algo, this._keyObj!, iv);
427
- const enc = c.update(data); // GCM: final() emits no bytes
428
- c.final(); // finalise — makes auth tag available
429
- // Single pre-allocated output buffer: magic(8) | iv(12) | tag(16) | ciphertext(N)
430
- const out = Buffer.allocUnsafe(MAGIC_LEN + IV_BYTES + TAG_BYTES + enc.length);
431
- magic.copy(out, 0);
432
- iv.copy(out, MAGIC_LEN);
433
- c.getAuthTag().copy(out, MAGIC_LEN + IV_BYTES);
434
- enc.copy(out, MAGIC_LEN + IV_BYTES + TAG_BYTES);
435
- return out;
436
- }
437
-
438
- /**
439
- * Decrypt a raw Buffer from disk/snapshot.
440
- * Auto-detects the magic header; returns the original buffer if no magic matches (legacy/unencrypted).
441
- * Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
442
- */
443
- decryptBuffer(data: Buffer): Buffer {
444
- try {
445
- return this._decryptBufferWithKey(data, this._key, this._keyObj);
446
- } catch (primaryErr) {
447
- if (this._prevKey) {
448
- try {
449
- return this._decryptBufferWithKey(data, this._prevKey, this._prevKeyObj);
450
- } catch { /* ignore — re-throw primary */ }
451
- }
452
- throw primaryErr;
453
- }
454
- }
455
-
456
- private _decryptBufferWithKey(data: Buffer, key: Buffer | null, keyObj: KeyObject | null): Buffer {
457
- if (data.length < MAGIC_LEN) return data;
458
- const magic = data.subarray(0, MAGIC_LEN);
459
-
460
- if (magic.equals(MAGIC_XOR)) {
461
- if (!key) throw new Error('Cannot decrypt buffer: encryption key is not set');
462
- // WARNING: XOR is NOT cryptographic — obfuscation only.
463
- const raw = data.subarray(MAGIC_LEN);
464
- const klen = key.length;
465
- const out = Buffer.allocUnsafe(raw.length);
466
- for (let i = 0; i < raw.length; i++) out[i] = raw[i] ^ key[i % klen];
467
- return out;
468
- }
469
-
470
- if (magic.equals(MAGIC_CTR)) {
471
- if (!keyObj) throw new Error('Cannot decrypt buffer: encryption key is not set');
472
- const iv = data.subarray(MAGIC_LEN, MAGIC_LEN + CTR_IV_BYTES);
473
- const ct = data.subarray(MAGIC_LEN + CTR_IV_BYTES);
474
- const d = createDecipheriv('aes-128-ctr', keyObj, iv);
475
- const plain = d.update(ct);
476
- const fin = d.final(); // CTR: almost always empty — captured defensively
477
- return fin.length > 0 ? Buffer.concat([plain, fin]) : plain;
478
- }
479
- const is256 = magic.equals(MAGIC_256);
480
- const is128 = magic.equals(MAGIC_128);
481
- if (!is256 && !is128) return data;
482
- if (!keyObj) throw new Error('Cannot decrypt buffer: encryption key is not set');
483
- const algo = is128 ? 'aes-128-gcm' : 'aes-256-gcm';
484
- const iv = data.subarray(MAGIC_LEN, MAGIC_LEN + IV_BYTES);
485
- const tag = data.subarray(MAGIC_LEN + IV_BYTES, MAGIC_LEN + IV_BYTES + TAG_BYTES);
486
- const ct = data.subarray(MAGIC_LEN + IV_BYTES + TAG_BYTES);
487
- const d = createDecipheriv(algo, keyObj, iv);
488
- d.setAuthTag(tag);
489
- const plain = d.update(ct); // GCM: final() emits no bytes
490
- d.final(); // verifies auth tag — throws on tamper
491
- return plain;
492
- }
493
- }
1
+ /**
2
+ * Encryption / obfuscation for L2 (Redis) values and disk snapshots at rest.
3
+ *
4
+ * Four modes are supported via the `encryptionMode` CacheOption:
5
+ *
6
+ * ┌──────────────┬────────────┬──────────────────────────────────────────────────────────────┐
7
+ * │ Mode │ Key bytes │ Notes │
8
+ * ├──────────────┼────────────┼──────────────────────────────────────────────────────────────┤
9
+ * │ aes-256-gcm │ 32 │ Default. Authenticated encryption (AEAD). │
10
+ * │ aes-128-gcm │ 16 │ ~15% faster than AES-256. AEAD. │
11
+ * │ aes-128-ctr │ 16 │ Fastest cipher. AES-NI keystream, no auth tag. │
12
+ * │ │ │ Use when integrity is guaranteed elsewhere (TLS, HMAC, etc.). │
13
+ * │ xor │ any (≥ 1) │ XOR obfuscation ONLY — NOT cryptographic. │
14
+ * │ │ │ Use only for dev or non-sensitive data. │
15
+ * └──────────────┴────────────┴──────────────────────────────────────────────────────────────┘
16
+ *
17
+ * Key generation:
18
+ * AES-256 (32 B): node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
19
+ * AES-128 (16 B): node -e "console.log(require('crypto').randomBytes(16).toString('base64'))"
20
+ * CTR (16 B): node -e "console.log(require('crypto').randomBytes(16).toString('base64'))"
21
+ * XOR (any len): node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
22
+ *
23
+ * Redis envelope formats:
24
+ * enc:v1:<base64(IV[12]|Tag[16]|CT)> ← AES-256-GCM
25
+ * a128:v1:<base64(IV[12]|Tag[16]|CT)> ← AES-128-GCM
26
+ * ctr:v1:<base64(IV[16]|CT)> ← AES-128-CTR (no auth tag)
27
+ * xor:v1:<base64(key⊕data)> ← XOR (self-inverse)
28
+ *
29
+ * Disk envelope formats:
30
+ * TRIC1ENC | IV[12] | Tag[16] | CT[N] ← AES-256-GCM
31
+ * TRIC1128 | IV[12] | Tag[16] | CT[N] ← AES-128-GCM
32
+ * TRIC1CTR | IV[16] | CT[N] ← AES-128-CTR (no auth tag)
33
+ * TRIC1XOR | key⊕data[N] ← XOR
34
+ */
35
+
36
+ import {
37
+ createCipheriv,
38
+ createDecipheriv,
39
+ createSecretKey,
40
+ randomFillSync,
41
+ constants,
42
+ publicEncrypt,
43
+ privateDecrypt,
44
+ randomBytes,
45
+ type KeyObject,
46
+ } from 'crypto';
47
+ import { type ILogger, consoleLogger } from './types';
48
+
49
+ // ── Public type ───────────────────────────────────────────────────────────────
50
+ /** Encryption algorithm used for L2 (Redis) values and disk-tier files. */
51
+ export type EncryptionMode = 'aes-256-gcm' | 'aes-128-gcm' | 'aes-128-ctr' | 'xor';
52
+
53
+ // ── GCM constants ─────────────────────────────────────────────────────────────
54
+ const IV_BYTES = 12; // 96-bit IV (NIST recommended for GCM)
55
+ const TAG_BYTES = 16; // 128-bit auth tag
56
+
57
+ // ── Redis prefixes ────────────────────────────────────────────────────────────
58
+ const PREFIX_256 = 'enc:v1:'; // AES-256-GCM (legacy-compatible)
59
+ const PREFIX_128 = 'a128:v1:'; // AES-128-GCM
60
+ const PREFIX_XOR = 'xor:v1:'; // XOR obfuscation
61
+
62
+ // ── Binary magic headers (8 bytes each) ──────────────────────────────────────
63
+ /** "TRIC1ENC" — AES-256-GCM disk blob */
64
+ const MAGIC_256 = Buffer.from([0x54, 0x52, 0x49, 0x43, 0x31, 0x45, 0x4e, 0x43]);
65
+ /** "TRIC1128" — AES-128-GCM disk blob */
66
+ const MAGIC_128 = Buffer.from([0x54, 0x52, 0x49, 0x43, 0x31, 0x31, 0x32, 0x38]);
67
+ /** "TRIC1XOR" — XOR-obfuscated disk blob */
68
+ const MAGIC_XOR = Buffer.from([0x54, 0x52, 0x49, 0x43, 0x31, 0x58, 0x4f, 0x52]);
69
+ /** "TRIC1CTR" — AES-128-CTR disk blob */
70
+ const MAGIC_CTR = Buffer.from([0x54, 0x52, 0x49, 0x43, 0x31, 0x43, 0x54, 0x52]);
71
+
72
+ const MAGIC_LEN = 8;
73
+
74
+ // ── CTR constants ─────────────────────────────────────────────────────────────
75
+ /** AES-128-CTR IV is the full 128-bit AES block used as the initial counter block. */
76
+ const CTR_IV_BYTES = 16;
77
+ const PREFIX_CTR = 'ctr:v1:'; // AES-128-CTR (no auth tag)
78
+
79
+ // ── IV pool ───────────────────────────────────────────────────────────────────
80
+ // randomFillSync() fills the existing Buffer in-place — no allocation on refill.
81
+ const IV_POOL_COUNT = 64;
82
+
83
+ export class CacheEncryption {
84
+ private _key: Buffer | null = null; // raw bytes — used only for XOR
85
+ private _keyObj: KeyObject | null = null; // parsed KeyObject — used for all AES modes
86
+ private _mode: EncryptionMode;
87
+ /** Fail-closed on invalid key material when opted in via constructor opts. */
88
+ private readonly _strictKeyValidation: boolean;
89
+ private _prevKey: Buffer | null = null;
90
+ private _prevKeyObj: KeyObject | null = null;
91
+ private _prevMode: EncryptionMode = 'aes-256-gcm';
92
+
93
+ // Pre-allocated GCM IV pool — 12-byte IVs (96-bit, NIST recommended).
94
+ private readonly _ivPool = Buffer.allocUnsafe(IV_BYTES * IV_POOL_COUNT);
95
+ private _ivOffset = IV_BYTES * IV_POOL_COUNT; // start exhausted → fill on first use
96
+
97
+ /** Return the next unique 12-byte IV slice from the pre-allocated GCM pool. */
98
+ private _nextIV(): Buffer {
99
+ if (this._ivOffset >= this._ivPool.length) {
100
+ randomFillSync(this._ivPool); // fills existing Buffer in-place — zero allocation
101
+ this._ivOffset = 0;
102
+ }
103
+ const iv = this._ivPool.subarray(this._ivOffset, this._ivOffset + IV_BYTES); // Buffer (not Uint8Array)
104
+ this._ivOffset += IV_BYTES;
105
+ return iv;
106
+ }
107
+
108
+ // Pre-allocated CTR IV pool — 16-byte IVs (full AES block = initial counter block).
109
+ private readonly _ctrIvPool = Buffer.allocUnsafe(CTR_IV_BYTES * IV_POOL_COUNT);
110
+ private _ctrIvOffset = CTR_IV_BYTES * IV_POOL_COUNT;
111
+
112
+ /** Return the next unique 16-byte IV slice from the pre-allocated CTR pool. */
113
+ private _nextCtrIV(): Buffer {
114
+ if (this._ctrIvOffset >= this._ctrIvPool.length) {
115
+ randomFillSync(this._ctrIvPool);
116
+ this._ctrIvOffset = 0;
117
+ }
118
+ const iv = this._ctrIvPool.subarray(this._ctrIvOffset, this._ctrIvOffset + CTR_IV_BYTES);
119
+ this._ctrIvOffset += CTR_IV_BYTES;
120
+ return iv;
121
+ }
122
+
123
+ /**
124
+ * XOR `data` with the key, cycling through key bytes.
125
+ * Self-inverse: _xorBuffer(_xorBuffer(x)) === x.
126
+ *
127
+ * Fast path: Uint32Array views over the existing Buffer memory — zero copy,
128
+ * no method-call overhead. V8 JITs `out32[i] = data32[i] ^ key32[...]`
129
+ * to a single `XOR r32, r32` instruction. Requires 4-byte-aligned byteOffsets,
130
+ * which Node.js guarantees (pool rounds up to 8 bytes; direct allocs to page).
131
+ *
132
+ * WARNING: XOR is NOT cryptographic. It provides obfuscation only.
133
+ */
134
+ private _xorBuffer(data: Buffer): Buffer {
135
+ const key = this._key!;
136
+ const klen = key.length;
137
+ const len = data.length;
138
+ const out = Buffer.allocUnsafe(len);
139
+
140
+ if (
141
+ klen % 4 === 0 &&
142
+ len >= 4 &&
143
+ data.byteOffset % 4 === 0 &&
144
+ out.byteOffset % 4 === 0 &&
145
+ key.byteOffset % 4 === 0
146
+ ) {
147
+ const wordCount = len >>> 2;
148
+ const data32 = new Uint32Array(data.buffer, data.byteOffset, wordCount);
149
+ const out32 = new Uint32Array(out.buffer, out.byteOffset, wordCount);
150
+ const key32 = new Uint32Array(key.buffer, key.byteOffset, klen >>> 2);
151
+ const kLen32 = key32.length;
152
+ for (let i = 0; i < wordCount; i++) {
153
+ out32[i] = data32[i] ^ key32[i % kLen32];
154
+ }
155
+ // 0–3 trailing bytes
156
+ for (let i = wordCount << 2; i < len; i++) {
157
+ out[i] = data[i] ^ key[i % klen];
158
+ }
159
+ return out;
160
+ }
161
+
162
+ // Fallback: buffer not 4-byte-aligned or key length not a multiple of 4
163
+ for (let i = 0; i < len; i++) {
164
+ out[i] = data[i] ^ key[i % klen];
165
+ }
166
+ return out;
167
+ }
168
+
169
+ constructor(
170
+ keyBase64: string | undefined,
171
+ loggerOrMode: ILogger | EncryptionMode = consoleLogger,
172
+ mode: EncryptionMode = 'aes-256-gcm',
173
+ previousKeyBase64?: string,
174
+ previousMode?: EncryptionMode,
175
+ opts?: { strictKeyValidation?: boolean },
176
+ ) {
177
+ const logger: ILogger = (typeof loggerOrMode === 'object' && loggerOrMode !== null)
178
+ ? loggerOrMode
179
+ : consoleLogger;
180
+ const resolvedMode: EncryptionMode = typeof loggerOrMode === 'string'
181
+ ? loggerOrMode
182
+ : mode;
183
+ this._strictKeyValidation = opts?.strictKeyValidation ?? false;
184
+
185
+ this._mode = resolvedMode;
186
+ if (keyBase64 === undefined || keyBase64 === null) {
187
+ // Key not configured at all — warn (prod) and run without encryption.
188
+ if (process.env.NODE_ENV === 'production') {
189
+ logger.warn(
190
+ 'SECURITY: encryption key not set — cache data stored unencrypted at rest',
191
+ { hint: 'Set encryptionKey option or CACHE_ENCRYPTION_KEY env var' },
192
+ );
193
+ }
194
+ return;
195
+ }
196
+ if (keyBase64 === '') {
197
+ // Key EXPLICITLY configured but empty — always a configuration mistake.
198
+ // Strict mode fails closed; default logs loudly and continues unencrypted.
199
+ const err = new Error('Encryption key is empty — set encryptionKey option or CACHE_ENCRYPTION_KEY');
200
+ if (this._strictKeyValidation) throw err;
201
+ logger.error('Empty encryption key — falling back to plaintext', {}, err);
202
+ return;
203
+ }
204
+ try {
205
+ const buf = Buffer.from(keyBase64, 'base64');
206
+ const requiredLen = resolvedMode === 'aes-256-gcm' ? 32 : (resolvedMode === 'aes-128-gcm' || resolvedMode === 'aes-128-ctr') ? 16 : 0;
207
+ if (requiredLen > 0 && buf.length !== requiredLen) {
208
+ throw new Error(`${resolvedMode} requires exactly ${requiredLen} bytes (got ${buf.length})`);
209
+ }
210
+ if (buf.length < 1) {
211
+ throw new Error('XOR key must be at least 1 byte');
212
+ }
213
+ this._key = buf;
214
+ if (resolvedMode !== 'xor') {
215
+ this._keyObj = createSecretKey(buf);
216
+ // Pre-warm OpenSSL's lazy key-schedule cache: first use of a KeyObject is slower
217
+ // because OpenSSL initialises internal state on demand. Paying that cost now
218
+ // (at construction) guarantees every production encrypt/decrypt call is fast.
219
+ const _wc = createCipheriv(
220
+ resolvedMode,
221
+ this._keyObj,
222
+ Buffer.alloc(resolvedMode === 'aes-128-ctr' ? CTR_IV_BYTES : IV_BYTES),
223
+ );
224
+ _wc.update(Buffer.alloc(0));
225
+ _wc.final();
226
+ }
227
+ if (resolvedMode === 'xor') {
228
+ logger.warn(
229
+ 'Cache obfuscation enabled (XOR). WARNING: XOR is NOT cryptographic — use only for dev or non-sensitive data.',
230
+ );
231
+ } else {
232
+ logger.debug(`Cache encryption enabled (${mode.toUpperCase()})`);
233
+ }
234
+ } catch (err) {
235
+ // Fail-open by default (backward compat): log loudly and continue WITHOUT
236
+ // encryption rather than crashing every process that typo'd a key.
237
+ // strictKeyValidation opts into fail-closed for deployments where serving
238
+ // plaintext at rest is worse than failing startup (PCI/HIPAA-style bars).
239
+ if (this._strictKeyValidation) {
240
+ throw err;
241
+ }
242
+ logger.error('Invalid encryption key — falling back to plaintext', {}, err as Error);
243
+ }
244
+
245
+ if (previousKeyBase64) {
246
+ try {
247
+ this._prevMode = previousMode ?? mode;
248
+ this._prevKey = Buffer.from(previousKeyBase64, 'base64');
249
+ if (this._prevMode !== 'xor') {
250
+ this._prevKeyObj = createSecretKey(this._prevKey);
251
+ const _wc = createCipheriv(
252
+ this._prevMode,
253
+ this._prevKeyObj,
254
+ Buffer.alloc(this._prevMode === 'aes-128-ctr' ? CTR_IV_BYTES : IV_BYTES),
255
+ );
256
+ _wc.update(Buffer.alloc(0));
257
+ _wc.final();
258
+ }
259
+ logger.debug('Previous encryption key loaded for key rotation fallback');
260
+ } catch (err) {
261
+ logger.warn('Invalid previousEncryptionKey — rotation fallback disabled', { error: (err as Error).message });
262
+ }
263
+ }
264
+ }
265
+
266
+ get isEnabled(): boolean { return this._key !== null; }
267
+ get mode(): EncryptionMode { return this._mode; }
268
+
269
+ /**
270
+ * Snapshot the key material needed to spin up an off-main-thread worker pool.
271
+ * Replaces the previously-used `as unknown as { _key, _mode, … }` private-field
272
+ * cast in cache-service.ts — the worker pool reads these via this accessor
273
+ * instead of reaching into underscore-prefixed internals.
274
+ */
275
+ toWorkerInit(): {
276
+ keyBase64: string;
277
+ mode: EncryptionMode;
278
+ prevKeyBase64: string | undefined;
279
+ prevMode: EncryptionMode;
280
+ } {
281
+ return {
282
+ keyBase64: this._key ? this._key.toString('base64') : '',
283
+ mode: this._mode,
284
+ prevKeyBase64: this._prevKey ? this._prevKey.toString('base64') : undefined,
285
+ prevMode: this._prevMode,
286
+ };
287
+ }
288
+
289
+ /**
290
+ * Rotate the active encryption key dynamically at runtime.
291
+ * Promotes the current primary key to previousEncryptionKey for zero-downtime
292
+ * fallback decryption of existing cache entries in L2/Disk, and installs
293
+ * the new key as primary for all subsequent writes.
294
+ */
295
+ rotateKey(newKeyBase64: string, newMode?: EncryptionMode): void {
296
+ if (!newKeyBase64) {
297
+ throw new Error('rotateKey requires a valid non-empty base64 key');
298
+ }
299
+ const mode = newMode ?? this._mode;
300
+ const buf = Buffer.from(newKeyBase64, 'base64');
301
+ const requiredLen = mode === 'aes-256-gcm' ? 32 : (mode === 'aes-128-gcm' || mode === 'aes-128-ctr') ? 16 : 0;
302
+ if (requiredLen > 0 && buf.length !== requiredLen) {
303
+ throw new Error(`${mode} requires exactly ${requiredLen} bytes (got ${buf.length})`);
304
+ }
305
+ if (buf.length < 1) {
306
+ throw new Error('XOR key must be at least 1 byte');
307
+ }
308
+
309
+ let newKeyObj: KeyObject | null = null;
310
+ if (mode !== 'xor') {
311
+ newKeyObj = createSecretKey(buf);
312
+ const _wc = createCipheriv(
313
+ mode,
314
+ newKeyObj,
315
+ Buffer.alloc(mode === 'aes-128-ctr' ? CTR_IV_BYTES : IV_BYTES),
316
+ );
317
+ _wc.update(Buffer.alloc(0));
318
+ _wc.final();
319
+ }
320
+
321
+ // Shift current primary to previous key
322
+ this._prevKey = this._key;
323
+ this._prevKeyObj = this._keyObj;
324
+ this._prevMode = this._mode;
325
+
326
+ // Set new primary key
327
+ this._key = buf;
328
+ this._keyObj = newKeyObj;
329
+ this._mode = mode;
330
+ }
331
+
332
+ // ── String (Redis) ────────────────────────────────────────────────────────
333
+
334
+ /**
335
+ * Encrypt a string for Redis storage.
336
+ * Returns a mode-prefixed base64 string when a key is configured;
337
+ * otherwise returns the original string unchanged (backward-compatible).
338
+ */
339
+ encrypt(plaintext: string): string {
340
+ if (!this._key) return plaintext;
341
+ if (this._mode === 'xor') {
342
+ // WARNING: XOR is NOT cryptographic — obfuscation only.
343
+ const masked = this._xorBuffer(Buffer.from(plaintext, 'utf8'));
344
+ return PREFIX_XOR + masked.toString('base64');
345
+ }
346
+ if (this._mode === 'aes-128-ctr') {
347
+ const iv = this._nextCtrIV();
348
+ const c = createCipheriv('aes-128-ctr', this._keyObj!, iv);
349
+ const enc = c.update(plaintext, 'utf8');
350
+ const fin = c.final(); // CTR: almost always empty — captured defensively
351
+ const out = Buffer.allocUnsafe(CTR_IV_BYTES + enc.length + fin.length);
352
+ iv.copy(out, 0);
353
+ enc.copy(out, CTR_IV_BYTES);
354
+ if (fin.length > 0) fin.copy(out, CTR_IV_BYTES + enc.length);
355
+ return PREFIX_CTR + out.toString('base64');
356
+ }
357
+ const algo = this._mode === 'aes-128-gcm' ? 'aes-128-gcm' : 'aes-256-gcm';
358
+ const prefix = this._mode === 'aes-128-gcm' ? PREFIX_128 : PREFIX_256;
359
+ const iv = this._nextIV();
360
+ const c = createCipheriv(algo, this._keyObj!, iv);
361
+ const enc = c.update(plaintext, 'utf8'); // GCM: final() emits no bytes
362
+ c.final(); // finalise — makes auth tag available
363
+ const out = Buffer.allocUnsafe(IV_BYTES + TAG_BYTES + enc.length);
364
+ iv.copy(out, 0);
365
+ c.getAuthTag().copy(out, IV_BYTES);
366
+ enc.copy(out, IV_BYTES + TAG_BYTES);
367
+ return prefix + out.toString('base64');
368
+ }
369
+
370
+ /**
371
+ * Decrypt a Redis value.
372
+ * Auto-detects the envelope prefix; returns plaintext unchanged if no prefix matches.
373
+ * Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
374
+ */
375
+ decrypt(value: string): string {
376
+ try {
377
+ return this._decryptWithKey(value, this._key, this._keyObj);
378
+ } catch (primaryErr) {
379
+ if (this._prevKey) {
380
+ try {
381
+ return this._decryptWithKey(value, this._prevKey, this._prevKeyObj);
382
+ } catch { /* ignore — fall through to re-throw primary */ }
383
+ }
384
+ throw primaryErr;
385
+ }
386
+ }
387
+
388
+ private _decryptWithKey(value: string, key: Buffer | null, keyObj: KeyObject | null): string {
389
+ if (value.startsWith(PREFIX_XOR)) {
390
+ if (!key) throw new Error('Cannot decrypt: encryption key is not set');
391
+ // WARNING: XOR is NOT cryptographic — obfuscation only.
392
+ const masked = Buffer.from(value.slice(PREFIX_XOR.length), 'base64');
393
+ // XOR is self-inverse; use the provided key regardless of mode
394
+ const klen = key.length;
395
+ const len = masked.length;
396
+ const out = Buffer.allocUnsafe(len);
397
+ for (let i = 0; i < len; i++) out[i] = masked[i] ^ key[i % klen];
398
+ return out.toString('utf8');
399
+ }
400
+ if (value.startsWith(PREFIX_CTR)) {
401
+ if (!keyObj) throw new Error('Cannot decrypt: encryption key is not set');
402
+ const combined = Buffer.from(value.slice(PREFIX_CTR.length), 'base64');
403
+ const iv = combined.subarray(0, CTR_IV_BYTES);
404
+ const ct = combined.subarray(CTR_IV_BYTES);
405
+ const d = createDecipheriv('aes-128-ctr', keyObj, iv);
406
+ const plain = d.update(ct);
407
+ const fin = d.final(); // CTR: almost always empty — concat before UTF-8 decode to avoid split-sequence corruption
408
+ return (fin.length > 0 ? Buffer.concat([plain, fin]) : plain).toString('utf8');
409
+ }
410
+ const is256 = value.startsWith(PREFIX_256);
411
+ const is128 = value.startsWith(PREFIX_128);
412
+ if (!is256 && !is128) return value;
413
+ if (!keyObj) throw new Error('Cannot decrypt: encryption key is not set');
414
+ const prefix = is128 ? PREFIX_128 : PREFIX_256;
415
+ const algo = is128 ? 'aes-128-gcm' : 'aes-256-gcm';
416
+ const combined = Buffer.from(value.slice(prefix.length), 'base64');
417
+ const iv = combined.subarray(0, IV_BYTES);
418
+ const tag = combined.subarray(IV_BYTES, IV_BYTES + TAG_BYTES);
419
+ const ct = combined.subarray(IV_BYTES + TAG_BYTES);
420
+ const d = createDecipheriv(algo, keyObj, iv);
421
+ d.setAuthTag(tag);
422
+ const plain = d.update(ct); // GCM: final() emits no bytes
423
+ d.final(); // verifies auth tag — throws on tamper
424
+ return plain.toString('utf8');
425
+ }
426
+
427
+ // ── Buffer (disk / snapshot) ──────────────────────────────────────────────
428
+
429
+ /** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
430
+ encryptBuffer(data: Buffer): Buffer {
431
+ if (!this._key) return data;
432
+ if (this._mode === 'xor') {
433
+ // WARNING: XOR is NOT cryptographic — obfuscation only.
434
+ const masked = this._xorBuffer(data);
435
+ const out = Buffer.allocUnsafe(MAGIC_LEN + masked.length);
436
+ MAGIC_XOR.copy(out, 0);
437
+ masked.copy(out, MAGIC_LEN);
438
+ return out;
439
+ }
440
+ if (this._mode === 'aes-128-ctr') {
441
+ const iv = this._nextCtrIV();
442
+ const c = createCipheriv('aes-128-ctr', this._keyObj!, iv);
443
+ const enc = c.update(data);
444
+ const fin = c.final(); // CTR: almost always empty — captured defensively
445
+ // Single pre-allocated output buffer: magic(8) | iv(16) | ciphertext(N)
446
+ const out = Buffer.allocUnsafe(MAGIC_LEN + CTR_IV_BYTES + enc.length + fin.length);
447
+ MAGIC_CTR.copy(out, 0);
448
+ iv.copy(out, MAGIC_LEN);
449
+ enc.copy(out, MAGIC_LEN + CTR_IV_BYTES);
450
+ if (fin.length > 0) fin.copy(out, MAGIC_LEN + CTR_IV_BYTES + enc.length);
451
+ return out;
452
+ }
453
+ const magic = this._mode === 'aes-128-gcm' ? MAGIC_128 : MAGIC_256;
454
+ const algo = this._mode === 'aes-128-gcm' ? 'aes-128-gcm' : 'aes-256-gcm';
455
+ const iv = this._nextIV();
456
+ const c = createCipheriv(algo, this._keyObj!, iv);
457
+ const enc = c.update(data); // GCM: final() emits no bytes
458
+ c.final(); // finalise — makes auth tag available
459
+ // Single pre-allocated output buffer: magic(8) | iv(12) | tag(16) | ciphertext(N)
460
+ const out = Buffer.allocUnsafe(MAGIC_LEN + IV_BYTES + TAG_BYTES + enc.length);
461
+ magic.copy(out, 0);
462
+ iv.copy(out, MAGIC_LEN);
463
+ c.getAuthTag().copy(out, MAGIC_LEN + IV_BYTES);
464
+ enc.copy(out, MAGIC_LEN + IV_BYTES + TAG_BYTES);
465
+ return out;
466
+ }
467
+
468
+ /**
469
+ * Decrypt a raw Buffer from disk/snapshot.
470
+ * Auto-detects the magic header; returns the original buffer if no magic matches (legacy/unencrypted).
471
+ * Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
472
+ */
473
+ decryptBuffer(data: Buffer): Buffer {
474
+ try {
475
+ return this._decryptBufferWithKey(data, this._key, this._keyObj);
476
+ } catch (primaryErr) {
477
+ if (this._prevKey) {
478
+ try {
479
+ return this._decryptBufferWithKey(data, this._prevKey, this._prevKeyObj);
480
+ } catch { /* ignore — re-throw primary */ }
481
+ }
482
+ throw primaryErr;
483
+ }
484
+ }
485
+
486
+ private _decryptBufferWithKey(data: Buffer, key: Buffer | null, keyObj: KeyObject | null): Buffer {
487
+ if (data.length < MAGIC_LEN) return data;
488
+ const magic = data.subarray(0, MAGIC_LEN);
489
+
490
+ if (magic.equals(MAGIC_XOR)) {
491
+ if (!key) throw new Error('Cannot decrypt buffer: encryption key is not set');
492
+ // WARNING: XOR is NOT cryptographic — obfuscation only.
493
+ const raw = data.subarray(MAGIC_LEN);
494
+ const klen = key.length;
495
+ const out = Buffer.allocUnsafe(raw.length);
496
+ for (let i = 0; i < raw.length; i++) out[i] = raw[i] ^ key[i % klen];
497
+ return out;
498
+ }
499
+
500
+ if (magic.equals(MAGIC_CTR)) {
501
+ if (!keyObj) throw new Error('Cannot decrypt buffer: encryption key is not set');
502
+ const iv = data.subarray(MAGIC_LEN, MAGIC_LEN + CTR_IV_BYTES);
503
+ const ct = data.subarray(MAGIC_LEN + CTR_IV_BYTES);
504
+ const d = createDecipheriv('aes-128-ctr', keyObj, iv);
505
+ const plain = d.update(ct);
506
+ const fin = d.final(); // CTR: almost always empty — captured defensively
507
+ return fin.length > 0 ? Buffer.concat([plain, fin]) : plain;
508
+ }
509
+ const is256 = magic.equals(MAGIC_256);
510
+ const is128 = magic.equals(MAGIC_128);
511
+ if (!is256 && !is128) return data;
512
+ if (!keyObj) throw new Error('Cannot decrypt buffer: encryption key is not set');
513
+ const algo = is128 ? 'aes-128-gcm' : 'aes-256-gcm';
514
+ const iv = data.subarray(MAGIC_LEN, MAGIC_LEN + IV_BYTES);
515
+ const tag = data.subarray(MAGIC_LEN + IV_BYTES, MAGIC_LEN + IV_BYTES + TAG_BYTES);
516
+ const ct = data.subarray(MAGIC_LEN + IV_BYTES + TAG_BYTES);
517
+ const d = createDecipheriv(algo, keyObj, iv);
518
+ d.setAuthTag(tag);
519
+ const plain = d.update(ct); // GCM: final() emits no bytes
520
+ d.final(); // verifies auth tag — throws on tamper
521
+ return plain;
522
+ }
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
+ }