@dynamic-labs-wallet/browser 1.0.43 → 1.0.44

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.cjs CHANGED
@@ -1265,6 +1265,22 @@ const downloadStringAsFile = ({ filename, content, mimeType = 'application/json'
1265
1265
  }
1266
1266
  return false;
1267
1267
  };
1268
+ /**
1269
+ * Checks for the server's stale-share preflight rejection (HTTP 409 sent as
1270
+ * an SSE error event with `code: 'STALE_CLIENT_SHARES'`). The server compares
1271
+ * the `shareSetId` the SDK sends on sign requests against the wallet's active
1272
+ * share set and rejects BEFORE any room/ceremony work when they diverge
1273
+ * (e.g. the shares were rotated by a reshare/refresh on another device).
1274
+ * The SDK heals (re-syncs local shares from backup) and retries internally.
1275
+ *
1276
+ * The SSE event-stream layer copies the event's data fields onto the Error
1277
+ * object (see createErrorFromEventData), so `code` is available here.
1278
+ */ const isStaleClientSharesError = (error)=>{
1279
+ if (!error || typeof error !== 'object') {
1280
+ return false;
1281
+ }
1282
+ return error.code === 'STALE_CLIENT_SHARES';
1283
+ };
1268
1284
  /**
1269
1285
  * Determines whether a reshare operation should reuse the wallet's existing backup locations.
1270
1286
  *
@@ -2565,6 +2581,15 @@ const KNOWN_SHARE_SET_TYPES = new Set([
2565
2581
  'delegated',
2566
2582
  'server'
2567
2583
  ]);
2584
+ /**
2585
+ * keygenIds the server records for the wallet's Dynamic-backed-up client
2586
+ * shares — the reference generation that local shares are compared against.
2587
+ * Empty for first-time backups or legacy data without keygenIds.
2588
+ */ const recordedDynamicKeygenIds = (backupInfo)=>{
2589
+ var _backupInfo_backups;
2590
+ var _backupInfo_backups_BackupLocation_DYNAMIC;
2591
+ return ((_backupInfo_backups_BackupLocation_DYNAMIC = backupInfo == null ? void 0 : (_backupInfo_backups = backupInfo.backups) == null ? void 0 : _backupInfo_backups[core.BackupLocation.DYNAMIC]) != null ? _backupInfo_backups_BackupLocation_DYNAMIC : []).map((backup)=>backup.keygenId).filter((keygenId)=>typeof keygenId === 'string' && keygenId.length > 0);
2592
+ };
2568
2593
  class DynamicWalletClient {
2569
2594
  /**
2570
2595
  * Check if wallet has heavy operations in progress
@@ -3399,22 +3424,114 @@ class DynamicWalletClient {
3399
3424
  }
3400
3425
  }
3401
3426
  /**
3402
- * On public-key mismatch, restore local shares from backup and rethrow so
3403
- * the caller's next call (with refreshed shares) succeeds. Auto-retry was
3404
- * removed because in the iframe transport the error response is already
3405
- * posted to the host before any retry can resolve.
3406
- * Passthrough for non-mismatch errors.
3407
- */ async recoverKeySharesOnMismatch({ error, accountAddress, password, signedSessionId, walletOperation, mfaToken, traceContext, dynamicRequestId }) {
3408
- if (!isPublicKeyMismatchError(error)) {
3409
- throw error;
3427
+ * Best-effort heal for stale local shares. Runs verifyAndRecoverStaleShare
3428
+ * through the shared recovery queue: concurrent triggers join the in-flight
3429
+ * recovery (WalletQueueManager dedup), and execution is deadlock-safe when
3430
+ * called from inside a queued sign/heavy operation. Never throws — callers
3431
+ * are already on a failing path and rethrow their original error.
3432
+ */ async healStaleShares(params) {
3433
+ const runCheck = ()=>WalletQueueManager.queueRecoverOperation(params.accountAddress, core.WalletOperation.RECOVER, ()=>this.verifyAndRecoverStaleShare(params));
3434
+ try {
3435
+ const result = await runCheck();
3436
+ // The queue dedup returns the in-flight recovery's promise, dropping
3437
+ // this caller's params. If that run skipped recovery but we carry a
3438
+ // confirmed mismatch, re-run once with our params. (A run we started
3439
+ // ourselves with confirmedMismatch=true always recovers, so this only
3440
+ // fires after joining a weaker concurrent check.)
3441
+ if (params.confirmedMismatch && (result == null ? void 0 : result.recovered) === false) {
3442
+ await runCheck();
3443
+ }
3444
+ } catch (error) {
3445
+ this.logger.error('[StaleShareCheck] share recovery failed', {
3446
+ accountAddress: params.accountAddress,
3447
+ dynamicRequestId: params.dynamicRequestId,
3448
+ trigger: params.trigger,
3449
+ error: error instanceof Error ? error.message : String(error)
3450
+ });
3410
3451
  }
3411
- this.logger.info('[DynamicWaasWalletClient] Public key mismatch detected, recovering key shares from backup', _extends({
3452
+ }
3453
+ /**
3454
+ * Ground-truth staleness check: refreshes the wallet from the API, compares
3455
+ * local share keygenIds against the server's recorded Dynamic-backup
3456
+ * keygenIds, and restores from backup when the local generation is stale
3457
+ * (a reshare/refresh on another device/browser rotates the shares without
3458
+ * this client noticing). No-ops when shares are fresh, so callers may run
3459
+ * it on any ceremony failure regardless of the error message.
3460
+ */ async verifyAndRecoverStaleShare({ accountAddress, chainName, password, signedSessionId, walletOperation, mfaToken, dynamicRequestId, traceContext, bitcoinConfig, trigger, confirmedMismatch }) {
3461
+ this.logger.info('[StaleShareCheck] verifying local share generation against server', _extends({
3412
3462
  accountAddress,
3413
- walletOperation,
3463
+ chainName,
3464
+ trigger,
3465
+ confirmedMismatch,
3414
3466
  dynamicRequestId
3415
3467
  }, this.getTraceContext(traceContext)));
3416
- // Refresh walletMap from API before recovery to ensure backup info is up-to-date.
3468
+ // Refresh walletMap from the API: the cached entry may predate a rotation
3469
+ // performed on another device, which would make this comparison a no-op.
3470
+ // Full getWallets (not just backup info) so shareSetId etc. are also
3471
+ // current for the caller's retry.
3417
3472
  await this.getWallets();
3473
+ const wallet = this.getWalletFromMap(accountAddress);
3474
+ const recordedKeygenIds = recordedDynamicKeygenIds(wallet == null ? void 0 : wallet.clientKeySharesBackupInfo);
3475
+ let staleness;
3476
+ let localKeygenIds = [];
3477
+ if (recordedKeygenIds.length === 0) {
3478
+ // First-time backup or legacy data (server didn't populate keygenId) —
3479
+ // generation can't be compared. A confirmed mismatch still recovers
3480
+ // below (legacy recovery behavior); an unclassified
3481
+ // failure does not.
3482
+ staleness = 'unverifiable';
3483
+ } else {
3484
+ try {
3485
+ const localShares = await this.getClientKeySharesFromStorage({
3486
+ accountAddress
3487
+ });
3488
+ const comparison = await this.compareShareGenerations({
3489
+ accountAddress,
3490
+ chainName,
3491
+ localShares,
3492
+ recordedKeygenIds,
3493
+ bitcoinConfig
3494
+ });
3495
+ localKeygenIds = comparison.localKeygenIds;
3496
+ staleness = comparison.fresh ? 'fresh' : 'stale';
3497
+ } catch (error) {
3498
+ // Unreadable/corrupted local share — treat as stale and recover.
3499
+ this.logger.warn('[StaleShareCheck] could not derive keygenId from local shares — treating as stale', {
3500
+ accountAddress,
3501
+ trigger,
3502
+ dynamicRequestId,
3503
+ error: error instanceof Error ? error.message : String(error)
3504
+ });
3505
+ staleness = 'stale';
3506
+ }
3507
+ }
3508
+ // Stale generation always recovers. A confirmed mismatch also recovers
3509
+ // when the comparison is inconclusive or even reports fresh (possible
3510
+ // server-side inconsistency) — matching the legacy recovery behavior.
3511
+ const shouldRecover = staleness === 'stale' || confirmedMismatch;
3512
+ if (!shouldRecover) {
3513
+ this.logger.info('[StaleShareCheck] no recovery needed', {
3514
+ accountAddress,
3515
+ trigger,
3516
+ staleness,
3517
+ localKeygenIds,
3518
+ dynamicRequestId
3519
+ });
3520
+ return {
3521
+ recovered: false,
3522
+ localKeygenIds,
3523
+ recordedKeygenIds
3524
+ };
3525
+ }
3526
+ this.logger.warn('[StaleShareCheck] recovering current shares from backup', _extends({
3527
+ accountAddress,
3528
+ trigger,
3529
+ confirmedMismatch,
3530
+ staleness,
3531
+ localKeygenIds,
3532
+ recordedKeygenIds,
3533
+ dynamicRequestId
3534
+ }, this.getTraceContext(traceContext)));
3418
3535
  await this.internalRecoverEncryptedBackupByWallet({
3419
3536
  accountAddress,
3420
3537
  password,
@@ -3423,12 +3540,35 @@ class DynamicWalletClient {
3423
3540
  mfaToken,
3424
3541
  storeRecoveredShares: true
3425
3542
  });
3426
- this.logger.info('[DynamicWaasWalletClient] Key shares recovered; rethrowing original error for caller to retry', _extends({
3543
+ this.logger.info('[StaleShareCheck] recovery completed next operation will use the recovered shares', {
3427
3544
  accountAddress,
3428
- walletOperation,
3545
+ trigger,
3429
3546
  dynamicRequestId
3430
- }, this.getTraceContext(traceContext)));
3431
- throw error;
3547
+ });
3548
+ return {
3549
+ recovered: true,
3550
+ localKeygenIds,
3551
+ recordedKeygenIds
3552
+ };
3553
+ }
3554
+ /**
3555
+ * Set-compare local share keygenIds (MPC exportID) against the keygenIds
3556
+ * the server recorded for the wallet's Dynamic backups. Shared by the
3557
+ * stale-share heal (verifyAndRecoverStaleShare) and the backup preflight
3558
+ * (ensureLocalSharesAreFresh).
3559
+ */ async compareShareGenerations({ accountAddress, chainName, localShares, recordedKeygenIds, bitcoinConfig }) {
3560
+ const mpcSigner = getMPCSigner({
3561
+ chainName,
3562
+ baseRelayUrl: this.baseMPCRelayApiUrl,
3563
+ bitcoinConfig: bitcoinConfig != null ? bitcoinConfig : this.getBitcoinConfigForChain(chainName, accountAddress)
3564
+ });
3565
+ const localKeygenIds = await Promise.all(localShares.map((share)=>this.getKeygenIdForShare(mpcSigner, share)));
3566
+ const recordedSet = new Set(recordedKeygenIds);
3567
+ const fresh = localKeygenIds.length === recordedSet.size && localKeygenIds.every((id)=>recordedSet.has(id));
3568
+ return {
3569
+ fresh,
3570
+ localKeygenIds
3571
+ };
3432
3572
  }
3433
3573
  //todo: need to modify with imported flag
3434
3574
  async sign({ accountAddress, message, chainName, password = undefined, isFormatted = false, signedSessionId, mfaToken, elevatedAccessToken, context, onError, traceContext, bitcoinConfig }) {
@@ -3447,7 +3587,7 @@ class DynamicWalletClient {
3447
3587
  bitcoinConfig
3448
3588
  }));
3449
3589
  }
3450
- async internalSign({ accountAddress, message, chainName, password = undefined, isFormatted = false, signedSessionId, mfaToken, elevatedAccessToken, context, onError, traceContext, bitcoinConfig }) {
3590
+ async internalSign({ accountAddress, message, chainName, password = undefined, isFormatted = false, signedSessionId, mfaToken, elevatedAccessToken, context, onError, traceContext, bitcoinConfig, staleShareRetry = false }) {
3451
3591
  const dynamicRequestId = uuid.v4();
3452
3592
  try {
3453
3593
  await this.verifyPassword({
@@ -3490,6 +3630,17 @@ class DynamicWalletClient {
3490
3630
  // (sseErrorPromise would never reach Promise.race in that path)
3491
3631
  // eslint-disable-next-line @typescript-eslint/no-empty-function
3492
3632
  sseErrorPromise.catch(()=>{});
3633
+ // Dedicated channel for the server's 409 stale-shares preflight: it must
3634
+ // abort the ceremony into the heal-and-retry path WITHOUT settling the
3635
+ // host request (so the transparent retry's outcome is what the host
3636
+ // sees). Needed as a race arm because in the cached-room flow
3637
+ // serverSignPromise is never awaited, so its rejection alone would float.
3638
+ let rejectOnStaleShares;
3639
+ const staleSharesPromise = new Promise((_, reject)=>{
3640
+ rejectOnStaleShares = reject;
3641
+ });
3642
+ // eslint-disable-next-line @typescript-eslint/no-empty-function
3643
+ staleSharesPromise.catch(()=>{});
3493
3644
  // Perform the server sign
3494
3645
  const serverSignPromise = this.serverSign({
3495
3646
  walletId: wallet.walletId,
@@ -3501,6 +3652,13 @@ class DynamicWalletClient {
3501
3652
  roomId,
3502
3653
  context,
3503
3654
  onError: (error)=>{
3655
+ // The server's 409 stale-shares preflight rejection is healed and
3656
+ // retried internally (see the catch below) — don't settle the host
3657
+ // request or poison the SSE race with it.
3658
+ if (isStaleClientSharesError(error)) {
3659
+ rejectOnStaleShares(error);
3660
+ return;
3661
+ }
3504
3662
  onError == null ? void 0 : onError(error);
3505
3663
  rejectOnSSEError(error);
3506
3664
  },
@@ -3508,6 +3666,11 @@ class DynamicWalletClient {
3508
3666
  traceContext,
3509
3667
  bitcoinConfig
3510
3668
  });
3669
+ // In the cached-room flow the promise below is never awaited — attach a
3670
+ // handler so a rejection (e.g. the 409 preflight, which also arrives via
3671
+ // staleSharesPromise above) doesn't surface as an unhandled rejection.
3672
+ // eslint-disable-next-line @typescript-eslint/no-empty-function
3673
+ serverSignPromise.catch(()=>{});
3511
3674
  // Only await if roomId is not provided
3512
3675
  roomId = roomId != null ? roomId : (await serverSignPromise).roomId;
3513
3676
  this.logger.info('[DynamicWaasWalletClient] Server sign completed', _extends({
@@ -3520,6 +3683,9 @@ class DynamicWalletClient {
3520
3683
  operation: 'serverSign'
3521
3684
  }, this.getTraceContext(traceContext)));
3522
3685
  let signature;
3686
+ // Set by the clientSign rejection handler below; read in the catch to
3687
+ // detect a client-side mismatch masked by a generic SSE race winner.
3688
+ let clientSignMismatchError;
3523
3689
  try {
3524
3690
  // Race clientSign against SSE errors so that server-side failures
3525
3691
  // (e.g. policy violations) immediately reject instead of hanging
@@ -3547,6 +3713,12 @@ class DynamicWalletClient {
3547
3713
  roomId: undefined,
3548
3714
  context,
3549
3715
  onError: (error)=>{
3716
+ // See the initial serverSign onError: 409 stale-shares is
3717
+ // healed + retried internally, never surfaced to the host.
3718
+ if (isStaleClientSharesError(error)) {
3719
+ rejectOnStaleShares(error);
3720
+ return;
3721
+ }
3550
3722
  onError == null ? void 0 : onError(error);
3551
3723
  rejectOnSSEError(error);
3552
3724
  },
@@ -3557,26 +3729,63 @@ class DynamicWalletClient {
3557
3729
  return freshRoomId;
3558
3730
  }
3559
3731
  });
3560
- // Prevent unhandled rejection from the losing promise in the race:
3561
- // if sseErrorPromise wins, clientSign keeps running and will eventually
3562
- // reject (MPC timeout); if clientSign wins, sseErrorPromise may never settle.
3563
- // eslint-disable-next-line @typescript-eslint/no-empty-function
3564
- clientSignPromise.catch(()=>{});
3732
+ // Handle the losing race promise (prevents an unhandled rejection) and
3733
+ // capture a client-side ERROR_PUBLIC_KEY_MISMATCH here the only place
3734
+ // a stale-local-share failure surfaces, since the server's generic SSE
3735
+ // error wins the race and masks it. Schedule recovery regardless of
3736
+ // which promise wins or when this rejection settles.
3737
+ clientSignPromise.catch((error)=>{
3738
+ if (isPublicKeyMismatchError(error)) {
3739
+ clientSignMismatchError = error;
3740
+ this.logger.warn('[StaleShareCheck] clientSign rejected with public-key mismatch — scheduling share recovery', _extends({
3741
+ accountAddress,
3742
+ chainName,
3743
+ dynamicRequestId
3744
+ }, this.getTraceContext(traceContext)));
3745
+ void this.healStaleShares({
3746
+ accountAddress,
3747
+ chainName,
3748
+ password,
3749
+ signedSessionId,
3750
+ walletOperation: core.WalletOperation.SIGN_MESSAGE,
3751
+ mfaToken,
3752
+ dynamicRequestId,
3753
+ traceContext,
3754
+ bitcoinConfig,
3755
+ trigger: 'clientSign rejection',
3756
+ confirmedMismatch: true
3757
+ });
3758
+ }
3759
+ });
3565
3760
  signature = await Promise.race([
3566
3761
  clientSignPromise,
3567
- sseErrorPromise
3762
+ sseErrorPromise,
3763
+ staleSharesPromise
3568
3764
  ]);
3569
3765
  } catch (signError) {
3570
- // Restore shares from backup on mismatch; passthrough otherwise.
3571
- await this.recoverKeySharesOnMismatch({
3572
- error: signError,
3766
+ // The 409 stale-shares preflight is handled exclusively by the outer
3767
+ // catch (heal + transparent retry) — skip the generic heal here so the
3768
+ // ground-truth check runs once, right before the retry decision.
3769
+ if (isStaleClientSharesError(signError)) {
3770
+ throw signError;
3771
+ }
3772
+ // Heal before rethrowing so the caller's retry succeeds. Run the
3773
+ // ground-truth check whatever the raced error was: a generic SSE
3774
+ // error frequently wins the race while the client-side mismatch
3775
+ // settles later, so error-string inspection alone is timing-dependent.
3776
+ // The check no-ops when shares are fresh.
3777
+ await this.healStaleShares({
3573
3778
  accountAddress,
3779
+ chainName,
3574
3780
  password,
3575
3781
  signedSessionId,
3576
3782
  walletOperation: core.WalletOperation.SIGN_MESSAGE,
3577
3783
  mfaToken,
3784
+ dynamicRequestId,
3578
3785
  traceContext,
3579
- dynamicRequestId
3786
+ bitcoinConfig,
3787
+ trigger: 'sign failure',
3788
+ confirmedMismatch: isPublicKeyMismatchError(signError) || clientSignMismatchError !== undefined
3580
3789
  });
3581
3790
  throw signError;
3582
3791
  }
@@ -3592,6 +3801,51 @@ class DynamicWalletClient {
3592
3801
  }, this.getTraceContext(traceContext)));
3593
3802
  return signature;
3594
3803
  } catch (error) {
3804
+ // Server-side stale-share preflight (409 STALE_CLIENT_SHARES): the
3805
+ // request was rejected BEFORE any room/ceremony work, and the onError
3806
+ // wrappers above kept it away from the host — so the host request is
3807
+ // still pending. Heal the local shares from backup and transparently
3808
+ // retry once; the host only ever sees the (successful) outcome.
3809
+ if (!staleShareRetry && isStaleClientSharesError(error)) {
3810
+ // Heal first (re-sync local shares + walletMap from the server), then
3811
+ // retry regardless of whether shares were replaced: even a "fresh"
3812
+ // verdict means the heal's getWallets() refreshed the stale
3813
+ // walletMap.shareSetId the server rejected. The retry is guarded to
3814
+ // run at most once; if it 409s again the error surfaces normally.
3815
+ await this.healStaleShares({
3816
+ accountAddress,
3817
+ chainName,
3818
+ password,
3819
+ signedSessionId,
3820
+ walletOperation: core.WalletOperation.SIGN_MESSAGE,
3821
+ mfaToken,
3822
+ dynamicRequestId,
3823
+ traceContext,
3824
+ bitcoinConfig,
3825
+ trigger: 'server 409 stale-shares preflight',
3826
+ confirmedMismatch: true
3827
+ });
3828
+ this.logger.info('[StaleShareCheck] retrying sign transparently after 409 stale-shares preflight', _extends({
3829
+ accountAddress,
3830
+ chainName,
3831
+ dynamicRequestId
3832
+ }, this.getTraceContext(traceContext)));
3833
+ return await this.internalSign({
3834
+ accountAddress,
3835
+ message,
3836
+ chainName,
3837
+ password,
3838
+ isFormatted,
3839
+ signedSessionId,
3840
+ mfaToken,
3841
+ elevatedAccessToken,
3842
+ context,
3843
+ onError,
3844
+ traceContext,
3845
+ bitcoinConfig,
3846
+ staleShareRetry: true
3847
+ });
3848
+ }
3595
3849
  logError({
3596
3850
  message: 'Error in sign',
3597
3851
  error: error,
@@ -3605,12 +3859,13 @@ class DynamicWalletClient {
3605
3859
  throw error;
3606
3860
  }
3607
3861
  }
3608
- async refreshWalletAccountShares({ accountAddress, chainName, password = undefined, signedSessionId, mfaToken, elevatedAccessToken, traceContext }) {
3862
+ async refreshWalletAccountShares({ accountAddress, chainName, password = undefined, signedSessionId, sessionPublicKey, mfaToken, elevatedAccessToken, traceContext }) {
3609
3863
  return WalletQueueManager.queueHeavyOperation(accountAddress, core.WalletOperation.REFRESH, ()=>this.internalRefreshWalletAccountShares({
3610
3864
  accountAddress,
3611
3865
  chainName,
3612
3866
  password,
3613
3867
  signedSessionId,
3868
+ sessionPublicKey,
3614
3869
  mfaToken,
3615
3870
  elevatedAccessToken,
3616
3871
  traceContext
@@ -3677,7 +3932,7 @@ class DynamicWalletClient {
3677
3932
  addressType: addressType
3678
3933
  } : undefined;
3679
3934
  }
3680
- async internalRefreshWalletAccountShares({ accountAddress, chainName, password = undefined, signedSessionId, mfaToken, elevatedAccessToken, traceContext }) {
3935
+ async internalRefreshWalletAccountShares({ accountAddress, chainName, password = undefined, signedSessionId, sessionPublicKey, mfaToken, elevatedAccessToken, traceContext, staleShareRetry = false }) {
3681
3936
  const dynamicRequestId = uuid.v4();
3682
3937
  try {
3683
3938
  this.assertPasswordRequired(password);
@@ -3769,16 +4024,19 @@ class DynamicWalletClient {
3769
4024
  try {
3770
4025
  refreshResults = await Promise.all(clientKeyShares.map((clientKeyShare)=>mpcSigner.refresh(roomId, clientKeyShare)));
3771
4026
  } catch (refreshError) {
3772
- // Restore shares from backup on mismatch; passthrough otherwise.
3773
- await this.recoverKeySharesOnMismatch({
3774
- error: refreshError,
4027
+ // Heal stale local shares before rethrowing so a retry succeeds.
4028
+ await this.healStaleShares({
3775
4029
  accountAddress,
4030
+ chainName,
3776
4031
  password,
3777
4032
  signedSessionId,
3778
4033
  walletOperation: core.WalletOperation.REFRESH,
3779
4034
  mfaToken,
4035
+ dynamicRequestId,
3780
4036
  traceContext,
3781
- dynamicRequestId
4037
+ bitcoinConfig,
4038
+ trigger: 'refresh failure',
4039
+ confirmedMismatch: isPublicKeyMismatchError(refreshError)
3782
4040
  });
3783
4041
  throw refreshError;
3784
4042
  }
@@ -3804,7 +4062,8 @@ class DynamicWalletClient {
3804
4062
  accountAddress,
3805
4063
  clientKeyShares: refreshResults,
3806
4064
  password: password != null ? password : this.environmentId,
3807
- signedSessionId
4065
+ signedSessionId,
4066
+ sessionPublicKey
3808
4067
  })
3809
4068
  });
3810
4069
  await this.setClientKeySharesToStorage({
@@ -3830,6 +4089,42 @@ class DynamicWalletClient {
3830
4089
  });
3831
4090
  throw error;
3832
4091
  }
4092
+ // Server-side stale-share preflight (409 STALE_CLIENT_SHARES): rejected
4093
+ // BEFORE any room/ceremony work, so nothing was rotated. Heal the local
4094
+ // shares from backup and transparently retry once — even a "fresh" heal
4095
+ // verdict matters, because its getWallets() refreshed the stale
4096
+ // walletMap.shareSetId the server rejected.
4097
+ if (!staleShareRetry && isStaleClientSharesError(error)) {
4098
+ await this.healStaleShares({
4099
+ accountAddress,
4100
+ chainName,
4101
+ password,
4102
+ signedSessionId,
4103
+ walletOperation: core.WalletOperation.REFRESH,
4104
+ mfaToken,
4105
+ dynamicRequestId,
4106
+ traceContext,
4107
+ bitcoinConfig: this.getBitcoinConfigForChain(chainName, accountAddress),
4108
+ trigger: 'server 409 stale-shares preflight (refresh)',
4109
+ confirmedMismatch: true
4110
+ });
4111
+ this.logger.info('[StaleShareCheck] retrying refresh transparently after 409 stale-shares preflight', _extends({
4112
+ accountAddress,
4113
+ chainName,
4114
+ dynamicRequestId
4115
+ }, this.getTraceContext(traceContext)));
4116
+ return await this.internalRefreshWalletAccountShares({
4117
+ accountAddress,
4118
+ chainName,
4119
+ password,
4120
+ signedSessionId,
4121
+ sessionPublicKey,
4122
+ mfaToken,
4123
+ elevatedAccessToken,
4124
+ traceContext,
4125
+ staleShareRetry: true
4126
+ });
4127
+ }
3833
4128
  logError({
3834
4129
  message: 'Error in refreshWalletAccountShares',
3835
4130
  error: error,
@@ -3921,7 +4216,7 @@ class DynamicWalletClient {
3921
4216
  existingClientKeyShares
3922
4217
  };
3923
4218
  }
3924
- async reshare({ chainName, accountAddress, oldThresholdSignatureScheme, newThresholdSignatureScheme, password = undefined, signedSessionId, cloudProviders = [], delegateToProjectEnvironment = false, mfaToken, elevatedAccessToken, revokeDelegation = false, googleDriveAccessToken, googleDriveTokenSource }) {
4219
+ async reshare({ chainName, accountAddress, oldThresholdSignatureScheme, newThresholdSignatureScheme, password = undefined, signedSessionId, sessionPublicKey, cloudProviders = [], delegateToProjectEnvironment = false, mfaToken, elevatedAccessToken, revokeDelegation = false, googleDriveAccessToken, googleDriveTokenSource }) {
3925
4220
  return WalletQueueManager.queueHeavyOperation(accountAddress, core.WalletOperation.RESHARE, ()=>this.internalReshare({
3926
4221
  chainName,
3927
4222
  accountAddress,
@@ -3929,6 +4224,7 @@ class DynamicWalletClient {
3929
4224
  newThresholdSignatureScheme,
3930
4225
  password,
3931
4226
  signedSessionId,
4227
+ sessionPublicKey,
3932
4228
  cloudProviders,
3933
4229
  delegateToProjectEnvironment,
3934
4230
  mfaToken,
@@ -4413,7 +4709,7 @@ class DynamicWalletClient {
4413
4709
  clientKeySharesBackupInfo: updatedBackupInfo
4414
4710
  } : {}));
4415
4711
  }
4416
- async internalReshare({ chainName, accountAddress, oldThresholdSignatureScheme, newThresholdSignatureScheme, password = undefined, signedSessionId, cloudProviders = [], delegateToProjectEnvironment = false, mfaToken, elevatedAccessToken, revokeDelegation = false, googleDriveAccessToken, googleDriveTokenSource }) {
4712
+ async internalReshare({ chainName, accountAddress, oldThresholdSignatureScheme, newThresholdSignatureScheme, password = undefined, signedSessionId, sessionPublicKey, cloudProviders = [], delegateToProjectEnvironment = false, mfaToken, elevatedAccessToken, revokeDelegation = false, googleDriveAccessToken, googleDriveTokenSource, staleShareRetry = false }) {
4417
4713
  const dynamicRequestId = uuid.v4();
4418
4714
  // Password validation - wrapped in try-catch for consistent error handling
4419
4715
  // This path should NOT wipe key shares on failure (shares remain valid)
@@ -4625,15 +4921,18 @@ class DynamicWalletClient {
4625
4921
  existingReshareResults = existingSettled.map((r)=>r.value);
4626
4922
  newReshareResults = newSettled.map((r)=>r.value);
4627
4923
  } catch (reshareError) {
4628
- // Restore shares from backup on mismatch; passthrough otherwise.
4629
- await this.recoverKeySharesOnMismatch({
4630
- error: reshareError,
4924
+ // Heal stale local shares before rethrowing so a retry succeeds.
4925
+ await this.healStaleShares({
4631
4926
  accountAddress,
4927
+ chainName,
4632
4928
  password,
4633
4929
  signedSessionId,
4634
4930
  walletOperation: core.WalletOperation.RESHARE,
4635
4931
  mfaToken,
4636
- dynamicRequestId
4932
+ dynamicRequestId,
4933
+ bitcoinConfig,
4934
+ trigger: 'reshare failure',
4935
+ confirmedMismatch: isPublicKeyMismatchError(reshareError)
4637
4936
  });
4638
4937
  throw reshareError;
4639
4938
  }
@@ -4668,6 +4967,7 @@ class DynamicWalletClient {
4668
4967
  accountAddress,
4669
4968
  password,
4670
4969
  signedSessionId,
4970
+ sessionPublicKey,
4671
4971
  distribution,
4672
4972
  googleDriveAccessToken,
4673
4973
  googleDriveTokenSource
@@ -4705,6 +5005,47 @@ class DynamicWalletClient {
4705
5005
  }
4706
5006
  });
4707
5007
  } catch (error) {
5008
+ // Server-side stale-share preflight (409 STALE_CLIENT_SHARES): rejected
5009
+ // BEFORE any room/ceremony work, so local shares are intact (nothing to
5010
+ // wipe). Heal from backup and transparently retry once — even a "fresh"
5011
+ // heal verdict matters, because its getWallets() refreshed the stale
5012
+ // walletMap.shareSetId the server rejected.
5013
+ if (!staleShareRetry && isStaleClientSharesError(error)) {
5014
+ await this.healStaleShares({
5015
+ accountAddress,
5016
+ chainName,
5017
+ password,
5018
+ signedSessionId,
5019
+ walletOperation: core.WalletOperation.RESHARE,
5020
+ mfaToken,
5021
+ dynamicRequestId,
5022
+ bitcoinConfig: this.getBitcoinConfigForChain(chainName, accountAddress),
5023
+ trigger: 'server 409 stale-shares preflight (reshare)',
5024
+ confirmedMismatch: true
5025
+ });
5026
+ this.logger.info('[StaleShareCheck] retrying reshare transparently after 409 stale-shares preflight', {
5027
+ accountAddress,
5028
+ chainName,
5029
+ dynamicRequestId
5030
+ });
5031
+ return await this.internalReshare({
5032
+ chainName,
5033
+ accountAddress,
5034
+ oldThresholdSignatureScheme,
5035
+ newThresholdSignatureScheme,
5036
+ password,
5037
+ signedSessionId,
5038
+ sessionPublicKey,
5039
+ cloudProviders,
5040
+ delegateToProjectEnvironment,
5041
+ mfaToken,
5042
+ elevatedAccessToken,
5043
+ revokeDelegation,
5044
+ googleDriveAccessToken,
5045
+ googleDriveTokenSource,
5046
+ staleShareRetry: true
5047
+ });
5048
+ }
4708
5049
  logError({
4709
5050
  message: 'Error in reshare, resetting wallet to previous state',
4710
5051
  error: error,
@@ -4719,9 +5060,12 @@ class DynamicWalletClient {
4719
5060
  dynamicRequestId
4720
5061
  }
4721
5062
  });
4722
- // Skip the wipe on mismatch — recoverKeySharesOnMismatch just restored
4723
- // these shares from backup, undoing that would break the caller's retry.
4724
- if (!isPublicKeyMismatchError(error)) {
5063
+ // Skip the wipe on mismatch — healStaleShares just restored these
5064
+ // shares from backup, undoing that would break the caller's retry.
5065
+ // Same for a 409 stale-shares preflight (only reachable here on the
5066
+ // retried attempt): the request was rejected before any ceremony, so
5067
+ // local shares are consistent — wiping would strand the user.
5068
+ if (!isPublicKeyMismatchError(error) && !isStaleClientSharesError(error)) {
4725
5069
  this.updateWalletMap(accountAddress, {
4726
5070
  thresholdSignatureScheme: oldThresholdSignatureScheme
4727
5071
  });
@@ -4733,7 +5077,7 @@ class DynamicWalletClient {
4733
5077
  throw error;
4734
5078
  }
4735
5079
  }
4736
- async performDelegationOperation({ accountAddress, password, signedSessionId, mfaToken, newThresholdSignatureScheme, revokeDelegation = false, useShareSetReshare = false, operationName }) {
5080
+ async performDelegationOperation({ accountAddress, password, signedSessionId, sessionPublicKey, mfaToken, newThresholdSignatureScheme, revokeDelegation = false, useShareSetReshare = false, operationName }) {
4737
5081
  try {
4738
5082
  const delegateToProjectEnvironment = this.featureFlags && this.featureFlags[core.FEATURE_FLAGS.ENABLE_DELEGATED_KEY_SHARES_FLAG] === true;
4739
5083
  if (!delegateToProjectEnvironment) {
@@ -4762,6 +5106,7 @@ class DynamicWalletClient {
4762
5106
  newThresholdSignatureScheme,
4763
5107
  password,
4764
5108
  signedSessionId,
5109
+ sessionPublicKey,
4765
5110
  cloudProviders: activeProviders,
4766
5111
  // Server soft-deletes the wallet API key on revoke; a delegated
4767
5112
  // distribution would 400 on the follow-up delivery POST.
@@ -4780,7 +5125,7 @@ class DynamicWalletClient {
4780
5125
  throw error;
4781
5126
  }
4782
5127
  }
4783
- async delegateKeyShares({ accountAddress, password = undefined, signedSessionId, mfaToken }) {
5128
+ async delegateKeyShares({ accountAddress, password = undefined, signedSessionId, sessionPublicKey, mfaToken }) {
4784
5129
  var _this_featureFlags;
4785
5130
  const useShareSetReshare = ((_this_featureFlags = this.featureFlags) == null ? void 0 : _this_featureFlags[core.FEATURE_FLAGS.ENABLE_SHARE_SET_RESHARE]) === true;
4786
5131
  if (useShareSetReshare) {
@@ -4805,6 +5150,7 @@ class DynamicWalletClient {
4805
5150
  accountAddress,
4806
5151
  password,
4807
5152
  signedSessionId,
5153
+ sessionPublicKey,
4808
5154
  mfaToken,
4809
5155
  // FF on: reshare to 2/2 — the new delegated share set is always 2/2
4810
5156
  // (server + delegated webhook). getReshareConfig now has a 2/2 → 2/2
@@ -4819,7 +5165,7 @@ class DynamicWalletClient {
4819
5165
  const delegatedKeyShares = backupInfo.backups[core.BackupLocation.DELEGATED] || [];
4820
5166
  return delegatedKeyShares;
4821
5167
  }
4822
- async revokeDelegation({ accountAddress, password = undefined, signedSessionId, mfaToken }) {
5168
+ async revokeDelegation({ accountAddress, password = undefined, signedSessionId, sessionPublicKey, mfaToken }) {
4823
5169
  var _this_featureFlags;
4824
5170
  const useShareSetReshare = ((_this_featureFlags = this.featureFlags) == null ? void 0 : _this_featureFlags[core.FEATURE_FLAGS.ENABLE_SHARE_SET_RESHARE]) === true;
4825
5171
  if (useShareSetReshare) {
@@ -4865,6 +5211,7 @@ class DynamicWalletClient {
4865
5211
  accountAddress,
4866
5212
  password,
4867
5213
  signedSessionId,
5214
+ sessionPublicKey,
4868
5215
  mfaToken,
4869
5216
  newThresholdSignatureScheme: core.ThresholdSignatureScheme.TWO_OF_TWO,
4870
5217
  revokeDelegation: true,
@@ -4881,6 +5228,22 @@ class DynamicWalletClient {
4881
5228
  return new web.BIP340KeygenResult(extractedPubkey, secretShare);
4882
5229
  }
4883
5230
  async exportKey({ accountAddress, chainName, bitcoinConfig, password = undefined, signedSessionId, mfaToken, elevatedAccessToken, traceContext }) {
5231
+ // Public entry point delegates to the private implementation. Keeping the
5232
+ // `staleShareRetry` flag off the public signature mirrors sign/refresh/
5233
+ // reshare and ensures the transparent 409 retry can't be suppressed by
5234
+ // external callers or intercepted by subclass overrides.
5235
+ return this.internalExportKey({
5236
+ accountAddress,
5237
+ chainName,
5238
+ bitcoinConfig,
5239
+ password,
5240
+ signedSessionId,
5241
+ mfaToken,
5242
+ elevatedAccessToken,
5243
+ traceContext
5244
+ });
5245
+ }
5246
+ async internalExportKey({ accountAddress, chainName, bitcoinConfig, password = undefined, signedSessionId, mfaToken, elevatedAccessToken, traceContext, staleShareRetry = false }) {
4884
5247
  const dynamicRequestId = uuid.v4();
4885
5248
  try {
4886
5249
  const wallet = await this.getWallet({
@@ -4925,10 +5288,51 @@ class DynamicWalletClient {
4925
5288
  roomId: data.roomId
4926
5289
  }, this.getTraceContext(traceContext)));
4927
5290
  const derivedPrivateKey = await this.derivePrivateKeyFromExport(mpcSigner, keyExportRaw, wallet);
5291
+ // derivePrivateKeyFromExport returns undefined for unsupported signer
5292
+ // types; fail loudly rather than returning undefined as a string.
5293
+ if (derivedPrivateKey === undefined) {
5294
+ throw new Error(`Private key export is not supported for chain ${chainName}`);
5295
+ }
4928
5296
  return {
4929
5297
  derivedPrivateKey
4930
5298
  };
4931
5299
  } catch (error) {
5300
+ // Server-side stale-share preflight (409 STALE_CLIENT_SHARES): rejected
5301
+ // BEFORE any room/ceremony work. Heal the local shares from backup and
5302
+ // transparently retry once — even a "fresh" heal verdict matters,
5303
+ // because its getWallets() refreshed the stale walletMap.shareSetId the
5304
+ // server rejected.
5305
+ if (!staleShareRetry && isStaleClientSharesError(error)) {
5306
+ await this.healStaleShares({
5307
+ accountAddress,
5308
+ chainName,
5309
+ password,
5310
+ signedSessionId,
5311
+ walletOperation: core.WalletOperation.EXPORT_PRIVATE_KEY,
5312
+ mfaToken,
5313
+ dynamicRequestId,
5314
+ traceContext,
5315
+ bitcoinConfig,
5316
+ trigger: 'server 409 stale-shares preflight (export)',
5317
+ confirmedMismatch: true
5318
+ });
5319
+ this.logger.info('[StaleShareCheck] retrying export transparently after 409 stale-shares preflight', _extends({
5320
+ accountAddress,
5321
+ chainName,
5322
+ dynamicRequestId
5323
+ }, this.getTraceContext(traceContext)));
5324
+ return await this.internalExportKey({
5325
+ accountAddress,
5326
+ chainName,
5327
+ bitcoinConfig,
5328
+ password,
5329
+ signedSessionId,
5330
+ mfaToken,
5331
+ elevatedAccessToken,
5332
+ traceContext,
5333
+ staleShareRetry: true
5334
+ });
5335
+ }
4932
5336
  logError({
4933
5337
  message: 'Error in exportKey',
4934
5338
  error: error,
@@ -4938,6 +5342,22 @@ class DynamicWalletClient {
4938
5342
  dynamicRequestId
4939
5343
  }, this.getTraceContext(traceContext))
4940
5344
  });
5345
+ // Heal stale local shares before rethrowing so a retry succeeds —
5346
+ // export reconstructs from the local share, so a generation rotated on
5347
+ // another device fails here too.
5348
+ await this.healStaleShares({
5349
+ accountAddress,
5350
+ chainName,
5351
+ password,
5352
+ signedSessionId,
5353
+ walletOperation: core.WalletOperation.EXPORT_PRIVATE_KEY,
5354
+ mfaToken,
5355
+ dynamicRequestId,
5356
+ traceContext,
5357
+ bitcoinConfig,
5358
+ trigger: 'export failure',
5359
+ confirmedMismatch: isPublicKeyMismatchError(error)
5360
+ });
4941
5361
  throw error;
4942
5362
  }
4943
5363
  }
@@ -5307,6 +5727,14 @@ class DynamicWalletClient {
5307
5727
  * Auto-recovery logic has been removed in favor of the queue pattern.
5308
5728
  * Callers should handle recovery explicitly if needed.
5309
5729
  */ async ensureClientShare(accountAddress) {
5730
+ var _WalletQueueManager_getPendingRecoveryPromise;
5731
+ // A recovery may be in flight (e.g. a stale-share heal scheduled when a
5732
+ // previous sign hit a public-key mismatch). Wait for it so this operation
5733
+ // reads the recovered shares instead of the superseded ones. Recovery
5734
+ // failures are logged where they happen; this operation should proceed
5735
+ // with whatever shares exist rather than fail on the recovery.
5736
+ // eslint-disable-next-line @typescript-eslint/no-empty-function
5737
+ await ((_WalletQueueManager_getPendingRecoveryPromise = WalletQueueManager.getPendingRecoveryPromise(accountAddress)) == null ? void 0 : _WalletQueueManager_getPendingRecoveryPromise.catch(()=>{}));
5310
5738
  const shares = await this.getClientKeySharesFromStorage({
5311
5739
  accountAddress
5312
5740
  });
@@ -5315,13 +5743,14 @@ class DynamicWalletClient {
5315
5743
  }
5316
5744
  return shares;
5317
5745
  }
5318
- async backupToDynamicBackend({ walletId, clientShares, password, signedSessionId, dynamicRequestId, chainName, bitcoinConfig, isPasswordEncrypted, accountAddress, preEncryptedShares, passwordUpdateBatchId, encryptionVersion = DEFAULT_ENCRYPTION_VERSION }) {
5746
+ async backupToDynamicBackend({ walletId, clientShares, password, signedSessionId, sessionPublicKey, dynamicRequestId, chainName, bitcoinConfig, isPasswordEncrypted, accountAddress, preEncryptedShares, passwordUpdateBatchId, encryptionVersion = DEFAULT_ENCRYPTION_VERSION }) {
5319
5747
  var _this_getWalletFromMap;
5320
5748
  const encryptedDynamicShares = preEncryptedShares != null ? preEncryptedShares : await Promise.all(clientShares.map((keyShare)=>this.encryptKeyShare({
5321
5749
  keyShare,
5322
5750
  password,
5323
5751
  version: encryptionVersion
5324
5752
  })));
5753
+ const resolvedSessionPublicKey = sessionPublicKey != null ? sessionPublicKey : await (this.getSessionPublicKeyCallback == null ? void 0 : this.getSessionPublicKeyCallback.call(this));
5325
5754
  const data = await this.apiClient.storeEncryptedBackupByWallet({
5326
5755
  walletId,
5327
5756
  shareSetId: (_this_getWalletFromMap = this.getWalletFromMap(accountAddress)) == null ? void 0 : _this_getWalletFromMap.shareSetId,
@@ -5329,6 +5758,7 @@ class DynamicWalletClient {
5329
5758
  passwordEncrypted: isPasswordEncrypted,
5330
5759
  encryptionVersion,
5331
5760
  signedSessionId,
5761
+ sessionPublicKey: resolvedSessionPublicKey,
5332
5762
  requiresSignedSessionId: this.requiresSignedSessionId(),
5333
5763
  dynamicRequestId
5334
5764
  });
@@ -5477,7 +5907,7 @@ class DynamicWalletClient {
5477
5907
  }
5478
5908
  return location;
5479
5909
  }
5480
- async backupSharesWithDistribution({ accountAddress, password, signedSessionId, distribution, preserveDelegatedLocation = false, passwordUpdateBatchId, googleDriveAccessToken, googleDriveTokenSource, businessAccountId, encryptionVersion }) {
5910
+ async backupSharesWithDistribution({ accountAddress, password, signedSessionId, sessionPublicKey, distribution, preserveDelegatedLocation = false, passwordUpdateBatchId, googleDriveAccessToken, googleDriveTokenSource, businessAccountId, encryptionVersion }) {
5481
5911
  const dynamicRequestId = uuid.v4();
5482
5912
  // Get wallet data early for logging context (also used in catch block)
5483
5913
  const walletData = this.getWalletFromMap(accountAddress);
@@ -5556,6 +5986,7 @@ class DynamicWalletClient {
5556
5986
  clientShares: distribution.clientShares,
5557
5987
  password,
5558
5988
  signedSessionId: resolvedSignedSessionId,
5989
+ sessionPublicKey,
5559
5990
  dynamicRequestId,
5560
5991
  chainName: walletData.chainName,
5561
5992
  bitcoinConfig,
@@ -5752,29 +6183,23 @@ class DynamicWalletClient {
5752
6183
  // re-enter the outer operation with correct context. Skipped on internal post-rotation
5753
6184
  // flows that pass clientKeyShares explicitly (the refresh path).
5754
6185
  async ensureLocalSharesAreFresh({ accountAddress, walletData, localShares, password, signedSessionId }) {
5755
- var _freshBackupInfo_backups;
5756
6186
  // Always round-trip to the server — walletMap is populated at wallet-load and is
5757
6187
  // not invalidated when another tab rotates shares, so trusting it would
5758
6188
  // false-positive on cross-tab refresh.
5759
6189
  const { chainName } = walletData;
5760
- const mpcSigner = getMPCSigner({
5761
- chainName,
5762
- baseRelayUrl: this.baseMPCRelayApiUrl,
5763
- bitcoinConfig: this.getBitcoinConfigForChain(chainName, accountAddress)
6190
+ const freshBackupInfo = await this.fetchFreshWalletBackupInfo({
6191
+ accountAddress
5764
6192
  });
5765
- const [freshBackupInfo, localKeygenIds] = await Promise.all([
5766
- this.fetchFreshWalletBackupInfo({
5767
- accountAddress
5768
- }),
5769
- Promise.all(localShares.map((share)=>this.getKeygenIdForShare(mpcSigner, share)))
5770
- ]);
5771
- var _freshBackupInfo_backups_BackupLocation_DYNAMIC;
5772
- const recordedKeygenIds = ((_freshBackupInfo_backups_BackupLocation_DYNAMIC = freshBackupInfo == null ? void 0 : (_freshBackupInfo_backups = freshBackupInfo.backups) == null ? void 0 : _freshBackupInfo_backups[core.BackupLocation.DYNAMIC]) != null ? _freshBackupInfo_backups_BackupLocation_DYNAMIC : []).map((entry)=>entry.keygenId).filter((id)=>typeof id === 'string' && id.length > 0);
6193
+ const recordedKeygenIds = recordedDynamicKeygenIds(freshBackupInfo);
5773
6194
  // First-time backup or legacy data (server didn't populate keygenId yet) — nothing to compare.
5774
6195
  if (recordedKeygenIds.length === 0) return;
5775
- const recordedSet = new Set(recordedKeygenIds);
5776
- const localMatchesRecorded = localKeygenIds.length === recordedSet.size && localKeygenIds.every((id)=>recordedSet.has(id));
5777
- if (localMatchesRecorded) return;
6196
+ const { fresh, localKeygenIds } = await this.compareShareGenerations({
6197
+ accountAddress,
6198
+ chainName,
6199
+ localShares,
6200
+ recordedKeygenIds
6201
+ });
6202
+ if (fresh) return;
5778
6203
  this.logger.warn('[storeEncryptedBackupByWallet] Stale local shares detected; refreshing local storage', {
5779
6204
  accountAddress,
5780
6205
  walletId: walletData.walletId,
@@ -5801,7 +6226,7 @@ class DynamicWalletClient {
5801
6226
  const recoveryPassword = freshBackupInfo.passwordEncrypted ? password : undefined;
5802
6227
  try {
5803
6228
  // walletMap was already refreshed by fetchFreshWalletBackupInfo above, so we skip the
5804
- // getWallets() refresh that recoverKeySharesOnMismatch performs for its own callers.
6229
+ // getWallets() refresh that verifyAndRecoverStaleShare performs for its own callers.
5805
6230
  await this.internalRecoverEncryptedBackupByWallet({
5806
6231
  accountAddress,
5807
6232
  password: recoveryPassword,
@@ -5859,7 +6284,7 @@ class DynamicWalletClient {
5859
6284
  * @param params.signedSessionId - Optional signed session ID for authentication
5860
6285
  * @param params.backupToGoogleDrive - Whether to backup to Google Drive (defaults to false)
5861
6286
  * @returns Promise with backup metadata including share locations and IDs
5862
- */ async storeEncryptedBackupByWallet({ accountAddress, clientKeyShares = undefined, password = undefined, signedSessionId, cloudProviders = [], delegatedKeyshare = undefined, passwordUpdateBatchId, googleDriveAccessToken, googleDriveTokenSource, businessAccountId, encryptionVersion }) {
6287
+ */ async storeEncryptedBackupByWallet({ accountAddress, clientKeyShares = undefined, password = undefined, signedSessionId, sessionPublicKey, cloudProviders = [], delegatedKeyshare = undefined, passwordUpdateBatchId, googleDriveAccessToken, googleDriveTokenSource, businessAccountId, encryptionVersion }) {
5863
6288
  var _backupData_locationsWithKeyShares, _backupData_locationsWithKeyShares1;
5864
6289
  const hasProvidedShares = clientKeyShares !== undefined;
5865
6290
  const keySharesToBackup = clientKeyShares != null ? clientKeyShares : await this.getClientKeySharesFromStorage({
@@ -5929,6 +6354,7 @@ class DynamicWalletClient {
5929
6354
  accountAddress,
5930
6355
  password,
5931
6356
  signedSessionId,
6357
+ sessionPublicKey,
5932
6358
  distribution,
5933
6359
  preserveDelegatedLocation,
5934
6360
  passwordUpdateBatchId,
@@ -6001,7 +6427,7 @@ class DynamicWalletClient {
6001
6427
  errorContext
6002
6428
  } : {}));
6003
6429
  }
6004
- async updatePassword({ accountAddress, existingPassword, newPassword, signedSessionId, passwordUpdateBatchId }) {
6430
+ async updatePassword({ accountAddress, existingPassword, newPassword, signedSessionId, sessionPublicKey, passwordUpdateBatchId }) {
6005
6431
  const dynamicRequestId = uuid.v4();
6006
6432
  try {
6007
6433
  const wallet = this.getWalletFromMap(accountAddress);
@@ -6021,6 +6447,7 @@ class DynamicWalletClient {
6021
6447
  accountAddress,
6022
6448
  password: newPassword,
6023
6449
  signedSessionId,
6450
+ sessionPublicKey,
6024
6451
  passwordUpdateBatchId
6025
6452
  });
6026
6453
  this.logPasswordOperationSuccess('updatePassword', {
@@ -6050,7 +6477,7 @@ class DynamicWalletClient {
6050
6477
  throw error;
6051
6478
  }
6052
6479
  }
6053
- async setPassword({ accountAddress, newPassword, signedSessionId, passwordUpdateBatchId }) {
6480
+ async setPassword({ accountAddress, newPassword, signedSessionId, sessionPublicKey, passwordUpdateBatchId }) {
6054
6481
  const dynamicRequestId = uuid.v4();
6055
6482
  try {
6056
6483
  const wallet = this.getWalletFromMap(accountAddress);
@@ -6061,6 +6488,7 @@ class DynamicWalletClient {
6061
6488
  accountAddress,
6062
6489
  password: newPassword,
6063
6490
  signedSessionId,
6491
+ sessionPublicKey,
6064
6492
  passwordUpdateBatchId
6065
6493
  });
6066
6494
  this.logPasswordOperationSuccess('setPassword', {
@@ -6481,7 +6909,7 @@ class DynamicWalletClient {
6481
6909
  * Internal helper method that handles the complete flow for ensuring wallet key shares are backed up to a cloud provider.
6482
6910
  * - For 2-of-2 wallets: Automatically reshares to 2-of-3 threshold, then distributes shares (1 to backend, 1 to cloud)
6483
6911
  * - For 2-of-3 wallets: Call storeEncryptedBackupByWallet to backup for backend and cloud
6484
- */ async backupKeySharesToCloudProvider({ accountAddress, password, signedSessionId, backupLocation, googleDriveAccessToken, googleDriveTokenSource }) {
6912
+ */ async backupKeySharesToCloudProvider({ accountAddress, password, signedSessionId, sessionPublicKey, backupLocation, googleDriveAccessToken, googleDriveTokenSource }) {
6485
6913
  try {
6486
6914
  await this.getWallet({
6487
6915
  accountAddress,
@@ -6500,6 +6928,7 @@ class DynamicWalletClient {
6500
6928
  newThresholdSignatureScheme: core.ThresholdSignatureScheme.TWO_OF_THREE,
6501
6929
  password,
6502
6930
  signedSessionId,
6931
+ sessionPublicKey,
6503
6932
  cloudProviders: [
6504
6933
  backupLocation
6505
6934
  ],
@@ -6511,6 +6940,7 @@ class DynamicWalletClient {
6511
6940
  accountAddress,
6512
6941
  password,
6513
6942
  signedSessionId,
6943
+ sessionPublicKey,
6514
6944
  cloudProviders: [
6515
6945
  backupLocation
6516
6946
  ],
@@ -6541,7 +6971,7 @@ class DynamicWalletClient {
6541
6971
  * @param params.signedSessionId - Optional signed session ID for authentication
6542
6972
  * @param params.googleDriveAccessToken - Optional Google OAuth access token. When provided, the SDK uses it directly
6543
6973
  * instead of looking up the user's linked Google account and exchanging it for a token via the Dynamic backend.
6544
- */ async backupKeySharesToGoogleDrive({ accountAddress, password, signedSessionId, googleDriveAccessToken }) {
6974
+ */ async backupKeySharesToGoogleDrive({ accountAddress, password, signedSessionId, sessionPublicKey, googleDriveAccessToken }) {
6545
6975
  // Track whether the Drive token was supplied by the caller (external) or
6546
6976
  // will be resolved from the user's stored OAuth account (stored_oauth), so
6547
6977
  // backups using a token we don't control are auditable. Enum only — the
@@ -6561,6 +6991,7 @@ class DynamicWalletClient {
6561
6991
  accountAddress,
6562
6992
  password,
6563
6993
  signedSessionId,
6994
+ sessionPublicKey,
6564
6995
  backupLocation: core.BackupLocation.GOOGLE_DRIVE,
6565
6996
  // Forward the resolved token so the downstream upload path doesn't
6566
6997
  // re-fetch it via fetchGoogleDriveAccessToken.
@@ -6632,11 +7063,12 @@ class DynamicWalletClient {
6632
7063
  * @param params.accountAddress - The wallet account address to backup
6633
7064
  * @param params.password - Optional password for encryption (uses environment ID if not provided)
6634
7065
  * @param params.signedSessionId - Optional signed session ID for authentication
6635
- */ async backupKeySharesToICloud({ accountAddress, password, signedSessionId }) {
7066
+ */ async backupKeySharesToICloud({ accountAddress, password, signedSessionId, sessionPublicKey }) {
6636
7067
  return this.backupKeySharesToCloudProvider({
6637
7068
  accountAddress,
6638
7069
  password,
6639
7070
  signedSessionId,
7071
+ sessionPublicKey,
6640
7072
  backupLocation: core.BackupLocation.ICLOUD
6641
7073
  });
6642
7074
  }
@@ -7849,6 +8281,10 @@ class DynamicWalletClient {
7849
8281
  if (internalOptions == null ? void 0 : internalOptions.getSignedSessionId) {
7850
8282
  this.getSignedSessionIdCallback = internalOptions.getSignedSessionId;
7851
8283
  }
8284
+ // Set session public key callback if provided (internal use only)
8285
+ if (internalOptions == null ? void 0 : internalOptions.getSessionPublicKey) {
8286
+ this.getSessionPublicKeyCallback = internalOptions.getSessionPublicKey;
8287
+ }
7852
8288
  // Read the callback lazily so it tracks `getSignedSessionIdCallback` even
7853
8289
  // when tests reassign it after construction.
7854
8290
  this.signedSession = new SignedSessionManager({
@@ -8050,6 +8486,7 @@ exports.isNonRetryableCeremonyError = isNonRetryableCeremonyError;
8050
8486
  exports.isPublicKeyMismatchError = isPublicKeyMismatchError;
8051
8487
  exports.isRecoverQueueOperation = isRecoverQueueOperation;
8052
8488
  exports.isSignQueueOperation = isSignQueueOperation;
8489
+ exports.isStaleClientSharesError = isStaleClientSharesError;
8053
8490
  exports.listICloudBackups = listICloudBackups;
8054
8491
  exports.markCeremonyErrorNonRetryable = markCeremonyErrorNonRetryable;
8055
8492
  exports.readEnvironmentSettings = readEnvironmentSettings;