wallaby-cash 3.2.1 → 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.2.1" ;
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,17 +4427,34 @@ 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 }) {
4430
- const decrypted = AES.decrypt(cipherText, this.getMasterKey().key).toString(enc.Utf8);
4431
- if (decrypted) {
4432
- return isJsonString(decrypted) ? safeJsonParse(decrypted) : decrypted;
4442
+ const ciphertext = cipherText.startsWith(MASTER_KEY_WRAP_PREFIX)
4443
+ ? cipherText.slice(MASTER_KEY_WRAP_PREFIX.length)
4444
+ : cipherText;
4445
+ try {
4446
+ const decrypted = AES.decrypt(ciphertext, this.getMasterKey().key).toString(enc.Utf8);
4447
+ if (decrypted) {
4448
+ return isJsonString(decrypted) ? safeJsonParse(decrypted) : decrypted;
4449
+ }
4433
4450
  }
4434
- else {
4435
- logger.error('Decryption failed with master key');
4451
+ catch (error) {
4452
+ // crypto-js throws "Malformed UTF-8 data" when the ciphertext can't be decrypted
4453
+ logger.error('Decryption failed with master key', error);
4436
4454
  return undefined;
4437
4455
  }
4456
+ logger.error('Decryption failed with master key');
4457
+ return undefined;
4438
4458
  }
4439
4459
  /**
4440
4460
  * Validate that a public key is the correct length and format.
@@ -4541,6 +4561,8 @@ class Cipher {
4541
4561
  }
4542
4562
  derivedKeyPair = await this.deriveKeyPairFromPasskey({ inputKeyMaterial: options.prfValue });
4543
4563
  return derivedKeyPair;
4564
+ default:
4565
+ throw new Error(`Unknown AuthType: ${options.authType}`);
4544
4566
  }
4545
4567
  }
4546
4568
  catch (error) {
@@ -4800,6 +4822,14 @@ class StorageService {
4800
4822
  return;
4801
4823
  }
4802
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
+ })));
4803
4833
  let storageKey;
4804
4834
  if (this._walletSpecificKeys.includes(key)) {
4805
4835
  if (!(options === null || options === void 0 ? void 0 : options.walletId)) {
@@ -4810,7 +4840,7 @@ class StorageService {
4810
4840
  else {
4811
4841
  storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}`;
4812
4842
  }
4813
- if (!isWeb) {
4843
+ if (env.isNative) {
4814
4844
  storageKey = normalizeKey(storageKey);
4815
4845
  }
4816
4846
  const item = await this.getItem(storageKey);
@@ -4819,14 +4849,11 @@ class StorageService {
4819
4849
  return undefined;
4820
4850
  }
4821
4851
  if (this._keysProtectedByMasterKey.includes(key)) {
4822
- let unwrapped;
4823
- // Temp fix to unblock prod issue. Need a more permanent solution.
4824
- try {
4825
- unwrapped = this.cipher.decryptWithMasterKey({ cipherText: item });
4826
- }
4827
- catch (_a) {
4828
- 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;
4829
4855
  }
4856
+ const unwrapped = this.cipher.decryptWithMasterKey({ cipherText: item });
4830
4857
  if (!unwrapped) {
4831
4858
  logger.error(`Failed to decrypt item with key ${storageKey}`);
4832
4859
  return undefined;
@@ -4846,7 +4873,7 @@ class StorageService {
4846
4873
  else {
4847
4874
  storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}`;
4848
4875
  }
4849
- if (!isWeb) {
4876
+ if (env.isNative) {
4850
4877
  storageKey = normalizeKey(storageKey);
4851
4878
  }
4852
4879
  let valueToStore;
@@ -4862,6 +4889,75 @@ class StorageService {
4862
4889
  async saveInBulk(data) {
4863
4890
  await Promise.all(data.map((item) => this.save(item.key, item.value, { walletId: item.walletId })));
4864
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
+ }
4865
4961
  async delete(key, options) {
4866
4962
  let storageKey;
4867
4963
  if (this._walletSpecificKeys.includes(key)) {
@@ -4873,7 +4969,7 @@ class StorageService {
4873
4969
  else {
4874
4970
  storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}`;
4875
4971
  }
4876
- if (!isWeb) {
4972
+ if (env.isNative) {
4877
4973
  storageKey = normalizeKey(storageKey);
4878
4974
  }
4879
4975
  return await this.removeItem(storageKey);
@@ -5138,11 +5234,16 @@ class StorageService {
5138
5234
  LocalStorageItems.AccessToken,
5139
5235
  LocalStorageItems.RefreshToken,
5140
5236
  V2KeyNames.EncryptedDevicePrivateKey,
5237
+ V2KeyNames.ClientAuthPublicKey,
5141
5238
  V2KeyNames.WallabyAuthPubKey,
5142
5239
  V2KeyNames.PasskeyCredential,
5143
5240
  V2KeyNames.MigrationVersion,
5144
5241
  V2KeyNames.LastMigratedAt,
5145
5242
  V2KeyNames.ClientAuthToken,
5243
+ V2KeyNames.PasswordResetAttempts,
5244
+ V2KeyNames.MigrationAttempts,
5245
+ V2KeyNames.CredentialConversionInProgress,
5246
+ V2KeyNames.PendingCommit,
5146
5247
  ];
5147
5248
  await Promise.all(userKeysToRemove.map((key) => this.delete(key)));
5148
5249
  if (walletId) {
@@ -5274,6 +5375,11 @@ const AuthRoutes = {
5274
5375
  method: RequestMethod.Get,
5275
5376
  requiresAccessToken: true,
5276
5377
  },
5378
+ issueJwtToken: {
5379
+ fullPath: '/auth/issue-jwt-token',
5380
+ method: RequestMethod.Post,
5381
+ requiresAccessToken: false,
5382
+ },
5277
5383
  };
5278
5384
 
5279
5385
  class LockManagerService {
@@ -5653,6 +5759,16 @@ class Api {
5653
5759
  * @secure
5654
5760
  */
5655
5761
  signIn: (data, params = {}) => this.http.request(Object.assign({ path: `/api/v1/auth/sign-in`, method: "POST", body: data, secure: true, type: ContentType.Json, format: "json" }, params)),
5762
+ /**
5763
+ * No description
5764
+ *
5765
+ * @tags Auth
5766
+ * @name IssueJwtToken
5767
+ * @summary Issue a Wallaby JWT token for a user using only x-api-key and x-client-jwt headers. Requires mfaVerified and that the user belongs to the API key merchant.
5768
+ * @request POST:/api/v1/auth/issue-jwt-token
5769
+ * @secure
5770
+ */
5771
+ issueJwtToken: (params = {}) => this.http.request(Object.assign({ path: `/api/v1/auth/issue-jwt-token`, method: "POST", secure: true, format: "json" }, params)),
5656
5772
  /**
5657
5773
  * No description
5658
5774
  *
@@ -6151,6 +6267,20 @@ class Api {
6151
6267
  if (params === void 0) { params = {}; }
6152
6268
  return this.http.request(Object.assign({ path: `/api/v1/wallets/${walletId}/assets`, method: "GET", query: query, secure: true, format: "json" }, params));
6153
6269
  },
6270
+ /**
6271
+ * No description
6272
+ *
6273
+ * @tags Wallets
6274
+ * @name GetWalletAddresses
6275
+ * @summary Get all assets that exist in a certain wallet, by specifying a wallet ID
6276
+ * @request GET:/api/v1/wallets/{walletId}/addresses
6277
+ * @secure
6278
+ */
6279
+ getWalletAddresses: (_a, params) => {
6280
+ var { walletId } = _a, query = __rest(_a, ["walletId"]);
6281
+ if (params === void 0) { params = {}; }
6282
+ return this.http.request(Object.assign({ path: `/api/v1/wallets/${walletId}/addresses`, method: "GET", query: query, secure: true, format: "json" }, params));
6283
+ },
6154
6284
  /**
6155
6285
  * No description
6156
6286
  *
@@ -6350,23 +6480,35 @@ class Api {
6350
6480
  /**
6351
6481
  * No description
6352
6482
  *
6353
- * @tags Transactions, Transactions, ERC1404
6483
+ * @tags Transactions, Transactions
6354
6484
  * @name DetectTransferRestriction
6355
6485
  * @summary Request to detect whether there is a transfer restriction on a particular transaction
6356
6486
  * @request GET:/api/v1/transactions/detect-transfers-restrictions
6487
+ * @deprecated
6357
6488
  * @secure
6358
6489
  */
6359
6490
  detectTransferRestriction: (query, params = {}) => this.http.request(Object.assign({ path: `/api/v1/transactions/detect-transfers-restrictions`, method: "GET", query: query, secure: true, format: "json" }, params)),
6360
6491
  /**
6361
6492
  * No description
6362
6493
  *
6363
- * @tags Transactions, Transactions, ERC1404
6494
+ * @tags Transactions, Transactions
6364
6495
  * @name FetchMessageForTransferRestriction
6365
6496
  * @summary Request restriction message by providing a restriction code
6366
6497
  * @request GET:/api/v1/transactions/transfer-restriction-message
6498
+ * @deprecated
6367
6499
  * @secure
6368
6500
  */
6369
6501
  fetchMessageForTransferRestriction: (query, params = {}) => this.http.request(Object.assign({ path: `/api/v1/transactions/transfer-restriction-message`, method: "GET", query: query, secure: true, format: "json" }, params)),
6502
+ /**
6503
+ * No description
6504
+ *
6505
+ * @tags Transactions, Transactions
6506
+ * @name GetRestriction
6507
+ * @summary Request to detect whether there is a transfer restriction on a particular transaction
6508
+ * @request GET:/api/v1/transactions/restriction
6509
+ * @secure
6510
+ */
6511
+ getRestriction: (query, params = {}) => this.http.request(Object.assign({ path: `/api/v1/transactions/restriction`, method: "GET", query: query, secure: true, format: "json" }, params)),
6370
6512
  /**
6371
6513
  * No description
6372
6514
  *
@@ -6845,8 +6987,9 @@ class Base {
6845
6987
  this.userId = sanitizedConfig.userId;
6846
6988
  this.options = sanitizedConfig.options;
6847
6989
  if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.platform) {
6848
- this.options.platform;
6849
- 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;
6850
6993
  }
6851
6994
  this.cipher = new Cipher();
6852
6995
  this.lockManager = new LockManagerService();
@@ -7340,7 +7483,22 @@ const TransactionsRoutes = {
7340
7483
  requiresAccessToken: true,
7341
7484
  },
7342
7485
  getTransactions: {
7343
- fullPath: '/query/transactions',
7486
+ fullPath: '/transactions',
7487
+ method: RequestMethod.Get,
7488
+ requiresAccessToken: true,
7489
+ },
7490
+ detectTransferRestrictions: {
7491
+ fullPath: '/transactions/detect-transfers-restrictions',
7492
+ method: RequestMethod.Get,
7493
+ requiresAccessToken: true,
7494
+ },
7495
+ transferRestrictionMessage: {
7496
+ fullPath: '/transactions/transfer-restriction-message',
7497
+ method: RequestMethod.Get,
7498
+ requiresAccessToken: true,
7499
+ },
7500
+ restriction: {
7501
+ fullPath: '/transactions/restriction',
7344
7502
  method: RequestMethod.Get,
7345
7503
  requiresAccessToken: true,
7346
7504
  },
@@ -7486,6 +7644,17 @@ function normalizeAndPadBase64(s) {
7486
7644
  function decodeBase64String(s) {
7487
7645
  return toUint8Array(normalizeAndPadBase64(s));
7488
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
+ }
7489
7658
  function decodeBase64URL(base64url) {
7490
7659
  const padded = normalizeAndPadBase64(base64url);
7491
7660
  const binary = atob(padded);
@@ -7496,29 +7665,6 @@ function decodeBase64URL(base64url) {
7496
7665
  return bytes;
7497
7666
  }
7498
7667
 
7499
- /**
7500
- * Web: round-trip with uint8ArrayToBase64 (which does btoa(fromUint8Array(bytes, true))).
7501
- * Single decode first; if the result looks like a base64 string, decode again to get original bytes.
7502
- */
7503
- function base64ToUint8Array(base64) {
7504
- try {
7505
- const first = toUint8Array(base64);
7506
- const asStr = String.fromCharCode.apply(null, first);
7507
- if (/^[A-Za-z0-9+/\-_=]*$/.test(asStr) && asStr.length >= 4) {
7508
- try {
7509
- return decodeBase64String(asStr);
7510
- }
7511
- catch (_a) {
7512
- // fall through
7513
- }
7514
- }
7515
- return first;
7516
- }
7517
- catch (_b) {
7518
- return decodeBase64String(base64);
7519
- }
7520
- }
7521
-
7522
7668
  class PasskeyService {
7523
7669
  constructor(userId, storageService, request) {
7524
7670
  this.cipher = new Cipher();
@@ -7821,7 +7967,6 @@ class PasskeyService {
7821
7967
  }
7822
7968
  logger.log('SDK::PasskeyService::register:: getting signature', {
7823
7969
  message: challengeResponse.message,
7824
- privateKey: deviceKeyPair.privateKey,
7825
7970
  });
7826
7971
  const { signature, message } = await this.cipher.sign({
7827
7972
  message: challengeResponse.message,
@@ -8467,7 +8612,7 @@ class AuthService extends Base {
8467
8612
  data: deviceKeyPair.privateKey,
8468
8613
  encryptionKey: credentialsKeyPair.publicKey,
8469
8614
  });
8470
- this.localStorageService.saveInBulk([
8615
+ await this.localStorageService.saveInBulk([
8471
8616
  {
8472
8617
  key: LocalStorageItems.EncryptedDevicePrivateKey,
8473
8618
  value: encryptedDevicePrivKey,
@@ -8538,6 +8683,24 @@ class AuthService extends Base {
8538
8683
  valid: true,
8539
8684
  };
8540
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
+ }
8541
8704
  }
8542
8705
  __decorate([
8543
8706
  WithLock('signUp'),
@@ -8558,6 +8721,63 @@ __decorate([
8558
8721
  __metadata("design:returntype", Promise)
8559
8722
  ], AuthService.prototype, "storeDeviceKeyPair", null);
8560
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
+ }
8561
8781
  class WalletHandlersService extends Base {
8562
8782
  constructor(config) {
8563
8783
  super(config);
@@ -8638,6 +8858,7 @@ class WalletHandlersService extends Base {
8638
8858
  shares: importWalletRequest.shares,
8639
8859
  credentialsKeyPair,
8640
8860
  encryptedBackupShare: importWalletRequest.encryptedBackupShare,
8861
+ devicePrivateKey: deviceAuthKeys.privateKey,
8641
8862
  });
8642
8863
  }
8643
8864
  return Object.assign({}, importWalletRequest);
@@ -8724,6 +8945,7 @@ class WalletHandlersService extends Base {
8724
8945
  shares: walletCreationResponse.shares,
8725
8946
  credentialsKeyPair,
8726
8947
  encryptedBackupShare: walletCreationResponse.encryptedBackupShare,
8948
+ devicePrivateKey: deviceAuthKeys.privateKey,
8727
8949
  });
8728
8950
  }
8729
8951
  return Object.assign(Object.assign({}, walletCreationResponse), { standardSeedPhrase: decryptedSeedPhrase });
@@ -8739,8 +8961,41 @@ class WalletHandlersService extends Base {
8739
8961
  });
8740
8962
  }
8741
8963
  }
8742
- 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, }) {
8743
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
+ }
8744
8999
  const encryptedWithCredentialsKeyShare = await this.cipher.encrypt({
8745
9000
  data: JSON.stringify(shares[0].encrypted),
8746
9001
  encryptionKey: credentialsKeyPair.publicKey,
@@ -8834,13 +9089,42 @@ class WalletHandlersService extends Base {
8834
9089
  class WalletService extends Base {
8835
9090
  constructor(config) {
8836
9091
  super(config);
8837
- this.passwordResetAttempts = 0;
8838
- this.migrationAttempts = 0;
8839
9092
  this.authService = new AuthService(config);
8840
9093
  this.handlers = new WalletHandlersService(config);
8841
9094
  this.userId = config.userId;
8842
9095
  this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request);
8843
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
+ }
8844
9128
  /**
8845
9129
  * @public
8846
9130
  * @returns {boolean} Returns true if the device has a seed phrase.
@@ -8946,20 +9230,7 @@ class WalletService extends Base {
8946
9230
  });
8947
9231
  }
8948
9232
  if (this.deviceAuthType === AuthType.Password && authenticationOptions.password) {
8949
- try {
8950
- await this.handleUpdateToV2({
8951
- password: authenticationOptions.password,
8952
- walletId: walletId,
8953
- });
8954
- }
8955
- catch (error) {
8956
- logger.error('SDK::WalletService::export::handleUpdateToV2::error', error);
8957
- throw new WallabyError({
8958
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
8959
- statusCode: 500,
8960
- errorCode: ErrorResponseCodes.sdk_unknown_error,
8961
- });
8962
- }
9233
+ await this.migrateToV2Safe({ password: authenticationOptions.password, walletId });
8963
9234
  }
8964
9235
  const encryptedSeed = await this.localStorageService.fetch(LocalStorageItems.EncryptedStandardSeedPhrase, { walletId });
8965
9236
  const encryptedPrimaryDeviceShare = await this.localStorageService.fetch(LocalStorageItems.PrimaryDeviceKeyShare, {
@@ -9202,6 +9473,7 @@ class WalletService extends Base {
9202
9473
  shares: recoverWithSeedPhraseResponse.shares,
9203
9474
  credentialsKeyPair,
9204
9475
  encryptedBackupShare: recoverWithSeedPhraseResponse.encryptedBackupShare,
9476
+ devicePrivateKey: deviceAuthKeyPair.privateKey,
9205
9477
  });
9206
9478
  }
9207
9479
  await this.authService.storeDeviceKeyPair({
@@ -9265,6 +9537,7 @@ class WalletService extends Base {
9265
9537
  shares: recoverWithSeedPhraseResponse.shares,
9266
9538
  credentialsKeyPair,
9267
9539
  encryptedBackupShare: recoverWithSeedPhraseResponse.encryptedBackupShare,
9540
+ devicePrivateKey: deviceAuthKeyPair.privateKey,
9268
9541
  });
9269
9542
  }
9270
9543
  await this.authService.storeDeviceKeyPair({
@@ -9297,8 +9570,7 @@ class WalletService extends Base {
9297
9570
  */
9298
9571
  async changePassword({ walletId, oldPassword, newPassword, }) {
9299
9572
  try {
9300
- this.passwordResetAttempts += 1;
9301
- if (this.passwordResetAttempts > 5) {
9573
+ if ((await this.recordRateAttempt(V2KeyNames.PasswordResetAttempts)) > WalletService.RATE_LIMIT_MAX) {
9302
9574
  throw new WallabyError({
9303
9575
  message: 'Too many password change attempts. Please try again later.',
9304
9576
  statusCode: 429,
@@ -9307,20 +9579,7 @@ class WalletService extends Base {
9307
9579
  }
9308
9580
  if (this.deviceAuthType === AuthType.Password && oldPassword) {
9309
9581
  // Handle migration to V2 first then change the password to the new one.
9310
- try {
9311
- await this.handleUpdateToV2({
9312
- password: oldPassword,
9313
- walletId,
9314
- });
9315
- }
9316
- catch (error) {
9317
- logger.error('SDK::WalletService::changePassword::handleUpdateToV2::error', error);
9318
- throw new WallabyError({
9319
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
9320
- statusCode: 500,
9321
- errorCode: ErrorResponseCodes.sdk_unknown_error,
9322
- });
9323
- }
9582
+ await this.migrateToV2Safe({ password: oldPassword, walletId });
9324
9583
  }
9325
9584
  const encryptedDevicePrivateKeyString = await this.localStorageService.fetch(V2KeyNames.EncryptedDevicePrivateKey);
9326
9585
  const encryptedSeedPhraseString = await this.localStorageService.fetch(V2KeyNames.EncryptedStandardSeedPhrase, {
@@ -9354,7 +9613,7 @@ class WalletService extends Base {
9354
9613
  password: newPassword,
9355
9614
  salt: clientSalt,
9356
9615
  });
9357
- if (!newCredentialsKeyPair.publicKey) {
9616
+ if (!newCredentialsKeyPair.publicKey || !newCredentialsKeyPair.privateKey) {
9358
9617
  throw new WallabyError({
9359
9618
  message: 'Could not derive keys for new password.',
9360
9619
  statusCode: 500,
@@ -9366,40 +9625,59 @@ class WalletService extends Base {
9366
9625
  decryptionKey: oldCredentialsKeyPair.privateKey,
9367
9626
  encryptionKey: newCredentialsKeyPair.publicKey,
9368
9627
  });
9369
- await this.localStorageService.save(LocalStorageItems.EncryptedDevicePrivateKey, reWrappedDevicePrivateKey);
9370
- if (encryptedSeedPhraseString) {
9371
- const parsedSeed = safeJsonParse(encryptedSeedPhraseString);
9372
- const reWrappedSeedPhrase = await this.cipher.flipEncryptedData({
9373
- cipherText: parsedSeed,
9374
- decryptionKey: oldCredentialsKeyPair.privateKey,
9375
- encryptionKey: newCredentialsKeyPair.publicKey,
9376
- });
9377
- await this.localStorageService.save(LocalStorageItems.EncryptedStandardSeedPhrase, reWrappedSeedPhrase, {
9378
- walletId,
9628
+ // Guard against persisting an empty/invalid re-wrap, which would lock the user out of
9629
+ // their device private key (the one mandatory item) under the new password. The type says
9630
+ // this is always defined, but we defend against a runtime contract violation regardless.
9631
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
9632
+ if (!reWrappedDevicePrivateKey) {
9633
+ throw new WallabyError({
9634
+ message: 'Failed to re-wrap device private key during password change.',
9635
+ statusCode: 500,
9636
+ errorCode: ErrorResponseCodes.sdk_unknown_error,
9379
9637
  });
9380
9638
  }
9381
- if (encryptedPrimaryShareString) {
9382
- const parsedPrimaryShare = safeJsonParse(encryptedPrimaryShareString);
9383
- const reWrappedPrimaryShare = await this.cipher.flipEncryptedData({
9384
- cipherText: parsedPrimaryShare,
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),
9385
9645
  decryptionKey: oldCredentialsKeyPair.privateKey,
9386
9646
  encryptionKey: newCredentialsKeyPair.publicKey,
9387
- });
9388
- await this.localStorageService.save(LocalStorageItems.PrimaryDeviceKeyShare, reWrappedPrimaryShare, {
9389
- walletId,
9390
- });
9391
- }
9392
- if (encryptedBackupShareString) {
9393
- const parsedBackupShare = safeJsonParse(encryptedBackupShareString);
9394
- const reWrappedBackupShare = await this.cipher.flipEncryptedData({
9395
- cipherText: parsedBackupShare,
9647
+ })
9648
+ : null;
9649
+ const reWrappedPrimaryShare = encryptedPrimaryShareString
9650
+ ? await this.cipher.flipEncryptedData({
9651
+ cipherText: safeJsonParse(encryptedPrimaryShareString),
9396
9652
  decryptionKey: oldCredentialsKeyPair.privateKey,
9397
9653
  encryptionKey: newCredentialsKeyPair.publicKey,
9398
- });
9399
- await this.localStorageService.save(LocalStorageItems.BackupDeviceKeyShare, reWrappedBackupShare, {
9400
- walletId,
9401
- });
9402
- }
9654
+ })
9655
+ : null;
9656
+ const reWrappedBackupShare = encryptedBackupShareString
9657
+ ? await this.cipher.flipEncryptedData({
9658
+ cipherText: safeJsonParse(encryptedBackupShareString),
9659
+ decryptionKey: oldCredentialsKeyPair.privateKey,
9660
+ encryptionKey: newCredentialsKeyPair.publicKey,
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);
9403
9681
  return true;
9404
9682
  }
9405
9683
  catch (error) {
@@ -9452,20 +9730,7 @@ class WalletService extends Base {
9452
9730
  }
9453
9731
  const parsedEncryptedDevicePrivateKey = safeJsonParse(encryptedDevicePrivateKey);
9454
9732
  if (this.deviceAuthType === AuthType.Password && input.authenticationOptions.password) {
9455
- try {
9456
- await this.handleUpdateToV2({
9457
- password: input.authenticationOptions.password,
9458
- walletId: input.walletId,
9459
- });
9460
- }
9461
- catch (error) {
9462
- logger.error('SDK::WalletService::initAddNewDevice::handleUpdateToV2::error', error);
9463
- throw new WallabyError({
9464
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
9465
- statusCode: 500,
9466
- errorCode: ErrorResponseCodes.sdk_unknown_error,
9467
- });
9468
- }
9733
+ await this.migrateToV2Safe({ password: input.authenticationOptions.password, walletId: input.walletId });
9469
9734
  }
9470
9735
  const storedEncryptedBackupShare = await this.localStorageService.fetch(LocalStorageItems.BackupDeviceKeyShare, { walletId });
9471
9736
  if (!storedEncryptedBackupShare) {
@@ -9563,6 +9828,7 @@ class WalletService extends Base {
9563
9828
  shares: [backUpResponse.share],
9564
9829
  credentialsKeyPair,
9565
9830
  encryptedBackupShare: input.encryptedBackupShare,
9831
+ devicePrivateKey: decryptedDevicePrivateKey,
9566
9832
  });
9567
9833
  return { success: true, reference: backUpResponse.reference };
9568
9834
  }
@@ -9581,20 +9847,7 @@ class WalletService extends Base {
9581
9847
  });
9582
9848
  }
9583
9849
  if (this.deviceAuthType === AuthType.Password && input.authenticationOptions.password) {
9584
- try {
9585
- await this.handleUpdateToV2({
9586
- password: input.authenticationOptions.password,
9587
- walletId: input.walletId,
9588
- });
9589
- }
9590
- catch (error) {
9591
- logger.error('SDK::WalletService::generateWalletAddresses::handleUpdateToV2::error', error);
9592
- throw new WallabyError({
9593
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
9594
- statusCode: 500,
9595
- errorCode: ErrorResponseCodes.sdk_unknown_error,
9596
- });
9597
- }
9850
+ await this.migrateToV2Safe({ password: input.authenticationOptions.password, walletId: input.walletId });
9598
9851
  }
9599
9852
  try {
9600
9853
  const walletOperationAuth = await this.prepareWalletOperationAuth({
@@ -9619,6 +9872,23 @@ class WalletService extends Base {
9619
9872
  throw error;
9620
9873
  }
9621
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
+ }
9622
9892
  /**
9623
9893
  * Detects and migrates legacy/v1 storage items to v2 format.
9624
9894
  * This function should be called in methods that use password as input when v2 items are missing.
@@ -9627,13 +9897,7 @@ class WalletService extends Base {
9627
9897
  */
9628
9898
  async handleUpdateToV2({ password, walletId }) {
9629
9899
  const migrationStartTime = Date.now();
9630
- if (this.migrationAttempts > 5) {
9631
- throw new WallabyError({
9632
- message: 'Too many migration attempts. Please try again later.',
9633
- statusCode: 429,
9634
- errorCode: ErrorResponseCodes.sdk_too_many_requests,
9635
- });
9636
- }
9900
+ await this.assertUnderRateLimit(V2KeyNames.MigrationAttempts, 'Too many migration attempts. Please try again later.');
9637
9901
  try {
9638
9902
  if (!password) {
9639
9903
  throw new WallabyError({
@@ -9704,7 +9968,7 @@ class WalletService extends Base {
9704
9968
  }
9705
9969
  }
9706
9970
  // Increment counter after V2 validation to avoid counting when migration not needed
9707
- this.migrationAttempts += 1;
9971
+ await this.recordRateAttempt(V2KeyNames.MigrationAttempts);
9708
9972
  let decryptedSeedPhrase;
9709
9973
  let decryptedPrivateKey;
9710
9974
  // Check for legacy format: `{item}_{userId}`
@@ -9757,7 +10021,10 @@ class WalletService extends Base {
9757
10021
  try {
9758
10022
  // Decrypt V1 items using storage service method (handles double encryption)
9759
10023
  logger.log('Attempting to decrypt V1 items during migration...');
9760
- 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
+ });
9761
10028
  decryptedSeedPhrase = await this.localStorageService.getV1DecryptedSeedPhrase(password, clientSalt);
9762
10029
  // For V1 format, private key is encrypted with just the password (not salt+password like legacy)
9763
10030
  decryptedPrivateKey = await this.localStorageService.getDecryptedV1PrivateKey(password);
@@ -9984,7 +10251,28 @@ class WalletService extends Base {
9984
10251
  * @returns { boolean } whether the operation was successful
9985
10252
  */
9986
10253
  async convertToPasskey(input) {
10254
+ let passkeyRegistered = false;
9987
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
+ }
9988
10276
  const v2EncryptedPriv = await this.localStorageService.fetch(LocalStorageItems.EncryptedDevicePrivateKey);
9989
10277
  const v2EncryptedSeed = await this.localStorageService.fetch(LocalStorageItems.EncryptedStandardSeedPhrase, {
9990
10278
  walletId: input.walletId,
@@ -10033,6 +10321,10 @@ class WalletService extends Base {
10033
10321
  });
10034
10322
  }
10035
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 } : {})));
10036
10328
  const authentication = await this.passkeyService.addNewPasskey({
10037
10329
  deviceKeyPair: {
10038
10330
  publicKey: clientPublicKey,
@@ -10040,6 +10332,7 @@ class WalletService extends Base {
10040
10332
  },
10041
10333
  getSignature: this.authService.getSignature.bind(this),
10042
10334
  });
10335
+ passkeyRegistered = true;
10043
10336
  const prfValue = authentication.prfValue;
10044
10337
  if (!prfValue || !(prfValue instanceof Uint8Array) || prfValue.length === 0) {
10045
10338
  logger.error('SDK::WalletService::convertToPasskey::prfValue is required and must be a non-empty Uint8Array');
@@ -10136,8 +10429,13 @@ class WalletService extends Base {
10136
10429
  storeOneKeyShareWithWallaby: true,
10137
10430
  },
10138
10431
  });
10139
- // Delete the old password-encrypted seed phrase since import stored the new passkey-encrypted version
10140
- 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
+ ]);
10141
10439
  logger.info('SDK::WalletService::convertToPasskey::Wallet imported and converted successfully, old seed phrase removed');
10142
10440
  return { authentication, seedPhrase: decryptedSeedPhrase };
10143
10441
  }
@@ -10155,6 +10453,24 @@ class WalletService extends Base {
10155
10453
  privateKey: decryptedClientAuthPrivKey,
10156
10454
  },
10157
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
+ }
10158
10474
  convertedShares.push({
10159
10475
  key: V2KeyNames.PrimaryDeviceKeyShare,
10160
10476
  value: encryptedPrimaryShare,
@@ -10173,9 +10489,16 @@ class WalletService extends Base {
10173
10489
  walletId: input.walletId,
10174
10490
  });
10175
10491
  }
10176
- 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
+ ]);
10177
10501
  if (v2EncryptedSeed) {
10178
- await this.localStorageService.delete(LocalStorageItems.EncryptedStandardSeedPhrase, { walletId: input.walletId });
10179
10502
  logger.info('SDK::WalletService::convertToPasskey::Seed phrase removed from device storage after conversion to passkey');
10180
10503
  }
10181
10504
  if (!decryptedSeedPhrase && decryptedPrimaryShare) {
@@ -10218,10 +10541,33 @@ class WalletService extends Base {
10218
10541
  }
10219
10542
  catch (error) {
10220
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
+ }
10221
10549
  throw error;
10222
10550
  }
10223
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
+ }
10224
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
10225
10571
  __decorate([
10226
10572
  WithLock('create'),
10227
10573
  __metadata("design:type", Function),
@@ -10241,7 +10587,7 @@ __decorate([
10241
10587
  __metadata("design:returntype", Promise)
10242
10588
  ], WalletService.prototype, "recover", null);
10243
10589
  __decorate([
10244
- WithLock('changePassword'),
10590
+ WithLock('credential-rewrap'),
10245
10591
  __metadata("design:type", Function),
10246
10592
  __metadata("design:paramtypes", [Object]),
10247
10593
  __metadata("design:returntype", Promise)
@@ -10252,6 +10598,12 @@ __decorate([
10252
10598
  __metadata("design:paramtypes", [Object]),
10253
10599
  __metadata("design:returntype", Promise)
10254
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);
10255
10607
 
10256
10608
  class WalletDataService extends Base {
10257
10609
  constructor(config) {
@@ -10504,20 +10856,7 @@ class WalletDataService extends Base {
10504
10856
  });
10505
10857
  }
10506
10858
  if (this.deviceAuthType === AuthType.Password && authenticationOptions.password) {
10507
- try {
10508
- await this.walletService.handleUpdateToV2({
10509
- password: authenticationOptions.password,
10510
- walletId: walletId,
10511
- });
10512
- }
10513
- catch (error) {
10514
- logger.error('SDK::WalletDataService::addNewChainAndTokenToWallet::handleUpdateToV2::error', error);
10515
- throw new WallabyError({
10516
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
10517
- statusCode: 500,
10518
- errorCode: ErrorResponseCodes.sdk_unknown_error,
10519
- });
10520
- }
10859
+ await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
10521
10860
  }
10522
10861
  try {
10523
10862
  const addressInfo = await this.walletService.generateWalletAddresses({
@@ -10718,179 +11057,6 @@ class Utils extends Base {
10718
11057
  }
10719
11058
  }
10720
11059
 
10721
- const MerchantsRoutes = {
10722
- create: {
10723
- fullPath: '/merchants',
10724
- method: RequestMethod.Post,
10725
- requiresAccessToken: false,
10726
- },
10727
- update: {
10728
- fullPath: ({ merchantId }) => `/merchants/${merchantId}`,
10729
- method: RequestMethod.Put,
10730
- requiresAccessToken: false,
10731
- },
10732
- getMerchantData: {
10733
- fullPath: ({ merchantId }) => `/merchants/${merchantId}`,
10734
- method: RequestMethod.Get,
10735
- requiresAccessToken: false,
10736
- },
10737
- list: {
10738
- fullPath: '/merchants',
10739
- method: RequestMethod.Get,
10740
- requiresAccessToken: false,
10741
- },
10742
- getAssets: {
10743
- fullPath: () => `/users/merchant/assets`,
10744
- method: RequestMethod.Get,
10745
- requiresAccessToken: true,
10746
- },
10747
- addAsset: {
10748
- fullPath: ({ merchantId, configId }) => `/merchants/${merchantId}/assets/${configId}`,
10749
- method: RequestMethod.Post,
10750
- requiresAccessToken: false,
10751
- },
10752
- deleteAsset: {
10753
- fullPath: ({ merchantId, configId }) => `/merchants/${merchantId}/assets/${configId}`,
10754
- method: RequestMethod.Delete,
10755
- requiresAccessToken: false,
10756
- },
10757
- };
10758
-
10759
- class Merchants extends Base {
10760
- constructor(config) {
10761
- super(config);
10762
- }
10763
- /**
10764
- * @description
10765
- * Retrieves the merchant ID from access token `aud` claim.
10766
- * Even though merchantId is possibly undefined. If an access token is not stored on device, the request will most likely
10767
- * not have it in headers and will fail with 401 regardless.
10768
- *
10769
- * @returns { string | undefined } Merchant ID
10770
- */
10771
- async _getMerchantId() {
10772
- const accessToken = await this.localStorageService.fetch(LocalStorageItems.AccessToken);
10773
- if (!accessToken)
10774
- return;
10775
- const jwtDecoded = jwtDecode(accessToken);
10776
- return jwtDecoded.aud;
10777
- }
10778
- /**
10779
- *
10780
- * @public
10781
- * List of all merchants in the system
10782
- * @returns { ListMerchantsResponse } Array of all merchants
10783
- */
10784
- async list() {
10785
- try {
10786
- const response = await this.request(MerchantsRoutes.list, {
10787
- payload: {},
10788
- });
10789
- return response;
10790
- }
10791
- catch (error) {
10792
- logger.error('SDK::Merchants::list::error', error);
10793
- return Promise.reject(error);
10794
- }
10795
- }
10796
- /**
10797
- *
10798
- * @public
10799
- * Allows to create a new merchant
10800
- * @returns { Merchant } Merchant data
10801
- */
10802
- async create({ name }) {
10803
- try {
10804
- const response = await this.request(MerchantsRoutes.create, {
10805
- payload: { name },
10806
- });
10807
- return response;
10808
- }
10809
- catch (error) {
10810
- logger.error('SDK::Merchants::list::error', error);
10811
- return Promise.reject(error);
10812
- }
10813
- }
10814
- /**
10815
- *
10816
- * @public
10817
- * Allows to update merchant data
10818
- * @returns { Merchant } Merchant data
10819
- */
10820
- async update({ name, status }) {
10821
- try {
10822
- const merchantId = await this._getMerchantId();
10823
- const response = await this.request(MerchantsRoutes.update, {
10824
- payload: { merchantId, name, status },
10825
- });
10826
- return response;
10827
- }
10828
- catch (error) {
10829
- logger.error('SDK::Merchants::list::error', error);
10830
- return Promise.reject(error);
10831
- }
10832
- }
10833
- /**
10834
- *
10835
- * @public
10836
- * @returns { Merchant } Merchant data
10837
- */
10838
- async getMerchantData() {
10839
- try {
10840
- const merchantId = await this._getMerchantId();
10841
- const response = await this.request(MerchantsRoutes.getMerchantData, {
10842
- payload: { merchantId },
10843
- });
10844
- return response.merchant;
10845
- }
10846
- catch (error) {
10847
- logger.error('SDK::Merchants::list::error', error);
10848
- return Promise.reject(error);
10849
- }
10850
- }
10851
- /**
10852
- *
10853
- * @public
10854
- * @returns { MerchantAsset[] } List of merchant assets
10855
- */
10856
- async getAssets() {
10857
- try {
10858
- const response = await this.request(MerchantsRoutes.getAssets);
10859
- return response.merchantAssets;
10860
- }
10861
- catch (error) {
10862
- logger.error('SDK::Merchants::list::error', error);
10863
- return Promise.reject(error);
10864
- }
10865
- }
10866
- async addAsset({ configId }) {
10867
- try {
10868
- const merchantId = await this._getMerchantId();
10869
- const response = await this.request(MerchantsRoutes.addAsset, {
10870
- payload: { merchantId, configId },
10871
- });
10872
- return response;
10873
- }
10874
- catch (error) {
10875
- logger.error('SDK::Merchants::list::error', error);
10876
- return Promise.reject(error);
10877
- }
10878
- }
10879
- async deleteAsset({ configId }) {
10880
- try {
10881
- const merchantId = await this._getMerchantId();
10882
- const response = await this.request(MerchantsRoutes.deleteAsset, {
10883
- payload: { merchantId, configId },
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
11060
  /**
10895
11061
  * HttpApi provides direct access to all REST API endpoints.
10896
11062
  * This class extends the Base class and includes the generated API client
@@ -10971,20 +11137,7 @@ class Swap extends Base {
10971
11137
  try {
10972
11138
  // Only attempt migration if we have password auth and V2 storage might be incomplete
10973
11139
  if (this.deviceAuthType === AuthType.Password && authenticationOptions.password) {
10974
- try {
10975
- await this.walletService.handleUpdateToV2({
10976
- password: authenticationOptions.password,
10977
- walletId: walletId,
10978
- });
10979
- }
10980
- catch (error) {
10981
- logger.error('SDK::Swap::executeSwap::handleUpdateToV2::error', error);
10982
- throw new WallabyError({
10983
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
10984
- statusCode: 500,
10985
- errorCode: ErrorResponseCodes.sdk_unknown_error,
10986
- });
10987
- }
11140
+ await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
10988
11141
  }
10989
11142
  const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareSwapAuth(authenticationOptions, walletId);
10990
11143
  let swapResponse;
@@ -11013,6 +11166,7 @@ class Swap extends Base {
11013
11166
  });
11014
11167
  }
11015
11168
  else {
11169
+ // Unreachable in practice: prepareSwapAuth throws sdk_seed_phrase_not_found before we get here; kept as a defensive guard.
11016
11170
  throw new WallabyError({
11017
11171
  message: 'No valid seed option found on this device.',
11018
11172
  statusCode: 400,
@@ -11178,6 +11332,27 @@ const sanitizeSuiObjectId = (objectId) => {
11178
11332
  return objectId.split('::')[0];
11179
11333
  };
11180
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
+
11181
11356
  class System extends Base {
11182
11357
  constructor(config) {
11183
11358
  super(config);
@@ -11266,6 +11441,9 @@ class System extends Base {
11266
11441
  * @param {BlockchainName} blockchain - The name of the blockchain.
11267
11442
  * @param {string} contractAddress - The contract address of the token (optional for non-SUI blockchains).
11268
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).
11269
11447
  *
11270
11448
  * @returns {Promise<{ decimals: number; symbol: string; name: string; tokenContractAddress: string }>} A promise that resolves to an object containing token information.
11271
11449
  *
@@ -11274,18 +11452,19 @@ class System extends Base {
11274
11452
  * @throws Will throw an error if `contractAddress` is not provided for non-SUI blockchains.
11275
11453
  * @throws Will throw an error if the response is invalid or contains an error.
11276
11454
  */
11277
- async fetchTokenInfo({ blockchain, contractAddress, suiObjectId, }) {
11455
+ async fetchTokenInfo({ blockchain, contractAddress, suiObjectId, assetSymbol, }) {
11278
11456
  try {
11279
11457
  const validatedContractAddress = this.validateContractAddress({
11280
11458
  blockchain,
11281
11459
  contractAddress,
11282
11460
  suiObjectId,
11283
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);
11284
11466
  const response = await this.request(SystemRoutes.fetchTokenInfo, {
11285
- queryParams: {
11286
- chainName: blockchain,
11287
- tokenContractAddress: validatedContractAddress,
11288
- },
11467
+ queryParams: Object.assign({ chainName: blockchain, tokenContractAddress: validatedContractAddress }, (resolvedAssetSymbol ? { assetSymbol: resolvedAssetSymbol } : {})),
11289
11468
  });
11290
11469
  return response;
11291
11470
  }
@@ -11434,27 +11613,54 @@ class Transactions extends Base {
11434
11613
  /**
11435
11614
  *
11436
11615
  * @public
11437
- * @param {string} address
11438
- * @param {string} symbol
11439
- * @param {TokenStandard} tokenStandard an optional param used when dealing with non native assets
11440
- * @returns {Promise<{ address: string; transactions: Transaction[] }>}
11616
+ * @param {GetTransactionsParams} params - Query parameters for filtering and paginating transactions
11617
+ * @returns {GetTransactionsResponseDto} Paginated list of transactions matching the given criteria
11441
11618
  */
11442
- async getTransactions({ address, symbol, tokenStandard, }) {
11619
+ async getTransactions(params) {
11443
11620
  try {
11444
- const response = await this.request(TransactionsRoutes.getTransactions, {
11445
- payload: {
11446
- address,
11447
- tokenSymbol: symbol,
11448
- tokenType: tokenStandard,
11449
- },
11621
+ return await this.request(TransactionsRoutes.getTransactions, {
11622
+ queryParams: params,
11450
11623
  });
11451
- return response;
11452
11624
  }
11453
11625
  catch (error) {
11454
11626
  logger.error('SDK::Transactions::getTransactions::error', error);
11455
11627
  throw error;
11456
11628
  }
11457
11629
  }
11630
+ /**
11631
+ *
11632
+ * @public
11633
+ * @param {GetRestrictionParams} params - Parameters to detect transfer restrictions (addresses, asset, value)
11634
+ * - {string} fromAddress
11635
+ * - {string} toAddress
11636
+ * - {string} amount
11637
+ * - [string] assetId
11638
+ * - [string] contractAddress
11639
+ * - [BlockchainName] blockchainName
11640
+ * @returns {Promise<DetectRestrictionResponseDto>}
11641
+ * Detection result; when transfer is blocked, also includes the human-readable restriction message and a boolean canTransfer
11642
+ */
11643
+ async getRestriction(params) {
11644
+ try {
11645
+ const hasAssetId = Boolean(params.assetId);
11646
+ const hasContractAndChain = Boolean(params.contractAddress && params.blockchainName);
11647
+ if (!hasAssetId && !hasContractAndChain) {
11648
+ throw new WallabyError({
11649
+ message: 'Either assetId or both contractAddress and blockchainName must be provided.',
11650
+ statusCode: 400,
11651
+ errorCode: ErrorResponseCodes.sdk_missing_parameter,
11652
+ });
11653
+ }
11654
+ const restrictionData = await this.request(TransactionsRoutes.restriction, {
11655
+ queryParams: Object.assign(Object.assign(Object.assign({ fromAddress: params.fromAddress, toAddress: params.toAddress, amount: params.amount }, (params.assetId && { assetId: params.assetId })), (params.contractAddress && { contractAddress: params.contractAddress })), (params.blockchainName && { blockchainName: params.blockchainName })),
11656
+ });
11657
+ return restrictionData;
11658
+ }
11659
+ catch (error) {
11660
+ logger.error('SDK::Transactions::getRestriction::error', error);
11661
+ throw error;
11662
+ }
11663
+ }
11458
11664
  /**
11459
11665
  *
11460
11666
  * @public
@@ -11472,20 +11678,7 @@ class Transactions extends Base {
11472
11678
  try {
11473
11679
  // Only attempt migration if we have password auth and V2 storage might be incomplete
11474
11680
  if (this.deviceAuthType === AuthType.Password && authenticationOptions.password) {
11475
- try {
11476
- await this.walletService.handleUpdateToV2({
11477
- password: authenticationOptions.password,
11478
- walletId: walletId,
11479
- });
11480
- }
11481
- catch (error) {
11482
- logger.error('SDK::Transactions::transfer::handleUpdateToV2::error', error);
11483
- throw new WallabyError({
11484
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
11485
- statusCode: 500,
11486
- errorCode: ErrorResponseCodes.sdk_unknown_error,
11487
- });
11488
- }
11681
+ await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
11489
11682
  }
11490
11683
  const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareTransactionAuth(authenticationOptions, walletId);
11491
11684
  let transferResponse;
@@ -11573,20 +11766,7 @@ class Transactions extends Base {
11573
11766
  }
11574
11767
  // Only attempt migration if we have password auth and V2 storage might be incomplete
11575
11768
  if (this.deviceAuthType === AuthType.Password && authenticationOptions.password) {
11576
- try {
11577
- await this.walletService.handleUpdateToV2({
11578
- password: authenticationOptions.password,
11579
- walletId: walletId,
11580
- });
11581
- }
11582
- catch (error) {
11583
- logger.error('SDK::Transactions::createAllowance::handleUpdateToV2::error', error);
11584
- throw new WallabyError({
11585
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
11586
- statusCode: 500,
11587
- errorCode: ErrorResponseCodes.sdk_unknown_error,
11588
- });
11589
- }
11769
+ await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
11590
11770
  }
11591
11771
  const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareTransactionAuth(authenticationOptions, walletId);
11592
11772
  const { message, signature } = signatureMessage;
@@ -11651,20 +11831,7 @@ class Transactions extends Base {
11651
11831
  try {
11652
11832
  // Only attempt migration if we have password auth and V2 storage might be incomplete
11653
11833
  if (this.deviceAuthType === AuthType.Password && authenticationOptions.password) {
11654
- try {
11655
- await this.walletService.handleUpdateToV2({
11656
- password: authenticationOptions.password,
11657
- walletId: walletId,
11658
- });
11659
- }
11660
- catch (error) {
11661
- logger.error('SDK::Transactions::resolvePendingTransaction::handleUpdateToV2::error', error);
11662
- throw new WallabyError({
11663
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
11664
- statusCode: 500,
11665
- errorCode: ErrorResponseCodes.sdk_unknown_error,
11666
- });
11667
- }
11834
+ await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
11668
11835
  }
11669
11836
  const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareTransactionAuth(authenticationOptions, walletId);
11670
11837
  if (!readyForTransportSeedPhrase && !hasShares) {
@@ -11789,6 +11956,12 @@ class Transactions extends Base {
11789
11956
  });
11790
11957
  }
11791
11958
  }
11959
+ __decorate([
11960
+ WithLock('transaction-restriction-message'),
11961
+ __metadata("design:type", Function),
11962
+ __metadata("design:paramtypes", [Object]),
11963
+ __metadata("design:returntype", Promise)
11964
+ ], Transactions.prototype, "getRestriction", null);
11792
11965
  __decorate([
11793
11966
  WithLock('transfer'),
11794
11967
  __metadata("design:type", Function),
@@ -11831,7 +12004,6 @@ class Wallaby {
11831
12004
  this.system = new System(config);
11832
12005
  this.transactions = new Transactions(config);
11833
12006
  this.swap = new Swap(config);
11834
- this.merchants = new Merchants(config);
11835
12007
  this.httpApi = new HttpApi(config);
11836
12008
  }
11837
12009
  get version() {