tricache 0.7.1 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +87 -1371
- package/dashboards/tricache-alerts.yaml +54 -0
- package/dashboards/tricache-grafana.json +548 -0
- package/dist/cache-service-5MZXFIGK.js +12 -0
- package/dist/cache-service-CyLdpo77.d.ts +871 -0
- package/dist/{chunk-EUGYR7KR.js → chunk-6PQ5MOWR.js} +2871 -490
- package/dist/chunk-7RV5ZVBB.js +1023 -0
- package/dist/{chunk-X5AXHPVD.js → chunk-LJ5QJB5O.js} +90 -5
- package/dist/chunk-QNU7B43J.js +687 -0
- package/dist/chunk-UGD4VEPD.js +138 -0
- package/dist/chunk-XZL45ABR.js +108 -0
- package/dist/chunk-ZTSWCFYO.js +135 -0
- package/dist/cli.cjs +2790 -471
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +103 -5
- package/dist/dashboard/index.cjs +1065 -0
- package/dist/dashboard/index.d.ts +183 -0
- package/dist/dashboard/index.js +22 -0
- package/dist/drizzle/index.cjs +2553 -470
- package/dist/drizzle/index.d.ts +3 -1
- package/dist/drizzle/index.js +1 -1
- package/dist/edge/index.cjs +1498 -0
- package/dist/edge/index.d.ts +127 -0
- package/dist/edge/index.js +1109 -0
- package/dist/hono-DQRS1Xd7.d.ts +370 -0
- package/dist/http/index.cjs +2926 -562
- package/dist/http/index.d.ts +109 -23
- package/dist/http/index.js +220 -72
- package/dist/index.cjs +6936 -2518
- package/dist/index.d.ts +547 -30
- package/dist/index.js +104 -5
- package/dist/murmur3-CMGw9PbV.d.ts +98 -0
- package/dist/nestjs/index.cjs +2494 -463
- package/dist/nestjs/index.d.ts +3 -1
- package/dist/nestjs/index.js +6 -3
- package/dist/next/index.cjs +2517 -483
- package/dist/next/index.d.ts +4 -2
- package/dist/next/index.js +14 -10
- package/dist/prisma/index.d.ts +3 -1
- package/dist/serialize-worker.cjs +5 -4
- package/dist/serialize-worker.js +1 -1
- package/dist/{cache-service-D8tIXmzb.d.ts → types-B6krw64X.d.ts} +596 -659
- package/package.json +34 -6
- package/src/adapters/auto-pipeliner.ts +206 -0
- package/src/adapters/node-redis.ts +370 -0
- package/src/cache-service.ts +1339 -402
- package/src/cli.ts +120 -2
- package/src/codec.ts +72 -0
- package/src/cross-region.ts +245 -0
- package/src/dashboard/handler.ts +392 -0
- package/src/dashboard/html.ts +594 -0
- package/src/dashboard/index.ts +195 -0
- package/src/dashboard/types.ts +96 -0
- package/src/disk-tier.ts +449 -47
- package/src/drizzle/index.ts +86 -86
- package/src/edge/adapters/cloudflare-do.ts +130 -0
- package/src/edge/adapters/cloudflare-kv.ts +115 -0
- package/src/edge/adapters/upstash.ts +143 -0
- package/src/edge/cache.ts +797 -0
- package/src/edge/crypto.ts +182 -0
- package/src/edge/hono.ts +203 -0
- package/src/edge/index.ts +37 -0
- package/src/edge/types.ts +230 -0
- package/src/edge/utils/base64.ts +63 -0
- package/src/edge/utils/murmur3.ts +179 -0
- package/src/encryption.ts +127 -5
- package/src/http/express.ts +195 -0
- package/src/http/fastify.ts +260 -0
- package/src/http/index.ts +39 -258
- package/src/http/utils.ts +92 -0
- package/src/index.ts +149 -47
- package/src/ipc-telemetry.ts +481 -0
- package/src/latency-watchdog.ts +282 -0
- package/src/nestjs/decorators.ts +161 -161
- package/src/nestjs/index.ts +23 -23
- package/src/nestjs/tricache.module.ts +104 -104
- package/src/nestjs/tricache.store.ts +97 -97
- package/src/nestjs/types.ts +79 -79
- package/src/next/cache-handler.ts +12 -9
- package/src/next/index.ts +37 -37
- package/src/next/isr-handler.ts +105 -105
- package/src/next/types.ts +130 -130
- package/src/remote-snapshot.ts +153 -0
- package/src/serialize-worker.ts +120 -120
- package/src/sigv4-snapshot-adapter.ts +260 -0
- package/src/smart-memory-cache.ts +91 -8
- package/src/types.ts +290 -2
- package/src/utils/cgroup.ts +100 -0
- package/src/utils/tracing.ts +54 -0
- package/src/wasm/bloom-filter-wasm.ts +109 -102
- package/src/worker-pool.ts +299 -299
- package/src/wtiny-lfu.ts +624 -0
- package/dist/cache-service-5GATUYAK.js +0 -7
- package/dist/chunk-UBSR5UYA.js +0 -0
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Zero-dependency Base64 <-> Uint8Array utilities designed for pure Edge isolates
|
|
3
|
+
* (Cloudflare Workers without nodejs_compat, Deno, Fastly Compute, browsers).
|
|
4
|
+
*
|
|
5
|
+
* Avoids call stack overflow (RangeError: Maximum call stack size exceeded)
|
|
6
|
+
* on payloads > 64 KB by chunking binary data into safe 8 KB slices.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
const CHUNK_SIZE = 8192;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Converts a Uint8Array to a standard Base64 string safely across all JS runtimes.
|
|
13
|
+
*/
|
|
14
|
+
export function uint8ArrayToBase64(bytes: Uint8Array): string {
|
|
15
|
+
// 1. Modern TC39 stage 3 Uint8Array.prototype.toBase64 support
|
|
16
|
+
const modernBytes = bytes as unknown as { toBase64?: () => string };
|
|
17
|
+
if (typeof modernBytes.toBase64 === 'function') {
|
|
18
|
+
return modernBytes.toBase64();
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// 2. Fallback using chunked String.fromCharCode + btoa
|
|
22
|
+
let binary = '';
|
|
23
|
+
const len = bytes.length;
|
|
24
|
+
for (let i = 0; i < len; i += CHUNK_SIZE) {
|
|
25
|
+
const chunk = bytes.subarray(i, Math.min(i + CHUNK_SIZE, len));
|
|
26
|
+
binary += String.fromCharCode(...chunk);
|
|
27
|
+
}
|
|
28
|
+
return globalThis.btoa(binary);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Converts a Base64 string to a Uint8Array safely across all JS runtimes.
|
|
33
|
+
*/
|
|
34
|
+
export function base64ToUint8Array(base64: string): Uint8Array {
|
|
35
|
+
// 1. Modern TC39 stage 3 Uint8Array.fromBase64 support
|
|
36
|
+
const modernU8 = Uint8Array as unknown as { fromBase64?: (s: string) => Uint8Array };
|
|
37
|
+
if (typeof modernU8.fromBase64 === 'function') {
|
|
38
|
+
return modernU8.fromBase64(base64);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// 2. Universal atob fallback
|
|
42
|
+
const binary = globalThis.atob(base64);
|
|
43
|
+
const len = binary.length;
|
|
44
|
+
const bytes = new Uint8Array(len);
|
|
45
|
+
for (let i = 0; i < len; i++) {
|
|
46
|
+
bytes[i] = binary.charCodeAt(i);
|
|
47
|
+
}
|
|
48
|
+
return bytes;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Encodes a UTF-8 string to a Uint8Array using standard TextEncoder.
|
|
53
|
+
*/
|
|
54
|
+
export function utf8ToUint8Array(str: string): Uint8Array {
|
|
55
|
+
return new TextEncoder().encode(str);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Decodes a Uint8Array to a UTF-8 string using standard TextDecoder.
|
|
60
|
+
*/
|
|
61
|
+
export function uint8ArrayToUtf8(bytes: Uint8Array): string {
|
|
62
|
+
return new TextDecoder().decode(bytes);
|
|
63
|
+
}
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Standard 32-bit MurmurHash3 (x86_32) implementation.
|
|
3
|
+
* Pure TypeScript, zero external dependencies, zero Node.js Buffer dependencies.
|
|
4
|
+
*
|
|
5
|
+
* Fully compatible with V8 Edge Isolates (Cloudflare Workers, Fastly Compute,
|
|
6
|
+
* Vercel Edge, Deno, Bun, and modern browsers).
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Computes the 32-bit MurmurHash3 of a string with an optional seed.
|
|
11
|
+
* Uses 32-bit unsigned arithmetic (>>> 0).
|
|
12
|
+
*/
|
|
13
|
+
export function murmur3_32(key: string, seed = 0): number {
|
|
14
|
+
const c1 = 0xcc9e2d51;
|
|
15
|
+
const c2 = 0x1b873593;
|
|
16
|
+
|
|
17
|
+
let h1 = seed >>> 0;
|
|
18
|
+
const len = key.length;
|
|
19
|
+
|
|
20
|
+
// Process 2-character (4-byte in UTF-16 code units / 2-char chunks) blocks
|
|
21
|
+
const remainder = len & 1;
|
|
22
|
+
const bytes = len - remainder;
|
|
23
|
+
|
|
24
|
+
for (let i = 0; i < bytes; i += 2) {
|
|
25
|
+
let k1 = (key.charCodeAt(i) & 0xffff) | ((key.charCodeAt(i + 1) & 0xffff) << 16);
|
|
26
|
+
|
|
27
|
+
k1 = Math.imul(k1, c1);
|
|
28
|
+
k1 = (k1 << 15) | (k1 >>> 17);
|
|
29
|
+
k1 = Math.imul(k1, c2);
|
|
30
|
+
|
|
31
|
+
h1 ^= k1;
|
|
32
|
+
h1 = (h1 << 13) | (h1 >>> 19);
|
|
33
|
+
h1 = (Math.imul(h1, 5) + 0xe6546b64) >>> 0;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
if (remainder === 1) {
|
|
37
|
+
let k1 = key.charCodeAt(bytes) & 0xffff;
|
|
38
|
+
k1 = Math.imul(k1, c1);
|
|
39
|
+
k1 = (k1 << 15) | (k1 >>> 17);
|
|
40
|
+
k1 = Math.imul(k1, c2);
|
|
41
|
+
h1 ^= k1;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Finalization avalanche mix (fmix32)
|
|
45
|
+
h1 ^= len;
|
|
46
|
+
h1 ^= h1 >>> 16;
|
|
47
|
+
h1 = Math.imul(h1, 0x85ebca6b);
|
|
48
|
+
h1 ^= h1 >>> 13;
|
|
49
|
+
h1 = Math.imul(h1, 0xc2b2ae35);
|
|
50
|
+
h1 ^= h1 >>> 16;
|
|
51
|
+
|
|
52
|
+
return h1 >>> 0;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface BloomFilterStats {
|
|
56
|
+
bitsSet: number;
|
|
57
|
+
fillFactor: number;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Pure TypeScript Bloom filter backed by a Uint8Array bitset.
|
|
62
|
+
* Uses Murmur3 double-hashing (Kirsch-Mitzenmacher technique):
|
|
63
|
+
* h_i(x) = (h1(x) + i * h2(x)) % m
|
|
64
|
+
*
|
|
65
|
+
* Zero Buffer dependency — runs identically in Node.js, Edge Isolates, and Browsers.
|
|
66
|
+
*/
|
|
67
|
+
export class Murmur3BloomFilter {
|
|
68
|
+
private readonly bits: Uint8Array;
|
|
69
|
+
readonly numBits: number;
|
|
70
|
+
readonly k: number;
|
|
71
|
+
private readonly _maxCapacity: number;
|
|
72
|
+
private _insertionCount = 0;
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* @param numBits Total bits in the filter (default: 100,000 bits = 12.5 KB)
|
|
76
|
+
* @param k Number of hash probes per key (default: 7, targeting ~1% FPR at 2,000 items)
|
|
77
|
+
*/
|
|
78
|
+
constructor(numBits = 100_000, k = 7) {
|
|
79
|
+
this.numBits = Math.max(64, numBits);
|
|
80
|
+
this.k = Math.max(1, k);
|
|
81
|
+
this.bits = new Uint8Array(Math.ceil(this.numBits / 8));
|
|
82
|
+
const p = 0.01;
|
|
83
|
+
this._maxCapacity = Math.floor(-this.numBits * Math.log(1 - Math.pow(p, 1 / this.k)) / this.k);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
private setBit(bitIndex: number): void {
|
|
87
|
+
const byteIndex = bitIndex >>> 3;
|
|
88
|
+
this.bits[byteIndex] |= 1 << (bitIndex & 7);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
private getBit(bitIndex: number): boolean {
|
|
92
|
+
const byteIndex = bitIndex >>> 3;
|
|
93
|
+
return (this.bits[byteIndex] & (1 << (bitIndex & 7))) !== 0;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Adds a key to the Bloom filter.
|
|
98
|
+
*/
|
|
99
|
+
add(key: string): void {
|
|
100
|
+
if (key.length === 0) return;
|
|
101
|
+
const h1 = murmur3_32(key, 0);
|
|
102
|
+
const h2 = murmur3_32(key, 0x9747b28c) || 1; // ensure non-zero step
|
|
103
|
+
const m = this.numBits;
|
|
104
|
+
|
|
105
|
+
for (let i = 0; i < this.k; i++) {
|
|
106
|
+
const bit = ((h1 + Math.imul(i, h2)) >>> 0) % m;
|
|
107
|
+
this.setBit(bit);
|
|
108
|
+
}
|
|
109
|
+
this._insertionCount++;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Tests whether a key might be in the set.
|
|
114
|
+
* Returns `false` for guaranteed misses, `true` for possible hits.
|
|
115
|
+
*/
|
|
116
|
+
mightContain(key: string): boolean {
|
|
117
|
+
if (key.length === 0) return true;
|
|
118
|
+
const h1 = murmur3_32(key, 0);
|
|
119
|
+
const h2 = murmur3_32(key, 0x9747b28c) || 1;
|
|
120
|
+
const m = this.numBits;
|
|
121
|
+
|
|
122
|
+
for (let i = 0; i < this.k; i++) {
|
|
123
|
+
const bit = ((h1 + Math.imul(i, h2)) >>> 0) % m;
|
|
124
|
+
if (!this.getBit(bit)) return false;
|
|
125
|
+
}
|
|
126
|
+
return true;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Clears all set bits in the filter.
|
|
131
|
+
*/
|
|
132
|
+
reset(): void {
|
|
133
|
+
this.bits.fill(0);
|
|
134
|
+
this._insertionCount = 0;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Rebuilds the filter from a collection of keys.
|
|
139
|
+
*/
|
|
140
|
+
rebuild(keys: Iterable<string>): void {
|
|
141
|
+
this.reset();
|
|
142
|
+
for (const key of keys) {
|
|
143
|
+
this.add(key);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Total add() calls since creation or last reset.
|
|
149
|
+
*/
|
|
150
|
+
get insertions(): number {
|
|
151
|
+
return this._insertionCount;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Maximum safe insertions before false positive rate exceeds target ~1%.
|
|
156
|
+
*/
|
|
157
|
+
get maxCapacity(): number {
|
|
158
|
+
return this._maxCapacity;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Returns current bit saturation metrics.
|
|
163
|
+
*/
|
|
164
|
+
get stats(): BloomFilterStats {
|
|
165
|
+
let bitsSet = 0;
|
|
166
|
+
const len = this.bits.length;
|
|
167
|
+
for (let i = 0; i < len; i++) {
|
|
168
|
+
let b = this.bits[i];
|
|
169
|
+
while (b) {
|
|
170
|
+
bitsSet++;
|
|
171
|
+
b &= b - 1;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
return {
|
|
175
|
+
bitsSet,
|
|
176
|
+
fillFactor: bitsSet / this.numBits,
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
}
|
package/src/encryption.ts
CHANGED
|
@@ -33,7 +33,17 @@
|
|
|
33
33
|
* TRIC1XOR | key⊕data[N] ← XOR
|
|
34
34
|
*/
|
|
35
35
|
|
|
36
|
-
import {
|
|
36
|
+
import {
|
|
37
|
+
createCipheriv,
|
|
38
|
+
createDecipheriv,
|
|
39
|
+
createSecretKey,
|
|
40
|
+
randomFillSync,
|
|
41
|
+
constants,
|
|
42
|
+
publicEncrypt,
|
|
43
|
+
privateDecrypt,
|
|
44
|
+
randomBytes,
|
|
45
|
+
type KeyObject,
|
|
46
|
+
} from 'crypto';
|
|
37
47
|
import { type ILogger, consoleLogger } from './types';
|
|
38
48
|
|
|
39
49
|
// ── Public type ───────────────────────────────────────────────────────────────
|
|
@@ -201,20 +211,20 @@ export class CacheEncryption {
|
|
|
201
211
|
throw new Error('XOR key must be at least 1 byte');
|
|
202
212
|
}
|
|
203
213
|
this._key = buf;
|
|
204
|
-
if (
|
|
214
|
+
if (resolvedMode !== 'xor') {
|
|
205
215
|
this._keyObj = createSecretKey(buf);
|
|
206
216
|
// Pre-warm OpenSSL's lazy key-schedule cache: first use of a KeyObject is slower
|
|
207
217
|
// because OpenSSL initialises internal state on demand. Paying that cost now
|
|
208
218
|
// (at construction) guarantees every production encrypt/decrypt call is fast.
|
|
209
219
|
const _wc = createCipheriv(
|
|
210
|
-
|
|
220
|
+
resolvedMode,
|
|
211
221
|
this._keyObj,
|
|
212
|
-
Buffer.alloc(
|
|
222
|
+
Buffer.alloc(resolvedMode === 'aes-128-ctr' ? CTR_IV_BYTES : IV_BYTES),
|
|
213
223
|
);
|
|
214
224
|
_wc.update(Buffer.alloc(0));
|
|
215
225
|
_wc.final();
|
|
216
226
|
}
|
|
217
|
-
if (
|
|
227
|
+
if (resolvedMode === 'xor') {
|
|
218
228
|
logger.warn(
|
|
219
229
|
'Cache obfuscation enabled (XOR). WARNING: XOR is NOT cryptographic — use only for dev or non-sensitive data.',
|
|
220
230
|
);
|
|
@@ -511,3 +521,115 @@ export class CacheEncryption {
|
|
|
511
521
|
return plain;
|
|
512
522
|
}
|
|
513
523
|
}
|
|
524
|
+
|
|
525
|
+
// ── Envelope Encryption (Asymmetric RSA-OAEP / KMS) ───────────────────────────
|
|
526
|
+
|
|
527
|
+
/** "TRICENV1" — Asymmetric Envelope Encrypted blob */
|
|
528
|
+
export const MAGIC_ENVELOPE = Buffer.from([0x54, 0x52, 0x49, 0x43, 0x45, 0x4e, 0x56, 0x31]);
|
|
529
|
+
|
|
530
|
+
export interface EnvelopeEncryptionOptions {
|
|
531
|
+
/** RSA public key (PEM string, KeyObject, or Buffer) for encrypting ephemeral snapshot DEKs via RSA-OAEP (SHA-256) */
|
|
532
|
+
publicKey?: string | KeyObject | Buffer;
|
|
533
|
+
/** RSA private key (PEM string, KeyObject, or Buffer) for decrypting ephemeral snapshot DEKs via RSA-OAEP (SHA-256) */
|
|
534
|
+
privateKey?: string | KeyObject | Buffer;
|
|
535
|
+
/** Optional custom KMS encrypt hook for cloud HSM / KMS integration */
|
|
536
|
+
kmsEncrypt?: (dek: Buffer) => Promise<Buffer> | Buffer;
|
|
537
|
+
/** Optional custom KMS decrypt hook for cloud HSM / KMS integration */
|
|
538
|
+
kmsDecrypt?: (encryptedDek: Buffer) => Promise<Buffer> | Buffer;
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/**
|
|
542
|
+
* EnvelopeEncryption — Asymmetric envelope encryption for remote snapshots and cold backups.
|
|
543
|
+
*
|
|
544
|
+
* Encrypts payload with an ephemeral 256-bit AES-GCM data encryption key (DEK),
|
|
545
|
+
* then wraps the DEK using asymmetric RSA-OAEP (SHA-256) or a custom KMS hook.
|
|
546
|
+
*
|
|
547
|
+
* Storage format:
|
|
548
|
+
* [MAGIC "TRICENV1" (8B)] | [keyLen (4B BE)] | [encryptedDEK (N bytes)] | [iv (12B)] | [tag (16B)] | [ciphertext (M bytes)]
|
|
549
|
+
*/
|
|
550
|
+
export class EnvelopeEncryption {
|
|
551
|
+
static isEnvelope(data: Buffer): boolean {
|
|
552
|
+
return data.length >= MAGIC_LEN && data.subarray(0, MAGIC_LEN).equals(MAGIC_ENVELOPE);
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
static async encrypt(data: Buffer, options: EnvelopeEncryptionOptions): Promise<Buffer> {
|
|
556
|
+
const dek = randomBytes(32);
|
|
557
|
+
let encryptedKey: Buffer;
|
|
558
|
+
|
|
559
|
+
if (options.kmsEncrypt) {
|
|
560
|
+
encryptedKey = await options.kmsEncrypt(dek);
|
|
561
|
+
} else if (options.publicKey) {
|
|
562
|
+
encryptedKey = publicEncrypt(
|
|
563
|
+
{
|
|
564
|
+
key: options.publicKey as any,
|
|
565
|
+
padding: constants.RSA_PKCS1_OAEP_PADDING,
|
|
566
|
+
oaepHash: 'sha256',
|
|
567
|
+
},
|
|
568
|
+
dek,
|
|
569
|
+
);
|
|
570
|
+
} else {
|
|
571
|
+
throw new Error('EnvelopeEncryption: either publicKey or kmsEncrypt must be provided to encrypt');
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
const iv = randomBytes(IV_BYTES);
|
|
575
|
+
const cipher = createCipheriv('aes-256-gcm', dek, iv);
|
|
576
|
+
const ct = cipher.update(data);
|
|
577
|
+
cipher.final();
|
|
578
|
+
const tag = cipher.getAuthTag();
|
|
579
|
+
|
|
580
|
+
const keyLen = encryptedKey.length;
|
|
581
|
+
const out = Buffer.allocUnsafe(MAGIC_LEN + 4 + keyLen + IV_BYTES + TAG_BYTES + ct.length);
|
|
582
|
+
|
|
583
|
+
MAGIC_ENVELOPE.copy(out, 0);
|
|
584
|
+
out.writeUInt32BE(keyLen, MAGIC_LEN);
|
|
585
|
+
encryptedKey.copy(out, MAGIC_LEN + 4);
|
|
586
|
+
iv.copy(out, MAGIC_LEN + 4 + keyLen);
|
|
587
|
+
tag.copy(out, MAGIC_LEN + 4 + keyLen + IV_BYTES);
|
|
588
|
+
ct.copy(out, MAGIC_LEN + 4 + keyLen + IV_BYTES + TAG_BYTES);
|
|
589
|
+
|
|
590
|
+
return out;
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
static async decrypt(data: Buffer, options: EnvelopeEncryptionOptions): Promise<Buffer> {
|
|
594
|
+
if (!this.isEnvelope(data)) {
|
|
595
|
+
throw new Error('EnvelopeEncryption: invalid header, expected TRICENV1');
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
if (data.length < MAGIC_LEN + 4 + IV_BYTES + TAG_BYTES) {
|
|
599
|
+
throw new Error('EnvelopeEncryption: truncated envelope buffer');
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
const keyLen = data.readUInt32BE(MAGIC_LEN);
|
|
603
|
+
const minExpected = MAGIC_LEN + 4 + keyLen + IV_BYTES + TAG_BYTES;
|
|
604
|
+
if (data.length < minExpected) {
|
|
605
|
+
throw new Error('EnvelopeEncryption: truncated envelope buffer (key length mismatch)');
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
const encryptedKey = data.subarray(MAGIC_LEN + 4, MAGIC_LEN + 4 + keyLen);
|
|
609
|
+
const iv = data.subarray(MAGIC_LEN + 4 + keyLen, MAGIC_LEN + 4 + keyLen + IV_BYTES);
|
|
610
|
+
const tag = data.subarray(MAGIC_LEN + 4 + keyLen + IV_BYTES, MAGIC_LEN + 4 + keyLen + IV_BYTES + TAG_BYTES);
|
|
611
|
+
const ct = data.subarray(MAGIC_LEN + 4 + keyLen + IV_BYTES + TAG_BYTES);
|
|
612
|
+
|
|
613
|
+
let dek: Buffer;
|
|
614
|
+
if (options.kmsDecrypt) {
|
|
615
|
+
dek = await options.kmsDecrypt(encryptedKey);
|
|
616
|
+
} else if (options.privateKey) {
|
|
617
|
+
dek = privateDecrypt(
|
|
618
|
+
{
|
|
619
|
+
key: options.privateKey as any,
|
|
620
|
+
padding: constants.RSA_PKCS1_OAEP_PADDING,
|
|
621
|
+
oaepHash: 'sha256',
|
|
622
|
+
},
|
|
623
|
+
encryptedKey,
|
|
624
|
+
);
|
|
625
|
+
} else {
|
|
626
|
+
throw new Error('EnvelopeEncryption: either privateKey or kmsDecrypt must be provided to decrypt');
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
const decipher = createDecipheriv('aes-256-gcm', dek, iv);
|
|
630
|
+
decipher.setAuthTag(tag);
|
|
631
|
+
const pt = decipher.update(ct);
|
|
632
|
+
decipher.final();
|
|
633
|
+
return pt;
|
|
634
|
+
}
|
|
635
|
+
}
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import type { CacheService } from '../cache-service.js';
|
|
2
|
+
import type { WrapOptions } from '../types.js';
|
|
3
|
+
import {
|
|
4
|
+
buildDeterministicKey,
|
|
5
|
+
generateETag,
|
|
6
|
+
shouldSkipCache,
|
|
7
|
+
type KeyDerivationOptions,
|
|
8
|
+
} from './utils.js';
|
|
9
|
+
|
|
10
|
+
export interface ExpressCacheOptions extends Omit<WrapOptions, 'tags'>, KeyDerivationOptions {
|
|
11
|
+
/** TriCache instance. If omitted, lazily resolves the default singleton via CacheService.create(). */
|
|
12
|
+
cache?: CacheService;
|
|
13
|
+
/** Whether to generate and evaluate weak ETags. Default: true. */
|
|
14
|
+
etag?: boolean;
|
|
15
|
+
/** Custom predicate to skip caching dynamically for this request (e.g. authenticated sessions). */
|
|
16
|
+
skipCache?: (req: any) => boolean;
|
|
17
|
+
/** Dynamic tags derivation from request. */
|
|
18
|
+
tags?: string[] | ((req: any) => string[]);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface CachedHttpResponse {
|
|
22
|
+
body: unknown;
|
|
23
|
+
contentType?: string;
|
|
24
|
+
etag?: string;
|
|
25
|
+
status: number;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Creates an Express / Connect middleware that provides deterministic response caching,
|
|
30
|
+
* weak ETag generation, conditional 304 Not Modified short-circuiting, and Cache-Control bypass controls.
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
* import express from 'express';
|
|
34
|
+
* import { CacheService } from 'tricache';
|
|
35
|
+
* import { createExpressMiddleware } from 'tricache/http';
|
|
36
|
+
*
|
|
37
|
+
* const app = express();
|
|
38
|
+
* const cache = CacheService.create();
|
|
39
|
+
*
|
|
40
|
+
* app.get(
|
|
41
|
+
* '/api/products',
|
|
42
|
+
* createExpressMiddleware({
|
|
43
|
+
* cache,
|
|
44
|
+
* ttl: 120,
|
|
45
|
+
* tags: ['products'],
|
|
46
|
+
* headerWhitelist: ['accept-language'],
|
|
47
|
+
* }),
|
|
48
|
+
* async (req, res) => {
|
|
49
|
+
* const data = await getProducts();
|
|
50
|
+
* res.json(data);
|
|
51
|
+
* }
|
|
52
|
+
* );
|
|
53
|
+
*/
|
|
54
|
+
export function createExpressMiddleware(options: ExpressCacheOptions = {}) {
|
|
55
|
+
const {
|
|
56
|
+
cache,
|
|
57
|
+
etag = true,
|
|
58
|
+
ttl = 300,
|
|
59
|
+
swr,
|
|
60
|
+
tags,
|
|
61
|
+
skipCache,
|
|
62
|
+
keyGenerator,
|
|
63
|
+
headerWhitelist,
|
|
64
|
+
} = options;
|
|
65
|
+
|
|
66
|
+
return async (req: any, res: any, next: any) => {
|
|
67
|
+
// Only cache safe, idempotent HTTP read methods
|
|
68
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
69
|
+
return next();
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
if (shouldSkipCache(req, skipCache)) {
|
|
73
|
+
return next();
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
let activeCache = cache;
|
|
77
|
+
if (!activeCache) {
|
|
78
|
+
const { CacheService } = await import('../cache-service.js');
|
|
79
|
+
activeCache = CacheService.create();
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const key = buildDeterministicKey(req, { keyGenerator, headerWhitelist });
|
|
83
|
+
const ifNoneMatch = req.headers ? (req.headers['if-none-match'] || req.headers['If-None-Match']) : undefined;
|
|
84
|
+
|
|
85
|
+
const resolvedTags = typeof tags === 'function' ? tags(req) : tags;
|
|
86
|
+
|
|
87
|
+
try {
|
|
88
|
+
const cached = await activeCache.get<CachedHttpResponse>(
|
|
89
|
+
key,
|
|
90
|
+
async () => {
|
|
91
|
+
return new Promise<CachedHttpResponse>((resolve) => {
|
|
92
|
+
const origJson = res.json?.bind(res);
|
|
93
|
+
const origSend = res.send?.bind(res);
|
|
94
|
+
const origEnd = res.end?.bind(res);
|
|
95
|
+
|
|
96
|
+
const getStatusCode = () => (res.statusCode ?? 200);
|
|
97
|
+
|
|
98
|
+
if (origJson) {
|
|
99
|
+
res.json = (body: any) => {
|
|
100
|
+
const status = getStatusCode();
|
|
101
|
+
const bodyEtag = etag ? generateETag(body) : undefined;
|
|
102
|
+
const contentType = res.getHeader?.('content-type') || 'application/json; charset=utf-8';
|
|
103
|
+
|
|
104
|
+
resolve({ body, contentType, etag: bodyEtag, status });
|
|
105
|
+
|
|
106
|
+
if (ifNoneMatch && bodyEtag && ifNoneMatch === bodyEtag) {
|
|
107
|
+
res.status?.(304);
|
|
108
|
+
origEnd?.();
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
if (bodyEtag && res.setHeader) {
|
|
113
|
+
res.setHeader('ETag', bodyEtag);
|
|
114
|
+
}
|
|
115
|
+
return origJson(body);
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
if (origSend) {
|
|
120
|
+
res.send = (body: any) => {
|
|
121
|
+
const status = getStatusCode();
|
|
122
|
+
const bodyEtag = etag ? generateETag(body) : undefined;
|
|
123
|
+
const contentType = res.getHeader?.('content-type') as string | undefined;
|
|
124
|
+
|
|
125
|
+
resolve({ body, contentType, etag: bodyEtag, status });
|
|
126
|
+
|
|
127
|
+
if (ifNoneMatch && bodyEtag && ifNoneMatch === bodyEtag) {
|
|
128
|
+
res.status?.(304);
|
|
129
|
+
origEnd?.();
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
if (bodyEtag && res.setHeader) {
|
|
134
|
+
res.setHeader('ETag', bodyEtag);
|
|
135
|
+
}
|
|
136
|
+
return origSend(body);
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
if (origEnd) {
|
|
141
|
+
res.end = (body?: unknown) => {
|
|
142
|
+
const status = getStatusCode();
|
|
143
|
+
const bodyEtag = etag && body != null ? generateETag(body) : undefined;
|
|
144
|
+
const contentType = res.getHeader?.('content-type') as string | undefined;
|
|
145
|
+
|
|
146
|
+
resolve({ body, contentType, etag: bodyEtag, status });
|
|
147
|
+
return origEnd(body as never);
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
next();
|
|
152
|
+
});
|
|
153
|
+
},
|
|
154
|
+
ttl,
|
|
155
|
+
{ swr, tags: resolvedTags }
|
|
156
|
+
);
|
|
157
|
+
|
|
158
|
+
// Status gate: only cache 2xx successful responses
|
|
159
|
+
if (typeof cached.status === 'number' && (cached.status < 200 || cached.status >= 300)) {
|
|
160
|
+
await activeCache.delete(key).catch(() => {});
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
if (!res.headersSent) {
|
|
165
|
+
if (cached.etag) {
|
|
166
|
+
if (res.setHeader) res.setHeader('ETag', cached.etag);
|
|
167
|
+
if (ifNoneMatch === cached.etag) {
|
|
168
|
+
return res.status(304).end();
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
if (cached.contentType && res.setHeader) {
|
|
173
|
+
res.setHeader('Content-Type', cached.contentType);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
if (cached.status && res.status) {
|
|
177
|
+
res.status(cached.status);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
if (typeof cached.body === 'object' && cached.body !== null && res.json) {
|
|
181
|
+
return res.json(cached.body);
|
|
182
|
+
} else if (res.send) {
|
|
183
|
+
return res.send(cached.body);
|
|
184
|
+
} else if (res.end) {
|
|
185
|
+
return res.end(cached.body);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
} catch (err) {
|
|
189
|
+
next(err);
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Alias matching legacy nomenclature */
|
|
195
|
+
export const expressCache = createExpressMiddleware;
|