@enclave-vm/stream 2.19.0 → 2.19.2
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 +137 -98
- package/crypto/aes-gcm.d.ts +84 -8
- package/crypto/ecdh.d.ts +11 -0
- package/crypto/index.d.ts +6 -2
- package/esm/index.mjs +271 -80
- package/index.d.ts +9 -6
- package/index.js +274 -80
- package/ndjson.d.ts +34 -4
- package/package.json +3 -3
package/esm/index.mjs
CHANGED
|
@@ -5,6 +5,81 @@ export * from "@enclave-vm/types";
|
|
|
5
5
|
import {
|
|
6
6
|
parseStreamEventOrEncrypted
|
|
7
7
|
} from "@enclave-vm/types";
|
|
8
|
+
var DEFAULT_MAX_LINE_LENGTH = 8 * 1024 * 1024;
|
|
9
|
+
var NdjsonLineTooLongError = class extends Error {
|
|
10
|
+
maxLineLength;
|
|
11
|
+
constructor(maxLineLength) {
|
|
12
|
+
super(`NDJSON line exceeds the maximum line length of ${maxLineLength} characters`);
|
|
13
|
+
this.name = "NdjsonLineTooLongError";
|
|
14
|
+
this.maxLineLength = maxLineLength;
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
function resolveMaxLineLength(value) {
|
|
18
|
+
if (value === void 0) return DEFAULT_MAX_LINE_LENGTH;
|
|
19
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1) {
|
|
20
|
+
throw new RangeError("maxLineLength must be a positive integer");
|
|
21
|
+
}
|
|
22
|
+
return value;
|
|
23
|
+
}
|
|
24
|
+
var LineAssembler = class {
|
|
25
|
+
constructor(maxLineLength) {
|
|
26
|
+
this.maxLineLength = maxLineLength;
|
|
27
|
+
}
|
|
28
|
+
pieces = [];
|
|
29
|
+
length = 0;
|
|
30
|
+
skipping = false;
|
|
31
|
+
/**
|
|
32
|
+
* Add a chunk.
|
|
33
|
+
*
|
|
34
|
+
* @param onLine - Called with every line the chunk completes (without its line end)
|
|
35
|
+
* @param onTooLong - Called when a line passes the limit, with the start of that line.
|
|
36
|
+
* It may throw; the assembler is then already past the line.
|
|
37
|
+
* @param onSkipped - Called when the end of a dropped line is reached
|
|
38
|
+
*/
|
|
39
|
+
push(chunk, onLine, onTooLong, onSkipped) {
|
|
40
|
+
let start = 0;
|
|
41
|
+
for (; ; ) {
|
|
42
|
+
const newline = chunk.indexOf("\n", start);
|
|
43
|
+
const end = newline === -1 ? chunk.length : newline;
|
|
44
|
+
if (!this.skipping) {
|
|
45
|
+
if (this.length + (end - start) > this.maxLineLength) {
|
|
46
|
+
const head = (this.pieces.length > 0 ? this.pieces[0] : chunk.slice(start, start + 100)).slice(0, 100);
|
|
47
|
+
this.pieces = [];
|
|
48
|
+
this.length = 0;
|
|
49
|
+
this.skipping = true;
|
|
50
|
+
onTooLong(head);
|
|
51
|
+
} else if (end > start) {
|
|
52
|
+
this.pieces.push(chunk.slice(start, end));
|
|
53
|
+
this.length += end - start;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
if (newline === -1) return;
|
|
57
|
+
if (this.skipping) {
|
|
58
|
+
this.skipping = false;
|
|
59
|
+
onSkipped?.();
|
|
60
|
+
} else {
|
|
61
|
+
onLine(this.take());
|
|
62
|
+
}
|
|
63
|
+
start = newline + 1;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Remove and return the unfinished line ('' when there is none, or when it is being dropped).
|
|
68
|
+
*/
|
|
69
|
+
take() {
|
|
70
|
+
const line = this.pieces.length === 1 ? this.pieces[0] : this.pieces.join("");
|
|
71
|
+
this.pieces = [];
|
|
72
|
+
this.length = 0;
|
|
73
|
+
this.skipping = false;
|
|
74
|
+
return line;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Whether an unfinished line with something other than whitespace is held.
|
|
78
|
+
*/
|
|
79
|
+
hasContent() {
|
|
80
|
+
return this.pieces.some((piece) => piece.trim().length > 0);
|
|
81
|
+
}
|
|
82
|
+
};
|
|
8
83
|
function serializeEvent(event) {
|
|
9
84
|
return JSON.stringify(event);
|
|
10
85
|
}
|
|
@@ -59,65 +134,57 @@ function parseLines(data) {
|
|
|
59
134
|
return { events, errors };
|
|
60
135
|
}
|
|
61
136
|
var NdjsonStreamParser = class {
|
|
62
|
-
|
|
137
|
+
lines;
|
|
138
|
+
maxLineLength;
|
|
63
139
|
onEvent;
|
|
64
140
|
onError;
|
|
65
141
|
lineNumber = 0;
|
|
66
142
|
constructor(options) {
|
|
67
143
|
this.onEvent = options.onEvent;
|
|
68
144
|
this.onError = options.onError;
|
|
145
|
+
this.maxLineLength = resolveMaxLineLength(options.maxLineLength);
|
|
146
|
+
this.lines = new LineAssembler(this.maxLineLength);
|
|
69
147
|
}
|
|
70
148
|
/**
|
|
71
149
|
* Feed a chunk of data into the parser.
|
|
72
150
|
* Complete lines are parsed and emitted immediately.
|
|
151
|
+
* A line longer than `maxLineLength` is reported through `onError` once and skipped.
|
|
73
152
|
*/
|
|
74
153
|
feed(chunk) {
|
|
75
|
-
this.
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
if (trimmed.length === 0) continue;
|
|
83
|
-
const result = parseLine(trimmed);
|
|
84
|
-
if (result.success) {
|
|
85
|
-
this.onEvent(result.data);
|
|
86
|
-
} else {
|
|
154
|
+
this.lines.push(
|
|
155
|
+
chunk,
|
|
156
|
+
(line) => {
|
|
157
|
+
this.lineNumber++;
|
|
158
|
+
this.parse(line);
|
|
159
|
+
},
|
|
160
|
+
(head) => {
|
|
87
161
|
this.onError({
|
|
88
|
-
line: this.lineNumber,
|
|
89
|
-
error:
|
|
90
|
-
content:
|
|
162
|
+
line: this.lineNumber + 1,
|
|
163
|
+
error: `Line exceeds the maximum line length of ${this.maxLineLength} characters`,
|
|
164
|
+
content: head + "..."
|
|
91
165
|
});
|
|
166
|
+
},
|
|
167
|
+
() => {
|
|
168
|
+
this.lineNumber++;
|
|
92
169
|
}
|
|
93
|
-
|
|
170
|
+
);
|
|
94
171
|
}
|
|
95
172
|
/**
|
|
96
173
|
* Flush any remaining buffered data.
|
|
97
174
|
* Should be called when the stream ends.
|
|
98
175
|
*/
|
|
99
176
|
flush() {
|
|
100
|
-
const trimmed = this.
|
|
177
|
+
const trimmed = this.lines.take().trim();
|
|
101
178
|
if (trimmed.length > 0) {
|
|
102
179
|
this.lineNumber++;
|
|
103
|
-
|
|
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
|
-
}
|
|
180
|
+
this.parse(trimmed);
|
|
113
181
|
}
|
|
114
|
-
this.buffer = "";
|
|
115
182
|
}
|
|
116
183
|
/**
|
|
117
184
|
* Reset the parser state.
|
|
118
185
|
*/
|
|
119
186
|
reset() {
|
|
120
|
-
this.
|
|
187
|
+
this.lines.take();
|
|
121
188
|
this.lineNumber = 0;
|
|
122
189
|
}
|
|
123
190
|
/**
|
|
@@ -130,34 +197,46 @@ var NdjsonStreamParser = class {
|
|
|
130
197
|
* Check if there's pending data in the buffer.
|
|
131
198
|
*/
|
|
132
199
|
hasPendingData() {
|
|
133
|
-
return this.
|
|
200
|
+
return this.lines.hasContent();
|
|
201
|
+
}
|
|
202
|
+
parse(line) {
|
|
203
|
+
const trimmed = line.trim();
|
|
204
|
+
if (trimmed.length === 0) return;
|
|
205
|
+
const result = parseLine(trimmed);
|
|
206
|
+
if (result.success) {
|
|
207
|
+
this.onEvent(result.data);
|
|
208
|
+
} else {
|
|
209
|
+
this.onError({
|
|
210
|
+
line: this.lineNumber,
|
|
211
|
+
error: result.error,
|
|
212
|
+
content: trimmed.length > 100 ? trimmed.slice(0, 100) + "..." : trimmed
|
|
213
|
+
});
|
|
214
|
+
}
|
|
134
215
|
}
|
|
135
216
|
};
|
|
136
|
-
function createNdjsonParseStream() {
|
|
137
|
-
|
|
217
|
+
function createNdjsonParseStream(options = {}) {
|
|
218
|
+
const maxLineLength = resolveMaxLineLength(options.maxLineLength);
|
|
219
|
+
const lines = new LineAssembler(maxLineLength);
|
|
220
|
+
const enqueueLine = (line, controller) => {
|
|
221
|
+
const trimmed = line.trim();
|
|
222
|
+
if (trimmed.length === 0) return;
|
|
223
|
+
const result = parseLine(trimmed);
|
|
224
|
+
if (result.success) {
|
|
225
|
+
controller.enqueue(result.data);
|
|
226
|
+
}
|
|
227
|
+
};
|
|
138
228
|
return new TransformStream({
|
|
139
229
|
transform(chunk, controller) {
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
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);
|
|
230
|
+
lines.push(
|
|
231
|
+
chunk,
|
|
232
|
+
(line) => enqueueLine(line, controller),
|
|
233
|
+
() => {
|
|
234
|
+
throw new NdjsonLineTooLongError(maxLineLength);
|
|
150
235
|
}
|
|
151
|
-
|
|
236
|
+
);
|
|
152
237
|
},
|
|
153
238
|
flush(controller) {
|
|
154
|
-
|
|
155
|
-
if (trimmed.length > 0) {
|
|
156
|
-
const result = parseLine(trimmed);
|
|
157
|
-
if (result.success) {
|
|
158
|
-
controller.enqueue(result.data);
|
|
159
|
-
}
|
|
160
|
-
}
|
|
239
|
+
enqueueLine(lines.take(), controller);
|
|
161
240
|
}
|
|
162
241
|
});
|
|
163
242
|
}
|
|
@@ -168,15 +247,19 @@ function createNdjsonSerializeStream() {
|
|
|
168
247
|
}
|
|
169
248
|
});
|
|
170
249
|
}
|
|
171
|
-
|
|
250
|
+
function parseNdjsonStream(stream, options = {}) {
|
|
251
|
+
return readNdjsonStream(stream, resolveMaxLineLength(options.maxLineLength));
|
|
252
|
+
}
|
|
253
|
+
async function* readNdjsonStream(stream, maxLineLength) {
|
|
172
254
|
const decoder = new TextDecoder();
|
|
173
255
|
const reader = stream.getReader();
|
|
174
|
-
|
|
256
|
+
const lines = new LineAssembler(maxLineLength);
|
|
257
|
+
const completed = [];
|
|
175
258
|
try {
|
|
176
259
|
while (true) {
|
|
177
260
|
const { done, value } = await reader.read();
|
|
178
261
|
if (done) {
|
|
179
|
-
const trimmed =
|
|
262
|
+
const trimmed = lines.take().trim();
|
|
180
263
|
if (trimmed.length > 0) {
|
|
181
264
|
const result = parseLine(trimmed);
|
|
182
265
|
if (result.success) {
|
|
@@ -185,11 +268,20 @@ async function* parseNdjsonStream(stream) {
|
|
|
185
268
|
}
|
|
186
269
|
break;
|
|
187
270
|
}
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
271
|
+
let tooLong;
|
|
272
|
+
try {
|
|
273
|
+
lines.push(
|
|
274
|
+
decoder.decode(value, { stream: true }),
|
|
275
|
+
(line) => completed.push(line),
|
|
276
|
+
() => {
|
|
277
|
+
throw new NdjsonLineTooLongError(maxLineLength);
|
|
278
|
+
}
|
|
279
|
+
);
|
|
280
|
+
} catch (error) {
|
|
281
|
+
if (!(error instanceof NdjsonLineTooLongError)) throw error;
|
|
282
|
+
tooLong = error;
|
|
283
|
+
}
|
|
284
|
+
for (const line of completed.splice(0)) {
|
|
193
285
|
const trimmed = line.trim();
|
|
194
286
|
if (trimmed.length === 0) continue;
|
|
195
287
|
const result = parseLine(trimmed);
|
|
@@ -197,6 +289,10 @@ async function* parseNdjsonStream(stream) {
|
|
|
197
289
|
yield result.data;
|
|
198
290
|
}
|
|
199
291
|
}
|
|
292
|
+
if (tooLong) {
|
|
293
|
+
await reader.cancel(tooLong).catch(() => void 0);
|
|
294
|
+
throw tooLong;
|
|
295
|
+
}
|
|
200
296
|
}
|
|
201
297
|
} finally {
|
|
202
298
|
reader.releaseLock();
|
|
@@ -208,6 +304,7 @@ import {
|
|
|
208
304
|
SupportedCurve,
|
|
209
305
|
EncryptionErrorCode,
|
|
210
306
|
PROTOCOL_VERSION,
|
|
307
|
+
PROTOCOL_VERSION_V1,
|
|
211
308
|
EncryptionAlgorithm,
|
|
212
309
|
KeyDerivation
|
|
213
310
|
} from "@enclave-vm/types";
|
|
@@ -232,8 +329,9 @@ async function generateKeyPair(curve = SupportedCurve.P256) {
|
|
|
232
329
|
name: "ECDH",
|
|
233
330
|
namedCurve: curve
|
|
234
331
|
},
|
|
235
|
-
|
|
236
|
-
//
|
|
332
|
+
// The private key stays inside Web Crypto. A public key can be exported whatever this
|
|
333
|
+
// flag says, which is all the handshake needs.
|
|
334
|
+
false,
|
|
237
335
|
["deriveBits"]
|
|
238
336
|
);
|
|
239
337
|
return {
|
|
@@ -322,7 +420,20 @@ async function createServerHello(keyPair, keyId) {
|
|
|
322
420
|
keyId
|
|
323
421
|
};
|
|
324
422
|
}
|
|
423
|
+
var HANDSHAKE_PROTOCOL_VERSIONS = [PROTOCOL_VERSION, PROTOCOL_VERSION_V1];
|
|
424
|
+
function assertHandshakeParameters(hello) {
|
|
425
|
+
if (!HANDSHAKE_PROTOCOL_VERSIONS.includes(hello.protocolVersion)) {
|
|
426
|
+
throw new EcdhError("Unsupported protocol version in handshake", EncryptionErrorCode.HandshakeFailed);
|
|
427
|
+
}
|
|
428
|
+
if (!Object.values(SupportedCurve).includes(hello.curve)) {
|
|
429
|
+
throw new EcdhError("Unsupported curve in handshake", EncryptionErrorCode.UnsupportedAlgorithm);
|
|
430
|
+
}
|
|
431
|
+
}
|
|
325
432
|
async function processClientHello(clientHello) {
|
|
433
|
+
assertHandshakeParameters(clientHello);
|
|
434
|
+
if (!Array.isArray(clientHello.supportedAlgorithms) || !clientHello.supportedAlgorithms.includes(EncryptionAlgorithm.AES_GCM_256)) {
|
|
435
|
+
throw new EcdhError("No supported encryption algorithm in client hello", EncryptionErrorCode.UnsupportedAlgorithm);
|
|
436
|
+
}
|
|
326
437
|
const serverKeyPair = await generateKeyPair(clientHello.curve);
|
|
327
438
|
const peerPublicKey = await importPublicKey(clientHello.clientEphemeralPubKeyB64, clientHello.curve);
|
|
328
439
|
const keyId = `k_${crypto.randomUUID()}`;
|
|
@@ -335,6 +446,16 @@ async function processClientHello(clientHello) {
|
|
|
335
446
|
};
|
|
336
447
|
}
|
|
337
448
|
async function processServerHello(serverHello) {
|
|
449
|
+
assertHandshakeParameters(serverHello);
|
|
450
|
+
if (serverHello.selectedAlgorithm !== EncryptionAlgorithm.AES_GCM_256) {
|
|
451
|
+
throw new EcdhError("Unsupported encryption algorithm in server hello", EncryptionErrorCode.UnsupportedAlgorithm);
|
|
452
|
+
}
|
|
453
|
+
if (serverHello.kdf !== KeyDerivation.HKDF_SHA256) {
|
|
454
|
+
throw new EcdhError("Unsupported key derivation in server hello", EncryptionErrorCode.UnsupportedAlgorithm);
|
|
455
|
+
}
|
|
456
|
+
if (typeof serverHello.keyId !== "string" || serverHello.keyId.length === 0) {
|
|
457
|
+
throw new EcdhError("Missing key id in server hello", EncryptionErrorCode.HandshakeFailed);
|
|
458
|
+
}
|
|
338
459
|
const peerPublicKey = await importPublicKey(serverHello.serverEphemeralPubKeyB64, serverHello.curve);
|
|
339
460
|
return {
|
|
340
461
|
peerPublicKey,
|
|
@@ -469,18 +590,54 @@ function generateCounterNonce(prefix, counter) {
|
|
|
469
590
|
}
|
|
470
591
|
const nonce = new Uint8Array(AES_GCM_NONCE_SIZE);
|
|
471
592
|
nonce.set(prefix);
|
|
472
|
-
|
|
593
|
+
if (typeof counter !== "bigint" || counter < 0n || counter > 0xffffffffn) {
|
|
594
|
+
throw new AesGcmError("Nonce counter must be between 0 and 2^32 - 1", EncryptionErrorCode3.NonceReuse);
|
|
595
|
+
}
|
|
596
|
+
const counterValue = Number(counter);
|
|
473
597
|
nonce[8] = counterValue >> 24 & 255;
|
|
474
598
|
nonce[9] = counterValue >> 16 & 255;
|
|
475
599
|
nonce[10] = counterValue >> 8 & 255;
|
|
476
600
|
nonce[11] = counterValue & 255;
|
|
477
601
|
return nonce;
|
|
478
602
|
}
|
|
603
|
+
var BASE64_CHUNK_SIZE = 32768;
|
|
479
604
|
function toBase64(bytes) {
|
|
480
|
-
|
|
605
|
+
let binary = "";
|
|
606
|
+
for (let offset = 0; offset < bytes.length; offset += BASE64_CHUNK_SIZE) {
|
|
607
|
+
binary += String.fromCharCode(...bytes.subarray(offset, offset + BASE64_CHUNK_SIZE));
|
|
608
|
+
}
|
|
609
|
+
return btoa(binary);
|
|
481
610
|
}
|
|
482
611
|
function fromBase64(base64) {
|
|
483
|
-
|
|
612
|
+
let binary;
|
|
613
|
+
try {
|
|
614
|
+
binary = atob(base64);
|
|
615
|
+
} catch {
|
|
616
|
+
throw new AesGcmError("Invalid base64 input", EncryptionErrorCode3.DecryptionFailed);
|
|
617
|
+
}
|
|
618
|
+
const bytes = new Uint8Array(binary.length);
|
|
619
|
+
for (let i = 0; i < binary.length; i++) {
|
|
620
|
+
bytes[i] = binary.charCodeAt(i);
|
|
621
|
+
}
|
|
622
|
+
return bytes;
|
|
623
|
+
}
|
|
624
|
+
function encodeEnvelopeHeader(header) {
|
|
625
|
+
const { protocolVersion, sessionId, seq, kid } = header;
|
|
626
|
+
if (!Number.isSafeInteger(protocolVersion) || typeof sessionId !== "string" || !Number.isSafeInteger(seq) || seq < 0 || typeof kid !== "string") {
|
|
627
|
+
throw new AesGcmError("Invalid envelope header", EncryptionErrorCode3.DecryptionFailed);
|
|
628
|
+
}
|
|
629
|
+
return new TextEncoder().encode(JSON.stringify(["enclavejs-envelope", protocolVersion, sessionId, seq, kid]));
|
|
630
|
+
}
|
|
631
|
+
function receivedEnvelopeHeader(envelope) {
|
|
632
|
+
if (typeof envelope !== "object" || envelope === null || typeof envelope.payload !== "object" || !envelope.payload) {
|
|
633
|
+
throw new AesGcmError("Invalid envelope", EncryptionErrorCode3.DecryptionFailed);
|
|
634
|
+
}
|
|
635
|
+
return encodeEnvelopeHeader({
|
|
636
|
+
protocolVersion: envelope.protocolVersion,
|
|
637
|
+
sessionId: envelope.sessionId,
|
|
638
|
+
seq: envelope.seq,
|
|
639
|
+
kid: envelope.payload.kid
|
|
640
|
+
});
|
|
484
641
|
}
|
|
485
642
|
async function encrypt(key, plaintext, nonce, additionalData) {
|
|
486
643
|
const subtle = getSubtle3();
|
|
@@ -538,25 +695,26 @@ async function decrypt(key, ciphertext, nonce, additionalData) {
|
|
|
538
695
|
);
|
|
539
696
|
}
|
|
540
697
|
}
|
|
541
|
-
async function encryptJson(key, keyId, data, nonce) {
|
|
698
|
+
async function encryptJson(key, keyId, data, nonce, additionalData) {
|
|
542
699
|
const actualNonce = nonce ?? generateNonce();
|
|
543
700
|
const plaintext = new TextEncoder().encode(JSON.stringify(data));
|
|
544
|
-
const ciphertext = await encrypt(key, plaintext, actualNonce);
|
|
701
|
+
const ciphertext = await encrypt(key, plaintext, actualNonce, additionalData);
|
|
545
702
|
return {
|
|
546
703
|
kid: keyId,
|
|
547
704
|
nonceB64: toBase64(actualNonce),
|
|
548
705
|
ciphertextB64: toBase64(ciphertext)
|
|
549
706
|
};
|
|
550
707
|
}
|
|
551
|
-
async function decryptJson(key, payload) {
|
|
708
|
+
async function decryptJson(key, payload, additionalData) {
|
|
552
709
|
const nonce = fromBase64(payload.nonceB64);
|
|
553
710
|
const ciphertext = fromBase64(payload.ciphertextB64);
|
|
554
|
-
const plaintext = await decrypt(key, ciphertext, nonce);
|
|
711
|
+
const plaintext = await decrypt(key, ciphertext, nonce, additionalData);
|
|
555
712
|
const json = new TextDecoder().decode(plaintext);
|
|
556
713
|
return JSON.parse(json);
|
|
557
714
|
}
|
|
558
715
|
async function createEncryptedEnvelope(key, keyId, sessionId, seq, innerEvent, nonce) {
|
|
559
|
-
const
|
|
716
|
+
const header = encodeEnvelopeHeader({ protocolVersion: PROTOCOL_VERSION2, sessionId, seq, kid: keyId });
|
|
717
|
+
const payload = await encryptJson(key, keyId, innerEvent, nonce, header);
|
|
560
718
|
return {
|
|
561
719
|
protocolVersion: PROTOCOL_VERSION2,
|
|
562
720
|
sessionId,
|
|
@@ -565,6 +723,9 @@ async function createEncryptedEnvelope(key, keyId, sessionId, seq, innerEvent, n
|
|
|
565
723
|
payload
|
|
566
724
|
};
|
|
567
725
|
}
|
|
726
|
+
async function openEncryptedEnvelope(key, envelope) {
|
|
727
|
+
return decryptJson(key, envelope.payload, receivedEnvelopeHeader(envelope));
|
|
728
|
+
}
|
|
568
729
|
var SessionEncryptionContext = class _SessionEncryptionContext {
|
|
569
730
|
key;
|
|
570
731
|
keyInfo;
|
|
@@ -590,22 +751,27 @@ var SessionEncryptionContext = class _SessionEncryptionContext {
|
|
|
590
751
|
}
|
|
591
752
|
/**
|
|
592
753
|
* Encrypt data and increment the nonce counter.
|
|
754
|
+
*
|
|
755
|
+
* @param additionalData - Optional additional authenticated data
|
|
593
756
|
*/
|
|
594
|
-
async encrypt(plaintext) {
|
|
757
|
+
async encrypt(plaintext, additionalData) {
|
|
595
758
|
if (this.needsRotation()) {
|
|
596
759
|
throw new AesGcmError("Key needs rotation: nonce limit reached", EncryptionErrorCode3.KeyExpired);
|
|
597
760
|
}
|
|
598
761
|
const nonce = generateCounterNonce(this.noncePrefix, this.nonceCounter);
|
|
599
762
|
this.nonceCounter++;
|
|
600
|
-
const ciphertext = await encrypt(this.key, plaintext, nonce);
|
|
763
|
+
const ciphertext = await encrypt(this.key, plaintext, nonce, additionalData);
|
|
601
764
|
return { ciphertext, nonce };
|
|
602
765
|
}
|
|
603
766
|
/**
|
|
604
767
|
* Encrypt JSON data.
|
|
768
|
+
*
|
|
769
|
+
* @param additionalData - Optional additional authenticated data; the same bytes must be
|
|
770
|
+
* given to `decryptJson`
|
|
605
771
|
*/
|
|
606
|
-
async encryptJson(data) {
|
|
772
|
+
async encryptJson(data, additionalData) {
|
|
607
773
|
const plaintext = new TextEncoder().encode(JSON.stringify(data));
|
|
608
|
-
const { ciphertext, nonce } = await this.encrypt(plaintext);
|
|
774
|
+
const { ciphertext, nonce } = await this.encrypt(plaintext, additionalData);
|
|
609
775
|
return {
|
|
610
776
|
kid: this.keyId,
|
|
611
777
|
nonceB64: toBase64(nonce),
|
|
@@ -614,9 +780,13 @@ var SessionEncryptionContext = class _SessionEncryptionContext {
|
|
|
614
780
|
}
|
|
615
781
|
/**
|
|
616
782
|
* Create an encrypted envelope.
|
|
783
|
+
*
|
|
784
|
+
* The envelope's header (protocol version, session id, sequence number, key id) is
|
|
785
|
+
* authenticated together with the event: read the envelope with `openEnvelope`.
|
|
617
786
|
*/
|
|
618
787
|
async createEnvelope(sessionId, seq, innerEvent) {
|
|
619
|
-
const
|
|
788
|
+
const header = encodeEnvelopeHeader({ protocolVersion: PROTOCOL_VERSION2, sessionId, seq, kid: this.keyId });
|
|
789
|
+
const payload = await this.encryptJson(innerEvent, header);
|
|
620
790
|
return {
|
|
621
791
|
protocolVersion: PROTOCOL_VERSION2,
|
|
622
792
|
sessionId,
|
|
@@ -626,21 +796,37 @@ var SessionEncryptionContext = class _SessionEncryptionContext {
|
|
|
626
796
|
};
|
|
627
797
|
}
|
|
628
798
|
/**
|
|
629
|
-
* Decrypt
|
|
799
|
+
* Decrypt a payload made by `encrypt` or `encryptJson`.
|
|
800
|
+
* The payload of an envelope is read with `openEnvelope`.
|
|
801
|
+
*
|
|
802
|
+
* @param additionalData - The additional authenticated data given when encrypting, if any
|
|
630
803
|
*/
|
|
631
|
-
async decrypt(payload) {
|
|
804
|
+
async decrypt(payload, additionalData) {
|
|
632
805
|
const nonce = fromBase64(payload.nonceB64);
|
|
633
806
|
const ciphertext = fromBase64(payload.ciphertextB64);
|
|
634
|
-
return decrypt(this.key, ciphertext, nonce);
|
|
807
|
+
return decrypt(this.key, ciphertext, nonce, additionalData);
|
|
635
808
|
}
|
|
636
809
|
/**
|
|
637
|
-
* Decrypt and parse JSON from
|
|
810
|
+
* Decrypt and parse JSON from a payload made by `encryptJson`.
|
|
811
|
+
* The payload of an envelope is read with `openEnvelope`.
|
|
812
|
+
*
|
|
813
|
+
* @param additionalData - The additional authenticated data given when encrypting, if any
|
|
638
814
|
*/
|
|
639
|
-
async decryptJson(payload) {
|
|
640
|
-
const plaintext = await this.decrypt(payload);
|
|
815
|
+
async decryptJson(payload, additionalData) {
|
|
816
|
+
const plaintext = await this.decrypt(payload, additionalData);
|
|
641
817
|
const json = new TextDecoder().decode(plaintext);
|
|
642
818
|
return JSON.parse(json);
|
|
643
819
|
}
|
|
820
|
+
/**
|
|
821
|
+
* Decrypt an encrypted envelope and parse the event inside it.
|
|
822
|
+
*
|
|
823
|
+
* Fails when the ciphertext or any header field of the envelope (protocol version, session
|
|
824
|
+
* id, sequence number, key id) is not what the sender encrypted. Whether a sequence number
|
|
825
|
+
* was seen before is for the caller to check.
|
|
826
|
+
*/
|
|
827
|
+
async openEnvelope(envelope) {
|
|
828
|
+
return this.decryptJson(envelope.payload, receivedEnvelopeHeader(envelope));
|
|
829
|
+
}
|
|
644
830
|
/**
|
|
645
831
|
* Get the current nonce counter value.
|
|
646
832
|
*/
|
|
@@ -649,6 +835,7 @@ var SessionEncryptionContext = class _SessionEncryptionContext {
|
|
|
649
835
|
}
|
|
650
836
|
/**
|
|
651
837
|
* Create session key info for serialization.
|
|
838
|
+
* The result holds the raw key bytes: treat it as the key itself.
|
|
652
839
|
*/
|
|
653
840
|
toKeyInfo() {
|
|
654
841
|
return {
|
|
@@ -1012,11 +1199,13 @@ var HeartbeatMonitor = class {
|
|
|
1012
1199
|
export {
|
|
1013
1200
|
AesGcmError,
|
|
1014
1201
|
ConnectionState,
|
|
1202
|
+
DEFAULT_MAX_LINE_LENGTH,
|
|
1015
1203
|
DEFAULT_RECONNECTION_CONFIG,
|
|
1016
1204
|
EcdhError,
|
|
1017
1205
|
EventBuffer,
|
|
1018
1206
|
HeartbeatMonitor,
|
|
1019
1207
|
HkdfError,
|
|
1208
|
+
NdjsonLineTooLongError,
|
|
1020
1209
|
NdjsonStreamParser,
|
|
1021
1210
|
ReconnectionStateMachine,
|
|
1022
1211
|
SequenceTracker,
|
|
@@ -1032,6 +1221,7 @@ export {
|
|
|
1032
1221
|
deriveSessionCryptoKeys,
|
|
1033
1222
|
deriveSessionKeys,
|
|
1034
1223
|
deriveSharedSecret,
|
|
1224
|
+
encodeEnvelopeHeader,
|
|
1035
1225
|
encrypt,
|
|
1036
1226
|
encryptJson,
|
|
1037
1227
|
exportPublicKey,
|
|
@@ -1041,6 +1231,7 @@ export {
|
|
|
1041
1231
|
generateNonce,
|
|
1042
1232
|
importAesGcmKey,
|
|
1043
1233
|
importPublicKey,
|
|
1234
|
+
openEncryptedEnvelope,
|
|
1044
1235
|
parseLine,
|
|
1045
1236
|
parseLines,
|
|
1046
1237
|
parseNdjsonStream,
|
package/index.d.ts
CHANGED
|
@@ -1,15 +1,18 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @enclave-vm/stream
|
|
3
3
|
*
|
|
4
|
-
* Streaming protocol
|
|
5
|
-
*
|
|
4
|
+
* Streaming protocol building blocks for the EnclaveJS runtime:
|
|
5
|
+
* NDJSON parsing, reconnection helpers and encryption primitives.
|
|
6
|
+
*
|
|
7
|
+
* The encryption primitives are not used by the client or the broker of this repository;
|
|
8
|
+
* an application that wants encrypted events wires them into both of its ends itself.
|
|
6
9
|
*
|
|
7
10
|
* @packageDocumentation
|
|
8
11
|
*/
|
|
9
12
|
export * from '@enclave-vm/types';
|
|
10
|
-
export { serializeEvent, serializeEvents, parseLine, parseLines, NdjsonStreamParser, createNdjsonParseStream, createNdjsonSerializeStream, parseNdjsonStream, } from './ndjson.js';
|
|
11
|
-
export type { ParseResult } from './ndjson.js';
|
|
12
|
-
export { generateKeyPair, exportPublicKey, importPublicKey, deriveSharedSecret, createClientHello, createServerHello, processClientHello, processServerHello, EcdhError, deriveKey, deriveSessionKeys, importAesGcmKey, deriveSessionCryptoKeys, HkdfError, generateNonce, generateCounterNonce, toBase64, fromBase64, encrypt, decrypt, encryptJson, decryptJson, createEncryptedEnvelope, SessionEncryptionContext, AesGcmError, } from './crypto/index.js';
|
|
13
|
-
export type { EcdhKeyPair, SerializedPublicKey } from './crypto/index.js';
|
|
13
|
+
export { serializeEvent, serializeEvents, parseLine, parseLines, NdjsonStreamParser, createNdjsonParseStream, createNdjsonSerializeStream, parseNdjsonStream, DEFAULT_MAX_LINE_LENGTH, NdjsonLineTooLongError, } from './ndjson.js';
|
|
14
|
+
export type { ParseResult, NdjsonParseOptions } from './ndjson.js';
|
|
15
|
+
export { generateKeyPair, exportPublicKey, importPublicKey, deriveSharedSecret, createClientHello, createServerHello, processClientHello, processServerHello, EcdhError, deriveKey, deriveSessionKeys, importAesGcmKey, deriveSessionCryptoKeys, HkdfError, generateNonce, generateCounterNonce, toBase64, fromBase64, encrypt, decrypt, encryptJson, decryptJson, createEncryptedEnvelope, openEncryptedEnvelope, encodeEnvelopeHeader, SessionEncryptionContext, AesGcmError, } from './crypto/index.js';
|
|
16
|
+
export type { EcdhKeyPair, SerializedPublicKey, EnvelopeHeader, EnvelopeLike } from './crypto/index.js';
|
|
14
17
|
export { ConnectionState, DEFAULT_RECONNECTION_CONFIG, ReconnectionStateMachine, SequenceTracker, EventBuffer, HeartbeatMonitor, } from './reconnect.js';
|
|
15
18
|
export type { ReconnectionConfig, ReconnectionEvent } from './reconnect.js';
|