@enclave-vm/stream 0.0.1 → 2.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@enclave-vm/stream",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.9.0",
|
|
4
4
|
"description": "Streaming protocol implementation for EnclaveJS runtime (NDJSON, encryption, reconnection)",
|
|
5
5
|
"author": "AgentFront <info@agentfront.dev>",
|
|
6
6
|
"homepage": "https://github.com/agentfront/enclave",
|
|
@@ -21,18 +21,19 @@
|
|
|
21
21
|
"bugs": {
|
|
22
22
|
"url": "https://github.com/agentfront/enclave/issues"
|
|
23
23
|
},
|
|
24
|
-
"main": "./
|
|
25
|
-
"
|
|
24
|
+
"main": "./index.js",
|
|
25
|
+
"module": "./esm/index.mjs",
|
|
26
|
+
"types": "./index.d.ts",
|
|
26
27
|
"exports": {
|
|
27
28
|
"./package.json": "./package.json",
|
|
28
29
|
".": {
|
|
29
|
-
"types": "./
|
|
30
|
-
"import": "./
|
|
31
|
-
"
|
|
30
|
+
"types": "./index.d.ts",
|
|
31
|
+
"import": "./esm/index.mjs",
|
|
32
|
+
"require": "./index.js",
|
|
33
|
+
"default": "./index.js"
|
|
32
34
|
}
|
|
33
35
|
},
|
|
34
36
|
"dependencies": {
|
|
35
|
-
"@enclave-vm/types": "
|
|
36
|
-
}
|
|
37
|
-
"type": "commonjs"
|
|
37
|
+
"@enclave-vm/types": "2.9.0"
|
|
38
|
+
}
|
|
38
39
|
}
|
package/src/crypto/aes-gcm.js
DELETED
|
@@ -1,293 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
/**
|
|
3
|
-
* @enclave-vm/stream - AES-GCM Encryption
|
|
4
|
-
*
|
|
5
|
-
* AES-GCM authenticated encryption using Web Crypto API.
|
|
6
|
-
*/
|
|
7
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
8
|
-
exports.SessionEncryptionContext = exports.AesGcmError = void 0;
|
|
9
|
-
exports.generateNonce = generateNonce;
|
|
10
|
-
exports.generateCounterNonce = generateCounterNonce;
|
|
11
|
-
exports.toBase64 = toBase64;
|
|
12
|
-
exports.fromBase64 = fromBase64;
|
|
13
|
-
exports.encrypt = encrypt;
|
|
14
|
-
exports.decrypt = decrypt;
|
|
15
|
-
exports.encryptJson = encryptJson;
|
|
16
|
-
exports.decryptJson = decryptJson;
|
|
17
|
-
exports.createEncryptedEnvelope = createEncryptedEnvelope;
|
|
18
|
-
const types_1 = require("@enclave-vm/types");
|
|
19
|
-
/**
|
|
20
|
-
* Convert a Uint8Array to an ArrayBuffer.
|
|
21
|
-
* Handles the case where the Uint8Array is a view into a larger buffer.
|
|
22
|
-
*/
|
|
23
|
-
function toArrayBuffer(arr) {
|
|
24
|
-
if (arr.byteOffset === 0 && arr.byteLength === arr.buffer.byteLength) {
|
|
25
|
-
return arr.buffer;
|
|
26
|
-
}
|
|
27
|
-
return arr.buffer.slice(arr.byteOffset, arr.byteOffset + arr.byteLength);
|
|
28
|
-
}
|
|
29
|
-
/**
|
|
30
|
-
* AES-GCM encryption error.
|
|
31
|
-
*/
|
|
32
|
-
class AesGcmError extends Error {
|
|
33
|
-
code;
|
|
34
|
-
constructor(message, code) {
|
|
35
|
-
super(message);
|
|
36
|
-
this.code = code;
|
|
37
|
-
this.name = 'AesGcmError';
|
|
38
|
-
}
|
|
39
|
-
}
|
|
40
|
-
exports.AesGcmError = AesGcmError;
|
|
41
|
-
/**
|
|
42
|
-
* Get the Web Crypto subtle API.
|
|
43
|
-
*/
|
|
44
|
-
function getSubtle() {
|
|
45
|
-
if (typeof globalThis.crypto?.subtle !== 'undefined') {
|
|
46
|
-
return globalThis.crypto.subtle;
|
|
47
|
-
}
|
|
48
|
-
throw new AesGcmError('Web Crypto API not available', types_1.EncryptionErrorCode.DecryptionFailed);
|
|
49
|
-
}
|
|
50
|
-
/**
|
|
51
|
-
* Generate a random nonce for AES-GCM.
|
|
52
|
-
*/
|
|
53
|
-
function generateNonce() {
|
|
54
|
-
const nonce = new Uint8Array(types_1.AES_GCM_NONCE_SIZE);
|
|
55
|
-
crypto.getRandomValues(nonce);
|
|
56
|
-
return nonce;
|
|
57
|
-
}
|
|
58
|
-
/**
|
|
59
|
-
* Generate a counter-based nonce for deterministic nonce generation.
|
|
60
|
-
* Uses 8 bytes of random prefix + 4 bytes of counter.
|
|
61
|
-
*/
|
|
62
|
-
function generateCounterNonce(prefix, counter) {
|
|
63
|
-
if (prefix.length !== 8) {
|
|
64
|
-
throw new AesGcmError('Nonce prefix must be 8 bytes', types_1.EncryptionErrorCode.NonceReuse);
|
|
65
|
-
}
|
|
66
|
-
const nonce = new Uint8Array(types_1.AES_GCM_NONCE_SIZE);
|
|
67
|
-
nonce.set(prefix);
|
|
68
|
-
// Write counter as big-endian 4 bytes
|
|
69
|
-
const counterValue = Number(counter & 0xffffffffn);
|
|
70
|
-
nonce[8] = (counterValue >> 24) & 0xff;
|
|
71
|
-
nonce[9] = (counterValue >> 16) & 0xff;
|
|
72
|
-
nonce[10] = (counterValue >> 8) & 0xff;
|
|
73
|
-
nonce[11] = counterValue & 0xff;
|
|
74
|
-
return nonce;
|
|
75
|
-
}
|
|
76
|
-
/**
|
|
77
|
-
* Encode bytes to base64.
|
|
78
|
-
*/
|
|
79
|
-
function toBase64(bytes) {
|
|
80
|
-
return btoa(String.fromCharCode(...bytes));
|
|
81
|
-
}
|
|
82
|
-
/**
|
|
83
|
-
* Decode base64 to bytes.
|
|
84
|
-
*/
|
|
85
|
-
function fromBase64(base64) {
|
|
86
|
-
return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
|
|
87
|
-
}
|
|
88
|
-
/**
|
|
89
|
-
* Encrypt data using AES-GCM.
|
|
90
|
-
*
|
|
91
|
-
* @param key - CryptoKey for AES-GCM
|
|
92
|
-
* @param plaintext - Data to encrypt
|
|
93
|
-
* @param nonce - 12-byte nonce/IV
|
|
94
|
-
* @param additionalData - Optional additional authenticated data (AAD)
|
|
95
|
-
* @returns Ciphertext with appended authentication tag
|
|
96
|
-
*/
|
|
97
|
-
async function encrypt(key, plaintext, nonce, additionalData) {
|
|
98
|
-
const subtle = getSubtle();
|
|
99
|
-
if (nonce.length !== types_1.AES_GCM_NONCE_SIZE) {
|
|
100
|
-
throw new AesGcmError(`Invalid nonce length: expected ${types_1.AES_GCM_NONCE_SIZE}, got ${nonce.length}`, types_1.EncryptionErrorCode.DecryptionFailed);
|
|
101
|
-
}
|
|
102
|
-
try {
|
|
103
|
-
const ciphertext = await subtle.encrypt({
|
|
104
|
-
name: 'AES-GCM',
|
|
105
|
-
iv: toArrayBuffer(nonce),
|
|
106
|
-
tagLength: types_1.AES_GCM_TAG_SIZE * 8, // bits
|
|
107
|
-
additionalData: additionalData ? toArrayBuffer(additionalData) : undefined,
|
|
108
|
-
}, key, toArrayBuffer(plaintext));
|
|
109
|
-
return new Uint8Array(ciphertext);
|
|
110
|
-
}
|
|
111
|
-
catch (err) {
|
|
112
|
-
throw new AesGcmError(`Encryption failed: ${err instanceof Error ? err.message : String(err)}`, types_1.EncryptionErrorCode.DecryptionFailed);
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
/**
|
|
116
|
-
* Decrypt data using AES-GCM.
|
|
117
|
-
*
|
|
118
|
-
* @param key - CryptoKey for AES-GCM
|
|
119
|
-
* @param ciphertext - Data to decrypt (with authentication tag)
|
|
120
|
-
* @param nonce - 12-byte nonce/IV used during encryption
|
|
121
|
-
* @param additionalData - Optional additional authenticated data (AAD)
|
|
122
|
-
* @returns Decrypted plaintext
|
|
123
|
-
*/
|
|
124
|
-
async function decrypt(key, ciphertext, nonce, additionalData) {
|
|
125
|
-
const subtle = getSubtle();
|
|
126
|
-
if (nonce.length !== types_1.AES_GCM_NONCE_SIZE) {
|
|
127
|
-
throw new AesGcmError(`Invalid nonce length: expected ${types_1.AES_GCM_NONCE_SIZE}, got ${nonce.length}`, types_1.EncryptionErrorCode.DecryptionFailed);
|
|
128
|
-
}
|
|
129
|
-
try {
|
|
130
|
-
const plaintext = await subtle.decrypt({
|
|
131
|
-
name: 'AES-GCM',
|
|
132
|
-
iv: toArrayBuffer(nonce),
|
|
133
|
-
tagLength: types_1.AES_GCM_TAG_SIZE * 8, // bits
|
|
134
|
-
additionalData: additionalData ? toArrayBuffer(additionalData) : undefined,
|
|
135
|
-
}, key, toArrayBuffer(ciphertext));
|
|
136
|
-
return new Uint8Array(plaintext);
|
|
137
|
-
}
|
|
138
|
-
catch (err) {
|
|
139
|
-
throw new AesGcmError(`Decryption failed: ${err instanceof Error ? err.message : String(err)}`, types_1.EncryptionErrorCode.DecryptionFailed);
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
/**
|
|
143
|
-
* Encrypt a JSON object and create an encrypted envelope payload.
|
|
144
|
-
*/
|
|
145
|
-
async function encryptJson(key, keyId, data, nonce) {
|
|
146
|
-
const actualNonce = nonce ?? generateNonce();
|
|
147
|
-
const plaintext = new TextEncoder().encode(JSON.stringify(data));
|
|
148
|
-
const ciphertext = await encrypt(key, plaintext, actualNonce);
|
|
149
|
-
return {
|
|
150
|
-
kid: keyId,
|
|
151
|
-
nonceB64: toBase64(actualNonce),
|
|
152
|
-
ciphertextB64: toBase64(ciphertext),
|
|
153
|
-
};
|
|
154
|
-
}
|
|
155
|
-
/**
|
|
156
|
-
* Decrypt an encrypted envelope payload and parse as JSON.
|
|
157
|
-
*/
|
|
158
|
-
async function decryptJson(key, payload) {
|
|
159
|
-
const nonce = fromBase64(payload.nonceB64);
|
|
160
|
-
const ciphertext = fromBase64(payload.ciphertextB64);
|
|
161
|
-
const plaintext = await decrypt(key, ciphertext, nonce);
|
|
162
|
-
const json = new TextDecoder().decode(plaintext);
|
|
163
|
-
return JSON.parse(json);
|
|
164
|
-
}
|
|
165
|
-
/**
|
|
166
|
-
* Create an encrypted envelope from an event.
|
|
167
|
-
*/
|
|
168
|
-
async function createEncryptedEnvelope(key, keyId, sessionId, seq, innerEvent, nonce) {
|
|
169
|
-
const payload = await encryptJson(key, keyId, innerEvent, nonce);
|
|
170
|
-
return {
|
|
171
|
-
protocolVersion: types_1.PROTOCOL_VERSION,
|
|
172
|
-
sessionId,
|
|
173
|
-
seq,
|
|
174
|
-
type: types_1.EventType.Encrypted,
|
|
175
|
-
payload,
|
|
176
|
-
};
|
|
177
|
-
}
|
|
178
|
-
/**
|
|
179
|
-
* Session encryption context for managing key state.
|
|
180
|
-
*/
|
|
181
|
-
class SessionEncryptionContext {
|
|
182
|
-
key;
|
|
183
|
-
keyInfo;
|
|
184
|
-
nonceCounter;
|
|
185
|
-
noncePrefix;
|
|
186
|
-
constructor(key, keyInfo) {
|
|
187
|
-
this.key = key;
|
|
188
|
-
this.keyInfo = keyInfo;
|
|
189
|
-
this.nonceCounter = keyInfo.nonceCounter;
|
|
190
|
-
this.noncePrefix = crypto.getRandomValues(new Uint8Array(8));
|
|
191
|
-
}
|
|
192
|
-
/**
|
|
193
|
-
* Get the key ID.
|
|
194
|
-
*/
|
|
195
|
-
get keyId() {
|
|
196
|
-
return this.keyInfo.keyId;
|
|
197
|
-
}
|
|
198
|
-
/**
|
|
199
|
-
* Check if the key needs rotation.
|
|
200
|
-
*/
|
|
201
|
-
needsRotation() {
|
|
202
|
-
return this.nonceCounter >= this.keyInfo.maxNonces;
|
|
203
|
-
}
|
|
204
|
-
/**
|
|
205
|
-
* Encrypt data and increment the nonce counter.
|
|
206
|
-
*/
|
|
207
|
-
async encrypt(plaintext) {
|
|
208
|
-
if (this.needsRotation()) {
|
|
209
|
-
throw new AesGcmError('Key needs rotation: nonce limit reached', types_1.EncryptionErrorCode.KeyExpired);
|
|
210
|
-
}
|
|
211
|
-
const nonce = generateCounterNonce(this.noncePrefix, this.nonceCounter);
|
|
212
|
-
this.nonceCounter++;
|
|
213
|
-
const ciphertext = await encrypt(this.key, plaintext, nonce);
|
|
214
|
-
return { ciphertext, nonce };
|
|
215
|
-
}
|
|
216
|
-
/**
|
|
217
|
-
* Encrypt JSON data.
|
|
218
|
-
*/
|
|
219
|
-
async encryptJson(data) {
|
|
220
|
-
const plaintext = new TextEncoder().encode(JSON.stringify(data));
|
|
221
|
-
const { ciphertext, nonce } = await this.encrypt(plaintext);
|
|
222
|
-
return {
|
|
223
|
-
kid: this.keyId,
|
|
224
|
-
nonceB64: toBase64(nonce),
|
|
225
|
-
ciphertextB64: toBase64(ciphertext),
|
|
226
|
-
};
|
|
227
|
-
}
|
|
228
|
-
/**
|
|
229
|
-
* Create an encrypted envelope.
|
|
230
|
-
*/
|
|
231
|
-
async createEnvelope(sessionId, seq, innerEvent) {
|
|
232
|
-
const payload = await this.encryptJson(innerEvent);
|
|
233
|
-
return {
|
|
234
|
-
protocolVersion: types_1.PROTOCOL_VERSION,
|
|
235
|
-
sessionId,
|
|
236
|
-
seq,
|
|
237
|
-
type: types_1.EventType.Encrypted,
|
|
238
|
-
payload,
|
|
239
|
-
};
|
|
240
|
-
}
|
|
241
|
-
/**
|
|
242
|
-
* Decrypt an encrypted envelope payload.
|
|
243
|
-
*/
|
|
244
|
-
async decrypt(payload) {
|
|
245
|
-
const nonce = fromBase64(payload.nonceB64);
|
|
246
|
-
const ciphertext = fromBase64(payload.ciphertextB64);
|
|
247
|
-
return decrypt(this.key, ciphertext, nonce);
|
|
248
|
-
}
|
|
249
|
-
/**
|
|
250
|
-
* Decrypt and parse JSON from an encrypted envelope payload.
|
|
251
|
-
*/
|
|
252
|
-
async decryptJson(payload) {
|
|
253
|
-
const plaintext = await this.decrypt(payload);
|
|
254
|
-
const json = new TextDecoder().decode(plaintext);
|
|
255
|
-
return JSON.parse(json);
|
|
256
|
-
}
|
|
257
|
-
/**
|
|
258
|
-
* Get the current nonce counter value.
|
|
259
|
-
*/
|
|
260
|
-
getNonceCounter() {
|
|
261
|
-
return this.nonceCounter;
|
|
262
|
-
}
|
|
263
|
-
/**
|
|
264
|
-
* Create session key info for serialization.
|
|
265
|
-
*/
|
|
266
|
-
toKeyInfo() {
|
|
267
|
-
return {
|
|
268
|
-
...this.keyInfo,
|
|
269
|
-
nonceCounter: this.nonceCounter,
|
|
270
|
-
};
|
|
271
|
-
}
|
|
272
|
-
/**
|
|
273
|
-
* Create a new encryption context from raw key bytes.
|
|
274
|
-
*/
|
|
275
|
-
static async fromKeyBytes(keyBytes, keyId) {
|
|
276
|
-
const subtle = getSubtle();
|
|
277
|
-
const key = await subtle.importKey('raw', toArrayBuffer(keyBytes), {
|
|
278
|
-
name: 'AES-GCM',
|
|
279
|
-
length: keyBytes.length * 8,
|
|
280
|
-
}, false, ['encrypt', 'decrypt']);
|
|
281
|
-
const keyInfo = {
|
|
282
|
-
keyId,
|
|
283
|
-
algorithm: types_1.EncryptionAlgorithm.AES_GCM_256,
|
|
284
|
-
keyBytes,
|
|
285
|
-
nonceCounter: 0n,
|
|
286
|
-
maxNonces: types_1.MAX_MESSAGES_PER_KEY,
|
|
287
|
-
createdAt: Date.now(),
|
|
288
|
-
};
|
|
289
|
-
return new SessionEncryptionContext(key, keyInfo);
|
|
290
|
-
}
|
|
291
|
-
}
|
|
292
|
-
exports.SessionEncryptionContext = SessionEncryptionContext;
|
|
293
|
-
//# sourceMappingURL=aes-gcm.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"aes-gcm.js","sourceRoot":"","sources":["../../../src/crypto/aes-gcm.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;;AAqDH,sCAIC;AAMD,oDAgBC;AAKD,4BAEC;AAKD,gCAEC;AAWD,0BAkCC;AAWD,0BAkCC;AAKD,kCAgBC;AAKD,kCAQC;AAKD,0DAiBC;AA7OD,6CAY2B;AAE3B;;;GAGG;AACH,SAAS,aAAa,CAAC,GAAe;IACpC,IAAI,GAAG,CAAC,UAAU,KAAK,CAAC,IAAI,GAAG,CAAC,UAAU,KAAK,GAAG,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC;QACrE,OAAO,GAAG,CAAC,MAAqB,CAAC;IACnC,CAAC;IACD,OAAO,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,CAAgB,CAAC;AAC1F,CAAC;AAED;;GAEG;AACH,MAAa,WAAY,SAAQ,KAAK;IAGlB;IAFlB,YACE,OAAe,EACC,IAAY;QAE5B,KAAK,CAAC,OAAO,CAAC,CAAC;QAFC,SAAI,GAAJ,IAAI,CAAQ;QAG5B,IAAI,CAAC,IAAI,GAAG,aAAa,CAAC;IAC5B,CAAC;CACF;AARD,kCAQC;AAED;;GAEG;AACH,SAAS,SAAS;IAChB,IAAI,OAAO,UAAU,CAAC,MAAM,EAAE,MAAM,KAAK,WAAW,EAAE,CAAC;QACrD,OAAO,UAAU,CAAC,MAAM,CAAC,MAAM,CAAC;IAClC,CAAC;IACD,MAAM,I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,QAAQ;YACR,YAAY,EAAE,EAAE;YAChB,SAAS,EAAE,4BAAoB;YAC/B,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;SACtB,CAAC;QAEF,OAAO,IAAI,wBAAwB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;IACpD,CAAC;CACF;AA3ID,4DA2IC","sourcesContent":["/**\n * @enclave-vm/stream - AES-GCM Encryption\n *\n * AES-GCM authenticated encryption using Web Crypto API.\n */\n\nimport {\n AES_GCM_NONCE_SIZE,\n AES_GCM_TAG_SIZE,\n MAX_MESSAGES_PER_KEY,\n EncryptionErrorCode,\n type EncryptedEnvelopePayload,\n type SessionKeyInfo,\n PROTOCOL_VERSION,\n EventType,\n type EncryptedEnvelope,\n type SessionId,\n EncryptionAlgorithm,\n} from '@enclave-vm/types';\n\n/**\n * Convert a Uint8Array to an ArrayBuffer.\n * Handles the case where the Uint8Array is a view into a larger buffer.\n */\nfunction toArrayBuffer(arr: Uint8Array): ArrayBuffer {\n if (arr.byteOffset === 0 && arr.byteLength === arr.buffer.byteLength) {\n return arr.buffer as ArrayBuffer;\n }\n return arr.buffer.slice(arr.byteOffset, arr.byteOffset + arr.byteLength) as ArrayBuffer;\n}\n\n/**\n * AES-GCM encryption error.\n */\nexport class AesGcmError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n ) {\n super(message);\n this.name = 'AesGcmError';\n }\n}\n\n/**\n * Get the Web Crypto subtle API.\n */\nfunction getSubtle(): SubtleCrypto {\n if (typeof globalThis.crypto?.subtle !== 'undefined') {\n return globalThis.crypto.subtle;\n }\n throw new AesGcmError('Web Crypto API not available', EncryptionErrorCode.DecryptionFailed);\n}\n\n/**\n * Generate a random nonce for AES-GCM.\n */\nexport function generateNonce(): Uint8Array {\n const nonce = new Uint8Array(AES_GCM_NONCE_SIZE);\n crypto.getRandomValues(nonce);\n return nonce;\n}\n\n/**\n * Generate a counter-based nonce for deterministic nonce generation.\n * Uses 8 bytes of random prefix + 4 bytes of counter.\n */\nexport function generateCounterNonce(prefix: Uint8Array, counter: bigint): Uint8Array {\n if (prefix.length !== 8) {\n throw new AesGcmError('Nonce prefix must be 8 bytes', EncryptionErrorCode.NonceReuse);\n }\n\n const nonce = new Uint8Array(AES_GCM_NONCE_SIZE);\n nonce.set(prefix);\n\n // Write counter as big-endian 4 bytes\n const counterValue = Number(counter & 0xffffffffn);\n nonce[8] = (counterValue >> 24) & 0xff;\n nonce[9] = (counterValue >> 16) & 0xff;\n nonce[10] = (counterValue >> 8) & 0xff;\n nonce[11] = counterValue & 0xff;\n\n return nonce;\n}\n\n/**\n * Encode bytes to base64.\n */\nexport function toBase64(bytes: Uint8Array): string {\n return btoa(String.fromCharCode(...bytes));\n}\n\n/**\n * Decode base64 to bytes.\n */\nexport function fromBase64(base64: string): Uint8Array {\n return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));\n}\n\n/**\n * Encrypt data using AES-GCM.\n *\n * @param key - CryptoKey for AES-GCM\n * @param plaintext - Data to encrypt\n * @param nonce - 12-byte nonce/IV\n * @param additionalData - Optional additional authenticated data (AAD)\n * @returns Ciphertext with appended authentication tag\n */\nexport async function encrypt(\n key: CryptoKey,\n plaintext: Uint8Array,\n nonce: Uint8Array,\n additionalData?: Uint8Array,\n): Promise<Uint8Array> {\n const subtle = getSubtle();\n\n if (nonce.length !== AES_GCM_NONCE_SIZE) {\n throw new AesGcmError(\n `Invalid nonce length: expected ${AES_GCM_NONCE_SIZE}, got ${nonce.length}`,\n EncryptionErrorCode.DecryptionFailed,\n );\n }\n\n try {\n const ciphertext = await subtle.encrypt(\n {\n name: 'AES-GCM',\n iv: toArrayBuffer(nonce),\n tagLength: AES_GCM_TAG_SIZE * 8, // bits\n additionalData: additionalData ? toArrayBuffer(additionalData) : undefined,\n },\n key,\n toArrayBuffer(plaintext),\n );\n\n return new Uint8Array(ciphertext);\n } catch (err) {\n throw new AesGcmError(\n `Encryption failed: ${err instanceof Error ? err.message : String(err)}`,\n EncryptionErrorCode.DecryptionFailed,\n );\n }\n}\n\n/**\n * Decrypt data using AES-GCM.\n *\n * @param key - CryptoKey for AES-GCM\n * @param ciphertext - Data to decrypt (with authentication tag)\n * @param nonce - 12-byte nonce/IV used during encryption\n * @param additionalData - Optional additional authenticated data (AAD)\n * @returns Decrypted plaintext\n */\nexport async function decrypt(\n key: CryptoKey,\n ciphertext: Uint8Array,\n nonce: Uint8Array,\n additionalData?: Uint8Array,\n): Promise<Uint8Array> {\n const subtle = getSubtle();\n\n if (nonce.length !== AES_GCM_NONCE_SIZE) {\n throw new AesGcmError(\n `Invalid nonce length: expected ${AES_GCM_NONCE_SIZE}, got ${nonce.length}`,\n EncryptionErrorCode.DecryptionFailed,\n );\n }\n\n try {\n const plaintext = await subtle.decrypt(\n {\n name: 'AES-GCM',\n iv: toArrayBuffer(nonce),\n tagLength: AES_GCM_TAG_SIZE * 8, // bits\n additionalData: additionalData ? toArrayBuffer(additionalData) : undefined,\n },\n key,\n toArrayBuffer(ciphertext),\n );\n\n return new Uint8Array(plaintext);\n } catch (err) {\n throw new AesGcmError(\n `Decryption failed: ${err instanceof Error ? err.message : String(err)}`,\n EncryptionErrorCode.DecryptionFailed,\n );\n }\n}\n\n/**\n * Encrypt a JSON object and create an encrypted envelope payload.\n */\nexport async function encryptJson(\n key: CryptoKey,\n keyId: string,\n data: unknown,\n nonce?: Uint8Array,\n): Promise<EncryptedEnvelopePayload> {\n const actualNonce = nonce ?? generateNonce();\n const plaintext = new TextEncoder().encode(JSON.stringify(data));\n\n const ciphertext = await encrypt(key, plaintext, actualNonce);\n\n return {\n kid: keyId,\n nonceB64: toBase64(actualNonce),\n ciphertextB64: toBase64(ciphertext),\n };\n}\n\n/**\n * Decrypt an encrypted envelope payload and parse as JSON.\n */\nexport async function decryptJson<T>(key: CryptoKey, payload: EncryptedEnvelopePayload): Promise<T> {\n const nonce = fromBase64(payload.nonceB64);\n const ciphertext = fromBase64(payload.ciphertextB64);\n\n const plaintext = await decrypt(key, ciphertext, nonce);\n const json = new TextDecoder().decode(plaintext);\n\n return JSON.parse(json) as T;\n}\n\n/**\n * Create an encrypted envelope from an event.\n */\nexport async function createEncryptedEnvelope(\n key: CryptoKey,\n keyId: string,\n sessionId: SessionId,\n seq: number,\n innerEvent: unknown,\n nonce?: Uint8Array,\n): Promise<EncryptedEnvelope> {\n const payload = await encryptJson(key, keyId, innerEvent, nonce);\n\n return {\n protocolVersion: PROTOCOL_VERSION,\n sessionId,\n seq,\n type: EventType.Encrypted,\n payload,\n };\n}\n\n/**\n * Session encryption context for managing key state.\n */\nexport class SessionEncryptionContext {\n private readonly key: CryptoKey;\n private readonly keyInfo: SessionKeyInfo;\n private nonceCounter: bigint;\n private readonly noncePrefix: Uint8Array;\n\n constructor(key: CryptoKey, keyInfo: SessionKeyInfo) {\n this.key = key;\n this.keyInfo = keyInfo;\n this.nonceCounter = keyInfo.nonceCounter;\n this.noncePrefix = crypto.getRandomValues(new Uint8Array(8));\n }\n\n /**\n * Get the key ID.\n */\n get keyId(): string {\n return this.keyInfo.keyId;\n }\n\n /**\n * Check if the key needs rotation.\n */\n needsRotation(): boolean {\n return this.nonceCounter >= this.keyInfo.maxNonces;\n }\n\n /**\n * Encrypt data and increment the nonce counter.\n */\n async encrypt(plaintext: Uint8Array): Promise<{\n ciphertext: Uint8Array;\n nonce: Uint8Array;\n }> {\n if (this.needsRotation()) {\n throw new AesGcmError('Key needs rotation: nonce limit reached', EncryptionErrorCode.KeyExpired);\n }\n\n const nonce = generateCounterNonce(this.noncePrefix, this.nonceCounter);\n this.nonceCounter++;\n\n const ciphertext = await encrypt(this.key, plaintext, nonce);\n\n return { ciphertext, nonce };\n }\n\n /**\n * Encrypt JSON data.\n */\n async encryptJson(data: unknown): Promise<EncryptedEnvelopePayload> {\n const plaintext = new TextEncoder().encode(JSON.stringify(data));\n const { ciphertext, nonce } = await this.encrypt(plaintext);\n\n return {\n kid: this.keyId,\n nonceB64: toBase64(nonce),\n ciphertextB64: toBase64(ciphertext),\n };\n }\n\n /**\n * Create an encrypted envelope.\n */\n async createEnvelope(sessionId: SessionId, seq: number, innerEvent: unknown): Promise<EncryptedEnvelope> {\n const payload = await this.encryptJson(innerEvent);\n\n return {\n protocolVersion: PROTOCOL_VERSION,\n sessionId,\n seq,\n type: EventType.Encrypted,\n payload,\n };\n }\n\n /**\n * Decrypt an encrypted envelope payload.\n */\n async decrypt(payload: EncryptedEnvelopePayload): Promise<Uint8Array> {\n const nonce = fromBase64(payload.nonceB64);\n const ciphertext = fromBase64(payload.ciphertextB64);\n\n return decrypt(this.key, ciphertext, nonce);\n }\n\n /**\n * Decrypt and parse JSON from an encrypted envelope payload.\n */\n async decryptJson<T>(payload: EncryptedEnvelopePayload): Promise<T> {\n const plaintext = await this.decrypt(payload);\n const json = new TextDecoder().decode(plaintext);\n return JSON.parse(json) as T;\n }\n\n /**\n * Get the current nonce counter value.\n */\n getNonceCounter(): bigint {\n return this.nonceCounter;\n }\n\n /**\n * Create session key info for serialization.\n */\n toKeyInfo(): SessionKeyInfo {\n return {\n ...this.keyInfo,\n nonceCounter: this.nonceCounter,\n };\n }\n\n /**\n * Create a new encryption context from raw key bytes.\n */\n static async fromKeyBytes(keyBytes: Uint8Array, keyId: string): Promise<SessionEncryptionContext> {\n const subtle = getSubtle();\n\n const key = await subtle.importKey(\n 'raw',\n toArrayBuffer(keyBytes),\n {\n name: 'AES-GCM',\n length: keyBytes.length * 8,\n },\n false,\n ['encrypt', 'decrypt'],\n );\n\n const keyInfo: SessionKeyInfo = {\n keyId,\n algorithm: EncryptionAlgorithm.AES_GCM_256,\n keyBytes,\n nonceCounter: 0n,\n maxNonces: MAX_MESSAGES_PER_KEY,\n createdAt: Date.now(),\n };\n\n return new SessionEncryptionContext(key, keyInfo);\n }\n}\n"]}
|
package/src/crypto/ecdh.js
DELETED
|
@@ -1,166 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
/**
|
|
3
|
-
* @enclave-vm/stream - ECDH Key Exchange
|
|
4
|
-
*
|
|
5
|
-
* Elliptic Curve Diffie-Hellman key exchange using Web Crypto API.
|
|
6
|
-
* Uses P-256 curve for broad browser compatibility.
|
|
7
|
-
*/
|
|
8
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
-
exports.EcdhError = void 0;
|
|
10
|
-
exports.generateKeyPair = generateKeyPair;
|
|
11
|
-
exports.exportPublicKey = exportPublicKey;
|
|
12
|
-
exports.importPublicKey = importPublicKey;
|
|
13
|
-
exports.deriveSharedSecret = deriveSharedSecret;
|
|
14
|
-
exports.createClientHello = createClientHello;
|
|
15
|
-
exports.createServerHello = createServerHello;
|
|
16
|
-
exports.processClientHello = processClientHello;
|
|
17
|
-
exports.processServerHello = processServerHello;
|
|
18
|
-
const types_1 = require("@enclave-vm/types");
|
|
19
|
-
/**
|
|
20
|
-
* ECDH encryption error.
|
|
21
|
-
*/
|
|
22
|
-
class EcdhError extends Error {
|
|
23
|
-
code;
|
|
24
|
-
constructor(message, code) {
|
|
25
|
-
super(message);
|
|
26
|
-
this.code = code;
|
|
27
|
-
this.name = 'EcdhError';
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
exports.EcdhError = EcdhError;
|
|
31
|
-
/**
|
|
32
|
-
* Get the Web Crypto subtle API.
|
|
33
|
-
* Works in both browser and Node.js 20+.
|
|
34
|
-
*/
|
|
35
|
-
function getSubtle() {
|
|
36
|
-
if (typeof globalThis.crypto?.subtle !== 'undefined') {
|
|
37
|
-
return globalThis.crypto.subtle;
|
|
38
|
-
}
|
|
39
|
-
throw new EcdhError('Web Crypto API not available', types_1.EncryptionErrorCode.HandshakeFailed);
|
|
40
|
-
}
|
|
41
|
-
/**
|
|
42
|
-
* Generate an ephemeral ECDH key pair.
|
|
43
|
-
*/
|
|
44
|
-
async function generateKeyPair(curve = types_1.SupportedCurve.P256) {
|
|
45
|
-
const subtle = getSubtle();
|
|
46
|
-
try {
|
|
47
|
-
const keyPair = await subtle.generateKey({
|
|
48
|
-
name: 'ECDH',
|
|
49
|
-
namedCurve: curve,
|
|
50
|
-
}, true, // extractable for export
|
|
51
|
-
['deriveBits']);
|
|
52
|
-
return {
|
|
53
|
-
publicKey: keyPair.publicKey,
|
|
54
|
-
privateKey: keyPair.privateKey,
|
|
55
|
-
};
|
|
56
|
-
}
|
|
57
|
-
catch (err) {
|
|
58
|
-
throw new EcdhError(`Failed to generate key pair: ${err instanceof Error ? err.message : String(err)}`, types_1.EncryptionErrorCode.HandshakeFailed);
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
/**
|
|
62
|
-
* Export a public key to base64 format.
|
|
63
|
-
*/
|
|
64
|
-
async function exportPublicKey(publicKey) {
|
|
65
|
-
const subtle = getSubtle();
|
|
66
|
-
try {
|
|
67
|
-
const rawKey = await subtle.exportKey('raw', publicKey);
|
|
68
|
-
const publicKeyB64 = btoa(String.fromCharCode(...new Uint8Array(rawKey)));
|
|
69
|
-
// Extract curve from key algorithm
|
|
70
|
-
const algorithm = publicKey.algorithm;
|
|
71
|
-
const curve = algorithm.namedCurve;
|
|
72
|
-
return { publicKeyB64, curve };
|
|
73
|
-
}
|
|
74
|
-
catch (err) {
|
|
75
|
-
throw new EcdhError(`Failed to export public key: ${err instanceof Error ? err.message : String(err)}`, types_1.EncryptionErrorCode.InvalidPublicKey);
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
/**
|
|
79
|
-
* Import a public key from base64 format.
|
|
80
|
-
*/
|
|
81
|
-
async function importPublicKey(publicKeyB64, curve = types_1.SupportedCurve.P256) {
|
|
82
|
-
const subtle = getSubtle();
|
|
83
|
-
try {
|
|
84
|
-
const rawKey = Uint8Array.from(atob(publicKeyB64), (c) => c.charCodeAt(0));
|
|
85
|
-
return await subtle.importKey('raw', rawKey, {
|
|
86
|
-
name: 'ECDH',
|
|
87
|
-
namedCurve: curve,
|
|
88
|
-
}, true, []);
|
|
89
|
-
}
|
|
90
|
-
catch (err) {
|
|
91
|
-
throw new EcdhError(`Failed to import public key: ${err instanceof Error ? err.message : String(err)}`, types_1.EncryptionErrorCode.InvalidPublicKey);
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
/**
|
|
95
|
-
* Derive shared secret from private key and peer's public key.
|
|
96
|
-
*/
|
|
97
|
-
async function deriveSharedSecret(privateKey, peerPublicKey) {
|
|
98
|
-
const subtle = getSubtle();
|
|
99
|
-
try {
|
|
100
|
-
// Derive 256 bits (32 bytes) of shared secret
|
|
101
|
-
const sharedBits = await subtle.deriveBits({
|
|
102
|
-
name: 'ECDH',
|
|
103
|
-
public: peerPublicKey,
|
|
104
|
-
}, privateKey, 256);
|
|
105
|
-
return new Uint8Array(sharedBits);
|
|
106
|
-
}
|
|
107
|
-
catch (err) {
|
|
108
|
-
throw new EcdhError(`Failed to derive shared secret: ${err instanceof Error ? err.message : String(err)}`, types_1.EncryptionErrorCode.KeyDerivationFailed);
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
/**
|
|
112
|
-
* Create a client hello message for the encryption handshake.
|
|
113
|
-
*/
|
|
114
|
-
async function createClientHello(keyPair) {
|
|
115
|
-
const { publicKeyB64, curve } = await exportPublicKey(keyPair.publicKey);
|
|
116
|
-
return {
|
|
117
|
-
protocolVersion: types_1.PROTOCOL_VERSION,
|
|
118
|
-
clientEphemeralPubKeyB64: publicKeyB64,
|
|
119
|
-
curve,
|
|
120
|
-
supportedAlgorithms: [types_1.EncryptionAlgorithm.AES_GCM_256],
|
|
121
|
-
};
|
|
122
|
-
}
|
|
123
|
-
/**
|
|
124
|
-
* Create a server hello message for the encryption handshake.
|
|
125
|
-
*/
|
|
126
|
-
async function createServerHello(keyPair, keyId) {
|
|
127
|
-
const { publicKeyB64, curve } = await exportPublicKey(keyPair.publicKey);
|
|
128
|
-
return {
|
|
129
|
-
protocolVersion: types_1.PROTOCOL_VERSION,
|
|
130
|
-
serverEphemeralPubKeyB64: publicKeyB64,
|
|
131
|
-
curve,
|
|
132
|
-
selectedAlgorithm: types_1.EncryptionAlgorithm.AES_GCM_256,
|
|
133
|
-
kdf: types_1.KeyDerivation.HKDF_SHA256,
|
|
134
|
-
keyId,
|
|
135
|
-
};
|
|
136
|
-
}
|
|
137
|
-
/**
|
|
138
|
-
* Process a client hello and generate server response.
|
|
139
|
-
*/
|
|
140
|
-
async function processClientHello(clientHello) {
|
|
141
|
-
// Generate server's ephemeral key pair
|
|
142
|
-
const serverKeyPair = await generateKeyPair(clientHello.curve);
|
|
143
|
-
// Import client's public key
|
|
144
|
-
const peerPublicKey = await importPublicKey(clientHello.clientEphemeralPubKeyB64, clientHello.curve);
|
|
145
|
-
// Generate a key ID
|
|
146
|
-
const keyId = `k_${crypto.randomUUID()}`;
|
|
147
|
-
// Create server hello
|
|
148
|
-
const serverHello = await createServerHello(serverKeyPair, keyId);
|
|
149
|
-
return {
|
|
150
|
-
serverKeyPair,
|
|
151
|
-
peerPublicKey,
|
|
152
|
-
serverHello,
|
|
153
|
-
keyId,
|
|
154
|
-
};
|
|
155
|
-
}
|
|
156
|
-
/**
|
|
157
|
-
* Process a server hello and extract peer's public key.
|
|
158
|
-
*/
|
|
159
|
-
async function processServerHello(serverHello) {
|
|
160
|
-
const peerPublicKey = await importPublicKey(serverHello.serverEphemeralPubKeyB64, serverHello.curve);
|
|
161
|
-
return {
|
|
162
|
-
peerPublicKey,
|
|
163
|
-
keyId: serverHello.keyId,
|
|
164
|
-
};
|
|
165
|
-
}
|
|
166
|
-
//# sourceMappingURL=ecdh.js.map
|
package/src/crypto/ecdh.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ecdh.js","sourceRoot":"","sources":["../../../src/crypto/ecdh.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAyDH,0CAuBC;AAKD,0CAkBC;AAKD,0CAyBC;AAKD,gDAqBC;AAKD,8CASC;AAKD,8CAWC;AAKD,gDAwBC;AAKD,gDAUC;AAvOD,6CAQ2B;AAoB3B;;GAEG;AACH,MAAa,SAAU,SAAQ,KAAK;IAGhB;IA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ED;;GAEG;AACI,KAAK,UAAU,kBAAkB,CAAC,WAAwB;IAM/D,uCAAuC;IACvC,MAAM,aAAa,GAAG,MAAM,eAAe,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;IAE/D,6BAA6B;IAC7B,MAAM,aAAa,GAAG,MAAM,eAAe,CAAC,WAAW,CAAC,wBAAwB,EAAE,WAAW,CAAC,KAAK,CAAC,CAAC;IAErG,oBAAoB;IACpB,MAAM,KAAK,GAAG,KAAK,MAAM,CAAC,UAAU,EAAE,EAAE,CAAC;IAEzC,sBAAsB;IACtB,MAAM,WAAW,GAAG,MAAM,iBAAiB,CAAC,aAAa,EAAE,KAAK,CAAC,CAAC;IAElE,OAAO;QACL,aAAa;QACb,aAAa;QACb,WAAW;QACX,KAAK;KACN,CAAC;AACJ,CAAC;AAED;;GAEG;AACI,KAAK,UAAU,kBAAkB,CAAC,WAAwB;IAI/D,MAAM,aAAa,GAAG,MAAM,eAAe,CAAC,WAAW,CAAC,wBAAwB,EAAE,WAAW,CAAC,KAAK,CAAC,CAAC;IAErG,OAAO;QACL,aAAa;QACb,KAAK,EAAE,WAAW,CAAC,KAAK;KACzB,CAAC;AACJ,CAAC","sourcesContent":["/**\n * @enclave-vm/stream - ECDH Key Exchange\n *\n * Elliptic Curve Diffie-Hellman key exchange using Web Crypto API.\n * Uses P-256 curve for broad browser compatibility.\n */\n\nimport {\n SupportedCurve,\n EncryptionErrorCode,\n type ClientHello,\n type ServerHello,\n PROTOCOL_VERSION,\n EncryptionAlgorithm,\n KeyDerivation,\n} from '@enclave-vm/types';\n\n/**\n * ECDH key pair.\n */\nexport interface EcdhKeyPair {\n publicKey: CryptoKey;\n privateKey: CryptoKey;\n}\n\n/**\n * Serialized ECDH public key.\n */\nexport interface SerializedPublicKey {\n /** Base64-encoded public key (raw format) */\n publicKeyB64: string;\n /** Curve used */\n curve: SupportedCurve;\n}\n\n/**\n * ECDH encryption error.\n */\nexport class EcdhError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n ) {\n super(message);\n this.name = 'EcdhError';\n }\n}\n\n/**\n * Get the Web Crypto subtle API.\n * Works in both browser and Node.js 20+.\n */\nfunction getSubtle(): SubtleCrypto {\n if (typeof globalThis.crypto?.subtle !== 'undefined') {\n return globalThis.crypto.subtle;\n }\n throw new EcdhError('Web Crypto API not available', EncryptionErrorCode.HandshakeFailed);\n}\n\n/**\n * Generate an ephemeral ECDH key pair.\n */\nexport async function generateKeyPair(curve: SupportedCurve = SupportedCurve.P256): Promise<EcdhKeyPair> {\n const subtle = getSubtle();\n\n try {\n const keyPair = await subtle.generateKey(\n {\n name: 'ECDH',\n namedCurve: curve,\n },\n true, // extractable for export\n ['deriveBits'],\n );\n\n return {\n publicKey: keyPair.publicKey,\n privateKey: keyPair.privateKey,\n };\n } catch (err) {\n throw new EcdhError(\n `Failed to generate key pair: ${err instanceof Error ? err.message : String(err)}`,\n EncryptionErrorCode.HandshakeFailed,\n );\n }\n}\n\n/**\n * Export a public key to base64 format.\n */\nexport async function exportPublicKey(publicKey: CryptoKey): Promise<SerializedPublicKey> {\n const subtle = getSubtle();\n\n try {\n const rawKey = await subtle.exportKey('raw', publicKey);\n const publicKeyB64 = btoa(String.fromCharCode(...new Uint8Array(rawKey)));\n\n // Extract curve from key algorithm\n const algorithm = publicKey.algorithm as EcKeyAlgorithm;\n const curve = algorithm.namedCurve as SupportedCurve;\n\n return { publicKeyB64, curve };\n } catch (err) {\n throw new EcdhError(\n `Failed to export public key: ${err instanceof Error ? err.message : String(err)}`,\n EncryptionErrorCode.InvalidPublicKey,\n );\n }\n}\n\n/**\n * Import a public key from base64 format.\n */\nexport async function importPublicKey(\n publicKeyB64: string,\n curve: SupportedCurve = SupportedCurve.P256,\n): Promise<CryptoKey> {\n const subtle = getSubtle();\n\n try {\n const rawKey = Uint8Array.from(atob(publicKeyB64), (c) => c.charCodeAt(0));\n\n return await subtle.importKey(\n 'raw',\n rawKey,\n {\n name: 'ECDH',\n namedCurve: curve,\n },\n true,\n [],\n );\n } catch (err) {\n throw new EcdhError(\n `Failed to import public key: ${err instanceof Error ? err.message : String(err)}`,\n EncryptionErrorCode.InvalidPublicKey,\n );\n }\n}\n\n/**\n * Derive shared secret from private key and peer's public key.\n */\nexport async function deriveSharedSecret(privateKey: CryptoKey, peerPublicKey: CryptoKey): Promise<Uint8Array> {\n const subtle = getSubtle();\n\n try {\n // Derive 256 bits (32 bytes) of shared secret\n const sharedBits = await subtle.deriveBits(\n {\n name: 'ECDH',\n public: peerPublicKey,\n },\n privateKey,\n 256,\n );\n\n return new Uint8Array(sharedBits);\n } catch (err) {\n throw new EcdhError(\n `Failed to derive shared secret: ${err instanceof Error ? err.message : String(err)}`,\n EncryptionErrorCode.KeyDerivationFailed,\n );\n }\n}\n\n/**\n * Create a client hello message for the encryption handshake.\n */\nexport async function createClientHello(keyPair: EcdhKeyPair): Promise<ClientHello> {\n const { publicKeyB64, curve } = await exportPublicKey(keyPair.publicKey);\n\n return {\n protocolVersion: PROTOCOL_VERSION,\n clientEphemeralPubKeyB64: publicKeyB64,\n curve,\n supportedAlgorithms: [EncryptionAlgorithm.AES_GCM_256],\n };\n}\n\n/**\n * Create a server hello message for the encryption handshake.\n */\nexport async function createServerHello(keyPair: EcdhKeyPair, keyId: string): Promise<ServerHello> {\n const { publicKeyB64, curve } = await exportPublicKey(keyPair.publicKey);\n\n return {\n protocolVersion: PROTOCOL_VERSION,\n serverEphemeralPubKeyB64: publicKeyB64,\n curve,\n selectedAlgorithm: EncryptionAlgorithm.AES_GCM_256,\n kdf: KeyDerivation.HKDF_SHA256,\n keyId,\n };\n}\n\n/**\n * Process a client hello and generate server response.\n */\nexport async function processClientHello(clientHello: ClientHello): Promise<{\n serverKeyPair: EcdhKeyPair;\n peerPublicKey: CryptoKey;\n serverHello: ServerHello;\n keyId: string;\n}> {\n // Generate server's ephemeral key pair\n const serverKeyPair = await generateKeyPair(clientHello.curve);\n\n // Import client's public key\n const peerPublicKey = await importPublicKey(clientHello.clientEphemeralPubKeyB64, clientHello.curve);\n\n // Generate a key ID\n const keyId = `k_${crypto.randomUUID()}`;\n\n // Create server hello\n const serverHello = await createServerHello(serverKeyPair, keyId);\n\n return {\n serverKeyPair,\n peerPublicKey,\n serverHello,\n keyId,\n };\n}\n\n/**\n * Process a server hello and extract peer's public key.\n */\nexport async function processServerHello(serverHello: ServerHello): Promise<{\n peerPublicKey: CryptoKey;\n keyId: string;\n}> {\n const peerPublicKey = await importPublicKey(serverHello.serverEphemeralPubKeyB64, serverHello.curve);\n\n return {\n peerPublicKey,\n keyId: serverHello.keyId,\n };\n}\n"]}
|
package/src/crypto/hkdf.js
DELETED
|
@@ -1,123 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
/**
|
|
3
|
-
* @enclave-vm/stream - HKDF Key Derivation
|
|
4
|
-
*
|
|
5
|
-
* HMAC-based Key Derivation Function using Web Crypto API.
|
|
6
|
-
* Derives encryption keys from ECDH shared secret.
|
|
7
|
-
*/
|
|
8
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
-
exports.HkdfError = void 0;
|
|
10
|
-
exports.deriveKey = deriveKey;
|
|
11
|
-
exports.deriveSessionKeys = deriveSessionKeys;
|
|
12
|
-
exports.importAesGcmKey = importAesGcmKey;
|
|
13
|
-
exports.deriveSessionCryptoKeys = deriveSessionCryptoKeys;
|
|
14
|
-
const types_1 = require("@enclave-vm/types");
|
|
15
|
-
/**
|
|
16
|
-
* Convert a Uint8Array to an ArrayBuffer.
|
|
17
|
-
* Handles the case where the Uint8Array is a view into a larger buffer.
|
|
18
|
-
*/
|
|
19
|
-
function toArrayBuffer(arr) {
|
|
20
|
-
if (arr.byteOffset === 0 && arr.byteLength === arr.buffer.byteLength) {
|
|
21
|
-
return arr.buffer;
|
|
22
|
-
}
|
|
23
|
-
return arr.buffer.slice(arr.byteOffset, arr.byteOffset + arr.byteLength);
|
|
24
|
-
}
|
|
25
|
-
/**
|
|
26
|
-
* HKDF derivation error.
|
|
27
|
-
*/
|
|
28
|
-
class HkdfError extends Error {
|
|
29
|
-
code;
|
|
30
|
-
constructor(message, code) {
|
|
31
|
-
super(message);
|
|
32
|
-
this.code = code;
|
|
33
|
-
this.name = 'HkdfError';
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
exports.HkdfError = HkdfError;
|
|
37
|
-
/**
|
|
38
|
-
* Get the Web Crypto subtle API.
|
|
39
|
-
*/
|
|
40
|
-
function getSubtle() {
|
|
41
|
-
if (typeof globalThis.crypto?.subtle !== 'undefined') {
|
|
42
|
-
return globalThis.crypto.subtle;
|
|
43
|
-
}
|
|
44
|
-
throw new HkdfError('Web Crypto API not available', types_1.EncryptionErrorCode.KeyDerivationFailed);
|
|
45
|
-
}
|
|
46
|
-
/**
|
|
47
|
-
* Derive a key using HKDF-SHA256.
|
|
48
|
-
*
|
|
49
|
-
* @param sharedSecret - The shared secret from ECDH
|
|
50
|
-
* @param salt - Optional salt (defaults to zeros)
|
|
51
|
-
* @param info - Context info string
|
|
52
|
-
* @param keyLength - Output key length in bytes (default: 32 for AES-256)
|
|
53
|
-
*/
|
|
54
|
-
async function deriveKey(sharedSecret, salt, info, keyLength = types_1.AES_256_KEY_SIZE) {
|
|
55
|
-
const subtle = getSubtle();
|
|
56
|
-
try {
|
|
57
|
-
// Import the shared secret as a raw key for HKDF
|
|
58
|
-
const baseKey = await subtle.importKey('raw', toArrayBuffer(sharedSecret), 'HKDF', false, ['deriveBits']);
|
|
59
|
-
// Use empty salt if not provided
|
|
60
|
-
const saltBytes = salt ?? new Uint8Array(32);
|
|
61
|
-
// Encode info string as bytes
|
|
62
|
-
const infoBytes = new TextEncoder().encode(info);
|
|
63
|
-
// Derive the key bits
|
|
64
|
-
const derivedBits = await subtle.deriveBits({
|
|
65
|
-
name: 'HKDF',
|
|
66
|
-
hash: 'SHA-256',
|
|
67
|
-
salt: toArrayBuffer(saltBytes),
|
|
68
|
-
info: toArrayBuffer(infoBytes),
|
|
69
|
-
}, baseKey, keyLength * 8);
|
|
70
|
-
return new Uint8Array(derivedBits);
|
|
71
|
-
}
|
|
72
|
-
catch (err) {
|
|
73
|
-
throw new HkdfError(`Failed to derive key: ${err instanceof Error ? err.message : String(err)}`, types_1.EncryptionErrorCode.KeyDerivationFailed);
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
/**
|
|
77
|
-
* Derive session keys for bidirectional communication.
|
|
78
|
-
*
|
|
79
|
-
* @param sharedSecret - The shared secret from ECDH
|
|
80
|
-
* @param sessionId - Session ID for domain separation
|
|
81
|
-
* @returns Client-to-server and server-to-client encryption keys
|
|
82
|
-
*/
|
|
83
|
-
async function deriveSessionKeys(sharedSecret, sessionId) {
|
|
84
|
-
// Use session ID as salt for domain separation
|
|
85
|
-
const salt = new TextEncoder().encode(sessionId);
|
|
86
|
-
// Derive separate keys for each direction
|
|
87
|
-
const [clientToServerKey, serverToClientKey] = await Promise.all([
|
|
88
|
-
deriveKey(sharedSecret, salt, types_1.HkdfInfo.ClientToServer),
|
|
89
|
-
deriveKey(sharedSecret, salt, types_1.HkdfInfo.ServerToClient),
|
|
90
|
-
]);
|
|
91
|
-
return {
|
|
92
|
-
clientToServerKey,
|
|
93
|
-
serverToClientKey,
|
|
94
|
-
};
|
|
95
|
-
}
|
|
96
|
-
/**
|
|
97
|
-
* Import a raw key as a CryptoKey for AES-GCM.
|
|
98
|
-
*/
|
|
99
|
-
async function importAesGcmKey(keyBytes) {
|
|
100
|
-
const subtle = getSubtle();
|
|
101
|
-
try {
|
|
102
|
-
return await subtle.importKey('raw', toArrayBuffer(keyBytes), {
|
|
103
|
-
name: 'AES-GCM',
|
|
104
|
-
length: keyBytes.length * 8,
|
|
105
|
-
}, false, // not extractable
|
|
106
|
-
['encrypt', 'decrypt']);
|
|
107
|
-
}
|
|
108
|
-
catch (err) {
|
|
109
|
-
throw new HkdfError(`Failed to import AES key: ${err instanceof Error ? err.message : String(err)}`, types_1.EncryptionErrorCode.KeyDerivationFailed);
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
/**
|
|
113
|
-
* Derive and import session keys as CryptoKeys.
|
|
114
|
-
*/
|
|
115
|
-
async function deriveSessionCryptoKeys(sharedSecret, sessionId) {
|
|
116
|
-
const { clientToServerKey, serverToClientKey } = await deriveSessionKeys(sharedSecret, sessionId);
|
|
117
|
-
const [c2sKey, s2cKey] = await Promise.all([importAesGcmKey(clientToServerKey), importAesGcmKey(serverToClientKey)]);
|
|
118
|
-
return {
|
|
119
|
-
clientToServerKey: c2sKey,
|
|
120
|
-
serverToClientKey: s2cKey,
|
|
121
|
-
};
|
|
122
|
-
}
|
|
123
|
-
//# sourceMappingURL=hkdf.js.map
|