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.esm.js CHANGED
@@ -313,6 +313,10 @@ var V2KeyNames;
313
313
  V2KeyNames["WallabyAuthPubKey"] = "wallaby-auth-pub-key";
314
314
  V2KeyNames["MigrationVersion"] = "wsdk_migrated_with_version";
315
315
  V2KeyNames["LastMigratedAt"] = "wsdk_last_migrated_at";
316
+ V2KeyNames["PasswordResetAttempts"] = "wsdk_password_reset_attempts";
317
+ V2KeyNames["MigrationAttempts"] = "wsdk_migration_attempts";
318
+ V2KeyNames["CredentialConversionInProgress"] = "credential-conversion-in-progress";
319
+ V2KeyNames["PendingCommit"] = "pending-commit";
316
320
  })(V2KeyNames || (V2KeyNames = {}));
317
321
 
318
322
  var ErrorResponseCodes;
@@ -543,7 +547,7 @@ const global$1 = (typeof global !== "undefined" ? global :
543
547
  typeof self !== "undefined" ? self :
544
548
  typeof window !== "undefined" ? window : {});
545
549
 
546
- var env = {};
550
+ var env$1 = {};
547
551
 
548
552
  // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js
549
553
  var performance = global$1.performance || {};
@@ -555,7 +559,7 @@ performance.now ||
555
559
  function(){ return (new Date()).getTime() };
556
560
 
557
561
  var browser$1 = {
558
- env: env};
562
+ env: env$1};
559
563
 
560
564
  var _a;
561
565
  /**
@@ -589,7 +593,12 @@ const MASTER_ENCRYPTION_KEY = '9fa9d3f3c77c20d3a50a08e5299644be29f6e6206ef3479fe
589
593
  { type: 'public-key', alg: PublicKeyCredentialAlgorithm.ES256 },
590
594
  ];
591
595
  const isWeb = typeof window !== 'undefined' && typeof document !== 'undefined';
592
- const currentPackageVersion = "3.3.0" ;
596
+ const env = {
597
+ platform: 'web',
598
+ isNative: !isWeb,
599
+ isWeb,
600
+ };
601
+ const currentPackageVersion = "3.4.0" ;
593
602
 
594
603
  /**
595
604
  * Storage keys adapter for Storage interface across different platforms.
@@ -3490,7 +3499,6 @@ const keccak256$1 = (() => {
3490
3499
  })();
3491
3500
 
3492
3501
  const DEFAULT_ENTROPY_BYTES = 32;
3493
- const MINIMUM_SHANNON_ENTROPY = 4;
3494
3502
  /**
3495
3503
  * creates a new private key
3496
3504
  * @param { Uint8Array } entropy - optional entropy to create the private key
@@ -3501,25 +3509,15 @@ const createPrivateKey = (entropy) => {
3501
3509
  if (!(entropy instanceof Uint8Array) || entropy.length < DEFAULT_ENTROPY_BYTES) {
3502
3510
  throw new Error(`entropy must be a Uint8Array of at least ${DEFAULT_ENTROPY_BYTES} bytes`);
3503
3511
  }
3504
- // Check byte diversity
3512
+ // Check byte diversity. This catches genuinely broken inputs (all-zeros, all-same-byte)
3513
+ // without false-positiving on 32-byte KDF output (~30 unique bytes expected).
3514
+ // the sampled Shannon-entropy check was removed (WAL-1465) — it's unsound for
3515
+ // 32 samples (max measurable = log2(32) ≈ 5 bits/byte vs a 4-bit threshold), so deterministic
3516
+ // KDF output could be rejected, permanently locking the user out.
3505
3517
  const uniqueBytes = new Set(entropy);
3506
3518
  if (uniqueBytes.size < Math.min(8, entropy.length / 4)) {
3507
3519
  throw new Error(`entropy is too repetitive (only ${uniqueBytes.size} unique byte values)`);
3508
3520
  }
3509
- // Estimate Shannon entropy
3510
- const byteCounts = new Uint32Array(256);
3511
- entropy.forEach((b) => byteCounts[b]++);
3512
- const total = entropy.length;
3513
- let shannonEntropy = 0;
3514
- for (let i = 0; i < 256; i++) {
3515
- if (byteCounts[i] > 0) {
3516
- const p = byteCounts[i] / total;
3517
- shannonEntropy -= p * Math.log2(p);
3518
- }
3519
- }
3520
- if (shannonEntropy < MINIMUM_SHANNON_ENTROPY) {
3521
- throw new Error(`entropy has low Shannon entropy (${shannonEntropy.toFixed(2)} bits/byte)`);
3522
- }
3523
3521
  const outerHex = keccak256$1(entropy);
3524
3522
  return addLeading0x(bytesToHex$1(outerHex));
3525
3523
  }
@@ -4394,6 +4392,11 @@ function pbkdf2Sync(password, salt, iterations, keylen, digest) {
4394
4392
  });
4395
4393
  }
4396
4394
 
4395
+ // Version marker prepended to values wrapped by the master key, so wrapped vs raw is deterministic.
4396
+ const MASTER_KEY_WRAP_PREFIX = 'wsdkmk:v1:';
4397
+ // crypto-js AES.encrypt with a string passphrase emits an OpenSSL "Salted__" header; its base64 always
4398
+ // starts with this. Used to recognize legacy wrapped values stored before MASTER_KEY_WRAP_PREFIX existed.
4399
+ const LEGACY_CRYPTOJS_PREFIX = 'U2FsdGVkX1';
4397
4400
  class Cipher {
4398
4401
  constructor() { }
4399
4402
  /**
@@ -4424,11 +4427,23 @@ class Cipher {
4424
4427
  * @returns The encrypted data as a string.
4425
4428
  */
4426
4429
  encryptWithMasterKey({ data }) {
4427
- return AES.encrypt(typeof data === 'string' ? data : JSON.stringify(data), this.getMasterKey().key).toString();
4430
+ const ciphertext = AES.encrypt(typeof data === 'string' ? data : JSON.stringify(data), this.getMasterKey().key).toString();
4431
+ return MASTER_KEY_WRAP_PREFIX + ciphertext;
4432
+ }
4433
+ /**
4434
+ * @description Determines deterministically whether a stored value was wrapped by the master key,
4435
+ * without inferring from decrypt behavior. Returns true for values carrying the version marker, or
4436
+ * legacy crypto-js ciphertext stored before the marker existed. Everything else is treated as raw.
4437
+ */
4438
+ isWrappedByMasterKey(value) {
4439
+ return value.startsWith(MASTER_KEY_WRAP_PREFIX) || value.startsWith(LEGACY_CRYPTOJS_PREFIX);
4428
4440
  }
4429
4441
  decryptWithMasterKey({ cipherText }) {
4442
+ const ciphertext = cipherText.startsWith(MASTER_KEY_WRAP_PREFIX)
4443
+ ? cipherText.slice(MASTER_KEY_WRAP_PREFIX.length)
4444
+ : cipherText;
4430
4445
  try {
4431
- const decrypted = AES.decrypt(cipherText, this.getMasterKey().key).toString(enc.Utf8);
4446
+ const decrypted = AES.decrypt(ciphertext, this.getMasterKey().key).toString(enc.Utf8);
4432
4447
  if (decrypted) {
4433
4448
  return isJsonString(decrypted) ? safeJsonParse(decrypted) : decrypted;
4434
4449
  }
@@ -4546,6 +4561,8 @@ class Cipher {
4546
4561
  }
4547
4562
  derivedKeyPair = await this.deriveKeyPairFromPasskey({ inputKeyMaterial: options.prfValue });
4548
4563
  return derivedKeyPair;
4564
+ default:
4565
+ throw new Error(`Unknown AuthType: ${options.authType}`);
4549
4566
  }
4550
4567
  }
4551
4568
  catch (error) {
@@ -4805,6 +4822,14 @@ class StorageService {
4805
4822
  return;
4806
4823
  }
4807
4824
  async fetch(key, options) {
4825
+ var _a;
4826
+ // Recover once per session; memoize the promise so concurrent first-fetches all await the same
4827
+ // recovery instead of racing past it and reading pre-recovery storage. recoverCommit uses
4828
+ // getItem/removeItem (not fetch), so there's no recursion. Swallow errors: recovery is
4829
+ // best-effort and a failure must not wedge every subsequent fetch.
4830
+ await ((_a = this._walRecovery) !== null && _a !== void 0 ? _a : (this._walRecovery = this.recoverCommit().catch((error) => {
4831
+ logger.error('SDK::StorageService::fetch::wal recovery failed', error);
4832
+ })));
4808
4833
  let storageKey;
4809
4834
  if (this._walletSpecificKeys.includes(key)) {
4810
4835
  if (!(options === null || options === void 0 ? void 0 : options.walletId)) {
@@ -4815,7 +4840,7 @@ class StorageService {
4815
4840
  else {
4816
4841
  storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}`;
4817
4842
  }
4818
- if (!isWeb) {
4843
+ if (env.isNative) {
4819
4844
  storageKey = normalizeKey(storageKey);
4820
4845
  }
4821
4846
  const item = await this.getItem(storageKey);
@@ -4824,14 +4849,11 @@ class StorageService {
4824
4849
  return undefined;
4825
4850
  }
4826
4851
  if (this._keysProtectedByMasterKey.includes(key)) {
4827
- let unwrapped;
4828
- // Temp fix to unblock prod issue. Need a more permanent solution.
4829
- try {
4830
- unwrapped = this.cipher.decryptWithMasterKey({ cipherText: item });
4831
- }
4832
- catch (_a) {
4833
- unwrapped = item;
4852
+ // Raw legacy value stored before master-key wrapping: return as-is instead of attempting decrypt.
4853
+ if (!this.cipher.isWrappedByMasterKey(item)) {
4854
+ return item;
4834
4855
  }
4856
+ const unwrapped = this.cipher.decryptWithMasterKey({ cipherText: item });
4835
4857
  if (!unwrapped) {
4836
4858
  logger.error(`Failed to decrypt item with key ${storageKey}`);
4837
4859
  return undefined;
@@ -4851,7 +4873,7 @@ class StorageService {
4851
4873
  else {
4852
4874
  storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}`;
4853
4875
  }
4854
- if (!isWeb) {
4876
+ if (env.isNative) {
4855
4877
  storageKey = normalizeKey(storageKey);
4856
4878
  }
4857
4879
  let valueToStore;
@@ -4867,6 +4889,75 @@ class StorageService {
4867
4889
  async saveInBulk(data) {
4868
4890
  await Promise.all(data.map((item) => this.save(item.key, item.value, { walletId: item.walletId })));
4869
4891
  }
4892
+ // Compute the final storage key the same way save/fetch/delete do.
4893
+ _computeRawKey(key, walletId) {
4894
+ let storageKey;
4895
+ if (this._walletSpecificKeys.includes(key)) {
4896
+ if (!walletId)
4897
+ throw new Error(`A walletId is required to compute key: ${key}`);
4898
+ storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}:${walletId}`;
4899
+ }
4900
+ else {
4901
+ storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}`;
4902
+ }
4903
+ return isWeb ? storageKey : normalizeKey(storageKey);
4904
+ }
4905
+ _serializeValue(key, value) {
4906
+ if (this._keysProtectedByMasterKey.includes(key)) {
4907
+ return this.cipher.encryptWithMasterKey({ data: value });
4908
+ }
4909
+ return typeof value === 'string' ? value : JSON.stringify(value);
4910
+ }
4911
+ async _applyWAL(record) {
4912
+ for (const { rawKey, value } of record.writes) {
4913
+ await this.setItem(rawKey, value);
4914
+ }
4915
+ for (const rawKey of record.deletes) {
4916
+ await this.removeItem(rawKey);
4917
+ }
4918
+ }
4919
+ // Atomically commit a batch of writes and deletes via a write-ahead log.
4920
+ // The WAL record is written in a single setItem before any credential key is
4921
+ // touched. A crash between that write and the individual setItem calls leaves
4922
+ // the WAL in place; recoverCommit() finishes the batch on the next call.
4923
+ async commitBatch(writes, deletes) {
4924
+ const record = {
4925
+ writes: writes.map(({ key, value, walletId }) => ({
4926
+ rawKey: this._computeRawKey(key, walletId),
4927
+ value: this._serializeValue(key, value),
4928
+ })),
4929
+ deletes: (deletes !== null && deletes !== void 0 ? deletes : []).map(({ key, walletId }) => this._computeRawKey(key, walletId)),
4930
+ };
4931
+ // Finish any dangling WAL from a prior partially-applied commit before writing a new one —
4932
+ // otherwise this setItem clobbers it and those half-written credentials become unrecoverable.
4933
+ await this.recoverCommit();
4934
+ const walKey = this._computeRawKey(V2KeyNames.PendingCommit);
4935
+ await this.setItem(walKey, JSON.stringify(record));
4936
+ await this._applyWAL(record);
4937
+ await this.removeItem(walKey);
4938
+ }
4939
+ // Re-apply a pending WAL commit if the process was killed mid-batch.
4940
+ // Call at the start of any operation that writes credential blobs.
4941
+ async recoverCommit() {
4942
+ const walKey = this._computeRawKey(V2KeyNames.PendingCommit);
4943
+ const raw = await this.getItem(walKey);
4944
+ if (!raw)
4945
+ return;
4946
+ let record;
4947
+ try {
4948
+ record = safeJsonParse(raw);
4949
+ }
4950
+ catch (error) {
4951
+ // Corrupt/unparseable WAL can never be replayed — discard so it doesn't wedge every fetch.
4952
+ logger.error('SDK::StorageService::recoverCommit::corrupt WAL, discarding', error);
4953
+ await this.removeItem(walKey);
4954
+ return;
4955
+ }
4956
+ // _applyWAL is idempotent. If it throws (transient storage error) keep the WAL and let the
4957
+ // caller retry — don't delete the only record needed to finish the batch. Remove only on success.
4958
+ await this._applyWAL(record);
4959
+ await this.removeItem(walKey);
4960
+ }
4870
4961
  async delete(key, options) {
4871
4962
  let storageKey;
4872
4963
  if (this._walletSpecificKeys.includes(key)) {
@@ -4878,7 +4969,7 @@ class StorageService {
4878
4969
  else {
4879
4970
  storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}`;
4880
4971
  }
4881
- if (!isWeb) {
4972
+ if (env.isNative) {
4882
4973
  storageKey = normalizeKey(storageKey);
4883
4974
  }
4884
4975
  return await this.removeItem(storageKey);
@@ -5143,11 +5234,16 @@ class StorageService {
5143
5234
  LocalStorageItems.AccessToken,
5144
5235
  LocalStorageItems.RefreshToken,
5145
5236
  V2KeyNames.EncryptedDevicePrivateKey,
5237
+ V2KeyNames.ClientAuthPublicKey,
5146
5238
  V2KeyNames.WallabyAuthPubKey,
5147
5239
  V2KeyNames.PasskeyCredential,
5148
5240
  V2KeyNames.MigrationVersion,
5149
5241
  V2KeyNames.LastMigratedAt,
5150
5242
  V2KeyNames.ClientAuthToken,
5243
+ V2KeyNames.PasswordResetAttempts,
5244
+ V2KeyNames.MigrationAttempts,
5245
+ V2KeyNames.CredentialConversionInProgress,
5246
+ V2KeyNames.PendingCommit,
5151
5247
  ];
5152
5248
  await Promise.all(userKeysToRemove.map((key) => this.delete(key)));
5153
5249
  if (walletId) {
@@ -5279,6 +5375,11 @@ const AuthRoutes = {
5279
5375
  method: RequestMethod.Get,
5280
5376
  requiresAccessToken: true,
5281
5377
  },
5378
+ issueJwtToken: {
5379
+ fullPath: '/auth/issue-jwt-token',
5380
+ method: RequestMethod.Post,
5381
+ requiresAccessToken: false,
5382
+ },
5282
5383
  };
5283
5384
 
5284
5385
  class LockManagerService {
@@ -6886,8 +6987,9 @@ class Base {
6886
6987
  this.userId = sanitizedConfig.userId;
6887
6988
  this.options = sanitizedConfig.options;
6888
6989
  if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.platform) {
6889
- this.options.platform;
6890
- this.options.platform === 'ios' || this.options.platform === 'android';
6990
+ env.platform = this.options.platform;
6991
+ env.isNative = this.options.platform === 'ios' || this.options.platform === 'android';
6992
+ env.isWeb = !env.isNative;
6891
6993
  }
6892
6994
  this.cipher = new Cipher();
6893
6995
  this.lockManager = new LockManagerService();
@@ -7542,6 +7644,17 @@ function normalizeAndPadBase64(s) {
7542
7644
  function decodeBase64String(s) {
7543
7645
  return toUint8Array(normalizeAndPadBase64(s));
7544
7646
  }
7647
+ /**
7648
+ * Single-decode only: decode base64 (or base64url) to bytes. No round-trip double-decode.
7649
+ */
7650
+ function base64ToUint8Array(base64) {
7651
+ try {
7652
+ return toUint8Array(base64);
7653
+ }
7654
+ catch (_a) {
7655
+ return decodeBase64String(base64);
7656
+ }
7657
+ }
7545
7658
  function decodeBase64URL(base64url) {
7546
7659
  const padded = normalizeAndPadBase64(base64url);
7547
7660
  const binary = atob(padded);
@@ -7552,29 +7665,6 @@ function decodeBase64URL(base64url) {
7552
7665
  return bytes;
7553
7666
  }
7554
7667
 
7555
- /**
7556
- * Web: round-trip with uint8ArrayToBase64 (which does btoa(fromUint8Array(bytes, true))).
7557
- * Single decode first; if the result looks like a base64 string, decode again to get original bytes.
7558
- */
7559
- function base64ToUint8Array(base64) {
7560
- try {
7561
- const first = toUint8Array(base64);
7562
- const asStr = String.fromCharCode.apply(null, first);
7563
- if (/^[A-Za-z0-9+/\-_=]*$/.test(asStr) && asStr.length >= 4) {
7564
- try {
7565
- return decodeBase64String(asStr);
7566
- }
7567
- catch (_a) {
7568
- // fall through
7569
- }
7570
- }
7571
- return first;
7572
- }
7573
- catch (_b) {
7574
- return decodeBase64String(base64);
7575
- }
7576
- }
7577
-
7578
7668
  class PasskeyService {
7579
7669
  constructor(userId, storageService, request) {
7580
7670
  this.cipher = new Cipher();
@@ -7877,7 +7967,6 @@ class PasskeyService {
7877
7967
  }
7878
7968
  logger.log('SDK::PasskeyService::register:: getting signature', {
7879
7969
  message: challengeResponse.message,
7880
- privateKey: deviceKeyPair.privateKey,
7881
7970
  });
7882
7971
  const { signature, message } = await this.cipher.sign({
7883
7972
  message: challengeResponse.message,
@@ -8523,7 +8612,7 @@ class AuthService extends Base {
8523
8612
  data: deviceKeyPair.privateKey,
8524
8613
  encryptionKey: credentialsKeyPair.publicKey,
8525
8614
  });
8526
- this.localStorageService.saveInBulk([
8615
+ await this.localStorageService.saveInBulk([
8527
8616
  {
8528
8617
  key: LocalStorageItems.EncryptedDevicePrivateKey,
8529
8618
  value: encryptedDevicePrivKey,
@@ -8594,6 +8683,24 @@ class AuthService extends Base {
8594
8683
  valid: true,
8595
8684
  };
8596
8685
  }
8686
+ /**
8687
+ * @description Exchanges the client JWT (set at SDK initialisation) for a
8688
+ * Wallaby access + refresh token pair. Tokens are persisted to storage so
8689
+ * subsequent SDK calls use them automatically.
8690
+ * @returns {Promise<IssueJWTTokenResponseDto>} The issued access/refresh tokens and basic user info.
8691
+ */
8692
+ async exchangeClientToken() {
8693
+ try {
8694
+ const response = await this.request(AuthRoutes.issueJwtToken);
8695
+ await this.localStorageService.save(LocalStorageItems.AccessToken, response.accessToken);
8696
+ await this.localStorageService.save(LocalStorageItems.RefreshToken, response.refreshToken);
8697
+ return response;
8698
+ }
8699
+ catch (error) {
8700
+ logger.error('SDK::Auth::exchangeClientToken::error', error);
8701
+ throw error;
8702
+ }
8703
+ }
8597
8704
  }
8598
8705
  __decorate([
8599
8706
  WithLock('signUp'),
@@ -8614,6 +8721,63 @@ __decorate([
8614
8721
  __metadata("design:returntype", Promise)
8615
8722
  ], AuthService.prototype, "storeDeviceKeyPair", null);
8616
8723
 
8724
+ const ENCRYPTED_PAYLOAD_FIELDS = ['iv', 'ephemPublicKey', 'ciphertext', 'mac'];
8725
+ // Backup share may be ECIES or symmetric ({ iv, ciphertext, mac, tag }) — both share these three fields.
8726
+ const SYMMETRIC_PAYLOAD_FIELDS = ['iv', 'ciphertext', 'mac', 'tag'];
8727
+ // API is the trust boundary: confirm every named field is a non-empty string.
8728
+ function hasNonEmptyStringFields(payload, fields) {
8729
+ return (!!payload &&
8730
+ typeof payload === 'object' &&
8731
+ fields.every((field) => {
8732
+ const value = payload[field];
8733
+ return typeof value === 'string' && value.length > 0;
8734
+ }));
8735
+ }
8736
+ /**
8737
+ * Fail fast if an encrypted payload from the API does not match the expected
8738
+ * ECIES structure ({ iv, ephemPublicKey, ciphertext, mac }). See the contract
8739
+ * note on `handleKeySharesFromResponse`.
8740
+ */
8741
+ function assertEncryptedPayloadShape(encrypted) {
8742
+ if (!hasNonEmptyStringFields(encrypted, ENCRYPTED_PAYLOAD_FIELDS)) {
8743
+ throw new WallabyError({
8744
+ message: 'Encrypted share does not match the expected { iv, ephemPublicKey, ciphertext, mac } format.',
8745
+ statusCode: 422,
8746
+ errorCode: ErrorResponseCodes.sdk_invalid_parameter,
8747
+ });
8748
+ }
8749
+ }
8750
+ /**
8751
+ * Shape-assert every share returned by the API. Empty arrays are rejected here
8752
+ * so callers get a clean error instead of crashing on `shares[0]`.
8753
+ */
8754
+ function assertSharesPayloadShape(shares) {
8755
+ if (!shares.length) {
8756
+ throw new WallabyError({
8757
+ message: 'No key shares were returned from the API.',
8758
+ statusCode: 422,
8759
+ errorCode: ErrorResponseCodes.sdk_invalid_parameter,
8760
+ });
8761
+ }
8762
+ for (const share of shares) {
8763
+ assertEncryptedPayloadShape(share.encrypted);
8764
+ }
8765
+ }
8766
+ /**
8767
+ * The backup share is stored as-is (the device can't peel it), so we only
8768
+ * shape-check it. It may be ECIES or symmetric, so accept either variant.
8769
+ */
8770
+ function assertBackupSharePayloadShape(encrypted) {
8771
+ const isEcies = hasNonEmptyStringFields(encrypted, ENCRYPTED_PAYLOAD_FIELDS);
8772
+ const isSymmetric = hasNonEmptyStringFields(encrypted, SYMMETRIC_PAYLOAD_FIELDS);
8773
+ if (!isEcies && !isSymmetric) {
8774
+ throw new WallabyError({
8775
+ message: 'Encrypted backup share does not match the expected ECIES ({ iv, ephemPublicKey, ciphertext, mac }) or symmetric ({ iv, ciphertext, mac, tag }) format.',
8776
+ statusCode: 422,
8777
+ errorCode: ErrorResponseCodes.sdk_invalid_parameter,
8778
+ });
8779
+ }
8780
+ }
8617
8781
  class WalletHandlersService extends Base {
8618
8782
  constructor(config) {
8619
8783
  super(config);
@@ -8694,6 +8858,7 @@ class WalletHandlersService extends Base {
8694
8858
  shares: importWalletRequest.shares,
8695
8859
  credentialsKeyPair,
8696
8860
  encryptedBackupShare: importWalletRequest.encryptedBackupShare,
8861
+ devicePrivateKey: deviceAuthKeys.privateKey,
8697
8862
  });
8698
8863
  }
8699
8864
  return Object.assign({}, importWalletRequest);
@@ -8780,6 +8945,7 @@ class WalletHandlersService extends Base {
8780
8945
  shares: walletCreationResponse.shares,
8781
8946
  credentialsKeyPair,
8782
8947
  encryptedBackupShare: walletCreationResponse.encryptedBackupShare,
8948
+ devicePrivateKey: deviceAuthKeys.privateKey,
8783
8949
  });
8784
8950
  }
8785
8951
  return Object.assign(Object.assign({}, walletCreationResponse), { standardSeedPhrase: decryptedSeedPhrase });
@@ -8795,8 +8961,41 @@ class WalletHandlersService extends Base {
8795
8961
  });
8796
8962
  }
8797
8963
  }
8798
- async handleKeySharesFromResponse({ walletId, shares, credentialsKeyPair, encryptedBackupShare, }) {
8964
+ /**
8965
+ * Encrypted share format contract (WAL-1467)
8966
+ * --------------------------------------------------------------------------
8967
+ * Every flow that ingests shares from the API (import, create, recover,
8968
+ * addNewDevice) routes through here, so the contract is asserted in one place.
8969
+ *
8970
+ * The API returns the main device share as `shares[0]`, an ECIES payload
8971
+ * ({ iv, ephemPublicKey, ciphertext, mac }) wrapped to the device public key,
8972
+ * so it MUST peel with the device private key. `encryptedBackupShare` is an
8973
+ * already-wrapped blob (ECIES or symmetric) that the device cannot decrypt, so
8974
+ * it is stored as-is.
8975
+ *
8976
+ * We shape-assert every share (and the backup share) here, at ingestion, so a
8977
+ * server-side wrapping change fails loudly now instead of silently breaking
8978
+ * export/recovery later.
8979
+ */
8980
+ async handleKeySharesFromResponse({ walletId, shares, credentialsKeyPair, encryptedBackupShare, devicePrivateKey, }) {
8799
8981
  try {
8982
+ assertSharesPayloadShape(shares);
8983
+ assertBackupSharePayloadShape(encryptedBackupShare);
8984
+ // Decrypt-test the contract: shares[0] is wrapped to the device public key and must peel with the device private key.
8985
+ try {
8986
+ await this.cipher.decrypt({
8987
+ cipherText: shares[0].encrypted,
8988
+ decryptionKey: devicePrivateKey,
8989
+ });
8990
+ }
8991
+ catch (error) {
8992
+ throw new WallabyError({
8993
+ message: 'Device-wrapped key share (shares[0]) could not be decrypted with the device private key; the share wrapping format may have changed.',
8994
+ statusCode: 422,
8995
+ errorCode: ErrorResponseCodes.sdk_key_share_decryption_failed,
8996
+ cause: error,
8997
+ });
8998
+ }
8800
8999
  const encryptedWithCredentialsKeyShare = await this.cipher.encrypt({
8801
9000
  data: JSON.stringify(shares[0].encrypted),
8802
9001
  encryptionKey: credentialsKeyPair.publicKey,
@@ -8890,13 +9089,42 @@ class WalletHandlersService extends Base {
8890
9089
  class WalletService extends Base {
8891
9090
  constructor(config) {
8892
9091
  super(config);
8893
- this.passwordResetAttempts = 0;
8894
- this.migrationAttempts = 0;
8895
9092
  this.authService = new AuthService(config);
8896
9093
  this.handlers = new WalletHandlersService(config);
8897
9094
  this.userId = config.userId;
8898
9095
  this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request);
8899
9096
  }
9097
+ /**
9098
+ * Reads the persisted sliding-window rate-limit state for a counter key.
9099
+ * Returns a fresh window ({ count: 0 }) when none is stored or the window has expired.
9100
+ */
9101
+ async getRateState(key) {
9102
+ const now = Date.now();
9103
+ const raw = await this.localStorageService.fetch(key);
9104
+ const state = raw ? safeJsonParse(raw) : undefined;
9105
+ if (!state || now - state.windowStart > WalletService.RATE_LIMIT_WINDOW_MS) {
9106
+ return { count: 0, windowStart: now };
9107
+ }
9108
+ return state;
9109
+ }
9110
+ /** Increments and persists the counter (resetting an expired window). Returns the new count. */
9111
+ async recordRateAttempt(key) {
9112
+ const state = await this.getRateState(key);
9113
+ state.count += 1;
9114
+ await this.localStorageService.save(key, JSON.stringify(state));
9115
+ return state.count;
9116
+ }
9117
+ /** Throws a 429 when the counter is already over the limit, without incrementing it. */
9118
+ async assertUnderRateLimit(key, message) {
9119
+ const { count } = await this.getRateState(key);
9120
+ if (count > WalletService.RATE_LIMIT_MAX) {
9121
+ throw new WallabyError({
9122
+ message,
9123
+ statusCode: 429,
9124
+ errorCode: ErrorResponseCodes.sdk_too_many_requests,
9125
+ });
9126
+ }
9127
+ }
8900
9128
  /**
8901
9129
  * @public
8902
9130
  * @returns {boolean} Returns true if the device has a seed phrase.
@@ -9002,20 +9230,7 @@ class WalletService extends Base {
9002
9230
  });
9003
9231
  }
9004
9232
  if (this.deviceAuthType === AuthType.Password && authenticationOptions.password) {
9005
- try {
9006
- await this.handleUpdateToV2({
9007
- password: authenticationOptions.password,
9008
- walletId: walletId,
9009
- });
9010
- }
9011
- catch (error) {
9012
- logger.error('SDK::WalletService::export::handleUpdateToV2::error', error);
9013
- throw new WallabyError({
9014
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
9015
- statusCode: 500,
9016
- errorCode: ErrorResponseCodes.sdk_unknown_error,
9017
- });
9018
- }
9233
+ await this.migrateToV2Safe({ password: authenticationOptions.password, walletId });
9019
9234
  }
9020
9235
  const encryptedSeed = await this.localStorageService.fetch(LocalStorageItems.EncryptedStandardSeedPhrase, { walletId });
9021
9236
  const encryptedPrimaryDeviceShare = await this.localStorageService.fetch(LocalStorageItems.PrimaryDeviceKeyShare, {
@@ -9258,6 +9473,7 @@ class WalletService extends Base {
9258
9473
  shares: recoverWithSeedPhraseResponse.shares,
9259
9474
  credentialsKeyPair,
9260
9475
  encryptedBackupShare: recoverWithSeedPhraseResponse.encryptedBackupShare,
9476
+ devicePrivateKey: deviceAuthKeyPair.privateKey,
9261
9477
  });
9262
9478
  }
9263
9479
  await this.authService.storeDeviceKeyPair({
@@ -9321,6 +9537,7 @@ class WalletService extends Base {
9321
9537
  shares: recoverWithSeedPhraseResponse.shares,
9322
9538
  credentialsKeyPair,
9323
9539
  encryptedBackupShare: recoverWithSeedPhraseResponse.encryptedBackupShare,
9540
+ devicePrivateKey: deviceAuthKeyPair.privateKey,
9324
9541
  });
9325
9542
  }
9326
9543
  await this.authService.storeDeviceKeyPair({
@@ -9353,8 +9570,7 @@ class WalletService extends Base {
9353
9570
  */
9354
9571
  async changePassword({ walletId, oldPassword, newPassword, }) {
9355
9572
  try {
9356
- this.passwordResetAttempts += 1;
9357
- if (this.passwordResetAttempts > 5) {
9573
+ if ((await this.recordRateAttempt(V2KeyNames.PasswordResetAttempts)) > WalletService.RATE_LIMIT_MAX) {
9358
9574
  throw new WallabyError({
9359
9575
  message: 'Too many password change attempts. Please try again later.',
9360
9576
  statusCode: 429,
@@ -9363,20 +9579,7 @@ class WalletService extends Base {
9363
9579
  }
9364
9580
  if (this.deviceAuthType === AuthType.Password && oldPassword) {
9365
9581
  // Handle migration to V2 first then change the password to the new one.
9366
- try {
9367
- await this.handleUpdateToV2({
9368
- password: oldPassword,
9369
- walletId,
9370
- });
9371
- }
9372
- catch (error) {
9373
- logger.error('SDK::WalletService::changePassword::handleUpdateToV2::error', error);
9374
- throw new WallabyError({
9375
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
9376
- statusCode: 500,
9377
- errorCode: ErrorResponseCodes.sdk_unknown_error,
9378
- });
9379
- }
9582
+ await this.migrateToV2Safe({ password: oldPassword, walletId });
9380
9583
  }
9381
9584
  const encryptedDevicePrivateKeyString = await this.localStorageService.fetch(V2KeyNames.EncryptedDevicePrivateKey);
9382
9585
  const encryptedSeedPhraseString = await this.localStorageService.fetch(V2KeyNames.EncryptedStandardSeedPhrase, {
@@ -9410,7 +9613,7 @@ class WalletService extends Base {
9410
9613
  password: newPassword,
9411
9614
  salt: clientSalt,
9412
9615
  });
9413
- if (!newCredentialsKeyPair.publicKey) {
9616
+ if (!newCredentialsKeyPair.publicKey || !newCredentialsKeyPair.privateKey) {
9414
9617
  throw new WallabyError({
9415
9618
  message: 'Could not derive keys for new password.',
9416
9619
  statusCode: 500,
@@ -9433,40 +9636,48 @@ class WalletService extends Base {
9433
9636
  errorCode: ErrorResponseCodes.sdk_unknown_error,
9434
9637
  });
9435
9638
  }
9436
- await this.localStorageService.save(LocalStorageItems.EncryptedDevicePrivateKey, reWrappedDevicePrivateKey);
9437
- if (encryptedSeedPhraseString) {
9438
- const parsedSeed = safeJsonParse(encryptedSeedPhraseString);
9439
- const reWrappedSeedPhrase = await this.cipher.flipEncryptedData({
9440
- cipherText: parsedSeed,
9639
+ // Round-trip validate: decrypt the re-wrapped blob with the new key before committing.
9640
+ // Catches a malformed re-encryption before it overwrites the live credential.
9641
+ await this.assertRoundTrip(reWrappedDevicePrivateKey, newCredentialsKeyPair.privateKey, 'device key');
9642
+ const reWrappedSeedPhrase = encryptedSeedPhraseString
9643
+ ? await this.cipher.flipEncryptedData({
9644
+ cipherText: safeJsonParse(encryptedSeedPhraseString),
9441
9645
  decryptionKey: oldCredentialsKeyPair.privateKey,
9442
9646
  encryptionKey: newCredentialsKeyPair.publicKey,
9443
- });
9444
- await this.localStorageService.save(LocalStorageItems.EncryptedStandardSeedPhrase, reWrappedSeedPhrase, {
9445
- walletId,
9446
- });
9447
- }
9448
- if (encryptedPrimaryShareString) {
9449
- const parsedPrimaryShare = safeJsonParse(encryptedPrimaryShareString);
9450
- const reWrappedPrimaryShare = await this.cipher.flipEncryptedData({
9451
- cipherText: parsedPrimaryShare,
9647
+ })
9648
+ : null;
9649
+ const reWrappedPrimaryShare = encryptedPrimaryShareString
9650
+ ? await this.cipher.flipEncryptedData({
9651
+ cipherText: safeJsonParse(encryptedPrimaryShareString),
9452
9652
  decryptionKey: oldCredentialsKeyPair.privateKey,
9453
9653
  encryptionKey: newCredentialsKeyPair.publicKey,
9454
- });
9455
- await this.localStorageService.save(LocalStorageItems.PrimaryDeviceKeyShare, reWrappedPrimaryShare, {
9456
- walletId,
9457
- });
9458
- }
9459
- if (encryptedBackupShareString) {
9460
- const parsedBackupShare = safeJsonParse(encryptedBackupShareString);
9461
- const reWrappedBackupShare = await this.cipher.flipEncryptedData({
9462
- cipherText: parsedBackupShare,
9654
+ })
9655
+ : null;
9656
+ const reWrappedBackupShare = encryptedBackupShareString
9657
+ ? await this.cipher.flipEncryptedData({
9658
+ cipherText: safeJsonParse(encryptedBackupShareString),
9463
9659
  decryptionKey: oldCredentialsKeyPair.privateKey,
9464
9660
  encryptionKey: newCredentialsKeyPair.publicKey,
9465
- });
9466
- await this.localStorageService.save(LocalStorageItems.BackupDeviceKeyShare, reWrappedBackupShare, {
9467
- walletId,
9468
- });
9469
- }
9661
+ })
9662
+ : null;
9663
+ if (reWrappedSeedPhrase)
9664
+ await this.assertRoundTrip(reWrappedSeedPhrase, newCredentialsKeyPair.privateKey, 'seed phrase');
9665
+ if (reWrappedPrimaryShare)
9666
+ await this.assertRoundTrip(reWrappedPrimaryShare, newCredentialsKeyPair.privateKey, 'primary share');
9667
+ if (reWrappedBackupShare)
9668
+ await this.assertRoundTrip(reWrappedBackupShare, newCredentialsKeyPair.privateKey, 'backup share');
9669
+ await this.localStorageService.commitBatch([
9670
+ { key: LocalStorageItems.EncryptedDevicePrivateKey, value: reWrappedDevicePrivateKey },
9671
+ ...(reWrappedSeedPhrase
9672
+ ? [{ key: LocalStorageItems.EncryptedStandardSeedPhrase, value: reWrappedSeedPhrase, walletId }]
9673
+ : []),
9674
+ ...(reWrappedPrimaryShare
9675
+ ? [{ key: LocalStorageItems.PrimaryDeviceKeyShare, value: reWrappedPrimaryShare, walletId }]
9676
+ : []),
9677
+ ...(reWrappedBackupShare ? [{ key: LocalStorageItems.BackupDeviceKeyShare, value: reWrappedBackupShare, walletId }] : []),
9678
+ ]);
9679
+ // Reset the rate-limit window on success so a normal change does not count against future ones.
9680
+ await this.localStorageService.delete(V2KeyNames.PasswordResetAttempts);
9470
9681
  return true;
9471
9682
  }
9472
9683
  catch (error) {
@@ -9519,20 +9730,7 @@ class WalletService extends Base {
9519
9730
  }
9520
9731
  const parsedEncryptedDevicePrivateKey = safeJsonParse(encryptedDevicePrivateKey);
9521
9732
  if (this.deviceAuthType === AuthType.Password && input.authenticationOptions.password) {
9522
- try {
9523
- await this.handleUpdateToV2({
9524
- password: input.authenticationOptions.password,
9525
- walletId: input.walletId,
9526
- });
9527
- }
9528
- catch (error) {
9529
- logger.error('SDK::WalletService::initAddNewDevice::handleUpdateToV2::error', error);
9530
- throw new WallabyError({
9531
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
9532
- statusCode: 500,
9533
- errorCode: ErrorResponseCodes.sdk_unknown_error,
9534
- });
9535
- }
9733
+ await this.migrateToV2Safe({ password: input.authenticationOptions.password, walletId: input.walletId });
9536
9734
  }
9537
9735
  const storedEncryptedBackupShare = await this.localStorageService.fetch(LocalStorageItems.BackupDeviceKeyShare, { walletId });
9538
9736
  if (!storedEncryptedBackupShare) {
@@ -9630,6 +9828,7 @@ class WalletService extends Base {
9630
9828
  shares: [backUpResponse.share],
9631
9829
  credentialsKeyPair,
9632
9830
  encryptedBackupShare: input.encryptedBackupShare,
9831
+ devicePrivateKey: decryptedDevicePrivateKey,
9633
9832
  });
9634
9833
  return { success: true, reference: backUpResponse.reference };
9635
9834
  }
@@ -9648,20 +9847,7 @@ class WalletService extends Base {
9648
9847
  });
9649
9848
  }
9650
9849
  if (this.deviceAuthType === AuthType.Password && input.authenticationOptions.password) {
9651
- try {
9652
- await this.handleUpdateToV2({
9653
- password: input.authenticationOptions.password,
9654
- walletId: input.walletId,
9655
- });
9656
- }
9657
- catch (error) {
9658
- logger.error('SDK::WalletService::generateWalletAddresses::handleUpdateToV2::error', error);
9659
- throw new WallabyError({
9660
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
9661
- statusCode: 500,
9662
- errorCode: ErrorResponseCodes.sdk_unknown_error,
9663
- });
9664
- }
9850
+ await this.migrateToV2Safe({ password: input.authenticationOptions.password, walletId: input.walletId });
9665
9851
  }
9666
9852
  try {
9667
9853
  const walletOperationAuth = await this.prepareWalletOperationAuth({
@@ -9686,6 +9872,23 @@ class WalletService extends Base {
9686
9872
  throw error;
9687
9873
  }
9688
9874
  }
9875
+ /**
9876
+ * Wraps handleUpdateToV2 with the standard user-facing error. All call sites that gate on
9877
+ * `AuthType.Password` should go through here so the error message stays consistent.
9878
+ */
9879
+ async migrateToV2Safe({ password, walletId }) {
9880
+ try {
9881
+ await this.handleUpdateToV2({ password, walletId });
9882
+ }
9883
+ catch (error) {
9884
+ logger.error('SDK::WalletService::migrateToV2Safe::error', error);
9885
+ throw new WallabyError({
9886
+ message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
9887
+ statusCode: 500,
9888
+ errorCode: ErrorResponseCodes.sdk_unknown_error,
9889
+ });
9890
+ }
9891
+ }
9689
9892
  /**
9690
9893
  * Detects and migrates legacy/v1 storage items to v2 format.
9691
9894
  * This function should be called in methods that use password as input when v2 items are missing.
@@ -9694,13 +9897,7 @@ class WalletService extends Base {
9694
9897
  */
9695
9898
  async handleUpdateToV2({ password, walletId }) {
9696
9899
  const migrationStartTime = Date.now();
9697
- if (this.migrationAttempts > 5) {
9698
- throw new WallabyError({
9699
- message: 'Too many migration attempts. Please try again later.',
9700
- statusCode: 429,
9701
- errorCode: ErrorResponseCodes.sdk_too_many_requests,
9702
- });
9703
- }
9900
+ await this.assertUnderRateLimit(V2KeyNames.MigrationAttempts, 'Too many migration attempts. Please try again later.');
9704
9901
  try {
9705
9902
  if (!password) {
9706
9903
  throw new WallabyError({
@@ -9771,7 +9968,7 @@ class WalletService extends Base {
9771
9968
  }
9772
9969
  }
9773
9970
  // Increment counter after V2 validation to avoid counting when migration not needed
9774
- this.migrationAttempts += 1;
9971
+ await this.recordRateAttempt(V2KeyNames.MigrationAttempts);
9775
9972
  let decryptedSeedPhrase;
9776
9973
  let decryptedPrivateKey;
9777
9974
  // Check for legacy format: `{item}_{userId}`
@@ -9824,7 +10021,10 @@ class WalletService extends Base {
9824
10021
  try {
9825
10022
  // Decrypt V1 items using storage service method (handles double encryption)
9826
10023
  logger.log('Attempting to decrypt V1 items during migration...');
9827
- logger.log('getV1DecryptedSeedPhrase should be called with password and clientSalt:', { password, clientSalt });
10024
+ logger.log('getV1DecryptedSeedPhrase should be called with password and clientSalt:', {
10025
+ hasPassword: !!password,
10026
+ hasClientSalt: !!clientSalt,
10027
+ });
9828
10028
  decryptedSeedPhrase = await this.localStorageService.getV1DecryptedSeedPhrase(password, clientSalt);
9829
10029
  // For V1 format, private key is encrypted with just the password (not salt+password like legacy)
9830
10030
  decryptedPrivateKey = await this.localStorageService.getDecryptedV1PrivateKey(password);
@@ -10051,7 +10251,28 @@ class WalletService extends Base {
10051
10251
  * @returns { boolean } whether the operation was successful
10052
10252
  */
10053
10253
  async convertToPasskey(input) {
10254
+ let passkeyRegistered = false;
10054
10255
  try {
10256
+ // Recover an interrupted conversion BEFORE reading any credential blob. A prior attempt may have
10257
+ // already rewrapped EncryptedDevicePrivateKey to passkey form (addNewPasskey persists it outside
10258
+ // this method's atomic commit), which the password can no longer decrypt — and deriving the passkey
10259
+ // key to decrypt it needs the device key itself (circular). The marker stashes the original
10260
+ // password-encrypted device key; restore it so the rest of the flow runs as a fresh conversion.
10261
+ const rawConversionMarker = (await this.localStorageService.fetch(V2KeyNames.CredentialConversionInProgress));
10262
+ const existingConversionMarker = rawConversionMarker
10263
+ ? safeJsonParse(rawConversionMarker)
10264
+ : undefined;
10265
+ // Restore the stashed device key whenever a marker carries one — independent of walletId. The
10266
+ // device key is per-user (not wallet-scoped), so a conversion interrupted on a different wallet
10267
+ // leaves the shared device key passkey-wrapped too. Restoring is idempotent (rewrites the
10268
+ // original password-encrypted blob) and stops a second wallet's conversion from destroying the
10269
+ // first's recovery state. v2 only — a v1 wallet's untouched v1 key still decrypts.
10270
+ if (existingConversionMarker === null || existingConversionMarker === void 0 ? void 0 : existingConversionMarker.encryptedDevicePrivateKey) {
10271
+ await this.localStorageService.save(LocalStorageItems.EncryptedDevicePrivateKey, existingConversionMarker.encryptedDevicePrivateKey);
10272
+ }
10273
+ if ((existingConversionMarker === null || existingConversionMarker === void 0 ? void 0 : existingConversionMarker.walletId) === input.walletId) {
10274
+ logger.info('SDK::WalletService::convertToPasskey::resuming interrupted conversion');
10275
+ }
10055
10276
  const v2EncryptedPriv = await this.localStorageService.fetch(LocalStorageItems.EncryptedDevicePrivateKey);
10056
10277
  const v2EncryptedSeed = await this.localStorageService.fetch(LocalStorageItems.EncryptedStandardSeedPhrase, {
10057
10278
  walletId: input.walletId,
@@ -10100,6 +10321,10 @@ class WalletService extends Base {
10100
10321
  });
10101
10322
  }
10102
10323
  const clientPublicKey = publicKeyByPrivateKey(decryptedClientAuthPrivKey);
10324
+ // Write-ahead marker: set before the unrevocable passkey registration so an interrupted
10325
+ // conversion can be resumed on the next attempt. Stash the original password-encrypted device
10326
+ // key so resume survives addNewPasskey rewrapping the stored device key to passkey form.
10327
+ await this.localStorageService.save(V2KeyNames.CredentialConversionInProgress, Object.assign({ walletId: input.walletId }, (v2EncryptedPriv ? { encryptedDevicePrivateKey: v2EncryptedPriv } : {})));
10103
10328
  const authentication = await this.passkeyService.addNewPasskey({
10104
10329
  deviceKeyPair: {
10105
10330
  publicKey: clientPublicKey,
@@ -10107,6 +10332,7 @@ class WalletService extends Base {
10107
10332
  },
10108
10333
  getSignature: this.authService.getSignature.bind(this),
10109
10334
  });
10335
+ passkeyRegistered = true;
10110
10336
  const prfValue = authentication.prfValue;
10111
10337
  if (!prfValue || !(prfValue instanceof Uint8Array) || prfValue.length === 0) {
10112
10338
  logger.error('SDK::WalletService::convertToPasskey::prfValue is required and must be a non-empty Uint8Array');
@@ -10203,8 +10429,13 @@ class WalletService extends Base {
10203
10429
  storeOneKeyShareWithWallaby: true,
10204
10430
  },
10205
10431
  });
10206
- // Delete the old password-encrypted seed phrase since import stored the new passkey-encrypted version
10207
- await this.localStorageService.delete(LocalStorageItems.EncryptedStandardSeedPhrase, { walletId: input.walletId });
10432
+ // idempotent — on retry (marker present, primary now passkey-encrypted so
10433
+ // decryptedPrimaryShare is undefined → Branch A re-enters), handleImportWallet re-shares
10434
+ // safely; this atomic delete clears the stale seed + marker together.
10435
+ await this.localStorageService.commitBatch([], [
10436
+ { key: LocalStorageItems.EncryptedStandardSeedPhrase, walletId: input.walletId },
10437
+ { key: V2KeyNames.CredentialConversionInProgress },
10438
+ ]);
10208
10439
  logger.info('SDK::WalletService::convertToPasskey::Wallet imported and converted successfully, old seed phrase removed');
10209
10440
  return { authentication, seedPhrase: decryptedSeedPhrase };
10210
10441
  }
@@ -10222,6 +10453,24 @@ class WalletService extends Base {
10222
10453
  privateKey: decryptedClientAuthPrivKey,
10223
10454
  },
10224
10455
  });
10456
+ // assertRoundTrip below only strips the outer (passkey) layer — validate the inner (device key) layer here.
10457
+ const outerDecrypted = await this.cipher.decrypt({
10458
+ cipherText: encryptedPrimaryShare,
10459
+ decryptionKey: passkeyDerivedKeyPair.privateKey,
10460
+ });
10461
+ const innerDecrypted = outerDecrypted
10462
+ ? await this.cipher.decrypt({
10463
+ cipherText: safeJsonParse(outerDecrypted),
10464
+ decryptionKey: decryptedClientAuthPrivKey,
10465
+ })
10466
+ : null;
10467
+ if (innerDecrypted !== decryptedPrimaryShare) {
10468
+ throw new WallabyError({
10469
+ message: 'Re-wrap validation failed for primary share: inner layer round-trip mismatch. Aborting to prevent credential corruption.',
10470
+ statusCode: 500,
10471
+ errorCode: ErrorResponseCodes.sdk_unknown_error,
10472
+ });
10473
+ }
10225
10474
  convertedShares.push({
10226
10475
  key: V2KeyNames.PrimaryDeviceKeyShare,
10227
10476
  value: encryptedPrimaryShare,
@@ -10240,9 +10489,16 @@ class WalletService extends Base {
10240
10489
  walletId: input.walletId,
10241
10490
  });
10242
10491
  }
10243
- await this.localStorageService.saveInBulk(convertedShares);
10492
+ // Round-trip validate each re-encrypted blob (outer layer only) before writing.
10493
+ // A failed decrypt here means re-encryption produced an unreadable blob — abort before overwriting live credentials.
10494
+ for (const share of convertedShares) {
10495
+ await this.assertRoundTrip(share.value, passkeyDerivedKeyPair.privateKey, share.key);
10496
+ }
10497
+ await this.localStorageService.commitBatch(convertedShares, [
10498
+ ...(v2EncryptedSeed ? [{ key: LocalStorageItems.EncryptedStandardSeedPhrase, walletId: input.walletId }] : []),
10499
+ { key: V2KeyNames.CredentialConversionInProgress },
10500
+ ]);
10244
10501
  if (v2EncryptedSeed) {
10245
- await this.localStorageService.delete(LocalStorageItems.EncryptedStandardSeedPhrase, { walletId: input.walletId });
10246
10502
  logger.info('SDK::WalletService::convertToPasskey::Seed phrase removed from device storage after conversion to passkey');
10247
10503
  }
10248
10504
  if (!decryptedSeedPhrase && decryptedPrimaryShare) {
@@ -10285,10 +10541,33 @@ class WalletService extends Base {
10285
10541
  }
10286
10542
  catch (error) {
10287
10543
  logger.error('SDK::WalletService::convertToPasskey::error', error);
10544
+ // Only clear the marker if the passkey was not yet registered. After registration the
10545
+ // marker must survive for roll-forward on the next attempt.
10546
+ if (!passkeyRegistered) {
10547
+ await this.localStorageService.delete(V2KeyNames.CredentialConversionInProgress);
10548
+ }
10288
10549
  throw error;
10289
10550
  }
10290
10551
  }
10552
+ // shared guard — decrypt-tests a re-wrapped blob before any write so a malformed
10553
+ // re-encryption is caught before it overwrites the live credential.
10554
+ async assertRoundTrip(blob, decryptionKey, label) {
10555
+ try {
10556
+ await this.cipher.decrypt({ cipherText: blob, decryptionKey });
10557
+ }
10558
+ catch (_a) {
10559
+ throw new WallabyError({
10560
+ message: `Re-wrap validation failed for ${label}: decryption of the re-encrypted blob failed. Aborting to prevent credential corruption.`,
10561
+ statusCode: 500,
10562
+ errorCode: ErrorResponseCodes.sdk_unknown_error,
10563
+ });
10564
+ }
10565
+ }
10291
10566
  }
10567
+ // soft client-side guardrail against runaway retries; server-side rate limiting is the real control.
10568
+ // Counters are persisted (sliding window) so rebuilding the service no longer resets them. Tune freely.
10569
+ WalletService.RATE_LIMIT_MAX = 5;
10570
+ WalletService.RATE_LIMIT_WINDOW_MS = 30 * 60000; // 30 min
10292
10571
  __decorate([
10293
10572
  WithLock('create'),
10294
10573
  __metadata("design:type", Function),
@@ -10308,7 +10587,7 @@ __decorate([
10308
10587
  __metadata("design:returntype", Promise)
10309
10588
  ], WalletService.prototype, "recover", null);
10310
10589
  __decorate([
10311
- WithLock('changePassword'),
10590
+ WithLock('credential-rewrap'),
10312
10591
  __metadata("design:type", Function),
10313
10592
  __metadata("design:paramtypes", [Object]),
10314
10593
  __metadata("design:returntype", Promise)
@@ -10319,6 +10598,12 @@ __decorate([
10319
10598
  __metadata("design:paramtypes", [Object]),
10320
10599
  __metadata("design:returntype", Promise)
10321
10600
  ], WalletService.prototype, "handleUpdateToV2", null);
10601
+ __decorate([
10602
+ WithLock('credential-rewrap'),
10603
+ __metadata("design:type", Function),
10604
+ __metadata("design:paramtypes", [Object]),
10605
+ __metadata("design:returntype", Promise)
10606
+ ], WalletService.prototype, "convertToPasskey", null);
10322
10607
 
10323
10608
  class WalletDataService extends Base {
10324
10609
  constructor(config) {
@@ -10571,20 +10856,7 @@ class WalletDataService extends Base {
10571
10856
  });
10572
10857
  }
10573
10858
  if (this.deviceAuthType === AuthType.Password && authenticationOptions.password) {
10574
- try {
10575
- await this.walletService.handleUpdateToV2({
10576
- password: authenticationOptions.password,
10577
- walletId: walletId,
10578
- });
10579
- }
10580
- catch (error) {
10581
- logger.error('SDK::WalletDataService::addNewChainAndTokenToWallet::handleUpdateToV2::error', error);
10582
- throw new WallabyError({
10583
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
10584
- statusCode: 500,
10585
- errorCode: ErrorResponseCodes.sdk_unknown_error,
10586
- });
10587
- }
10859
+ await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
10588
10860
  }
10589
10861
  try {
10590
10862
  const addressInfo = await this.walletService.generateWalletAddresses({
@@ -10785,179 +11057,6 @@ class Utils extends Base {
10785
11057
  }
10786
11058
  }
10787
11059
 
10788
- const MerchantsRoutes = {
10789
- create: {
10790
- fullPath: '/merchants',
10791
- method: RequestMethod.Post,
10792
- requiresAccessToken: false,
10793
- },
10794
- update: {
10795
- fullPath: ({ merchantId }) => `/merchants/${merchantId}`,
10796
- method: RequestMethod.Put,
10797
- requiresAccessToken: false,
10798
- },
10799
- getMerchantData: {
10800
- fullPath: ({ merchantId }) => `/merchants/${merchantId}`,
10801
- method: RequestMethod.Get,
10802
- requiresAccessToken: false,
10803
- },
10804
- list: {
10805
- fullPath: '/merchants',
10806
- method: RequestMethod.Get,
10807
- requiresAccessToken: false,
10808
- },
10809
- getAssets: {
10810
- fullPath: () => `/users/merchant/assets`,
10811
- method: RequestMethod.Get,
10812
- requiresAccessToken: true,
10813
- },
10814
- addAsset: {
10815
- fullPath: ({ merchantId, configId }) => `/merchants/${merchantId}/assets/${configId}`,
10816
- method: RequestMethod.Post,
10817
- requiresAccessToken: false,
10818
- },
10819
- deleteAsset: {
10820
- fullPath: ({ merchantId, configId }) => `/merchants/${merchantId}/assets/${configId}`,
10821
- method: RequestMethod.Delete,
10822
- requiresAccessToken: false,
10823
- },
10824
- };
10825
-
10826
- class Merchants extends Base {
10827
- constructor(config) {
10828
- super(config);
10829
- }
10830
- /**
10831
- * @description
10832
- * Retrieves the merchant ID from access token `aud` claim.
10833
- * Even though merchantId is possibly undefined. If an access token is not stored on device, the request will most likely
10834
- * not have it in headers and will fail with 401 regardless.
10835
- *
10836
- * @returns { string | undefined } Merchant ID
10837
- */
10838
- async _getMerchantId() {
10839
- const accessToken = await this.localStorageService.fetch(LocalStorageItems.AccessToken);
10840
- if (!accessToken)
10841
- return;
10842
- const jwtDecoded = jwtDecode(accessToken);
10843
- return jwtDecoded.aud;
10844
- }
10845
- /**
10846
- *
10847
- * @public
10848
- * List of all merchants in the system
10849
- * @returns { ListMerchantsResponse } Array of all merchants
10850
- */
10851
- async list() {
10852
- try {
10853
- const response = await this.request(MerchantsRoutes.list, {
10854
- payload: {},
10855
- });
10856
- return response;
10857
- }
10858
- catch (error) {
10859
- logger.error('SDK::Merchants::list::error', error);
10860
- return Promise.reject(error);
10861
- }
10862
- }
10863
- /**
10864
- *
10865
- * @public
10866
- * Allows to create a new merchant
10867
- * @returns { Merchant } Merchant data
10868
- */
10869
- async create({ name }) {
10870
- try {
10871
- const response = await this.request(MerchantsRoutes.create, {
10872
- payload: { name },
10873
- });
10874
- return response;
10875
- }
10876
- catch (error) {
10877
- logger.error('SDK::Merchants::list::error', error);
10878
- return Promise.reject(error);
10879
- }
10880
- }
10881
- /**
10882
- *
10883
- * @public
10884
- * Allows to update merchant data
10885
- * @returns { Merchant } Merchant data
10886
- */
10887
- async update({ name, status }) {
10888
- try {
10889
- const merchantId = await this._getMerchantId();
10890
- const response = await this.request(MerchantsRoutes.update, {
10891
- payload: { merchantId, name, status },
10892
- });
10893
- return response;
10894
- }
10895
- catch (error) {
10896
- logger.error('SDK::Merchants::list::error', error);
10897
- return Promise.reject(error);
10898
- }
10899
- }
10900
- /**
10901
- *
10902
- * @public
10903
- * @returns { Merchant } Merchant data
10904
- */
10905
- async getMerchantData() {
10906
- try {
10907
- const merchantId = await this._getMerchantId();
10908
- const response = await this.request(MerchantsRoutes.getMerchantData, {
10909
- payload: { merchantId },
10910
- });
10911
- return response.merchant;
10912
- }
10913
- catch (error) {
10914
- logger.error('SDK::Merchants::list::error', error);
10915
- return Promise.reject(error);
10916
- }
10917
- }
10918
- /**
10919
- *
10920
- * @public
10921
- * @returns { MerchantAsset[] } List of merchant assets
10922
- */
10923
- async getAssets() {
10924
- try {
10925
- const response = await this.request(MerchantsRoutes.getAssets);
10926
- return response.merchantAssets;
10927
- }
10928
- catch (error) {
10929
- logger.error('SDK::Merchants::list::error', error);
10930
- return Promise.reject(error);
10931
- }
10932
- }
10933
- async addAsset({ configId }) {
10934
- try {
10935
- const merchantId = await this._getMerchantId();
10936
- const response = await this.request(MerchantsRoutes.addAsset, {
10937
- payload: { merchantId, configId },
10938
- });
10939
- return response;
10940
- }
10941
- catch (error) {
10942
- logger.error('SDK::Merchants::list::error', error);
10943
- return Promise.reject(error);
10944
- }
10945
- }
10946
- async deleteAsset({ configId }) {
10947
- try {
10948
- const merchantId = await this._getMerchantId();
10949
- const response = await this.request(MerchantsRoutes.deleteAsset, {
10950
- payload: { merchantId, configId },
10951
- });
10952
- return response;
10953
- }
10954
- catch (error) {
10955
- logger.error('SDK::Merchants::list::error', error);
10956
- return Promise.reject(error);
10957
- }
10958
- }
10959
- }
10960
-
10961
11060
  /**
10962
11061
  * HttpApi provides direct access to all REST API endpoints.
10963
11062
  * This class extends the Base class and includes the generated API client
@@ -11038,20 +11137,7 @@ class Swap extends Base {
11038
11137
  try {
11039
11138
  // Only attempt migration if we have password auth and V2 storage might be incomplete
11040
11139
  if (this.deviceAuthType === AuthType.Password && authenticationOptions.password) {
11041
- try {
11042
- await this.walletService.handleUpdateToV2({
11043
- password: authenticationOptions.password,
11044
- walletId: walletId,
11045
- });
11046
- }
11047
- catch (error) {
11048
- logger.error('SDK::Swap::executeSwap::handleUpdateToV2::error', error);
11049
- throw new WallabyError({
11050
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
11051
- statusCode: 500,
11052
- errorCode: ErrorResponseCodes.sdk_unknown_error,
11053
- });
11054
- }
11140
+ await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
11055
11141
  }
11056
11142
  const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareSwapAuth(authenticationOptions, walletId);
11057
11143
  let swapResponse;
@@ -11246,6 +11332,27 @@ const sanitizeSuiObjectId = (objectId) => {
11246
11332
  return objectId.split('::')[0];
11247
11333
  };
11248
11334
 
11335
+ /**
11336
+ * Extracts the asset symbol from a fully-qualified Sui coin type.
11337
+ *
11338
+ * A Sui coin type has the shape `<package>::<module>::<TYPE>`, where the final
11339
+ * segment is the coin's struct name and doubles as its symbol.
11340
+ *
11341
+ * @param objectId - The Sui object id / coin type. Example input:
11342
+ * "0xc91acfb75009c5ff2fd57c54f3caaee12ad1fbe997681334adc0b574fc277a07::icorgi::ICORGI"
11343
+ * @returns The symbol (e.g. "ICORGI"), or undefined when the id carries no
11344
+ * `::module::TYPE` suffix to derive it from.
11345
+ */
11346
+ const extractSuiAssetSymbol = (objectId) => {
11347
+ var _a;
11348
+ if (!objectId || !objectId.includes('::')) {
11349
+ return undefined;
11350
+ }
11351
+ const segments = objectId.split('::');
11352
+ const symbol = (_a = segments[segments.length - 1]) === null || _a === void 0 ? void 0 : _a.trim();
11353
+ return symbol || undefined;
11354
+ };
11355
+
11249
11356
  class System extends Base {
11250
11357
  constructor(config) {
11251
11358
  super(config);
@@ -11334,6 +11441,9 @@ class System extends Base {
11334
11441
  * @param {BlockchainName} blockchain - The name of the blockchain.
11335
11442
  * @param {string} contractAddress - The contract address of the token (optional for non-SUI blockchains).
11336
11443
  * @param {string} suiObjectId - The SUI object ID of the token (optional for SUI blockchain).
11444
+ * @param {string} assetSymbol - The asset symbol; disambiguates new SUI assets. For SUI it is
11445
+ * optional: when omitted, it is derived from the `::module::TYPE` suffix of `suiObjectId`
11446
+ * (which is otherwise trimmed off before the request is sent).
11337
11447
  *
11338
11448
  * @returns {Promise<{ decimals: number; symbol: string; name: string; tokenContractAddress: string }>} A promise that resolves to an object containing token information.
11339
11449
  *
@@ -11342,18 +11452,19 @@ class System extends Base {
11342
11452
  * @throws Will throw an error if `contractAddress` is not provided for non-SUI blockchains.
11343
11453
  * @throws Will throw an error if the response is invalid or contains an error.
11344
11454
  */
11345
- async fetchTokenInfo({ blockchain, contractAddress, suiObjectId, }) {
11455
+ async fetchTokenInfo({ blockchain, contractAddress, suiObjectId, assetSymbol, }) {
11346
11456
  try {
11347
11457
  const validatedContractAddress = this.validateContractAddress({
11348
11458
  blockchain,
11349
11459
  contractAddress,
11350
11460
  suiObjectId,
11351
11461
  });
11462
+ // For SUI, the coin symbol is the last segment of the coin type
11463
+ // (`<package>::<module>::<TYPE>`), which sanitizeSuiObjectId strips out.
11464
+ // Derive it so callers don't have to pass assetSymbol explicitly.
11465
+ const resolvedAssetSymbol = assetSymbol !== null && assetSymbol !== void 0 ? assetSymbol : (blockchain === BlockchainName.Sui ? extractSuiAssetSymbol(suiObjectId) : undefined);
11352
11466
  const response = await this.request(SystemRoutes.fetchTokenInfo, {
11353
- queryParams: {
11354
- chainName: blockchain,
11355
- tokenContractAddress: validatedContractAddress,
11356
- },
11467
+ queryParams: Object.assign({ chainName: blockchain, tokenContractAddress: validatedContractAddress }, (resolvedAssetSymbol ? { assetSymbol: resolvedAssetSymbol } : {})),
11357
11468
  });
11358
11469
  return response;
11359
11470
  }
@@ -11567,20 +11678,7 @@ class Transactions extends Base {
11567
11678
  try {
11568
11679
  // Only attempt migration if we have password auth and V2 storage might be incomplete
11569
11680
  if (this.deviceAuthType === AuthType.Password && authenticationOptions.password) {
11570
- try {
11571
- await this.walletService.handleUpdateToV2({
11572
- password: authenticationOptions.password,
11573
- walletId: walletId,
11574
- });
11575
- }
11576
- catch (error) {
11577
- logger.error('SDK::Transactions::transfer::handleUpdateToV2::error', error);
11578
- throw new WallabyError({
11579
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
11580
- statusCode: 500,
11581
- errorCode: ErrorResponseCodes.sdk_unknown_error,
11582
- });
11583
- }
11681
+ await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
11584
11682
  }
11585
11683
  const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareTransactionAuth(authenticationOptions, walletId);
11586
11684
  let transferResponse;
@@ -11668,20 +11766,7 @@ class Transactions extends Base {
11668
11766
  }
11669
11767
  // Only attempt migration if we have password auth and V2 storage might be incomplete
11670
11768
  if (this.deviceAuthType === AuthType.Password && authenticationOptions.password) {
11671
- try {
11672
- await this.walletService.handleUpdateToV2({
11673
- password: authenticationOptions.password,
11674
- walletId: walletId,
11675
- });
11676
- }
11677
- catch (error) {
11678
- logger.error('SDK::Transactions::createAllowance::handleUpdateToV2::error', error);
11679
- throw new WallabyError({
11680
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
11681
- statusCode: 500,
11682
- errorCode: ErrorResponseCodes.sdk_unknown_error,
11683
- });
11684
- }
11769
+ await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
11685
11770
  }
11686
11771
  const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareTransactionAuth(authenticationOptions, walletId);
11687
11772
  const { message, signature } = signatureMessage;
@@ -11746,20 +11831,7 @@ class Transactions extends Base {
11746
11831
  try {
11747
11832
  // Only attempt migration if we have password auth and V2 storage might be incomplete
11748
11833
  if (this.deviceAuthType === AuthType.Password && authenticationOptions.password) {
11749
- try {
11750
- await this.walletService.handleUpdateToV2({
11751
- password: authenticationOptions.password,
11752
- walletId: walletId,
11753
- });
11754
- }
11755
- catch (error) {
11756
- logger.error('SDK::Transactions::resolvePendingTransaction::handleUpdateToV2::error', error);
11757
- throw new WallabyError({
11758
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
11759
- statusCode: 500,
11760
- errorCode: ErrorResponseCodes.sdk_unknown_error,
11761
- });
11762
- }
11834
+ await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
11763
11835
  }
11764
11836
  const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareTransactionAuth(authenticationOptions, walletId);
11765
11837
  if (!readyForTransportSeedPhrase && !hasShares) {
@@ -11932,7 +12004,6 @@ class Wallaby {
11932
12004
  this.system = new System(config);
11933
12005
  this.transactions = new Transactions(config);
11934
12006
  this.swap = new Swap(config);
11935
- this.merchants = new Merchants(config);
11936
12007
  this.httpApi = new HttpApi(config);
11937
12008
  }
11938
12009
  get version() {