wallaby-cash 2.2.2 → 2.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -297,6 +297,8 @@ var V2KeyNames;
297
297
  V2KeyNames["PasskeyCredential"] = "pass-key-credential";
298
298
  V2KeyNames["PrimaryDeviceKeyShare"] = "primary-device-key-share";
299
299
  V2KeyNames["WallabyAuthPubKey"] = "wallaby-auth-pub-key";
300
+ V2KeyNames["MigrationVersion"] = "wsdk_migrated_with_version";
301
+ V2KeyNames["LastMigratedAt"] = "wsdk_last_migrated_at";
300
302
  })(V2KeyNames || (V2KeyNames = {}));
301
303
 
302
304
  var ErrorResponseCodes;
@@ -349,6 +351,7 @@ var ErrorResponseCodes;
349
351
  ErrorResponseCodes["sdk_jwt_invalid"] = "sdk_jwt_invalid";
350
352
  ErrorResponseCodes["sdk_jwt_expired"] = "sdk_jwt_expired";
351
353
  ErrorResponseCodes["sdk_unknown_error"] = "sdk_unknown_error";
354
+ ErrorResponseCodes["sdk_too_many_requests"] = "sdk_too_many_requests";
352
355
  ErrorResponseCodes["sdk_seed_phrase_decryption_failed"] = "sdk_seed_phrase_decryption_failed";
353
356
  ErrorResponseCodes["sdk_key_shares_not_found"] = "sdk_key_shares_not_found";
354
357
  ErrorResponseCodes["sdk_key_share_decryption_failed"] = "sdk_key_share_decryption_failed";
@@ -771,6 +774,7 @@ const MASTER_ENCRYPTION_KEY = '9fa9d3f3c77c20d3a50a08e5299644be29f6e6206ef3479fe
771
774
  { type: 'public-key', alg: PublicKeyCredentialAlgorithm.RS256 },
772
775
  { type: 'public-key', alg: PublicKeyCredentialAlgorithm.ES256 },
773
776
  ];
777
+ const currentPackageVersion = "2.2.4";
774
778
 
775
779
  const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
776
780
 
@@ -4819,7 +4823,7 @@ class Cipher {
4819
4823
  * @param {string} deviceKeyPair - The public key to encrypt the data with.
4820
4824
  * @returns {Promise<Encrypted>} The encrypted data ready for storage.
4821
4825
  */
4822
- async prepareDecryptedDataForStorage({ decryptedData, credentialsKeyPair, deviceKeyPair, }) {
4826
+ async doubleEncrypt({ decryptedData, credentialsKeyPair, deviceKeyPair, }) {
4823
4827
  try {
4824
4828
  // First layer of encryption using the device public key
4825
4829
  const encryptedOnceData = await this.encrypt({
@@ -4834,7 +4838,7 @@ class Cipher {
4834
4838
  return encryptedTwiceData;
4835
4839
  }
4836
4840
  catch (error) {
4837
- logger.error('SDK::prepareDecryptedDataForStorage::error', error);
4841
+ logger.error('SDK::doubleEncrypt::error', error);
4838
4842
  throw error;
4839
4843
  }
4840
4844
  }
@@ -7036,6 +7040,12 @@ class Base {
7036
7040
  set setClientAuthToken(token) {
7037
7041
  this._initializeClientAuthToken(token);
7038
7042
  }
7043
+ get version() {
7044
+ // const currentVersion = pkg.version;
7045
+ const currentVersion = currentPackageVersion;
7046
+ logger.log(`wsdk is running v${currentVersion}`);
7047
+ return currentVersion;
7048
+ }
7039
7049
  _initializeClientAuthToken(token) {
7040
7050
  if (!jwtHasSameUser(token, this.userId)) {
7041
7051
  throw new WallabyError({
@@ -8731,7 +8741,7 @@ class WalletHandlersService extends Base {
8731
8741
  errorCode: ErrorResponseCodes.sdk_unknown_error,
8732
8742
  data: error,
8733
8743
  cause: error.cause,
8734
- onError: () => console.log('Reported the error'),
8744
+ onError: () => logger.log('Reported the error'),
8735
8745
  });
8736
8746
  }
8737
8747
  }));
@@ -8838,6 +8848,8 @@ class WalletHandlersService extends Base {
8838
8848
  class WalletService extends Base {
8839
8849
  constructor(config) {
8840
8850
  super(config);
8851
+ this.passwordResetAttempts = 0;
8852
+ this.migrationAttempts = 0;
8841
8853
  this.authService = new AuthService(config);
8842
8854
  this.handlers = new WalletHandlersService(config);
8843
8855
  this.userId = config.userId;
@@ -8956,9 +8968,12 @@ class WalletService extends Base {
8956
8968
  });
8957
8969
  }
8958
8970
  catch (error) {
8959
- // If migration fails, log it but don't block the transaction
8960
- // The original transaction logic will handle missing storage items appropriately
8961
- logger.debug('Migration to V2 failed, continuing with original flow:', error);
8971
+ logger.error('SDK::WalletService::export::handleUpdateToV2::error', error);
8972
+ throw new WallabyError({
8973
+ message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
8974
+ statusCode: 500,
8975
+ errorCode: ErrorResponseCodes.sdk_unknown_error,
8976
+ });
8962
8977
  }
8963
8978
  }
8964
8979
  const encryptedSeed = await this.localStorageService.fetch(LocalStorageItems.EncryptedStandardSeedPhrase, { walletId });
@@ -9347,12 +9362,30 @@ class WalletService extends Base {
9347
9362
  */
9348
9363
  async changePassword({ walletId, oldPassword, newPassword, }) {
9349
9364
  try {
9365
+ this.passwordResetAttempts += 1;
9366
+ if (this.passwordResetAttempts > 5) {
9367
+ throw new WallabyError({
9368
+ message: 'Too many password change attempts. Please try again later.',
9369
+ statusCode: 429,
9370
+ errorCode: ErrorResponseCodes.sdk_too_many_requests,
9371
+ });
9372
+ }
9350
9373
  if (this.deviceAuthType === AuthType.Password && oldPassword) {
9351
9374
  // Handle migration to V2 first then change the password to the new one.
9352
- await this.handleUpdateToV2({
9353
- password: oldPassword,
9354
- walletId,
9355
- });
9375
+ try {
9376
+ await this.handleUpdateToV2({
9377
+ password: oldPassword,
9378
+ walletId,
9379
+ });
9380
+ }
9381
+ catch (error) {
9382
+ logger.error('SDK::WalletService::changePassword::handleUpdateToV2::error', error);
9383
+ throw new WallabyError({
9384
+ message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
9385
+ statusCode: 500,
9386
+ errorCode: ErrorResponseCodes.sdk_unknown_error,
9387
+ });
9388
+ }
9356
9389
  }
9357
9390
  const encryptedDevicePrivateKeyString = await this.localStorageService.fetch(V2KeyNames.EncryptedDevicePrivateKey);
9358
9391
  const encryptedSeedPhraseString = await this.localStorageService.fetch(V2KeyNames.EncryptedStandardSeedPhrase, {
@@ -9468,9 +9501,12 @@ class WalletService extends Base {
9468
9501
  });
9469
9502
  }
9470
9503
  catch (error) {
9471
- // If migration fails, log it but don't block the transaction
9472
- // The original transaction logic will handle missing storage items appropriately
9473
- logger.debug('Migration to V2 failed, continuing with original flow:', error);
9504
+ logger.error('SDK::WalletService::getAlgorandSeedPhrase::handleUpdateToV2::error', error);
9505
+ throw new WallabyError({
9506
+ message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
9507
+ statusCode: 500,
9508
+ errorCode: ErrorResponseCodes.sdk_unknown_error,
9509
+ });
9474
9510
  }
9475
9511
  }
9476
9512
  let wallabyBoundSeedPhrase;
@@ -9574,9 +9610,12 @@ class WalletService extends Base {
9574
9610
  });
9575
9611
  }
9576
9612
  catch (error) {
9577
- // If migration fails, log it but don't block the transaction
9578
- // The original transaction logic will handle missing storage items appropriately
9579
- logger.debug('Migration to V2 failed, continuing with original flow:', error);
9613
+ logger.error('SDK::WalletService::initAddNewDevice::handleUpdateToV2::error', error);
9614
+ throw new WallabyError({
9615
+ message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
9616
+ statusCode: 500,
9617
+ errorCode: ErrorResponseCodes.sdk_unknown_error,
9618
+ });
9580
9619
  }
9581
9620
  }
9582
9621
  const storedEncryptedPrimaryShare = await this.localStorageService.fetch(LocalStorageItems.PrimaryDeviceKeyShare, {
@@ -9739,9 +9778,12 @@ class WalletService extends Base {
9739
9778
  });
9740
9779
  }
9741
9780
  catch (error) {
9742
- // If migration fails, log it but don't block the transaction
9743
- // The original transaction logic will handle missing storage items appropriately
9744
- logger.debug('Migration to V2 failed, continuing with original flow:', error);
9781
+ logger.error('SDK::WalletService::generateWalletAddresses::handleUpdateToV2::error', error);
9782
+ throw new WallabyError({
9783
+ message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
9784
+ statusCode: 500,
9785
+ errorCode: ErrorResponseCodes.sdk_unknown_error,
9786
+ });
9745
9787
  }
9746
9788
  }
9747
9789
  try {
@@ -9833,19 +9875,15 @@ class WalletService extends Base {
9833
9875
  * decrypt them using appropriate decryption methods, and call wallet.recover() to create new v2 keys.
9834
9876
  */
9835
9877
  async handleUpdateToV2({ password, walletId }) {
9836
- try {
9837
- logger.info('SDK::WalletService::handleUpdateToV2::starting migration check');
9838
- const v2EncryptedDevicePrivateKey = await this.localStorageService.fetch(V2KeyNames.EncryptedDevicePrivateKey);
9839
- const v2EncryptedSeed = await this.localStorageService.fetch(V2KeyNames.EncryptedStandardSeedPhrase, { walletId });
9840
- const v2EncryptedPrimaryDeviceShare = await this.localStorageService.fetch(V2KeyNames.PrimaryDeviceKeyShare, {
9841
- walletId,
9878
+ const migrationStartTime = Date.now();
9879
+ if (this.migrationAttempts > 5) {
9880
+ throw new WallabyError({
9881
+ message: 'Too many migration attempts. Please try again later.',
9882
+ statusCode: 429,
9883
+ errorCode: ErrorResponseCodes.sdk_too_many_requests,
9842
9884
  });
9843
- if (v2EncryptedDevicePrivateKey && (v2EncryptedSeed || v2EncryptedPrimaryDeviceShare)) {
9844
- logger.info('SDK::WalletService::handleUpdateToV2::V2 items already exist, no migration needed');
9845
- // If V2 items are present,
9846
- // we don't need to throw any errors, just continue with rest of flow.
9847
- return;
9848
- }
9885
+ }
9886
+ try {
9849
9887
  if (!password) {
9850
9888
  throw new WallabyError({
9851
9889
  message: 'Password is required for migration to v2',
@@ -9853,24 +9891,90 @@ class WalletService extends Base {
9853
9891
  errorCode: ErrorResponseCodes.sdk_missing_parameter,
9854
9892
  });
9855
9893
  }
9894
+ // Check migration metadata FIRST (lightweight, no network/crypto operations)
9895
+ const currentSdkVersion = this.version;
9896
+ const sdkMigrationVersion = await this.localStorageService.fetch(V2KeyNames.MigrationVersion);
9897
+ const lastMigratedAt = await this.localStorageService.fetch(V2KeyNames.LastMigratedAt);
9898
+ logger.info('SDK::WalletService::handleUpdateToV2::starting migration check', {
9899
+ timestamp: new Date(migrationStartTime).toISOString(),
9900
+ walletId: walletId.substring(0, 8) + '...',
9901
+ lastMigratedAt,
9902
+ currentSdkVersion,
9903
+ sdkMigrationVersion,
9904
+ });
9905
+ // If migration completed successfully before (has a valid timestamp, not 'never')
9906
+ // 'never' indicates a previous failure and allows retry attempts
9907
+ if (lastMigratedAt && lastMigratedAt !== 'never' && sdkMigrationVersion) {
9908
+ logger.info('SDK::WalletService::handleUpdateToV2::Migration already completed successfully, skipping', {
9909
+ migratedVersion: sdkMigrationVersion,
9910
+ migratedAt: lastMigratedAt,
9911
+ });
9912
+ return;
9913
+ }
9914
+ // Migration needed - proceed with V2 existence check and potential migration
9915
+ const v2EncryptedDevicePrivateKey = await this.localStorageService.fetch(V2KeyNames.EncryptedDevicePrivateKey);
9916
+ const v2EncryptedSeed = await this.localStorageService.fetch(V2KeyNames.EncryptedStandardSeedPhrase, { walletId });
9917
+ const v2EncryptedPrimaryDeviceShare = await this.localStorageService.fetch(V2KeyNames.PrimaryDeviceKeyShare, {
9918
+ walletId,
9919
+ });
9856
9920
  const clientSalt = await this.authService.getUserSalt();
9921
+ const credentialsKeyPair = await this.cipher.getCredentialsKeyPair({
9922
+ authType: AuthType.Password,
9923
+ password,
9924
+ salt: clientSalt,
9925
+ });
9926
+ if (v2EncryptedDevicePrivateKey && (v2EncryptedSeed || v2EncryptedPrimaryDeviceShare)) {
9927
+ try {
9928
+ await this.cipher.decrypt({
9929
+ cipherText: safeJsonParse(v2EncryptedDevicePrivateKey),
9930
+ decryptionKey: credentialsKeyPair.privateKey,
9931
+ });
9932
+ // Explicitly select the non-empty value between seed and primary device share
9933
+ const v2SeedData = v2EncryptedSeed || v2EncryptedPrimaryDeviceShare;
9934
+ await this.cipher.displayStoredData({
9935
+ storedEncryptedData: safeJsonParse(v2SeedData),
9936
+ encryptedDevicePrivateKey: safeJsonParse(v2EncryptedDevicePrivateKey),
9937
+ options: {
9938
+ authType: AuthType.Password,
9939
+ password,
9940
+ salt: clientSalt,
9941
+ },
9942
+ });
9943
+ logger.info('SDK::WalletService::handleUpdateToV2::V2 items already exist and are valid, no migration needed');
9944
+ // V2 exists and is valid - update metadata to avoid future checks
9945
+ await this.localStorageService.save(V2KeyNames.LastMigratedAt, new Date().toISOString());
9946
+ await this.localStorageService.save(V2KeyNames.MigrationVersion, currentSdkVersion);
9947
+ return;
9948
+ }
9949
+ catch (error) {
9950
+ logger.info('SDK::WalletService::handleUpdateToV2::V2 items exist but decryption failed, proceeding with migration', {
9951
+ error: JSON.stringify(error),
9952
+ });
9953
+ }
9954
+ }
9955
+ // Increment counter after V2 validation to avoid counting when migration not needed
9956
+ this.migrationAttempts += 1;
9857
9957
  let decryptedSeedPhrase;
9858
9958
  let decryptedPrivateKey;
9859
9959
  // Check for legacy format: `{item}_{userId}`
9860
9960
  const legacyEncryptedSeed = await this.localStorageService.getFromDeviceStorage(`${LegacyKeyNames.EncryptedSeed}_${this.userId}`);
9861
- const legacyEncryptedPrivateKey = await this.localStorageService.getFromDeviceStorage(`${LegacyKeyNames.EncryptedPrivateKey}_${this.userId}`);
9862
- if (legacyEncryptedSeed && legacyEncryptedPrivateKey) {
9863
- logger.info('SDK::WalletService::handleUpdateToV2::Found legacy storage items, attempting migration');
9961
+ // getDecryptedV1PrivateKey checks for both v1 and legacy formats internally
9962
+ const legacyDecryptedPrivateKey = await this.localStorageService.getDecryptedV1PrivateKey(password);
9963
+ if (legacyEncryptedSeed && legacyDecryptedPrivateKey) {
9964
+ const legacyPublicKey = publicKeyByPrivateKey(legacyDecryptedPrivateKey);
9965
+ logger.info('SDK::WalletService::handleUpdateToV2::Found legacy storage items, attempting migration', {
9966
+ storageFormat: 'legacy',
9967
+ devicePublicKey: legacyPublicKey.substring(0, 16) + '...',
9968
+ });
9864
9969
  try {
9865
9970
  // Decrypt legacy items using password/salt combination
9866
- const decryptedLegacyKey = AES.decrypt(legacyEncryptedPrivateKey, `${clientSalt}${password}`);
9867
9971
  const decryptedOnceSeed = AES.decrypt(legacyEncryptedSeed, `${clientSalt}${password}`);
9868
- const parsedDecryptedSeed = safeJsonParse(decryptedOnceSeed.toString(enc.Utf8));
9869
- decryptedPrivateKey = decryptedLegacyKey.toString(enc.Utf8);
9870
- decryptedSeedPhrase = decryptWithPrivateKey(decryptedPrivateKey, parsedDecryptedSeed);
9871
- if (!decryptedSeedPhrase || !decryptedPrivateKey) {
9972
+ const parsedDecryptedOnceSeed = safeJsonParse(decryptedOnceSeed.toString(enc.Utf8));
9973
+ decryptedSeedPhrase = decryptWithPrivateKey(legacyDecryptedPrivateKey, parsedDecryptedOnceSeed);
9974
+ decryptedPrivateKey = legacyDecryptedPrivateKey; // Assign the decrypted private key
9975
+ if (!decryptedSeedPhrase) {
9872
9976
  throw new WallabyError({
9873
- message: 'Failed to decrypt legacy items with provided password',
9977
+ message: 'Failed to decrypt legacy seed phrase items with provided password',
9874
9978
  statusCode: 500,
9875
9979
  errorCode: ErrorResponseCodes.sdk_seed_phrase_decryption_failed,
9876
9980
  });
@@ -9892,9 +9996,17 @@ class WalletService extends Base {
9892
9996
  const v1EncryptedSeed = await this.localStorageService.getEncryptedSeedPhrase(SeedPhraseType.Standard, walletId);
9893
9997
  const v1EncryptedPrivateKey = await this.localStorageService.getEncryptedPrivateKey();
9894
9998
  if (v1EncryptedSeed && v1EncryptedPrivateKey) {
9895
- logger.info('SDK::WalletService::handleUpdateToV2::Found V1 storage items, attempting migration');
9999
+ // Get public key before decryption for logging
10000
+ decryptedPrivateKey = await this.localStorageService.getDecryptedV1PrivateKey(password);
10001
+ const v1PublicKey = decryptedPrivateKey ? publicKeyByPrivateKey(decryptedPrivateKey) : 'unknown';
10002
+ logger.info('SDK::WalletService::handleUpdateToV2::Found V1 storage items, attempting migration', {
10003
+ storageFormat: 'v1',
10004
+ devicePublicKey: v1PublicKey.substring(0, 16) + '...',
10005
+ });
9896
10006
  try {
9897
10007
  // Decrypt V1 items using storage service method (handles double encryption)
10008
+ logger.log('Attempting to decrypt V1 items during migration...');
10009
+ logger.log('getV1DecryptedSeedPhrase should be called with password and clientSalt:', { password, clientSalt });
9898
10010
  decryptedSeedPhrase = await this.localStorageService.getV1DecryptedSeedPhrase(password, clientSalt);
9899
10011
  // For V1 format, private key is encrypted with just the password (not salt+password like legacy)
9900
10012
  decryptedPrivateKey = await this.localStorageService.getDecryptedV1PrivateKey(password);
@@ -9922,44 +10034,72 @@ class WalletService extends Base {
9922
10034
  return;
9923
10035
  }
9924
10036
  }
9925
- if (decryptedSeedPhrase) {
10037
+ if (decryptedSeedPhrase && decryptedPrivateKey) {
9926
10038
  logger.info('SDK::WalletService::handleUpdateToV2::Initiating wallet recovery for V2 migration');
9927
10039
  logger.info('SDK::WalletService::handleUpdateToV2::Migration data prepared');
9928
10040
  logger.info('SDK::WalletService::handleUpdateToV2::Seed phrase available:', !!decryptedSeedPhrase);
9929
10041
  // During migration, we need to authenticate but avoid creating conflicting device keypairs
9930
- // We'll create a temporary device keypair just for authentication, then let recover() create the final one
9931
- const tempDeviceKeyPair = createIdentity();
9932
- const tempSignatureMessage = await this.authService.getSignature({
9933
- publicKey: tempDeviceKeyPair.publicKey,
9934
- privateKey: tempDeviceKeyPair.privateKey,
10042
+ const devicePublicKey = publicKeyByPrivateKey(decryptedPrivateKey);
10043
+ const signInSignatureMessage = await this.authService.getSignature({
10044
+ publicKey: devicePublicKey,
10045
+ privateKey: decryptedPrivateKey,
9935
10046
  });
10047
+ // this would ensure the stored public key is consistent with wallaby and can authenticate the user.
9936
10048
  const authResponse = await this.request(AuthRoutes.signIn, {
9937
10049
  payload: {
9938
10050
  externalUserId: this.userId,
9939
- message: tempSignatureMessage.message,
9940
- signature: tempSignatureMessage.signature,
9941
- clientAuthPubKey: tempDeviceKeyPair.publicKey,
10051
+ message: signInSignatureMessage.message,
10052
+ signature: signInSignatureMessage.signature,
10053
+ clientAuthPubKey: devicePublicKey,
10054
+ },
10055
+ });
10056
+ const encryptedV2PrivateKey = await this.cipher.encrypt({
10057
+ data: decryptedPrivateKey,
10058
+ encryptionKey: credentialsKeyPair.publicKey,
10059
+ });
10060
+ const encryptedV2Seed = await this.cipher.doubleEncrypt({
10061
+ decryptedData: decryptedSeedPhrase,
10062
+ credentialsKeyPair,
10063
+ deviceKeyPair: {
10064
+ publicKey: devicePublicKey,
10065
+ privateKey: decryptedPrivateKey,
9942
10066
  },
9943
10067
  });
9944
10068
  // Store authentication tokens
9945
10069
  await this.localStorageService.saveInBulk([
9946
10070
  { key: LocalStorageItems.AccessToken, value: authResponse.accessToken },
9947
10071
  { key: LocalStorageItems.WallabyAuthPubKey, value: authResponse.user.wallabyAuthPubKey },
10072
+ { key: V2KeyNames.EncryptedStandardSeedPhrase, value: encryptedV2Seed, walletId },
10073
+ { key: V2KeyNames.EncryptedDevicePrivateKey, value: encryptedV2PrivateKey },
9948
10074
  ]);
9949
- await this.recover({
9950
- authenticationOptions: Object.assign(Object.assign({}, authResponse), { signatureMessageResponse: tempSignatureMessage, password,
9951
- clientSalt }),
9952
- walletId,
9953
- seedPhrase: decryptedSeedPhrase,
9954
- storeSeedPhrase: true,
9955
- returnWalletOption: ReturnWalletOption.ReturnOnlyEncryptedSeedPhrase,
10075
+ logger.info('SDK::WalletService::handleUpdateToV2::Migration completed successfully', {
10076
+ timestamp: new Date().toISOString(),
10077
+ duration: Date.now() - migrationStartTime,
10078
+ devicePublicKey: devicePublicKey.substring(0, 16) + '...',
10079
+ migratedKeys: ['EncryptedDevicePrivateKey', 'EncryptedStandardSeedPhrase'],
9956
10080
  });
9957
- logger.info('SDK::WalletService::handleUpdateToV2::Migration completed successfully');
10081
+ await this.localStorageService.save(V2KeyNames.LastMigratedAt, new Date().toISOString());
10082
+ await this.localStorageService.save(V2KeyNames.MigrationVersion, this.version);
9958
10083
  return;
9959
10084
  }
10085
+ else {
10086
+ throw new WallabyError({
10087
+ message: 'Decrypted data required for migration is missing, operation cannot be completed.',
10088
+ statusCode: 500,
10089
+ errorCode: ErrorResponseCodes.sdk_unknown_error,
10090
+ });
10091
+ }
9960
10092
  }
9961
10093
  catch (error) {
9962
- logger.error('SDK::WalletService::handleUpdateToV2::Migration failed', error);
10094
+ logger.error('SDK::WalletService::handleUpdateToV2::Migration failed', {
10095
+ timestamp: new Date().toISOString(),
10096
+ duration: Date.now() - migrationStartTime,
10097
+ error: error instanceof Error ? error.message : 'Unknown error',
10098
+ });
10099
+ // Save 'never' to indicate failure, which still allows retries (checked in early return)
10100
+ // Rate limiting prevents infinite retry attempts
10101
+ await this.localStorageService.save(V2KeyNames.LastMigratedAt, 'never');
10102
+ await this.localStorageService.save(V2KeyNames.MigrationVersion, this.version);
9963
10103
  throw error;
9964
10104
  }
9965
10105
  }
@@ -9976,15 +10116,6 @@ class WalletService extends Base {
9976
10116
  try {
9977
10117
  const { readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares, signatureMessage, deviceAuthPublicKey } = await this.prepareWalletOperationAuth({ authenticationOptions: input.authenticationOptions, walletId: input.walletId });
9978
10118
  const shouldSendSeedPhrase = readyForTransportSeedPhrase && !hasShares;
9979
- // const accessVerificationResponse = await this.request<{ isAccessVerified: boolean }>(WalletRoutes.verifyAccess, {
9980
- // payload: {
9981
- // ...signatureMessage,
9982
- // clientAuthPubKey: deviceAuthPublicKey,
9983
- // encryptedSeed: shouldSendSeedPhrase ? readyForTransportSeedPhrase : undefined,
9984
- // encryptedShares: !shouldSendSeedPhrase ? sharesEncryptedWithWallabyPubKey : undefined,
9985
- // walletId: input.walletId,
9986
- // },
9987
- // });
9988
10119
  const accessVerificationResponse = await this.api.wallets.verifyAccess({
9989
10120
  message: signatureMessage.message,
9990
10121
  signature: signatureMessage.signature,
@@ -10224,6 +10355,12 @@ __decorate([
10224
10355
  __metadata("design:paramtypes", [Object]),
10225
10356
  __metadata("design:returntype", Promise)
10226
10357
  ], WalletService.prototype, "changePassword", null);
10358
+ __decorate([
10359
+ WithLock('migrateToV2'),
10360
+ __metadata("design:type", Function),
10361
+ __metadata("design:paramtypes", [Object]),
10362
+ __metadata("design:returntype", Promise)
10363
+ ], WalletService.prototype, "handleUpdateToV2", null);
10227
10364
 
10228
10365
  class WalletDataService extends Base {
10229
10366
  constructor(config) {
@@ -10451,10 +10588,20 @@ class WalletDataService extends Base {
10451
10588
  });
10452
10589
  }
10453
10590
  if (this.deviceAuthType === AuthType.Password && authenticationOptions.password) {
10454
- await this.walletService.handleUpdateToV2({
10455
- password: authenticationOptions.password,
10456
- walletId: walletId,
10457
- });
10591
+ try {
10592
+ await this.walletService.handleUpdateToV2({
10593
+ password: authenticationOptions.password,
10594
+ walletId: walletId,
10595
+ });
10596
+ }
10597
+ catch (error) {
10598
+ logger.error('SDK::WalletDataService::addNewChainAndTokenToWallet::handleUpdateToV2::error', error);
10599
+ throw new WallabyError({
10600
+ message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
10601
+ statusCode: 500,
10602
+ errorCode: ErrorResponseCodes.sdk_unknown_error,
10603
+ });
10604
+ }
10458
10605
  }
10459
10606
  try {
10460
10607
  const addressInfo = await this.walletService.generateWalletAddresses({
@@ -11138,9 +11285,12 @@ class Transactions extends Base {
11138
11285
  });
11139
11286
  }
11140
11287
  catch (error) {
11141
- // If migration fails, log it but don't block the transaction
11142
- // The original transaction logic will handle missing storage items appropriately
11143
- logger.debug('Migration to V2 failed, continuing with original flow:', error);
11288
+ logger.error('SDK::Transactions::transfer::handleUpdateToV2::error', error);
11289
+ throw new WallabyError({
11290
+ message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
11291
+ statusCode: 500,
11292
+ errorCode: ErrorResponseCodes.sdk_unknown_error,
11293
+ });
11144
11294
  }
11145
11295
  }
11146
11296
  const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareTransactionAuth(authenticationOptions, walletId);
@@ -11215,9 +11365,12 @@ class Transactions extends Base {
11215
11365
  });
11216
11366
  }
11217
11367
  catch (error) {
11218
- // If migration fails, log it but don't block the transaction
11219
- // The original transaction logic will handle missing storage items appropriately
11220
- logger.debug('Migration to V2 failed, continuing with original flow:', error);
11368
+ logger.error('SDK::Transactions::createAllowance::handleUpdateToV2::error', error);
11369
+ throw new WallabyError({
11370
+ message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
11371
+ statusCode: 500,
11372
+ errorCode: ErrorResponseCodes.sdk_unknown_error,
11373
+ });
11221
11374
  }
11222
11375
  }
11223
11376
  const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareTransactionAuth(authenticationOptions, walletId);
@@ -11290,9 +11443,12 @@ class Transactions extends Base {
11290
11443
  });
11291
11444
  }
11292
11445
  catch (error) {
11293
- // If migration fails, log it but don't block the transaction
11294
- // The original transaction logic will handle missing storage items appropriately
11295
- logger.debug('Migration to V2 failed, continuing with original flow:', error);
11446
+ logger.error('SDK::Transactions::resolvePendingTransaction::handleUpdateToV2::error', error);
11447
+ throw new WallabyError({
11448
+ message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
11449
+ statusCode: 500,
11450
+ errorCode: ErrorResponseCodes.sdk_unknown_error,
11451
+ });
11296
11452
  }
11297
11453
  }
11298
11454
  const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareTransactionAuth(authenticationOptions, walletId);
@@ -11453,6 +11609,9 @@ class Wallaby {
11453
11609
  this.merchants = new Merchants(config);
11454
11610
  this.httpApi = new HttpApi(config);
11455
11611
  }
11612
+ get version() {
11613
+ return currentPackageVersion;
11614
+ }
11456
11615
  }
11457
11616
 
11458
11617
  export { AddressType, AndroidVersionNotSupportedError, ApiKeyStatus, AssetConfigStatus, AssetType, AuthType, AuthenticatorGeneralError, AuthenticatorMissingDiscoverableCredentialSupportError, AuthenticatorMissingUserVerificationSupportError, AuthenticatorNoSupportedPubKeyCredParamsAlgError, AuthenticatorNotRegisteredError, AuthenticatorPreviouslyRegisteredError, AutoRegisterUserVerificationFailureError, BadConfiguration, BlockchainName, BlockchainSlip44, BlockchainStatus, CeremonyAbortedError, ErrorResponseCodes, IOSVersionNotSupportedError, InterruptedError, InvalidChallengeError, InvalidDomainError, InvalidRpIdError, InvalidStateError, InvalidUserIdError, InvalidUserIdLengthError, KeyTypeName, LegacyKeyNames, LocalStorageItems, MalformedPubKeyCredParamsError, NativeError, NoCredentialsError, NotAllowedError, OwnershipType, PasskeyChallengeType, PasskeyErrorCodes, PassthroughSeeCausePropertyError, PublicKeyCredentialAlgorithm, RequestFailedError, RequestMethod, ReturnWalletOption, SeedPhraseType, TimeoutError, TokenStandard, TransactionEntryType, TransportEnum, UnknownError, UserAssetSource, UserCancelledError, V1KeyNames, V2KeyNames, Wallaby, Api as WallabyApiClient, WallabyError, HttpClient as WallabyHttpClient, WalletAddressTypeName, WalletOwnershipType, createIdentity, decryptWithPrivateKey, encryptWithPublicKey, hash, keccak256, publicKeyByPrivateKey, recoverPublicKey, sign };