wallaby-cash 3.3.0 → 3.4.0

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.cjs.js CHANGED
@@ -342,6 +342,10 @@ exports.V2KeyNames = void 0;
342
342
  V2KeyNames["WallabyAuthPubKey"] = "wallaby-auth-pub-key";
343
343
  V2KeyNames["MigrationVersion"] = "wsdk_migrated_with_version";
344
344
  V2KeyNames["LastMigratedAt"] = "wsdk_last_migrated_at";
345
+ V2KeyNames["PasswordResetAttempts"] = "wsdk_password_reset_attempts";
346
+ V2KeyNames["MigrationAttempts"] = "wsdk_migration_attempts";
347
+ V2KeyNames["CredentialConversionInProgress"] = "credential-conversion-in-progress";
348
+ V2KeyNames["PendingCommit"] = "pending-commit";
345
349
  })(exports.V2KeyNames || (exports.V2KeyNames = {}));
346
350
 
347
351
  exports.ErrorResponseCodes = void 0;
@@ -572,7 +576,7 @@ const global$1 = (typeof global !== "undefined" ? global :
572
576
  typeof self !== "undefined" ? self :
573
577
  typeof window !== "undefined" ? window : {});
574
578
 
575
- var env = {};
579
+ var env$1 = {};
576
580
 
577
581
  // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js
578
582
  var performance = global$1.performance || {};
@@ -584,7 +588,7 @@ performance.now ||
584
588
  function(){ return (new Date()).getTime() };
585
589
 
586
590
  var browser$1 = {
587
- env: env};
591
+ env: env$1};
588
592
 
589
593
  var _a;
590
594
  /**
@@ -618,7 +622,12 @@ const MASTER_ENCRYPTION_KEY = '9fa9d3f3c77c20d3a50a08e5299644be29f6e6206ef3479fe
618
622
  { type: 'public-key', alg: exports.PublicKeyCredentialAlgorithm.ES256 },
619
623
  ];
620
624
  const isWeb = typeof window !== 'undefined' && typeof document !== 'undefined';
621
- const currentPackageVersion = "3.3.0" ;
625
+ const env = {
626
+ platform: 'web',
627
+ isNative: !isWeb,
628
+ isWeb,
629
+ };
630
+ const currentPackageVersion = "3.4.0" ;
622
631
 
623
632
  /**
624
633
  * Storage keys adapter for Storage interface across different platforms.
@@ -3519,7 +3528,6 @@ const keccak256$1 = (() => {
3519
3528
  })();
3520
3529
 
3521
3530
  const DEFAULT_ENTROPY_BYTES = 32;
3522
- const MINIMUM_SHANNON_ENTROPY = 4;
3523
3531
  /**
3524
3532
  * creates a new private key
3525
3533
  * @param { Uint8Array } entropy - optional entropy to create the private key
@@ -3530,25 +3538,15 @@ const createPrivateKey = (entropy) => {
3530
3538
  if (!(entropy instanceof Uint8Array) || entropy.length < DEFAULT_ENTROPY_BYTES) {
3531
3539
  throw new Error(`entropy must be a Uint8Array of at least ${DEFAULT_ENTROPY_BYTES} bytes`);
3532
3540
  }
3533
- // Check byte diversity
3541
+ // Check byte diversity. This catches genuinely broken inputs (all-zeros, all-same-byte)
3542
+ // without false-positiving on 32-byte KDF output (~30 unique bytes expected).
3543
+ // the sampled Shannon-entropy check was removed (WAL-1465) — it's unsound for
3544
+ // 32 samples (max measurable = log2(32) ≈ 5 bits/byte vs a 4-bit threshold), so deterministic
3545
+ // KDF output could be rejected, permanently locking the user out.
3534
3546
  const uniqueBytes = new Set(entropy);
3535
3547
  if (uniqueBytes.size < Math.min(8, entropy.length / 4)) {
3536
3548
  throw new Error(`entropy is too repetitive (only ${uniqueBytes.size} unique byte values)`);
3537
3549
  }
3538
- // Estimate Shannon entropy
3539
- const byteCounts = new Uint32Array(256);
3540
- entropy.forEach((b) => byteCounts[b]++);
3541
- const total = entropy.length;
3542
- let shannonEntropy = 0;
3543
- for (let i = 0; i < 256; i++) {
3544
- if (byteCounts[i] > 0) {
3545
- const p = byteCounts[i] / total;
3546
- shannonEntropy -= p * Math.log2(p);
3547
- }
3548
- }
3549
- if (shannonEntropy < MINIMUM_SHANNON_ENTROPY) {
3550
- throw new Error(`entropy has low Shannon entropy (${shannonEntropy.toFixed(2)} bits/byte)`);
3551
- }
3552
3550
  const outerHex = keccak256$1(entropy);
3553
3551
  return addLeading0x(bytesToHex$1(outerHex));
3554
3552
  }
@@ -4423,6 +4421,11 @@ function pbkdf2Sync(password, salt, iterations, keylen, digest) {
4423
4421
  });
4424
4422
  }
4425
4423
 
4424
+ // Version marker prepended to values wrapped by the master key, so wrapped vs raw is deterministic.
4425
+ const MASTER_KEY_WRAP_PREFIX = 'wsdkmk:v1:';
4426
+ // crypto-js AES.encrypt with a string passphrase emits an OpenSSL "Salted__" header; its base64 always
4427
+ // starts with this. Used to recognize legacy wrapped values stored before MASTER_KEY_WRAP_PREFIX existed.
4428
+ const LEGACY_CRYPTOJS_PREFIX = 'U2FsdGVkX1';
4426
4429
  class Cipher {
4427
4430
  constructor() { }
4428
4431
  /**
@@ -4453,11 +4456,23 @@ class Cipher {
4453
4456
  * @returns The encrypted data as a string.
4454
4457
  */
4455
4458
  encryptWithMasterKey({ data }) {
4456
- return cryptoJs.AES.encrypt(typeof data === 'string' ? data : JSON.stringify(data), this.getMasterKey().key).toString();
4459
+ const ciphertext = cryptoJs.AES.encrypt(typeof data === 'string' ? data : JSON.stringify(data), this.getMasterKey().key).toString();
4460
+ return MASTER_KEY_WRAP_PREFIX + ciphertext;
4461
+ }
4462
+ /**
4463
+ * @description Determines deterministically whether a stored value was wrapped by the master key,
4464
+ * without inferring from decrypt behavior. Returns true for values carrying the version marker, or
4465
+ * legacy crypto-js ciphertext stored before the marker existed. Everything else is treated as raw.
4466
+ */
4467
+ isWrappedByMasterKey(value) {
4468
+ return value.startsWith(MASTER_KEY_WRAP_PREFIX) || value.startsWith(LEGACY_CRYPTOJS_PREFIX);
4457
4469
  }
4458
4470
  decryptWithMasterKey({ cipherText }) {
4471
+ const ciphertext = cipherText.startsWith(MASTER_KEY_WRAP_PREFIX)
4472
+ ? cipherText.slice(MASTER_KEY_WRAP_PREFIX.length)
4473
+ : cipherText;
4459
4474
  try {
4460
- const decrypted = cryptoJs.AES.decrypt(cipherText, this.getMasterKey().key).toString(cryptoJs.enc.Utf8);
4475
+ const decrypted = cryptoJs.AES.decrypt(ciphertext, this.getMasterKey().key).toString(cryptoJs.enc.Utf8);
4461
4476
  if (decrypted) {
4462
4477
  return isJsonString(decrypted) ? safeJsonParse(decrypted) : decrypted;
4463
4478
  }
@@ -4575,6 +4590,8 @@ class Cipher {
4575
4590
  }
4576
4591
  derivedKeyPair = await this.deriveKeyPairFromPasskey({ inputKeyMaterial: options.prfValue });
4577
4592
  return derivedKeyPair;
4593
+ default:
4594
+ throw new Error(`Unknown AuthType: ${options.authType}`);
4578
4595
  }
4579
4596
  }
4580
4597
  catch (error) {
@@ -4834,6 +4851,14 @@ class StorageService {
4834
4851
  return;
4835
4852
  }
4836
4853
  async fetch(key, options) {
4854
+ var _a;
4855
+ // Recover once per session; memoize the promise so concurrent first-fetches all await the same
4856
+ // recovery instead of racing past it and reading pre-recovery storage. recoverCommit uses
4857
+ // getItem/removeItem (not fetch), so there's no recursion. Swallow errors: recovery is
4858
+ // best-effort and a failure must not wedge every subsequent fetch.
4859
+ await ((_a = this._walRecovery) !== null && _a !== void 0 ? _a : (this._walRecovery = this.recoverCommit().catch((error) => {
4860
+ logger.error('SDK::StorageService::fetch::wal recovery failed', error);
4861
+ })));
4837
4862
  let storageKey;
4838
4863
  if (this._walletSpecificKeys.includes(key)) {
4839
4864
  if (!(options === null || options === void 0 ? void 0 : options.walletId)) {
@@ -4844,7 +4869,7 @@ class StorageService {
4844
4869
  else {
4845
4870
  storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}`;
4846
4871
  }
4847
- if (!isWeb) {
4872
+ if (env.isNative) {
4848
4873
  storageKey = normalizeKey(storageKey);
4849
4874
  }
4850
4875
  const item = await this.getItem(storageKey);
@@ -4853,14 +4878,11 @@ class StorageService {
4853
4878
  return undefined;
4854
4879
  }
4855
4880
  if (this._keysProtectedByMasterKey.includes(key)) {
4856
- let unwrapped;
4857
- // Temp fix to unblock prod issue. Need a more permanent solution.
4858
- try {
4859
- unwrapped = this.cipher.decryptWithMasterKey({ cipherText: item });
4860
- }
4861
- catch (_a) {
4862
- unwrapped = item;
4881
+ // Raw legacy value stored before master-key wrapping: return as-is instead of attempting decrypt.
4882
+ if (!this.cipher.isWrappedByMasterKey(item)) {
4883
+ return item;
4863
4884
  }
4885
+ const unwrapped = this.cipher.decryptWithMasterKey({ cipherText: item });
4864
4886
  if (!unwrapped) {
4865
4887
  logger.error(`Failed to decrypt item with key ${storageKey}`);
4866
4888
  return undefined;
@@ -4880,7 +4902,7 @@ class StorageService {
4880
4902
  else {
4881
4903
  storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}`;
4882
4904
  }
4883
- if (!isWeb) {
4905
+ if (env.isNative) {
4884
4906
  storageKey = normalizeKey(storageKey);
4885
4907
  }
4886
4908
  let valueToStore;
@@ -4896,6 +4918,75 @@ class StorageService {
4896
4918
  async saveInBulk(data) {
4897
4919
  await Promise.all(data.map((item) => this.save(item.key, item.value, { walletId: item.walletId })));
4898
4920
  }
4921
+ // Compute the final storage key the same way save/fetch/delete do.
4922
+ _computeRawKey(key, walletId) {
4923
+ let storageKey;
4924
+ if (this._walletSpecificKeys.includes(key)) {
4925
+ if (!walletId)
4926
+ throw new Error(`A walletId is required to compute key: ${key}`);
4927
+ storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}:${walletId}`;
4928
+ }
4929
+ else {
4930
+ storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}`;
4931
+ }
4932
+ return isWeb ? storageKey : normalizeKey(storageKey);
4933
+ }
4934
+ _serializeValue(key, value) {
4935
+ if (this._keysProtectedByMasterKey.includes(key)) {
4936
+ return this.cipher.encryptWithMasterKey({ data: value });
4937
+ }
4938
+ return typeof value === 'string' ? value : JSON.stringify(value);
4939
+ }
4940
+ async _applyWAL(record) {
4941
+ for (const { rawKey, value } of record.writes) {
4942
+ await this.setItem(rawKey, value);
4943
+ }
4944
+ for (const rawKey of record.deletes) {
4945
+ await this.removeItem(rawKey);
4946
+ }
4947
+ }
4948
+ // Atomically commit a batch of writes and deletes via a write-ahead log.
4949
+ // The WAL record is written in a single setItem before any credential key is
4950
+ // touched. A crash between that write and the individual setItem calls leaves
4951
+ // the WAL in place; recoverCommit() finishes the batch on the next call.
4952
+ async commitBatch(writes, deletes) {
4953
+ const record = {
4954
+ writes: writes.map(({ key, value, walletId }) => ({
4955
+ rawKey: this._computeRawKey(key, walletId),
4956
+ value: this._serializeValue(key, value),
4957
+ })),
4958
+ deletes: (deletes !== null && deletes !== void 0 ? deletes : []).map(({ key, walletId }) => this._computeRawKey(key, walletId)),
4959
+ };
4960
+ // Finish any dangling WAL from a prior partially-applied commit before writing a new one —
4961
+ // otherwise this setItem clobbers it and those half-written credentials become unrecoverable.
4962
+ await this.recoverCommit();
4963
+ const walKey = this._computeRawKey(exports.V2KeyNames.PendingCommit);
4964
+ await this.setItem(walKey, JSON.stringify(record));
4965
+ await this._applyWAL(record);
4966
+ await this.removeItem(walKey);
4967
+ }
4968
+ // Re-apply a pending WAL commit if the process was killed mid-batch.
4969
+ // Call at the start of any operation that writes credential blobs.
4970
+ async recoverCommit() {
4971
+ const walKey = this._computeRawKey(exports.V2KeyNames.PendingCommit);
4972
+ const raw = await this.getItem(walKey);
4973
+ if (!raw)
4974
+ return;
4975
+ let record;
4976
+ try {
4977
+ record = safeJsonParse(raw);
4978
+ }
4979
+ catch (error) {
4980
+ // Corrupt/unparseable WAL can never be replayed — discard so it doesn't wedge every fetch.
4981
+ logger.error('SDK::StorageService::recoverCommit::corrupt WAL, discarding', error);
4982
+ await this.removeItem(walKey);
4983
+ return;
4984
+ }
4985
+ // _applyWAL is idempotent. If it throws (transient storage error) keep the WAL and let the
4986
+ // caller retry — don't delete the only record needed to finish the batch. Remove only on success.
4987
+ await this._applyWAL(record);
4988
+ await this.removeItem(walKey);
4989
+ }
4899
4990
  async delete(key, options) {
4900
4991
  let storageKey;
4901
4992
  if (this._walletSpecificKeys.includes(key)) {
@@ -4907,7 +4998,7 @@ class StorageService {
4907
4998
  else {
4908
4999
  storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}`;
4909
5000
  }
4910
- if (!isWeb) {
5001
+ if (env.isNative) {
4911
5002
  storageKey = normalizeKey(storageKey);
4912
5003
  }
4913
5004
  return await this.removeItem(storageKey);
@@ -5172,11 +5263,16 @@ class StorageService {
5172
5263
  exports.LocalStorageItems.AccessToken,
5173
5264
  exports.LocalStorageItems.RefreshToken,
5174
5265
  exports.V2KeyNames.EncryptedDevicePrivateKey,
5266
+ exports.V2KeyNames.ClientAuthPublicKey,
5175
5267
  exports.V2KeyNames.WallabyAuthPubKey,
5176
5268
  exports.V2KeyNames.PasskeyCredential,
5177
5269
  exports.V2KeyNames.MigrationVersion,
5178
5270
  exports.V2KeyNames.LastMigratedAt,
5179
5271
  exports.V2KeyNames.ClientAuthToken,
5272
+ exports.V2KeyNames.PasswordResetAttempts,
5273
+ exports.V2KeyNames.MigrationAttempts,
5274
+ exports.V2KeyNames.CredentialConversionInProgress,
5275
+ exports.V2KeyNames.PendingCommit,
5180
5276
  ];
5181
5277
  await Promise.all(userKeysToRemove.map((key) => this.delete(key)));
5182
5278
  if (walletId) {
@@ -5308,6 +5404,11 @@ const AuthRoutes = {
5308
5404
  method: exports.RequestMethod.Get,
5309
5405
  requiresAccessToken: true,
5310
5406
  },
5407
+ issueJwtToken: {
5408
+ fullPath: '/auth/issue-jwt-token',
5409
+ method: exports.RequestMethod.Post,
5410
+ requiresAccessToken: false,
5411
+ },
5311
5412
  };
5312
5413
 
5313
5414
  class LockManagerService {
@@ -6915,8 +7016,9 @@ class Base {
6915
7016
  this.userId = sanitizedConfig.userId;
6916
7017
  this.options = sanitizedConfig.options;
6917
7018
  if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.platform) {
6918
- this.options.platform;
6919
- this.options.platform === 'ios' || this.options.platform === 'android';
7019
+ env.platform = this.options.platform;
7020
+ env.isNative = this.options.platform === 'ios' || this.options.platform === 'android';
7021
+ env.isWeb = !env.isNative;
6920
7022
  }
6921
7023
  this.cipher = new Cipher();
6922
7024
  this.lockManager = new LockManagerService();
@@ -7571,6 +7673,17 @@ function normalizeAndPadBase64(s) {
7571
7673
  function decodeBase64String(s) {
7572
7674
  return jsBase64.toUint8Array(normalizeAndPadBase64(s));
7573
7675
  }
7676
+ /**
7677
+ * Single-decode only: decode base64 (or base64url) to bytes. No round-trip double-decode.
7678
+ */
7679
+ function base64ToUint8Array(base64) {
7680
+ try {
7681
+ return jsBase64.toUint8Array(base64);
7682
+ }
7683
+ catch (_a) {
7684
+ return decodeBase64String(base64);
7685
+ }
7686
+ }
7574
7687
  function decodeBase64URL(base64url) {
7575
7688
  const padded = normalizeAndPadBase64(base64url);
7576
7689
  const binary = jsBase64.atob(padded);
@@ -7581,29 +7694,6 @@ function decodeBase64URL(base64url) {
7581
7694
  return bytes;
7582
7695
  }
7583
7696
 
7584
- /**
7585
- * Web: round-trip with uint8ArrayToBase64 (which does btoa(fromUint8Array(bytes, true))).
7586
- * Single decode first; if the result looks like a base64 string, decode again to get original bytes.
7587
- */
7588
- function base64ToUint8Array(base64) {
7589
- try {
7590
- const first = jsBase64.toUint8Array(base64);
7591
- const asStr = String.fromCharCode.apply(null, first);
7592
- if (/^[A-Za-z0-9+/\-_=]*$/.test(asStr) && asStr.length >= 4) {
7593
- try {
7594
- return decodeBase64String(asStr);
7595
- }
7596
- catch (_a) {
7597
- // fall through
7598
- }
7599
- }
7600
- return first;
7601
- }
7602
- catch (_b) {
7603
- return decodeBase64String(base64);
7604
- }
7605
- }
7606
-
7607
7697
  class PasskeyService {
7608
7698
  constructor(userId, storageService, request) {
7609
7699
  this.cipher = new Cipher();
@@ -7906,7 +7996,6 @@ class PasskeyService {
7906
7996
  }
7907
7997
  logger.log('SDK::PasskeyService::register:: getting signature', {
7908
7998
  message: challengeResponse.message,
7909
- privateKey: deviceKeyPair.privateKey,
7910
7999
  });
7911
8000
  const { signature, message } = await this.cipher.sign({
7912
8001
  message: challengeResponse.message,
@@ -8552,7 +8641,7 @@ class AuthService extends Base {
8552
8641
  data: deviceKeyPair.privateKey,
8553
8642
  encryptionKey: credentialsKeyPair.publicKey,
8554
8643
  });
8555
- this.localStorageService.saveInBulk([
8644
+ await this.localStorageService.saveInBulk([
8556
8645
  {
8557
8646
  key: exports.LocalStorageItems.EncryptedDevicePrivateKey,
8558
8647
  value: encryptedDevicePrivKey,
@@ -8623,6 +8712,24 @@ class AuthService extends Base {
8623
8712
  valid: true,
8624
8713
  };
8625
8714
  }
8715
+ /**
8716
+ * @description Exchanges the client JWT (set at SDK initialisation) for a
8717
+ * Wallaby access + refresh token pair. Tokens are persisted to storage so
8718
+ * subsequent SDK calls use them automatically.
8719
+ * @returns {Promise<IssueJWTTokenResponseDto>} The issued access/refresh tokens and basic user info.
8720
+ */
8721
+ async exchangeClientToken() {
8722
+ try {
8723
+ const response = await this.request(AuthRoutes.issueJwtToken);
8724
+ await this.localStorageService.save(exports.LocalStorageItems.AccessToken, response.accessToken);
8725
+ await this.localStorageService.save(exports.LocalStorageItems.RefreshToken, response.refreshToken);
8726
+ return response;
8727
+ }
8728
+ catch (error) {
8729
+ logger.error('SDK::Auth::exchangeClientToken::error', error);
8730
+ throw error;
8731
+ }
8732
+ }
8626
8733
  }
8627
8734
  __decorate([
8628
8735
  WithLock('signUp'),
@@ -8643,6 +8750,63 @@ __decorate([
8643
8750
  __metadata("design:returntype", Promise)
8644
8751
  ], AuthService.prototype, "storeDeviceKeyPair", null);
8645
8752
 
8753
+ const ENCRYPTED_PAYLOAD_FIELDS = ['iv', 'ephemPublicKey', 'ciphertext', 'mac'];
8754
+ // Backup share may be ECIES or symmetric ({ iv, ciphertext, mac, tag }) — both share these three fields.
8755
+ const SYMMETRIC_PAYLOAD_FIELDS = ['iv', 'ciphertext', 'mac', 'tag'];
8756
+ // API is the trust boundary: confirm every named field is a non-empty string.
8757
+ function hasNonEmptyStringFields(payload, fields) {
8758
+ return (!!payload &&
8759
+ typeof payload === 'object' &&
8760
+ fields.every((field) => {
8761
+ const value = payload[field];
8762
+ return typeof value === 'string' && value.length > 0;
8763
+ }));
8764
+ }
8765
+ /**
8766
+ * Fail fast if an encrypted payload from the API does not match the expected
8767
+ * ECIES structure ({ iv, ephemPublicKey, ciphertext, mac }). See the contract
8768
+ * note on `handleKeySharesFromResponse`.
8769
+ */
8770
+ function assertEncryptedPayloadShape(encrypted) {
8771
+ if (!hasNonEmptyStringFields(encrypted, ENCRYPTED_PAYLOAD_FIELDS)) {
8772
+ throw new WallabyError({
8773
+ message: 'Encrypted share does not match the expected { iv, ephemPublicKey, ciphertext, mac } format.',
8774
+ statusCode: 422,
8775
+ errorCode: exports.ErrorResponseCodes.sdk_invalid_parameter,
8776
+ });
8777
+ }
8778
+ }
8779
+ /**
8780
+ * Shape-assert every share returned by the API. Empty arrays are rejected here
8781
+ * so callers get a clean error instead of crashing on `shares[0]`.
8782
+ */
8783
+ function assertSharesPayloadShape(shares) {
8784
+ if (!shares.length) {
8785
+ throw new WallabyError({
8786
+ message: 'No key shares were returned from the API.',
8787
+ statusCode: 422,
8788
+ errorCode: exports.ErrorResponseCodes.sdk_invalid_parameter,
8789
+ });
8790
+ }
8791
+ for (const share of shares) {
8792
+ assertEncryptedPayloadShape(share.encrypted);
8793
+ }
8794
+ }
8795
+ /**
8796
+ * The backup share is stored as-is (the device can't peel it), so we only
8797
+ * shape-check it. It may be ECIES or symmetric, so accept either variant.
8798
+ */
8799
+ function assertBackupSharePayloadShape(encrypted) {
8800
+ const isEcies = hasNonEmptyStringFields(encrypted, ENCRYPTED_PAYLOAD_FIELDS);
8801
+ const isSymmetric = hasNonEmptyStringFields(encrypted, SYMMETRIC_PAYLOAD_FIELDS);
8802
+ if (!isEcies && !isSymmetric) {
8803
+ throw new WallabyError({
8804
+ message: 'Encrypted backup share does not match the expected ECIES ({ iv, ephemPublicKey, ciphertext, mac }) or symmetric ({ iv, ciphertext, mac, tag }) format.',
8805
+ statusCode: 422,
8806
+ errorCode: exports.ErrorResponseCodes.sdk_invalid_parameter,
8807
+ });
8808
+ }
8809
+ }
8646
8810
  class WalletHandlersService extends Base {
8647
8811
  constructor(config) {
8648
8812
  super(config);
@@ -8723,6 +8887,7 @@ class WalletHandlersService extends Base {
8723
8887
  shares: importWalletRequest.shares,
8724
8888
  credentialsKeyPair,
8725
8889
  encryptedBackupShare: importWalletRequest.encryptedBackupShare,
8890
+ devicePrivateKey: deviceAuthKeys.privateKey,
8726
8891
  });
8727
8892
  }
8728
8893
  return Object.assign({}, importWalletRequest);
@@ -8809,6 +8974,7 @@ class WalletHandlersService extends Base {
8809
8974
  shares: walletCreationResponse.shares,
8810
8975
  credentialsKeyPair,
8811
8976
  encryptedBackupShare: walletCreationResponse.encryptedBackupShare,
8977
+ devicePrivateKey: deviceAuthKeys.privateKey,
8812
8978
  });
8813
8979
  }
8814
8980
  return Object.assign(Object.assign({}, walletCreationResponse), { standardSeedPhrase: decryptedSeedPhrase });
@@ -8824,8 +8990,41 @@ class WalletHandlersService extends Base {
8824
8990
  });
8825
8991
  }
8826
8992
  }
8827
- async handleKeySharesFromResponse({ walletId, shares, credentialsKeyPair, encryptedBackupShare, }) {
8993
+ /**
8994
+ * Encrypted share format contract (WAL-1467)
8995
+ * --------------------------------------------------------------------------
8996
+ * Every flow that ingests shares from the API (import, create, recover,
8997
+ * addNewDevice) routes through here, so the contract is asserted in one place.
8998
+ *
8999
+ * The API returns the main device share as `shares[0]`, an ECIES payload
9000
+ * ({ iv, ephemPublicKey, ciphertext, mac }) wrapped to the device public key,
9001
+ * so it MUST peel with the device private key. `encryptedBackupShare` is an
9002
+ * already-wrapped blob (ECIES or symmetric) that the device cannot decrypt, so
9003
+ * it is stored as-is.
9004
+ *
9005
+ * We shape-assert every share (and the backup share) here, at ingestion, so a
9006
+ * server-side wrapping change fails loudly now instead of silently breaking
9007
+ * export/recovery later.
9008
+ */
9009
+ async handleKeySharesFromResponse({ walletId, shares, credentialsKeyPair, encryptedBackupShare, devicePrivateKey, }) {
8828
9010
  try {
9011
+ assertSharesPayloadShape(shares);
9012
+ assertBackupSharePayloadShape(encryptedBackupShare);
9013
+ // Decrypt-test the contract: shares[0] is wrapped to the device public key and must peel with the device private key.
9014
+ try {
9015
+ await this.cipher.decrypt({
9016
+ cipherText: shares[0].encrypted,
9017
+ decryptionKey: devicePrivateKey,
9018
+ });
9019
+ }
9020
+ catch (error) {
9021
+ throw new WallabyError({
9022
+ message: 'Device-wrapped key share (shares[0]) could not be decrypted with the device private key; the share wrapping format may have changed.',
9023
+ statusCode: 422,
9024
+ errorCode: exports.ErrorResponseCodes.sdk_key_share_decryption_failed,
9025
+ cause: error,
9026
+ });
9027
+ }
8829
9028
  const encryptedWithCredentialsKeyShare = await this.cipher.encrypt({
8830
9029
  data: JSON.stringify(shares[0].encrypted),
8831
9030
  encryptionKey: credentialsKeyPair.publicKey,
@@ -8919,13 +9118,42 @@ class WalletHandlersService extends Base {
8919
9118
  class WalletService extends Base {
8920
9119
  constructor(config) {
8921
9120
  super(config);
8922
- this.passwordResetAttempts = 0;
8923
- this.migrationAttempts = 0;
8924
9121
  this.authService = new AuthService(config);
8925
9122
  this.handlers = new WalletHandlersService(config);
8926
9123
  this.userId = config.userId;
8927
9124
  this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request);
8928
9125
  }
9126
+ /**
9127
+ * Reads the persisted sliding-window rate-limit state for a counter key.
9128
+ * Returns a fresh window ({ count: 0 }) when none is stored or the window has expired.
9129
+ */
9130
+ async getRateState(key) {
9131
+ const now = Date.now();
9132
+ const raw = await this.localStorageService.fetch(key);
9133
+ const state = raw ? safeJsonParse(raw) : undefined;
9134
+ if (!state || now - state.windowStart > WalletService.RATE_LIMIT_WINDOW_MS) {
9135
+ return { count: 0, windowStart: now };
9136
+ }
9137
+ return state;
9138
+ }
9139
+ /** Increments and persists the counter (resetting an expired window). Returns the new count. */
9140
+ async recordRateAttempt(key) {
9141
+ const state = await this.getRateState(key);
9142
+ state.count += 1;
9143
+ await this.localStorageService.save(key, JSON.stringify(state));
9144
+ return state.count;
9145
+ }
9146
+ /** Throws a 429 when the counter is already over the limit, without incrementing it. */
9147
+ async assertUnderRateLimit(key, message) {
9148
+ const { count } = await this.getRateState(key);
9149
+ if (count > WalletService.RATE_LIMIT_MAX) {
9150
+ throw new WallabyError({
9151
+ message,
9152
+ statusCode: 429,
9153
+ errorCode: exports.ErrorResponseCodes.sdk_too_many_requests,
9154
+ });
9155
+ }
9156
+ }
8929
9157
  /**
8930
9158
  * @public
8931
9159
  * @returns {boolean} Returns true if the device has a seed phrase.
@@ -9031,20 +9259,7 @@ class WalletService extends Base {
9031
9259
  });
9032
9260
  }
9033
9261
  if (this.deviceAuthType === exports.AuthType.Password && authenticationOptions.password) {
9034
- try {
9035
- await this.handleUpdateToV2({
9036
- password: authenticationOptions.password,
9037
- walletId: walletId,
9038
- });
9039
- }
9040
- catch (error) {
9041
- logger.error('SDK::WalletService::export::handleUpdateToV2::error', error);
9042
- throw new WallabyError({
9043
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
9044
- statusCode: 500,
9045
- errorCode: exports.ErrorResponseCodes.sdk_unknown_error,
9046
- });
9047
- }
9262
+ await this.migrateToV2Safe({ password: authenticationOptions.password, walletId });
9048
9263
  }
9049
9264
  const encryptedSeed = await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedStandardSeedPhrase, { walletId });
9050
9265
  const encryptedPrimaryDeviceShare = await this.localStorageService.fetch(exports.LocalStorageItems.PrimaryDeviceKeyShare, {
@@ -9287,6 +9502,7 @@ class WalletService extends Base {
9287
9502
  shares: recoverWithSeedPhraseResponse.shares,
9288
9503
  credentialsKeyPair,
9289
9504
  encryptedBackupShare: recoverWithSeedPhraseResponse.encryptedBackupShare,
9505
+ devicePrivateKey: deviceAuthKeyPair.privateKey,
9290
9506
  });
9291
9507
  }
9292
9508
  await this.authService.storeDeviceKeyPair({
@@ -9350,6 +9566,7 @@ class WalletService extends Base {
9350
9566
  shares: recoverWithSeedPhraseResponse.shares,
9351
9567
  credentialsKeyPair,
9352
9568
  encryptedBackupShare: recoverWithSeedPhraseResponse.encryptedBackupShare,
9569
+ devicePrivateKey: deviceAuthKeyPair.privateKey,
9353
9570
  });
9354
9571
  }
9355
9572
  await this.authService.storeDeviceKeyPair({
@@ -9382,8 +9599,7 @@ class WalletService extends Base {
9382
9599
  */
9383
9600
  async changePassword({ walletId, oldPassword, newPassword, }) {
9384
9601
  try {
9385
- this.passwordResetAttempts += 1;
9386
- if (this.passwordResetAttempts > 5) {
9602
+ if ((await this.recordRateAttempt(exports.V2KeyNames.PasswordResetAttempts)) > WalletService.RATE_LIMIT_MAX) {
9387
9603
  throw new WallabyError({
9388
9604
  message: 'Too many password change attempts. Please try again later.',
9389
9605
  statusCode: 429,
@@ -9392,20 +9608,7 @@ class WalletService extends Base {
9392
9608
  }
9393
9609
  if (this.deviceAuthType === exports.AuthType.Password && oldPassword) {
9394
9610
  // Handle migration to V2 first then change the password to the new one.
9395
- try {
9396
- await this.handleUpdateToV2({
9397
- password: oldPassword,
9398
- walletId,
9399
- });
9400
- }
9401
- catch (error) {
9402
- logger.error('SDK::WalletService::changePassword::handleUpdateToV2::error', error);
9403
- throw new WallabyError({
9404
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
9405
- statusCode: 500,
9406
- errorCode: exports.ErrorResponseCodes.sdk_unknown_error,
9407
- });
9408
- }
9611
+ await this.migrateToV2Safe({ password: oldPassword, walletId });
9409
9612
  }
9410
9613
  const encryptedDevicePrivateKeyString = await this.localStorageService.fetch(exports.V2KeyNames.EncryptedDevicePrivateKey);
9411
9614
  const encryptedSeedPhraseString = await this.localStorageService.fetch(exports.V2KeyNames.EncryptedStandardSeedPhrase, {
@@ -9439,7 +9642,7 @@ class WalletService extends Base {
9439
9642
  password: newPassword,
9440
9643
  salt: clientSalt,
9441
9644
  });
9442
- if (!newCredentialsKeyPair.publicKey) {
9645
+ if (!newCredentialsKeyPair.publicKey || !newCredentialsKeyPair.privateKey) {
9443
9646
  throw new WallabyError({
9444
9647
  message: 'Could not derive keys for new password.',
9445
9648
  statusCode: 500,
@@ -9462,40 +9665,48 @@ class WalletService extends Base {
9462
9665
  errorCode: exports.ErrorResponseCodes.sdk_unknown_error,
9463
9666
  });
9464
9667
  }
9465
- await this.localStorageService.save(exports.LocalStorageItems.EncryptedDevicePrivateKey, reWrappedDevicePrivateKey);
9466
- if (encryptedSeedPhraseString) {
9467
- const parsedSeed = safeJsonParse(encryptedSeedPhraseString);
9468
- const reWrappedSeedPhrase = await this.cipher.flipEncryptedData({
9469
- cipherText: parsedSeed,
9668
+ // Round-trip validate: decrypt the re-wrapped blob with the new key before committing.
9669
+ // Catches a malformed re-encryption before it overwrites the live credential.
9670
+ await this.assertRoundTrip(reWrappedDevicePrivateKey, newCredentialsKeyPair.privateKey, 'device key');
9671
+ const reWrappedSeedPhrase = encryptedSeedPhraseString
9672
+ ? await this.cipher.flipEncryptedData({
9673
+ cipherText: safeJsonParse(encryptedSeedPhraseString),
9470
9674
  decryptionKey: oldCredentialsKeyPair.privateKey,
9471
9675
  encryptionKey: newCredentialsKeyPair.publicKey,
9472
- });
9473
- await this.localStorageService.save(exports.LocalStorageItems.EncryptedStandardSeedPhrase, reWrappedSeedPhrase, {
9474
- walletId,
9475
- });
9476
- }
9477
- if (encryptedPrimaryShareString) {
9478
- const parsedPrimaryShare = safeJsonParse(encryptedPrimaryShareString);
9479
- const reWrappedPrimaryShare = await this.cipher.flipEncryptedData({
9480
- cipherText: parsedPrimaryShare,
9676
+ })
9677
+ : null;
9678
+ const reWrappedPrimaryShare = encryptedPrimaryShareString
9679
+ ? await this.cipher.flipEncryptedData({
9680
+ cipherText: safeJsonParse(encryptedPrimaryShareString),
9481
9681
  decryptionKey: oldCredentialsKeyPair.privateKey,
9482
9682
  encryptionKey: newCredentialsKeyPair.publicKey,
9483
- });
9484
- await this.localStorageService.save(exports.LocalStorageItems.PrimaryDeviceKeyShare, reWrappedPrimaryShare, {
9485
- walletId,
9486
- });
9487
- }
9488
- if (encryptedBackupShareString) {
9489
- const parsedBackupShare = safeJsonParse(encryptedBackupShareString);
9490
- const reWrappedBackupShare = await this.cipher.flipEncryptedData({
9491
- cipherText: parsedBackupShare,
9683
+ })
9684
+ : null;
9685
+ const reWrappedBackupShare = encryptedBackupShareString
9686
+ ? await this.cipher.flipEncryptedData({
9687
+ cipherText: safeJsonParse(encryptedBackupShareString),
9492
9688
  decryptionKey: oldCredentialsKeyPair.privateKey,
9493
9689
  encryptionKey: newCredentialsKeyPair.publicKey,
9494
- });
9495
- await this.localStorageService.save(exports.LocalStorageItems.BackupDeviceKeyShare, reWrappedBackupShare, {
9496
- walletId,
9497
- });
9498
- }
9690
+ })
9691
+ : null;
9692
+ if (reWrappedSeedPhrase)
9693
+ await this.assertRoundTrip(reWrappedSeedPhrase, newCredentialsKeyPair.privateKey, 'seed phrase');
9694
+ if (reWrappedPrimaryShare)
9695
+ await this.assertRoundTrip(reWrappedPrimaryShare, newCredentialsKeyPair.privateKey, 'primary share');
9696
+ if (reWrappedBackupShare)
9697
+ await this.assertRoundTrip(reWrappedBackupShare, newCredentialsKeyPair.privateKey, 'backup share');
9698
+ await this.localStorageService.commitBatch([
9699
+ { key: exports.LocalStorageItems.EncryptedDevicePrivateKey, value: reWrappedDevicePrivateKey },
9700
+ ...(reWrappedSeedPhrase
9701
+ ? [{ key: exports.LocalStorageItems.EncryptedStandardSeedPhrase, value: reWrappedSeedPhrase, walletId }]
9702
+ : []),
9703
+ ...(reWrappedPrimaryShare
9704
+ ? [{ key: exports.LocalStorageItems.PrimaryDeviceKeyShare, value: reWrappedPrimaryShare, walletId }]
9705
+ : []),
9706
+ ...(reWrappedBackupShare ? [{ key: exports.LocalStorageItems.BackupDeviceKeyShare, value: reWrappedBackupShare, walletId }] : []),
9707
+ ]);
9708
+ // Reset the rate-limit window on success so a normal change does not count against future ones.
9709
+ await this.localStorageService.delete(exports.V2KeyNames.PasswordResetAttempts);
9499
9710
  return true;
9500
9711
  }
9501
9712
  catch (error) {
@@ -9548,20 +9759,7 @@ class WalletService extends Base {
9548
9759
  }
9549
9760
  const parsedEncryptedDevicePrivateKey = safeJsonParse(encryptedDevicePrivateKey);
9550
9761
  if (this.deviceAuthType === exports.AuthType.Password && input.authenticationOptions.password) {
9551
- try {
9552
- await this.handleUpdateToV2({
9553
- password: input.authenticationOptions.password,
9554
- walletId: input.walletId,
9555
- });
9556
- }
9557
- catch (error) {
9558
- logger.error('SDK::WalletService::initAddNewDevice::handleUpdateToV2::error', error);
9559
- throw new WallabyError({
9560
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
9561
- statusCode: 500,
9562
- errorCode: exports.ErrorResponseCodes.sdk_unknown_error,
9563
- });
9564
- }
9762
+ await this.migrateToV2Safe({ password: input.authenticationOptions.password, walletId: input.walletId });
9565
9763
  }
9566
9764
  const storedEncryptedBackupShare = await this.localStorageService.fetch(exports.LocalStorageItems.BackupDeviceKeyShare, { walletId });
9567
9765
  if (!storedEncryptedBackupShare) {
@@ -9659,6 +9857,7 @@ class WalletService extends Base {
9659
9857
  shares: [backUpResponse.share],
9660
9858
  credentialsKeyPair,
9661
9859
  encryptedBackupShare: input.encryptedBackupShare,
9860
+ devicePrivateKey: decryptedDevicePrivateKey,
9662
9861
  });
9663
9862
  return { success: true, reference: backUpResponse.reference };
9664
9863
  }
@@ -9677,20 +9876,7 @@ class WalletService extends Base {
9677
9876
  });
9678
9877
  }
9679
9878
  if (this.deviceAuthType === exports.AuthType.Password && input.authenticationOptions.password) {
9680
- try {
9681
- await this.handleUpdateToV2({
9682
- password: input.authenticationOptions.password,
9683
- walletId: input.walletId,
9684
- });
9685
- }
9686
- catch (error) {
9687
- logger.error('SDK::WalletService::generateWalletAddresses::handleUpdateToV2::error', error);
9688
- throw new WallabyError({
9689
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
9690
- statusCode: 500,
9691
- errorCode: exports.ErrorResponseCodes.sdk_unknown_error,
9692
- });
9693
- }
9879
+ await this.migrateToV2Safe({ password: input.authenticationOptions.password, walletId: input.walletId });
9694
9880
  }
9695
9881
  try {
9696
9882
  const walletOperationAuth = await this.prepareWalletOperationAuth({
@@ -9715,6 +9901,23 @@ class WalletService extends Base {
9715
9901
  throw error;
9716
9902
  }
9717
9903
  }
9904
+ /**
9905
+ * Wraps handleUpdateToV2 with the standard user-facing error. All call sites that gate on
9906
+ * `AuthType.Password` should go through here so the error message stays consistent.
9907
+ */
9908
+ async migrateToV2Safe({ password, walletId }) {
9909
+ try {
9910
+ await this.handleUpdateToV2({ password, walletId });
9911
+ }
9912
+ catch (error) {
9913
+ logger.error('SDK::WalletService::migrateToV2Safe::error', error);
9914
+ throw new WallabyError({
9915
+ message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
9916
+ statusCode: 500,
9917
+ errorCode: exports.ErrorResponseCodes.sdk_unknown_error,
9918
+ });
9919
+ }
9920
+ }
9718
9921
  /**
9719
9922
  * Detects and migrates legacy/v1 storage items to v2 format.
9720
9923
  * This function should be called in methods that use password as input when v2 items are missing.
@@ -9723,13 +9926,7 @@ class WalletService extends Base {
9723
9926
  */
9724
9927
  async handleUpdateToV2({ password, walletId }) {
9725
9928
  const migrationStartTime = Date.now();
9726
- if (this.migrationAttempts > 5) {
9727
- throw new WallabyError({
9728
- message: 'Too many migration attempts. Please try again later.',
9729
- statusCode: 429,
9730
- errorCode: exports.ErrorResponseCodes.sdk_too_many_requests,
9731
- });
9732
- }
9929
+ await this.assertUnderRateLimit(exports.V2KeyNames.MigrationAttempts, 'Too many migration attempts. Please try again later.');
9733
9930
  try {
9734
9931
  if (!password) {
9735
9932
  throw new WallabyError({
@@ -9800,7 +9997,7 @@ class WalletService extends Base {
9800
9997
  }
9801
9998
  }
9802
9999
  // Increment counter after V2 validation to avoid counting when migration not needed
9803
- this.migrationAttempts += 1;
10000
+ await this.recordRateAttempt(exports.V2KeyNames.MigrationAttempts);
9804
10001
  let decryptedSeedPhrase;
9805
10002
  let decryptedPrivateKey;
9806
10003
  // Check for legacy format: `{item}_{userId}`
@@ -9853,7 +10050,10 @@ class WalletService extends Base {
9853
10050
  try {
9854
10051
  // Decrypt V1 items using storage service method (handles double encryption)
9855
10052
  logger.log('Attempting to decrypt V1 items during migration...');
9856
- logger.log('getV1DecryptedSeedPhrase should be called with password and clientSalt:', { password, clientSalt });
10053
+ logger.log('getV1DecryptedSeedPhrase should be called with password and clientSalt:', {
10054
+ hasPassword: !!password,
10055
+ hasClientSalt: !!clientSalt,
10056
+ });
9857
10057
  decryptedSeedPhrase = await this.localStorageService.getV1DecryptedSeedPhrase(password, clientSalt);
9858
10058
  // For V1 format, private key is encrypted with just the password (not salt+password like legacy)
9859
10059
  decryptedPrivateKey = await this.localStorageService.getDecryptedV1PrivateKey(password);
@@ -10080,7 +10280,28 @@ class WalletService extends Base {
10080
10280
  * @returns { boolean } whether the operation was successful
10081
10281
  */
10082
10282
  async convertToPasskey(input) {
10283
+ let passkeyRegistered = false;
10083
10284
  try {
10285
+ // Recover an interrupted conversion BEFORE reading any credential blob. A prior attempt may have
10286
+ // already rewrapped EncryptedDevicePrivateKey to passkey form (addNewPasskey persists it outside
10287
+ // this method's atomic commit), which the password can no longer decrypt — and deriving the passkey
10288
+ // key to decrypt it needs the device key itself (circular). The marker stashes the original
10289
+ // password-encrypted device key; restore it so the rest of the flow runs as a fresh conversion.
10290
+ const rawConversionMarker = (await this.localStorageService.fetch(exports.V2KeyNames.CredentialConversionInProgress));
10291
+ const existingConversionMarker = rawConversionMarker
10292
+ ? safeJsonParse(rawConversionMarker)
10293
+ : undefined;
10294
+ // Restore the stashed device key whenever a marker carries one — independent of walletId. The
10295
+ // device key is per-user (not wallet-scoped), so a conversion interrupted on a different wallet
10296
+ // leaves the shared device key passkey-wrapped too. Restoring is idempotent (rewrites the
10297
+ // original password-encrypted blob) and stops a second wallet's conversion from destroying the
10298
+ // first's recovery state. v2 only — a v1 wallet's untouched v1 key still decrypts.
10299
+ if (existingConversionMarker === null || existingConversionMarker === void 0 ? void 0 : existingConversionMarker.encryptedDevicePrivateKey) {
10300
+ await this.localStorageService.save(exports.LocalStorageItems.EncryptedDevicePrivateKey, existingConversionMarker.encryptedDevicePrivateKey);
10301
+ }
10302
+ if ((existingConversionMarker === null || existingConversionMarker === void 0 ? void 0 : existingConversionMarker.walletId) === input.walletId) {
10303
+ logger.info('SDK::WalletService::convertToPasskey::resuming interrupted conversion');
10304
+ }
10084
10305
  const v2EncryptedPriv = await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);
10085
10306
  const v2EncryptedSeed = await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedStandardSeedPhrase, {
10086
10307
  walletId: input.walletId,
@@ -10129,6 +10350,10 @@ class WalletService extends Base {
10129
10350
  });
10130
10351
  }
10131
10352
  const clientPublicKey = publicKeyByPrivateKey(decryptedClientAuthPrivKey);
10353
+ // Write-ahead marker: set before the unrevocable passkey registration so an interrupted
10354
+ // conversion can be resumed on the next attempt. Stash the original password-encrypted device
10355
+ // key so resume survives addNewPasskey rewrapping the stored device key to passkey form.
10356
+ await this.localStorageService.save(exports.V2KeyNames.CredentialConversionInProgress, Object.assign({ walletId: input.walletId }, (v2EncryptedPriv ? { encryptedDevicePrivateKey: v2EncryptedPriv } : {})));
10132
10357
  const authentication = await this.passkeyService.addNewPasskey({
10133
10358
  deviceKeyPair: {
10134
10359
  publicKey: clientPublicKey,
@@ -10136,6 +10361,7 @@ class WalletService extends Base {
10136
10361
  },
10137
10362
  getSignature: this.authService.getSignature.bind(this),
10138
10363
  });
10364
+ passkeyRegistered = true;
10139
10365
  const prfValue = authentication.prfValue;
10140
10366
  if (!prfValue || !(prfValue instanceof Uint8Array) || prfValue.length === 0) {
10141
10367
  logger.error('SDK::WalletService::convertToPasskey::prfValue is required and must be a non-empty Uint8Array');
@@ -10232,8 +10458,13 @@ class WalletService extends Base {
10232
10458
  storeOneKeyShareWithWallaby: true,
10233
10459
  },
10234
10460
  });
10235
- // Delete the old password-encrypted seed phrase since import stored the new passkey-encrypted version
10236
- await this.localStorageService.delete(exports.LocalStorageItems.EncryptedStandardSeedPhrase, { walletId: input.walletId });
10461
+ // idempotent — on retry (marker present, primary now passkey-encrypted so
10462
+ // decryptedPrimaryShare is undefined → Branch A re-enters), handleImportWallet re-shares
10463
+ // safely; this atomic delete clears the stale seed + marker together.
10464
+ await this.localStorageService.commitBatch([], [
10465
+ { key: exports.LocalStorageItems.EncryptedStandardSeedPhrase, walletId: input.walletId },
10466
+ { key: exports.V2KeyNames.CredentialConversionInProgress },
10467
+ ]);
10237
10468
  logger.info('SDK::WalletService::convertToPasskey::Wallet imported and converted successfully, old seed phrase removed');
10238
10469
  return { authentication, seedPhrase: decryptedSeedPhrase };
10239
10470
  }
@@ -10251,6 +10482,24 @@ class WalletService extends Base {
10251
10482
  privateKey: decryptedClientAuthPrivKey,
10252
10483
  },
10253
10484
  });
10485
+ // assertRoundTrip below only strips the outer (passkey) layer — validate the inner (device key) layer here.
10486
+ const outerDecrypted = await this.cipher.decrypt({
10487
+ cipherText: encryptedPrimaryShare,
10488
+ decryptionKey: passkeyDerivedKeyPair.privateKey,
10489
+ });
10490
+ const innerDecrypted = outerDecrypted
10491
+ ? await this.cipher.decrypt({
10492
+ cipherText: safeJsonParse(outerDecrypted),
10493
+ decryptionKey: decryptedClientAuthPrivKey,
10494
+ })
10495
+ : null;
10496
+ if (innerDecrypted !== decryptedPrimaryShare) {
10497
+ throw new WallabyError({
10498
+ message: 'Re-wrap validation failed for primary share: inner layer round-trip mismatch. Aborting to prevent credential corruption.',
10499
+ statusCode: 500,
10500
+ errorCode: exports.ErrorResponseCodes.sdk_unknown_error,
10501
+ });
10502
+ }
10254
10503
  convertedShares.push({
10255
10504
  key: exports.V2KeyNames.PrimaryDeviceKeyShare,
10256
10505
  value: encryptedPrimaryShare,
@@ -10269,9 +10518,16 @@ class WalletService extends Base {
10269
10518
  walletId: input.walletId,
10270
10519
  });
10271
10520
  }
10272
- await this.localStorageService.saveInBulk(convertedShares);
10521
+ // Round-trip validate each re-encrypted blob (outer layer only) before writing.
10522
+ // A failed decrypt here means re-encryption produced an unreadable blob — abort before overwriting live credentials.
10523
+ for (const share of convertedShares) {
10524
+ await this.assertRoundTrip(share.value, passkeyDerivedKeyPair.privateKey, share.key);
10525
+ }
10526
+ await this.localStorageService.commitBatch(convertedShares, [
10527
+ ...(v2EncryptedSeed ? [{ key: exports.LocalStorageItems.EncryptedStandardSeedPhrase, walletId: input.walletId }] : []),
10528
+ { key: exports.V2KeyNames.CredentialConversionInProgress },
10529
+ ]);
10273
10530
  if (v2EncryptedSeed) {
10274
- await this.localStorageService.delete(exports.LocalStorageItems.EncryptedStandardSeedPhrase, { walletId: input.walletId });
10275
10531
  logger.info('SDK::WalletService::convertToPasskey::Seed phrase removed from device storage after conversion to passkey');
10276
10532
  }
10277
10533
  if (!decryptedSeedPhrase && decryptedPrimaryShare) {
@@ -10314,10 +10570,33 @@ class WalletService extends Base {
10314
10570
  }
10315
10571
  catch (error) {
10316
10572
  logger.error('SDK::WalletService::convertToPasskey::error', error);
10573
+ // Only clear the marker if the passkey was not yet registered. After registration the
10574
+ // marker must survive for roll-forward on the next attempt.
10575
+ if (!passkeyRegistered) {
10576
+ await this.localStorageService.delete(exports.V2KeyNames.CredentialConversionInProgress);
10577
+ }
10317
10578
  throw error;
10318
10579
  }
10319
10580
  }
10581
+ // shared guard — decrypt-tests a re-wrapped blob before any write so a malformed
10582
+ // re-encryption is caught before it overwrites the live credential.
10583
+ async assertRoundTrip(blob, decryptionKey, label) {
10584
+ try {
10585
+ await this.cipher.decrypt({ cipherText: blob, decryptionKey });
10586
+ }
10587
+ catch (_a) {
10588
+ throw new WallabyError({
10589
+ message: `Re-wrap validation failed for ${label}: decryption of the re-encrypted blob failed. Aborting to prevent credential corruption.`,
10590
+ statusCode: 500,
10591
+ errorCode: exports.ErrorResponseCodes.sdk_unknown_error,
10592
+ });
10593
+ }
10594
+ }
10320
10595
  }
10596
+ // soft client-side guardrail against runaway retries; server-side rate limiting is the real control.
10597
+ // Counters are persisted (sliding window) so rebuilding the service no longer resets them. Tune freely.
10598
+ WalletService.RATE_LIMIT_MAX = 5;
10599
+ WalletService.RATE_LIMIT_WINDOW_MS = 30 * 60000; // 30 min
10321
10600
  __decorate([
10322
10601
  WithLock('create'),
10323
10602
  __metadata("design:type", Function),
@@ -10337,7 +10616,7 @@ __decorate([
10337
10616
  __metadata("design:returntype", Promise)
10338
10617
  ], WalletService.prototype, "recover", null);
10339
10618
  __decorate([
10340
- WithLock('changePassword'),
10619
+ WithLock('credential-rewrap'),
10341
10620
  __metadata("design:type", Function),
10342
10621
  __metadata("design:paramtypes", [Object]),
10343
10622
  __metadata("design:returntype", Promise)
@@ -10348,6 +10627,12 @@ __decorate([
10348
10627
  __metadata("design:paramtypes", [Object]),
10349
10628
  __metadata("design:returntype", Promise)
10350
10629
  ], WalletService.prototype, "handleUpdateToV2", null);
10630
+ __decorate([
10631
+ WithLock('credential-rewrap'),
10632
+ __metadata("design:type", Function),
10633
+ __metadata("design:paramtypes", [Object]),
10634
+ __metadata("design:returntype", Promise)
10635
+ ], WalletService.prototype, "convertToPasskey", null);
10351
10636
 
10352
10637
  class WalletDataService extends Base {
10353
10638
  constructor(config) {
@@ -10600,20 +10885,7 @@ class WalletDataService extends Base {
10600
10885
  });
10601
10886
  }
10602
10887
  if (this.deviceAuthType === exports.AuthType.Password && authenticationOptions.password) {
10603
- try {
10604
- await this.walletService.handleUpdateToV2({
10605
- password: authenticationOptions.password,
10606
- walletId: walletId,
10607
- });
10608
- }
10609
- catch (error) {
10610
- logger.error('SDK::WalletDataService::addNewChainAndTokenToWallet::handleUpdateToV2::error', error);
10611
- throw new WallabyError({
10612
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
10613
- statusCode: 500,
10614
- errorCode: exports.ErrorResponseCodes.sdk_unknown_error,
10615
- });
10616
- }
10888
+ await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
10617
10889
  }
10618
10890
  try {
10619
10891
  const addressInfo = await this.walletService.generateWalletAddresses({
@@ -10814,179 +11086,6 @@ class Utils extends Base {
10814
11086
  }
10815
11087
  }
10816
11088
 
10817
- const MerchantsRoutes = {
10818
- create: {
10819
- fullPath: '/merchants',
10820
- method: exports.RequestMethod.Post,
10821
- requiresAccessToken: false,
10822
- },
10823
- update: {
10824
- fullPath: ({ merchantId }) => `/merchants/${merchantId}`,
10825
- method: exports.RequestMethod.Put,
10826
- requiresAccessToken: false,
10827
- },
10828
- getMerchantData: {
10829
- fullPath: ({ merchantId }) => `/merchants/${merchantId}`,
10830
- method: exports.RequestMethod.Get,
10831
- requiresAccessToken: false,
10832
- },
10833
- list: {
10834
- fullPath: '/merchants',
10835
- method: exports.RequestMethod.Get,
10836
- requiresAccessToken: false,
10837
- },
10838
- getAssets: {
10839
- fullPath: () => `/users/merchant/assets`,
10840
- method: exports.RequestMethod.Get,
10841
- requiresAccessToken: true,
10842
- },
10843
- addAsset: {
10844
- fullPath: ({ merchantId, configId }) => `/merchants/${merchantId}/assets/${configId}`,
10845
- method: exports.RequestMethod.Post,
10846
- requiresAccessToken: false,
10847
- },
10848
- deleteAsset: {
10849
- fullPath: ({ merchantId, configId }) => `/merchants/${merchantId}/assets/${configId}`,
10850
- method: exports.RequestMethod.Delete,
10851
- requiresAccessToken: false,
10852
- },
10853
- };
10854
-
10855
- class Merchants extends Base {
10856
- constructor(config) {
10857
- super(config);
10858
- }
10859
- /**
10860
- * @description
10861
- * Retrieves the merchant ID from access token `aud` claim.
10862
- * Even though merchantId is possibly undefined. If an access token is not stored on device, the request will most likely
10863
- * not have it in headers and will fail with 401 regardless.
10864
- *
10865
- * @returns { string | undefined } Merchant ID
10866
- */
10867
- async _getMerchantId() {
10868
- const accessToken = await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken);
10869
- if (!accessToken)
10870
- return;
10871
- const jwtDecoded = jwtDecode.jwtDecode(accessToken);
10872
- return jwtDecoded.aud;
10873
- }
10874
- /**
10875
- *
10876
- * @public
10877
- * List of all merchants in the system
10878
- * @returns { ListMerchantsResponse } Array of all merchants
10879
- */
10880
- async list() {
10881
- try {
10882
- const response = await this.request(MerchantsRoutes.list, {
10883
- payload: {},
10884
- });
10885
- return response;
10886
- }
10887
- catch (error) {
10888
- logger.error('SDK::Merchants::list::error', error);
10889
- return Promise.reject(error);
10890
- }
10891
- }
10892
- /**
10893
- *
10894
- * @public
10895
- * Allows to create a new merchant
10896
- * @returns { Merchant } Merchant data
10897
- */
10898
- async create({ name }) {
10899
- try {
10900
- const response = await this.request(MerchantsRoutes.create, {
10901
- payload: { name },
10902
- });
10903
- return response;
10904
- }
10905
- catch (error) {
10906
- logger.error('SDK::Merchants::list::error', error);
10907
- return Promise.reject(error);
10908
- }
10909
- }
10910
- /**
10911
- *
10912
- * @public
10913
- * Allows to update merchant data
10914
- * @returns { Merchant } Merchant data
10915
- */
10916
- async update({ name, status }) {
10917
- try {
10918
- const merchantId = await this._getMerchantId();
10919
- const response = await this.request(MerchantsRoutes.update, {
10920
- payload: { merchantId, name, status },
10921
- });
10922
- return response;
10923
- }
10924
- catch (error) {
10925
- logger.error('SDK::Merchants::list::error', error);
10926
- return Promise.reject(error);
10927
- }
10928
- }
10929
- /**
10930
- *
10931
- * @public
10932
- * @returns { Merchant } Merchant data
10933
- */
10934
- async getMerchantData() {
10935
- try {
10936
- const merchantId = await this._getMerchantId();
10937
- const response = await this.request(MerchantsRoutes.getMerchantData, {
10938
- payload: { merchantId },
10939
- });
10940
- return response.merchant;
10941
- }
10942
- catch (error) {
10943
- logger.error('SDK::Merchants::list::error', error);
10944
- return Promise.reject(error);
10945
- }
10946
- }
10947
- /**
10948
- *
10949
- * @public
10950
- * @returns { MerchantAsset[] } List of merchant assets
10951
- */
10952
- async getAssets() {
10953
- try {
10954
- const response = await this.request(MerchantsRoutes.getAssets);
10955
- return response.merchantAssets;
10956
- }
10957
- catch (error) {
10958
- logger.error('SDK::Merchants::list::error', error);
10959
- return Promise.reject(error);
10960
- }
10961
- }
10962
- async addAsset({ configId }) {
10963
- try {
10964
- const merchantId = await this._getMerchantId();
10965
- const response = await this.request(MerchantsRoutes.addAsset, {
10966
- payload: { merchantId, configId },
10967
- });
10968
- return response;
10969
- }
10970
- catch (error) {
10971
- logger.error('SDK::Merchants::list::error', error);
10972
- return Promise.reject(error);
10973
- }
10974
- }
10975
- async deleteAsset({ configId }) {
10976
- try {
10977
- const merchantId = await this._getMerchantId();
10978
- const response = await this.request(MerchantsRoutes.deleteAsset, {
10979
- payload: { merchantId, configId },
10980
- });
10981
- return response;
10982
- }
10983
- catch (error) {
10984
- logger.error('SDK::Merchants::list::error', error);
10985
- return Promise.reject(error);
10986
- }
10987
- }
10988
- }
10989
-
10990
11089
  /**
10991
11090
  * HttpApi provides direct access to all REST API endpoints.
10992
11091
  * This class extends the Base class and includes the generated API client
@@ -11067,20 +11166,7 @@ class Swap extends Base {
11067
11166
  try {
11068
11167
  // Only attempt migration if we have password auth and V2 storage might be incomplete
11069
11168
  if (this.deviceAuthType === exports.AuthType.Password && authenticationOptions.password) {
11070
- try {
11071
- await this.walletService.handleUpdateToV2({
11072
- password: authenticationOptions.password,
11073
- walletId: walletId,
11074
- });
11075
- }
11076
- catch (error) {
11077
- logger.error('SDK::Swap::executeSwap::handleUpdateToV2::error', error);
11078
- throw new WallabyError({
11079
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
11080
- statusCode: 500,
11081
- errorCode: exports.ErrorResponseCodes.sdk_unknown_error,
11082
- });
11083
- }
11169
+ await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
11084
11170
  }
11085
11171
  const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareSwapAuth(authenticationOptions, walletId);
11086
11172
  let swapResponse;
@@ -11275,6 +11361,27 @@ const sanitizeSuiObjectId = (objectId) => {
11275
11361
  return objectId.split('::')[0];
11276
11362
  };
11277
11363
 
11364
+ /**
11365
+ * Extracts the asset symbol from a fully-qualified Sui coin type.
11366
+ *
11367
+ * A Sui coin type has the shape `<package>::<module>::<TYPE>`, where the final
11368
+ * segment is the coin's struct name and doubles as its symbol.
11369
+ *
11370
+ * @param objectId - The Sui object id / coin type. Example input:
11371
+ * "0xc91acfb75009c5ff2fd57c54f3caaee12ad1fbe997681334adc0b574fc277a07::icorgi::ICORGI"
11372
+ * @returns The symbol (e.g. "ICORGI"), or undefined when the id carries no
11373
+ * `::module::TYPE` suffix to derive it from.
11374
+ */
11375
+ const extractSuiAssetSymbol = (objectId) => {
11376
+ var _a;
11377
+ if (!objectId || !objectId.includes('::')) {
11378
+ return undefined;
11379
+ }
11380
+ const segments = objectId.split('::');
11381
+ const symbol = (_a = segments[segments.length - 1]) === null || _a === void 0 ? void 0 : _a.trim();
11382
+ return symbol || undefined;
11383
+ };
11384
+
11278
11385
  class System extends Base {
11279
11386
  constructor(config) {
11280
11387
  super(config);
@@ -11363,6 +11470,9 @@ class System extends Base {
11363
11470
  * @param {BlockchainName} blockchain - The name of the blockchain.
11364
11471
  * @param {string} contractAddress - The contract address of the token (optional for non-SUI blockchains).
11365
11472
  * @param {string} suiObjectId - The SUI object ID of the token (optional for SUI blockchain).
11473
+ * @param {string} assetSymbol - The asset symbol; disambiguates new SUI assets. For SUI it is
11474
+ * optional: when omitted, it is derived from the `::module::TYPE` suffix of `suiObjectId`
11475
+ * (which is otherwise trimmed off before the request is sent).
11366
11476
  *
11367
11477
  * @returns {Promise<{ decimals: number; symbol: string; name: string; tokenContractAddress: string }>} A promise that resolves to an object containing token information.
11368
11478
  *
@@ -11371,18 +11481,19 @@ class System extends Base {
11371
11481
  * @throws Will throw an error if `contractAddress` is not provided for non-SUI blockchains.
11372
11482
  * @throws Will throw an error if the response is invalid or contains an error.
11373
11483
  */
11374
- async fetchTokenInfo({ blockchain, contractAddress, suiObjectId, }) {
11484
+ async fetchTokenInfo({ blockchain, contractAddress, suiObjectId, assetSymbol, }) {
11375
11485
  try {
11376
11486
  const validatedContractAddress = this.validateContractAddress({
11377
11487
  blockchain,
11378
11488
  contractAddress,
11379
11489
  suiObjectId,
11380
11490
  });
11491
+ // For SUI, the coin symbol is the last segment of the coin type
11492
+ // (`<package>::<module>::<TYPE>`), which sanitizeSuiObjectId strips out.
11493
+ // Derive it so callers don't have to pass assetSymbol explicitly.
11494
+ const resolvedAssetSymbol = assetSymbol !== null && assetSymbol !== void 0 ? assetSymbol : (blockchain === exports.BlockchainName.Sui ? extractSuiAssetSymbol(suiObjectId) : undefined);
11381
11495
  const response = await this.request(SystemRoutes.fetchTokenInfo, {
11382
- queryParams: {
11383
- chainName: blockchain,
11384
- tokenContractAddress: validatedContractAddress,
11385
- },
11496
+ queryParams: Object.assign({ chainName: blockchain, tokenContractAddress: validatedContractAddress }, (resolvedAssetSymbol ? { assetSymbol: resolvedAssetSymbol } : {})),
11386
11497
  });
11387
11498
  return response;
11388
11499
  }
@@ -11596,20 +11707,7 @@ class Transactions extends Base {
11596
11707
  try {
11597
11708
  // Only attempt migration if we have password auth and V2 storage might be incomplete
11598
11709
  if (this.deviceAuthType === exports.AuthType.Password && authenticationOptions.password) {
11599
- try {
11600
- await this.walletService.handleUpdateToV2({
11601
- password: authenticationOptions.password,
11602
- walletId: walletId,
11603
- });
11604
- }
11605
- catch (error) {
11606
- logger.error('SDK::Transactions::transfer::handleUpdateToV2::error', error);
11607
- throw new WallabyError({
11608
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
11609
- statusCode: 500,
11610
- errorCode: exports.ErrorResponseCodes.sdk_unknown_error,
11611
- });
11612
- }
11710
+ await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
11613
11711
  }
11614
11712
  const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareTransactionAuth(authenticationOptions, walletId);
11615
11713
  let transferResponse;
@@ -11697,20 +11795,7 @@ class Transactions extends Base {
11697
11795
  }
11698
11796
  // Only attempt migration if we have password auth and V2 storage might be incomplete
11699
11797
  if (this.deviceAuthType === exports.AuthType.Password && authenticationOptions.password) {
11700
- try {
11701
- await this.walletService.handleUpdateToV2({
11702
- password: authenticationOptions.password,
11703
- walletId: walletId,
11704
- });
11705
- }
11706
- catch (error) {
11707
- logger.error('SDK::Transactions::createAllowance::handleUpdateToV2::error', error);
11708
- throw new WallabyError({
11709
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
11710
- statusCode: 500,
11711
- errorCode: exports.ErrorResponseCodes.sdk_unknown_error,
11712
- });
11713
- }
11798
+ await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
11714
11799
  }
11715
11800
  const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareTransactionAuth(authenticationOptions, walletId);
11716
11801
  const { message, signature } = signatureMessage;
@@ -11775,20 +11860,7 @@ class Transactions extends Base {
11775
11860
  try {
11776
11861
  // Only attempt migration if we have password auth and V2 storage might be incomplete
11777
11862
  if (this.deviceAuthType === exports.AuthType.Password && authenticationOptions.password) {
11778
- try {
11779
- await this.walletService.handleUpdateToV2({
11780
- password: authenticationOptions.password,
11781
- walletId: walletId,
11782
- });
11783
- }
11784
- catch (error) {
11785
- logger.error('SDK::Transactions::resolvePendingTransaction::handleUpdateToV2::error', error);
11786
- throw new WallabyError({
11787
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
11788
- statusCode: 500,
11789
- errorCode: exports.ErrorResponseCodes.sdk_unknown_error,
11790
- });
11791
- }
11863
+ await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
11792
11864
  }
11793
11865
  const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareTransactionAuth(authenticationOptions, walletId);
11794
11866
  if (!readyForTransportSeedPhrase && !hasShares) {
@@ -11961,7 +12033,6 @@ class Wallaby {
11961
12033
  this.system = new System(config);
11962
12034
  this.transactions = new Transactions(config);
11963
12035
  this.swap = new Swap(config);
11964
- this.merchants = new Merchants(config);
11965
12036
  this.httpApi = new HttpApi(config);
11966
12037
  }
11967
12038
  get version() {