@dynamic-labs-wallet/browser 1.0.80 → 1.0.82

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/index.esm.js CHANGED
@@ -1,4 +1,4 @@
1
- import { BitcoinAddressType, MPC_RELAY_PROD_API_URL, getMPCChainConfig, BackupLocation, ENCRYPTED_SHARES_STORAGE_SUFFIX, Logger, WalletApiError, handleAxiosError, WalletOperation, parseNamespacedVersion, WalletReadyState, classifyForwardMpcError, isRecoveredForwardMpcConnectionChurn, FEATURE_FLAGS, ThresholdSignatureScheme, getClientThreshold, MPC_CONFIG, getTSSConfig, serializeMessageForForwardMPC, isEvmCompatibleChain, serializeError, getReshareConfig, getRequiredExternalKeyShareId, verifiedCredentialNameToChainEnum, AuthMode, NoopLogger, DynamicApiClient, BusinessAccountClient, getEnvironmentFromUrl, IFRAME_DOMAIN_MAP } from '@dynamic-labs-wallet/core';
1
+ import { BitcoinAddressType, MPC_RELAY_PROD_API_URL, getMPCChainConfig, parseNamespacedVersion, WalletApiError, BackupLocation, ENCRYPTED_SHARES_STORAGE_SUFFIX, Logger, handleAxiosError, WalletOperation, WalletReadyState, classifyForwardMpcError, isRecoveredForwardMpcConnectionChurn, FEATURE_FLAGS, ThresholdSignatureScheme, getClientThreshold, MPC_CONFIG, getTSSConfig, serializeMessageForForwardMPC, isEvmCompatibleChain, serializeError, getReshareConfig, getRequiredExternalKeyShareId, verifiedCredentialNameToChainEnum, AuthMode, NoopLogger, DynamicApiClient, BusinessAccountClient, getEnvironmentFromUrl, IFRAME_DOMAIN_MAP } from '@dynamic-labs-wallet/core';
2
2
  export * from '@dynamic-labs-wallet/core';
3
3
  export { Logger } from '@dynamic-labs-wallet/core';
4
4
  import { EdBls12377, BIP340, ExportableEd25519, Ecdsa, MessageHash, EcdsaSignature, EcdsaKeygenResult, ExportableEd25519KeygenResult, BIP340KeygenResult } from '#internal/web';
@@ -8,8 +8,8 @@ import { SigningAlgorithm } from '@dynamic-labs-wallet/primitives';
8
8
  import { ProviderEnum, RoomTypeEnum } from '@dynamic-labs/sdk-api-core';
9
9
  import loadArgon2idWasm from 'argon2id';
10
10
  import { AxiosError } from 'axios';
11
- import PQueue from 'p-queue';
12
11
  import gte from 'semver/functions/gte';
12
+ import PQueue from 'p-queue';
13
13
 
14
14
  function _extends() {
15
15
  _extends = Object.assign || function assign(target) {
@@ -464,6 +464,237 @@ class EncryptionSelfTestFailedError extends Error {
464
464
  }
465
465
  }
466
466
 
467
+ /**
468
+ * Extracts the HTTP status from an `AxiosError`, or `undefined` for non-HTTP
469
+ * errors. Lives in its own leaf module (no `#internal/web` / WASM imports) so
470
+ * lightweight consumers like `services/signedSession.ts` can use it without
471
+ * pulling the MPC WASM bundle that `utils.ts` loads.
472
+ */ const getHttpStatus = (error)=>{
473
+ var _error_response;
474
+ return error instanceof AxiosError ? (_error_response = error.response) == null ? void 0 : _error_response.status : undefined;
475
+ };
476
+
477
+ const STORAGE_KEY = 'dynamic-waas-wallet-client';
478
+ const BACKUP_FILENAME = 'dynamicWalletKeyShareBackup.json';
479
+ const CLIENT_KEYSHARE_EXPORT_FILENAME_PREFIX = 'dynamicWalletKeyShareBackup';
480
+ const SIGNED_SESSION_ID_MIN_VERSION = '4.25.4';
481
+ // Namespace-specific version requirements
482
+ const SIGNED_SESSION_ID_MIN_VERSION_BY_NAMESPACE = {
483
+ WalletKit: '4.25.4',
484
+ ClientSDK: '0.1.0-alpha.0'
485
+ };
486
+ // Minimum SDK version that forwards `getSignedSessionId` to the iframe's postMessage
487
+ // reverse channel, distinct from SIGNED_SESSION_ID_MIN_VERSION above (which only
488
+ // gates whether a signed session value is sent at all).
489
+ // WalletKit: dynamic-auth#10577 (v4.74.0). ClientSDK: dynamic-js-sdk#1937 (v1.12.1).
490
+ const SIGNED_SESSION_REVERSE_CHANNEL_MIN_VERSION = '4.74.0';
491
+ const SIGNED_SESSION_REVERSE_CHANNEL_MIN_VERSION_BY_NAMESPACE = {
492
+ WalletKit: SIGNED_SESSION_REVERSE_CHANNEL_MIN_VERSION,
493
+ ClientSDK: '1.12.1'
494
+ };
495
+ const ROOM_EXPIRATION_TIME = 1000 * 60 * 10; // 10 minutes
496
+ const ROOM_CACHE_COUNT = 5;
497
+ const ENVIRONMENT_SETTINGS_STORAGE_KEY = 'dynamic_environment_settings';
498
+
499
+ function meetsMinVersion(sdkVersion, { minVersionByNamespace, fallbackMinVersion, label }, logger) {
500
+ if (!sdkVersion) {
501
+ return false;
502
+ }
503
+ try {
504
+ const parsedVersion = parseNamespacedVersion(sdkVersion);
505
+ if (!parsedVersion) {
506
+ return false;
507
+ }
508
+ const { namespace, version } = parsedVersion;
509
+ var _minVersionByNamespace_namespace;
510
+ return gte(version, (_minVersionByNamespace_namespace = minVersionByNamespace[namespace]) != null ? _minVersionByNamespace_namespace : fallbackMinVersion);
511
+ } catch (error) {
512
+ logger.warn(`[DynamicWaasWalletClient] Error checking ${label} for version ${sdkVersion}`, {
513
+ error: error instanceof Error ? error.message : String(error)
514
+ });
515
+ return false;
516
+ }
517
+ }
518
+ /** Whether the given SDK version requires a signed session ID to be sent at all. */ function isRequiresSignedSessionId(sdkVersion, logger) {
519
+ return meetsMinVersion(sdkVersion, {
520
+ minVersionByNamespace: SIGNED_SESSION_ID_MIN_VERSION_BY_NAMESPACE,
521
+ fallbackMinVersion: SIGNED_SESSION_ID_MIN_VERSION,
522
+ label: 'requiresSignedSessionId'
523
+ }, logger);
524
+ }
525
+ /**
526
+ * Whether the SDK version is known to forward `getSignedSessionId` to the iframe's
527
+ * postMessage reverse channel — stricter than {@link isRequiresSignedSessionId},
528
+ * which only checks whether a session value is sent at all.
529
+ */ function isReverseChannelSupported(sdkVersion, logger) {
530
+ return meetsMinVersion(sdkVersion, {
531
+ minVersionByNamespace: SIGNED_SESSION_REVERSE_CHANNEL_MIN_VERSION_BY_NAMESPACE,
532
+ fallbackMinVersion: SIGNED_SESSION_REVERSE_CHANNEL_MIN_VERSION,
533
+ label: 'supportsReverseChannel'
534
+ }, logger);
535
+ }
536
+
537
+ /**
538
+ * Datadog event name emitted on every signed-session nonce rejection (a 400 or
539
+ * 401 from the backup/recovery endpoints). Log-only: lets us split the failure
540
+ * bucket by `reason` and measure the true per-wallet unrecoverable rate
541
+ * without changing any retry behavior. See DYNT-1599.
542
+ */ const NONCE_FAILURE_EVENT = 'waas.signed_session.nonce_failure';
543
+ /**
544
+ * Reasons that represent a genuine session-key signature mismatch (the 401 the
545
+ * server returns per DYNT-1282). Used to gate 401 instrumentation so callers
546
+ * that reuse 401 for unrelated rejections don't pollute the failure metric.
547
+ */ const SESSION_SIGNATURE_FAILURE_REASONS = new Set([
548
+ 'invalid_nonce_signature',
549
+ 'invalid_session_signature'
550
+ ]);
551
+ /** Best-effort extraction of the server error `code`/`message` from a 4xx body. */ const readErrorBody = (error)=>{
552
+ var _error_response;
553
+ if (!(error instanceof AxiosError)) {
554
+ return {};
555
+ }
556
+ const data = (_error_response = error.response) == null ? void 0 : _error_response.data;
557
+ if (typeof data === 'string') {
558
+ return {
559
+ message: data
560
+ };
561
+ }
562
+ if (!data || typeof data !== 'object') {
563
+ return {};
564
+ }
565
+ const record = data;
566
+ // Prefer a string `code`, else fall back to `error_code` (the field the Key
567
+ // Share Service emits, see KSS #271) or a bare `error`.
568
+ const code = [
569
+ record['code'],
570
+ record['error_code'],
571
+ record['error']
572
+ ].find((value)=>typeof value === 'string');
573
+ const message = typeof record['message'] === 'string' ? record['message'] : undefined;
574
+ return {
575
+ code,
576
+ message
577
+ };
578
+ };
579
+ /** Maps the server error `code`/`message` onto a {@link NonceFailureReason}. */ const classifyNonceFailure = ({ code, message })=>{
580
+ const haystack = `${code != null ? code : ''} ${message != null ? message : ''}`.toLowerCase();
581
+ if (haystack.includes('already_used') || haystack.includes('already used') || haystack.includes('consumption failed')) {
582
+ return 'nonce_already_used';
583
+ }
584
+ if (haystack.includes('invalid_nonce_signature') || haystack.includes('invalid nonce signature')) {
585
+ return 'invalid_nonce_signature';
586
+ }
587
+ if (haystack.includes('invalid_session_signature') || haystack.includes('invalid session public key') || haystack.includes('invalid session signature')) {
588
+ return 'invalid_session_signature';
589
+ }
590
+ return 'other';
591
+ };
592
+ /**
593
+ * Owns everything about signed sessions and their single-use replay nonces:
594
+ * resolving a session from an explicit value or the host reverse channel,
595
+ * deciding whether the SDK version requires one, and building the
596
+ * refresh-on-replay-400 retry predicate shared by the backup and recovery
597
+ * flows.
598
+ *
599
+ * Extracted from `DynamicWalletClient` so this logic can be exercised in
600
+ * isolation. The host callback is read lazily (`getCallback`) so it stays in
601
+ * sync with the owning client even if reassigned after construction.
602
+ */ class SignedSessionManager {
603
+ /** True when a reverse channel is configured to mint fresh signed sessions. */ get canRefresh() {
604
+ return this.getCallback() !== undefined;
605
+ }
606
+ /**
607
+ * Resolves the signed session ID from an explicit value or falls back to the
608
+ * host reverse channel. Throws if neither source provides a value.
609
+ */ async resolve(signedSessionId) {
610
+ const callback = this.getCallback();
611
+ const resolved = signedSessionId != null ? signedSessionId : await (callback == null ? void 0 : callback());
612
+ if (!resolved) {
613
+ throw new Error(signedSessionId === undefined && callback ? 'signedSessionId callback returned an invalid value' : 'signedSessionId is required for backup but was not provided and no callback is configured');
614
+ }
615
+ return resolved;
616
+ }
617
+ /** Whether the configured SDK version requires a signed session ID. */ isRequired() {
618
+ return this.required;
619
+ }
620
+ /** Whether the host SDK version supports the getSignedSessionId reverse channel (see version-check.ts). */ supportsReverseChannel() {
621
+ return this.reverseChannelSupported;
622
+ }
623
+ /**
624
+ * Builds a `retryPromise` `shouldRetry` predicate that refreshes a consumed
625
+ * single-use nonce via the reverse channel on a replay 400 and retries once.
626
+ * The signed session carries a single-use replay nonce: it is valid on its
627
+ * first use, but once consumed (e.g. by a preceding operation) the server
628
+ * rejects with a 400, at which point a fresh session is fetched and the call
629
+ * retried. `alsoRetry` lets callers opt into additional retryable statuses
630
+ * (e.g. 429 / 5xx) on top of the nonce refresh.
631
+ */ refreshShouldRetry({ onRefreshed, operationName, logContext, alsoRetry }) {
632
+ return async (error, attempt)=>{
633
+ const status = getHttpStatus(error);
634
+ // A 400 is a refreshable replay nonce; a 401 is a session-key mismatch the
635
+ // server returns to break the refresh loop (DYNT-1282) — logged only when the
636
+ // body classifies as a genuine session-signature failure so unrelated 401s
637
+ // (e.g. an exhausted add-signer grant) don't pollute the DYNT-1599 metric.
638
+ // Only the 400 can actually refresh.
639
+ const isSessionSignatureFailure = status === 401 && SESSION_SIGNATURE_FAILURE_REASONS.has(classifyNonceFailure(readErrorBody(error)));
640
+ const shouldInstrument = status === 400 || isSessionSignatureFailure;
641
+ if (shouldInstrument) {
642
+ const willRefresh = status === 400 && attempt === 1 && this.canRefresh && this.supportsReverseChannel();
643
+ this.instrumentNonceFailure({
644
+ error,
645
+ attempt,
646
+ status,
647
+ operationName,
648
+ willRefresh,
649
+ logContext
650
+ });
651
+ }
652
+ if (status === 400 && attempt === 1 && this.canRefresh) {
653
+ // canRefresh only proves a local callback exists, not that the host answers it.
654
+ if (!this.supportsReverseChannel()) {
655
+ this.logger.warn(`[${operationName}] host SDK version predates the signed-session reverse channel, declining nonce refresh`, _extends({
656
+ status
657
+ }, logContext));
658
+ return alsoRetry ? alsoRetry(status) : false;
659
+ }
660
+ onRefreshed(await this.resolve());
661
+ this.logger.info(`[${operationName}] refreshed signed session, retrying`, _extends({
662
+ status
663
+ }, logContext));
664
+ return true;
665
+ }
666
+ return alsoRetry ? alsoRetry(status) : false;
667
+ };
668
+ }
669
+ /**
670
+ * Emits a single Datadog log per signed-session nonce rejection so the
671
+ * failure bucket can be split by `reason` and correlated per wallet/request.
672
+ * Purely observational — it never alters the retry decision.
673
+ */ instrumentNonceFailure({ error, attempt, status, operationName, willRefresh, logContext }) {
674
+ const body = readErrorBody(error);
675
+ this.logger.info(NONCE_FAILURE_EVENT, _extends({}, logContext, {
676
+ operationName,
677
+ attempt,
678
+ status,
679
+ reason: classifyNonceFailure(body),
680
+ errorCode: body.code,
681
+ errorMessage: body.message,
682
+ willRefresh,
683
+ canRefresh: this.canRefresh,
684
+ reverseChannelSupported: this.reverseChannelSupported,
685
+ required: this.required,
686
+ sdkVersion: this.sdkVersion
687
+ }));
688
+ }
689
+ constructor({ logger, sdkVersion, getCallback }){
690
+ this.logger = logger;
691
+ this.getCallback = getCallback;
692
+ this.sdkVersion = sdkVersion;
693
+ this.required = isRequiresSignedSessionId(sdkVersion, this.logger);
694
+ this.reverseChannelSupported = isReverseChannelSupported(sdkVersion, this.logger);
695
+ }
696
+ }
697
+
467
698
  const ERROR_NO_KEY_SHARES_BACKED_UP = 'No key shares were backed up to Dynamic backend';
468
699
  const ERROR_KEYGEN_FAILED = '[DynamicWaasWalletClient]: Error with keygen';
469
700
  const ERROR_CREATE_WALLET_ACCOUNT = '[DynamicWaasWalletClient]: Error creating wallet account';
@@ -556,6 +787,10 @@ const ERROR_WALLETS_ALREADY_ENCRYPTED = '[DynamicWaasWalletClient]: Cannot set p
556
787
  */ const USER_ACTIONABLE_PASSWORD_BACKUP_ERROR_REASONS = {
557
788
  wrong_password: true,
558
789
  stale_local_shares: false,
790
+ nonce_already_used: false,
791
+ invalid_nonce_signature: false,
792
+ invalid_session_signature: false,
793
+ signed_session: false,
559
794
  encryption_failure: false,
560
795
  decryption_failure: false,
561
796
  upload_failure: false,
@@ -578,6 +813,30 @@ const FETCH_NETWORK_ERROR_REGEX = /failed to fetch|networkerror|load failed|netw
578
813
  const ENCRYPTION_FAILURE_MESSAGE_PREFIX = 'Error encrypting data:';
579
814
  const DECRYPTION_FAILURE_MESSAGE_PREFIX = 'Decryption failed:';
580
815
  const isStaleSharesError = (error)=>error instanceof StaleLocalSharesError || error instanceof Error && error.name === 'StaleLocalSharesError';
816
+ // The backup/recovery endpoints reject the chaining signature with a 400
817
+ // (stale signed session / replay nonce) or 401 (session-key mismatch,
818
+ // DYNT-1282); the preserved backend code splits those into their precise
819
+ // cause so the failure is actionable instead of a generic `unknown`.
820
+ const SIGNED_SESSION_FAILURE_STATUSES = new Set([
821
+ 400,
822
+ 401
823
+ ]);
824
+ const NONCE_REASON_TO_BACKUP_REASON = {
825
+ nonce_already_used: 'nonce_already_used',
826
+ invalid_nonce_signature: 'invalid_nonce_signature',
827
+ invalid_session_signature: 'invalid_session_signature',
828
+ other: 'signed_session'
829
+ };
830
+ const classifyWalletApiError = (error)=>{
831
+ if (!SIGNED_SESSION_FAILURE_STATUSES.has(error.status)) {
832
+ return 'upload_failure';
833
+ }
834
+ const nonceReason = classifyNonceFailure({
835
+ code: error.code,
836
+ message: error.message
837
+ });
838
+ return NONCE_REASON_TO_BACKUP_REASON[nonceReason];
839
+ };
581
840
  const isNetworkLikeError = (error)=>{
582
841
  if (typeof error !== 'object' || error === null) {
583
842
  return false;
@@ -629,6 +888,12 @@ const computeReason = (error)=>{
629
888
  if (isStaleSharesError(error)) {
630
889
  return 'stale_local_shares';
631
890
  }
891
+ // WalletApiError is a wrapped HTTP failure carrying the resolved status; its
892
+ // message is a generic status string ('Invalid request', etc.) so classify
893
+ // by status ahead of the message-based checks below.
894
+ if (error instanceof WalletApiError) {
895
+ return classifyWalletApiError(error);
896
+ }
632
897
  if (error instanceof Error) {
633
898
  if (error.message.includes(ERROR_PASSWORD_MISMATCH) || error.message.includes(ERROR_INCORRECT_PASSWORD)) {
634
899
  return 'wrong_password';
@@ -996,38 +1261,6 @@ const downloadFileFromGoogleDrive = async ({ accessToken, fileName })=>{
996
1261
  }
997
1262
  };
998
1263
 
999
- /**
1000
- * Extracts the HTTP status from an `AxiosError`, or `undefined` for non-HTTP
1001
- * errors. Lives in its own leaf module (no `#internal/web` / WASM imports) so
1002
- * lightweight consumers like `services/signedSession.ts` can use it without
1003
- * pulling the MPC WASM bundle that `utils.ts` loads.
1004
- */ const getHttpStatus = (error)=>{
1005
- var _error_response;
1006
- return error instanceof AxiosError ? (_error_response = error.response) == null ? void 0 : _error_response.status : undefined;
1007
- };
1008
-
1009
- const STORAGE_KEY = 'dynamic-waas-wallet-client';
1010
- const BACKUP_FILENAME = 'dynamicWalletKeyShareBackup.json';
1011
- const CLIENT_KEYSHARE_EXPORT_FILENAME_PREFIX = 'dynamicWalletKeyShareBackup';
1012
- const SIGNED_SESSION_ID_MIN_VERSION = '4.25.4';
1013
- // Namespace-specific version requirements
1014
- const SIGNED_SESSION_ID_MIN_VERSION_BY_NAMESPACE = {
1015
- WalletKit: '4.25.4',
1016
- ClientSDK: '0.1.0-alpha.0'
1017
- };
1018
- // Minimum SDK version that forwards `getSignedSessionId` to the iframe's postMessage
1019
- // reverse channel, distinct from SIGNED_SESSION_ID_MIN_VERSION above (which only
1020
- // gates whether a signed session value is sent at all).
1021
- // WalletKit: dynamic-auth#10577 (v4.74.0). ClientSDK: dynamic-js-sdk#1937 (v1.12.1).
1022
- const SIGNED_SESSION_REVERSE_CHANNEL_MIN_VERSION = '4.74.0';
1023
- const SIGNED_SESSION_REVERSE_CHANNEL_MIN_VERSION_BY_NAMESPACE = {
1024
- WalletKit: SIGNED_SESSION_REVERSE_CHANNEL_MIN_VERSION,
1025
- ClientSDK: '1.12.1'
1026
- };
1027
- const ROOM_EXPIRATION_TIME = 1000 * 60 * 10; // 10 minutes
1028
- const ROOM_CACHE_COUNT = 5;
1029
- const ENVIRONMENT_SETTINGS_STORAGE_KEY = 'dynamic_environment_settings';
1030
-
1031
1264
  /**
1032
1265
  * Normalizes an address to lowercase for consistent map key lookups.
1033
1266
  * This ensures that addresses with different casing (e.g., EIP-55 checksummed vs lowercase)
@@ -2413,6 +2646,22 @@ const createDynamicOnlyDistribution = ({ allShares })=>({
2413
2646
  /** Track which wallets are currently executing inside a sign operation.
2414
2647
  * Used to prevent deadlocks when recovery is called from within a sign op. */ WalletQueueManager.walletsWithActiveSignOp = new Map();
2415
2648
 
2649
+ // A DYNAMIC backup can persist multiple shares (e.g. 2-of-3); the singular
2650
+ // externalKeyShareId is a fallback for older single-id shapes.
2651
+ const collectDynamicKeyShareIds = (locations)=>{
2652
+ return locations.filter((loc)=>loc.location === BackupLocation.DYNAMIC).flatMap((loc)=>{
2653
+ if (loc.externalKeyShareIds && loc.externalKeyShareIds.length > 0) {
2654
+ return loc.externalKeyShareIds;
2655
+ }
2656
+ if (loc.externalKeyShareId) {
2657
+ return [
2658
+ loc.externalKeyShareId
2659
+ ];
2660
+ }
2661
+ return [];
2662
+ });
2663
+ };
2664
+
2416
2665
  // Pure routing helper: maps a completed reshare ceremony's results into the
2417
2666
  // ShareDistribution that storage/publish should follow. Lives outside the
2418
2667
  // client class so it's straightforward to reason about and unit-test
@@ -2613,184 +2862,6 @@ const readEnvironmentSettings = ()=>{
2613
2862
  }
2614
2863
  });
2615
2864
 
2616
- function meetsMinVersion(sdkVersion, { minVersionByNamespace, fallbackMinVersion, label }, logger) {
2617
- if (!sdkVersion) {
2618
- return false;
2619
- }
2620
- try {
2621
- const parsedVersion = parseNamespacedVersion(sdkVersion);
2622
- if (!parsedVersion) {
2623
- return false;
2624
- }
2625
- const { namespace, version } = parsedVersion;
2626
- var _minVersionByNamespace_namespace;
2627
- return gte(version, (_minVersionByNamespace_namespace = minVersionByNamespace[namespace]) != null ? _minVersionByNamespace_namespace : fallbackMinVersion);
2628
- } catch (error) {
2629
- logger.warn(`[DynamicWaasWalletClient] Error checking ${label} for version ${sdkVersion}`, {
2630
- error: error instanceof Error ? error.message : String(error)
2631
- });
2632
- return false;
2633
- }
2634
- }
2635
- /** Whether the given SDK version requires a signed session ID to be sent at all. */ function isRequiresSignedSessionId(sdkVersion, logger) {
2636
- return meetsMinVersion(sdkVersion, {
2637
- minVersionByNamespace: SIGNED_SESSION_ID_MIN_VERSION_BY_NAMESPACE,
2638
- fallbackMinVersion: SIGNED_SESSION_ID_MIN_VERSION,
2639
- label: 'requiresSignedSessionId'
2640
- }, logger);
2641
- }
2642
- /**
2643
- * Whether the SDK version is known to forward `getSignedSessionId` to the iframe's
2644
- * postMessage reverse channel — stricter than {@link isRequiresSignedSessionId},
2645
- * which only checks whether a session value is sent at all.
2646
- */ function isReverseChannelSupported(sdkVersion, logger) {
2647
- return meetsMinVersion(sdkVersion, {
2648
- minVersionByNamespace: SIGNED_SESSION_REVERSE_CHANNEL_MIN_VERSION_BY_NAMESPACE,
2649
- fallbackMinVersion: SIGNED_SESSION_REVERSE_CHANNEL_MIN_VERSION,
2650
- label: 'supportsReverseChannel'
2651
- }, logger);
2652
- }
2653
-
2654
- /**
2655
- * Datadog event name emitted on every signed-session nonce rejection (a 400
2656
- * from the backup/recovery endpoints). Log-only: lets us split the failure
2657
- * bucket by `reason` and measure the true per-wallet unrecoverable rate
2658
- * without changing any retry behavior. See DYNT-1599.
2659
- */ const NONCE_FAILURE_EVENT = 'waas.signed_session.nonce_failure';
2660
- /** Best-effort extraction of the server error `code`/`message` from a 400 body. */ const readErrorBody = (error)=>{
2661
- var _error_response;
2662
- if (!(error instanceof AxiosError)) {
2663
- return {};
2664
- }
2665
- const data = (_error_response = error.response) == null ? void 0 : _error_response.data;
2666
- if (typeof data === 'string') {
2667
- return {
2668
- message: data
2669
- };
2670
- }
2671
- if (!data || typeof data !== 'object') {
2672
- return {};
2673
- }
2674
- const record = data;
2675
- // Prefer a string `code`, else fall back to a string `error`.
2676
- const code = [
2677
- record['code'],
2678
- record['error']
2679
- ].find((value)=>typeof value === 'string');
2680
- const message = typeof record['message'] === 'string' ? record['message'] : undefined;
2681
- return {
2682
- code,
2683
- message
2684
- };
2685
- };
2686
- /** Maps the server error `code`/`message` onto a {@link NonceFailureReason}. */ const classifyNonceFailure = ({ code, message })=>{
2687
- const haystack = `${code != null ? code : ''} ${message != null ? message : ''}`.toLowerCase();
2688
- if (haystack.includes('already_used') || haystack.includes('already used') || haystack.includes('consumption failed')) {
2689
- return 'nonce_already_used';
2690
- }
2691
- if (haystack.includes('invalid_nonce_signature') || haystack.includes('invalid nonce signature')) {
2692
- return 'invalid_nonce_signature';
2693
- }
2694
- return 'other';
2695
- };
2696
- /**
2697
- * Owns everything about signed sessions and their single-use replay nonces:
2698
- * resolving a session from an explicit value or the host reverse channel,
2699
- * deciding whether the SDK version requires one, and building the
2700
- * refresh-on-replay-400 retry predicate shared by the backup and recovery
2701
- * flows.
2702
- *
2703
- * Extracted from `DynamicWalletClient` so this logic can be exercised in
2704
- * isolation. The host callback is read lazily (`getCallback`) so it stays in
2705
- * sync with the owning client even if reassigned after construction.
2706
- */ class SignedSessionManager {
2707
- /** True when a reverse channel is configured to mint fresh signed sessions. */ get canRefresh() {
2708
- return this.getCallback() !== undefined;
2709
- }
2710
- /**
2711
- * Resolves the signed session ID from an explicit value or falls back to the
2712
- * host reverse channel. Throws if neither source provides a value.
2713
- */ async resolve(signedSessionId) {
2714
- const callback = this.getCallback();
2715
- const resolved = signedSessionId != null ? signedSessionId : await (callback == null ? void 0 : callback());
2716
- if (!resolved) {
2717
- throw new Error(signedSessionId === undefined && callback ? 'signedSessionId callback returned an invalid value' : 'signedSessionId is required for backup but was not provided and no callback is configured');
2718
- }
2719
- return resolved;
2720
- }
2721
- /** Whether the configured SDK version requires a signed session ID. */ isRequired() {
2722
- return this.required;
2723
- }
2724
- /** Whether the host SDK version supports the getSignedSessionId reverse channel (see version-check.ts). */ supportsReverseChannel() {
2725
- return this.reverseChannelSupported;
2726
- }
2727
- /**
2728
- * Builds a `retryPromise` `shouldRetry` predicate that refreshes a consumed
2729
- * single-use nonce via the reverse channel on a replay 400 and retries once.
2730
- * The signed session carries a single-use replay nonce: it is valid on its
2731
- * first use, but once consumed (e.g. by a preceding operation) the server
2732
- * rejects with a 400, at which point a fresh session is fetched and the call
2733
- * retried. `alsoRetry` lets callers opt into additional retryable statuses
2734
- * (e.g. 429 / 5xx) on top of the nonce refresh.
2735
- */ refreshShouldRetry({ onRefreshed, operationName, logContext, alsoRetry }) {
2736
- return async (error, attempt)=>{
2737
- const status = getHttpStatus(error);
2738
- if (status === 400) {
2739
- const willRefresh = attempt === 1 && this.canRefresh && this.supportsReverseChannel();
2740
- this.instrumentNonceFailure({
2741
- error,
2742
- attempt,
2743
- operationName,
2744
- willRefresh,
2745
- logContext
2746
- });
2747
- if (attempt === 1 && this.canRefresh) {
2748
- // canRefresh only proves a local callback exists, not that the host answers it.
2749
- if (!this.supportsReverseChannel()) {
2750
- this.logger.warn(`[${operationName}] host SDK version predates the signed-session reverse channel, declining nonce refresh`, _extends({
2751
- status
2752
- }, logContext));
2753
- return alsoRetry ? alsoRetry(status) : false;
2754
- }
2755
- onRefreshed(await this.resolve());
2756
- this.logger.info(`[${operationName}] refreshed signed session, retrying`, _extends({
2757
- status
2758
- }, logContext));
2759
- return true;
2760
- }
2761
- }
2762
- return alsoRetry ? alsoRetry(status) : false;
2763
- };
2764
- }
2765
- /**
2766
- * Emits a single Datadog log per signed-session nonce rejection so the
2767
- * failure bucket can be split by `reason` and correlated per wallet/request.
2768
- * Purely observational — it never alters the retry decision.
2769
- */ instrumentNonceFailure({ error, attempt, operationName, willRefresh, logContext }) {
2770
- const body = readErrorBody(error);
2771
- this.logger.info(NONCE_FAILURE_EVENT, _extends({}, logContext, {
2772
- operationName,
2773
- attempt,
2774
- status: 400,
2775
- reason: classifyNonceFailure(body),
2776
- errorCode: body.code,
2777
- errorMessage: body.message,
2778
- willRefresh,
2779
- canRefresh: this.canRefresh,
2780
- reverseChannelSupported: this.reverseChannelSupported,
2781
- required: this.required,
2782
- sdkVersion: this.sdkVersion
2783
- }));
2784
- }
2785
- constructor({ logger, sdkVersion, getCallback }){
2786
- this.logger = logger;
2787
- this.getCallback = getCallback;
2788
- this.sdkVersion = sdkVersion;
2789
- this.required = isRequiresSignedSessionId(sdkVersion, this.logger);
2790
- this.reverseChannelSupported = isReverseChannelSupported(sdkVersion, this.logger);
2791
- }
2792
- }
2793
-
2794
2865
  /**
2795
2866
  * Determines the recovery state of a wallet based on backup info and local shares.
2796
2867
  *
@@ -6352,6 +6423,7 @@ class DynamicWalletClient {
6352
6423
  return {
6353
6424
  location: BackupLocation.DYNAMIC,
6354
6425
  externalKeyShareId: data.keyShareIds[0],
6426
+ externalKeyShareIds: data.keyShareIds,
6355
6427
  passwordEncrypted: isPasswordEncrypted,
6356
6428
  keygenId
6357
6429
  };
@@ -6648,7 +6720,7 @@ class DynamicWalletClient {
6648
6720
  // aborts the backup before activation, so an unrecoverable share is never
6649
6721
  // marked active; the local share is never touched.
6650
6722
  if (this.featureFlags[FEATURE_FLAGS.VERIFY_BACKUP_RECOVERABILITY_FLAG] === true) {
6651
- const dynamicKeyShareIds = locations.filter((loc)=>loc.location === BackupLocation.DYNAMIC && loc.externalKeyShareId).map((loc)=>loc.externalKeyShareId);
6723
+ const dynamicKeyShareIds = collectDynamicKeyShareIds(locations);
6652
6724
  await this.assertServerCopyRecoverable({
6653
6725
  walletId: walletData.walletId,
6654
6726
  shareSetId: targetShareSetId,
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@dynamic-labs-wallet/browser",
3
- "version": "1.0.80",
3
+ "version": "1.0.82",
4
4
  "license": "Licensed under the Dynamic Labs, Inc. Terms Of Service (https://www.dynamic.xyz/terms-conditions)",
5
5
  "type": "module",
6
6
  "dependencies": {
7
- "@dynamic-labs-wallet/core": "1.0.80",
7
+ "@dynamic-labs-wallet/core": "1.0.82",
8
8
  "@dynamic-labs-wallet/forward-mpc-client": "1.0.1",
9
- "@dynamic-labs-wallet/primitives": "1.0.80",
9
+ "@dynamic-labs-wallet/primitives": "1.0.82",
10
10
  "@dynamic-labs/sdk-api-core": "^0.0.1083",
11
11
  "argon2id": "1.0.1",
12
12
  "axios": "1.16.0",
@@ -11,7 +11,7 @@ export type PasswordOperation = 'setPassword' | 'updatePassword' | 'unlockWallet
11
11
  * Mirrors the convention established by GoogleDriveBackupErrorReason
12
12
  * (backup/providers/googleDrive.ts) — see PR #958.
13
13
  */
14
- export type PasswordBackupErrorReason = 'wrong_password' | 'stale_local_shares' | 'encryption_failure' | 'decryption_failure' | 'upload_failure' | 'activation_failure' | 'already_encrypted' | 'network' | 'unknown';
14
+ export type PasswordBackupErrorReason = 'wrong_password' | 'stale_local_shares' | 'nonce_already_used' | 'invalid_nonce_signature' | 'invalid_session_signature' | 'signed_session' | 'encryption_failure' | 'decryption_failure' | 'upload_failure' | 'activation_failure' | 'already_encrypted' | 'network' | 'unknown';
15
15
  /**
16
16
  * Failures classified as user-actionable are caused by end-user input or
17
17
  * local state and are not actionable by oncall. They are emitted at log
@@ -26,6 +26,10 @@ export type PasswordBackupErrorReason = 'wrong_password' | 'stale_local_shares'
26
26
  export declare const USER_ACTIONABLE_PASSWORD_BACKUP_ERROR_REASONS: {
27
27
  readonly wrong_password: true;
28
28
  readonly stale_local_shares: false;
29
+ readonly nonce_already_used: false;
30
+ readonly invalid_nonce_signature: false;
31
+ readonly invalid_session_signature: false;
32
+ readonly signed_session: false;
29
33
  readonly encryption_failure: false;
30
34
  readonly decryption_failure: false;
31
35
  readonly upload_failure: false;
@@ -1 +1 @@
1
- {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../../src/backup/password/errors.ts"],"names":[],"mappings":"AAUA;;;GAGG;AACH,MAAM,MAAM,iBAAiB,GAAG,aAAa,GAAG,gBAAgB,GAAG,cAAc,CAAC;AAElF;;;;;;;GAOG;AACH,MAAM,MAAM,yBAAyB,GACjC,gBAAgB,GAChB,oBAAoB,GACpB,oBAAoB,GACpB,oBAAoB,GACpB,gBAAgB,GAChB,oBAAoB,GACpB,mBAAmB,GACnB,SAAS,GACT,SAAS,CAAC;AAEd;;;;;;;;;;GAUG;AACH,eAAO,MAAM,6CAA6C;;;;;;;;;;CAUK,CAAC;AAEhE,eAAO,MAAM,yCAAyC,WAAY,yBAAyB,KAAG,OACvC,CAAC;AAmGxD;;;;;;;;;GASG;AACH,eAAO,MAAM,2BAA2B,UAAW,OAAO,KAAG,yBAM5D,CAAC"}
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../../src/backup/password/errors.ts"],"names":[],"mappings":"AAYA;;;GAGG;AACH,MAAM,MAAM,iBAAiB,GAAG,aAAa,GAAG,gBAAgB,GAAG,cAAc,CAAC;AAElF;;;;;;;GAOG;AACH,MAAM,MAAM,yBAAyB,GACjC,gBAAgB,GAChB,oBAAoB,GACpB,oBAAoB,GACpB,yBAAyB,GACzB,2BAA2B,GAC3B,gBAAgB,GAChB,oBAAoB,GACpB,oBAAoB,GACpB,gBAAgB,GAChB,oBAAoB,GACpB,mBAAmB,GACnB,SAAS,GACT,SAAS,CAAC;AAEd;;;;;;;;;;GAUG;AACH,eAAO,MAAM,6CAA6C;;;;;;;;;;;;;;CAcK,CAAC;AAEhE,eAAO,MAAM,yCAAyC,WAAY,yBAAyB,KAAG,OACvC,CAAC;AA8HxD;;;;;;;;;GASG;AACH,eAAO,MAAM,2BAA2B,UAAW,OAAO,KAAG,yBAM5D,CAAC"}