tricache 0.6.0 โ 0.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +119 -0
- package/dist/chunk-F24NEZGQ.js +342 -0
- package/dist/index.cjs +494 -164
- package/dist/index.d.cts +125 -0
- package/dist/index.d.ts +1552 -18
- package/dist/index.js +3524 -25
- package/dist/serialize-worker.cjs +366 -0
- package/dist/serialize-worker.d.cts +2 -0
- package/dist/serialize-worker.d.ts +2 -0
- package/dist/serialize-worker.js +35 -0
- package/package.json +5 -5
- package/src/cache-service.ts +310 -93
- package/src/serialize-worker.ts +56 -0
- package/src/smart-memory-cache.ts +42 -1
- package/src/types.ts +99 -1
- package/src/worker-pool.ts +190 -0
- package/dist/cache-service.d.ts +0 -419
- package/dist/cache-service.d.ts.map +0 -1
- package/dist/cache-service.js +0 -1788
- package/dist/cache-service.js.map +0 -1
- package/dist/disk-tier.d.ts +0 -150
- package/dist/disk-tier.d.ts.map +0 -1
- package/dist/disk-tier.js +0 -808
- package/dist/disk-tier.js.map +0 -1
- package/dist/encryption.d.ts +0 -90
- package/dist/encryption.d.ts.map +0 -1
- package/dist/encryption.js +0 -393
- package/dist/encryption.js.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/smart-memory-cache.d.ts +0 -208
- package/dist/smart-memory-cache.d.ts.map +0 -1
- package/dist/smart-memory-cache.js +0 -933
- package/dist/smart-memory-cache.js.map +0 -1
- package/dist/types.d.ts +0 -537
- package/dist/types.d.ts.map +0 -1
- package/dist/types.js +0 -20
- package/dist/types.js.map +0 -1
- package/dist/wasm/bloom-filter-wasm.d.ts +0 -29
- package/dist/wasm/bloom-filter-wasm.d.ts.map +0 -1
- package/dist/wasm/bloom-filter-wasm.js +0 -83
- package/dist/wasm/bloom-filter-wasm.js.map +0 -1
package/README.md
CHANGED
|
@@ -713,6 +713,125 @@ CacheService.create({
|
|
|
713
713
|
|
|
714
714
|
---
|
|
715
715
|
|
|
716
|
+
## ๐งต Worker thread crypto offload
|
|
717
|
+
|
|
718
|
+
By default, AES-GCM encryption/decryption runs synchronously on the V8 main thread. For payloads above a configurable size threshold this blocks the event loop for measurable durations. Enable worker thread offload to move encryption off the main thread:
|
|
719
|
+
|
|
720
|
+
```typescript
|
|
721
|
+
CacheService.create({
|
|
722
|
+
encryptionKey: process.env.CACHE_ENCRYPTION_KEY,
|
|
723
|
+
workerThreads: true, // enable off-main-thread crypto
|
|
724
|
+
workerThresholdBytes: 131_072, // only offload payloads โฅ 128 KB (default)
|
|
725
|
+
workerPoolSize: 4, // threads; 0 = auto (min(4, logical CPUs))
|
|
726
|
+
});
|
|
727
|
+
```
|
|
728
|
+
|
|
729
|
+
**How it works:**
|
|
730
|
+
- A fixed-size pool of Node.js `worker_threads` is created at startup; each worker holds an initialised `CacheEncryption` instance.
|
|
731
|
+
- Dispatch is round-robin; inter-thread IPC carries only strings (structured-clone fast path).
|
|
732
|
+
- Workers are `unref()`'d โ they do not prevent the process from exiting cleanly.
|
|
733
|
+
- If worker initialisation fails the pool is silently disabled and synchronous crypto is used as a fallback โ zero configuration required in environments where workers are unavailable.
|
|
734
|
+
|
|
735
|
+
**When to enable:**
|
|
736
|
+
- Payloads routinely exceed a few hundred KB with encryption enabled.
|
|
737
|
+
- You observe event-loop lag correlated with L2 read/write operations in APM.
|
|
738
|
+
- Rule of thumb: the default 128 KB threshold keeps overhead negligible for typical API response payloads while protecting against multi-MB documents.
|
|
739
|
+
|
|
740
|
+
---
|
|
741
|
+
|
|
742
|
+
## ๐ Backplane staleness fence
|
|
743
|
+
|
|
744
|
+
Redis Pub/Sub has no delivery guarantees โ a subscriber disconnect (network blip, Redis failover, container restart) can cause peer invalidation messages to be silently dropped. Entries written to L1 between the disconnect and reconnect may silently serve stale data.
|
|
745
|
+
|
|
746
|
+
TriCache tracks when the subscriber disconnects and, on reconnect, compares the gap duration against `backplaneMaxStalenessMs`. If the gap exceeds the threshold, every L1 entry that was written before the disconnect is proactively evicted, forcing a controlled re-fetch from L2 on the next access:
|
|
747
|
+
|
|
748
|
+
```typescript
|
|
749
|
+
CacheService.create({
|
|
750
|
+
invalidationBackplane: true,
|
|
751
|
+
backplaneMaxStalenessMs: 5_000, // default: evict stale L1 on gaps > 5 s
|
|
752
|
+
});
|
|
753
|
+
```
|
|
754
|
+
|
|
755
|
+
Setting `backplaneMaxStalenessMs: 0` disables the fence entirely. The eviction count and gap duration are logged at `warn` level on every triggered flush.
|
|
756
|
+
|
|
757
|
+
---
|
|
758
|
+
|
|
759
|
+
## โ๏ธ Serverless / ephemeral disk environments
|
|
760
|
+
|
|
761
|
+
On Lambda, Cloud Run, Fly.io, Railway, and similar platforms, the filesystem (`os.tmpdir()`) is container-scoped and is wiped on every cold start. Disk spill and cold-start snapshots are therefore useless and waste I/O budget.
|
|
762
|
+
|
|
763
|
+
TriCache auto-detects serverless runtimes at construction time (zero I/O โ environment variable checks only) and automatically disables the disk tier:
|
|
764
|
+
|
|
765
|
+
| Runtime | Detection env var |
|
|
766
|
+
|---|---|
|
|
767
|
+
| AWS Lambda | `AWS_LAMBDA_FUNCTION_NAME` |
|
|
768
|
+
| Google Cloud Run | `K_SERVICE` |
|
|
769
|
+
| Google Cloud Functions | `FUNCTION_TARGET` |
|
|
770
|
+
| Azure Functions | `WEBSITE_INSTANCE_ID` |
|
|
771
|
+
| Fly.io | `FLY_APP_NAME` |
|
|
772
|
+
| Railway | `RAILWAY_ENVIRONMENT` |
|
|
773
|
+
| Vercel | `VERCEL` |
|
|
774
|
+
|
|
775
|
+
You can also control disk behaviour explicitly:
|
|
776
|
+
|
|
777
|
+
```typescript
|
|
778
|
+
// Force-disable disk tier (e.g., when running inside a Docker container with no writable tmpdir)
|
|
779
|
+
CacheService.create({ disableDisk: true });
|
|
780
|
+
|
|
781
|
+
// Force-enable disk tier even when a serverless env var is present (advanced override)
|
|
782
|
+
CacheService.create({ disableDisk: false });
|
|
783
|
+
```
|
|
784
|
+
|
|
785
|
+
When disk is disabled:
|
|
786
|
+
- The disk spill callback is a no-op.
|
|
787
|
+
- `disk.load()` / `disk.delete()` / `disk.clear()` are never called.
|
|
788
|
+
- `loadSnapshot()` and `writeSnapshot()` are skipped.
|
|
789
|
+
- The background disk janitor timer is not started.
|
|
790
|
+
- `metrics().disk.disabled` is `true`.
|
|
791
|
+
|
|
792
|
+
---
|
|
793
|
+
|
|
794
|
+
## ๐ด Redis Cluster and Sentinel
|
|
795
|
+
|
|
796
|
+
TriCache supports Redis Cluster (slot-based sharding) and Redis Sentinel (automatic primary failover) via ioredis built-in support.
|
|
797
|
+
|
|
798
|
+
### Redis Cluster
|
|
799
|
+
|
|
800
|
+
```typescript
|
|
801
|
+
CacheService.create({
|
|
802
|
+
redisClusterNodes: [
|
|
803
|
+
{ host: 'redis-node-1.example.com', port: 6379 },
|
|
804
|
+
{ host: 'redis-node-2.example.com', port: 6379 },
|
|
805
|
+
{ host: 'redis-node-3.example.com', port: 6379 },
|
|
806
|
+
],
|
|
807
|
+
redisTls: true,
|
|
808
|
+
});
|
|
809
|
+
```
|
|
810
|
+
|
|
811
|
+
ioredis handles slot routing, moved/ask redirects, and re-queuing commands during slot migrations transparently. You can list any subset of cluster nodes โ ioredis discovers the full topology automatically.
|
|
812
|
+
|
|
813
|
+
### Redis Sentinel
|
|
814
|
+
|
|
815
|
+
```typescript
|
|
816
|
+
CacheService.create({
|
|
817
|
+
redisSentinel: {
|
|
818
|
+
name: 'mymaster',
|
|
819
|
+
sentinels: [
|
|
820
|
+
{ host: 'sentinel-1.example.com', port: 26379 },
|
|
821
|
+
{ host: 'sentinel-2.example.com', port: 26379 },
|
|
822
|
+
{ host: 'sentinel-3.example.com', port: 26379 },
|
|
823
|
+
],
|
|
824
|
+
},
|
|
825
|
+
redisTls: true,
|
|
826
|
+
});
|
|
827
|
+
```
|
|
828
|
+
|
|
829
|
+
ioredis monitors the current master via the Sentinel topology and transparently reconnects to a new primary after failover. The backplane subscriber is also constructed in the appropriate cluster/sentinel mode.
|
|
830
|
+
|
|
831
|
+
> `redisHost` / `redisPort` are ignored when `redisClusterNodes` or `redisSentinel` is set. All three topology modes support `redisTls`.
|
|
832
|
+
|
|
833
|
+
---
|
|
834
|
+
|
|
716
835
|
## โก WASM Bloom filter
|
|
717
836
|
|
|
718
837
|
A 100,000-bit filter with k=7 hash probes:
|
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
2
|
+
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
3
|
+
}) : x)(function(x) {
|
|
4
|
+
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
5
|
+
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
6
|
+
});
|
|
7
|
+
|
|
8
|
+
// src/encryption.ts
|
|
9
|
+
import { createCipheriv, createDecipheriv, createSecretKey, randomFillSync } from "crypto";
|
|
10
|
+
var IV_BYTES = 12;
|
|
11
|
+
var TAG_BYTES = 16;
|
|
12
|
+
var PREFIX_256 = "enc:v1:";
|
|
13
|
+
var PREFIX_128 = "a128:v1:";
|
|
14
|
+
var PREFIX_XOR = "xor:v1:";
|
|
15
|
+
var MAGIC_256 = Buffer.from([84, 82, 73, 67, 49, 69, 78, 67]);
|
|
16
|
+
var MAGIC_128 = Buffer.from([84, 82, 73, 67, 49, 49, 50, 56]);
|
|
17
|
+
var MAGIC_XOR = Buffer.from([84, 82, 73, 67, 49, 88, 79, 82]);
|
|
18
|
+
var MAGIC_CTR = Buffer.from([84, 82, 73, 67, 49, 67, 84, 82]);
|
|
19
|
+
var MAGIC_LEN = 8;
|
|
20
|
+
var CTR_IV_BYTES = 16;
|
|
21
|
+
var PREFIX_CTR = "ctr:v1:";
|
|
22
|
+
var IV_POOL_COUNT = 64;
|
|
23
|
+
var CacheEncryption = class {
|
|
24
|
+
_key = null;
|
|
25
|
+
// raw bytes โ used only for XOR
|
|
26
|
+
_keyObj = null;
|
|
27
|
+
// parsed KeyObject โ used for all AES modes
|
|
28
|
+
_mode;
|
|
29
|
+
_prevKey = null;
|
|
30
|
+
_prevKeyObj = null;
|
|
31
|
+
_prevMode = "aes-256-gcm";
|
|
32
|
+
// Pre-allocated GCM IV pool โ 12-byte IVs (96-bit, NIST recommended).
|
|
33
|
+
_ivPool = Buffer.allocUnsafe(IV_BYTES * IV_POOL_COUNT);
|
|
34
|
+
_ivOffset = IV_BYTES * IV_POOL_COUNT;
|
|
35
|
+
// start exhausted โ fill on first use
|
|
36
|
+
/** Return the next unique 12-byte IV slice from the pre-allocated GCM pool. */
|
|
37
|
+
_nextIV() {
|
|
38
|
+
if (this._ivOffset >= this._ivPool.length) {
|
|
39
|
+
randomFillSync(this._ivPool);
|
|
40
|
+
this._ivOffset = 0;
|
|
41
|
+
}
|
|
42
|
+
const iv = this._ivPool.subarray(this._ivOffset, this._ivOffset + IV_BYTES);
|
|
43
|
+
this._ivOffset += IV_BYTES;
|
|
44
|
+
return iv;
|
|
45
|
+
}
|
|
46
|
+
// Pre-allocated CTR IV pool โ 16-byte IVs (full AES block = initial counter block).
|
|
47
|
+
_ctrIvPool = Buffer.allocUnsafe(CTR_IV_BYTES * IV_POOL_COUNT);
|
|
48
|
+
_ctrIvOffset = CTR_IV_BYTES * IV_POOL_COUNT;
|
|
49
|
+
/** Return the next unique 16-byte IV slice from the pre-allocated CTR pool. */
|
|
50
|
+
_nextCtrIV() {
|
|
51
|
+
if (this._ctrIvOffset >= this._ctrIvPool.length) {
|
|
52
|
+
randomFillSync(this._ctrIvPool);
|
|
53
|
+
this._ctrIvOffset = 0;
|
|
54
|
+
}
|
|
55
|
+
const iv = this._ctrIvPool.subarray(this._ctrIvOffset, this._ctrIvOffset + CTR_IV_BYTES);
|
|
56
|
+
this._ctrIvOffset += CTR_IV_BYTES;
|
|
57
|
+
return iv;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* XOR `data` with the key, cycling through key bytes.
|
|
61
|
+
* Self-inverse: _xorBuffer(_xorBuffer(x)) === x.
|
|
62
|
+
*
|
|
63
|
+
* Fast path: Uint32Array views over the existing Buffer memory โ zero copy,
|
|
64
|
+
* no method-call overhead. V8 JITs `out32[i] = data32[i] ^ key32[...]`
|
|
65
|
+
* to a single `XOR r32, r32` instruction. Requires 4-byte-aligned byteOffsets,
|
|
66
|
+
* which Node.js guarantees (pool rounds up to 8 bytes; direct allocs to page).
|
|
67
|
+
*
|
|
68
|
+
* WARNING: XOR is NOT cryptographic. It provides obfuscation only.
|
|
69
|
+
*/
|
|
70
|
+
_xorBuffer(data) {
|
|
71
|
+
const key = this._key;
|
|
72
|
+
const klen = key.length;
|
|
73
|
+
const len = data.length;
|
|
74
|
+
const out = Buffer.allocUnsafe(len);
|
|
75
|
+
if (klen % 4 === 0 && len >= 4 && data.byteOffset % 4 === 0 && out.byteOffset % 4 === 0 && key.byteOffset % 4 === 0) {
|
|
76
|
+
const wordCount = len >>> 2;
|
|
77
|
+
const data32 = new Uint32Array(data.buffer, data.byteOffset, wordCount);
|
|
78
|
+
const out32 = new Uint32Array(out.buffer, out.byteOffset, wordCount);
|
|
79
|
+
const key32 = new Uint32Array(key.buffer, key.byteOffset, klen >>> 2);
|
|
80
|
+
const kLen32 = key32.length;
|
|
81
|
+
for (let i = 0; i < wordCount; i++) {
|
|
82
|
+
out32[i] = data32[i] ^ key32[i % kLen32];
|
|
83
|
+
}
|
|
84
|
+
for (let i = wordCount << 2; i < len; i++) {
|
|
85
|
+
out[i] = data[i] ^ key[i % klen];
|
|
86
|
+
}
|
|
87
|
+
return out;
|
|
88
|
+
}
|
|
89
|
+
for (let i = 0; i < len; i++) {
|
|
90
|
+
out[i] = data[i] ^ key[i % klen];
|
|
91
|
+
}
|
|
92
|
+
return out;
|
|
93
|
+
}
|
|
94
|
+
constructor(keyBase64, logger, mode = "aes-256-gcm", previousKeyBase64, previousMode) {
|
|
95
|
+
this._mode = mode;
|
|
96
|
+
if (!keyBase64) {
|
|
97
|
+
if (process.env.NODE_ENV === "production") {
|
|
98
|
+
logger.warn(
|
|
99
|
+
"SECURITY: encryption key not set \u2014 cache data stored unencrypted at rest",
|
|
100
|
+
{ hint: "Set encryptionKey option or CACHE_ENCRYPTION_KEY env var" }
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
try {
|
|
106
|
+
const buf = Buffer.from(keyBase64, "base64");
|
|
107
|
+
const requiredLen = mode === "aes-256-gcm" ? 32 : mode === "aes-128-gcm" || mode === "aes-128-ctr" ? 16 : 0;
|
|
108
|
+
if (requiredLen > 0 && buf.length !== requiredLen) {
|
|
109
|
+
throw new Error(`${mode} requires exactly ${requiredLen} bytes (got ${buf.length})`);
|
|
110
|
+
}
|
|
111
|
+
if (buf.length < 1) {
|
|
112
|
+
throw new Error("XOR key must be at least 1 byte");
|
|
113
|
+
}
|
|
114
|
+
this._key = buf;
|
|
115
|
+
if (mode !== "xor") {
|
|
116
|
+
this._keyObj = createSecretKey(buf);
|
|
117
|
+
const _wc = createCipheriv(
|
|
118
|
+
mode,
|
|
119
|
+
this._keyObj,
|
|
120
|
+
Buffer.alloc(mode === "aes-128-ctr" ? CTR_IV_BYTES : IV_BYTES)
|
|
121
|
+
);
|
|
122
|
+
_wc.update(Buffer.alloc(0));
|
|
123
|
+
_wc.final();
|
|
124
|
+
}
|
|
125
|
+
if (mode === "xor") {
|
|
126
|
+
logger.warn(
|
|
127
|
+
"Cache obfuscation enabled (XOR). WARNING: XOR is NOT cryptographic \u2014 use only for dev or non-sensitive data."
|
|
128
|
+
);
|
|
129
|
+
} else {
|
|
130
|
+
logger.debug(`Cache encryption enabled (${mode.toUpperCase()})`);
|
|
131
|
+
}
|
|
132
|
+
} catch (err) {
|
|
133
|
+
logger.error("Invalid encryption key \u2014 falling back to plaintext", {}, err);
|
|
134
|
+
}
|
|
135
|
+
if (previousKeyBase64) {
|
|
136
|
+
try {
|
|
137
|
+
this._prevMode = previousMode ?? mode;
|
|
138
|
+
this._prevKey = Buffer.from(previousKeyBase64, "base64");
|
|
139
|
+
if (this._prevMode !== "xor") {
|
|
140
|
+
this._prevKeyObj = createSecretKey(this._prevKey);
|
|
141
|
+
const _wc = createCipheriv(
|
|
142
|
+
this._prevMode,
|
|
143
|
+
this._prevKeyObj,
|
|
144
|
+
Buffer.alloc(this._prevMode === "aes-128-ctr" ? CTR_IV_BYTES : IV_BYTES)
|
|
145
|
+
);
|
|
146
|
+
_wc.update(Buffer.alloc(0));
|
|
147
|
+
_wc.final();
|
|
148
|
+
}
|
|
149
|
+
logger.debug("Previous encryption key loaded for key rotation fallback");
|
|
150
|
+
} catch (err) {
|
|
151
|
+
logger.warn("Invalid previousEncryptionKey \u2014 rotation fallback disabled", { error: err.message });
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
get isEnabled() {
|
|
156
|
+
return this._key !== null;
|
|
157
|
+
}
|
|
158
|
+
// โโ String (Redis) โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
|
159
|
+
/**
|
|
160
|
+
* Encrypt a string for Redis storage.
|
|
161
|
+
* Returns a mode-prefixed base64 string when a key is configured;
|
|
162
|
+
* otherwise returns the original string unchanged (backward-compatible).
|
|
163
|
+
*/
|
|
164
|
+
encrypt(plaintext) {
|
|
165
|
+
if (!this._key) return plaintext;
|
|
166
|
+
if (this._mode === "xor") {
|
|
167
|
+
const masked = this._xorBuffer(Buffer.from(plaintext, "utf8"));
|
|
168
|
+
return PREFIX_XOR + masked.toString("base64");
|
|
169
|
+
}
|
|
170
|
+
if (this._mode === "aes-128-ctr") {
|
|
171
|
+
const iv2 = this._nextCtrIV();
|
|
172
|
+
const c2 = createCipheriv("aes-128-ctr", this._keyObj, iv2);
|
|
173
|
+
const enc2 = c2.update(plaintext, "utf8");
|
|
174
|
+
const fin = c2.final();
|
|
175
|
+
const out2 = Buffer.allocUnsafe(CTR_IV_BYTES + enc2.length + fin.length);
|
|
176
|
+
iv2.copy(out2, 0);
|
|
177
|
+
enc2.copy(out2, CTR_IV_BYTES);
|
|
178
|
+
if (fin.length > 0) fin.copy(out2, CTR_IV_BYTES + enc2.length);
|
|
179
|
+
return PREFIX_CTR + out2.toString("base64");
|
|
180
|
+
}
|
|
181
|
+
const algo = this._mode === "aes-128-gcm" ? "aes-128-gcm" : "aes-256-gcm";
|
|
182
|
+
const prefix = this._mode === "aes-128-gcm" ? PREFIX_128 : PREFIX_256;
|
|
183
|
+
const iv = this._nextIV();
|
|
184
|
+
const c = createCipheriv(algo, this._keyObj, iv);
|
|
185
|
+
const enc = c.update(plaintext, "utf8");
|
|
186
|
+
c.final();
|
|
187
|
+
const out = Buffer.allocUnsafe(IV_BYTES + TAG_BYTES + enc.length);
|
|
188
|
+
iv.copy(out, 0);
|
|
189
|
+
c.getAuthTag().copy(out, IV_BYTES);
|
|
190
|
+
enc.copy(out, IV_BYTES + TAG_BYTES);
|
|
191
|
+
return prefix + out.toString("base64");
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Decrypt a Redis value.
|
|
195
|
+
* Auto-detects the envelope prefix; returns plaintext unchanged if no prefix matches.
|
|
196
|
+
* Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
|
|
197
|
+
*/
|
|
198
|
+
decrypt(value) {
|
|
199
|
+
try {
|
|
200
|
+
return this._decryptWithKey(value, this._key, this._keyObj, this._mode);
|
|
201
|
+
} catch (primaryErr) {
|
|
202
|
+
if (this._prevKey) {
|
|
203
|
+
try {
|
|
204
|
+
return this._decryptWithKey(value, this._prevKey, this._prevKeyObj, this._prevMode);
|
|
205
|
+
} catch {
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
throw primaryErr;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
_decryptWithKey(value, key, keyObj, mode) {
|
|
212
|
+
if (value.startsWith(PREFIX_XOR)) {
|
|
213
|
+
if (!key) throw new Error("Cannot decrypt: encryption key is not set");
|
|
214
|
+
const masked = Buffer.from(value.slice(PREFIX_XOR.length), "base64");
|
|
215
|
+
const klen = key.length;
|
|
216
|
+
const len = masked.length;
|
|
217
|
+
const out = Buffer.allocUnsafe(len);
|
|
218
|
+
for (let i = 0; i < len; i++) out[i] = masked[i] ^ key[i % klen];
|
|
219
|
+
return out.toString("utf8");
|
|
220
|
+
}
|
|
221
|
+
if (value.startsWith(PREFIX_CTR)) {
|
|
222
|
+
if (!keyObj) throw new Error("Cannot decrypt: encryption key is not set");
|
|
223
|
+
const combined2 = Buffer.from(value.slice(PREFIX_CTR.length), "base64");
|
|
224
|
+
const iv2 = combined2.subarray(0, CTR_IV_BYTES);
|
|
225
|
+
const ct2 = combined2.subarray(CTR_IV_BYTES);
|
|
226
|
+
const d2 = createDecipheriv("aes-128-ctr", keyObj, iv2);
|
|
227
|
+
const plain2 = d2.update(ct2);
|
|
228
|
+
const fin = d2.final();
|
|
229
|
+
return (fin.length > 0 ? Buffer.concat([plain2, fin]) : plain2).toString("utf8");
|
|
230
|
+
}
|
|
231
|
+
const is256 = value.startsWith(PREFIX_256);
|
|
232
|
+
const is128 = value.startsWith(PREFIX_128);
|
|
233
|
+
if (!is256 && !is128) return value;
|
|
234
|
+
if (!keyObj) throw new Error("Cannot decrypt: encryption key is not set");
|
|
235
|
+
const prefix = is128 ? PREFIX_128 : PREFIX_256;
|
|
236
|
+
const algo = is128 ? "aes-128-gcm" : "aes-256-gcm";
|
|
237
|
+
const combined = Buffer.from(value.slice(prefix.length), "base64");
|
|
238
|
+
const iv = combined.subarray(0, IV_BYTES);
|
|
239
|
+
const tag = combined.subarray(IV_BYTES, IV_BYTES + TAG_BYTES);
|
|
240
|
+
const ct = combined.subarray(IV_BYTES + TAG_BYTES);
|
|
241
|
+
const d = createDecipheriv(algo, keyObj, iv);
|
|
242
|
+
d.setAuthTag(tag);
|
|
243
|
+
const plain = d.update(ct);
|
|
244
|
+
d.final();
|
|
245
|
+
return plain.toString("utf8");
|
|
246
|
+
void mode;
|
|
247
|
+
void key;
|
|
248
|
+
}
|
|
249
|
+
// โโ Buffer (disk / snapshot) โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
|
250
|
+
/** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
|
|
251
|
+
encryptBuffer(data) {
|
|
252
|
+
if (!this._key) return data;
|
|
253
|
+
if (this._mode === "xor") {
|
|
254
|
+
const masked = this._xorBuffer(data);
|
|
255
|
+
const out2 = Buffer.allocUnsafe(MAGIC_LEN + masked.length);
|
|
256
|
+
MAGIC_XOR.copy(out2, 0);
|
|
257
|
+
masked.copy(out2, MAGIC_LEN);
|
|
258
|
+
return out2;
|
|
259
|
+
}
|
|
260
|
+
if (this._mode === "aes-128-ctr") {
|
|
261
|
+
const iv2 = this._nextCtrIV();
|
|
262
|
+
const c2 = createCipheriv("aes-128-ctr", this._keyObj, iv2);
|
|
263
|
+
const enc2 = c2.update(data);
|
|
264
|
+
const fin = c2.final();
|
|
265
|
+
const out2 = Buffer.allocUnsafe(MAGIC_LEN + CTR_IV_BYTES + enc2.length + fin.length);
|
|
266
|
+
MAGIC_CTR.copy(out2, 0);
|
|
267
|
+
iv2.copy(out2, MAGIC_LEN);
|
|
268
|
+
enc2.copy(out2, MAGIC_LEN + CTR_IV_BYTES);
|
|
269
|
+
if (fin.length > 0) fin.copy(out2, MAGIC_LEN + CTR_IV_BYTES + enc2.length);
|
|
270
|
+
return out2;
|
|
271
|
+
}
|
|
272
|
+
const magic = this._mode === "aes-128-gcm" ? MAGIC_128 : MAGIC_256;
|
|
273
|
+
const algo = this._mode === "aes-128-gcm" ? "aes-128-gcm" : "aes-256-gcm";
|
|
274
|
+
const iv = this._nextIV();
|
|
275
|
+
const c = createCipheriv(algo, this._keyObj, iv);
|
|
276
|
+
const enc = c.update(data);
|
|
277
|
+
c.final();
|
|
278
|
+
const out = Buffer.allocUnsafe(MAGIC_LEN + IV_BYTES + TAG_BYTES + enc.length);
|
|
279
|
+
magic.copy(out, 0);
|
|
280
|
+
iv.copy(out, MAGIC_LEN);
|
|
281
|
+
c.getAuthTag().copy(out, MAGIC_LEN + IV_BYTES);
|
|
282
|
+
enc.copy(out, MAGIC_LEN + IV_BYTES + TAG_BYTES);
|
|
283
|
+
return out;
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* Decrypt a raw Buffer from disk/snapshot.
|
|
287
|
+
* Auto-detects the magic header; returns the original buffer if no magic matches (legacy/unencrypted).
|
|
288
|
+
* Falls back to `previousEncryptionKey` when the primary key fails (key rotation).
|
|
289
|
+
*/
|
|
290
|
+
decryptBuffer(data) {
|
|
291
|
+
try {
|
|
292
|
+
return this._decryptBufferWithKey(data, this._key, this._keyObj);
|
|
293
|
+
} catch (primaryErr) {
|
|
294
|
+
if (this._prevKey) {
|
|
295
|
+
try {
|
|
296
|
+
return this._decryptBufferWithKey(data, this._prevKey, this._prevKeyObj);
|
|
297
|
+
} catch {
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
throw primaryErr;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
_decryptBufferWithKey(data, key, keyObj) {
|
|
304
|
+
if (data.length < MAGIC_LEN) return data;
|
|
305
|
+
const magic = data.subarray(0, MAGIC_LEN);
|
|
306
|
+
if (magic.equals(MAGIC_XOR)) {
|
|
307
|
+
if (!key) throw new Error("Cannot decrypt buffer: encryption key is not set");
|
|
308
|
+
const raw = data.subarray(MAGIC_LEN);
|
|
309
|
+
const klen = key.length;
|
|
310
|
+
const out = Buffer.allocUnsafe(raw.length);
|
|
311
|
+
for (let i = 0; i < raw.length; i++) out[i] = raw[i] ^ key[i % klen];
|
|
312
|
+
return out;
|
|
313
|
+
}
|
|
314
|
+
if (magic.equals(MAGIC_CTR)) {
|
|
315
|
+
if (!keyObj) throw new Error("Cannot decrypt buffer: encryption key is not set");
|
|
316
|
+
const iv2 = data.subarray(MAGIC_LEN, MAGIC_LEN + CTR_IV_BYTES);
|
|
317
|
+
const ct2 = data.subarray(MAGIC_LEN + CTR_IV_BYTES);
|
|
318
|
+
const d2 = createDecipheriv("aes-128-ctr", keyObj, iv2);
|
|
319
|
+
const plain2 = d2.update(ct2);
|
|
320
|
+
const fin = d2.final();
|
|
321
|
+
return fin.length > 0 ? Buffer.concat([plain2, fin]) : plain2;
|
|
322
|
+
}
|
|
323
|
+
const is256 = magic.equals(MAGIC_256);
|
|
324
|
+
const is128 = magic.equals(MAGIC_128);
|
|
325
|
+
if (!is256 && !is128) return data;
|
|
326
|
+
if (!keyObj) throw new Error("Cannot decrypt buffer: encryption key is not set");
|
|
327
|
+
const algo = is128 ? "aes-128-gcm" : "aes-256-gcm";
|
|
328
|
+
const iv = data.subarray(MAGIC_LEN, MAGIC_LEN + IV_BYTES);
|
|
329
|
+
const tag = data.subarray(MAGIC_LEN + IV_BYTES, MAGIC_LEN + IV_BYTES + TAG_BYTES);
|
|
330
|
+
const ct = data.subarray(MAGIC_LEN + IV_BYTES + TAG_BYTES);
|
|
331
|
+
const d = createDecipheriv(algo, keyObj, iv);
|
|
332
|
+
d.setAuthTag(tag);
|
|
333
|
+
const plain = d.update(ct);
|
|
334
|
+
d.final();
|
|
335
|
+
return plain;
|
|
336
|
+
}
|
|
337
|
+
};
|
|
338
|
+
|
|
339
|
+
export {
|
|
340
|
+
__require,
|
|
341
|
+
CacheEncryption
|
|
342
|
+
};
|