tricache 0.5.1 → 0.6.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.
- package/README.md +133 -0
- package/dist/chunk-F24NEZGQ.js +342 -0
- package/dist/index.cjs +938 -217
- package/dist/index.d.cts +248 -6
- package/dist/index.d.ts +248 -6
- package/dist/index.js +845 -452
- 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 +6 -6
- package/src/cache-service.ts +510 -109
- package/src/disk-tier.ts +244 -28
- package/src/encryption.ts +47 -22
- package/src/serialize-worker.ts +56 -0
- package/src/smart-memory-cache.ts +105 -31
- package/src/types.ts +179 -1
- package/src/worker-pool.ts +190 -0
package/src/disk-tier.ts
CHANGED
|
@@ -17,8 +17,29 @@
|
|
|
17
17
|
import fs from 'fs';
|
|
18
18
|
import path from 'path';
|
|
19
19
|
import crypto from 'crypto';
|
|
20
|
+
import { createRequire } from 'module';
|
|
20
21
|
import { pack, unpack } from 'msgpackr';
|
|
21
22
|
import { DiskCacheEntry, ILogger } from './types.js';
|
|
23
|
+
|
|
24
|
+
// ── node:sqlite lazy bootstrap ────────────────────────────────────────────────
|
|
25
|
+
// Stable in Node 24; experimental (needs --experimental-sqlite) in Node 22.
|
|
26
|
+
// Falls back to file-only mode silently when unavailable (edge runtimes, etc.).
|
|
27
|
+
type _SqliteRow = Record<string, unknown>;
|
|
28
|
+
type _SqliteStmt = {
|
|
29
|
+
get(...p: unknown[]): _SqliteRow | undefined;
|
|
30
|
+
all(...p: unknown[]): _SqliteRow[];
|
|
31
|
+
run(...p: unknown[]): void;
|
|
32
|
+
};
|
|
33
|
+
type _SqliteDB = {
|
|
34
|
+
prepare(sql: string): _SqliteStmt;
|
|
35
|
+
exec(sql: string): void;
|
|
36
|
+
close(): void;
|
|
37
|
+
};
|
|
38
|
+
let _SqliteDB: (new (p: string) => _SqliteDB) | null = null;
|
|
39
|
+
try {
|
|
40
|
+
const _req = createRequire(import.meta.url);
|
|
41
|
+
_SqliteDB = (_req('node:sqlite') as { DatabaseSync: new (p: string) => _SqliteDB }).DatabaseSync;
|
|
42
|
+
} catch { /* node:sqlite unavailable — file-only mode */ }
|
|
22
43
|
// ── Encryption (self-contained to avoid circular import) ─────────────────────
|
|
23
44
|
|
|
24
45
|
const AES_ALGO = 'aes-256-gcm' as const;
|
|
@@ -65,6 +86,15 @@ export class DiskTier {
|
|
|
65
86
|
/** Next bucket index (0–255) for the staggered janitor wheel. */
|
|
66
87
|
private _nextJanitorBucket = 0;
|
|
67
88
|
|
|
89
|
+
// ── SQLite metadata index (optional, requires node:sqlite) ───────────────
|
|
90
|
+
private _db: _SqliteDB | null = null;
|
|
91
|
+
private _stmtInsert: _SqliteStmt | null = null; // INSERT OR REPLACE
|
|
92
|
+
private _stmtSelect: _SqliteStmt | null = null; // SELECT by key_hash
|
|
93
|
+
private _stmtDelete: _SqliteStmt | null = null; // DELETE by key_hash
|
|
94
|
+
private _stmtExpire: _SqliteStmt | null = null; // SELECT expired rows
|
|
95
|
+
private _stmtDelExp: _SqliteStmt | null = null; // DELETE expired rows
|
|
96
|
+
private _stmtStats: _SqliteStmt | null = null; // COUNT + SUM(size)
|
|
97
|
+
|
|
68
98
|
constructor(opts: DiskTierOptions) {
|
|
69
99
|
this.opts = opts;
|
|
70
100
|
}
|
|
@@ -76,14 +106,75 @@ export class DiskTier {
|
|
|
76
106
|
try {
|
|
77
107
|
fs.mkdirSync(this.opts.dir, { recursive: true, mode: 0o700 });
|
|
78
108
|
this.dirReady = true;
|
|
109
|
+
this._initSqlite();
|
|
79
110
|
} catch (err) {
|
|
80
111
|
this.opts.logger.warn('DiskTier: cannot create cache dir', { dir: this.opts.dir, error: (err as Error).message });
|
|
81
112
|
}
|
|
82
113
|
}
|
|
83
114
|
|
|
115
|
+
/**
|
|
116
|
+
* Initialise the SQLite metadata index. Called once after the cache directory
|
|
117
|
+
* is confirmed to exist. On any failure the instance silently falls back to
|
|
118
|
+
* file-only mode — all public methods handle `this._db === null`.
|
|
119
|
+
*
|
|
120
|
+
* Schema:
|
|
121
|
+
* meta(key_hash TEXT PK, file_path TEXT, expires_at INT, size INT)
|
|
122
|
+
* idx_expires on (expires_at) — makes WHERE expires_at <= ? O(log n).
|
|
123
|
+
*
|
|
124
|
+
* WAL + synchronous=NORMAL: durable enough for a cache (a crash loses at
|
|
125
|
+
* most one WAL frame — acceptable data loss for an L1.5 spill store).
|
|
126
|
+
*/
|
|
127
|
+
private _initSqlite(): void {
|
|
128
|
+
if (!_SqliteDB) return;
|
|
129
|
+
try {
|
|
130
|
+
const dbPath = path.join(this.opts.dir, 'meta.db');
|
|
131
|
+
this._db = new _SqliteDB(dbPath);
|
|
132
|
+
this._db.exec(`
|
|
133
|
+
PRAGMA journal_mode = WAL;
|
|
134
|
+
PRAGMA synchronous = NORMAL;
|
|
135
|
+
PRAGMA temp_store = MEMORY;
|
|
136
|
+
CREATE TABLE IF NOT EXISTS meta (
|
|
137
|
+
key_hash TEXT PRIMARY KEY,
|
|
138
|
+
file_path TEXT NOT NULL,
|
|
139
|
+
expires_at INTEGER NOT NULL,
|
|
140
|
+
size INTEGER NOT NULL DEFAULT 0
|
|
141
|
+
);
|
|
142
|
+
CREATE INDEX IF NOT EXISTS idx_expires ON meta (expires_at);
|
|
143
|
+
`);
|
|
144
|
+
this._stmtInsert = this._db.prepare(
|
|
145
|
+
'INSERT OR REPLACE INTO meta (key_hash, file_path, expires_at, size) VALUES (?,?,?,?)',
|
|
146
|
+
);
|
|
147
|
+
this._stmtSelect = this._db.prepare(
|
|
148
|
+
'SELECT file_path, expires_at FROM meta WHERE key_hash = ?',
|
|
149
|
+
);
|
|
150
|
+
this._stmtDelete = this._db.prepare('DELETE FROM meta WHERE key_hash = ?');
|
|
151
|
+
this._stmtExpire = this._db.prepare(
|
|
152
|
+
'SELECT key_hash, file_path, size FROM meta WHERE expires_at <= ?',
|
|
153
|
+
);
|
|
154
|
+
this._stmtDelExp = this._db.prepare('DELETE FROM meta WHERE expires_at <= ?');
|
|
155
|
+
this._stmtStats = this._db.prepare(
|
|
156
|
+
'SELECT COUNT(*) AS cnt, COALESCE(SUM(size), 0) AS bytes FROM meta',
|
|
157
|
+
);
|
|
158
|
+
// Seed in-memory counters from the index — avoids startup walkCacheFiles().
|
|
159
|
+
const row = this._stmtStats.get() as { cnt: number; bytes: number };
|
|
160
|
+
this.fileCount = row.cnt;
|
|
161
|
+
this.diskUsageBytes = row.bytes;
|
|
162
|
+
this.usageCounted = true;
|
|
163
|
+
this.opts.logger.debug('DiskTier: SQLite index ready', { entries: row.cnt });
|
|
164
|
+
} catch (err) {
|
|
165
|
+
this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete =
|
|
166
|
+
this._stmtExpire = this._stmtDelExp = this._stmtStats = null;
|
|
167
|
+
this.opts.logger.warn('DiskTier: SQLite init failed, using file-only mode', {
|
|
168
|
+
error: (err as Error).message,
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
84
173
|
private ensureUsageCounted(): void {
|
|
85
174
|
if (this.usageCounted) return;
|
|
86
175
|
this.usageCounted = true;
|
|
176
|
+
// SQLite path: counts were already seeded in _initSqlite() — nothing more to do.
|
|
177
|
+
if (this._db) return;
|
|
87
178
|
try {
|
|
88
179
|
this.ensureDir();
|
|
89
180
|
let total = 0;
|
|
@@ -283,10 +374,14 @@ export class DiskTier {
|
|
|
283
374
|
try {
|
|
284
375
|
await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
|
|
285
376
|
await fs.promises.writeFile(filePath, final, { mode: 0o600 });
|
|
377
|
+
if (this._db) {
|
|
378
|
+
this._stmtInsert!.run(hash, filePath, entry.expiresAt, final.length);
|
|
379
|
+
}
|
|
286
380
|
this.opts.logger.debug('DiskTier: entry saved', { key: key.slice(0, 50), bytes: final.length });
|
|
287
381
|
} catch (err) {
|
|
288
382
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, final.length); // rollback
|
|
289
383
|
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
384
|
+
if (this._db) try { this._stmtDelete!.run(hash); } catch { /* ok */ }
|
|
290
385
|
this.opts.logger.debug('DiskTier: save failed', { key: key.slice(0, 50), error: (err as Error).message });
|
|
291
386
|
}
|
|
292
387
|
}
|
|
@@ -297,24 +392,45 @@ export class DiskTier {
|
|
|
297
392
|
this.ensureDir();
|
|
298
393
|
if (!this.dirReady) return null;
|
|
299
394
|
|
|
300
|
-
const hash
|
|
301
|
-
|
|
302
|
-
|
|
395
|
+
const hash = this.keyToHash(key);
|
|
396
|
+
let filePath: string | null;
|
|
397
|
+
|
|
398
|
+
if (this._db) {
|
|
399
|
+
// SQLite fast path: single B-tree lookup replaces readdirSync + filename scan.
|
|
400
|
+
const row = this._stmtSelect!.get(hash) as { file_path: string; expires_at: number } | undefined;
|
|
401
|
+
if (!row) return null;
|
|
402
|
+
if (row.expires_at <= Date.now()) {
|
|
403
|
+
this._stmtDelete!.run(hash);
|
|
404
|
+
try {
|
|
405
|
+
const sz = fs.statSync(row.file_path).size;
|
|
406
|
+
fs.unlinkSync(row.file_path);
|
|
407
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
408
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
409
|
+
} catch { /* ok */ }
|
|
410
|
+
return null;
|
|
411
|
+
}
|
|
412
|
+
filePath = row.file_path;
|
|
413
|
+
} else {
|
|
414
|
+
filePath = this.findFilePath(hash);
|
|
415
|
+
if (!filePath) return null;
|
|
416
|
+
}
|
|
303
417
|
|
|
304
418
|
try {
|
|
305
|
-
// V3 fast
|
|
306
|
-
// when the entry is already
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
419
|
+
// V3 filename fast-path (file-only mode): expiresAt encoded in name avoids
|
|
420
|
+
// opening the file when the entry is already stale.
|
|
421
|
+
if (!this._db) {
|
|
422
|
+
const filename = path.basename(filePath);
|
|
423
|
+
if (filename.length === 77 && filename[64] === '_') {
|
|
424
|
+
const expiresAt = parseInt(filename.slice(65), 16);
|
|
425
|
+
if (expiresAt <= Date.now()) {
|
|
426
|
+
try {
|
|
427
|
+
const sz = fs.statSync(filePath).size;
|
|
428
|
+
fs.unlinkSync(filePath);
|
|
429
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
430
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
431
|
+
} catch { /* ok */ }
|
|
432
|
+
return null;
|
|
433
|
+
}
|
|
318
434
|
}
|
|
319
435
|
}
|
|
320
436
|
|
|
@@ -322,12 +438,18 @@ export class DiskTier {
|
|
|
322
438
|
if (stat.size > this.opts.entryMaxBytes) {
|
|
323
439
|
fs.unlinkSync(filePath);
|
|
324
440
|
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
441
|
+
if (this._db) this._stmtDelete!.run(hash);
|
|
325
442
|
return null;
|
|
326
443
|
}
|
|
327
444
|
|
|
328
445
|
const raw = fs.readFileSync(filePath);
|
|
329
446
|
// Delete immediately — entry will be promoted back to L1
|
|
330
|
-
try {
|
|
447
|
+
try {
|
|
448
|
+
fs.unlinkSync(filePath);
|
|
449
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, stat.size);
|
|
450
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
451
|
+
} catch { /* ok */ }
|
|
452
|
+
if (this._db) this._stmtDelete!.run(hash);
|
|
331
453
|
|
|
332
454
|
let decrypted: Buffer;
|
|
333
455
|
if (raw.length >= V2_HEADER_LEN && raw.subarray(0, 8).equals(DISK_MAGIC_V2)) {
|
|
@@ -350,6 +472,7 @@ export class DiskTier {
|
|
|
350
472
|
this.opts.logger.debug('DiskTier: hit (→L1)', { key: key.slice(0, 50), ageMs: Date.now() - payload.writtenAt });
|
|
351
473
|
return entry;
|
|
352
474
|
} catch (err) {
|
|
475
|
+
if (this._db) try { this._stmtDelete!.run(hash); } catch { /* ok */ }
|
|
353
476
|
this.opts.logger.debug('DiskTier: load failed', { key: key.slice(0, 50), error: (err as Error).message });
|
|
354
477
|
return null;
|
|
355
478
|
}
|
|
@@ -357,8 +480,15 @@ export class DiskTier {
|
|
|
357
480
|
|
|
358
481
|
/** Explicitly delete a key from disk (cache invalidation). */
|
|
359
482
|
delete(key: string): void {
|
|
360
|
-
const hash
|
|
361
|
-
|
|
483
|
+
const hash = this.keyToHash(key);
|
|
484
|
+
let filePath: string | null;
|
|
485
|
+
if (this._db) {
|
|
486
|
+
const row = this._stmtSelect!.get(hash) as { file_path: string } | undefined;
|
|
487
|
+
filePath = row?.file_path ?? null;
|
|
488
|
+
this._stmtDelete!.run(hash);
|
|
489
|
+
} else {
|
|
490
|
+
filePath = this.findFilePath(hash);
|
|
491
|
+
}
|
|
362
492
|
if (!filePath) return;
|
|
363
493
|
try {
|
|
364
494
|
const stat = fs.statSync(filePath);
|
|
@@ -372,6 +502,22 @@ export class DiskTier {
|
|
|
372
502
|
purgeExpired(): number {
|
|
373
503
|
this.ensureDir();
|
|
374
504
|
if (!this.dirReady) return 0;
|
|
505
|
+
|
|
506
|
+
if (this._db) {
|
|
507
|
+
// SQLite fast path: one indexed query finds all expired rows.
|
|
508
|
+
const now = Date.now();
|
|
509
|
+
const expired = this._stmtExpire!.all(now) as Array<{ key_hash: string; file_path: string; size: number }>;
|
|
510
|
+
for (const row of expired) {
|
|
511
|
+
try {
|
|
512
|
+
fs.unlinkSync(row.file_path);
|
|
513
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, row.size);
|
|
514
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
515
|
+
} catch { /* already gone */ }
|
|
516
|
+
}
|
|
517
|
+
if (expired.length > 0) this._stmtDelExp!.run(now);
|
|
518
|
+
return expired.length;
|
|
519
|
+
}
|
|
520
|
+
|
|
375
521
|
const now = Date.now();
|
|
376
522
|
let purged = 0;
|
|
377
523
|
// One reusable header buffer — avoids per-file allocation inside the V2 fallback loop.
|
|
@@ -442,22 +588,68 @@ export class DiskTier {
|
|
|
442
588
|
}
|
|
443
589
|
|
|
444
590
|
/**
|
|
445
|
-
* Purge expired entries
|
|
446
|
-
* advance the wheel pointer. Call on a short recurring interval (e.g. 30 s) so
|
|
447
|
-
* the O(fileCount) work of a full purgeExpired() is spread over 256 ticks instead
|
|
448
|
-
* of landing as one large synchronous burst every 5 minutes.
|
|
591
|
+
* Purge expired entries. Two modes depending on availability of SQLite:
|
|
449
592
|
*
|
|
450
|
-
*
|
|
451
|
-
*
|
|
593
|
+
* SQLite mode (Node 24 / Node 22 + --experimental-sqlite):
|
|
594
|
+
* One indexed query (`WHERE expires_at <= now`) replaces the entire bucket
|
|
595
|
+
* wheel. All expired entries are found and deleted in a single pass — the
|
|
596
|
+
* 128-minute stagger is no longer necessary. `_nextJanitorBucket` is still
|
|
597
|
+
* incremented so tests that inspect the counter continue to work.
|
|
598
|
+
*
|
|
599
|
+
* File-only fallback:
|
|
600
|
+
* Original staggered bucket wheel — purges exactly one of 256 subdirectory
|
|
601
|
+
* buckets per call, spreading the O(fileCount) work across 256 ticks.
|
|
452
602
|
*
|
|
453
603
|
* Returns the number of entries deleted in this tick.
|
|
454
604
|
*/
|
|
455
605
|
purgeNextBucket(): number {
|
|
456
606
|
this.ensureDir();
|
|
457
607
|
if (!this.dirReady) return 0;
|
|
458
|
-
|
|
608
|
+
// Always advance the pointer — preserves observable state for tests and
|
|
609
|
+
// metrics regardless of which code path runs below.
|
|
459
610
|
this._nextJanitorBucket = (this._nextJanitorBucket + 1) % 256;
|
|
460
|
-
|
|
611
|
+
|
|
612
|
+
if (this._db) {
|
|
613
|
+
const now = Date.now();
|
|
614
|
+
const expired = this._stmtExpire!.all(now) as Array<{ key_hash: string; file_path: string; size: number }>;
|
|
615
|
+
for (const row of expired) {
|
|
616
|
+
try {
|
|
617
|
+
fs.unlinkSync(row.file_path);
|
|
618
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, row.size);
|
|
619
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
620
|
+
} catch { /* already gone */ }
|
|
621
|
+
}
|
|
622
|
+
if (expired.length > 0) this._stmtDelExp!.run(now);
|
|
623
|
+
|
|
624
|
+
// Belt-and-suspenders: scan one filesystem bucket for orphan files — files
|
|
625
|
+
// written to disk before a crash between writeFile() and the SQLite INSERT.
|
|
626
|
+
// V3 fast path: no file I/O for live entries (expiry is in the filename).
|
|
627
|
+
// Expired orphans are unlinked here; they are invisible to the SQLite query.
|
|
628
|
+
const orphanBucket = (this._nextJanitorBucket - 1 + 256) % 256;
|
|
629
|
+
const orphanBucketP = path.join(this.opts.dir, orphanBucket.toString(16).padStart(2, '0'));
|
|
630
|
+
let orphanFiles: string[];
|
|
631
|
+
try { orphanFiles = fs.readdirSync(orphanBucketP); } catch { return expired.length; }
|
|
632
|
+
for (const file of orphanFiles) {
|
|
633
|
+
if (file.length === 77 && file[64] === '_') {
|
|
634
|
+
const expiresAt = parseInt(file.slice(65), 16);
|
|
635
|
+
if (expiresAt <= now) {
|
|
636
|
+
const fp = path.join(orphanBucketP, file);
|
|
637
|
+
try {
|
|
638
|
+
const sz = fs.statSync(fp).size;
|
|
639
|
+
fs.unlinkSync(fp);
|
|
640
|
+
this.diskUsageBytes -= Math.min(this.diskUsageBytes, sz);
|
|
641
|
+
this.fileCount = Math.max(0, this.fileCount - 1);
|
|
642
|
+
} catch { /* already gone */ }
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
return expired.length;
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
// ── File-only fallback: one-bucket scan ───────────────────────────────
|
|
650
|
+
const bucket = (this._nextJanitorBucket - 1 + 256) % 256; // use the bucket we just advanced past
|
|
651
|
+
const bucketHex = bucket.toString(16).padStart(2, '0');
|
|
652
|
+
const bucketPath = path.join(this.opts.dir, bucketHex);
|
|
461
653
|
let files: string[];
|
|
462
654
|
try { files = fs.readdirSync(bucketPath); } catch { return 0; }
|
|
463
655
|
const now = Date.now();
|
|
@@ -544,11 +736,35 @@ export class DiskTier {
|
|
|
544
736
|
cleared++;
|
|
545
737
|
} catch { /* skip locked/gone */ }
|
|
546
738
|
}
|
|
739
|
+
if (this._db) {
|
|
740
|
+
this._db.exec('DELETE FROM meta');
|
|
741
|
+
this.diskUsageBytes = 0;
|
|
742
|
+
this.fileCount = 0;
|
|
743
|
+
}
|
|
547
744
|
return cleared;
|
|
548
745
|
}
|
|
549
746
|
|
|
550
747
|
get stats(): { files: number; sizeKB: number; maxKB: number } {
|
|
551
|
-
|
|
748
|
+
if (this._db) {
|
|
749
|
+
// Query the index for authoritative counts — O(1) SQLite aggregate.
|
|
750
|
+
const row = this._stmtStats!.get() as { cnt: number; bytes: number };
|
|
751
|
+
this.fileCount = row.cnt;
|
|
752
|
+
this.diskUsageBytes = row.bytes;
|
|
753
|
+
}
|
|
552
754
|
return { files: this.fileCount, sizeKB: Math.round(this.diskUsageBytes / 1024), maxKB: Math.round(this.opts.maxBytes / 1024) };
|
|
553
755
|
}
|
|
756
|
+
|
|
757
|
+
/** Whether a SQLite metadata index is active ('sqlite') or the disk is scanned directly ('file-only'). */
|
|
758
|
+
get indexMode(): 'sqlite' | 'file-only' {
|
|
759
|
+
return this._db ? 'sqlite' : 'file-only';
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
/** Release the SQLite connection (if open). Call during shutdown before deleting the cache directory. */
|
|
763
|
+
close(): void {
|
|
764
|
+
if (this._db) {
|
|
765
|
+
try { this._db.close(); } catch { /* ok */ }
|
|
766
|
+
this._db = this._stmtInsert = this._stmtSelect = this._stmtDelete =
|
|
767
|
+
this._stmtExpire = this._stmtDelExp = this._stmtStats = null;
|
|
768
|
+
}
|
|
769
|
+
}
|
|
554
770
|
}
|
package/src/encryption.ts
CHANGED
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
* TRIC1XOR | key⊕data[N] ← XOR
|
|
34
34
|
*/
|
|
35
35
|
|
|
36
|
-
import { createCipheriv, createDecipheriv, randomFillSync } from 'crypto';
|
|
36
|
+
import { createCipheriv, createDecipheriv, createSecretKey, randomFillSync, type KeyObject } from 'crypto';
|
|
37
37
|
import type { ILogger } from './types';
|
|
38
38
|
|
|
39
39
|
// ── Public type ───────────────────────────────────────────────────────────────
|
|
@@ -71,9 +71,11 @@ const PREFIX_CTR = 'ctr:v1:'; // AES-128-CTR (no auth tag)
|
|
|
71
71
|
const IV_POOL_COUNT = 64;
|
|
72
72
|
|
|
73
73
|
export class CacheEncryption {
|
|
74
|
-
private _key:
|
|
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
|
|
75
76
|
private readonly _mode: EncryptionMode;
|
|
76
|
-
private _prevKey:
|
|
77
|
+
private _prevKey: Buffer | null = null;
|
|
78
|
+
private _prevKeyObj: KeyObject | null = null;
|
|
77
79
|
private _prevMode: EncryptionMode = 'aes-256-gcm';
|
|
78
80
|
|
|
79
81
|
// Pre-allocated GCM IV pool — 12-byte IVs (96-bit, NIST recommended).
|
|
@@ -179,6 +181,19 @@ export class CacheEncryption {
|
|
|
179
181
|
throw new Error('XOR key must be at least 1 byte');
|
|
180
182
|
}
|
|
181
183
|
this._key = buf;
|
|
184
|
+
if (mode !== 'xor') {
|
|
185
|
+
this._keyObj = createSecretKey(buf);
|
|
186
|
+
// Pre-warm OpenSSL's lazy key-schedule cache: first use of a KeyObject is slower
|
|
187
|
+
// because OpenSSL initialises internal state on demand. Paying that cost now
|
|
188
|
+
// (at construction) guarantees every production encrypt/decrypt call is fast.
|
|
189
|
+
const _wc = createCipheriv(
|
|
190
|
+
mode,
|
|
191
|
+
this._keyObj,
|
|
192
|
+
Buffer.alloc(mode === 'aes-128-ctr' ? CTR_IV_BYTES : IV_BYTES),
|
|
193
|
+
);
|
|
194
|
+
_wc.update(Buffer.alloc(0));
|
|
195
|
+
_wc.final();
|
|
196
|
+
}
|
|
182
197
|
if (mode === 'xor') {
|
|
183
198
|
logger.warn(
|
|
184
199
|
'Cache obfuscation enabled (XOR). WARNING: XOR is NOT cryptographic — use only for dev or non-sensitive data.',
|
|
@@ -194,6 +209,16 @@ export class CacheEncryption {
|
|
|
194
209
|
try {
|
|
195
210
|
this._prevMode = previousMode ?? mode;
|
|
196
211
|
this._prevKey = Buffer.from(previousKeyBase64, 'base64');
|
|
212
|
+
if (this._prevMode !== 'xor') {
|
|
213
|
+
this._prevKeyObj = createSecretKey(this._prevKey);
|
|
214
|
+
const _wc = createCipheriv(
|
|
215
|
+
this._prevMode,
|
|
216
|
+
this._prevKeyObj,
|
|
217
|
+
Buffer.alloc(this._prevMode === 'aes-128-ctr' ? CTR_IV_BYTES : IV_BYTES),
|
|
218
|
+
);
|
|
219
|
+
_wc.update(Buffer.alloc(0));
|
|
220
|
+
_wc.final();
|
|
221
|
+
}
|
|
197
222
|
logger.debug('Previous encryption key loaded for key rotation fallback');
|
|
198
223
|
} catch (err) {
|
|
199
224
|
logger.warn('Invalid previousEncryptionKey — rotation fallback disabled', { error: (err as Error).message });
|
|
@@ -219,7 +244,7 @@ export class CacheEncryption {
|
|
|
219
244
|
}
|
|
220
245
|
if (this._mode === 'aes-128-ctr') {
|
|
221
246
|
const iv = this._nextCtrIV();
|
|
222
|
-
const c = createCipheriv('aes-128-ctr', this.
|
|
247
|
+
const c = createCipheriv('aes-128-ctr', this._keyObj!, iv);
|
|
223
248
|
const enc = c.update(plaintext, 'utf8');
|
|
224
249
|
const fin = c.final(); // CTR: almost always empty — captured defensively
|
|
225
250
|
const out = Buffer.allocUnsafe(CTR_IV_BYTES + enc.length + fin.length);
|
|
@@ -231,7 +256,7 @@ export class CacheEncryption {
|
|
|
231
256
|
const algo = this._mode === 'aes-128-gcm' ? 'aes-128-gcm' : 'aes-256-gcm';
|
|
232
257
|
const prefix = this._mode === 'aes-128-gcm' ? PREFIX_128 : PREFIX_256;
|
|
233
258
|
const iv = this._nextIV();
|
|
234
|
-
const c = createCipheriv(algo, this.
|
|
259
|
+
const c = createCipheriv(algo, this._keyObj!, iv);
|
|
235
260
|
const enc = c.update(plaintext, 'utf8'); // GCM: final() emits no bytes
|
|
236
261
|
c.final(); // finalise — makes auth tag available
|
|
237
262
|
const out = Buffer.allocUnsafe(IV_BYTES + TAG_BYTES + enc.length);
|
|
@@ -248,18 +273,18 @@ export class CacheEncryption {
|
|
|
248
273
|
*/
|
|
249
274
|
decrypt(value: string): string {
|
|
250
275
|
try {
|
|
251
|
-
return this._decryptWithKey(value, this._key, this._mode);
|
|
276
|
+
return this._decryptWithKey(value, this._key, this._keyObj, this._mode);
|
|
252
277
|
} catch (primaryErr) {
|
|
253
278
|
if (this._prevKey) {
|
|
254
279
|
try {
|
|
255
|
-
return this._decryptWithKey(value, this._prevKey, this._prevMode);
|
|
280
|
+
return this._decryptWithKey(value, this._prevKey, this._prevKeyObj, this._prevMode);
|
|
256
281
|
} catch { /* ignore — fall through to re-throw primary */ }
|
|
257
282
|
}
|
|
258
283
|
throw primaryErr;
|
|
259
284
|
}
|
|
260
285
|
}
|
|
261
286
|
|
|
262
|
-
private _decryptWithKey(value: string, key: Buffer | null, mode: EncryptionMode): string {
|
|
287
|
+
private _decryptWithKey(value: string, key: Buffer | null, keyObj: KeyObject | null, mode: EncryptionMode): string {
|
|
263
288
|
if (value.startsWith(PREFIX_XOR)) {
|
|
264
289
|
if (!key) throw new Error('Cannot decrypt: encryption key is not set');
|
|
265
290
|
// WARNING: XOR is NOT cryptographic — obfuscation only.
|
|
@@ -272,11 +297,11 @@ export class CacheEncryption {
|
|
|
272
297
|
return out.toString('utf8');
|
|
273
298
|
}
|
|
274
299
|
if (value.startsWith(PREFIX_CTR)) {
|
|
275
|
-
if (!
|
|
300
|
+
if (!keyObj) throw new Error('Cannot decrypt: encryption key is not set');
|
|
276
301
|
const combined = Buffer.from(value.slice(PREFIX_CTR.length), 'base64');
|
|
277
302
|
const iv = combined.subarray(0, CTR_IV_BYTES);
|
|
278
303
|
const ct = combined.subarray(CTR_IV_BYTES);
|
|
279
|
-
const d = createDecipheriv('aes-128-ctr',
|
|
304
|
+
const d = createDecipheriv('aes-128-ctr', keyObj, iv);
|
|
280
305
|
const plain = d.update(ct);
|
|
281
306
|
const fin = d.final(); // CTR: almost always empty — concat before UTF-8 decode to avoid split-sequence corruption
|
|
282
307
|
return (fin.length > 0 ? Buffer.concat([plain, fin]) : plain).toString('utf8');
|
|
@@ -284,19 +309,19 @@ export class CacheEncryption {
|
|
|
284
309
|
const is256 = value.startsWith(PREFIX_256);
|
|
285
310
|
const is128 = value.startsWith(PREFIX_128);
|
|
286
311
|
if (!is256 && !is128) return value;
|
|
287
|
-
if (!
|
|
312
|
+
if (!keyObj) throw new Error('Cannot decrypt: encryption key is not set');
|
|
288
313
|
const prefix = is128 ? PREFIX_128 : PREFIX_256;
|
|
289
314
|
const algo = is128 ? 'aes-128-gcm' : 'aes-256-gcm';
|
|
290
315
|
const combined = Buffer.from(value.slice(prefix.length), 'base64');
|
|
291
316
|
const iv = combined.subarray(0, IV_BYTES);
|
|
292
317
|
const tag = combined.subarray(IV_BYTES, IV_BYTES + TAG_BYTES);
|
|
293
318
|
const ct = combined.subarray(IV_BYTES + TAG_BYTES);
|
|
294
|
-
const d = createDecipheriv(algo,
|
|
319
|
+
const d = createDecipheriv(algo, keyObj, iv);
|
|
295
320
|
d.setAuthTag(tag);
|
|
296
321
|
const plain = d.update(ct); // GCM: final() emits no bytes
|
|
297
322
|
d.final(); // verifies auth tag — throws on tamper
|
|
298
323
|
return plain.toString('utf8');
|
|
299
|
-
void mode; // mode
|
|
324
|
+
void mode; void key; // mode and raw key used implicitly (mode via prefix; key via keyObj for AES, directly for XOR)
|
|
300
325
|
}
|
|
301
326
|
|
|
302
327
|
// ── Buffer (disk / snapshot) ──────────────────────────────────────────────
|
|
@@ -314,7 +339,7 @@ export class CacheEncryption {
|
|
|
314
339
|
}
|
|
315
340
|
if (this._mode === 'aes-128-ctr') {
|
|
316
341
|
const iv = this._nextCtrIV();
|
|
317
|
-
const c = createCipheriv('aes-128-ctr', this.
|
|
342
|
+
const c = createCipheriv('aes-128-ctr', this._keyObj!, iv);
|
|
318
343
|
const enc = c.update(data);
|
|
319
344
|
const fin = c.final(); // CTR: almost always empty — captured defensively
|
|
320
345
|
// Single pre-allocated output buffer: magic(8) | iv(16) | ciphertext(N)
|
|
@@ -328,7 +353,7 @@ export class CacheEncryption {
|
|
|
328
353
|
const magic = this._mode === 'aes-128-gcm' ? MAGIC_128 : MAGIC_256;
|
|
329
354
|
const algo = this._mode === 'aes-128-gcm' ? 'aes-128-gcm' : 'aes-256-gcm';
|
|
330
355
|
const iv = this._nextIV();
|
|
331
|
-
const c = createCipheriv(algo, this.
|
|
356
|
+
const c = createCipheriv(algo, this._keyObj!, iv);
|
|
332
357
|
const enc = c.update(data); // GCM: final() emits no bytes
|
|
333
358
|
c.final(); // finalise — makes auth tag available
|
|
334
359
|
// Single pre-allocated output buffer: magic(8) | iv(12) | tag(16) | ciphertext(N)
|
|
@@ -347,18 +372,18 @@ export class CacheEncryption {
|
|
|
347
372
|
*/
|
|
348
373
|
decryptBuffer(data: Buffer): Buffer {
|
|
349
374
|
try {
|
|
350
|
-
return this._decryptBufferWithKey(data, this._key);
|
|
375
|
+
return this._decryptBufferWithKey(data, this._key, this._keyObj);
|
|
351
376
|
} catch (primaryErr) {
|
|
352
377
|
if (this._prevKey) {
|
|
353
378
|
try {
|
|
354
|
-
return this._decryptBufferWithKey(data, this._prevKey);
|
|
379
|
+
return this._decryptBufferWithKey(data, this._prevKey, this._prevKeyObj);
|
|
355
380
|
} catch { /* ignore — re-throw primary */ }
|
|
356
381
|
}
|
|
357
382
|
throw primaryErr;
|
|
358
383
|
}
|
|
359
384
|
}
|
|
360
385
|
|
|
361
|
-
private _decryptBufferWithKey(data: Buffer, key: Buffer | null): Buffer {
|
|
386
|
+
private _decryptBufferWithKey(data: Buffer, key: Buffer | null, keyObj: KeyObject | null): Buffer {
|
|
362
387
|
if (data.length < MAGIC_LEN) return data;
|
|
363
388
|
const magic = data.subarray(0, MAGIC_LEN);
|
|
364
389
|
|
|
@@ -373,10 +398,10 @@ export class CacheEncryption {
|
|
|
373
398
|
}
|
|
374
399
|
|
|
375
400
|
if (magic.equals(MAGIC_CTR)) {
|
|
376
|
-
if (!
|
|
401
|
+
if (!keyObj) throw new Error('Cannot decrypt buffer: encryption key is not set');
|
|
377
402
|
const iv = data.subarray(MAGIC_LEN, MAGIC_LEN + CTR_IV_BYTES);
|
|
378
403
|
const ct = data.subarray(MAGIC_LEN + CTR_IV_BYTES);
|
|
379
|
-
const d = createDecipheriv('aes-128-ctr',
|
|
404
|
+
const d = createDecipheriv('aes-128-ctr', keyObj, iv);
|
|
380
405
|
const plain = d.update(ct);
|
|
381
406
|
const fin = d.final(); // CTR: almost always empty — captured defensively
|
|
382
407
|
return fin.length > 0 ? Buffer.concat([plain, fin]) : plain;
|
|
@@ -384,12 +409,12 @@ export class CacheEncryption {
|
|
|
384
409
|
const is256 = magic.equals(MAGIC_256);
|
|
385
410
|
const is128 = magic.equals(MAGIC_128);
|
|
386
411
|
if (!is256 && !is128) return data;
|
|
387
|
-
if (!
|
|
412
|
+
if (!keyObj) throw new Error('Cannot decrypt buffer: encryption key is not set');
|
|
388
413
|
const algo = is128 ? 'aes-128-gcm' : 'aes-256-gcm';
|
|
389
414
|
const iv = data.subarray(MAGIC_LEN, MAGIC_LEN + IV_BYTES);
|
|
390
415
|
const tag = data.subarray(MAGIC_LEN + IV_BYTES, MAGIC_LEN + IV_BYTES + TAG_BYTES);
|
|
391
416
|
const ct = data.subarray(MAGIC_LEN + IV_BYTES + TAG_BYTES);
|
|
392
|
-
const d = createDecipheriv(algo,
|
|
417
|
+
const d = createDecipheriv(algo, keyObj, iv);
|
|
393
418
|
d.setAuthTag(tag);
|
|
394
419
|
const plain = d.update(ct); // GCM: final() emits no bytes
|
|
395
420
|
d.final(); // verifies auth tag — throws on tamper
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* serialize-worker — worker-thread entry point for off-main-thread encryption/decryption.
|
|
3
|
+
*
|
|
4
|
+
* Receives messages from WorkerPool:
|
|
5
|
+
* { id: number; type: 'encrypt'; payload: string }
|
|
6
|
+
* { id: number; type: 'decrypt'; payload: string }
|
|
7
|
+
*
|
|
8
|
+
* Posts back:
|
|
9
|
+
* { id: number; result: string } — on success
|
|
10
|
+
* { id: number; error: string } — on failure
|
|
11
|
+
*
|
|
12
|
+
* The encryption key and mode are received once via workerData at thread creation,
|
|
13
|
+
* so no key material travels with every per-message IPC call.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { parentPort, workerData } from 'worker_threads';
|
|
17
|
+
import { CacheEncryption } from './encryption.js';
|
|
18
|
+
import type { EncryptionMode } from './encryption.js';
|
|
19
|
+
import type { ILogger } from './types.js';
|
|
20
|
+
|
|
21
|
+
interface WorkerInit {
|
|
22
|
+
keyBase64: string;
|
|
23
|
+
mode: EncryptionMode;
|
|
24
|
+
prevKeyBase64: string | undefined;
|
|
25
|
+
prevMode: EncryptionMode | undefined;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Minimal no-op logger — worker thread does not log to avoid interleaved I/O.
|
|
29
|
+
const silentLogger: ILogger = {
|
|
30
|
+
debug: () => {},
|
|
31
|
+
info: () => {},
|
|
32
|
+
warn: () => {},
|
|
33
|
+
error: () => {},
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
const { keyBase64, mode, prevKeyBase64, prevMode } = workerData as WorkerInit;
|
|
37
|
+
|
|
38
|
+
const enc = new CacheEncryption(
|
|
39
|
+
keyBase64 || undefined,
|
|
40
|
+
silentLogger,
|
|
41
|
+
mode,
|
|
42
|
+
prevKeyBase64 || undefined,
|
|
43
|
+
prevMode,
|
|
44
|
+
);
|
|
45
|
+
|
|
46
|
+
parentPort!.on('message', ({ id, type, payload }: { id: number; type: 'encrypt' | 'decrypt'; payload: string }) => {
|
|
47
|
+
try {
|
|
48
|
+
if (type === 'encrypt') {
|
|
49
|
+
parentPort!.postMessage({ id, result: enc.encrypt(payload) });
|
|
50
|
+
} else {
|
|
51
|
+
parentPort!.postMessage({ id, result: enc.decrypt(payload) });
|
|
52
|
+
}
|
|
53
|
+
} catch (e) {
|
|
54
|
+
parentPort!.postMessage({ id, error: (e as Error).message });
|
|
55
|
+
}
|
|
56
|
+
});
|