@dynamic-labs-wallet/browser 1.0.81 → 1.0.83

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)
@@ -1094,15 +1327,20 @@ const getClientKeyShareBackupInfo = (params)=>{
1094
1327
  const timeoutPromise = ({ timeInMs, activity = 'Ceremony' })=>{
1095
1328
  return new Promise((_, reject)=>setTimeout(()=>reject(new Error(`${activity} did not complete in ${timeInMs}ms`)), timeInMs));
1096
1329
  };
1097
- const buildErrorContext = (error)=>{
1098
- var _error_response, _error_response1;
1330
+ const buildAxiosErrorContext = (error)=>{
1331
+ var _error_response, _error_response1, _error_request, _error_config;
1332
+ var _error_response_status;
1099
1333
  return {
1100
- error: error instanceof Error ? error.message : 'Unknown error',
1101
- errorStack: error instanceof Error ? error.stack : undefined,
1102
- axiosError: error instanceof AxiosError ? (_error_response = error.response) == null ? void 0 : _error_response.data : undefined,
1103
- axiosStatus: error instanceof AxiosError ? (_error_response1 = error.response) == null ? void 0 : _error_response1.status : undefined
1334
+ axiosError: (_error_response = error.response) == null ? void 0 : _error_response.data,
1335
+ axiosStatus: (_error_response_status = (_error_response1 = error.response) == null ? void 0 : _error_response1.status) != null ? _error_response_status : (_error_request = error.request) == null ? void 0 : _error_request.status,
1336
+ axiosErrorCode: error.code,
1337
+ axiosUrl: (_error_config = error.config) == null ? void 0 : _error_config.url
1104
1338
  };
1105
1339
  };
1340
+ const buildErrorContext = (error)=>_extends({
1341
+ error: error instanceof Error ? error.message : 'Unknown error',
1342
+ errorStack: error instanceof Error ? error.stack : undefined
1343
+ }, error instanceof AxiosError && buildAxiosErrorContext(error));
1106
1344
  const logRetrySuccess = (operationName, attempts, logContext)=>{
1107
1345
  Logger.info(`Successfully executed ${operationName} after ${attempts + 1} attempts`, _extends({}, logContext, {
1108
1346
  attemptsTaken: attempts + 1
@@ -1134,6 +1372,7 @@ const logRetryExhausted = (operationName, maxAttempts, errorContext, logContext)
1134
1372
  */ async function retryPromise(operation, { maxAttempts = 5, retryInterval = 500, operationName = 'operation', logContext = {}, shouldRetry } = {}) {
1135
1373
  let attempts = 0;
1136
1374
  while(attempts < maxAttempts){
1375
+ const attemptStartMs = Date.now();
1137
1376
  try {
1138
1377
  const result = await operation();
1139
1378
  if (attempts > 0) {
@@ -1144,9 +1383,12 @@ const logRetryExhausted = (operationName, maxAttempts, errorContext, logContext)
1144
1383
  attempts++;
1145
1384
  const errorContext = buildErrorContext(error);
1146
1385
  const isNonRetryable = (error == null ? void 0 : error.isRetryable) === false;
1147
- logRetryFailure(operationName, attempts, maxAttempts, errorContext, logContext, isNonRetryable);
1386
+ const attemptLogContext = _extends({}, logContext, {
1387
+ requestDurationMs: Date.now() - attemptStartMs
1388
+ });
1389
+ logRetryFailure(operationName, attempts, maxAttempts, errorContext, attemptLogContext, isNonRetryable);
1148
1390
  if (isNonRetryable) {
1149
- Logger.debug(`Skipping retry for ${operationName}: error marked non-retryable`, _extends({}, logContext, errorContext));
1391
+ Logger.debug(`Skipping retry for ${operationName}: error marked non-retryable`, _extends({}, attemptLogContext, errorContext));
1150
1392
  throw error;
1151
1393
  }
1152
1394
  if (shouldRetry) {
@@ -1154,7 +1396,7 @@ const logRetryExhausted = (operationName, maxAttempts, errorContext, logContext)
1154
1396
  try {
1155
1397
  allow = await shouldRetry(error, attempts);
1156
1398
  } catch (predicateError) {
1157
- Logger.warn(`shouldRetry predicate failed for ${operationName}, surfacing original error`, _extends({}, logContext, errorContext, {
1399
+ Logger.warn(`shouldRetry predicate failed for ${operationName}, surfacing original error`, _extends({}, attemptLogContext, errorContext, {
1158
1400
  predicateError: predicateError instanceof Error ? predicateError.message : 'Unknown error'
1159
1401
  }));
1160
1402
  }
@@ -1163,7 +1405,7 @@ const logRetryExhausted = (operationName, maxAttempts, errorContext, logContext)
1163
1405
  }
1164
1406
  }
1165
1407
  if (attempts === maxAttempts) {
1166
- logRetryExhausted(operationName, maxAttempts, errorContext, logContext);
1408
+ logRetryExhausted(operationName, maxAttempts, errorContext, attemptLogContext);
1167
1409
  throw error;
1168
1410
  }
1169
1411
  const exponentialDelay = retryInterval * 2 ** (attempts - 1);
@@ -2413,6 +2655,22 @@ const createDynamicOnlyDistribution = ({ allShares })=>({
2413
2655
  /** Track which wallets are currently executing inside a sign operation.
2414
2656
  * Used to prevent deadlocks when recovery is called from within a sign op. */ WalletQueueManager.walletsWithActiveSignOp = new Map();
2415
2657
 
2658
+ // A DYNAMIC backup can persist multiple shares (e.g. 2-of-3); the singular
2659
+ // externalKeyShareId is a fallback for older single-id shapes.
2660
+ const collectDynamicKeyShareIds = (locations)=>{
2661
+ return locations.filter((loc)=>loc.location === BackupLocation.DYNAMIC).flatMap((loc)=>{
2662
+ if (loc.externalKeyShareIds && loc.externalKeyShareIds.length > 0) {
2663
+ return loc.externalKeyShareIds;
2664
+ }
2665
+ if (loc.externalKeyShareId) {
2666
+ return [
2667
+ loc.externalKeyShareId
2668
+ ];
2669
+ }
2670
+ return [];
2671
+ });
2672
+ };
2673
+
2416
2674
  // Pure routing helper: maps a completed reshare ceremony's results into the
2417
2675
  // ShareDistribution that storage/publish should follow. Lives outside the
2418
2676
  // client class so it's straightforward to reason about and unit-test
@@ -2613,205 +2871,6 @@ const readEnvironmentSettings = ()=>{
2613
2871
  }
2614
2872
  });
2615
2873
 
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 or
2656
- * 401 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
- /**
2661
- * Reasons that represent a genuine session-key signature mismatch (the 401 the
2662
- * server returns per DYNT-1282). Used to gate 401 instrumentation so callers
2663
- * that reuse 401 for unrelated rejections don't pollute the failure metric.
2664
- */ const SESSION_SIGNATURE_FAILURE_REASONS = new Set([
2665
- 'invalid_nonce_signature',
2666
- 'invalid_session_signature'
2667
- ]);
2668
- /** Best-effort extraction of the server error `code`/`message` from a 4xx body. */ const readErrorBody = (error)=>{
2669
- var _error_response;
2670
- if (!(error instanceof AxiosError)) {
2671
- return {};
2672
- }
2673
- const data = (_error_response = error.response) == null ? void 0 : _error_response.data;
2674
- if (typeof data === 'string') {
2675
- return {
2676
- message: data
2677
- };
2678
- }
2679
- if (!data || typeof data !== 'object') {
2680
- return {};
2681
- }
2682
- const record = data;
2683
- // Prefer a string `code`, else fall back to `error_code` (the field the Key
2684
- // Share Service emits, see KSS #271) or a bare `error`.
2685
- const code = [
2686
- record['code'],
2687
- record['error_code'],
2688
- record['error']
2689
- ].find((value)=>typeof value === 'string');
2690
- const message = typeof record['message'] === 'string' ? record['message'] : undefined;
2691
- return {
2692
- code,
2693
- message
2694
- };
2695
- };
2696
- /** Maps the server error `code`/`message` onto a {@link NonceFailureReason}. */ const classifyNonceFailure = ({ code, message })=>{
2697
- const haystack = `${code != null ? code : ''} ${message != null ? message : ''}`.toLowerCase();
2698
- if (haystack.includes('already_used') || haystack.includes('already used') || haystack.includes('consumption failed')) {
2699
- return 'nonce_already_used';
2700
- }
2701
- if (haystack.includes('invalid_nonce_signature') || haystack.includes('invalid nonce signature')) {
2702
- return 'invalid_nonce_signature';
2703
- }
2704
- if (haystack.includes('invalid_session_signature') || haystack.includes('invalid session public key') || haystack.includes('invalid session signature')) {
2705
- return 'invalid_session_signature';
2706
- }
2707
- return 'other';
2708
- };
2709
- /**
2710
- * Owns everything about signed sessions and their single-use replay nonces:
2711
- * resolving a session from an explicit value or the host reverse channel,
2712
- * deciding whether the SDK version requires one, and building the
2713
- * refresh-on-replay-400 retry predicate shared by the backup and recovery
2714
- * flows.
2715
- *
2716
- * Extracted from `DynamicWalletClient` so this logic can be exercised in
2717
- * isolation. The host callback is read lazily (`getCallback`) so it stays in
2718
- * sync with the owning client even if reassigned after construction.
2719
- */ class SignedSessionManager {
2720
- /** True when a reverse channel is configured to mint fresh signed sessions. */ get canRefresh() {
2721
- return this.getCallback() !== undefined;
2722
- }
2723
- /**
2724
- * Resolves the signed session ID from an explicit value or falls back to the
2725
- * host reverse channel. Throws if neither source provides a value.
2726
- */ async resolve(signedSessionId) {
2727
- const callback = this.getCallback();
2728
- const resolved = signedSessionId != null ? signedSessionId : await (callback == null ? void 0 : callback());
2729
- if (!resolved) {
2730
- 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');
2731
- }
2732
- return resolved;
2733
- }
2734
- /** Whether the configured SDK version requires a signed session ID. */ isRequired() {
2735
- return this.required;
2736
- }
2737
- /** Whether the host SDK version supports the getSignedSessionId reverse channel (see version-check.ts). */ supportsReverseChannel() {
2738
- return this.reverseChannelSupported;
2739
- }
2740
- /**
2741
- * Builds a `retryPromise` `shouldRetry` predicate that refreshes a consumed
2742
- * single-use nonce via the reverse channel on a replay 400 and retries once.
2743
- * The signed session carries a single-use replay nonce: it is valid on its
2744
- * first use, but once consumed (e.g. by a preceding operation) the server
2745
- * rejects with a 400, at which point a fresh session is fetched and the call
2746
- * retried. `alsoRetry` lets callers opt into additional retryable statuses
2747
- * (e.g. 429 / 5xx) on top of the nonce refresh.
2748
- */ refreshShouldRetry({ onRefreshed, operationName, logContext, alsoRetry }) {
2749
- return async (error, attempt)=>{
2750
- const status = getHttpStatus(error);
2751
- // A 400 is a refreshable replay nonce; a 401 is a session-key mismatch the
2752
- // server returns to break the refresh loop (DYNT-1282) — logged only when the
2753
- // body classifies as a genuine session-signature failure so unrelated 401s
2754
- // (e.g. an exhausted add-signer grant) don't pollute the DYNT-1599 metric.
2755
- // Only the 400 can actually refresh.
2756
- const isSessionSignatureFailure = status === 401 && SESSION_SIGNATURE_FAILURE_REASONS.has(classifyNonceFailure(readErrorBody(error)));
2757
- const shouldInstrument = status === 400 || isSessionSignatureFailure;
2758
- if (shouldInstrument) {
2759
- const willRefresh = status === 400 && attempt === 1 && this.canRefresh && this.supportsReverseChannel();
2760
- this.instrumentNonceFailure({
2761
- error,
2762
- attempt,
2763
- status,
2764
- operationName,
2765
- willRefresh,
2766
- logContext
2767
- });
2768
- }
2769
- if (status === 400 && attempt === 1 && this.canRefresh) {
2770
- // canRefresh only proves a local callback exists, not that the host answers it.
2771
- if (!this.supportsReverseChannel()) {
2772
- this.logger.warn(`[${operationName}] host SDK version predates the signed-session reverse channel, declining nonce refresh`, _extends({
2773
- status
2774
- }, logContext));
2775
- return alsoRetry ? alsoRetry(status) : false;
2776
- }
2777
- onRefreshed(await this.resolve());
2778
- this.logger.info(`[${operationName}] refreshed signed session, retrying`, _extends({
2779
- status
2780
- }, logContext));
2781
- return true;
2782
- }
2783
- return alsoRetry ? alsoRetry(status) : false;
2784
- };
2785
- }
2786
- /**
2787
- * Emits a single Datadog log per signed-session nonce rejection so the
2788
- * failure bucket can be split by `reason` and correlated per wallet/request.
2789
- * Purely observational — it never alters the retry decision.
2790
- */ instrumentNonceFailure({ error, attempt, status, operationName, willRefresh, logContext }) {
2791
- const body = readErrorBody(error);
2792
- this.logger.info(NONCE_FAILURE_EVENT, _extends({}, logContext, {
2793
- operationName,
2794
- attempt,
2795
- status,
2796
- reason: classifyNonceFailure(body),
2797
- errorCode: body.code,
2798
- errorMessage: body.message,
2799
- willRefresh,
2800
- canRefresh: this.canRefresh,
2801
- reverseChannelSupported: this.reverseChannelSupported,
2802
- required: this.required,
2803
- sdkVersion: this.sdkVersion
2804
- }));
2805
- }
2806
- constructor({ logger, sdkVersion, getCallback }){
2807
- this.logger = logger;
2808
- this.getCallback = getCallback;
2809
- this.sdkVersion = sdkVersion;
2810
- this.required = isRequiresSignedSessionId(sdkVersion, this.logger);
2811
- this.reverseChannelSupported = isReverseChannelSupported(sdkVersion, this.logger);
2812
- }
2813
- }
2814
-
2815
2874
  /**
2816
2875
  * Determines the recovery state of a wallet based on backup info and local shares.
2817
2876
  *
@@ -6373,6 +6432,7 @@ class DynamicWalletClient {
6373
6432
  return {
6374
6433
  location: BackupLocation.DYNAMIC,
6375
6434
  externalKeyShareId: data.keyShareIds[0],
6435
+ externalKeyShareIds: data.keyShareIds,
6376
6436
  passwordEncrypted: isPasswordEncrypted,
6377
6437
  keygenId
6378
6438
  };
@@ -6669,7 +6729,7 @@ class DynamicWalletClient {
6669
6729
  // aborts the backup before activation, so an unrecoverable share is never
6670
6730
  // marked active; the local share is never touched.
6671
6731
  if (this.featureFlags[FEATURE_FLAGS.VERIFY_BACKUP_RECOVERABILITY_FLAG] === true) {
6672
- const dynamicKeyShareIds = locations.filter((loc)=>loc.location === BackupLocation.DYNAMIC && loc.externalKeyShareId).map((loc)=>loc.externalKeyShareId);
6732
+ const dynamicKeyShareIds = collectDynamicKeyShareIds(locations);
6673
6733
  await this.assertServerCopyRecoverable({
6674
6734
  walletId: walletData.walletId,
6675
6735
  shareSetId: targetShareSetId,
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@dynamic-labs-wallet/browser",
3
- "version": "1.0.81",
3
+ "version": "1.0.83",
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.81",
7
+ "@dynamic-labs-wallet/core": "1.0.83",
8
8
  "@dynamic-labs-wallet/forward-mpc-client": "1.0.1",
9
- "@dynamic-labs-wallet/primitives": "1.0.81",
9
+ "@dynamic-labs-wallet/primitives": "1.0.83",
10
10
  "@dynamic-labs/sdk-api-core": "^0.0.1083",
11
11
  "argon2id": "1.0.1",
12
12
  "axios": "1.16.0",