@tianacloud/dsh-remote 0.0.0-stage → 0.2.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.
@@ -0,0 +1,460 @@
1
+ /**
2
+ * Shared WebCrypto End-to-End Encryption (E2EE v2) for @tianacloud/dsh-remote.
3
+ *
4
+ * Uses strictly standard WebCrypto APIs (`crypto.subtle`, `crypto.getRandomValues`)
5
+ * so both Node.js (>=22) and modern browsers execute identical cryptography:
6
+ * - Ephemeral ECDH P-256 per session (Forward Secrecy)
7
+ * - HKDF-SHA256 + HMAC-SHA256 mutual transcript authentication bound to Host E2EE secret (anti-MITM)
8
+ * - Directional AES-256-GCM subkeys + deterministic 96-bit nonces (4B HKDF prefix + 8B monotonic seq)
9
+ * - Strict monotonic sequence checking + GCM AAD binding (anti-replay / anti-reorder)
10
+ */
11
+
12
+ export const E2EE_PROTOCOL_VERSION = 2;
13
+ export const E2EE_ALGORITHM = 'ECDH-P256+HKDF-SHA256+AES-256-GCM';
14
+
15
+ export const MSG_E2EE_CLIENT_HELLO = 0x02;
16
+ export const MSG_E2EE_HOST_HELLO = 0x03;
17
+ export const MSG_E2EE_ERROR = 0x04;
18
+ export const MSG_E2EE_BOX = 0x30;
19
+ export const MSG_E2EE_CTRL = 0x31;
20
+ export const MAX_PLAINTEXT_BYTES = 1024 * 1024 - 64;
21
+ const MAX_QUEUE_BYTES = 8 * 1024 * 1024;
22
+ const MAX_QUEUE_FRAMES = 256;
23
+ const MAX_SEQ = 1n << 24n;
24
+ const MAX_KEY_BYTES = 32 * 1024 * 1024 * 1024;
25
+
26
+ const DIR_CLIENT_TO_HOST = 0x01;
27
+ const DIR_HOST_TO_CLIENT = 0x02;
28
+
29
+ const textEncoder = new TextEncoder();
30
+ const textDecoder = new TextDecoder();
31
+ const PROTOCOL_SALT = textEncoder.encode('dsh-remote-e2ee-v2');
32
+ const AUTH_INFO = textEncoder.encode('handshake-auth');
33
+ const C2H_TAG = textEncoder.encode('C2H-HELLO');
34
+ const H2C_TAG = textEncoder.encode('H2C-HELLO');
35
+ const INFO_C2H_KEY = textEncoder.encode('dsh-remote-e2ee-v2-c2h-key');
36
+ const INFO_H2C_KEY = textEncoder.encode('dsh-remote-e2ee-v2-h2c-key');
37
+ const INFO_C2H_IV = textEncoder.encode('dsh-remote-e2ee-v2-c2h-iv');
38
+ const INFO_H2C_IV = textEncoder.encode('dsh-remote-e2ee-v2-h2c-iv');
39
+
40
+ function getCrypto() {
41
+ const c = globalThis.crypto;
42
+ if (!c || !c.subtle) {
43
+ throw new Error('WebCrypto API (crypto.subtle) is unavailable in this context (HTTPS or localhost required)');
44
+ }
45
+ return c;
46
+ }
47
+
48
+ export function concatBytes(...parts) {
49
+ let total = 0;
50
+ for (const p of parts) total += p.byteLength;
51
+ const out = new Uint8Array(total);
52
+ let offset = 0;
53
+ for (const p of parts) {
54
+ out.set(p, offset);
55
+ offset += p.byteLength;
56
+ }
57
+ return out;
58
+ }
59
+
60
+ export function base64UrlEncode(bytes) {
61
+ const u8 = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
62
+ let bin = '';
63
+ for (let i = 0; i < u8.length; i += 1) {
64
+ bin += String.fromCharCode(u8[i]);
65
+ }
66
+ return btoa(bin).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/g, '');
67
+ }
68
+
69
+ export function base64UrlDecode(str) {
70
+ const clean = String(str || '').trim();
71
+ if (!clean || !/^[A-Za-z0-9_-]+$/.test(clean)) {
72
+ throw new Error('Invalid base64url encoding');
73
+ }
74
+ const padLen = (4 - (clean.length % 4)) % 4;
75
+ const b64 = clean.replaceAll('-', '+').replaceAll('_', '/') + '='.repeat(padLen);
76
+ const bin = atob(b64);
77
+ const out = new Uint8Array(bin.length);
78
+ for (let i = 0; i < bin.length; i += 1) {
79
+ out[i] = bin.charCodeAt(i);
80
+ }
81
+ return out;
82
+ }
83
+
84
+ export const PAIRING_KEY_PREFIX = 'dshk1_';
85
+
86
+ export function normalizePairingKey(secretStr) {
87
+ const clean = String(secretStr || '').trim();
88
+ return clean.startsWith(PAIRING_KEY_PREFIX) ? clean.slice(PAIRING_KEY_PREFIX.length) : clean;
89
+ }
90
+
91
+ export function decodeMasterSecret(secretStr) {
92
+ const bytes = base64UrlDecode(normalizePairingKey(secretStr));
93
+ if (bytes.byteLength !== 32) {
94
+ throw new Error(`Invalid E2EE key length: expected 32 bytes, got ${bytes.byteLength}`);
95
+ }
96
+ return bytes;
97
+ }
98
+
99
+ export function formatPairingKey(secretStr) {
100
+ const normalized = normalizePairingKey(secretStr);
101
+ decodeMasterSecret(normalized);
102
+ return `${PAIRING_KEY_PREFIX}${normalized}`;
103
+ }
104
+
105
+ export function generateE2eeSecretWeb() {
106
+ const bytes = new Uint8Array(32);
107
+ getCrypto().getRandomValues(bytes);
108
+ return base64UrlEncode(bytes);
109
+ }
110
+
111
+ export async function computeKeyFingerprint(secretStr) {
112
+ const bytes = decodeMasterSecret(secretStr);
113
+ const digest = new Uint8Array(await getCrypto().subtle.digest('SHA-256', bytes));
114
+ const parts = [];
115
+ for (let i = 0; i < 6; i += 2) {
116
+ parts.push(digest[i].toString(16).padStart(2, '0') + digest[i + 1].toString(16).padStart(2, '0'));
117
+ }
118
+ return parts.join(':');
119
+ }
120
+
121
+ async function deriveAuthKey(masterSecretBytes) {
122
+ const subtle = getCrypto().subtle;
123
+ const baseKey = await subtle.importKey('raw', masterSecretBytes, 'HKDF', false, ['deriveKey']);
124
+ return await subtle.deriveKey(
125
+ { name: 'HKDF', hash: 'SHA-256', salt: PROTOCOL_SALT, info: AUTH_INFO },
126
+ baseKey,
127
+ { name: 'HMAC', hash: 'SHA-256', length: 256 },
128
+ false,
129
+ ['sign', 'verify'],
130
+ );
131
+ }
132
+
133
+ async function signHmac(authKey, parts) {
134
+ const sig = await getCrypto().subtle.sign('HMAC', authKey, concatBytes(...parts));
135
+ return new Uint8Array(sig);
136
+ }
137
+
138
+ async function verifyHmac(authKey, parts, macBytes) {
139
+ if (!(macBytes instanceof Uint8Array) || macBytes.byteLength !== 32) return false;
140
+ return await getCrypto().subtle.verify('HMAC', authKey, macBytes, concatBytes(...parts));
141
+ }
142
+
143
+ export const MULTIPATH_CAPABILITIES = 'multipath-v1;assets-v1;ws-fragments-v1';
144
+ export function generateLogicalSessionId() {
145
+ return base64UrlEncode(crypto.getRandomValues(new Uint8Array(16)));
146
+ }
147
+
148
+ function handshakeContext({ hostId, webId, logicalSessionId, ownerUserId, tenantId }) {
149
+ if (typeof hostId !== 'string' || !hostId || hostId.length > 48 ||
150
+ typeof webId !== 'string' || !webId || webId.length > 128) {
151
+ throw new Error('Invalid E2EE target');
152
+ }
153
+ if (logicalSessionId === undefined) return textEncoder.encode(JSON.stringify([hostId, webId]));
154
+ if (base64UrlDecode(logicalSessionId).length !== 16 ||
155
+ ![ownerUserId, tenantId].every((id) => typeof id === 'string' && id.length > 0 && id.length <= 128)) {
156
+ throw new Error('Invalid E2EE session identity');
157
+ }
158
+ return textEncoder.encode(JSON.stringify([E2EE_PROTOCOL_VERSION, MULTIPATH_CAPABILITIES,
159
+ hostId, webId, logicalSessionId, ownerUserId, tenantId]));
160
+ }
161
+
162
+ async function deriveSessionKeys(masterSecretBytes, ecdhSharedBytes, clientNonce, hostNonce, context, control = false) {
163
+ const subtle = getCrypto().subtle;
164
+ const ikm = concatBytes(ecdhSharedBytes, masterSecretBytes);
165
+ const salt = concatBytes(clientNonce, hostNonce, context);
166
+ const baseKey = await subtle.importKey('raw', ikm, 'HKDF', false, ['deriveKey', 'deriveBits']);
167
+
168
+ const info = (value) => control ? concatBytes(value, textEncoder.encode('-control')) : value;
169
+ const [c2hKey, h2cKey, c2hIvBits, h2cIvBits] = await Promise.all([
170
+ subtle.deriveKey(
171
+ { name: 'HKDF', hash: 'SHA-256', salt, info: info(INFO_C2H_KEY) },
172
+ baseKey,
173
+ { name: 'AES-GCM', length: 256 },
174
+ false,
175
+ ['encrypt', 'decrypt'],
176
+ ),
177
+ subtle.deriveKey(
178
+ { name: 'HKDF', hash: 'SHA-256', salt, info: info(INFO_H2C_KEY) },
179
+ baseKey,
180
+ { name: 'AES-GCM', length: 256 },
181
+ false,
182
+ ['encrypt', 'decrypt'],
183
+ ),
184
+ subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt, info: info(INFO_C2H_IV) }, baseKey, 32),
185
+ subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt, info: info(INFO_H2C_IV) }, baseKey, 32),
186
+ ]);
187
+
188
+ return {
189
+ c2hKey,
190
+ h2cKey,
191
+ c2hIvPrefix: new Uint8Array(c2hIvBits),
192
+ h2cIvPrefix: new Uint8Array(h2cIvBits),
193
+ };
194
+ }
195
+
196
+ function buildAad(dirByte, seq) {
197
+ const out = new Uint8Array(PROTOCOL_SALT.byteLength + 1 + 8);
198
+ out.set(PROTOCOL_SALT, 0);
199
+ out[PROTOCOL_SALT.byteLength] = dirByte;
200
+ new DataView(out.buffer).setBigUint64(PROTOCOL_SALT.byteLength + 1, seq, false);
201
+ return out;
202
+ }
203
+
204
+ function buildIv(prefix4, seq) {
205
+ const iv = new Uint8Array(12);
206
+ iv.set(prefix4, 0);
207
+ new DataView(iv.buffer).setBigUint64(4, seq, false);
208
+ return iv;
209
+ }
210
+
211
+ export class E2EECipherSession {
212
+ constructor({ txKey, txIvPrefix, txDirByte, rxKey, rxIvPrefix, rxDirByte }) {
213
+ this.txKey = txKey;
214
+ this.txIvPrefix = txIvPrefix;
215
+ this.txDirByte = txDirByte;
216
+ this.rxKey = rxKey;
217
+ this.rxIvPrefix = rxIvPrefix;
218
+ this.rxDirByte = rxDirByte;
219
+ this.txSeq = 0n;
220
+ this.rxSeq = 0n;
221
+ this.txBytes = 0;
222
+ this.rxBytes = 0;
223
+ this.txQueue = { tail: Promise.resolve(), bytes: 0, frames: 0 };
224
+ this.rxQueue = { tail: Promise.resolve(), bytes: 0, frames: 0 };
225
+ this.failed = false;
226
+ }
227
+
228
+ async seal(plaintextBytes) {
229
+ const pt = plaintextBytes instanceof Uint8Array ? plaintextBytes : new Uint8Array(plaintextBytes);
230
+ if (this.failed || pt.byteLength > MAX_PLAINTEXT_BYTES ||
231
+ this.txSeq >= MAX_SEQ || this.txBytes + pt.byteLength > MAX_KEY_BYTES) {
232
+ this.failed = true;
233
+ throw new Error('E2EE send budget exceeded');
234
+ }
235
+ const seq = ++this.txSeq;
236
+ this.txBytes += pt.byteLength;
237
+ const iv = buildIv(this.txIvPrefix, seq);
238
+ const aad = buildAad(this.txDirByte, seq);
239
+ const ct = new Uint8Array(
240
+ await getCrypto().subtle.encrypt(
241
+ { name: 'AES-GCM', iv, additionalData: aad, tagLength: 128 },
242
+ this.txKey,
243
+ pt,
244
+ ),
245
+ );
246
+ const out = new Uint8Array(8 + ct.byteLength);
247
+ new DataView(out.buffer).setBigUint64(0, seq, false);
248
+ out.set(ct, 8);
249
+ return out;
250
+ }
251
+
252
+ async openPacket(boxBytes) {
253
+ const raw = boxBytes instanceof Uint8Array ? boxBytes : new Uint8Array(boxBytes);
254
+ if (this.failed || raw.byteLength > MAX_PLAINTEXT_BYTES + 24 ||
255
+ raw.byteLength < 24 || this.rxBytes + raw.byteLength - 24 > MAX_KEY_BYTES) {
256
+ throw new Error('Invalid E2EE receive budget');
257
+ }
258
+ const seq = new DataView(raw.buffer, raw.byteOffset, 8).getBigUint64(0, false);
259
+ if (seq === 0n || seq > MAX_SEQ) throw new Error('Invalid E2EE sequence');
260
+ const iv = buildIv(this.rxIvPrefix, seq);
261
+ const aad = buildAad(this.rxDirByte, seq);
262
+ const pt = new Uint8Array(await getCrypto().subtle.decrypt(
263
+ { name: 'AES-GCM', iv, additionalData: aad, tagLength: 128 }, this.rxKey, raw.subarray(8),
264
+ ));
265
+ if (this.rxBytes + pt.byteLength > MAX_KEY_BYTES) {
266
+ this.failed = true;
267
+ throw new Error('E2EE receive budget exceeded');
268
+ }
269
+ this.rxBytes += pt.byteLength;
270
+ return pt;
271
+ }
272
+
273
+ async open(boxBytes) {
274
+ if (boxBytes.byteLength < 24) throw new Error('Invalid E2EE box length');
275
+ const seq = new DataView(boxBytes.buffer ?? boxBytes, boxBytes.byteOffset ?? 0, 8).getBigUint64(0, false);
276
+ if (seq !== this.rxSeq + 1n) throw new Error('E2EE replay, missing or out-of-order frame');
277
+ const plaintext = await this.openPacket(boxBytes);
278
+ if (seq !== this.rxSeq + 1n) throw new Error('Concurrent E2EE sequence change');
279
+ this.rxSeq = seq;
280
+ return plaintext;
281
+ }
282
+
283
+ enqueue(queue, size, run) {
284
+ if (this.failed || queue.frames >= MAX_QUEUE_FRAMES || queue.bytes + size > MAX_QUEUE_BYTES) {
285
+ this.failed = true;
286
+ return Promise.reject(new Error('E2EE queue limit exceeded'));
287
+ }
288
+ queue.frames++;
289
+ queue.bytes += size;
290
+ const next = queue.tail.then(run).catch((err) => {
291
+ this.failed = true;
292
+ throw err;
293
+ }).finally(() => {
294
+ queue.frames--;
295
+ queue.bytes -= size;
296
+ });
297
+ queue.tail = next.catch(() => {});
298
+ return next;
299
+ }
300
+
301
+ enqueueSend(plaintextBytes, sendBoxFn) {
302
+ return this.enqueue(this.txQueue, plaintextBytes.byteLength, async () => {
303
+ const box = await this.seal(plaintextBytes);
304
+ sendBoxFn(box);
305
+ });
306
+ }
307
+
308
+ enqueueReceive(boxBytes, onPlaintextFn) {
309
+ return this.enqueue(this.rxQueue, boxBytes.byteLength, async () => {
310
+ const pt = await this.open(boxBytes);
311
+ await onPlaintextFn(pt);
312
+ });
313
+ }
314
+ }
315
+
316
+ async function createCiphers(secret, shared, clientNonce, hostNonce, context, client, logicalSessionId) {
317
+ function cipher(keys, domain) {
318
+ return new E2EECipherSession({
319
+ txKey: client ? keys.c2hKey : keys.h2cKey,
320
+ txIvPrefix: client ? keys.c2hIvPrefix : keys.h2cIvPrefix,
321
+ txDirByte: (client ? DIR_CLIENT_TO_HOST : DIR_HOST_TO_CLIENT) + domain,
322
+ rxKey: client ? keys.h2cKey : keys.c2hKey,
323
+ rxIvPrefix: client ? keys.h2cIvPrefix : keys.c2hIvPrefix,
324
+ rxDirByte: (client ? DIR_HOST_TO_CLIENT : DIR_CLIENT_TO_HOST) + domain,
325
+ });
326
+ }
327
+ const derive = (control) => deriveSessionKeys(secret, shared, clientNonce, hostNonce, context, control);
328
+ const data = cipher(await derive(false), 0);
329
+ if (logicalSessionId) {
330
+ data.control = cipher(await derive(true), 2);
331
+ data.logicalSessionId = logicalSessionId;
332
+ }
333
+ return data;
334
+ }
335
+
336
+ export async function createClientHandshake(secretStr, target) {
337
+ const context = handshakeContext(target);
338
+ const c = getCrypto();
339
+ const masterSecretBytes = decodeMasterSecret(secretStr);
340
+ const authKey = await deriveAuthKey(masterSecretBytes);
341
+ const kp = await c.subtle.generateKey({ name: 'ECDH', namedCurve: 'P-256' }, false, ['deriveBits']);
342
+ const clientPubRaw = new Uint8Array(await c.subtle.exportKey('raw', kp.publicKey));
343
+ const clientNonce = new Uint8Array(16);
344
+ c.getRandomValues(clientNonce);
345
+
346
+ const mac = await signHmac(authKey, [C2H_TAG, clientNonce, clientPubRaw, context]);
347
+ const helloPayload = textEncoder.encode(
348
+ JSON.stringify({
349
+ v: E2EE_PROTOCOL_VERSION,
350
+ clientPub: base64UrlEncode(clientPubRaw),
351
+ ...(target.logicalSessionId && {
352
+ capabilities: MULTIPATH_CAPABILITIES, logicalSessionId: target.logicalSessionId,
353
+ }),
354
+ clientNonce: base64UrlEncode(clientNonce),
355
+ mac: base64UrlEncode(mac),
356
+ }),
357
+ );
358
+
359
+ return {
360
+ helloPayload,
361
+ async finalize(hostHelloPayload) {
362
+ const msg = JSON.parse(textDecoder.decode(hostHelloPayload));
363
+ if (msg?.v !== E2EE_PROTOCOL_VERSION ||
364
+ (target.logicalSessionId && (msg.capabilities !== MULTIPATH_CAPABILITIES ||
365
+ msg.logicalSessionId !== target.logicalSessionId))) {
366
+ throw new Error(`Unsupported E2EE protocol version: ${msg?.v}`);
367
+ }
368
+ const hostPubRaw = base64UrlDecode(msg.hostPub);
369
+ const hostNonce = base64UrlDecode(msg.hostNonce);
370
+ const hostMac = base64UrlDecode(msg.mac);
371
+ if (hostNonce.byteLength !== 16 || hostPubRaw.byteLength !== 65) {
372
+ throw new Error('Malformed E2EE host hello parameters');
373
+ }
374
+ const valid = await verifyHmac(
375
+ authKey,
376
+ [H2C_TAG, clientNonce, clientPubRaw, hostNonce, hostPubRaw, context],
377
+ hostMac,
378
+ );
379
+ if (!valid) {
380
+ throw new Error('E2EE host authentication failed (possible MITM or mismatched key)');
381
+ }
382
+
383
+ const hostPubKey = await c.subtle.importKey(
384
+ 'raw',
385
+ hostPubRaw,
386
+ { name: 'ECDH', namedCurve: 'P-256' },
387
+ false,
388
+ [],
389
+ );
390
+ const ecdhShared = new Uint8Array(
391
+ await c.subtle.deriveBits({ name: 'ECDH', public: hostPubKey }, kp.privateKey, 256),
392
+ );
393
+ return createCiphers(masterSecretBytes, ecdhShared, clientNonce, hostNonce, context, true, target.logicalSessionId);
394
+ },
395
+ };
396
+ }
397
+
398
+ export async function respondHostHandshake(secretStr, clientHelloPayload, target) {
399
+ const context = handshakeContext(target);
400
+ const c = getCrypto();
401
+ const masterSecretBytes = decodeMasterSecret(secretStr);
402
+ const authKey = await deriveAuthKey(masterSecretBytes);
403
+ const msg = JSON.parse(textDecoder.decode(clientHelloPayload));
404
+ if (msg?.v !== E2EE_PROTOCOL_VERSION ||
405
+ (target.logicalSessionId && (msg.capabilities !== MULTIPATH_CAPABILITIES ||
406
+ msg.logicalSessionId !== target.logicalSessionId))) {
407
+ throw new Error(`Unsupported E2EE protocol version: ${msg?.v}`);
408
+ }
409
+ const clientPubRaw = base64UrlDecode(msg.clientPub);
410
+ const clientNonce = base64UrlDecode(msg.clientNonce);
411
+ const clientMac = base64UrlDecode(msg.mac);
412
+ if (clientNonce.byteLength !== 16 || clientPubRaw.byteLength !== 65) {
413
+ throw new Error('Malformed E2EE client hello parameters');
414
+ }
415
+ const valid = await verifyHmac(authKey, [C2H_TAG, clientNonce, clientPubRaw, context], clientMac);
416
+ if (!valid) {
417
+ const err = new Error('Invalid E2EE key or handshake authentication failed');
418
+ err.code = 'AUTH_FAILED';
419
+ throw err;
420
+ }
421
+
422
+ const clientPubKey = await c.subtle.importKey(
423
+ 'raw',
424
+ clientPubRaw,
425
+ { name: 'ECDH', namedCurve: 'P-256' },
426
+ false,
427
+ [],
428
+ );
429
+ const kp = await c.subtle.generateKey({ name: 'ECDH', namedCurve: 'P-256' }, false, ['deriveBits']);
430
+ const hostPubRaw = new Uint8Array(await c.subtle.exportKey('raw', kp.publicKey));
431
+ const hostNonce = new Uint8Array(16);
432
+ c.getRandomValues(hostNonce);
433
+
434
+ const ecdhShared = new Uint8Array(
435
+ await c.subtle.deriveBits({ name: 'ECDH', public: clientPubKey }, kp.privateKey, 256),
436
+ );
437
+ const hostMac = await signHmac(authKey, [
438
+ H2C_TAG,
439
+ clientNonce,
440
+ clientPubRaw,
441
+ hostNonce,
442
+ hostPubRaw,
443
+ context,
444
+ ]);
445
+
446
+ const hostHelloPayload = textEncoder.encode(
447
+ JSON.stringify({
448
+ v: E2EE_PROTOCOL_VERSION,
449
+ hostPub: base64UrlEncode(hostPubRaw),
450
+ ...(target.logicalSessionId && {
451
+ capabilities: MULTIPATH_CAPABILITIES, logicalSessionId: target.logicalSessionId,
452
+ }),
453
+ hostNonce: base64UrlEncode(hostNonce),
454
+ mac: base64UrlEncode(hostMac),
455
+ }),
456
+ );
457
+
458
+ const cipher = await createCiphers(masterSecretBytes, ecdhShared, clientNonce, hostNonce, context, false, target.logicalSessionId);
459
+ return { hostHelloPayload, cipher };
460
+ }