@enclave-vm/stream 0.0.1 → 2.9.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/esm/index.mjs ADDED
@@ -0,0 +1,1052 @@
1
+ // libs/enclavejs-stream/src/index.ts
2
+ export * from "@enclave-vm/types";
3
+
4
+ // libs/enclavejs-stream/src/ndjson.ts
5
+ import {
6
+ parseStreamEventOrEncrypted
7
+ } from "@enclave-vm/types";
8
+ function serializeEvent(event) {
9
+ return JSON.stringify(event);
10
+ }
11
+ function serializeEvents(events) {
12
+ return events.map(serializeEvent).join("\n");
13
+ }
14
+ function parseLine(line) {
15
+ const trimmed = line.trim();
16
+ if (trimmed.length === 0) {
17
+ return { success: false, error: "Empty line", line };
18
+ }
19
+ let parsed;
20
+ try {
21
+ parsed = JSON.parse(trimmed);
22
+ } catch (err) {
23
+ return {
24
+ success: false,
25
+ error: `JSON parse error: ${err instanceof Error ? err.message : String(err)}`,
26
+ line
27
+ };
28
+ }
29
+ const result = parseStreamEventOrEncrypted(parsed);
30
+ if (!result.success) {
31
+ return {
32
+ success: false,
33
+ error: `Validation error: ${result.error.message}`,
34
+ line
35
+ };
36
+ }
37
+ return { success: true, data: result.data };
38
+ }
39
+ function parseLines(data) {
40
+ const lines = data.split("\n");
41
+ const events = [];
42
+ const errors = [];
43
+ for (let i = 0; i < lines.length; i++) {
44
+ const line = lines[i];
45
+ if (!line) continue;
46
+ const trimmed = line.trim();
47
+ if (trimmed.length === 0) continue;
48
+ const result = parseLine(trimmed);
49
+ if (result.success) {
50
+ events.push(result.data);
51
+ } else {
52
+ errors.push({
53
+ line: i + 1,
54
+ error: result.error,
55
+ content: trimmed.length > 100 ? trimmed.slice(0, 100) + "..." : trimmed
56
+ });
57
+ }
58
+ }
59
+ return { events, errors };
60
+ }
61
+ var NdjsonStreamParser = class {
62
+ buffer = "";
63
+ onEvent;
64
+ onError;
65
+ lineNumber = 0;
66
+ constructor(options) {
67
+ this.onEvent = options.onEvent;
68
+ this.onError = options.onError;
69
+ }
70
+ /**
71
+ * Feed a chunk of data into the parser.
72
+ * Complete lines are parsed and emitted immediately.
73
+ */
74
+ feed(chunk) {
75
+ this.buffer += chunk;
76
+ let newlineIndex;
77
+ while ((newlineIndex = this.buffer.indexOf("\n")) !== -1) {
78
+ const line = this.buffer.slice(0, newlineIndex);
79
+ this.buffer = this.buffer.slice(newlineIndex + 1);
80
+ this.lineNumber++;
81
+ const trimmed = line.trim();
82
+ if (trimmed.length === 0) continue;
83
+ const result = parseLine(trimmed);
84
+ if (result.success) {
85
+ this.onEvent(result.data);
86
+ } else {
87
+ this.onError({
88
+ line: this.lineNumber,
89
+ error: result.error,
90
+ content: trimmed.length > 100 ? trimmed.slice(0, 100) + "..." : trimmed
91
+ });
92
+ }
93
+ }
94
+ }
95
+ /**
96
+ * Flush any remaining buffered data.
97
+ * Should be called when the stream ends.
98
+ */
99
+ flush() {
100
+ const trimmed = this.buffer.trim();
101
+ if (trimmed.length > 0) {
102
+ this.lineNumber++;
103
+ const result = parseLine(trimmed);
104
+ if (result.success) {
105
+ this.onEvent(result.data);
106
+ } else {
107
+ this.onError({
108
+ line: this.lineNumber,
109
+ error: result.error,
110
+ content: trimmed.length > 100 ? trimmed.slice(0, 100) + "..." : trimmed
111
+ });
112
+ }
113
+ }
114
+ this.buffer = "";
115
+ }
116
+ /**
117
+ * Reset the parser state.
118
+ */
119
+ reset() {
120
+ this.buffer = "";
121
+ this.lineNumber = 0;
122
+ }
123
+ /**
124
+ * Get the current line number.
125
+ */
126
+ getLineNumber() {
127
+ return this.lineNumber;
128
+ }
129
+ /**
130
+ * Check if there's pending data in the buffer.
131
+ */
132
+ hasPendingData() {
133
+ return this.buffer.trim().length > 0;
134
+ }
135
+ };
136
+ function createNdjsonParseStream() {
137
+ let buffer = "";
138
+ return new TransformStream({
139
+ transform(chunk, controller) {
140
+ buffer += chunk;
141
+ let newlineIndex;
142
+ while ((newlineIndex = buffer.indexOf("\n")) !== -1) {
143
+ const line = buffer.slice(0, newlineIndex);
144
+ buffer = buffer.slice(newlineIndex + 1);
145
+ const trimmed = line.trim();
146
+ if (trimmed.length === 0) continue;
147
+ const result = parseLine(trimmed);
148
+ if (result.success) {
149
+ controller.enqueue(result.data);
150
+ }
151
+ }
152
+ },
153
+ flush(controller) {
154
+ const trimmed = buffer.trim();
155
+ if (trimmed.length > 0) {
156
+ const result = parseLine(trimmed);
157
+ if (result.success) {
158
+ controller.enqueue(result.data);
159
+ }
160
+ }
161
+ }
162
+ });
163
+ }
164
+ function createNdjsonSerializeStream() {
165
+ return new TransformStream({
166
+ transform(event, controller) {
167
+ controller.enqueue(serializeEvent(event) + "\n");
168
+ }
169
+ });
170
+ }
171
+ async function* parseNdjsonStream(stream) {
172
+ const decoder = new TextDecoder();
173
+ const reader = stream.getReader();
174
+ let buffer = "";
175
+ try {
176
+ while (true) {
177
+ const { done, value } = await reader.read();
178
+ if (done) {
179
+ const trimmed = buffer.trim();
180
+ if (trimmed.length > 0) {
181
+ const result = parseLine(trimmed);
182
+ if (result.success) {
183
+ yield result.data;
184
+ }
185
+ }
186
+ break;
187
+ }
188
+ buffer += decoder.decode(value, { stream: true });
189
+ let newlineIndex;
190
+ while ((newlineIndex = buffer.indexOf("\n")) !== -1) {
191
+ const line = buffer.slice(0, newlineIndex);
192
+ buffer = buffer.slice(newlineIndex + 1);
193
+ const trimmed = line.trim();
194
+ if (trimmed.length === 0) continue;
195
+ const result = parseLine(trimmed);
196
+ if (result.success) {
197
+ yield result.data;
198
+ }
199
+ }
200
+ }
201
+ } finally {
202
+ reader.releaseLock();
203
+ }
204
+ }
205
+
206
+ // libs/enclavejs-stream/src/crypto/ecdh.ts
207
+ import {
208
+ SupportedCurve,
209
+ EncryptionErrorCode,
210
+ PROTOCOL_VERSION,
211
+ EncryptionAlgorithm,
212
+ KeyDerivation
213
+ } from "@enclave-vm/types";
214
+ var EcdhError = class extends Error {
215
+ constructor(message, code) {
216
+ super(message);
217
+ this.code = code;
218
+ this.name = "EcdhError";
219
+ }
220
+ };
221
+ function getSubtle() {
222
+ if (typeof globalThis.crypto?.subtle !== "undefined") {
223
+ return globalThis.crypto.subtle;
224
+ }
225
+ throw new EcdhError("Web Crypto API not available", EncryptionErrorCode.HandshakeFailed);
226
+ }
227
+ async function generateKeyPair(curve = SupportedCurve.P256) {
228
+ const subtle = getSubtle();
229
+ try {
230
+ const keyPair = await subtle.generateKey(
231
+ {
232
+ name: "ECDH",
233
+ namedCurve: curve
234
+ },
235
+ true,
236
+ // extractable for export
237
+ ["deriveBits"]
238
+ );
239
+ return {
240
+ publicKey: keyPair.publicKey,
241
+ privateKey: keyPair.privateKey
242
+ };
243
+ } catch (err) {
244
+ throw new EcdhError(
245
+ `Failed to generate key pair: ${err instanceof Error ? err.message : String(err)}`,
246
+ EncryptionErrorCode.HandshakeFailed
247
+ );
248
+ }
249
+ }
250
+ async function exportPublicKey(publicKey) {
251
+ const subtle = getSubtle();
252
+ try {
253
+ const rawKey = await subtle.exportKey("raw", publicKey);
254
+ const publicKeyB64 = btoa(String.fromCharCode(...new Uint8Array(rawKey)));
255
+ const algorithm = publicKey.algorithm;
256
+ const curve = algorithm.namedCurve;
257
+ return { publicKeyB64, curve };
258
+ } catch (err) {
259
+ throw new EcdhError(
260
+ `Failed to export public key: ${err instanceof Error ? err.message : String(err)}`,
261
+ EncryptionErrorCode.InvalidPublicKey
262
+ );
263
+ }
264
+ }
265
+ async function importPublicKey(publicKeyB64, curve = SupportedCurve.P256) {
266
+ const subtle = getSubtle();
267
+ try {
268
+ const rawKey = Uint8Array.from(atob(publicKeyB64), (c) => c.charCodeAt(0));
269
+ return await subtle.importKey(
270
+ "raw",
271
+ rawKey,
272
+ {
273
+ name: "ECDH",
274
+ namedCurve: curve
275
+ },
276
+ true,
277
+ []
278
+ );
279
+ } catch (err) {
280
+ throw new EcdhError(
281
+ `Failed to import public key: ${err instanceof Error ? err.message : String(err)}`,
282
+ EncryptionErrorCode.InvalidPublicKey
283
+ );
284
+ }
285
+ }
286
+ async function deriveSharedSecret(privateKey, peerPublicKey) {
287
+ const subtle = getSubtle();
288
+ try {
289
+ const sharedBits = await subtle.deriveBits(
290
+ {
291
+ name: "ECDH",
292
+ public: peerPublicKey
293
+ },
294
+ privateKey,
295
+ 256
296
+ );
297
+ return new Uint8Array(sharedBits);
298
+ } catch (err) {
299
+ throw new EcdhError(
300
+ `Failed to derive shared secret: ${err instanceof Error ? err.message : String(err)}`,
301
+ EncryptionErrorCode.KeyDerivationFailed
302
+ );
303
+ }
304
+ }
305
+ async function createClientHello(keyPair) {
306
+ const { publicKeyB64, curve } = await exportPublicKey(keyPair.publicKey);
307
+ return {
308
+ protocolVersion: PROTOCOL_VERSION,
309
+ clientEphemeralPubKeyB64: publicKeyB64,
310
+ curve,
311
+ supportedAlgorithms: [EncryptionAlgorithm.AES_GCM_256]
312
+ };
313
+ }
314
+ async function createServerHello(keyPair, keyId) {
315
+ const { publicKeyB64, curve } = await exportPublicKey(keyPair.publicKey);
316
+ return {
317
+ protocolVersion: PROTOCOL_VERSION,
318
+ serverEphemeralPubKeyB64: publicKeyB64,
319
+ curve,
320
+ selectedAlgorithm: EncryptionAlgorithm.AES_GCM_256,
321
+ kdf: KeyDerivation.HKDF_SHA256,
322
+ keyId
323
+ };
324
+ }
325
+ async function processClientHello(clientHello) {
326
+ const serverKeyPair = await generateKeyPair(clientHello.curve);
327
+ const peerPublicKey = await importPublicKey(clientHello.clientEphemeralPubKeyB64, clientHello.curve);
328
+ const keyId = `k_${crypto.randomUUID()}`;
329
+ const serverHello = await createServerHello(serverKeyPair, keyId);
330
+ return {
331
+ serverKeyPair,
332
+ peerPublicKey,
333
+ serverHello,
334
+ keyId
335
+ };
336
+ }
337
+ async function processServerHello(serverHello) {
338
+ const peerPublicKey = await importPublicKey(serverHello.serverEphemeralPubKeyB64, serverHello.curve);
339
+ return {
340
+ peerPublicKey,
341
+ keyId: serverHello.keyId
342
+ };
343
+ }
344
+
345
+ // libs/enclavejs-stream/src/crypto/hkdf.ts
346
+ import { HkdfInfo, AES_256_KEY_SIZE, EncryptionErrorCode as EncryptionErrorCode2 } from "@enclave-vm/types";
347
+ function toArrayBuffer(arr) {
348
+ if (arr.byteOffset === 0 && arr.byteLength === arr.buffer.byteLength) {
349
+ return arr.buffer;
350
+ }
351
+ return arr.buffer.slice(arr.byteOffset, arr.byteOffset + arr.byteLength);
352
+ }
353
+ var HkdfError = class extends Error {
354
+ constructor(message, code) {
355
+ super(message);
356
+ this.code = code;
357
+ this.name = "HkdfError";
358
+ }
359
+ };
360
+ function getSubtle2() {
361
+ if (typeof globalThis.crypto?.subtle !== "undefined") {
362
+ return globalThis.crypto.subtle;
363
+ }
364
+ throw new HkdfError("Web Crypto API not available", EncryptionErrorCode2.KeyDerivationFailed);
365
+ }
366
+ async function deriveKey(sharedSecret, salt, info, keyLength = AES_256_KEY_SIZE) {
367
+ const subtle = getSubtle2();
368
+ try {
369
+ const baseKey = await subtle.importKey("raw", toArrayBuffer(sharedSecret), "HKDF", false, ["deriveBits"]);
370
+ const saltBytes = salt ?? new Uint8Array(32);
371
+ const infoBytes = new TextEncoder().encode(info);
372
+ const derivedBits = await subtle.deriveBits(
373
+ {
374
+ name: "HKDF",
375
+ hash: "SHA-256",
376
+ salt: toArrayBuffer(saltBytes),
377
+ info: toArrayBuffer(infoBytes)
378
+ },
379
+ baseKey,
380
+ keyLength * 8
381
+ // bits
382
+ );
383
+ return new Uint8Array(derivedBits);
384
+ } catch (err) {
385
+ throw new HkdfError(
386
+ `Failed to derive key: ${err instanceof Error ? err.message : String(err)}`,
387
+ EncryptionErrorCode2.KeyDerivationFailed
388
+ );
389
+ }
390
+ }
391
+ async function deriveSessionKeys(sharedSecret, sessionId) {
392
+ const salt = new TextEncoder().encode(sessionId);
393
+ const [clientToServerKey, serverToClientKey] = await Promise.all([
394
+ deriveKey(sharedSecret, salt, HkdfInfo.ClientToServer),
395
+ deriveKey(sharedSecret, salt, HkdfInfo.ServerToClient)
396
+ ]);
397
+ return {
398
+ clientToServerKey,
399
+ serverToClientKey
400
+ };
401
+ }
402
+ async function importAesGcmKey(keyBytes) {
403
+ const subtle = getSubtle2();
404
+ try {
405
+ return await subtle.importKey(
406
+ "raw",
407
+ toArrayBuffer(keyBytes),
408
+ {
409
+ name: "AES-GCM",
410
+ length: keyBytes.length * 8
411
+ },
412
+ false,
413
+ // not extractable
414
+ ["encrypt", "decrypt"]
415
+ );
416
+ } catch (err) {
417
+ throw new HkdfError(
418
+ `Failed to import AES key: ${err instanceof Error ? err.message : String(err)}`,
419
+ EncryptionErrorCode2.KeyDerivationFailed
420
+ );
421
+ }
422
+ }
423
+ async function deriveSessionCryptoKeys(sharedSecret, sessionId) {
424
+ const { clientToServerKey, serverToClientKey } = await deriveSessionKeys(sharedSecret, sessionId);
425
+ const [c2sKey, s2cKey] = await Promise.all([importAesGcmKey(clientToServerKey), importAesGcmKey(serverToClientKey)]);
426
+ return {
427
+ clientToServerKey: c2sKey,
428
+ serverToClientKey: s2cKey
429
+ };
430
+ }
431
+
432
+ // libs/enclavejs-stream/src/crypto/aes-gcm.ts
433
+ import {
434
+ AES_GCM_NONCE_SIZE,
435
+ AES_GCM_TAG_SIZE,
436
+ MAX_MESSAGES_PER_KEY,
437
+ EncryptionErrorCode as EncryptionErrorCode3,
438
+ PROTOCOL_VERSION as PROTOCOL_VERSION2,
439
+ EventType,
440
+ EncryptionAlgorithm as EncryptionAlgorithm2
441
+ } from "@enclave-vm/types";
442
+ function toArrayBuffer2(arr) {
443
+ if (arr.byteOffset === 0 && arr.byteLength === arr.buffer.byteLength) {
444
+ return arr.buffer;
445
+ }
446
+ return arr.buffer.slice(arr.byteOffset, arr.byteOffset + arr.byteLength);
447
+ }
448
+ var AesGcmError = class extends Error {
449
+ constructor(message, code) {
450
+ super(message);
451
+ this.code = code;
452
+ this.name = "AesGcmError";
453
+ }
454
+ };
455
+ function getSubtle3() {
456
+ if (typeof globalThis.crypto?.subtle !== "undefined") {
457
+ return globalThis.crypto.subtle;
458
+ }
459
+ throw new AesGcmError("Web Crypto API not available", EncryptionErrorCode3.DecryptionFailed);
460
+ }
461
+ function generateNonce() {
462
+ const nonce = new Uint8Array(AES_GCM_NONCE_SIZE);
463
+ crypto.getRandomValues(nonce);
464
+ return nonce;
465
+ }
466
+ function generateCounterNonce(prefix, counter) {
467
+ if (prefix.length !== 8) {
468
+ throw new AesGcmError("Nonce prefix must be 8 bytes", EncryptionErrorCode3.NonceReuse);
469
+ }
470
+ const nonce = new Uint8Array(AES_GCM_NONCE_SIZE);
471
+ nonce.set(prefix);
472
+ const counterValue = Number(counter & 0xffffffffn);
473
+ nonce[8] = counterValue >> 24 & 255;
474
+ nonce[9] = counterValue >> 16 & 255;
475
+ nonce[10] = counterValue >> 8 & 255;
476
+ nonce[11] = counterValue & 255;
477
+ return nonce;
478
+ }
479
+ function toBase64(bytes) {
480
+ return btoa(String.fromCharCode(...bytes));
481
+ }
482
+ function fromBase64(base64) {
483
+ return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
484
+ }
485
+ async function encrypt(key, plaintext, nonce, additionalData) {
486
+ const subtle = getSubtle3();
487
+ if (nonce.length !== AES_GCM_NONCE_SIZE) {
488
+ throw new AesGcmError(
489
+ `Invalid nonce length: expected ${AES_GCM_NONCE_SIZE}, got ${nonce.length}`,
490
+ EncryptionErrorCode3.DecryptionFailed
491
+ );
492
+ }
493
+ try {
494
+ const ciphertext = await subtle.encrypt(
495
+ {
496
+ name: "AES-GCM",
497
+ iv: toArrayBuffer2(nonce),
498
+ tagLength: AES_GCM_TAG_SIZE * 8,
499
+ // bits
500
+ additionalData: additionalData ? toArrayBuffer2(additionalData) : void 0
501
+ },
502
+ key,
503
+ toArrayBuffer2(plaintext)
504
+ );
505
+ return new Uint8Array(ciphertext);
506
+ } catch (err) {
507
+ throw new AesGcmError(
508
+ `Encryption failed: ${err instanceof Error ? err.message : String(err)}`,
509
+ EncryptionErrorCode3.DecryptionFailed
510
+ );
511
+ }
512
+ }
513
+ async function decrypt(key, ciphertext, nonce, additionalData) {
514
+ const subtle = getSubtle3();
515
+ if (nonce.length !== AES_GCM_NONCE_SIZE) {
516
+ throw new AesGcmError(
517
+ `Invalid nonce length: expected ${AES_GCM_NONCE_SIZE}, got ${nonce.length}`,
518
+ EncryptionErrorCode3.DecryptionFailed
519
+ );
520
+ }
521
+ try {
522
+ const plaintext = await subtle.decrypt(
523
+ {
524
+ name: "AES-GCM",
525
+ iv: toArrayBuffer2(nonce),
526
+ tagLength: AES_GCM_TAG_SIZE * 8,
527
+ // bits
528
+ additionalData: additionalData ? toArrayBuffer2(additionalData) : void 0
529
+ },
530
+ key,
531
+ toArrayBuffer2(ciphertext)
532
+ );
533
+ return new Uint8Array(plaintext);
534
+ } catch (err) {
535
+ throw new AesGcmError(
536
+ `Decryption failed: ${err instanceof Error ? err.message : String(err)}`,
537
+ EncryptionErrorCode3.DecryptionFailed
538
+ );
539
+ }
540
+ }
541
+ async function encryptJson(key, keyId, data, nonce) {
542
+ const actualNonce = nonce ?? generateNonce();
543
+ const plaintext = new TextEncoder().encode(JSON.stringify(data));
544
+ const ciphertext = await encrypt(key, plaintext, actualNonce);
545
+ return {
546
+ kid: keyId,
547
+ nonceB64: toBase64(actualNonce),
548
+ ciphertextB64: toBase64(ciphertext)
549
+ };
550
+ }
551
+ async function decryptJson(key, payload) {
552
+ const nonce = fromBase64(payload.nonceB64);
553
+ const ciphertext = fromBase64(payload.ciphertextB64);
554
+ const plaintext = await decrypt(key, ciphertext, nonce);
555
+ const json = new TextDecoder().decode(plaintext);
556
+ return JSON.parse(json);
557
+ }
558
+ async function createEncryptedEnvelope(key, keyId, sessionId, seq, innerEvent, nonce) {
559
+ const payload = await encryptJson(key, keyId, innerEvent, nonce);
560
+ return {
561
+ protocolVersion: PROTOCOL_VERSION2,
562
+ sessionId,
563
+ seq,
564
+ type: EventType.Encrypted,
565
+ payload
566
+ };
567
+ }
568
+ var SessionEncryptionContext = class _SessionEncryptionContext {
569
+ key;
570
+ keyInfo;
571
+ nonceCounter;
572
+ noncePrefix;
573
+ constructor(key, keyInfo) {
574
+ this.key = key;
575
+ this.keyInfo = keyInfo;
576
+ this.nonceCounter = keyInfo.nonceCounter;
577
+ this.noncePrefix = crypto.getRandomValues(new Uint8Array(8));
578
+ }
579
+ /**
580
+ * Get the key ID.
581
+ */
582
+ get keyId() {
583
+ return this.keyInfo.keyId;
584
+ }
585
+ /**
586
+ * Check if the key needs rotation.
587
+ */
588
+ needsRotation() {
589
+ return this.nonceCounter >= this.keyInfo.maxNonces;
590
+ }
591
+ /**
592
+ * Encrypt data and increment the nonce counter.
593
+ */
594
+ async encrypt(plaintext) {
595
+ if (this.needsRotation()) {
596
+ throw new AesGcmError("Key needs rotation: nonce limit reached", EncryptionErrorCode3.KeyExpired);
597
+ }
598
+ const nonce = generateCounterNonce(this.noncePrefix, this.nonceCounter);
599
+ this.nonceCounter++;
600
+ const ciphertext = await encrypt(this.key, plaintext, nonce);
601
+ return { ciphertext, nonce };
602
+ }
603
+ /**
604
+ * Encrypt JSON data.
605
+ */
606
+ async encryptJson(data) {
607
+ const plaintext = new TextEncoder().encode(JSON.stringify(data));
608
+ const { ciphertext, nonce } = await this.encrypt(plaintext);
609
+ return {
610
+ kid: this.keyId,
611
+ nonceB64: toBase64(nonce),
612
+ ciphertextB64: toBase64(ciphertext)
613
+ };
614
+ }
615
+ /**
616
+ * Create an encrypted envelope.
617
+ */
618
+ async createEnvelope(sessionId, seq, innerEvent) {
619
+ const payload = await this.encryptJson(innerEvent);
620
+ return {
621
+ protocolVersion: PROTOCOL_VERSION2,
622
+ sessionId,
623
+ seq,
624
+ type: EventType.Encrypted,
625
+ payload
626
+ };
627
+ }
628
+ /**
629
+ * Decrypt an encrypted envelope payload.
630
+ */
631
+ async decrypt(payload) {
632
+ const nonce = fromBase64(payload.nonceB64);
633
+ const ciphertext = fromBase64(payload.ciphertextB64);
634
+ return decrypt(this.key, ciphertext, nonce);
635
+ }
636
+ /**
637
+ * Decrypt and parse JSON from an encrypted envelope payload.
638
+ */
639
+ async decryptJson(payload) {
640
+ const plaintext = await this.decrypt(payload);
641
+ const json = new TextDecoder().decode(plaintext);
642
+ return JSON.parse(json);
643
+ }
644
+ /**
645
+ * Get the current nonce counter value.
646
+ */
647
+ getNonceCounter() {
648
+ return this.nonceCounter;
649
+ }
650
+ /**
651
+ * Create session key info for serialization.
652
+ */
653
+ toKeyInfo() {
654
+ return {
655
+ ...this.keyInfo,
656
+ nonceCounter: this.nonceCounter
657
+ };
658
+ }
659
+ /**
660
+ * Create a new encryption context from raw key bytes.
661
+ */
662
+ static async fromKeyBytes(keyBytes, keyId) {
663
+ const subtle = getSubtle3();
664
+ const key = await subtle.importKey(
665
+ "raw",
666
+ toArrayBuffer2(keyBytes),
667
+ {
668
+ name: "AES-GCM",
669
+ length: keyBytes.length * 8
670
+ },
671
+ false,
672
+ ["encrypt", "decrypt"]
673
+ );
674
+ const keyInfo = {
675
+ keyId,
676
+ algorithm: EncryptionAlgorithm2.AES_GCM_256,
677
+ keyBytes,
678
+ nonceCounter: 0n,
679
+ maxNonces: MAX_MESSAGES_PER_KEY,
680
+ createdAt: Date.now()
681
+ };
682
+ return new _SessionEncryptionContext(key, keyInfo);
683
+ }
684
+ };
685
+
686
+ // libs/enclavejs-stream/src/reconnect.ts
687
+ var ConnectionState = {
688
+ /** Not connected */
689
+ Disconnected: "disconnected",
690
+ /** Attempting to connect */
691
+ Connecting: "connecting",
692
+ /** Successfully connected */
693
+ Connected: "connected",
694
+ /** Connection lost, will attempt reconnection */
695
+ Reconnecting: "reconnecting",
696
+ /** Permanently failed (max retries exceeded or fatal error) */
697
+ Failed: "failed",
698
+ /** Intentionally closed */
699
+ Closed: "closed"
700
+ };
701
+ var DEFAULT_RECONNECTION_CONFIG = {
702
+ maxRetries: 5,
703
+ initialDelayMs: 1e3,
704
+ maxDelayMs: 3e4,
705
+ backoffMultiplier: 2,
706
+ jitter: true,
707
+ jitterFactor: 0.3
708
+ };
709
+ var ReconnectionStateMachine = class {
710
+ state = ConnectionState.Disconnected;
711
+ retryCount = 0;
712
+ retryTimeoutId = null;
713
+ config;
714
+ onEvent;
715
+ constructor(options) {
716
+ this.config = { ...DEFAULT_RECONNECTION_CONFIG, ...options.config };
717
+ this.onEvent = options.onEvent;
718
+ }
719
+ /**
720
+ * Get current connection state.
721
+ */
722
+ getState() {
723
+ return this.state;
724
+ }
725
+ /**
726
+ * Get current retry count.
727
+ */
728
+ getRetryCount() {
729
+ return this.retryCount;
730
+ }
731
+ /**
732
+ * Transition to a new state.
733
+ */
734
+ transition(newState) {
735
+ const previousState = this.state;
736
+ if (previousState === newState) return;
737
+ this.state = newState;
738
+ this.onEvent({ type: "state_change", state: newState, previousState });
739
+ }
740
+ /**
741
+ * Calculate backoff delay with optional jitter.
742
+ */
743
+ calculateBackoff() {
744
+ const { initialDelayMs, maxDelayMs, backoffMultiplier, jitter, jitterFactor } = this.config;
745
+ let delay = initialDelayMs * Math.pow(backoffMultiplier, this.retryCount);
746
+ delay = Math.min(delay, maxDelayMs);
747
+ if (jitter) {
748
+ const jitterAmount = delay * jitterFactor;
749
+ delay = delay - jitterAmount + Math.random() * jitterAmount * 2;
750
+ }
751
+ return Math.round(delay);
752
+ }
753
+ /**
754
+ * Start connecting.
755
+ */
756
+ connect() {
757
+ if (this.state === ConnectionState.Connected || this.state === ConnectionState.Connecting) {
758
+ return;
759
+ }
760
+ this.cancelRetry();
761
+ this.retryCount = 0;
762
+ this.transition(ConnectionState.Connecting);
763
+ }
764
+ /**
765
+ * Called when connection succeeds.
766
+ */
767
+ onConnected() {
768
+ this.cancelRetry();
769
+ this.retryCount = 0;
770
+ this.transition(ConnectionState.Connected);
771
+ this.onEvent({ type: "connected" });
772
+ }
773
+ /**
774
+ * Called when connection is lost.
775
+ */
776
+ onDisconnected(reason) {
777
+ this.cancelRetry();
778
+ if (this.state === ConnectionState.Closed || this.state === ConnectionState.Failed) {
779
+ return;
780
+ }
781
+ this.onEvent({ type: "disconnected", reason });
782
+ if (this.retryCount < this.config.maxRetries) {
783
+ this.scheduleRetry();
784
+ } else {
785
+ this.transition(ConnectionState.Failed);
786
+ this.onEvent({ type: "failed", reason: reason ?? "Max retries exceeded" });
787
+ }
788
+ }
789
+ /**
790
+ * Called when connection fails with a fatal error.
791
+ */
792
+ onFatalError(reason) {
793
+ this.cancelRetry();
794
+ this.transition(ConnectionState.Failed);
795
+ this.onEvent({ type: "failed", reason });
796
+ }
797
+ /**
798
+ * Schedule a reconnection attempt.
799
+ */
800
+ scheduleRetry() {
801
+ this.transition(ConnectionState.Reconnecting);
802
+ const delayMs = this.calculateBackoff();
803
+ const attempt = this.retryCount + 1;
804
+ this.onEvent({ type: "retry_scheduled", attempt, delayMs });
805
+ this.retryTimeoutId = setTimeout(() => {
806
+ this.retryTimeoutId = null;
807
+ this.retryCount++;
808
+ this.onEvent({ type: "retry_started", attempt });
809
+ this.transition(ConnectionState.Connecting);
810
+ }, delayMs);
811
+ }
812
+ /**
813
+ * Cancel any pending retry.
814
+ */
815
+ cancelRetry() {
816
+ if (this.retryTimeoutId !== null) {
817
+ clearTimeout(this.retryTimeoutId);
818
+ this.retryTimeoutId = null;
819
+ }
820
+ }
821
+ /**
822
+ * Intentionally close the connection.
823
+ */
824
+ close() {
825
+ this.cancelRetry();
826
+ this.transition(ConnectionState.Closed);
827
+ }
828
+ /**
829
+ * Reset to initial state.
830
+ */
831
+ reset() {
832
+ this.cancelRetry();
833
+ this.retryCount = 0;
834
+ this.transition(ConnectionState.Disconnected);
835
+ }
836
+ /**
837
+ * Check if reconnection is possible.
838
+ */
839
+ canReconnect() {
840
+ return this.state !== ConnectionState.Failed && this.state !== ConnectionState.Closed && this.retryCount < this.config.maxRetries;
841
+ }
842
+ };
843
+ var SequenceTracker = class {
844
+ lastSeq = 0;
845
+ gaps = [];
846
+ maxGaps;
847
+ constructor(maxGaps = 100) {
848
+ this.maxGaps = maxGaps;
849
+ }
850
+ /**
851
+ * Process a received sequence number.
852
+ * Returns any gaps detected.
853
+ */
854
+ receive(seq) {
855
+ if (this.lastSeq === 0) {
856
+ this.lastSeq = seq;
857
+ return { gap: false };
858
+ }
859
+ if (seq === this.lastSeq + 1) {
860
+ this.lastSeq = seq;
861
+ return { gap: false };
862
+ }
863
+ if (seq <= this.lastSeq) {
864
+ return { gap: false };
865
+ }
866
+ const missingStart = this.lastSeq + 1;
867
+ const missingEnd = seq - 1;
868
+ if (this.gaps.length < this.maxGaps) {
869
+ this.gaps.push({ start: missingStart, end: missingEnd });
870
+ }
871
+ this.lastSeq = seq;
872
+ return { gap: true, missingStart, missingEnd };
873
+ }
874
+ /**
875
+ * Get the last received sequence number.
876
+ */
877
+ getLastSeq() {
878
+ return this.lastSeq;
879
+ }
880
+ /**
881
+ * Get all detected gaps.
882
+ */
883
+ getGaps() {
884
+ return [...this.gaps];
885
+ }
886
+ /**
887
+ * Clear a gap after it's been filled.
888
+ */
889
+ clearGap(start, end) {
890
+ const index = this.gaps.findIndex((g) => g.start === start && g.end === end);
891
+ if (index !== -1) {
892
+ this.gaps.splice(index, 1);
893
+ }
894
+ }
895
+ /**
896
+ * Check if there are pending gaps.
897
+ */
898
+ hasGaps() {
899
+ return this.gaps.length > 0;
900
+ }
901
+ /**
902
+ * Reset the tracker.
903
+ */
904
+ reset() {
905
+ this.lastSeq = 0;
906
+ this.gaps.length = 0;
907
+ }
908
+ };
909
+ var EventBuffer = class {
910
+ buffer = [];
911
+ maxSize;
912
+ constructor(maxSize = 1e3) {
913
+ this.maxSize = maxSize;
914
+ }
915
+ /**
916
+ * Add an event to the buffer.
917
+ */
918
+ add(event) {
919
+ if (this.buffer.length >= this.maxSize) {
920
+ return false;
921
+ }
922
+ this.buffer.push(event);
923
+ return true;
924
+ }
925
+ /**
926
+ * Get all buffered events.
927
+ */
928
+ getAll() {
929
+ return [...this.buffer];
930
+ }
931
+ /**
932
+ * Drain the buffer (get all events and clear).
933
+ */
934
+ drain() {
935
+ const events = [...this.buffer];
936
+ this.buffer.length = 0;
937
+ return events;
938
+ }
939
+ /**
940
+ * Get buffer size.
941
+ */
942
+ size() {
943
+ return this.buffer.length;
944
+ }
945
+ /**
946
+ * Check if buffer is full.
947
+ */
948
+ isFull() {
949
+ return this.buffer.length >= this.maxSize;
950
+ }
951
+ /**
952
+ * Clear the buffer.
953
+ */
954
+ clear() {
955
+ this.buffer.length = 0;
956
+ }
957
+ };
958
+ var HeartbeatMonitor = class {
959
+ lastHeartbeat = Date.now();
960
+ timeoutId = null;
961
+ timeoutMs;
962
+ onTimeout;
963
+ constructor(options) {
964
+ this.timeoutMs = options.timeoutMs;
965
+ this.onTimeout = options.onTimeout;
966
+ }
967
+ /**
968
+ * Start monitoring.
969
+ */
970
+ start() {
971
+ this.lastHeartbeat = Date.now();
972
+ this.scheduleCheck();
973
+ }
974
+ /**
975
+ * Stop monitoring.
976
+ */
977
+ stop() {
978
+ if (this.timeoutId !== null) {
979
+ clearTimeout(this.timeoutId);
980
+ this.timeoutId = null;
981
+ }
982
+ }
983
+ /**
984
+ * Reset the heartbeat timer.
985
+ */
986
+ reset() {
987
+ this.lastHeartbeat = Date.now();
988
+ }
989
+ /**
990
+ * Called when a heartbeat is received.
991
+ */
992
+ onHeartbeat() {
993
+ this.lastHeartbeat = Date.now();
994
+ }
995
+ /**
996
+ * Get time since last heartbeat in milliseconds.
997
+ */
998
+ getTimeSinceLastHeartbeat() {
999
+ return Date.now() - this.lastHeartbeat;
1000
+ }
1001
+ scheduleCheck() {
1002
+ this.timeoutId = setTimeout(() => {
1003
+ const elapsed = Date.now() - this.lastHeartbeat;
1004
+ if (elapsed >= this.timeoutMs) {
1005
+ this.onTimeout();
1006
+ } else {
1007
+ this.scheduleCheck();
1008
+ }
1009
+ }, this.timeoutMs);
1010
+ }
1011
+ };
1012
+ export {
1013
+ AesGcmError,
1014
+ ConnectionState,
1015
+ DEFAULT_RECONNECTION_CONFIG,
1016
+ EcdhError,
1017
+ EventBuffer,
1018
+ HeartbeatMonitor,
1019
+ HkdfError,
1020
+ NdjsonStreamParser,
1021
+ ReconnectionStateMachine,
1022
+ SequenceTracker,
1023
+ SessionEncryptionContext,
1024
+ createClientHello,
1025
+ createEncryptedEnvelope,
1026
+ createNdjsonParseStream,
1027
+ createNdjsonSerializeStream,
1028
+ createServerHello,
1029
+ decrypt,
1030
+ decryptJson,
1031
+ deriveKey,
1032
+ deriveSessionCryptoKeys,
1033
+ deriveSessionKeys,
1034
+ deriveSharedSecret,
1035
+ encrypt,
1036
+ encryptJson,
1037
+ exportPublicKey,
1038
+ fromBase64,
1039
+ generateCounterNonce,
1040
+ generateKeyPair,
1041
+ generateNonce,
1042
+ importAesGcmKey,
1043
+ importPublicKey,
1044
+ parseLine,
1045
+ parseLines,
1046
+ parseNdjsonStream,
1047
+ processClientHello,
1048
+ processServerHello,
1049
+ serializeEvent,
1050
+ serializeEvents,
1051
+ toBase64
1052
+ };