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/src/encryption.ts CHANGED
@@ -1,493 +1,513 @@
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 { 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
+ /** Fail-closed on invalid key material when opted in via constructor opts. */
78
+ private readonly _strictKeyValidation: boolean;
79
+ private _prevKey: Buffer | null = null;
80
+ private _prevKeyObj: KeyObject | null = null;
81
+ private _prevMode: EncryptionMode = 'aes-256-gcm';
82
+
83
+ // Pre-allocated GCM IV pool — 12-byte IVs (96-bit, NIST recommended).
84
+ private readonly _ivPool = Buffer.allocUnsafe(IV_BYTES * IV_POOL_COUNT);
85
+ private _ivOffset = IV_BYTES * IV_POOL_COUNT; // start exhausted → fill on first use
86
+
87
+ /** Return the next unique 12-byte IV slice from the pre-allocated GCM pool. */
88
+ private _nextIV(): Buffer {
89
+ if (this._ivOffset >= this._ivPool.length) {
90
+ randomFillSync(this._ivPool); // fills existing Buffer in-place — zero allocation
91
+ this._ivOffset = 0;
92
+ }
93
+ const iv = this._ivPool.subarray(this._ivOffset, this._ivOffset + IV_BYTES); // Buffer (not Uint8Array)
94
+ this._ivOffset += IV_BYTES;
95
+ return iv;
96
+ }
97
+
98
+ // Pre-allocated CTR IV pool — 16-byte IVs (full AES block = initial counter block).
99
+ private readonly _ctrIvPool = Buffer.allocUnsafe(CTR_IV_BYTES * IV_POOL_COUNT);
100
+ private _ctrIvOffset = CTR_IV_BYTES * IV_POOL_COUNT;
101
+
102
+ /** Return the next unique 16-byte IV slice from the pre-allocated CTR pool. */
103
+ private _nextCtrIV(): Buffer {
104
+ if (this._ctrIvOffset >= this._ctrIvPool.length) {
105
+ randomFillSync(this._ctrIvPool);
106
+ this._ctrIvOffset = 0;
107
+ }
108
+ const iv = this._ctrIvPool.subarray(this._ctrIvOffset, this._ctrIvOffset + CTR_IV_BYTES);
109
+ this._ctrIvOffset += CTR_IV_BYTES;
110
+ return iv;
111
+ }
112
+
113
+ /**
114
+ * XOR `data` with the key, cycling through key bytes.
115
+ * Self-inverse: _xorBuffer(_xorBuffer(x)) === x.
116
+ *
117
+ * Fast path: Uint32Array views over the existing Buffer memory — zero copy,
118
+ * no method-call overhead. V8 JITs `out32[i] = data32[i] ^ key32[...]`
119
+ * to a single `XOR r32, r32` instruction. Requires 4-byte-aligned byteOffsets,
120
+ * which Node.js guarantees (pool rounds up to 8 bytes; direct allocs to page).
121
+ *
122
+ * WARNING: XOR is NOT cryptographic. It provides obfuscation only.
123
+ */
124
+ private _xorBuffer(data: Buffer): Buffer {
125
+ const key = this._key!;
126
+ const klen = key.length;
127
+ const len = data.length;
128
+ const out = Buffer.allocUnsafe(len);
129
+
130
+ if (
131
+ klen % 4 === 0 &&
132
+ len >= 4 &&
133
+ data.byteOffset % 4 === 0 &&
134
+ out.byteOffset % 4 === 0 &&
135
+ key.byteOffset % 4 === 0
136
+ ) {
137
+ const wordCount = len >>> 2;
138
+ const data32 = new Uint32Array(data.buffer, data.byteOffset, wordCount);
139
+ const out32 = new Uint32Array(out.buffer, out.byteOffset, wordCount);
140
+ const key32 = new Uint32Array(key.buffer, key.byteOffset, klen >>> 2);
141
+ const kLen32 = key32.length;
142
+ for (let i = 0; i < wordCount; i++) {
143
+ out32[i] = data32[i] ^ key32[i % kLen32];
144
+ }
145
+ // 0–3 trailing bytes
146
+ for (let i = wordCount << 2; i < len; i++) {
147
+ out[i] = data[i] ^ key[i % klen];
148
+ }
149
+ return out;
150
+ }
151
+
152
+ // Fallback: buffer not 4-byte-aligned or key length not a multiple of 4
153
+ for (let i = 0; i < len; i++) {
154
+ out[i] = data[i] ^ key[i % klen];
155
+ }
156
+ return out;
157
+ }
158
+
159
+ constructor(
160
+ keyBase64: string | undefined,
161
+ loggerOrMode: ILogger | EncryptionMode = consoleLogger,
162
+ mode: EncryptionMode = 'aes-256-gcm',
163
+ previousKeyBase64?: string,
164
+ previousMode?: EncryptionMode,
165
+ opts?: { strictKeyValidation?: boolean },
166
+ ) {
167
+ const logger: ILogger = (typeof loggerOrMode === 'object' && loggerOrMode !== null)
168
+ ? loggerOrMode
169
+ : consoleLogger;
170
+ const resolvedMode: EncryptionMode = typeof loggerOrMode === 'string'
171
+ ? loggerOrMode
172
+ : mode;
173
+ this._strictKeyValidation = opts?.strictKeyValidation ?? false;
174
+
175
+ this._mode = resolvedMode;
176
+ if (keyBase64 === undefined || keyBase64 === null) {
177
+ // Key not configured at all — warn (prod) and run without encryption.
178
+ if (process.env.NODE_ENV === 'production') {
179
+ logger.warn(
180
+ 'SECURITY: encryption key not set — cache data stored unencrypted at rest',
181
+ { hint: 'Set encryptionKey option or CACHE_ENCRYPTION_KEY env var' },
182
+ );
183
+ }
184
+ return;
185
+ }
186
+ if (keyBase64 === '') {
187
+ // Key EXPLICITLY configured but empty — always a configuration mistake.
188
+ // Strict mode fails closed; default logs loudly and continues unencrypted.
189
+ const err = new Error('Encryption key is empty — set encryptionKey option or CACHE_ENCRYPTION_KEY');
190
+ if (this._strictKeyValidation) throw err;
191
+ logger.error('Empty encryption key — falling back to plaintext', {}, err);
192
+ return;
193
+ }
194
+ try {
195
+ const buf = Buffer.from(keyBase64, 'base64');
196
+ const requiredLen = resolvedMode === 'aes-256-gcm' ? 32 : (resolvedMode === 'aes-128-gcm' || resolvedMode === 'aes-128-ctr') ? 16 : 0;
197
+ if (requiredLen > 0 && buf.length !== requiredLen) {
198
+ throw new Error(`${resolvedMode} requires exactly ${requiredLen} bytes (got ${buf.length})`);
199
+ }
200
+ if (buf.length < 1) {
201
+ throw new Error('XOR key must be at least 1 byte');
202
+ }
203
+ this._key = buf;
204
+ if (mode !== 'xor') {
205
+ this._keyObj = createSecretKey(buf);
206
+ // Pre-warm OpenSSL's lazy key-schedule cache: first use of a KeyObject is slower
207
+ // because OpenSSL initialises internal state on demand. Paying that cost now
208
+ // (at construction) guarantees every production encrypt/decrypt call is fast.
209
+ const _wc = createCipheriv(
210
+ mode,
211
+ this._keyObj,
212
+ Buffer.alloc(mode === 'aes-128-ctr' ? CTR_IV_BYTES : IV_BYTES),
213
+ );
214
+ _wc.update(Buffer.alloc(0));
215
+ _wc.final();
216
+ }
217
+ if (mode === 'xor') {
218
+ logger.warn(
219
+ 'Cache obfuscation enabled (XOR). WARNING: XOR is NOT cryptographic — use only for dev or non-sensitive data.',
220
+ );
221
+ } else {
222
+ logger.debug(`Cache encryption enabled (${mode.toUpperCase()})`);
223
+ }
224
+ } catch (err) {
225
+ // Fail-open by default (backward compat): log loudly and continue WITHOUT
226
+ // encryption rather than crashing every process that typo'd a key.
227
+ // strictKeyValidation opts into fail-closed for deployments where serving
228
+ // plaintext at rest is worse than failing startup (PCI/HIPAA-style bars).
229
+ if (this._strictKeyValidation) {
230
+ throw err;
231
+ }
232
+ logger.error('Invalid encryption key — falling back to plaintext', {}, err as Error);
233
+ }
234
+
235
+ if (previousKeyBase64) {
236
+ try {
237
+ this._prevMode = previousMode ?? mode;
238
+ this._prevKey = Buffer.from(previousKeyBase64, 'base64');
239
+ if (this._prevMode !== 'xor') {
240
+ this._prevKeyObj = createSecretKey(this._prevKey);
241
+ const _wc = createCipheriv(
242
+ this._prevMode,
243
+ this._prevKeyObj,
244
+ Buffer.alloc(this._prevMode === 'aes-128-ctr' ? CTR_IV_BYTES : IV_BYTES),
245
+ );
246
+ _wc.update(Buffer.alloc(0));
247
+ _wc.final();
248
+ }
249
+ logger.debug('Previous encryption key loaded for key rotation fallback');
250
+ } catch (err) {
251
+ logger.warn('Invalid previousEncryptionKey — rotation fallback disabled', { error: (err as Error).message });
252
+ }
253
+ }
254
+ }
255
+
256
+ get isEnabled(): boolean { return this._key !== null; }
257
+ get mode(): EncryptionMode { return this._mode; }
258
+
259
+ /**
260
+ * Snapshot the key material needed to spin up an off-main-thread worker pool.
261
+ * Replaces the previously-used `as unknown as { _key, _mode, … }` private-field
262
+ * cast in cache-service.ts — the worker pool reads these via this accessor
263
+ * instead of reaching into underscore-prefixed internals.
264
+ */
265
+ toWorkerInit(): {
266
+ keyBase64: string;
267
+ mode: EncryptionMode;
268
+ prevKeyBase64: string | undefined;
269
+ prevMode: EncryptionMode;
270
+ } {
271
+ return {
272
+ keyBase64: this._key ? this._key.toString('base64') : '',
273
+ mode: this._mode,
274
+ prevKeyBase64: this._prevKey ? this._prevKey.toString('base64') : undefined,
275
+ prevMode: this._prevMode,
276
+ };
277
+ }
278
+
279
+ /**
280
+ * Rotate the active encryption key dynamically at runtime.
281
+ * Promotes the current primary key to previousEncryptionKey for zero-downtime
282
+ * fallback decryption of existing cache entries in L2/Disk, and installs
283
+ * the new key as primary for all subsequent writes.
284
+ */
285
+ rotateKey(newKeyBase64: string, newMode?: EncryptionMode): void {
286
+ if (!newKeyBase64) {
287
+ throw new Error('rotateKey requires a valid non-empty base64 key');
288
+ }
289
+ const mode = newMode ?? this._mode;
290
+ const buf = Buffer.from(newKeyBase64, 'base64');
291
+ const requiredLen = mode === 'aes-256-gcm' ? 32 : (mode === 'aes-128-gcm' || mode === 'aes-128-ctr') ? 16 : 0;
292
+ if (requiredLen > 0 && buf.length !== requiredLen) {
293
+ throw new Error(`${mode} requires exactly ${requiredLen} bytes (got ${buf.length})`);
294
+ }
295
+ if (buf.length < 1) {
296
+ throw new Error('XOR key must be at least 1 byte');
297
+ }
298
+
299
+ let newKeyObj: KeyObject | null = null;
300
+ if (mode !== 'xor') {
301
+ newKeyObj = createSecretKey(buf);
302
+ const _wc = createCipheriv(
303
+ mode,
304
+ newKeyObj,
305
+ Buffer.alloc(mode === 'aes-128-ctr' ? CTR_IV_BYTES : IV_BYTES),
306
+ );
307
+ _wc.update(Buffer.alloc(0));
308
+ _wc.final();
309
+ }
310
+
311
+ // Shift current primary to previous key
312
+ this._prevKey = this._key;
313
+ this._prevKeyObj = this._keyObj;
314
+ this._prevMode = this._mode;
315
+
316
+ // Set new primary key
317
+ this._key = buf;
318
+ this._keyObj = newKeyObj;
319
+ this._mode = mode;
320
+ }
321
+
322
+ // ── String (Redis) ────────────────────────────────────────────────────────
323
+
324
+ /**
325
+ * Encrypt a string for Redis storage.
326
+ * Returns a mode-prefixed base64 string when a key is configured;
327
+ * otherwise returns the original string unchanged (backward-compatible).
328
+ */
329
+ encrypt(plaintext: string): string {
330
+ if (!this._key) return plaintext;
331
+ if (this._mode === 'xor') {
332
+ // WARNING: XOR is NOT cryptographic — obfuscation only.
333
+ const masked = this._xorBuffer(Buffer.from(plaintext, 'utf8'));
334
+ return PREFIX_XOR + masked.toString('base64');
335
+ }
336
+ if (this._mode === 'aes-128-ctr') {
337
+ const iv = this._nextCtrIV();
338
+ const c = createCipheriv('aes-128-ctr', this._keyObj!, iv);
339
+ const enc = c.update(plaintext, 'utf8');
340
+ const fin = c.final(); // CTR: almost always empty — captured defensively
341
+ const out = Buffer.allocUnsafe(CTR_IV_BYTES + enc.length + fin.length);
342
+ iv.copy(out, 0);
343
+ enc.copy(out, CTR_IV_BYTES);
344
+ if (fin.length > 0) fin.copy(out, CTR_IV_BYTES + enc.length);
345
+ return PREFIX_CTR + out.toString('base64');
346
+ }
347
+ const algo = this._mode === 'aes-128-gcm' ? 'aes-128-gcm' : 'aes-256-gcm';
348
+ const prefix = this._mode === 'aes-128-gcm' ? PREFIX_128 : PREFIX_256;
349
+ const iv = this._nextIV();
350
+ const c = createCipheriv(algo, this._keyObj!, iv);
351
+ const enc = c.update(plaintext, 'utf8'); // GCM: final() emits no bytes
352
+ c.final(); // finalise — makes auth tag available
353
+ const out = Buffer.allocUnsafe(IV_BYTES + TAG_BYTES + enc.length);
354
+ iv.copy(out, 0);
355
+ c.getAuthTag().copy(out, IV_BYTES);
356
+ enc.copy(out, IV_BYTES + TAG_BYTES);
357
+ return prefix + out.toString('base64');
358
+ }
359
+
360
+ /**
361
+ * Decrypt a Redis value.
362
+ * Auto-detects the envelope prefix; returns plaintext unchanged if no prefix matches.
363
+ * Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
364
+ */
365
+ decrypt(value: string): string {
366
+ try {
367
+ return this._decryptWithKey(value, this._key, this._keyObj);
368
+ } catch (primaryErr) {
369
+ if (this._prevKey) {
370
+ try {
371
+ return this._decryptWithKey(value, this._prevKey, this._prevKeyObj);
372
+ } catch { /* ignore — fall through to re-throw primary */ }
373
+ }
374
+ throw primaryErr;
375
+ }
376
+ }
377
+
378
+ private _decryptWithKey(value: string, key: Buffer | null, keyObj: KeyObject | null): string {
379
+ if (value.startsWith(PREFIX_XOR)) {
380
+ if (!key) throw new Error('Cannot decrypt: encryption key is not set');
381
+ // WARNING: XOR is NOT cryptographic — obfuscation only.
382
+ const masked = Buffer.from(value.slice(PREFIX_XOR.length), 'base64');
383
+ // XOR is self-inverse; use the provided key regardless of mode
384
+ const klen = key.length;
385
+ const len = masked.length;
386
+ const out = Buffer.allocUnsafe(len);
387
+ for (let i = 0; i < len; i++) out[i] = masked[i] ^ key[i % klen];
388
+ return out.toString('utf8');
389
+ }
390
+ if (value.startsWith(PREFIX_CTR)) {
391
+ if (!keyObj) throw new Error('Cannot decrypt: encryption key is not set');
392
+ const combined = Buffer.from(value.slice(PREFIX_CTR.length), 'base64');
393
+ const iv = combined.subarray(0, CTR_IV_BYTES);
394
+ const ct = combined.subarray(CTR_IV_BYTES);
395
+ const d = createDecipheriv('aes-128-ctr', keyObj, iv);
396
+ const plain = d.update(ct);
397
+ const fin = d.final(); // CTR: almost always empty — concat before UTF-8 decode to avoid split-sequence corruption
398
+ return (fin.length > 0 ? Buffer.concat([plain, fin]) : plain).toString('utf8');
399
+ }
400
+ const is256 = value.startsWith(PREFIX_256);
401
+ const is128 = value.startsWith(PREFIX_128);
402
+ if (!is256 && !is128) return value;
403
+ if (!keyObj) throw new Error('Cannot decrypt: encryption key is not set');
404
+ const prefix = is128 ? PREFIX_128 : PREFIX_256;
405
+ const algo = is128 ? 'aes-128-gcm' : 'aes-256-gcm';
406
+ const combined = Buffer.from(value.slice(prefix.length), 'base64');
407
+ const iv = combined.subarray(0, IV_BYTES);
408
+ const tag = combined.subarray(IV_BYTES, IV_BYTES + TAG_BYTES);
409
+ const ct = combined.subarray(IV_BYTES + TAG_BYTES);
410
+ const d = createDecipheriv(algo, keyObj, iv);
411
+ d.setAuthTag(tag);
412
+ const plain = d.update(ct); // GCM: final() emits no bytes
413
+ d.final(); // verifies auth tag — throws on tamper
414
+ return plain.toString('utf8');
415
+ }
416
+
417
+ // ── Buffer (disk / snapshot) ──────────────────────────────────────────────
418
+
419
+ /** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
420
+ encryptBuffer(data: Buffer): Buffer {
421
+ if (!this._key) return data;
422
+ if (this._mode === 'xor') {
423
+ // WARNING: XOR is NOT cryptographic — obfuscation only.
424
+ const masked = this._xorBuffer(data);
425
+ const out = Buffer.allocUnsafe(MAGIC_LEN + masked.length);
426
+ MAGIC_XOR.copy(out, 0);
427
+ masked.copy(out, MAGIC_LEN);
428
+ return out;
429
+ }
430
+ if (this._mode === 'aes-128-ctr') {
431
+ const iv = this._nextCtrIV();
432
+ const c = createCipheriv('aes-128-ctr', this._keyObj!, iv);
433
+ const enc = c.update(data);
434
+ const fin = c.final(); // CTR: almost always empty — captured defensively
435
+ // Single pre-allocated output buffer: magic(8) | iv(16) | ciphertext(N)
436
+ const out = Buffer.allocUnsafe(MAGIC_LEN + CTR_IV_BYTES + enc.length + fin.length);
437
+ MAGIC_CTR.copy(out, 0);
438
+ iv.copy(out, MAGIC_LEN);
439
+ enc.copy(out, MAGIC_LEN + CTR_IV_BYTES);
440
+ if (fin.length > 0) fin.copy(out, MAGIC_LEN + CTR_IV_BYTES + enc.length);
441
+ return out;
442
+ }
443
+ const magic = this._mode === 'aes-128-gcm' ? MAGIC_128 : MAGIC_256;
444
+ const algo = this._mode === 'aes-128-gcm' ? 'aes-128-gcm' : 'aes-256-gcm';
445
+ const iv = this._nextIV();
446
+ const c = createCipheriv(algo, this._keyObj!, iv);
447
+ const enc = c.update(data); // GCM: final() emits no bytes
448
+ c.final(); // finalise — makes auth tag available
449
+ // Single pre-allocated output buffer: magic(8) | iv(12) | tag(16) | ciphertext(N)
450
+ const out = Buffer.allocUnsafe(MAGIC_LEN + IV_BYTES + TAG_BYTES + enc.length);
451
+ magic.copy(out, 0);
452
+ iv.copy(out, MAGIC_LEN);
453
+ c.getAuthTag().copy(out, MAGIC_LEN + IV_BYTES);
454
+ enc.copy(out, MAGIC_LEN + IV_BYTES + TAG_BYTES);
455
+ return out;
456
+ }
457
+
458
+ /**
459
+ * Decrypt a raw Buffer from disk/snapshot.
460
+ * Auto-detects the magic header; returns the original buffer if no magic matches (legacy/unencrypted).
461
+ * Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
462
+ */
463
+ decryptBuffer(data: Buffer): Buffer {
464
+ try {
465
+ return this._decryptBufferWithKey(data, this._key, this._keyObj);
466
+ } catch (primaryErr) {
467
+ if (this._prevKey) {
468
+ try {
469
+ return this._decryptBufferWithKey(data, this._prevKey, this._prevKeyObj);
470
+ } catch { /* ignore — re-throw primary */ }
471
+ }
472
+ throw primaryErr;
473
+ }
474
+ }
475
+
476
+ private _decryptBufferWithKey(data: Buffer, key: Buffer | null, keyObj: KeyObject | null): Buffer {
477
+ if (data.length < MAGIC_LEN) return data;
478
+ const magic = data.subarray(0, MAGIC_LEN);
479
+
480
+ if (magic.equals(MAGIC_XOR)) {
481
+ if (!key) throw new Error('Cannot decrypt buffer: encryption key is not set');
482
+ // WARNING: XOR is NOT cryptographic — obfuscation only.
483
+ const raw = data.subarray(MAGIC_LEN);
484
+ const klen = key.length;
485
+ const out = Buffer.allocUnsafe(raw.length);
486
+ for (let i = 0; i < raw.length; i++) out[i] = raw[i] ^ key[i % klen];
487
+ return out;
488
+ }
489
+
490
+ if (magic.equals(MAGIC_CTR)) {
491
+ if (!keyObj) throw new Error('Cannot decrypt buffer: encryption key is not set');
492
+ const iv = data.subarray(MAGIC_LEN, MAGIC_LEN + CTR_IV_BYTES);
493
+ const ct = data.subarray(MAGIC_LEN + CTR_IV_BYTES);
494
+ const d = createDecipheriv('aes-128-ctr', keyObj, iv);
495
+ const plain = d.update(ct);
496
+ const fin = d.final(); // CTR: almost always empty — captured defensively
497
+ return fin.length > 0 ? Buffer.concat([plain, fin]) : plain;
498
+ }
499
+ const is256 = magic.equals(MAGIC_256);
500
+ const is128 = magic.equals(MAGIC_128);
501
+ if (!is256 && !is128) return data;
502
+ if (!keyObj) throw new Error('Cannot decrypt buffer: encryption key is not set');
503
+ const algo = is128 ? 'aes-128-gcm' : 'aes-256-gcm';
504
+ const iv = data.subarray(MAGIC_LEN, MAGIC_LEN + IV_BYTES);
505
+ const tag = data.subarray(MAGIC_LEN + IV_BYTES, MAGIC_LEN + IV_BYTES + TAG_BYTES);
506
+ const ct = data.subarray(MAGIC_LEN + IV_BYTES + TAG_BYTES);
507
+ const d = createDecipheriv(algo, keyObj, iv);
508
+ d.setAuthTag(tag);
509
+ const plain = d.update(ct); // GCM: final() emits no bytes
510
+ d.final(); // verifies auth tag — throws on tamper
511
+ return plain;
512
+ }
513
+ }