@dynamic-labs-wallet/forward-mpc-client 0.2.0 → 0.4.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/dist/index.js CHANGED
@@ -1,10 +1,13 @@
1
- import { EventEmitter } from 'eventemitter3';
1
+ import EventEmitter2, { EventEmitter } from 'eventemitter3';
2
2
  import * as ws from 'ws';
3
- import { messageRegistry, generateMlKem768Keypair, HandshakeV1RequestMessage, decapsulateMlKem768, encryptKeyshare, SignMessageV1RequestMessage } from '@dynamic-labs-wallet/forward-mpc-shared';
3
+ import { messageRegistry, generateMlKem768Keypair, HandshakeV1RequestMessage, decapsulateMlKem768, encryptKeyshare, SignMessageV1RequestMessage, encryptKeygenInit, KeygenV1RequestMessage, decryptKeygenResult, ReceiveKeyV1RequestMessage, fromDynamicSigningAlgorithm } from '@dynamic-labs-wallet/forward-mpc-shared';
4
4
  import init, { PCRs, validateAttestationDocPcrs, getUserData, getNonce } from '@evervault/wasm-attestation-bindings';
5
5
  import { sha256 } from '@noble/hashes/sha2.js';
6
6
  import { randomBytes, hexToBytes } from '@noble/hashes/utils.js';
7
7
  import { either } from 'fp-ts';
8
+ import { SigningAlgorithm } from '@dynamic-labs-wallet/core';
9
+ export { SigningAlgorithm } from '@dynamic-labs-wallet/core';
10
+ import { WebSocket } from 'isows';
8
11
 
9
12
  var __defProp = Object.defineProperty;
10
13
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
@@ -18,7 +21,7 @@ var NitroAttestationVerifier = class {
18
21
  __name(this, "NitroAttestationVerifier");
19
22
  }
20
23
  config;
21
- wasmInitialized = false;
24
+ wasmInitPromise = null;
22
25
  constructor(config) {
23
26
  this.config = {
24
27
  strictCertValidation: true,
@@ -27,17 +30,16 @@ var NitroAttestationVerifier = class {
27
30
  };
28
31
  }
29
32
  /**
30
- * Initialize WASM module if not already initialized
33
+ * Initialises the WASM module exactly once. Concurrent callers share the
34
+ * same in-flight promise, preventing duplicate initialisation.
35
+ * On failure the promise is cleared so the next call may retry.
31
36
  */
32
- async ensureWasmInitialized() {
33
- if (!this.wasmInitialized) {
34
- try {
35
- await init();
36
- this.wasmInitialized = true;
37
- } catch (error) {
38
- throw new Error(`Failed to initialize WASM module: ${error instanceof Error ? error.message : "Unknown error"}`);
39
- }
40
- }
37
+ ensureWasmInitialized() {
38
+ this.wasmInitPromise ??= init().then(() => void 0).catch((error) => {
39
+ this.wasmInitPromise = null;
40
+ throw new Error(`Failed to initialize WASM module: ${error instanceof Error ? error.message : "Unknown error"}`);
41
+ });
42
+ return this.wasmInitPromise;
41
43
  }
42
44
  /**
43
45
  * Verify an attestation document using Evervault WASM bindings
@@ -45,9 +47,9 @@ var NitroAttestationVerifier = class {
45
47
  *
46
48
  * @param attestationDocBase64 - Base64-encoded attestation document
47
49
  * @param expectedChallenge - Expected challenge (ciphertext hash)
48
- * @param expectedNonce - Expected nonce (REQUIRED for security)
50
+ * @param nonce - Expected nonce (REQUIRED for security)
49
51
  */
50
- async verify(attestationDocBase64, expectedChallenge, expectedNonce) {
52
+ async verify(attestationDocBase64, expectedChallenge, nonce) {
51
53
  try {
52
54
  await this.ensureWasmInitialized();
53
55
  const expectedPcrs = PCRs.empty();
@@ -64,37 +66,44 @@ var NitroAttestationVerifier = class {
64
66
  timestamp: Date.now()
65
67
  };
66
68
  }
67
- if (expectedChallenge) {
68
- try {
69
- const userData = getUserData(attestationDocBase64);
70
- if (!userData) {
71
- return {
72
- valid: false,
73
- errors: [
74
- "No user data found in attestation document"
75
- ],
76
- timestamp: Date.now()
77
- };
78
- }
79
- const userDataString = new TextDecoder("utf-8").decode(userData);
80
- if (!userDataString.includes(expectedChallenge)) {
81
- return {
82
- valid: false,
83
- errors: [
84
- "Ciphertext hash verification failed - challenge not found in attestation user data"
85
- ],
86
- timestamp: Date.now()
87
- };
88
- }
89
- } catch (error) {
69
+ if (!expectedChallenge) {
70
+ return {
71
+ valid: false,
72
+ errors: [
73
+ "No challenge provided \u2014 ciphertext binding cannot be verified"
74
+ ],
75
+ timestamp: Date.now()
76
+ };
77
+ }
78
+ try {
79
+ const userData = getUserData(attestationDocBase64);
80
+ if (!userData) {
81
+ return {
82
+ valid: false,
83
+ errors: [
84
+ "No user data found in attestation document"
85
+ ],
86
+ timestamp: Date.now()
87
+ };
88
+ }
89
+ const userDataString = new TextDecoder("utf-8").decode(userData);
90
+ if (userDataString !== expectedChallenge) {
90
91
  return {
91
92
  valid: false,
92
93
  errors: [
93
- `Failed to extract or verify ciphertext hash: ${error instanceof Error ? error.message : String(error)}`
94
+ "Ciphertext hash verification failed - challenge mismatch in attestation user data"
94
95
  ],
95
96
  timestamp: Date.now()
96
97
  };
97
98
  }
99
+ } catch (error) {
100
+ return {
101
+ valid: false,
102
+ errors: [
103
+ `Failed to extract or verify ciphertext hash: ${error instanceof Error ? error.message : String(error)}`
104
+ ],
105
+ timestamp: Date.now()
106
+ };
98
107
  }
99
108
  try {
100
109
  const extractedNonceRaw = getNonce(attestationDocBase64);
@@ -117,8 +126,7 @@ var NitroAttestationVerifier = class {
117
126
  extractedNonce[i] = binaryString.charCodeAt(i);
118
127
  }
119
128
  } else {
120
- const decodedBuffer = Buffer.from(nonceString, "base64");
121
- extractedNonce = new Uint8Array(decodedBuffer);
129
+ extractedNonce = new Uint8Array(Buffer.from(nonceString, "base64"));
122
130
  }
123
131
  } catch (decodeError) {
124
132
  return {
@@ -129,25 +137,27 @@ var NitroAttestationVerifier = class {
129
137
  timestamp: Date.now()
130
138
  };
131
139
  }
132
- if (extractedNonce.length !== expectedNonce.length) {
140
+ if (extractedNonce.length !== nonce.length) {
133
141
  return {
134
142
  valid: false,
135
143
  errors: [
136
- `Nonce length mismatch: expected ${expectedNonce.length} bytes, got ${extractedNonce.length} bytes`
144
+ `Nonce length mismatch: expected ${nonce.length} bytes, got ${extractedNonce.length} bytes`
137
145
  ],
138
146
  timestamp: Date.now()
139
147
  };
140
148
  }
141
- for (let i = 0; i < expectedNonce.length; i++) {
142
- if (extractedNonce[i] !== expectedNonce[i]) {
143
- return {
144
- valid: false,
145
- errors: [
146
- "Nonce verification failed - nonce mismatch"
147
- ],
148
- timestamp: Date.now()
149
- };
150
- }
149
+ let diff = 0;
150
+ for (let i = 0; i < nonce.length; i++) {
151
+ diff |= extractedNonce[i] ^ nonce[i];
152
+ }
153
+ if (diff !== 0) {
154
+ return {
155
+ valid: false,
156
+ errors: [
157
+ "Nonce verification failed - nonce mismatch"
158
+ ],
159
+ timestamp: Date.now()
160
+ };
151
161
  }
152
162
  } catch (error) {
153
163
  return {
@@ -464,6 +474,57 @@ var ForwardMPCClient = class extends EventEmitter {
464
474
  });
465
475
  return this.sendRequest(request);
466
476
  }
477
+ /**
478
+ * Perform MPC keygen for ECDSA and BIP340 algorithms
479
+ * For ED25519, use sampleKey() or receiveKey() methods instead
480
+ */
481
+ async keygen(params) {
482
+ if (params.signingAlgo === SigningAlgorithm.ED25519) {
483
+ throw new Error("ED25519 keygen not supported via keygen() method. Use sampleKey() or receiveKey() instead.");
484
+ }
485
+ const { sharedSecret, connectionId } = await this.ensureWsConnection();
486
+ const encryptedKeygenInit = encryptKeygenInit(params.keygenInit, sharedSecret, connectionId);
487
+ const request = new KeygenV1RequestMessage({
488
+ relayDomain: params.relayDomain,
489
+ signingAlgo: params.signingAlgo,
490
+ roomUuid: params.roomUuid,
491
+ numParties: params.numParties,
492
+ threshold: params.threshold,
493
+ keygenInit: encryptedKeygenInit,
494
+ keygenIds: params.keygenIds,
495
+ traceContext: params.traceContext,
496
+ userId: params.userId,
497
+ environmentId: params.environmentId
498
+ });
499
+ const response = await this.sendRequest(request);
500
+ const responseData = response.getData();
501
+ const keygenResult = decryptKeygenResult(responseData.keygenResult, sharedSecret, connectionId);
502
+ return keygenResult;
503
+ }
504
+ /**
505
+ * Receive an ED25519 key (one party receives the key generated by another)
506
+ * Uses ExportableEd25519 - the receiving party gets the key sampled by another party
507
+ */
508
+ async receiveKey(params) {
509
+ const { sharedSecret, connectionId } = await this.ensureWsConnection();
510
+ const encryptedKeygenInit = encryptKeygenInit(params.keygenInit, sharedSecret, connectionId);
511
+ const request = new ReceiveKeyV1RequestMessage({
512
+ relayDomain: params.relayDomain,
513
+ signingAlgo: "ed25519",
514
+ roomUuid: params.roomUuid,
515
+ numParties: params.numParties,
516
+ threshold: params.threshold,
517
+ keygenInit: encryptedKeygenInit,
518
+ keygenIds: params.keygenIds,
519
+ traceContext: params.traceContext,
520
+ userId: params.userId,
521
+ environmentId: params.environmentId
522
+ });
523
+ const response = await this.sendRequest(request);
524
+ const responseData = response.getData();
525
+ const keygenResult = decryptKeygenResult(responseData.keygenResult, sharedSecret, connectionId);
526
+ return keygenResult;
527
+ }
467
528
  get connected() {
468
529
  return this.isConnected;
469
530
  }
@@ -503,6 +564,828 @@ var ForwardMPCClient = class extends EventEmitter {
503
564
  }
504
565
  };
505
566
 
506
- export { ForwardMPCClient };
567
+ // src/client-v2/errors.ts
568
+ var ErrorCode = {
569
+ // Transport
570
+ CONNECTION_FAILED: "CONNECTION_FAILED",
571
+ CONNECTION_TIMEOUT: "CONNECTION_TIMEOUT",
572
+ NOT_CONNECTED: "NOT_CONNECTED",
573
+ // Session
574
+ HANDSHAKE_FAILED: "HANDSHAKE_FAILED",
575
+ HANDSHAKE_INVALID_RESPONSE: "HANDSHAKE_INVALID_RESPONSE",
576
+ ATTESTATION_FAILED: "ATTESTATION_FAILED",
577
+ ATTESTATION_NONCE_MISSING: "ATTESTATION_NONCE_MISSING",
578
+ REQUEST_TIMEOUT: "REQUEST_TIMEOUT",
579
+ SESSION_DISPOSED: "SESSION_DISPOSED",
580
+ SERVER_ERROR: "SERVER_ERROR",
581
+ MESSAGE_PARSE_FAILED: "MESSAGE_PARSE_FAILED",
582
+ // Client
583
+ SESSION_ESTABLISH_FAILED: "SESSION_ESTABLISH_FAILED",
584
+ UNSUPPORTED_ALGORITHM: "UNSUPPORTED_ALGORITHM"
585
+ };
586
+ var ForwardMPCErrorType = {
587
+ TRANSPORT: "transport",
588
+ SESSION: "session",
589
+ CLIENT: "client"
590
+ };
591
+ var ForwardMPCError = class extends Error {
592
+ static {
593
+ __name(this, "ForwardMPCError");
594
+ }
595
+ code;
596
+ type;
597
+ context;
598
+ constructor(message, code, type, context) {
599
+ super(message);
600
+ this.name = this.constructor.name;
601
+ this.code = code;
602
+ this.type = type;
603
+ this.context = context;
604
+ Object.setPrototypeOf(this, new.target.prototype);
605
+ }
606
+ toJSON() {
607
+ return {
608
+ name: this.name,
609
+ message: this.message,
610
+ code: this.code,
611
+ type: this.type,
612
+ stack: this.stack,
613
+ context: this.context
614
+ };
615
+ }
616
+ };
617
+ var TransportError = class extends ForwardMPCError {
618
+ static {
619
+ __name(this, "TransportError");
620
+ }
621
+ constructor(message, code, context) {
622
+ super(message, code, ForwardMPCErrorType.TRANSPORT, context);
623
+ }
624
+ };
625
+ var SessionError = class extends ForwardMPCError {
626
+ static {
627
+ __name(this, "SessionError");
628
+ }
629
+ constructor(message, code, context) {
630
+ super(message, code, ForwardMPCErrorType.SESSION, context);
631
+ }
632
+ };
633
+ var ClientError = class extends ForwardMPCError {
634
+ static {
635
+ __name(this, "ClientError");
636
+ }
637
+ constructor(message, code, context) {
638
+ super(message, code, ForwardMPCErrorType.CLIENT, context);
639
+ }
640
+ };
641
+ var TransportConnectionError = class extends TransportError {
642
+ static {
643
+ __name(this, "TransportConnectionError");
644
+ }
645
+ constructor(context) {
646
+ super("WebSocket connection failed", ErrorCode.CONNECTION_FAILED, context);
647
+ }
648
+ };
649
+ var TransportConnectionTimeoutError = class extends TransportError {
650
+ static {
651
+ __name(this, "TransportConnectionTimeoutError");
652
+ }
653
+ constructor(context) {
654
+ super("WebSocket connection timed out", ErrorCode.CONNECTION_TIMEOUT, context);
655
+ }
656
+ };
657
+ var TransportNotConnectedError = class extends TransportError {
658
+ static {
659
+ __name(this, "TransportNotConnectedError");
660
+ }
661
+ constructor(context) {
662
+ super("WebSocket is not connected", ErrorCode.NOT_CONNECTED, context);
663
+ }
664
+ };
665
+ var SessionHandshakeError = class extends SessionError {
666
+ static {
667
+ __name(this, "SessionHandshakeError");
668
+ }
669
+ constructor(reason, context) {
670
+ super(`ML-KEM-768 handshake failed: ${reason}`, ErrorCode.HANDSHAKE_FAILED, {
671
+ reason,
672
+ ...context
673
+ });
674
+ }
675
+ };
676
+ var SessionHandshakeInvalidResponseError = class extends SessionError {
677
+ static {
678
+ __name(this, "SessionHandshakeInvalidResponseError");
679
+ }
680
+ constructor(context) {
681
+ super("Handshake response was invalid or incomplete", ErrorCode.HANDSHAKE_INVALID_RESPONSE, context);
682
+ }
683
+ };
684
+ var SessionAttestationError = class extends SessionError {
685
+ static {
686
+ __name(this, "SessionAttestationError");
687
+ }
688
+ constructor(context) {
689
+ super("Attestation verification failed", ErrorCode.ATTESTATION_FAILED, context);
690
+ }
691
+ };
692
+ var SessionAttestationNonceMissingError = class extends SessionError {
693
+ static {
694
+ __name(this, "SessionAttestationNonceMissingError");
695
+ }
696
+ constructor(context) {
697
+ super("Nonce missing from attestation document", ErrorCode.ATTESTATION_NONCE_MISSING, context);
698
+ }
699
+ };
700
+ var SessionRequestTimeoutError = class extends SessionError {
701
+ static {
702
+ __name(this, "SessionRequestTimeoutError");
703
+ }
704
+ constructor(context) {
705
+ super("Request timed out waiting for server response", ErrorCode.REQUEST_TIMEOUT, context);
706
+ }
707
+ };
708
+ var SessionDisposedError = class extends SessionError {
709
+ static {
710
+ __name(this, "SessionDisposedError");
711
+ }
712
+ constructor(context) {
713
+ super("Session has been disposed", ErrorCode.SESSION_DISPOSED, context);
714
+ }
715
+ };
716
+ var SessionServerError = class extends SessionError {
717
+ static {
718
+ __name(this, "SessionServerError");
719
+ }
720
+ constructor(reason, context) {
721
+ super(`Server returned an error response: ${reason}`, ErrorCode.SERVER_ERROR, {
722
+ reason,
723
+ ...context
724
+ });
725
+ }
726
+ };
727
+ var SessionMessageParseError = class extends SessionError {
728
+ static {
729
+ __name(this, "SessionMessageParseError");
730
+ }
731
+ constructor(context) {
732
+ super("Failed to parse server message", ErrorCode.MESSAGE_PARSE_FAILED, context);
733
+ }
734
+ };
735
+ var SessionRemoteError = class extends SessionError {
736
+ static {
737
+ __name(this, "SessionRemoteError");
738
+ }
739
+ serverError;
740
+ constructor(serverError, context) {
741
+ super(serverError.message, ErrorCode.SERVER_ERROR, context), this.serverError = serverError;
742
+ }
743
+ };
744
+ var ClientUnsupportedAlgorithmError = class extends ClientError {
745
+ static {
746
+ __name(this, "ClientUnsupportedAlgorithmError");
747
+ }
748
+ constructor(context) {
749
+ super("Signing algorithm is not supported", ErrorCode.UNSUPPORTED_ALGORITHM, context);
750
+ }
751
+ };
752
+ var ClientSessionEstablishFailedError = class extends ClientError {
753
+ static {
754
+ __name(this, "ClientSessionEstablishFailedError");
755
+ }
756
+ constructor(context) {
757
+ super("Failed to establish session", ErrorCode.SESSION_ESTABLISH_FAILED, context);
758
+ }
759
+ };
760
+
761
+ // src/client-v2/transport.ts
762
+ var ForwardMPCTransport = class extends EventEmitter2 {
763
+ static {
764
+ __name(this, "ForwardMPCTransport");
765
+ }
766
+ url;
767
+ ws = null;
768
+ _isConnected = false;
769
+ _destroyed = false;
770
+ _hadSuccessfulConnection = false;
771
+ _midSessionReconnectCount = 0;
772
+ _connectPromise = null;
773
+ options;
774
+ logger;
775
+ constructor(url, options = {}) {
776
+ super(), this.url = url;
777
+ this.logger = options.logger;
778
+ this.options = {
779
+ reconnectAttempts: options.reconnectAttempts ?? 1,
780
+ reconnectInterval: options.reconnectInterval ?? 1e3,
781
+ connectionTimeout: options.connectionTimeout ?? 1e4
782
+ };
783
+ }
784
+ get connected() {
785
+ return this._isConnected;
786
+ }
787
+ /**
788
+ * Opens the WebSocket connection. Concurrent callers coalesce on a single
789
+ * in-flight promise. `reconnectAttempts` controls how many silent retries
790
+ * are attempted before the promise rejects (default: 1 retry = 2 total tries).
791
+ */
792
+ async connect() {
793
+ this._destroyed = false;
794
+ if (this._isConnected) return;
795
+ if (this._connectPromise) return this._connectPromise;
796
+ this._connectPromise = this._connectWithRetry().finally(() => {
797
+ this._connectPromise = null;
798
+ });
799
+ return this._connectPromise;
800
+ }
801
+ disconnect() {
802
+ this._destroyed = true;
803
+ if (this.ws) {
804
+ this.ws.close();
805
+ this.ws = null;
806
+ }
807
+ this._isConnected = false;
808
+ this.emit("disconnected");
809
+ }
810
+ send(data) {
811
+ if (!this._isConnected || !this.ws) {
812
+ throw new TransportNotConnectedError();
813
+ }
814
+ this.ws.send(data);
815
+ }
816
+ /**
817
+ * Attempts the initial connection, then silently retries up to
818
+ * `reconnectAttempts` times before surfacing an error.
819
+ */
820
+ async _connectWithRetry() {
821
+ let lastError;
822
+ for (let attempt = 0; attempt <= this.options.reconnectAttempts; attempt++) {
823
+ try {
824
+ await this._connectOnce();
825
+ return;
826
+ } catch (error) {
827
+ lastError = error;
828
+ }
829
+ }
830
+ throw lastError;
831
+ }
832
+ _connectOnce() {
833
+ return new Promise((resolve, reject) => {
834
+ const timeoutHandle = setTimeout(() => {
835
+ this.ws?.close();
836
+ reject(new TransportConnectionTimeoutError({
837
+ url: this.url
838
+ }));
839
+ }, this.options.connectionTimeout);
840
+ this.ws = new WebSocket(this.url);
841
+ this.ws.onopen = () => {
842
+ clearTimeout(timeoutHandle);
843
+ this._isConnected = true;
844
+ this._hadSuccessfulConnection = true;
845
+ this._midSessionReconnectCount = 0;
846
+ this.logger?.info("WebSocket connected", {
847
+ url: this.url
848
+ });
849
+ this.emit("connected");
850
+ resolve();
851
+ };
852
+ this.ws.onerror = () => {
853
+ clearTimeout(timeoutHandle);
854
+ const err = new TransportConnectionError({
855
+ url: this.url
856
+ });
857
+ this.emit("error", err);
858
+ reject(err);
859
+ };
860
+ this.ws.onmessage = (event) => {
861
+ this.logger?.debug("WebSocket message received", {
862
+ data: event.data
863
+ });
864
+ this.emit("message", event.data);
865
+ };
866
+ this.ws.onclose = () => {
867
+ this._isConnected = false;
868
+ if (!this._destroyed) {
869
+ this.emit("disconnected");
870
+ }
871
+ this.maybeReconnect();
872
+ };
873
+ });
874
+ }
875
+ /**
876
+ * Attempts mid-session reconnects after a drop, up to `reconnectAttempts`
877
+ * times. Only fires when a successful connection was previously established.
878
+ */
879
+ maybeReconnect() {
880
+ if (this._destroyed) return;
881
+ if (!this._hadSuccessfulConnection) return;
882
+ if (this._midSessionReconnectCount >= this.options.reconnectAttempts) return;
883
+ this._midSessionReconnectCount++;
884
+ this.logger?.warn("WebSocket disconnected \u2014 attempting reconnect", {
885
+ url: this.url,
886
+ attempt: this._midSessionReconnectCount,
887
+ maxAttempts: this.options.reconnectAttempts
888
+ });
889
+ setTimeout(() => {
890
+ this._connectOnce().catch((error) => {
891
+ const err = error instanceof Error ? error : new Error(String(error));
892
+ this.logger?.error("Reconnect failed", {
893
+ attempt: this._midSessionReconnectCount
894
+ }, err);
895
+ this.emit("error", err);
896
+ });
897
+ }, this.options.reconnectInterval);
898
+ }
899
+ };
900
+ function isWebSocketError(v) {
901
+ return typeof v === "object" && v !== null && typeof v["message"] === "string" && typeof v["type"] === "string";
902
+ }
903
+ __name(isWebSocketError, "isWebSocketError");
904
+ var Session = class _Session {
905
+ static {
906
+ __name(this, "Session");
907
+ }
908
+ transport;
909
+ _connectionId;
910
+ _sharedSecret;
911
+ requestTimeout;
912
+ logger;
913
+ _disposed = false;
914
+ _abort = new AbortController();
915
+ /**
916
+ * Session is only constructed with fully-validated crypto material.
917
+ * All handshake and attestation work is done in the static handshake() factory
918
+ * before this constructor is called.
919
+ */
920
+ constructor(transport, _connectionId, _sharedSecret, requestTimeout, logger) {
921
+ this.transport = transport;
922
+ this._connectionId = _connectionId;
923
+ this._sharedSecret = _sharedSecret;
924
+ this.requestTimeout = requestTimeout;
925
+ this.logger = logger;
926
+ }
927
+ get connectionId() {
928
+ return this._connectionId;
929
+ }
930
+ get sharedSecret() {
931
+ if (this._disposed) {
932
+ throw new SessionDisposedError();
933
+ }
934
+ return this._sharedSecret;
935
+ }
936
+ /**
937
+ * Performs the ML-KEM-768 handshake over an established transport connection
938
+ * and returns a fully authenticated Session. All crypto material is derived
939
+ * before the Session object is created — the constructor never receives
940
+ * partially-initialised state.
941
+ *
942
+ * Attestation is verified (when configured) before the Session is returned.
943
+ */
944
+ static async handshake(transport, traceContext, options = {}, logger) {
945
+ const requestTimeout = options.requestTimeout ?? 3e4;
946
+ const { encapsulationKey, decapsulationKey } = generateMlKem768Keypair();
947
+ const nonceBytes = randomBytes(32);
948
+ const request = new HandshakeV1RequestMessage({
949
+ challenge: encapsulationKey,
950
+ nonce: nonceBytes,
951
+ traceContext
952
+ });
953
+ let data;
954
+ try {
955
+ data = await _Session.doRequest(transport, request, requestTimeout);
956
+ } catch (error) {
957
+ decapsulationKey.fill(0);
958
+ nonceBytes.fill(0);
959
+ const message = error instanceof Error ? error.message : String(error);
960
+ throw new SessionHandshakeError(message);
961
+ }
962
+ if (!data.encapsulatedSharedSecret || !data.connectionId) {
963
+ decapsulationKey.fill(0);
964
+ nonceBytes.fill(0);
965
+ throw new SessionHandshakeInvalidResponseError();
966
+ }
967
+ const connectionId = data.connectionId;
968
+ const cipherText = hexToBytes(data.encapsulatedSharedSecret);
969
+ const sharedSecret = decapsulateMlKem768(decapsulationKey, cipherText);
970
+ decapsulationKey.fill(0);
971
+ if (options.attestationVerifier && !options.bypassAttestation) {
972
+ if (!data.attestationDoc) {
973
+ sharedSecret.fill(0);
974
+ nonceBytes.fill(0);
975
+ throw new SessionAttestationError({
976
+ reason: "Server did not return an attestation document"
977
+ });
978
+ }
979
+ try {
980
+ await _Session.verifyAttestation(data.attestationDoc, cipherText, nonceBytes, options.attestationVerifier);
981
+ } catch (error) {
982
+ sharedSecret.fill(0);
983
+ nonceBytes.fill(0);
984
+ throw error;
985
+ }
986
+ }
987
+ nonceBytes.fill(0);
988
+ logger?.debug("Handshake completed", {
989
+ connectionId
990
+ });
991
+ return new _Session(transport, connectionId, sharedSecret, requestTimeout, logger);
992
+ }
993
+ sendRequest(message) {
994
+ if (this._disposed) {
995
+ return Promise.reject(new SessionDisposedError());
996
+ }
997
+ return _Session.doRequest(this.transport, message, this.requestTimeout, this._abort.signal);
998
+ }
999
+ dispose() {
1000
+ if (this._disposed) return;
1001
+ this._disposed = true;
1002
+ this._abort.abort();
1003
+ this._sharedSecret.fill(0);
1004
+ this.logger?.debug("Session disposed", {
1005
+ connectionId: this._connectionId
1006
+ });
1007
+ }
1008
+ /**
1009
+ * Sends a single request and resolves with the decoded response data.
1010
+ * Used by both handshake() and sendRequest(). The optional AbortSignal
1011
+ * allows dispose() to cancel all in-flight requests immediately.
1012
+ */
1013
+ static doRequest(transport, message, timeout, signal) {
1014
+ const requestId = _Session.generateRequestId();
1015
+ return new Promise((resolve, reject) => {
1016
+ if (signal?.aborted) {
1017
+ reject(new SessionDisposedError());
1018
+ return;
1019
+ }
1020
+ const cleanup = /* @__PURE__ */ __name(() => {
1021
+ clearTimeout(timeoutHandle);
1022
+ transport.off("message", handler);
1023
+ signal?.removeEventListener("abort", onAbort);
1024
+ }, "cleanup");
1025
+ const onAbort = /* @__PURE__ */ __name(() => {
1026
+ cleanup();
1027
+ reject(new SessionDisposedError());
1028
+ }, "onAbort");
1029
+ signal?.addEventListener("abort", onAbort, {
1030
+ once: true
1031
+ });
1032
+ const timeoutHandle = setTimeout(() => {
1033
+ cleanup();
1034
+ reject(new SessionRequestTimeoutError({
1035
+ requestId
1036
+ }));
1037
+ }, timeout);
1038
+ const handler = /* @__PURE__ */ __name((rawData) => {
1039
+ let parsed;
1040
+ try {
1041
+ parsed = JSON.parse(rawData);
1042
+ } catch {
1043
+ return;
1044
+ }
1045
+ if (parsed["requestId"] !== requestId) return;
1046
+ cleanup();
1047
+ const { requestId: _rid, ...body } = parsed;
1048
+ let msg = null;
1049
+ try {
1050
+ const result = messageRegistry.decode(body);
1051
+ if (either.isRight(result)) msg = result.right;
1052
+ } catch {
1053
+ }
1054
+ if (msg === null) {
1055
+ reject(new SessionMessageParseError({
1056
+ requestId
1057
+ }));
1058
+ return;
1059
+ }
1060
+ if (msg.type === "error") {
1061
+ reject(isWebSocketError(msg.error) ? new SessionRemoteError(msg.error) : new SessionMessageParseError({
1062
+ requestId
1063
+ }));
1064
+ } else {
1065
+ resolve(msg.getData());
1066
+ }
1067
+ }, "handler");
1068
+ transport.on("message", handler);
1069
+ try {
1070
+ transport.send(_Session.serializeWithRequestId(message, requestId));
1071
+ } catch (error) {
1072
+ cleanup();
1073
+ reject(error instanceof Error ? error : new Error(String(error)));
1074
+ }
1075
+ });
1076
+ }
1077
+ /**
1078
+ * Serialises a message with the given requestId injected without mutating
1079
+ * the original message object. Handles both encodeable (registry) messages
1080
+ * and plain objects.
1081
+ */
1082
+ static serializeWithRequestId(message, requestId) {
1083
+ const msg = message;
1084
+ if (typeof msg["encode"] === "function") {
1085
+ const encoded = msg["encode"]();
1086
+ encoded["requestId"] = requestId;
1087
+ return JSON.stringify(encoded);
1088
+ }
1089
+ return JSON.stringify({
1090
+ ...msg,
1091
+ requestId
1092
+ });
1093
+ }
1094
+ static generateRequestId() {
1095
+ const rand = randomBytes(8);
1096
+ return `req_${Array.from(rand).map((b) => b.toString(16).padStart(2, "0")).join("")}`;
1097
+ }
1098
+ static async verifyAttestation(attestationDocBase64, cipherText, nonce, verifier) {
1099
+ const challengeHash = sha256(cipherText);
1100
+ const expectedChallenge = Array.from(challengeHash).map((b) => b.toString(16).padStart(2, "0")).join("");
1101
+ const result = await verifier.verify(attestationDocBase64, expectedChallenge, nonce);
1102
+ if (!result.valid) {
1103
+ throw new SessionAttestationError({
1104
+ errors: result.errors
1105
+ });
1106
+ }
1107
+ }
1108
+ };
1109
+
1110
+ // src/client-v2/logger.ts
1111
+ var Logger = class {
1112
+ static {
1113
+ __name(this, "Logger");
1114
+ }
1115
+ externalLogger;
1116
+ MESSAGE_PREFIX = "[ForwardMPCClientV2]";
1117
+ constructor(externalLogger) {
1118
+ this.externalLogger = externalLogger;
1119
+ }
1120
+ debug(message, messageContext, error) {
1121
+ this.externalLogger?.debug(`${this.MESSAGE_PREFIX} ${message}`, messageContext, error);
1122
+ }
1123
+ info(message, messageContext, error) {
1124
+ this.externalLogger?.info(`${this.MESSAGE_PREFIX} ${message}`, messageContext, error);
1125
+ }
1126
+ warn(message, messageContext, error) {
1127
+ this.externalLogger?.warn(`${this.MESSAGE_PREFIX} ${message}`, messageContext, error);
1128
+ }
1129
+ error(message, messageContext, error) {
1130
+ this.externalLogger?.error(`${this.MESSAGE_PREFIX} ${message}`, messageContext, error);
1131
+ }
1132
+ };
1133
+
1134
+ // src/client-v2/client-v2.ts
1135
+ var ForwardMPCClientV2 = class extends EventEmitter2 {
1136
+ static {
1137
+ __name(this, "ForwardMPCClientV2");
1138
+ }
1139
+ url;
1140
+ options;
1141
+ transport;
1142
+ sessionOptions;
1143
+ logger;
1144
+ session = null;
1145
+ _connectPromise = null;
1146
+ _handshaking = false;
1147
+ _disconnectedIntentionally = false;
1148
+ constructor(url, options = {}) {
1149
+ super();
1150
+ this.url = url;
1151
+ this.options = options;
1152
+ if (options.dangerouslyBypassAttestation) {
1153
+ console.warn("[ForwardMPCClientV2] dangerouslyBypassAttestation is enabled \u2014 attestation verification is disabled. Do not use in production.");
1154
+ } else if (!options.attestationVerifier && !options.attestationConfig) {
1155
+ console.warn("[ForwardMPCClientV2] No attestation verifier configured \u2014 connections will not be attested. This is insecure in production.");
1156
+ }
1157
+ this.logger = new Logger(this.options.logger);
1158
+ const transportOptions = {
1159
+ reconnectAttempts: this.options.reconnectAttempts,
1160
+ reconnectInterval: this.options.reconnectInterval,
1161
+ connectionTimeout: this.options.connectionTimeout,
1162
+ logger: this.logger
1163
+ };
1164
+ this.transport = new ForwardMPCTransport(url, transportOptions);
1165
+ const attestationVerifier = options.attestationVerifier ?? (options.attestationConfig ? new NitroAttestationVerifier(options.attestationConfig) : void 0);
1166
+ this.sessionOptions = {
1167
+ attestationVerifier,
1168
+ bypassAttestation: options.dangerouslyBypassAttestation,
1169
+ requestTimeout: options.requestTimeout
1170
+ };
1171
+ this.transport.on("connected", () => this.onTransportConnected());
1172
+ this.transport.on("disconnected", () => this.onTransportDisconnected());
1173
+ this.transport.on("error", (error) => this.emit("error", error));
1174
+ }
1175
+ get connected() {
1176
+ return this.transport.connected && this.session !== null;
1177
+ }
1178
+ /**
1179
+ * Opens the WebSocket connection and performs the ML-KEM-768 handshake.
1180
+ * Resolves once the session is fully established (and attested, if configured).
1181
+ * Concurrent calls coalesce on a single in-flight promise.
1182
+ */
1183
+ async connect(traceContext) {
1184
+ if (this.session) return;
1185
+ if (this._connectPromise) return this._connectPromise;
1186
+ this._connectPromise = this._doConnect(traceContext).finally(() => {
1187
+ this._connectPromise = null;
1188
+ });
1189
+ return this._connectPromise;
1190
+ }
1191
+ /**
1192
+ * Disposes the current session (zeroing crypto material) and closes the transport.
1193
+ */
1194
+ disconnect() {
1195
+ this._disconnectedIntentionally = true;
1196
+ this.session?.dispose();
1197
+ this.session = null;
1198
+ this.transport.disconnect();
1199
+ }
1200
+ async signMessage(params) {
1201
+ const session = await this.ensureSession();
1202
+ let messageToSign;
1203
+ if (typeof params.message === "string") {
1204
+ const hex = params.message.startsWith("0x") ? params.message.slice(2) : params.message;
1205
+ messageToSign = hexToBytes(hex);
1206
+ } else {
1207
+ messageToSign = params.message;
1208
+ }
1209
+ const encryptedKeyshare = encryptKeyshare(params.keyshare, session.sharedSecret, session.connectionId, fromDynamicSigningAlgorithm(params.signingAlgo));
1210
+ const request = new SignMessageV1RequestMessage({
1211
+ relayDomain: params.relayDomain,
1212
+ signingAlgo: params.signingAlgo,
1213
+ hashAlgo: params.hashAlgo,
1214
+ derivationPath: params.derivationPath,
1215
+ tweak: params.tweak,
1216
+ keyshare: encryptedKeyshare,
1217
+ message: messageToSign,
1218
+ roomUuid: params.roomUuid,
1219
+ traceContext: params.traceContext,
1220
+ userId: params.userId,
1221
+ environmentId: params.environmentId
1222
+ });
1223
+ const { signature } = await session.sendRequest(request);
1224
+ if (!signature) {
1225
+ throw new SessionServerError("No signature in response");
1226
+ }
1227
+ return {
1228
+ signature
1229
+ };
1230
+ }
1231
+ /**
1232
+ * MPC key generation for ECDSA and BIP340.
1233
+ * ED25519 is not supported here — use receiveKey() instead.
1234
+ */
1235
+ async keygen(params) {
1236
+ if (params.signingAlgo === SigningAlgorithm.ED25519) {
1237
+ throw new ClientUnsupportedAlgorithmError();
1238
+ }
1239
+ const session = await this.ensureSession();
1240
+ const encryptedKeygenInit = encryptKeygenInit(params.keygenInit, session.sharedSecret, session.connectionId);
1241
+ const request = new KeygenV1RequestMessage({
1242
+ relayDomain: params.relayDomain,
1243
+ signingAlgo: params.signingAlgo,
1244
+ roomUuid: params.roomUuid,
1245
+ numParties: params.numParties,
1246
+ threshold: params.threshold,
1247
+ keygenInit: encryptedKeygenInit,
1248
+ keygenIds: params.keygenIds,
1249
+ traceContext: params.traceContext,
1250
+ userId: params.userId,
1251
+ environmentId: params.environmentId
1252
+ });
1253
+ const { keygenResult } = await session.sendRequest(request);
1254
+ if (!keygenResult) {
1255
+ throw new SessionServerError("No keygen result in response");
1256
+ }
1257
+ return decryptKeygenResult(keygenResult, session.sharedSecret, session.connectionId);
1258
+ }
1259
+ /**
1260
+ * Receives an ED25519 key generated by another party (ExportableEd25519).
1261
+ */
1262
+ async receiveKey(params) {
1263
+ const session = await this.ensureSession();
1264
+ const encryptedKeygenInit = encryptKeygenInit(params.keygenInit, session.sharedSecret, session.connectionId);
1265
+ const request = new ReceiveKeyV1RequestMessage({
1266
+ relayDomain: params.relayDomain,
1267
+ signingAlgo: "ed25519",
1268
+ roomUuid: params.roomUuid,
1269
+ numParties: params.numParties,
1270
+ threshold: params.threshold,
1271
+ keygenInit: encryptedKeygenInit,
1272
+ keygenIds: params.keygenIds,
1273
+ traceContext: params.traceContext,
1274
+ userId: params.userId,
1275
+ environmentId: params.environmentId
1276
+ });
1277
+ const { keygenResult } = await session.sendRequest(request);
1278
+ if (!keygenResult) {
1279
+ throw new SessionServerError("No keygen result in response");
1280
+ }
1281
+ return decryptKeygenResult(keygenResult, session.sharedSecret, session.connectionId);
1282
+ }
1283
+ /**
1284
+ * Ensures an active session exists, auto-connecting if needed.
1285
+ */
1286
+ async ensureSession() {
1287
+ if (this.session) return this.session;
1288
+ await this.connect();
1289
+ if (!this.session) {
1290
+ throw new ClientSessionEstablishFailedError();
1291
+ }
1292
+ return this.session;
1293
+ }
1294
+ async _runHandshake(traceContext) {
1295
+ this.session = await Session.handshake(this.transport, traceContext, this.sessionOptions, this.logger);
1296
+ this.emit("connected");
1297
+ }
1298
+ async _doConnect(traceContext) {
1299
+ this._handshaking = true;
1300
+ try {
1301
+ await this.transport.connect();
1302
+ await this._runHandshake(traceContext);
1303
+ } finally {
1304
+ this._handshaking = false;
1305
+ }
1306
+ }
1307
+ /**
1308
+ * Called when the transport connects (both initial and after auto-reconnect).
1309
+ * The `_handshaking` flag is set synchronously at the top of `_doConnect`
1310
+ * before any await, so it reliably indicates when we already own the handshake.
1311
+ *
1312
+ * For transport-initiated reconnects, `_connectPromise` is set so that
1313
+ * concurrent `connect()` or `ensureSession()` callers coalesce on the
1314
+ * in-flight handshake rather than initiating a second one.
1315
+ */
1316
+ onTransportConnected() {
1317
+ if (this._handshaking) return;
1318
+ this._handshaking = true;
1319
+ const doHandshake = /* @__PURE__ */ __name(async () => {
1320
+ try {
1321
+ await this._runHandshake();
1322
+ } catch (error) {
1323
+ this.emit("error", error instanceof Error ? error : new Error(String(error)));
1324
+ } finally {
1325
+ this._handshaking = false;
1326
+ this._connectPromise = null;
1327
+ }
1328
+ }, "doHandshake");
1329
+ this._connectPromise = doHandshake();
1330
+ }
1331
+ onTransportDisconnected() {
1332
+ const intentional = this._disconnectedIntentionally;
1333
+ this._disconnectedIntentionally = false;
1334
+ this.session?.dispose();
1335
+ this.session = null;
1336
+ if (!intentional) {
1337
+ this.logger.warn("Unexpected WebSocket disconnect");
1338
+ }
1339
+ this.emit("disconnected");
1340
+ }
1341
+ };
1342
+
1343
+ // src/client-v2/utils.ts
1344
+ function deepEqual(obj1, obj2) {
1345
+ if (obj1 === obj2) return true;
1346
+ if (typeof obj1 !== "object" || obj1 === null || typeof obj2 !== "object" || obj2 === null) {
1347
+ return false;
1348
+ }
1349
+ const keys1 = Object.keys(obj1);
1350
+ const keys2 = Object.keys(obj2);
1351
+ if (keys1.length !== keys2.length) return false;
1352
+ for (const key of keys1) {
1353
+ if (!keys2.includes(key) || !deepEqual(obj1[key], obj2[key])) {
1354
+ return false;
1355
+ }
1356
+ }
1357
+ return true;
1358
+ }
1359
+ __name(deepEqual, "deepEqual");
1360
+
1361
+ // src/client-v2/singleton.ts
1362
+ var ForwardMPCClientSingleton = class _ForwardMPCClientSingleton extends ForwardMPCClientV2 {
1363
+ static {
1364
+ __name(this, "ForwardMPCClientSingleton");
1365
+ }
1366
+ static _instance = null;
1367
+ constructor(url, options) {
1368
+ const existing = _ForwardMPCClientSingleton._instance;
1369
+ if (existing !== null) {
1370
+ if (existing.url !== url) {
1371
+ throw new Error(`ForwardMPCClientSingleton already exists for "${existing.url}". Call disconnect() first to create a new instance.`);
1372
+ }
1373
+ if (!deepEqual(options, existing.options)) {
1374
+ throw new Error(`ForwardMPCClientSingleton already exists for the same URL but with different options.Call disconnect() first to create a new instance.`);
1375
+ }
1376
+ return existing;
1377
+ }
1378
+ super(url, options);
1379
+ _ForwardMPCClientSingleton._instance = this;
1380
+ }
1381
+ disconnect() {
1382
+ super.disconnect();
1383
+ if (_ForwardMPCClientSingleton._instance === this) {
1384
+ _ForwardMPCClientSingleton._instance = null;
1385
+ }
1386
+ }
1387
+ };
1388
+
1389
+ export { ClientError, ClientSessionEstablishFailedError, ClientUnsupportedAlgorithmError, ErrorCode, ForwardMPCClient, ForwardMPCClientSingleton, ForwardMPCClientV2, ForwardMPCError, ForwardMPCErrorType, NitroAttestationVerifier, SessionAttestationError, SessionAttestationNonceMissingError, SessionDisposedError, SessionError, SessionHandshakeError, SessionHandshakeInvalidResponseError, SessionMessageParseError, SessionRemoteError, SessionRequestTimeoutError, SessionServerError, TransportConnectionError, TransportConnectionTimeoutError, TransportError, TransportNotConnectedError };
507
1390
  //# sourceMappingURL=index.js.map
508
1391
  //# sourceMappingURL=index.js.map