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