@enclave-vm/stream 2.19.1 → 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/README.md
CHANGED
|
@@ -4,17 +4,17 @@
|
|
|
4
4
|
[](LICENSE)
|
|
5
5
|
[](https://www.typescriptlang.org/)
|
|
6
6
|
|
|
7
|
-
> Streaming protocol
|
|
7
|
+
> Streaming protocol building blocks for EnclaveJS (NDJSON, reconnection helpers, encryption primitives)
|
|
8
8
|
|
|
9
|
-
The @enclave-vm/stream package provides the
|
|
9
|
+
The @enclave-vm/stream package provides the building blocks of the EnclaveJS streaming protocol: NDJSON serialization and parsing, helpers for reconnection, and encryption primitives built on the Web Crypto API. It also re-exports everything from `@enclave-vm/types`.
|
|
10
|
+
|
|
11
|
+
> **No EnclaveJS package uses the encryption primitives.** `@enclave-vm/client`, `@enclave-vm/react`, `@enclave-vm/broker` and `@enclave-vm/runtime` do not encrypt, perform no handshake and have no encryption option. A session between the client and the broker is plain JSON protected only by the transport, so serve it over HTTPS. The encryption functions of this package are for an application that implements both ends of an encrypted channel itself. See [Encryption Primitives](#encryption-primitives) for what such an application has to do.
|
|
10
12
|
|
|
11
13
|
## Features
|
|
12
14
|
|
|
13
|
-
- **NDJSON
|
|
14
|
-
- **
|
|
15
|
-
- **
|
|
16
|
-
- **State Recovery**: Resume sessions after disconnection
|
|
17
|
-
- **Backpressure Handling**: Flow control for high-throughput scenarios
|
|
15
|
+
- **NDJSON**: Serialize and parse stream events, one JSON object per line, with a limit on the line length
|
|
16
|
+
- **Reconnection Helpers**: Backoff state machine, sequence tracker, event buffer and heartbeat monitor
|
|
17
|
+
- **Encryption Primitives**: ECDH P-256 key exchange helpers, HKDF-SHA-256 key derivation, AES-256-GCM and the `enc` envelope
|
|
18
18
|
- **Cross-Platform**: Works in Node.js and browsers
|
|
19
19
|
|
|
20
20
|
## Installation
|
|
@@ -30,129 +30,168 @@ pnpm add @enclave-vm/stream
|
|
|
30
30
|
## Quick Start
|
|
31
31
|
|
|
32
32
|
```typescript
|
|
33
|
-
import {
|
|
33
|
+
import { serializeEvent, NdjsonStreamParser } from '@enclave-vm/stream';
|
|
34
|
+
|
|
35
|
+
// One event per line
|
|
36
|
+
const line = serializeEvent({
|
|
37
|
+
protocolVersion: 2,
|
|
38
|
+
sessionId: 's_123',
|
|
39
|
+
seq: 1,
|
|
40
|
+
type: 'stdout',
|
|
41
|
+
payload: { chunk: 'Hello\n' },
|
|
42
|
+
});
|
|
34
43
|
|
|
35
|
-
//
|
|
36
|
-
const
|
|
37
|
-
|
|
44
|
+
// Incremental parsing: a chunk may end in the middle of a line
|
|
45
|
+
const parser = new NdjsonStreamParser({
|
|
46
|
+
onEvent: (event) => console.log('Received:', event.type),
|
|
47
|
+
onError: (error) => console.error(`Line ${error.line}: ${error.error}`),
|
|
48
|
+
});
|
|
38
49
|
|
|
39
|
-
|
|
40
|
-
|
|
50
|
+
parser.feed(line.slice(0, 20));
|
|
51
|
+
parser.feed(line.slice(20) + '\n');
|
|
41
52
|
|
|
42
|
-
//
|
|
43
|
-
|
|
44
|
-
console.log('Received:', message);
|
|
45
|
-
});
|
|
46
|
-
decoder.write(encoded);
|
|
53
|
+
// When the stream ends
|
|
54
|
+
parser.flush();
|
|
47
55
|
```
|
|
48
56
|
|
|
49
|
-
##
|
|
57
|
+
## NDJSON
|
|
50
58
|
|
|
51
|
-
|
|
59
|
+
| Export | Description |
|
|
60
|
+
| ------------------------------------- | ------------------------------------------------------------------------ |
|
|
61
|
+
| `serializeEvent(event)` | One event as one line (no trailing newline) |
|
|
62
|
+
| `serializeEvents(events)` | Several events, joined with `\n` |
|
|
63
|
+
| `parseLine(line)` | Parse and validate one line: `{ success, data }` or `{ success, error }` |
|
|
64
|
+
| `parseLines(data)` | Parse several lines: `{ events, errors }` |
|
|
65
|
+
| `NdjsonStreamParser` | Incremental parser (`feed`, `flush`) with `onEvent` and `onError` |
|
|
66
|
+
| `createNdjsonParseStream(options?)` | `TransformStream` from text chunks to events |
|
|
67
|
+
| `createNdjsonSerializeStream()` | `TransformStream` from events to lines |
|
|
68
|
+
| `parseNdjsonStream(stream, options?)` | Async generator over a `ReadableStream<Uint8Array>` (a `fetch()` body) |
|
|
52
69
|
|
|
53
|
-
|
|
54
|
-
import { createEncryptedChannel } from '@enclave-vm/stream';
|
|
70
|
+
Lines are validated against the event schemas of `@enclave-vm/types`. `NdjsonStreamParser` reports a line that is not an event through `onError`; `createNdjsonParseStream` and `parseNdjsonStream` skip it.
|
|
55
71
|
|
|
56
|
-
|
|
57
|
-
const serverChannel = await createEncryptedChannel({
|
|
58
|
-
role: 'server',
|
|
59
|
-
onMessage: (message) => {
|
|
60
|
-
console.log('Decrypted message:', message);
|
|
61
|
-
},
|
|
62
|
-
});
|
|
72
|
+
The incremental parsers take a `maxLineLength` option, in characters. The default is `DEFAULT_MAX_LINE_LENGTH` (8 MiB). When a line is longer:
|
|
63
73
|
|
|
64
|
-
|
|
65
|
-
|
|
74
|
+
- `NdjsonStreamParser` reports it once through `onError` and skips it.
|
|
75
|
+
- `createNdjsonParseStream` and `parseNdjsonStream` end with an `NdjsonLineTooLongError`.
|
|
66
76
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
onMessage: (message) => {
|
|
72
|
-
console.log('Decrypted message:', message);
|
|
73
|
-
},
|
|
74
|
-
});
|
|
77
|
+
A `maxLineLength` that is not a positive integer throws a `RangeError`.
|
|
78
|
+
|
|
79
|
+
```typescript
|
|
80
|
+
import { parseNdjsonStream } from '@enclave-vm/stream';
|
|
75
81
|
|
|
76
|
-
|
|
77
|
-
|
|
82
|
+
const response = await fetch('https://api.example.com/sessions/s_123/stream');
|
|
83
|
+
if (!response.body) throw new Error('No response body');
|
|
84
|
+
|
|
85
|
+
for await (const event of parseNdjsonStream(response.body, { maxLineLength: 1024 * 1024 })) {
|
|
86
|
+
console.log(event.type);
|
|
87
|
+
}
|
|
78
88
|
```
|
|
79
89
|
|
|
80
|
-
## Reconnection
|
|
90
|
+
## Reconnection Helpers
|
|
81
91
|
|
|
82
|
-
|
|
92
|
+
The package does not open connections. These classes keep the state of a connection that the application opens:
|
|
83
93
|
|
|
84
94
|
```typescript
|
|
85
|
-
import {
|
|
86
|
-
|
|
87
|
-
const
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
},
|
|
99
|
-
onMessage: (message) => {
|
|
100
|
-
handleMessage(message);
|
|
95
|
+
import { ConnectionState, ReconnectionStateMachine, SequenceTracker } from '@enclave-vm/stream';
|
|
96
|
+
|
|
97
|
+
const tracker = new SequenceTracker();
|
|
98
|
+
|
|
99
|
+
const connection = new ReconnectionStateMachine({
|
|
100
|
+
config: { maxRetries: 5, initialDelayMs: 1000, maxDelayMs: 30000, backoffMultiplier: 2 },
|
|
101
|
+
onEvent: (event) => {
|
|
102
|
+
if (event.type === 'state_change' && event.state === ConnectionState.Connecting) {
|
|
103
|
+
// Open the connection here, asking for the events after tracker.getLastSeq()
|
|
104
|
+
}
|
|
105
|
+
if (event.type === 'retry_scheduled') {
|
|
106
|
+
console.log(`Reconnecting in ${event.delayMs}ms (attempt ${event.attempt})`);
|
|
107
|
+
}
|
|
101
108
|
},
|
|
102
109
|
});
|
|
103
110
|
|
|
104
|
-
|
|
105
|
-
```
|
|
106
|
-
|
|
107
|
-
## NDJSON Utilities
|
|
111
|
+
connection.connect();
|
|
108
112
|
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
// Parse NDJSON string
|
|
113
|
-
const messages = parseNDJSON(ndjsonString);
|
|
113
|
+
// Report what happens to the connection
|
|
114
|
+
connection.onConnected();
|
|
115
|
+
connection.onDisconnected('network error'); // schedules a retry with exponential backoff
|
|
114
116
|
|
|
115
|
-
//
|
|
116
|
-
|
|
117
|
-
{
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
]);
|
|
117
|
+
// For every event received
|
|
118
|
+
function track(event: { seq: number }): void {
|
|
119
|
+
const { gap, missingStart, missingEnd } = tracker.receive(event.seq);
|
|
120
|
+
if (gap) console.log(`Missing events ${missingStart} to ${missingEnd}`);
|
|
121
|
+
}
|
|
121
122
|
```
|
|
122
123
|
|
|
123
|
-
|
|
124
|
+
| Export | Description |
|
|
125
|
+
| ----------------------------- | ----------------------------------------------------------------------------------- |
|
|
126
|
+
| `ReconnectionStateMachine` | Connection state and retries with exponential backoff and jitter |
|
|
127
|
+
| `ConnectionState` | `Disconnected`, `Connecting`, `Connected`, `Reconnecting`, `Failed`, `Closed` |
|
|
128
|
+
| `DEFAULT_RECONNECTION_CONFIG` | 5 retries, 1 s initial delay, 30 s maximum delay, multiplier 2, jitter factor 0.3 |
|
|
129
|
+
| `SequenceTracker` | Last sequence number received and the gaps before it |
|
|
130
|
+
| `EventBuffer` | Bounded buffer of events (1000 by default); `add()` returns `false` when it is full |
|
|
131
|
+
| `HeartbeatMonitor` | Calls `onTimeout` when no heartbeat was reported for `timeoutMs` |
|
|
124
132
|
|
|
125
|
-
|
|
133
|
+
## Encryption Primitives
|
|
126
134
|
|
|
127
|
-
|
|
128
|
-
- **Symmetric Encryption**: AES-256-GCM with random IV per message
|
|
129
|
-
- **Key Derivation**: HKDF for deriving encryption keys from shared secret
|
|
135
|
+
The package exports ECDH P-256 key exchange helpers, HKDF-SHA-256 key derivation, AES-256-GCM encryption and the `enc` envelope of the protocol. Nothing in EnclaveJS calls them: an application that wants payload encryption has to write both ends, exchange the hello messages and envelopes over its own endpoints, and keep using TLS.
|
|
130
136
|
|
|
131
137
|
```typescript
|
|
132
|
-
import {
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
138
|
+
import {
|
|
139
|
+
generateKeyPair,
|
|
140
|
+
createClientHello,
|
|
141
|
+
processClientHello,
|
|
142
|
+
processServerHello,
|
|
143
|
+
deriveSharedSecret,
|
|
144
|
+
deriveSessionKeys,
|
|
145
|
+
SessionEncryptionContext,
|
|
146
|
+
} from '@enclave-vm/stream';
|
|
147
|
+
|
|
148
|
+
const sessionId = 's_123';
|
|
149
|
+
|
|
150
|
+
// Client: ephemeral key pair and hello
|
|
151
|
+
const clientKeyPair = await generateKeyPair();
|
|
152
|
+
const clientHello = await createClientHello(clientKeyPair);
|
|
153
|
+
|
|
154
|
+
// Server: answer the hello, derive the session keys
|
|
155
|
+
const { serverKeyPair, peerPublicKey: clientPublicKey, serverHello, keyId } = await processClientHello(clientHello);
|
|
156
|
+
const serverSecret = await deriveSharedSecret(serverKeyPair.privateKey, clientPublicKey);
|
|
157
|
+
const serverKeys = await deriveSessionKeys(serverSecret, sessionId);
|
|
158
|
+
|
|
159
|
+
// Client: read the server hello, derive the same session keys
|
|
160
|
+
const { peerPublicKey: serverPublicKey } = await processServerHello(serverHello);
|
|
161
|
+
const clientSecret = await deriveSharedSecret(clientKeyPair.privateKey, serverPublicKey);
|
|
162
|
+
const clientKeys = await deriveSessionKeys(clientSecret, sessionId);
|
|
163
|
+
|
|
164
|
+
// One context per direction, on each side
|
|
165
|
+
const serverSends = await SessionEncryptionContext.fromKeyBytes(serverKeys.serverToClientKey, keyId);
|
|
166
|
+
const clientReceives = await SessionEncryptionContext.fromKeyBytes(clientKeys.serverToClientKey, keyId);
|
|
167
|
+
|
|
168
|
+
// Server: wrap an event in an `enc` envelope
|
|
169
|
+
const envelope = await serverSends.createEnvelope(sessionId, 1, { type: 'stdout', payload: { chunk: 'Hello\n' } });
|
|
170
|
+
|
|
171
|
+
// Client: open it
|
|
172
|
+
const event = await clientReceives.openEnvelope(envelope);
|
|
173
|
+
```
|
|
137
174
|
|
|
138
|
-
|
|
139
|
-
const serverSecret = await deriveSharedSecret(serverKeys.privateKey, clientKeys.publicKey);
|
|
140
|
-
const clientSecret = await deriveSharedSecret(clientKeys.privateKey, serverKeys.publicKey);
|
|
175
|
+
What the primitives do, and what is left to the application:
|
|
141
176
|
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
177
|
+
- **The key exchange is not authenticated.** `ServerHello.signatureB64` is neither created nor verified, and there is no key confirmation. The exchange protects against a party that can only read the connection. A party that can change messages can replace both public keys. An application that needs more has to authenticate the hello messages itself (for example by signing them with a key the client pins) or rely on TLS for the identity of the server.
|
|
178
|
+
- **There are two keys, one per direction.** `deriveSessionKeys` and `deriveSessionCryptoKeys` return `clientToServerKey` and `serverToClientKey`. Use one `SessionEncryptionContext` per direction, never one context for both.
|
|
179
|
+
- **An envelope authenticates its header.** `createEncryptedEnvelope(key, keyId, sessionId, seq, innerEvent, nonce?)` and `context.createEnvelope(sessionId, seq, innerEvent)` authenticate the protocol version, session id, sequence number and key id together with the event. Read envelopes with `openEncryptedEnvelope(key, envelope)` or `context.openEnvelope(envelope)`: they throw `AesGcmError` when the ciphertext or a header field differs.
|
|
180
|
+
- **`decryptJson` does not open an envelope.** `decryptJson(key, payload)` and `context.decryptJson(payload)` read payloads made by `encryptJson`. Both forms of `encryptJson` and `decryptJson` take optional additional authenticated data.
|
|
181
|
+
- **Replays are for the receiver to detect.** Opening an envelope does not tell whether its sequence number was seen before. Compare it with the last one received, for example with `SequenceTracker`.
|
|
182
|
+
- **A context has a message limit.** `SessionEncryptionContext` uses a counter nonce (8 random bytes per context and a 32-bit counter) and refuses to encrypt after 2^30 messages (`needsRotation()` then returns `true`). There is no rotation: exchange keys again.
|
|
183
|
+
- **Key material.** `generateKeyPair` returns a private key that cannot be exported. `deriveSessionKeys` returns raw key bytes, and so does `context.toKeyInfo()`: treat both as the key itself.
|
|
184
|
+
- **Errors.** `processClientHello` and `processServerHello` throw `EcdhError` for a protocol version, curve, algorithm or key derivation that is not implemented. `fromBase64` throws `AesGcmError` on malformed input. `generateCounterNonce` throws for a counter outside 0 to 2^32 - 1.
|
|
146
185
|
|
|
147
186
|
## Related Packages
|
|
148
187
|
|
|
149
|
-
| Package
|
|
150
|
-
|
|
|
151
|
-
| [@enclave-vm/types](../
|
|
152
|
-
| [@enclave-vm/broker](../
|
|
153
|
-
| [@enclave-vm/client](../
|
|
154
|
-
| [@enclave-vm/react](../
|
|
155
|
-
| [@enclave-vm/runtime](../
|
|
188
|
+
| Package | Description |
|
|
189
|
+
| --------------------------------- | ------------------------------------------------------- |
|
|
190
|
+
| [@enclave-vm/types](../types) | Type definitions and Zod schemas |
|
|
191
|
+
| [@enclave-vm/broker](../broker) | Tool broker and session management |
|
|
192
|
+
| [@enclave-vm/client](../client) | Browser/Node.js client SDK |
|
|
193
|
+
| [@enclave-vm/react](../react) | React hooks and components |
|
|
194
|
+
| [@enclave-vm/runtime](../runtime) | Runtime worker building blocks (not a runnable service) |
|
|
156
195
|
|
|
157
196
|
## License
|
|
158
197
|
|
package/crypto/aes-gcm.d.ts
CHANGED
|
@@ -26,8 +26,41 @@ export declare function generateCounterNonce(prefix: Uint8Array, counter: bigint
|
|
|
26
26
|
export declare function toBase64(bytes: Uint8Array): string;
|
|
27
27
|
/**
|
|
28
28
|
* Decode base64 to bytes.
|
|
29
|
+
*
|
|
30
|
+
* @throws AesGcmError when the input is not base64
|
|
29
31
|
*/
|
|
30
32
|
export declare function fromBase64(base64: string): Uint8Array;
|
|
33
|
+
/**
|
|
34
|
+
* The header fields of an encrypted envelope: everything that travels in clear next to the
|
|
35
|
+
* ciphertext.
|
|
36
|
+
*/
|
|
37
|
+
export interface EnvelopeHeader {
|
|
38
|
+
protocolVersion: number;
|
|
39
|
+
sessionId: string;
|
|
40
|
+
seq: number;
|
|
41
|
+
/** Key ID (`payload.kid` of the envelope) */
|
|
42
|
+
kid: string;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Encode an envelope header as additional authenticated data.
|
|
46
|
+
*
|
|
47
|
+
* The envelope functions pass this to AES-GCM, so the header is covered by the authentication
|
|
48
|
+
* tag: an envelope whose protocol version, session id, sequence number or key id differs from
|
|
49
|
+
* what the sender encrypted under does not decrypt.
|
|
50
|
+
*
|
|
51
|
+
* @throws AesGcmError when a field is not of its type (the encoding must be unambiguous)
|
|
52
|
+
*/
|
|
53
|
+
export declare function encodeEnvelopeHeader(header: EnvelopeHeader): Uint8Array;
|
|
54
|
+
/**
|
|
55
|
+
* An encrypted envelope as it is received: an `EncryptedEnvelope`, or what the schema of
|
|
56
|
+
* `@enclave-vm/types` parses one into.
|
|
57
|
+
*/
|
|
58
|
+
export interface EnvelopeLike {
|
|
59
|
+
protocolVersion: number;
|
|
60
|
+
sessionId: string;
|
|
61
|
+
seq: number;
|
|
62
|
+
payload: EncryptedEnvelopePayload;
|
|
63
|
+
}
|
|
31
64
|
/**
|
|
32
65
|
* Encrypt data using AES-GCM.
|
|
33
66
|
*
|
|
@@ -50,16 +83,36 @@ export declare function encrypt(key: CryptoKey, plaintext: Uint8Array, nonce: Ui
|
|
|
50
83
|
export declare function decrypt(key: CryptoKey, ciphertext: Uint8Array, nonce: Uint8Array, additionalData?: Uint8Array): Promise<Uint8Array>;
|
|
51
84
|
/**
|
|
52
85
|
* Encrypt a JSON object and create an encrypted envelope payload.
|
|
86
|
+
*
|
|
87
|
+
* @param additionalData - Optional additional authenticated data; the same bytes must be given
|
|
88
|
+
* to `decryptJson`
|
|
53
89
|
*/
|
|
54
|
-
export declare function encryptJson(key: CryptoKey, keyId: string, data: unknown, nonce?: Uint8Array): Promise<EncryptedEnvelopePayload>;
|
|
90
|
+
export declare function encryptJson(key: CryptoKey, keyId: string, data: unknown, nonce?: Uint8Array, additionalData?: Uint8Array): Promise<EncryptedEnvelopePayload>;
|
|
55
91
|
/**
|
|
56
92
|
* Decrypt an encrypted envelope payload and parse as JSON.
|
|
93
|
+
*
|
|
94
|
+
* This reads a payload made by `encryptJson`. The payload of an envelope is read with
|
|
95
|
+
* `openEncryptedEnvelope`, which also checks the envelope's header.
|
|
96
|
+
*
|
|
97
|
+
* @param additionalData - The additional authenticated data given to `encryptJson`, if any
|
|
57
98
|
*/
|
|
58
|
-
export declare function decryptJson<T>(key: CryptoKey, payload: EncryptedEnvelopePayload): Promise<T>;
|
|
99
|
+
export declare function decryptJson<T>(key: CryptoKey, payload: EncryptedEnvelopePayload, additionalData?: Uint8Array): Promise<T>;
|
|
59
100
|
/**
|
|
60
101
|
* Create an encrypted envelope from an event.
|
|
102
|
+
*
|
|
103
|
+
* The envelope's header (protocol version, session id, sequence number, key id) is
|
|
104
|
+
* authenticated together with the event: read the envelope with `openEncryptedEnvelope`.
|
|
61
105
|
*/
|
|
62
106
|
export declare function createEncryptedEnvelope(key: CryptoKey, keyId: string, sessionId: SessionId, seq: number, innerEvent: unknown, nonce?: Uint8Array): Promise<EncryptedEnvelope>;
|
|
107
|
+
/**
|
|
108
|
+
* Decrypt an encrypted envelope and parse the event inside it.
|
|
109
|
+
*
|
|
110
|
+
* Fails when the ciphertext or any header field of the envelope (protocol version, session id,
|
|
111
|
+
* sequence number, key id) is not what the sender encrypted. The header fields can therefore be
|
|
112
|
+
* trusted after this returns; whether a sequence number was seen before is for the caller to
|
|
113
|
+
* check.
|
|
114
|
+
*/
|
|
115
|
+
export declare function openEncryptedEnvelope<T>(key: CryptoKey, envelope: EnvelopeLike): Promise<T>;
|
|
63
116
|
/**
|
|
64
117
|
* Session encryption context for managing key state.
|
|
65
118
|
*/
|
|
@@ -79,33 +132,56 @@ export declare class SessionEncryptionContext {
|
|
|
79
132
|
needsRotation(): boolean;
|
|
80
133
|
/**
|
|
81
134
|
* Encrypt data and increment the nonce counter.
|
|
135
|
+
*
|
|
136
|
+
* @param additionalData - Optional additional authenticated data
|
|
82
137
|
*/
|
|
83
|
-
encrypt(plaintext: Uint8Array): Promise<{
|
|
138
|
+
encrypt(plaintext: Uint8Array, additionalData?: Uint8Array): Promise<{
|
|
84
139
|
ciphertext: Uint8Array;
|
|
85
140
|
nonce: Uint8Array;
|
|
86
141
|
}>;
|
|
87
142
|
/**
|
|
88
143
|
* Encrypt JSON data.
|
|
144
|
+
*
|
|
145
|
+
* @param additionalData - Optional additional authenticated data; the same bytes must be
|
|
146
|
+
* given to `decryptJson`
|
|
89
147
|
*/
|
|
90
|
-
encryptJson(data: unknown): Promise<EncryptedEnvelopePayload>;
|
|
148
|
+
encryptJson(data: unknown, additionalData?: Uint8Array): Promise<EncryptedEnvelopePayload>;
|
|
91
149
|
/**
|
|
92
150
|
* Create an encrypted envelope.
|
|
151
|
+
*
|
|
152
|
+
* The envelope's header (protocol version, session id, sequence number, key id) is
|
|
153
|
+
* authenticated together with the event: read the envelope with `openEnvelope`.
|
|
93
154
|
*/
|
|
94
155
|
createEnvelope(sessionId: SessionId, seq: number, innerEvent: unknown): Promise<EncryptedEnvelope>;
|
|
95
156
|
/**
|
|
96
|
-
* Decrypt
|
|
157
|
+
* Decrypt a payload made by `encrypt` or `encryptJson`.
|
|
158
|
+
* The payload of an envelope is read with `openEnvelope`.
|
|
159
|
+
*
|
|
160
|
+
* @param additionalData - The additional authenticated data given when encrypting, if any
|
|
161
|
+
*/
|
|
162
|
+
decrypt(payload: EncryptedEnvelopePayload, additionalData?: Uint8Array): Promise<Uint8Array>;
|
|
163
|
+
/**
|
|
164
|
+
* Decrypt and parse JSON from a payload made by `encryptJson`.
|
|
165
|
+
* The payload of an envelope is read with `openEnvelope`.
|
|
166
|
+
*
|
|
167
|
+
* @param additionalData - The additional authenticated data given when encrypting, if any
|
|
97
168
|
*/
|
|
98
|
-
|
|
169
|
+
decryptJson<T>(payload: EncryptedEnvelopePayload, additionalData?: Uint8Array): Promise<T>;
|
|
99
170
|
/**
|
|
100
|
-
* Decrypt and parse
|
|
171
|
+
* Decrypt an encrypted envelope and parse the event inside it.
|
|
172
|
+
*
|
|
173
|
+
* Fails when the ciphertext or any header field of the envelope (protocol version, session
|
|
174
|
+
* id, sequence number, key id) is not what the sender encrypted. Whether a sequence number
|
|
175
|
+
* was seen before is for the caller to check.
|
|
101
176
|
*/
|
|
102
|
-
|
|
177
|
+
openEnvelope<T>(envelope: EnvelopeLike): Promise<T>;
|
|
103
178
|
/**
|
|
104
179
|
* Get the current nonce counter value.
|
|
105
180
|
*/
|
|
106
181
|
getNonceCounter(): bigint;
|
|
107
182
|
/**
|
|
108
183
|
* Create session key info for serialization.
|
|
184
|
+
* The result holds the raw key bytes: treat it as the key itself.
|
|
109
185
|
*/
|
|
110
186
|
toKeyInfo(): SessionKeyInfo;
|
|
111
187
|
/**
|
package/crypto/ecdh.d.ts
CHANGED
|
@@ -54,6 +54,11 @@ export declare function createClientHello(keyPair: EcdhKeyPair): Promise<ClientH
|
|
|
54
54
|
export declare function createServerHello(keyPair: EcdhKeyPair, keyId: string): Promise<ServerHello>;
|
|
55
55
|
/**
|
|
56
56
|
* Process a client hello and generate server response.
|
|
57
|
+
*
|
|
58
|
+
* The exchange is not authenticated: nothing here proves who sent the hello, and the server
|
|
59
|
+
* hello carries no signature. It protects against a party that can only read the connection.
|
|
60
|
+
*
|
|
61
|
+
* @throws EcdhError when the hello names a version, curve or algorithm that is not implemented
|
|
57
62
|
*/
|
|
58
63
|
export declare function processClientHello(clientHello: ClientHello): Promise<{
|
|
59
64
|
serverKeyPair: EcdhKeyPair;
|
|
@@ -63,6 +68,12 @@ export declare function processClientHello(clientHello: ClientHello): Promise<{
|
|
|
63
68
|
}>;
|
|
64
69
|
/**
|
|
65
70
|
* Process a server hello and extract peer's public key.
|
|
71
|
+
*
|
|
72
|
+
* The exchange is not authenticated: `signatureB64` is neither created nor verified by this
|
|
73
|
+
* module, so the public key is only as trustworthy as the connection it arrived on.
|
|
74
|
+
*
|
|
75
|
+
* @throws EcdhError when the hello names a version, curve, algorithm or key derivation that is
|
|
76
|
+
* not implemented, or has no key id
|
|
66
77
|
*/
|
|
67
78
|
export declare function processServerHello(serverHello: ServerHello): Promise<{
|
|
68
79
|
peerPublicKey: CryptoKey;
|
package/crypto/index.d.ts
CHANGED
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @enclave-vm/stream - Crypto module
|
|
3
3
|
*
|
|
4
|
-
*
|
|
4
|
+
* Primitives for per-hop encryption: ECDH key exchange, HKDF key derivation and AES-GCM.
|
|
5
|
+
*
|
|
6
|
+
* Nothing in this repository wires them into a client or a broker. The key exchange is not
|
|
7
|
+
* authenticated; see the package README for what an application that uses them has to add.
|
|
5
8
|
*/
|
|
6
9
|
export { generateKeyPair, exportPublicKey, importPublicKey, deriveSharedSecret, createClientHello, createServerHello, processClientHello, processServerHello, EcdhError, } from './ecdh.js';
|
|
7
10
|
export type { EcdhKeyPair, SerializedPublicKey } from './ecdh.js';
|
|
8
11
|
export { deriveKey, deriveSessionKeys, importAesGcmKey, deriveSessionCryptoKeys, HkdfError } from './hkdf.js';
|
|
9
|
-
export { generateNonce, generateCounterNonce, toBase64, fromBase64, encrypt, decrypt, encryptJson, decryptJson, createEncryptedEnvelope, SessionEncryptionContext, AesGcmError, } from './aes-gcm.js';
|
|
12
|
+
export { generateNonce, generateCounterNonce, toBase64, fromBase64, encrypt, decrypt, encryptJson, decryptJson, createEncryptedEnvelope, openEncryptedEnvelope, encodeEnvelopeHeader, SessionEncryptionContext, AesGcmError, } from './aes-gcm.js';
|
|
13
|
+
export type { EnvelopeHeader, EnvelopeLike } from './aes-gcm.js';
|