tricache 0.1.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.
- package/LICENSE +21 -0
- package/README.md +438 -0
- package/dist/index.cjs +1784 -0
- package/dist/index.d.cts +718 -0
- package/dist/index.d.ts +718 -0
- package/dist/index.js +1741 -0
- package/package.json +64 -0
- package/src/cache-service.ts +866 -0
- package/src/disk-tier.ts +300 -0
- package/src/encryption.ts +340 -0
- package/src/index.ts +36 -0
- package/src/smart-memory-cache.ts +472 -0
- package/src/types.ts +317 -0
- package/src/wasm/bloom-filter-wasm.ts +117 -0
package/src/disk-tier.ts
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DiskTier — L1.5 NVMe-fast overflow cache between L1 RAM and L2 Redis/DB.
|
|
3
|
+
*
|
|
4
|
+
* When L1 evicts an entry it is spilled here instead of being discarded.
|
|
5
|
+
* On a subsequent L1 miss the entry is promoted back (2–100 µs disk read
|
|
6
|
+
* vs 10–100 ms DB round-trip).
|
|
7
|
+
*
|
|
8
|
+
* Storage:
|
|
9
|
+
* - Directory: configurable (default os.tmpdir()/tricache-disk)
|
|
10
|
+
* - Filename: SHA-256(key) hex — bounded, URL-safe, no key injection
|
|
11
|
+
* - Format: msgpack({ version, key, entry, writtenAt })
|
|
12
|
+
* - Mode: 0o600 — owner read/write only
|
|
13
|
+
*
|
|
14
|
+
* Encryption: same AES-256-GCM as L2 when CacheEncryption is configured.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import fs from 'fs';
|
|
18
|
+
import path from 'path';
|
|
19
|
+
import crypto from 'crypto';
|
|
20
|
+
import { pack, unpack } from 'msgpackr';
|
|
21
|
+
import type { DiskCacheEntry, ILogger } from './types';
|
|
22
|
+
|
|
23
|
+
// ── Encryption (self-contained to avoid circular import) ─────────────────────
|
|
24
|
+
|
|
25
|
+
const AES_ALGO = 'aes-256-gcm' as const;
|
|
26
|
+
const IV_BYTES = 12;
|
|
27
|
+
const TAG_BYTES = 16;
|
|
28
|
+
const DISK_MAGIC = Buffer.from([0x44, 0x54, 0x49, 0x45, 0x52, 0x56, 0x31, 0x00]); // "DTIERV1\0"
|
|
29
|
+
|
|
30
|
+
interface DiskPayload {
|
|
31
|
+
version: number;
|
|
32
|
+
key: string;
|
|
33
|
+
entry: DiskCacheEntry;
|
|
34
|
+
writtenAt: number;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const DISK_TIER_VERSION = 1;
|
|
38
|
+
|
|
39
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
40
|
+
|
|
41
|
+
export interface DiskTierOptions {
|
|
42
|
+
dir: string;
|
|
43
|
+
maxBytes: number;
|
|
44
|
+
entryMaxBytes: number;
|
|
45
|
+
forbiddenPrefixes: readonly string[];
|
|
46
|
+
encryptionKey?: Buffer | null;
|
|
47
|
+
logger: ILogger;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export class DiskTier {
|
|
51
|
+
private readonly opts: DiskTierOptions;
|
|
52
|
+
private dirReady = false;
|
|
53
|
+
private diskUsageBytes = 0;
|
|
54
|
+
private usageCounted = false;
|
|
55
|
+
private fileCount = 0; // maintained in-memory; avoids walkCacheFiles() in stats
|
|
56
|
+
|
|
57
|
+
constructor(opts: DiskTierOptions) {
|
|
58
|
+
this.opts = opts;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// ── Helpers ───────────────────────────────────────────────────────────────
|
|
62
|
+
|
|
63
|
+
private ensureDir(): void {
|
|
64
|
+
if (this.dirReady) return;
|
|
65
|
+
try {
|
|
66
|
+
fs.mkdirSync(this.opts.dir, { recursive: true, mode: 0o700 });
|
|
67
|
+
this.dirReady = true;
|
|
68
|
+
} catch (err) {
|
|
69
|
+
this.opts.logger.warn('DiskTier: cannot create cache dir', { dir: this.opts.dir, error: (err as Error).message });
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
private ensureUsageCounted(): void {
|
|
74
|
+
if (this.usageCounted) return;
|
|
75
|
+
this.usageCounted = true;
|
|
76
|
+
try {
|
|
77
|
+
this.ensureDir();
|
|
78
|
+
let total = 0;
|
|
79
|
+
const files = this.walkCacheFiles();
|
|
80
|
+
this.fileCount = files.length;
|
|
81
|
+
for (const filePath of files) {
|
|
82
|
+
try { total += fs.statSync(filePath).size; } catch { /* ok */ }
|
|
83
|
+
}
|
|
84
|
+
this.diskUsageBytes = total;
|
|
85
|
+
} catch { this.diskUsageBytes = 0; this.fileCount = 0; }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Map a cache key to its on-disk path.
|
|
90
|
+
*
|
|
91
|
+
* Files are sharded into two-character hex prefix subdirectories to avoid
|
|
92
|
+
* putting thousands of flat files into a single directory node — which
|
|
93
|
+
* degrades EXT4/NTFS performance at scale.
|
|
94
|
+
*
|
|
95
|
+
* key → SHA-256 hex e3b0c442...
|
|
96
|
+
* path → {dir}/e3/e3b0c442...
|
|
97
|
+
*/
|
|
98
|
+
private keyToPath(key: string): string {
|
|
99
|
+
const hash = crypto.createHash('sha256').update(key, 'utf8').digest('hex');
|
|
100
|
+
return path.join(this.opts.dir, hash.slice(0, 2), hash);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Recursively list all cache file paths across the 2-level sharded subdirs.
|
|
105
|
+
* Top-level entries that are not directories are skipped (e.g. stale flat
|
|
106
|
+
* files written by older versions).
|
|
107
|
+
*/
|
|
108
|
+
private walkCacheFiles(): string[] {
|
|
109
|
+
const results: string[] = [];
|
|
110
|
+
let topEntries: string[];
|
|
111
|
+
try { topEntries = fs.readdirSync(this.opts.dir); } catch { return results; }
|
|
112
|
+
for (const top of topEntries) {
|
|
113
|
+
const topPath = path.join(this.opts.dir, top);
|
|
114
|
+
try {
|
|
115
|
+
if (!fs.statSync(topPath).isDirectory()) continue;
|
|
116
|
+
for (const file of fs.readdirSync(topPath)) {
|
|
117
|
+
results.push(path.join(topPath, file));
|
|
118
|
+
}
|
|
119
|
+
} catch { /* skip locked/gone */ }
|
|
120
|
+
}
|
|
121
|
+
return results;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
private isForbidden(key: string): boolean {
|
|
125
|
+
return this.opts.forbiddenPrefixes.some(p => key.startsWith(p));
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
private encrypt(data: Buffer): Buffer {
|
|
129
|
+
const key = this.opts.encryptionKey;
|
|
130
|
+
if (!key) return data;
|
|
131
|
+
const iv = crypto.randomBytes(IV_BYTES);
|
|
132
|
+
const c = crypto.createCipheriv(AES_ALGO, key, iv);
|
|
133
|
+
const enc = Buffer.concat([c.update(data), c.final()]);
|
|
134
|
+
const tag = c.getAuthTag();
|
|
135
|
+
return Buffer.concat([DISK_MAGIC, iv, tag, enc]);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
private decrypt(data: Buffer): Buffer {
|
|
139
|
+
const mLen = DISK_MAGIC.length;
|
|
140
|
+
if (data.length < mLen || !data.subarray(0, mLen).equals(DISK_MAGIC)) return data;
|
|
141
|
+
const key = this.opts.encryptionKey;
|
|
142
|
+
if (!key) throw new Error('DiskTier: entry is encrypted but no key is set');
|
|
143
|
+
const iv = data.subarray(mLen, mLen + IV_BYTES);
|
|
144
|
+
const tag = data.subarray(mLen + IV_BYTES, mLen + IV_BYTES + TAG_BYTES);
|
|
145
|
+
const ct = data.subarray(mLen + IV_BYTES + TAG_BYTES);
|
|
146
|
+
const d = crypto.createDecipheriv(AES_ALGO, key, iv);
|
|
147
|
+
d.setAuthTag(tag);
|
|
148
|
+
return Buffer.concat([d.update(ct), d.final()]);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// ── Public API ────────────────────────────────────────────────────────────
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Spill an evicted L1 entry to disk.
|
|
155
|
+
*
|
|
156
|
+
* Returns a Promise that resolves when the file is durably written. Callers
|
|
157
|
+
* that treat the spill as fire-and-forget should do:
|
|
158
|
+
* `void disk.save(key, entry)`
|
|
159
|
+
*
|
|
160
|
+
* Implementation notes:
|
|
161
|
+
* - pack() + AES-256-GCM encrypt run synchronously — both are pure CPU,
|
|
162
|
+
* sub-millisecond for entries up to diskEntryMaxBytes, and do not block
|
|
163
|
+
* on any external resource.
|
|
164
|
+
* - The actual write syscall (mkdir + writeFile) is async via fs.promises,
|
|
165
|
+
* so the Node.js event loop is never stalled waiting for disk I/O.
|
|
166
|
+
*/
|
|
167
|
+
async save(key: string, entry: DiskCacheEntry): Promise<void> {
|
|
168
|
+
if (this.isForbidden(key)) return;
|
|
169
|
+
if (entry.expiresAt <= Date.now()) return;
|
|
170
|
+
|
|
171
|
+
this.ensureDir();
|
|
172
|
+
if (!this.dirReady) return;
|
|
173
|
+
this.ensureUsageCounted();
|
|
174
|
+
if (this.diskUsageBytes >= this.opts.maxBytes) return; // disk cap hit
|
|
175
|
+
|
|
176
|
+
// ── Synchronous phase: pack + encrypt (CPU-only, no I/O) ─────────────
|
|
177
|
+
let final: Buffer;
|
|
178
|
+
try {
|
|
179
|
+
const payload: DiskPayload = {
|
|
180
|
+
version: DISK_TIER_VERSION,
|
|
181
|
+
key,
|
|
182
|
+
entry: {
|
|
183
|
+
...entry,
|
|
184
|
+
data: entry.data instanceof Uint8Array
|
|
185
|
+
? Buffer.from(entry.data)
|
|
186
|
+
: entry.data,
|
|
187
|
+
},
|
|
188
|
+
writtenAt: Date.now(),
|
|
189
|
+
};
|
|
190
|
+
const packed = pack(payload);
|
|
191
|
+
if (packed.length > this.opts.entryMaxBytes) return;
|
|
192
|
+
final = this.encrypt(packed);
|
|
193
|
+
} catch (err) {
|
|
194
|
+
this.opts.logger.debug('DiskTier: pack/encrypt failed', { key: key.slice(0, 50), error: (err as Error).message });
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// ── Async phase: mkdir + write (does not block the event loop) ────────
|
|
199
|
+
const filePath = this.keyToPath(key);
|
|
200
|
+
this.diskUsageBytes += final.length; // optimistic — rolled back on error
|
|
201
|
+
this.fileCount++;
|
|
202
|
+
|
|
203
|
+
try {
|
|
204
|
+
await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
|
|
205
|
+
await fs.promises.writeFile(filePath, final, { mode: 0o600 });
|
|
206
|
+
this.opts.logger.debug('DiskTier: entry saved', { key: key.slice(0, 50), bytes: final.length });
|
|
207
|
+
} catch (err) {
|
|
208
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length); // rollback
|
|
209
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
210
|
+
this.opts.logger.debug('DiskTier: save failed', { key: key.slice(0, 50), error: (err as Error).message });
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Load a key from disk, or return null on miss/expiry/corruption. */
|
|
215
|
+
load(key: string): DiskCacheEntry | null {
|
|
216
|
+
if (this.isForbidden(key)) return null;
|
|
217
|
+
this.ensureDir();
|
|
218
|
+
if (!this.dirReady) return null;
|
|
219
|
+
|
|
220
|
+
const filePath = this.keyToPath(key);
|
|
221
|
+
try {
|
|
222
|
+
if (!fs.existsSync(filePath)) return null;
|
|
223
|
+
|
|
224
|
+
const stat = fs.statSync(filePath);
|
|
225
|
+
if (stat.size > this.opts.entryMaxBytes) {
|
|
226
|
+
fs.unlinkSync(filePath);
|
|
227
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
228
|
+
return null;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
const raw = fs.readFileSync(filePath);
|
|
232
|
+
// Delete immediately — entry will be promoted back to L1
|
|
233
|
+
try { fs.unlinkSync(filePath); this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size); this.fileCount = Math.max(0, this.fileCount - 1); } catch { /* ok */ }
|
|
234
|
+
|
|
235
|
+
let decrypted: Buffer;
|
|
236
|
+
try { decrypted = this.decrypt(raw); } catch { return null; }
|
|
237
|
+
|
|
238
|
+
const payload = unpack(decrypted) as DiskPayload;
|
|
239
|
+
if (!payload || payload.version !== DISK_TIER_VERSION || payload.key !== key) return null;
|
|
240
|
+
if (payload.entry.expiresAt <= Date.now()) return null;
|
|
241
|
+
|
|
242
|
+
const entry = payload.entry;
|
|
243
|
+
if (entry.data instanceof Uint8Array) entry.data = Buffer.from(entry.data);
|
|
244
|
+
|
|
245
|
+
this.opts.logger.debug('DiskTier: hit (→L1)', { key: key.slice(0, 50), ageMs: Date.now() - payload.writtenAt });
|
|
246
|
+
return entry;
|
|
247
|
+
} catch (err) {
|
|
248
|
+
this.opts.logger.debug('DiskTier: load failed', { key: key.slice(0, 50), error: (err as Error).message });
|
|
249
|
+
return null;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** Explicitly delete a key from disk (cache invalidation). */
|
|
254
|
+
delete(key: string): void {
|
|
255
|
+
const filePath = this.keyToPath(key);
|
|
256
|
+
try {
|
|
257
|
+
if (fs.existsSync(filePath)) {
|
|
258
|
+
const stat = fs.statSync(filePath);
|
|
259
|
+
fs.unlinkSync(filePath);
|
|
260
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
261
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
262
|
+
}
|
|
263
|
+
} catch { /* ok */ }
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** Purge all expired entries. Returns number deleted. */
|
|
267
|
+
purgeExpired(): number {
|
|
268
|
+
this.ensureDir();
|
|
269
|
+
if (!this.dirReady) return 0;
|
|
270
|
+
let purged = 0;
|
|
271
|
+
for (const filePath of this.walkCacheFiles()) {
|
|
272
|
+
try {
|
|
273
|
+
const stat = fs.statSync(filePath);
|
|
274
|
+
if (stat.size > this.opts.entryMaxBytes) {
|
|
275
|
+
fs.unlinkSync(filePath);
|
|
276
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
277
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
278
|
+
purged++;
|
|
279
|
+
continue;
|
|
280
|
+
}
|
|
281
|
+
const raw = fs.readFileSync(filePath);
|
|
282
|
+
let dec: Buffer;
|
|
283
|
+
try { dec = this.decrypt(raw); } catch { fs.unlinkSync(filePath); this.fileCount = Math.max(0, this.fileCount - 1); purged++; continue; }
|
|
284
|
+
const payload = unpack(dec) as DiskPayload;
|
|
285
|
+
if (!payload || payload.version !== DISK_TIER_VERSION || payload.entry.expiresAt <= Date.now()) {
|
|
286
|
+
fs.unlinkSync(filePath);
|
|
287
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
288
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
289
|
+
purged++;
|
|
290
|
+
}
|
|
291
|
+
} catch { /* skip locked/gone */ }
|
|
292
|
+
}
|
|
293
|
+
return purged;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
get stats(): { files: number; sizeKB: number; maxKB: number } {
|
|
297
|
+
// fileCount is maintained in-memory — O(1), no filesystem scan.
|
|
298
|
+
return { files: this.fileCount, sizeKB: Math.round(this.diskUsageBytes / 1024), maxKB: Math.round(this.opts.maxBytes / 1024) };
|
|
299
|
+
}
|
|
300
|
+
}
|
|
@@ -0,0 +1,340 @@
|
|
|
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, randomFillSync } from 'crypto';
|
|
37
|
+
import type { ILogger } 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;
|
|
75
|
+
private readonly _mode: EncryptionMode;
|
|
76
|
+
|
|
77
|
+
// Pre-allocated GCM IV pool — 12-byte IVs (96-bit, NIST recommended).
|
|
78
|
+
private readonly _ivPool = Buffer.allocUnsafe(IV_BYTES * IV_POOL_COUNT);
|
|
79
|
+
private _ivOffset = IV_BYTES * IV_POOL_COUNT; // start exhausted → fill on first use
|
|
80
|
+
|
|
81
|
+
/** Return the next unique 12-byte IV slice from the pre-allocated GCM pool. */
|
|
82
|
+
private _nextIV(): Buffer {
|
|
83
|
+
if (this._ivOffset >= this._ivPool.length) {
|
|
84
|
+
randomFillSync(this._ivPool); // fills existing Buffer in-place — zero allocation
|
|
85
|
+
this._ivOffset = 0;
|
|
86
|
+
}
|
|
87
|
+
const iv = this._ivPool.subarray(this._ivOffset, this._ivOffset + IV_BYTES); // Buffer (not Uint8Array)
|
|
88
|
+
this._ivOffset += IV_BYTES;
|
|
89
|
+
return iv;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Pre-allocated CTR IV pool — 16-byte IVs (full AES block = initial counter block).
|
|
93
|
+
private readonly _ctrIvPool = Buffer.allocUnsafe(CTR_IV_BYTES * IV_POOL_COUNT);
|
|
94
|
+
private _ctrIvOffset = CTR_IV_BYTES * IV_POOL_COUNT;
|
|
95
|
+
|
|
96
|
+
/** Return the next unique 16-byte IV slice from the pre-allocated CTR pool. */
|
|
97
|
+
private _nextCtrIV(): Buffer {
|
|
98
|
+
if (this._ctrIvOffset >= this._ctrIvPool.length) {
|
|
99
|
+
randomFillSync(this._ctrIvPool);
|
|
100
|
+
this._ctrIvOffset = 0;
|
|
101
|
+
}
|
|
102
|
+
const iv = this._ctrIvPool.subarray(this._ctrIvOffset, this._ctrIvOffset + CTR_IV_BYTES);
|
|
103
|
+
this._ctrIvOffset += CTR_IV_BYTES;
|
|
104
|
+
return iv;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* XOR `data` with the key, cycling through key bytes.
|
|
109
|
+
* Self-inverse: _xorBuffer(_xorBuffer(x)) === x.
|
|
110
|
+
*
|
|
111
|
+
* Fast path: Uint32Array views over the existing Buffer memory — zero copy,
|
|
112
|
+
* no method-call overhead. V8 JITs `out32[i] = data32[i] ^ key32[...]`
|
|
113
|
+
* to a single `XOR r32, r32` instruction. Requires 4-byte-aligned byteOffsets,
|
|
114
|
+
* which Node.js guarantees (pool rounds up to 8 bytes; direct allocs to page).
|
|
115
|
+
*
|
|
116
|
+
* WARNING: XOR is NOT cryptographic. It provides obfuscation only.
|
|
117
|
+
*/
|
|
118
|
+
private _xorBuffer(data: Buffer): Buffer {
|
|
119
|
+
const key = this._key!;
|
|
120
|
+
const klen = key.length;
|
|
121
|
+
const len = data.length;
|
|
122
|
+
const out = Buffer.allocUnsafe(len);
|
|
123
|
+
|
|
124
|
+
if (
|
|
125
|
+
klen % 4 === 0 &&
|
|
126
|
+
len >= 4 &&
|
|
127
|
+
data.byteOffset % 4 === 0 &&
|
|
128
|
+
out.byteOffset % 4 === 0 &&
|
|
129
|
+
key.byteOffset % 4 === 0
|
|
130
|
+
) {
|
|
131
|
+
const wordCount = len >>> 2;
|
|
132
|
+
const data32 = new Uint32Array(data.buffer, data.byteOffset, wordCount);
|
|
133
|
+
const out32 = new Uint32Array(out.buffer, out.byteOffset, wordCount);
|
|
134
|
+
const key32 = new Uint32Array(key.buffer, key.byteOffset, klen >>> 2);
|
|
135
|
+
const kLen32 = key32.length;
|
|
136
|
+
for (let i = 0; i < wordCount; i++) {
|
|
137
|
+
out32[i] = data32[i] ^ key32[i % kLen32];
|
|
138
|
+
}
|
|
139
|
+
// 0–3 trailing bytes
|
|
140
|
+
for (let i = wordCount << 2; i < len; i++) {
|
|
141
|
+
out[i] = data[i] ^ key[i % klen];
|
|
142
|
+
}
|
|
143
|
+
return out;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// Fallback: buffer not 4-byte-aligned or key length not a multiple of 4
|
|
147
|
+
for (let i = 0; i < len; i++) {
|
|
148
|
+
out[i] = data[i] ^ key[i % klen];
|
|
149
|
+
}
|
|
150
|
+
return out;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
constructor(keyBase64: string | undefined, logger: ILogger, mode: EncryptionMode = 'aes-256-gcm') {
|
|
154
|
+
this._mode = mode;
|
|
155
|
+
if (!keyBase64) {
|
|
156
|
+
if (process.env.NODE_ENV === 'production') {
|
|
157
|
+
logger.warn(
|
|
158
|
+
'SECURITY: encryption key not set — cache data stored unencrypted at rest',
|
|
159
|
+
{ hint: 'Set encryptionKey option or CACHE_ENCRYPTION_KEY env var' },
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
try {
|
|
165
|
+
const buf = Buffer.from(keyBase64, 'base64');
|
|
166
|
+
const requiredLen = mode === 'aes-256-gcm' ? 32 : (mode === 'aes-128-gcm' || mode === 'aes-128-ctr') ? 16 : 0;
|
|
167
|
+
if (requiredLen > 0 && buf.length !== requiredLen) {
|
|
168
|
+
throw new Error(`${mode} requires exactly ${requiredLen} bytes (got ${buf.length})`);
|
|
169
|
+
}
|
|
170
|
+
if (buf.length < 1) {
|
|
171
|
+
throw new Error('XOR key must be at least 1 byte');
|
|
172
|
+
}
|
|
173
|
+
this._key = buf;
|
|
174
|
+
if (mode === 'xor') {
|
|
175
|
+
logger.warn(
|
|
176
|
+
'Cache obfuscation enabled (XOR). WARNING: XOR is NOT cryptographic — use only for dev or non-sensitive data.',
|
|
177
|
+
);
|
|
178
|
+
} else {
|
|
179
|
+
logger.debug(`Cache encryption enabled (${mode.toUpperCase()})`);
|
|
180
|
+
}
|
|
181
|
+
} catch (err) {
|
|
182
|
+
logger.error('Invalid encryption key — falling back to plaintext', {}, err as Error);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
get isEnabled(): boolean { return this._key !== null; }
|
|
187
|
+
|
|
188
|
+
// ── String (Redis) ────────────────────────────────────────────────────────
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Encrypt a string for Redis storage.
|
|
192
|
+
* Returns a mode-prefixed base64 string when a key is configured;
|
|
193
|
+
* otherwise returns the original string unchanged (backward-compatible).
|
|
194
|
+
*/
|
|
195
|
+
encrypt(plaintext: string): string {
|
|
196
|
+
if (!this._key) return plaintext;
|
|
197
|
+
if (this._mode === 'xor') {
|
|
198
|
+
// WARNING: XOR is NOT cryptographic — obfuscation only.
|
|
199
|
+
const masked = this._xorBuffer(Buffer.from(plaintext, 'utf8'));
|
|
200
|
+
return PREFIX_XOR + masked.toString('base64');
|
|
201
|
+
}
|
|
202
|
+
if (this._mode === 'aes-128-ctr') {
|
|
203
|
+
const iv = this._nextCtrIV();
|
|
204
|
+
const c = createCipheriv('aes-128-ctr', this._key, iv);
|
|
205
|
+
const enc = c.update(plaintext, 'utf8'); // CTR: stream cipher — final() emits no bytes
|
|
206
|
+
c.final();
|
|
207
|
+
const out = Buffer.allocUnsafe(CTR_IV_BYTES + enc.length);
|
|
208
|
+
iv.copy(out, 0);
|
|
209
|
+
enc.copy(out, CTR_IV_BYTES);
|
|
210
|
+
return PREFIX_CTR + out.toString('base64');
|
|
211
|
+
}
|
|
212
|
+
const algo = this._mode === 'aes-128-gcm' ? 'aes-128-gcm' : 'aes-256-gcm';
|
|
213
|
+
const prefix = this._mode === 'aes-128-gcm' ? PREFIX_128 : PREFIX_256;
|
|
214
|
+
const iv = this._nextIV();
|
|
215
|
+
const c = createCipheriv(algo, this._key, iv);
|
|
216
|
+
const enc = c.update(plaintext, 'utf8'); // GCM: final() emits no bytes
|
|
217
|
+
c.final(); // finalise — makes auth tag available
|
|
218
|
+
const out = Buffer.allocUnsafe(IV_BYTES + TAG_BYTES + enc.length);
|
|
219
|
+
iv.copy(out, 0);
|
|
220
|
+
c.getAuthTag().copy(out, IV_BYTES);
|
|
221
|
+
enc.copy(out, IV_BYTES + TAG_BYTES);
|
|
222
|
+
return prefix + out.toString('base64');
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Decrypt a Redis value.
|
|
227
|
+
* Auto-detects the envelope prefix; returns plaintext unchanged if no prefix matches.
|
|
228
|
+
*/
|
|
229
|
+
decrypt(value: string): string {
|
|
230
|
+
if (value.startsWith(PREFIX_XOR)) {
|
|
231
|
+
if (!this._key) throw new Error('Cannot decrypt: encryption key is not set');
|
|
232
|
+
// WARNING: XOR is NOT cryptographic — obfuscation only.
|
|
233
|
+
const masked = Buffer.from(value.slice(PREFIX_XOR.length), 'base64');
|
|
234
|
+
return this._xorBuffer(masked).toString('utf8');
|
|
235
|
+
}
|
|
236
|
+
if (value.startsWith(PREFIX_CTR)) {
|
|
237
|
+
if (!this._key) throw new Error('Cannot decrypt: encryption key is not set');
|
|
238
|
+
const combined = Buffer.from(value.slice(PREFIX_CTR.length), 'base64');
|
|
239
|
+
const iv = combined.subarray(0, CTR_IV_BYTES);
|
|
240
|
+
const ct = combined.subarray(CTR_IV_BYTES);
|
|
241
|
+
const d = createDecipheriv('aes-128-ctr', this._key, iv);
|
|
242
|
+
const plain = d.update(ct); // CTR: stream cipher — final() emits no bytes
|
|
243
|
+
d.final();
|
|
244
|
+
return plain.toString('utf8');
|
|
245
|
+
}
|
|
246
|
+
const is256 = value.startsWith(PREFIX_256);
|
|
247
|
+
const is128 = value.startsWith(PREFIX_128);
|
|
248
|
+
if (!is256 && !is128) return value;
|
|
249
|
+
if (!this._key) throw new Error('Cannot decrypt: encryption key is not set');
|
|
250
|
+
const prefix = is128 ? PREFIX_128 : PREFIX_256;
|
|
251
|
+
const algo = is128 ? 'aes-128-gcm' : 'aes-256-gcm';
|
|
252
|
+
const combined = Buffer.from(value.slice(prefix.length), 'base64');
|
|
253
|
+
const iv = combined.subarray(0, IV_BYTES);
|
|
254
|
+
const tag = combined.subarray(IV_BYTES, IV_BYTES + TAG_BYTES);
|
|
255
|
+
const ct = combined.subarray(IV_BYTES + TAG_BYTES);
|
|
256
|
+
const d = createDecipheriv(algo, this._key, iv);
|
|
257
|
+
d.setAuthTag(tag);
|
|
258
|
+
const plain = d.update(ct); // GCM: final() emits no bytes
|
|
259
|
+
d.final(); // verifies auth tag — throws on tamper
|
|
260
|
+
return plain.toString('utf8');
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// ── Buffer (disk / snapshot) ──────────────────────────────────────────────
|
|
264
|
+
|
|
265
|
+
/** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */
|
|
266
|
+
encryptBuffer(data: Buffer): Buffer {
|
|
267
|
+
if (!this._key) return data;
|
|
268
|
+
if (this._mode === 'xor') {
|
|
269
|
+
// WARNING: XOR is NOT cryptographic — obfuscation only.
|
|
270
|
+
const masked = this._xorBuffer(data);
|
|
271
|
+
const out = Buffer.allocUnsafe(MAGIC_LEN + masked.length);
|
|
272
|
+
MAGIC_XOR.copy(out, 0);
|
|
273
|
+
masked.copy(out, MAGIC_LEN);
|
|
274
|
+
return out;
|
|
275
|
+
}
|
|
276
|
+
if (this._mode === 'aes-128-ctr') {
|
|
277
|
+
const iv = this._nextCtrIV();
|
|
278
|
+
const c = createCipheriv('aes-128-ctr', this._key, iv);
|
|
279
|
+
const enc = c.update(data); // CTR: stream cipher — final() emits no bytes
|
|
280
|
+
c.final();
|
|
281
|
+
// Single pre-allocated output buffer: magic(8) | iv(16) | ciphertext(N)
|
|
282
|
+
const out = Buffer.allocUnsafe(MAGIC_LEN + CTR_IV_BYTES + enc.length);
|
|
283
|
+
MAGIC_CTR.copy(out, 0);
|
|
284
|
+
iv.copy(out, MAGIC_LEN);
|
|
285
|
+
enc.copy(out, MAGIC_LEN + CTR_IV_BYTES);
|
|
286
|
+
return out;
|
|
287
|
+
}
|
|
288
|
+
const magic = this._mode === 'aes-128-gcm' ? MAGIC_128 : MAGIC_256;
|
|
289
|
+
const algo = this._mode === 'aes-128-gcm' ? 'aes-128-gcm' : 'aes-256-gcm';
|
|
290
|
+
const iv = this._nextIV();
|
|
291
|
+
const c = createCipheriv(algo, this._key, iv);
|
|
292
|
+
const enc = c.update(data); // GCM: final() emits no bytes
|
|
293
|
+
c.final(); // finalise — makes auth tag available
|
|
294
|
+
// Single pre-allocated output buffer: magic(8) | iv(12) | tag(16) | ciphertext(N)
|
|
295
|
+
const out = Buffer.allocUnsafe(MAGIC_LEN + IV_BYTES + TAG_BYTES + enc.length);
|
|
296
|
+
magic.copy(out, 0);
|
|
297
|
+
iv.copy(out, MAGIC_LEN);
|
|
298
|
+
c.getAuthTag().copy(out, MAGIC_LEN + IV_BYTES);
|
|
299
|
+
enc.copy(out, MAGIC_LEN + IV_BYTES + TAG_BYTES);
|
|
300
|
+
return out;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* Decrypt a raw Buffer from disk/snapshot.
|
|
305
|
+
* Auto-detects the magic header; returns the original buffer if no magic matches (legacy/unencrypted).
|
|
306
|
+
*/
|
|
307
|
+
decryptBuffer(data: Buffer): Buffer {
|
|
308
|
+
if (data.length < MAGIC_LEN) return data;
|
|
309
|
+
const magic = data.subarray(0, MAGIC_LEN);
|
|
310
|
+
|
|
311
|
+
if (magic.equals(MAGIC_XOR)) {
|
|
312
|
+
if (!this._key) throw new Error('Cannot decrypt buffer: encryption key is not set');
|
|
313
|
+
// WARNING: XOR is NOT cryptographic — obfuscation only.
|
|
314
|
+
return this._xorBuffer(data.subarray(MAGIC_LEN));
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
if (magic.equals(MAGIC_CTR)) {
|
|
318
|
+
if (!this._key) throw new Error('Cannot decrypt buffer: encryption key is not set');
|
|
319
|
+
const iv = data.subarray(MAGIC_LEN, MAGIC_LEN + CTR_IV_BYTES);
|
|
320
|
+
const ct = data.subarray(MAGIC_LEN + CTR_IV_BYTES);
|
|
321
|
+
const d = createDecipheriv('aes-128-ctr', this._key, iv);
|
|
322
|
+
const plain = d.update(ct); // CTR: stream cipher — final() emits no bytes
|
|
323
|
+
d.final();
|
|
324
|
+
return plain;
|
|
325
|
+
}
|
|
326
|
+
const is256 = magic.equals(MAGIC_256);
|
|
327
|
+
const is128 = magic.equals(MAGIC_128);
|
|
328
|
+
if (!is256 && !is128) return data;
|
|
329
|
+
if (!this._key) throw new Error('Cannot decrypt buffer: encryption key is not set');
|
|
330
|
+
const algo = is128 ? 'aes-128-gcm' : 'aes-256-gcm';
|
|
331
|
+
const iv = data.subarray(MAGIC_LEN, MAGIC_LEN + IV_BYTES);
|
|
332
|
+
const tag = data.subarray(MAGIC_LEN + IV_BYTES, MAGIC_LEN + IV_BYTES + TAG_BYTES);
|
|
333
|
+
const ct = data.subarray(MAGIC_LEN + IV_BYTES + TAG_BYTES);
|
|
334
|
+
const d = createDecipheriv(algo, this._key, iv);
|
|
335
|
+
d.setAuthTag(tag);
|
|
336
|
+
const plain = d.update(ct); // GCM: final() emits no bytes
|
|
337
|
+
d.final(); // verifies auth tag — throws on tamper
|
|
338
|
+
return plain;
|
|
339
|
+
}
|
|
340
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* tricache — three-tier cache for Node.js
|
|
3
|
+
*
|
|
4
|
+
* L1 (RAM) → L1.5 (disk) → L2 (Redis/Valkey) → your fetch function
|
|
5
|
+
*
|
|
6
|
+
* Quick start:
|
|
7
|
+
* import { CacheService, CachePriority } from 'tricache';
|
|
8
|
+
*
|
|
9
|
+
* const cache = CacheService.create({ redisHost: 'localhost' });
|
|
10
|
+
*
|
|
11
|
+
* const user = await cache.get(
|
|
12
|
+
* `user:${userId}`,
|
|
13
|
+
* () => db.users.findById(userId),
|
|
14
|
+
* 300, // 5-minute TTL
|
|
15
|
+
* );
|
|
16
|
+
*
|
|
17
|
+
* await cache.delete(`user:${userId}`);
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
export { CacheService } from './cache-service';
|
|
21
|
+
export { CacheEncryption, type EncryptionMode } from './encryption';
|
|
22
|
+
export { SmartMemoryCache } from './smart-memory-cache';
|
|
23
|
+
export { DiskTier } from './disk-tier';
|
|
24
|
+
export { WasmBloomFilter } from './wasm/bloom-filter-wasm';
|
|
25
|
+
|
|
26
|
+
export {
|
|
27
|
+
CachePriority,
|
|
28
|
+
consoleLogger,
|
|
29
|
+
type ILogger,
|
|
30
|
+
type CacheOptions,
|
|
31
|
+
type CacheMetrics,
|
|
32
|
+
type CategoryLimit,
|
|
33
|
+
type SmartCacheEntry,
|
|
34
|
+
type DiskCacheEntry,
|
|
35
|
+
type CacheHit,
|
|
36
|
+
} from './types';
|