wallaby-cash 2.2.3 → 2.2.5

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