wallaby-cash 3.3.0 → 3.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -342,6 +342,8 @@ exports.V2KeyNames = void 0;
342
342
  V2KeyNames["WallabyAuthPubKey"] = "wallaby-auth-pub-key";
343
343
  V2KeyNames["MigrationVersion"] = "wsdk_migrated_with_version";
344
344
  V2KeyNames["LastMigratedAt"] = "wsdk_last_migrated_at";
345
+ V2KeyNames["PasswordResetAttempts"] = "wsdk_password_reset_attempts";
346
+ V2KeyNames["MigrationAttempts"] = "wsdk_migration_attempts";
345
347
  })(exports.V2KeyNames || (exports.V2KeyNames = {}));
346
348
 
347
349
  exports.ErrorResponseCodes = void 0;
@@ -572,7 +574,7 @@ const global$1 = (typeof global !== "undefined" ? global :
572
574
  typeof self !== "undefined" ? self :
573
575
  typeof window !== "undefined" ? window : {});
574
576
 
575
- var env = {};
577
+ var env$1 = {};
576
578
 
577
579
  // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js
578
580
  var performance = global$1.performance || {};
@@ -584,7 +586,7 @@ performance.now ||
584
586
  function(){ return (new Date()).getTime() };
585
587
 
586
588
  var browser$1 = {
587
- env: env};
589
+ env: env$1};
588
590
 
589
591
  var _a;
590
592
  /**
@@ -597,7 +599,6 @@ const defaultEnvironment = (_a = browser$1.env.NODE_ENV) !== null && _a !== void
597
599
  * Please pass the network value in the WallabyConfigOptions object to override it for production-mainnet.
598
600
  */
599
601
  const defaultNetwork = 'testnet';
600
- const isTest = browser$1.env.NODE_ENV === 'test';
601
602
  const DEFAULT_ENTROPY_BYTES$1 = 32;
602
603
  const PBKDF2_ITERATIONS = 131072;
603
604
  const DEFAULT_HOSTNAME = 'https://www.republic.com';
@@ -618,6 +619,11 @@ const MASTER_ENCRYPTION_KEY = '9fa9d3f3c77c20d3a50a08e5299644be29f6e6206ef3479fe
618
619
  { type: 'public-key', alg: exports.PublicKeyCredentialAlgorithm.ES256 },
619
620
  ];
620
621
  const isWeb = typeof window !== 'undefined' && typeof document !== 'undefined';
622
+ const env = {
623
+ platform: 'web',
624
+ isNative: !isWeb,
625
+ isWeb,
626
+ };
621
627
  const currentPackageVersion = "3.3.0" ;
622
628
 
623
629
  /**
@@ -3519,7 +3525,6 @@ const keccak256$1 = (() => {
3519
3525
  })();
3520
3526
 
3521
3527
  const DEFAULT_ENTROPY_BYTES = 32;
3522
- const MINIMUM_SHANNON_ENTROPY = 4;
3523
3528
  /**
3524
3529
  * creates a new private key
3525
3530
  * @param { Uint8Array } entropy - optional entropy to create the private key
@@ -3530,25 +3535,15 @@ const createPrivateKey = (entropy) => {
3530
3535
  if (!(entropy instanceof Uint8Array) || entropy.length < DEFAULT_ENTROPY_BYTES) {
3531
3536
  throw new Error(`entropy must be a Uint8Array of at least ${DEFAULT_ENTROPY_BYTES} bytes`);
3532
3537
  }
3533
- // Check byte diversity
3538
+ // Check byte diversity. This catches genuinely broken inputs (all-zeros, all-same-byte)
3539
+ // without false-positiving on 32-byte KDF output (~30 unique bytes expected).
3540
+ // ponytail: the sampled Shannon-entropy check was removed (WAL-1465) — it's unsound for
3541
+ // 32 samples (max measurable = log2(32) ≈ 5 bits/byte vs a 4-bit threshold), so deterministic
3542
+ // KDF output could be rejected, permanently locking the user out.
3534
3543
  const uniqueBytes = new Set(entropy);
3535
3544
  if (uniqueBytes.size < Math.min(8, entropy.length / 4)) {
3536
3545
  throw new Error(`entropy is too repetitive (only ${uniqueBytes.size} unique byte values)`);
3537
3546
  }
3538
- // Estimate Shannon entropy
3539
- const byteCounts = new Uint32Array(256);
3540
- entropy.forEach((b) => byteCounts[b]++);
3541
- const total = entropy.length;
3542
- let shannonEntropy = 0;
3543
- for (let i = 0; i < 256; i++) {
3544
- if (byteCounts[i] > 0) {
3545
- const p = byteCounts[i] / total;
3546
- shannonEntropy -= p * Math.log2(p);
3547
- }
3548
- }
3549
- if (shannonEntropy < MINIMUM_SHANNON_ENTROPY) {
3550
- throw new Error(`entropy has low Shannon entropy (${shannonEntropy.toFixed(2)} bits/byte)`);
3551
- }
3552
3547
  const outerHex = keccak256$1(entropy);
3553
3548
  return addLeading0x(bytesToHex$1(outerHex));
3554
3549
  }
@@ -4423,6 +4418,11 @@ function pbkdf2Sync(password, salt, iterations, keylen, digest) {
4423
4418
  });
4424
4419
  }
4425
4420
 
4421
+ // Version marker prepended to values wrapped by the master key, so wrapped vs raw is deterministic.
4422
+ const MASTER_KEY_WRAP_PREFIX = 'wsdkmk:v1:';
4423
+ // crypto-js AES.encrypt with a string passphrase emits an OpenSSL "Salted__" header; its base64 always
4424
+ // starts with this. Used to recognize legacy wrapped values stored before MASTER_KEY_WRAP_PREFIX existed.
4425
+ const LEGACY_CRYPTOJS_PREFIX = 'U2FsdGVkX1';
4426
4426
  class Cipher {
4427
4427
  constructor() { }
4428
4428
  /**
@@ -4453,11 +4453,23 @@ class Cipher {
4453
4453
  * @returns The encrypted data as a string.
4454
4454
  */
4455
4455
  encryptWithMasterKey({ data }) {
4456
- return cryptoJs.AES.encrypt(typeof data === 'string' ? data : JSON.stringify(data), this.getMasterKey().key).toString();
4456
+ const ciphertext = cryptoJs.AES.encrypt(typeof data === 'string' ? data : JSON.stringify(data), this.getMasterKey().key).toString();
4457
+ return MASTER_KEY_WRAP_PREFIX + ciphertext;
4458
+ }
4459
+ /**
4460
+ * @description Determines deterministically whether a stored value was wrapped by the master key,
4461
+ * without inferring from decrypt behavior. Returns true for values carrying the version marker, or
4462
+ * legacy crypto-js ciphertext stored before the marker existed. Everything else is treated as raw.
4463
+ */
4464
+ isWrappedByMasterKey(value) {
4465
+ return value.startsWith(MASTER_KEY_WRAP_PREFIX) || value.startsWith(LEGACY_CRYPTOJS_PREFIX);
4457
4466
  }
4458
4467
  decryptWithMasterKey({ cipherText }) {
4468
+ const ciphertext = cipherText.startsWith(MASTER_KEY_WRAP_PREFIX)
4469
+ ? cipherText.slice(MASTER_KEY_WRAP_PREFIX.length)
4470
+ : cipherText;
4459
4471
  try {
4460
- const decrypted = cryptoJs.AES.decrypt(cipherText, this.getMasterKey().key).toString(cryptoJs.enc.Utf8);
4472
+ const decrypted = cryptoJs.AES.decrypt(ciphertext, this.getMasterKey().key).toString(cryptoJs.enc.Utf8);
4461
4473
  if (decrypted) {
4462
4474
  return isJsonString(decrypted) ? safeJsonParse(decrypted) : decrypted;
4463
4475
  }
@@ -4575,6 +4587,8 @@ class Cipher {
4575
4587
  }
4576
4588
  derivedKeyPair = await this.deriveKeyPairFromPasskey({ inputKeyMaterial: options.prfValue });
4577
4589
  return derivedKeyPair;
4590
+ default:
4591
+ throw new Error(`Unknown AuthType: ${options.authType}`);
4578
4592
  }
4579
4593
  }
4580
4594
  catch (error) {
@@ -4844,7 +4858,7 @@ class StorageService {
4844
4858
  else {
4845
4859
  storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}`;
4846
4860
  }
4847
- if (!isWeb) {
4861
+ if (env.isNative) {
4848
4862
  storageKey = normalizeKey(storageKey);
4849
4863
  }
4850
4864
  const item = await this.getItem(storageKey);
@@ -4853,14 +4867,11 @@ class StorageService {
4853
4867
  return undefined;
4854
4868
  }
4855
4869
  if (this._keysProtectedByMasterKey.includes(key)) {
4856
- let unwrapped;
4857
- // Temp fix to unblock prod issue. Need a more permanent solution.
4858
- try {
4859
- unwrapped = this.cipher.decryptWithMasterKey({ cipherText: item });
4860
- }
4861
- catch (_a) {
4862
- unwrapped = item;
4870
+ // Raw legacy value stored before master-key wrapping: return as-is instead of attempting decrypt.
4871
+ if (!this.cipher.isWrappedByMasterKey(item)) {
4872
+ return item;
4863
4873
  }
4874
+ const unwrapped = this.cipher.decryptWithMasterKey({ cipherText: item });
4864
4875
  if (!unwrapped) {
4865
4876
  logger.error(`Failed to decrypt item with key ${storageKey}`);
4866
4877
  return undefined;
@@ -4880,7 +4891,7 @@ class StorageService {
4880
4891
  else {
4881
4892
  storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}`;
4882
4893
  }
4883
- if (!isWeb) {
4894
+ if (env.isNative) {
4884
4895
  storageKey = normalizeKey(storageKey);
4885
4896
  }
4886
4897
  let valueToStore;
@@ -4907,7 +4918,7 @@ class StorageService {
4907
4918
  else {
4908
4919
  storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}`;
4909
4920
  }
4910
- if (!isWeb) {
4921
+ if (env.isNative) {
4911
4922
  storageKey = normalizeKey(storageKey);
4912
4923
  }
4913
4924
  return await this.removeItem(storageKey);
@@ -5172,11 +5183,14 @@ class StorageService {
5172
5183
  exports.LocalStorageItems.AccessToken,
5173
5184
  exports.LocalStorageItems.RefreshToken,
5174
5185
  exports.V2KeyNames.EncryptedDevicePrivateKey,
5186
+ exports.V2KeyNames.ClientAuthPublicKey,
5175
5187
  exports.V2KeyNames.WallabyAuthPubKey,
5176
5188
  exports.V2KeyNames.PasskeyCredential,
5177
5189
  exports.V2KeyNames.MigrationVersion,
5178
5190
  exports.V2KeyNames.LastMigratedAt,
5179
5191
  exports.V2KeyNames.ClientAuthToken,
5192
+ exports.V2KeyNames.PasswordResetAttempts,
5193
+ exports.V2KeyNames.MigrationAttempts,
5180
5194
  ];
5181
5195
  await Promise.all(userKeysToRemove.map((key) => this.delete(key)));
5182
5196
  if (walletId) {
@@ -5223,11 +5237,11 @@ class StorageService {
5223
5237
  * @param jwt - The JWT string to check. If null, the function will return true.
5224
5238
  * @returns `true` if the JWT has expired or is null, otherwise `false`.
5225
5239
  */
5226
- function jwtHasExpired(jwt) {
5240
+ function jwtHasExpired(jwt, now = Date.now) {
5227
5241
  if (!jwt) {
5228
5242
  return true;
5229
5243
  }
5230
- return millisecondsToJWTTimeout(jwt) <= 0;
5244
+ return millisecondsToJWTTimeout(jwt, now) <= 0;
5231
5245
  }
5232
5246
  function jwtHasSameUser(jwt, userId) {
5233
5247
  if (!jwt || !userId) {
@@ -5247,11 +5261,11 @@ function userIsMfaVerified(jwt) {
5247
5261
  * @param thresholdSeconds - Number of seconds before expiry to consider "near expiry".
5248
5262
  * @returns `true` if the JWT expires within `thresholdSeconds` seconds, otherwise `false`.
5249
5263
  */
5250
- function isJwtNearExpiry(jwt, thresholdSeconds) {
5264
+ function isJwtNearExpiry(jwt, thresholdSeconds, now = Date.now) {
5251
5265
  if (!jwt) {
5252
5266
  return false;
5253
5267
  }
5254
- return millisecondsToJWTTimeout(jwt) <= thresholdSeconds * 1000;
5268
+ return millisecondsToJWTTimeout(jwt, now) <= thresholdSeconds * 1000;
5255
5269
  }
5256
5270
  /**
5257
5271
  * Calculates the remaining time in milliseconds until a given JWT expires.
@@ -5259,11 +5273,11 @@ function isJwtNearExpiry(jwt, thresholdSeconds) {
5259
5273
  * @param jwt - The JWT string to decode and check.
5260
5274
  * @returns The number of milliseconds until the JWT expires. If the JWT has already expired, the returned value will be less than or equal to 0.
5261
5275
  */
5262
- function millisecondsToJWTTimeout(jwt) {
5276
+ function millisecondsToJWTTimeout(jwt, now = Date.now) {
5263
5277
  const jwtDecoded = jwtDecode.jwtDecode(jwt);
5264
5278
  const jwtExpirationTimeSeconds = jwtDecoded.exp;
5265
5279
  const jwtExpirationTimeMilliseconds = (jwtExpirationTimeSeconds !== null && jwtExpirationTimeSeconds !== void 0 ? jwtExpirationTimeSeconds : 0) * 1000;
5266
- const timeNowMilliseconds = Date.now();
5280
+ const timeNowMilliseconds = now();
5267
5281
  return jwtExpirationTimeMilliseconds - timeNowMilliseconds;
5268
5282
  }
5269
5283
 
@@ -5308,6 +5322,11 @@ const AuthRoutes = {
5308
5322
  method: exports.RequestMethod.Get,
5309
5323
  requiresAccessToken: true,
5310
5324
  },
5325
+ issueJwtToken: {
5326
+ fullPath: '/auth/issue-jwt-token',
5327
+ method: exports.RequestMethod.Post,
5328
+ requiresAccessToken: false,
5329
+ },
5311
5330
  };
5312
5331
 
5313
5332
  class LockManagerService {
@@ -6907,18 +6926,21 @@ function shouldClearTokensAfterRefreshFailure(error) {
6907
6926
  // Module-level dedupe manager for token refresh to ensure only one refresh request per user/environment/network at a time
6908
6927
  const refreshDedupeManager = new DedupeManagerService();
6909
6928
  class Base {
6910
- constructor(config) {
6911
- var _a, _b;
6929
+ constructor(config, ports = {}) {
6930
+ var _a, _b, _c, _d, _e;
6912
6931
  const sanitizedConfig = sanitizeConfig(config);
6913
6932
  this.apiKey = sanitizedConfig.apiKey;
6914
6933
  this.baseUrl = sanitizedConfig.baseUrl;
6915
6934
  this.userId = sanitizedConfig.userId;
6916
6935
  this.options = sanitizedConfig.options;
6917
6936
  if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.platform) {
6918
- this.options.platform;
6919
- this.options.platform === 'ios' || this.options.platform === 'android';
6937
+ env.platform = this.options.platform;
6938
+ env.isNative = this.options.platform === 'ios' || this.options.platform === 'android';
6939
+ env.isWeb = !env.isNative;
6920
6940
  }
6921
- this.cipher = new Cipher();
6941
+ this.cipher = (_b = ports.cipher) !== null && _b !== void 0 ? _b : new Cipher();
6942
+ this.transport = (_c = ports.transport) !== null && _c !== void 0 ? _c : ((...args) => fetch(...args));
6943
+ this.clock = (_d = ports.clock) !== null && _d !== void 0 ? _d : { now: () => Date.now() };
6922
6944
  this.lockManager = new LockManagerService();
6923
6945
  this._initializeClientAuthToken(sanitizedConfig.clientAuthToken);
6924
6946
  this.request = this.request.bind(this);
@@ -6932,6 +6954,7 @@ class Base {
6932
6954
  secure: true, // Enable security worker for all requests by default
6933
6955
  },
6934
6956
  securityWorker: this.securityWorker.bind(this),
6957
+ customFetch: this.transport,
6935
6958
  });
6936
6959
  /**
6937
6960
  * This intercepts all API responses and transforms errors into WallabyError format.
@@ -6976,7 +6999,7 @@ class Base {
6976
6999
  return attemptRequest(false);
6977
7000
  };
6978
7001
  this.api = new Api(httpClient);
6979
- this.api.http.setSecurityData(Object.assign({ 'x-api-key': config.apiKey, 'x-client-jwt': config.clientAuthToken }, (_b = this.options) === null || _b === void 0 ? void 0 : _b.headers));
7002
+ this.api.http.setSecurityData(Object.assign({ 'x-api-key': config.apiKey, 'x-client-jwt': config.clientAuthToken }, (_e = this.options) === null || _e === void 0 ? void 0 : _e.headers));
6980
7003
  }
6981
7004
  set setClientAuthToken(token) {
6982
7005
  this._initializeClientAuthToken(token);
@@ -7095,7 +7118,7 @@ class Base {
7095
7118
  // Proactive token refresh: if access token is near expiry, refresh before making the request
7096
7119
  if (route !== AuthRoutes.refreshAccessToken && !retried) {
7097
7120
  const accessToken = await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken);
7098
- if (accessToken && isJwtNearExpiry(accessToken, 60)) {
7121
+ if (accessToken && isJwtNearExpiry(accessToken, 60, this.clock.now)) {
7099
7122
  await this._performTokenRefresh();
7100
7123
  }
7101
7124
  }
@@ -7119,7 +7142,7 @@ class Base {
7119
7142
  fetchOptions.body = JSON.stringify(options.payload);
7120
7143
  }
7121
7144
  logger.debug(`SDK::Base::${route.method}::Request`, { path: fullUrl, payload: options === null || options === void 0 ? void 0 : options.payload });
7122
- const response = await fetch(fullUrl, fetchOptions);
7145
+ const response = await this.transport(fullUrl, fetchOptions);
7123
7146
  const contentType = response.headers.get('content-type');
7124
7147
  let data;
7125
7148
  if (contentType === null || contentType === void 0 ? void 0 : contentType.includes('application/json')) {
@@ -7190,7 +7213,7 @@ class Base {
7190
7213
  }
7191
7214
  async _getRequestHeaders() {
7192
7215
  const accessToken = await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken);
7193
- if (!isTest && jwtHasExpired(this.clientAuthToken)) {
7216
+ if (jwtHasExpired(this.clientAuthToken, this.clock.now)) {
7194
7217
  throw new WallabyError({
7195
7218
  message: 'Auth token has expired',
7196
7219
  statusCode: 401,
@@ -7212,7 +7235,7 @@ class Base {
7212
7235
  // Proactive token refresh before building headers for the generated client
7213
7236
  try {
7214
7237
  const accessToken = await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken);
7215
- if (accessToken && isJwtNearExpiry(accessToken, 60)) {
7238
+ if (accessToken && isJwtNearExpiry(accessToken, 60, this.clock.now)) {
7216
7239
  await this._performTokenRefresh();
7217
7240
  }
7218
7241
  }
@@ -7571,6 +7594,17 @@ function normalizeAndPadBase64(s) {
7571
7594
  function decodeBase64String(s) {
7572
7595
  return jsBase64.toUint8Array(normalizeAndPadBase64(s));
7573
7596
  }
7597
+ /**
7598
+ * Single-decode only: decode base64 (or base64url) to bytes. No round-trip double-decode.
7599
+ */
7600
+ function base64ToUint8Array(base64) {
7601
+ try {
7602
+ return jsBase64.toUint8Array(base64);
7603
+ }
7604
+ catch (_a) {
7605
+ return decodeBase64String(base64);
7606
+ }
7607
+ }
7574
7608
  function decodeBase64URL(base64url) {
7575
7609
  const padded = normalizeAndPadBase64(base64url);
7576
7610
  const binary = jsBase64.atob(padded);
@@ -7581,32 +7615,9 @@ function decodeBase64URL(base64url) {
7581
7615
  return bytes;
7582
7616
  }
7583
7617
 
7584
- /**
7585
- * Web: round-trip with uint8ArrayToBase64 (which does btoa(fromUint8Array(bytes, true))).
7586
- * Single decode first; if the result looks like a base64 string, decode again to get original bytes.
7587
- */
7588
- function base64ToUint8Array(base64) {
7589
- try {
7590
- const first = jsBase64.toUint8Array(base64);
7591
- const asStr = String.fromCharCode.apply(null, first);
7592
- if (/^[A-Za-z0-9+/\-_=]*$/.test(asStr) && asStr.length >= 4) {
7593
- try {
7594
- return decodeBase64String(asStr);
7595
- }
7596
- catch (_a) {
7597
- // fall through
7598
- }
7599
- }
7600
- return first;
7601
- }
7602
- catch (_b) {
7603
- return decodeBase64String(base64);
7604
- }
7605
- }
7606
-
7607
7618
  class PasskeyService {
7608
- constructor(userId, storageService, request) {
7609
- this.cipher = new Cipher();
7619
+ constructor(userId, storageService, request, cipher = new Cipher()) {
7620
+ this.cipher = cipher;
7610
7621
  this.localStorageService = storageService;
7611
7622
  this.userId = userId;
7612
7623
  this.request = request;
@@ -7906,7 +7917,6 @@ class PasskeyService {
7906
7917
  }
7907
7918
  logger.log('SDK::PasskeyService::register:: getting signature', {
7908
7919
  message: challengeResponse.message,
7909
- privateKey: deviceKeyPair.privateKey,
7910
7920
  });
7911
7921
  const { signature, message } = await this.cipher.sign({
7912
7922
  message: challengeResponse.message,
@@ -8129,10 +8139,10 @@ function WithLock(lockKey) {
8129
8139
  }
8130
8140
 
8131
8141
  class AuthService extends Base {
8132
- constructor(config) {
8133
- super(config);
8142
+ constructor(config, ports = {}) {
8143
+ super(config, ports);
8134
8144
  this.getUserSalt = this.getUserSalt.bind(this);
8135
- this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request);
8145
+ this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request, this.cipher);
8136
8146
  }
8137
8147
  /**
8138
8148
  * @description
@@ -8552,7 +8562,7 @@ class AuthService extends Base {
8552
8562
  data: deviceKeyPair.privateKey,
8553
8563
  encryptionKey: credentialsKeyPair.publicKey,
8554
8564
  });
8555
- this.localStorageService.saveInBulk([
8565
+ await this.localStorageService.saveInBulk([
8556
8566
  {
8557
8567
  key: exports.LocalStorageItems.EncryptedDevicePrivateKey,
8558
8568
  value: encryptedDevicePrivKey,
@@ -8623,6 +8633,24 @@ class AuthService extends Base {
8623
8633
  valid: true,
8624
8634
  };
8625
8635
  }
8636
+ /**
8637
+ * @description Exchanges the client JWT (set at SDK initialisation) for a
8638
+ * Wallaby access + refresh token pair. Tokens are persisted to storage so
8639
+ * subsequent SDK calls use them automatically.
8640
+ * @returns {Promise<IssueJWTTokenResponseDto>} The issued access/refresh tokens and basic user info.
8641
+ */
8642
+ async exchangeClientToken() {
8643
+ try {
8644
+ const response = await this.request(AuthRoutes.issueJwtToken);
8645
+ await this.localStorageService.save(exports.LocalStorageItems.AccessToken, response.accessToken);
8646
+ await this.localStorageService.save(exports.LocalStorageItems.RefreshToken, response.refreshToken);
8647
+ return response;
8648
+ }
8649
+ catch (error) {
8650
+ logger.error('SDK::Auth::exchangeClientToken::error', error);
8651
+ throw error;
8652
+ }
8653
+ }
8626
8654
  }
8627
8655
  __decorate([
8628
8656
  WithLock('signUp'),
@@ -8643,10 +8671,67 @@ __decorate([
8643
8671
  __metadata("design:returntype", Promise)
8644
8672
  ], AuthService.prototype, "storeDeviceKeyPair", null);
8645
8673
 
8674
+ const ENCRYPTED_PAYLOAD_FIELDS = ['iv', 'ephemPublicKey', 'ciphertext', 'mac'];
8675
+ // Backup share may be ECIES or symmetric ({ iv, ciphertext, mac, tag }) — both share these three fields.
8676
+ const SYMMETRIC_PAYLOAD_FIELDS = ['iv', 'ciphertext', 'mac', 'tag'];
8677
+ // API is the trust boundary: confirm every named field is a non-empty string.
8678
+ function hasNonEmptyStringFields(payload, fields) {
8679
+ return (!!payload &&
8680
+ typeof payload === 'object' &&
8681
+ fields.every((field) => {
8682
+ const value = payload[field];
8683
+ return typeof value === 'string' && value.length > 0;
8684
+ }));
8685
+ }
8686
+ /**
8687
+ * Fail fast if an encrypted payload from the API does not match the expected
8688
+ * ECIES structure ({ iv, ephemPublicKey, ciphertext, mac }). See the contract
8689
+ * note on `handleKeySharesFromResponse`.
8690
+ */
8691
+ function assertEncryptedPayloadShape(encrypted) {
8692
+ if (!hasNonEmptyStringFields(encrypted, ENCRYPTED_PAYLOAD_FIELDS)) {
8693
+ throw new WallabyError({
8694
+ message: 'Encrypted share does not match the expected { iv, ephemPublicKey, ciphertext, mac } format.',
8695
+ statusCode: 422,
8696
+ errorCode: exports.ErrorResponseCodes.sdk_invalid_parameter,
8697
+ });
8698
+ }
8699
+ }
8700
+ /**
8701
+ * Shape-assert every share returned by the API. Empty arrays are rejected here
8702
+ * so callers get a clean error instead of crashing on `shares[0]`.
8703
+ */
8704
+ function assertSharesPayloadShape(shares) {
8705
+ if (!shares.length) {
8706
+ throw new WallabyError({
8707
+ message: 'No key shares were returned from the API.',
8708
+ statusCode: 422,
8709
+ errorCode: exports.ErrorResponseCodes.sdk_invalid_parameter,
8710
+ });
8711
+ }
8712
+ for (const share of shares) {
8713
+ assertEncryptedPayloadShape(share.encrypted);
8714
+ }
8715
+ }
8716
+ /**
8717
+ * The backup share is stored as-is (the device can't peel it), so we only
8718
+ * shape-check it. It may be ECIES or symmetric, so accept either variant.
8719
+ */
8720
+ function assertBackupSharePayloadShape(encrypted) {
8721
+ const isEcies = hasNonEmptyStringFields(encrypted, ENCRYPTED_PAYLOAD_FIELDS);
8722
+ const isSymmetric = hasNonEmptyStringFields(encrypted, SYMMETRIC_PAYLOAD_FIELDS);
8723
+ if (!isEcies && !isSymmetric) {
8724
+ throw new WallabyError({
8725
+ message: 'Encrypted backup share does not match the expected ECIES ({ iv, ephemPublicKey, ciphertext, mac }) or symmetric ({ iv, ciphertext, mac, tag }) format.',
8726
+ statusCode: 422,
8727
+ errorCode: exports.ErrorResponseCodes.sdk_invalid_parameter,
8728
+ });
8729
+ }
8730
+ }
8646
8731
  class WalletHandlersService extends Base {
8647
- constructor(config) {
8648
- super(config);
8649
- this.authService = new AuthService(config);
8732
+ constructor(config, ports = {}) {
8733
+ super(config, ports);
8734
+ this.authService = new AuthService(config, ports);
8650
8735
  this.userId = config.userId;
8651
8736
  }
8652
8737
  async handleImportWallet(deviceAuthKeys, importWalletInput) {
@@ -8723,6 +8808,7 @@ class WalletHandlersService extends Base {
8723
8808
  shares: importWalletRequest.shares,
8724
8809
  credentialsKeyPair,
8725
8810
  encryptedBackupShare: importWalletRequest.encryptedBackupShare,
8811
+ devicePrivateKey: deviceAuthKeys.privateKey,
8726
8812
  });
8727
8813
  }
8728
8814
  return Object.assign({}, importWalletRequest);
@@ -8809,6 +8895,7 @@ class WalletHandlersService extends Base {
8809
8895
  shares: walletCreationResponse.shares,
8810
8896
  credentialsKeyPair,
8811
8897
  encryptedBackupShare: walletCreationResponse.encryptedBackupShare,
8898
+ devicePrivateKey: deviceAuthKeys.privateKey,
8812
8899
  });
8813
8900
  }
8814
8901
  return Object.assign(Object.assign({}, walletCreationResponse), { standardSeedPhrase: decryptedSeedPhrase });
@@ -8824,8 +8911,41 @@ class WalletHandlersService extends Base {
8824
8911
  });
8825
8912
  }
8826
8913
  }
8827
- async handleKeySharesFromResponse({ walletId, shares, credentialsKeyPair, encryptedBackupShare, }) {
8914
+ /**
8915
+ * Encrypted share format contract (WAL-1467)
8916
+ * --------------------------------------------------------------------------
8917
+ * Every flow that ingests shares from the API (import, create, recover,
8918
+ * addNewDevice) routes through here, so the contract is asserted in one place.
8919
+ *
8920
+ * The API returns the main device share as `shares[0]`, an ECIES payload
8921
+ * ({ iv, ephemPublicKey, ciphertext, mac }) wrapped to the device public key,
8922
+ * so it MUST peel with the device private key. `encryptedBackupShare` is an
8923
+ * already-wrapped blob (ECIES or symmetric) that the device cannot decrypt, so
8924
+ * it is stored as-is.
8925
+ *
8926
+ * We shape-assert every share (and the backup share) here, at ingestion, so a
8927
+ * server-side wrapping change fails loudly now instead of silently breaking
8928
+ * export/recovery later.
8929
+ */
8930
+ async handleKeySharesFromResponse({ walletId, shares, credentialsKeyPair, encryptedBackupShare, devicePrivateKey, }) {
8828
8931
  try {
8932
+ assertSharesPayloadShape(shares);
8933
+ assertBackupSharePayloadShape(encryptedBackupShare);
8934
+ // Decrypt-test the contract: shares[0] is wrapped to the device public key and must peel with the device private key.
8935
+ try {
8936
+ await this.cipher.decrypt({
8937
+ cipherText: shares[0].encrypted,
8938
+ decryptionKey: devicePrivateKey,
8939
+ });
8940
+ }
8941
+ catch (error) {
8942
+ throw new WallabyError({
8943
+ message: 'Device-wrapped key share (shares[0]) could not be decrypted with the device private key; the share wrapping format may have changed.',
8944
+ statusCode: 422,
8945
+ errorCode: exports.ErrorResponseCodes.sdk_key_share_decryption_failed,
8946
+ cause: error,
8947
+ });
8948
+ }
8829
8949
  const encryptedWithCredentialsKeyShare = await this.cipher.encrypt({
8830
8950
  data: JSON.stringify(shares[0].encrypted),
8831
8951
  encryptionKey: credentialsKeyPair.publicKey,
@@ -8917,14 +9037,43 @@ class WalletHandlersService extends Base {
8917
9037
  }
8918
9038
 
8919
9039
  class WalletService extends Base {
8920
- constructor(config) {
8921
- super(config);
8922
- this.passwordResetAttempts = 0;
8923
- this.migrationAttempts = 0;
8924
- this.authService = new AuthService(config);
8925
- this.handlers = new WalletHandlersService(config);
9040
+ constructor(config, ports = {}) {
9041
+ super(config, ports);
9042
+ this.authService = new AuthService(config, ports);
9043
+ this.handlers = new WalletHandlersService(config, ports);
8926
9044
  this.userId = config.userId;
8927
- this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request);
9045
+ this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request, this.cipher);
9046
+ }
9047
+ /**
9048
+ * Reads the persisted sliding-window rate-limit state for a counter key.
9049
+ * Returns a fresh window ({ count: 0 }) when none is stored or the window has expired.
9050
+ */
9051
+ async getRateState(key) {
9052
+ const now = Date.now();
9053
+ const raw = await this.localStorageService.fetch(key);
9054
+ const state = raw ? safeJsonParse(raw) : undefined;
9055
+ if (!state || now - state.windowStart > WalletService.RATE_LIMIT_WINDOW_MS) {
9056
+ return { count: 0, windowStart: now };
9057
+ }
9058
+ return state;
9059
+ }
9060
+ /** Increments and persists the counter (resetting an expired window). Returns the new count. */
9061
+ async recordRateAttempt(key) {
9062
+ const state = await this.getRateState(key);
9063
+ state.count += 1;
9064
+ await this.localStorageService.save(key, JSON.stringify(state));
9065
+ return state.count;
9066
+ }
9067
+ /** Throws a 429 when the counter is already over the limit, without incrementing it. */
9068
+ async assertUnderRateLimit(key, message) {
9069
+ const { count } = await this.getRateState(key);
9070
+ if (count > WalletService.RATE_LIMIT_MAX) {
9071
+ throw new WallabyError({
9072
+ message,
9073
+ statusCode: 429,
9074
+ errorCode: exports.ErrorResponseCodes.sdk_too_many_requests,
9075
+ });
9076
+ }
8928
9077
  }
8929
9078
  /**
8930
9079
  * @public
@@ -9031,20 +9180,7 @@ class WalletService extends Base {
9031
9180
  });
9032
9181
  }
9033
9182
  if (this.deviceAuthType === exports.AuthType.Password && authenticationOptions.password) {
9034
- try {
9035
- await this.handleUpdateToV2({
9036
- password: authenticationOptions.password,
9037
- walletId: walletId,
9038
- });
9039
- }
9040
- catch (error) {
9041
- logger.error('SDK::WalletService::export::handleUpdateToV2::error', error);
9042
- throw new WallabyError({
9043
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
9044
- statusCode: 500,
9045
- errorCode: exports.ErrorResponseCodes.sdk_unknown_error,
9046
- });
9047
- }
9183
+ await this.migrateToV2Safe({ password: authenticationOptions.password, walletId });
9048
9184
  }
9049
9185
  const encryptedSeed = await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedStandardSeedPhrase, { walletId });
9050
9186
  const encryptedPrimaryDeviceShare = await this.localStorageService.fetch(exports.LocalStorageItems.PrimaryDeviceKeyShare, {
@@ -9287,6 +9423,7 @@ class WalletService extends Base {
9287
9423
  shares: recoverWithSeedPhraseResponse.shares,
9288
9424
  credentialsKeyPair,
9289
9425
  encryptedBackupShare: recoverWithSeedPhraseResponse.encryptedBackupShare,
9426
+ devicePrivateKey: deviceAuthKeyPair.privateKey,
9290
9427
  });
9291
9428
  }
9292
9429
  await this.authService.storeDeviceKeyPair({
@@ -9350,6 +9487,7 @@ class WalletService extends Base {
9350
9487
  shares: recoverWithSeedPhraseResponse.shares,
9351
9488
  credentialsKeyPair,
9352
9489
  encryptedBackupShare: recoverWithSeedPhraseResponse.encryptedBackupShare,
9490
+ devicePrivateKey: deviceAuthKeyPair.privateKey,
9353
9491
  });
9354
9492
  }
9355
9493
  await this.authService.storeDeviceKeyPair({
@@ -9382,8 +9520,7 @@ class WalletService extends Base {
9382
9520
  */
9383
9521
  async changePassword({ walletId, oldPassword, newPassword, }) {
9384
9522
  try {
9385
- this.passwordResetAttempts += 1;
9386
- if (this.passwordResetAttempts > 5) {
9523
+ if ((await this.recordRateAttempt(exports.V2KeyNames.PasswordResetAttempts)) > WalletService.RATE_LIMIT_MAX) {
9387
9524
  throw new WallabyError({
9388
9525
  message: 'Too many password change attempts. Please try again later.',
9389
9526
  statusCode: 429,
@@ -9392,20 +9529,7 @@ class WalletService extends Base {
9392
9529
  }
9393
9530
  if (this.deviceAuthType === exports.AuthType.Password && oldPassword) {
9394
9531
  // Handle migration to V2 first then change the password to the new one.
9395
- try {
9396
- await this.handleUpdateToV2({
9397
- password: oldPassword,
9398
- walletId,
9399
- });
9400
- }
9401
- catch (error) {
9402
- logger.error('SDK::WalletService::changePassword::handleUpdateToV2::error', error);
9403
- throw new WallabyError({
9404
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
9405
- statusCode: 500,
9406
- errorCode: exports.ErrorResponseCodes.sdk_unknown_error,
9407
- });
9408
- }
9532
+ await this.migrateToV2Safe({ password: oldPassword, walletId });
9409
9533
  }
9410
9534
  const encryptedDevicePrivateKeyString = await this.localStorageService.fetch(exports.V2KeyNames.EncryptedDevicePrivateKey);
9411
9535
  const encryptedSeedPhraseString = await this.localStorageService.fetch(exports.V2KeyNames.EncryptedStandardSeedPhrase, {
@@ -9462,40 +9586,41 @@ class WalletService extends Base {
9462
9586
  errorCode: exports.ErrorResponseCodes.sdk_unknown_error,
9463
9587
  });
9464
9588
  }
9465
- await this.localStorageService.save(exports.LocalStorageItems.EncryptedDevicePrivateKey, reWrappedDevicePrivateKey);
9466
- if (encryptedSeedPhraseString) {
9467
- const parsedSeed = safeJsonParse(encryptedSeedPhraseString);
9468
- const reWrappedSeedPhrase = await this.cipher.flipEncryptedData({
9469
- cipherText: parsedSeed,
9589
+ const reWrappedSeedPhrase = encryptedSeedPhraseString
9590
+ ? await this.cipher.flipEncryptedData({
9591
+ cipherText: safeJsonParse(encryptedSeedPhraseString),
9470
9592
  decryptionKey: oldCredentialsKeyPair.privateKey,
9471
9593
  encryptionKey: newCredentialsKeyPair.publicKey,
9472
- });
9473
- await this.localStorageService.save(exports.LocalStorageItems.EncryptedStandardSeedPhrase, reWrappedSeedPhrase, {
9474
- walletId,
9475
- });
9476
- }
9477
- if (encryptedPrimaryShareString) {
9478
- const parsedPrimaryShare = safeJsonParse(encryptedPrimaryShareString);
9479
- const reWrappedPrimaryShare = await this.cipher.flipEncryptedData({
9480
- cipherText: parsedPrimaryShare,
9594
+ })
9595
+ : null;
9596
+ const reWrappedPrimaryShare = encryptedPrimaryShareString
9597
+ ? await this.cipher.flipEncryptedData({
9598
+ cipherText: safeJsonParse(encryptedPrimaryShareString),
9481
9599
  decryptionKey: oldCredentialsKeyPair.privateKey,
9482
9600
  encryptionKey: newCredentialsKeyPair.publicKey,
9483
- });
9484
- await this.localStorageService.save(exports.LocalStorageItems.PrimaryDeviceKeyShare, reWrappedPrimaryShare, {
9485
- walletId,
9486
- });
9487
- }
9488
- if (encryptedBackupShareString) {
9489
- const parsedBackupShare = safeJsonParse(encryptedBackupShareString);
9490
- const reWrappedBackupShare = await this.cipher.flipEncryptedData({
9491
- cipherText: parsedBackupShare,
9601
+ })
9602
+ : null;
9603
+ const reWrappedBackupShare = encryptedBackupShareString
9604
+ ? await this.cipher.flipEncryptedData({
9605
+ cipherText: safeJsonParse(encryptedBackupShareString),
9492
9606
  decryptionKey: oldCredentialsKeyPair.privateKey,
9493
9607
  encryptionKey: newCredentialsKeyPair.publicKey,
9494
- });
9495
- await this.localStorageService.save(exports.LocalStorageItems.BackupDeviceKeyShare, reWrappedBackupShare, {
9496
- walletId,
9497
- });
9498
- }
9608
+ })
9609
+ : null;
9610
+ // Commit all re-wrapped blobs in one batch so a partial failure cannot leave the device
9611
+ // in a half-migrated state (some items under the new password, others under the old).
9612
+ await this.localStorageService.saveInBulk([
9613
+ { key: exports.LocalStorageItems.EncryptedDevicePrivateKey, value: reWrappedDevicePrivateKey },
9614
+ ...(reWrappedSeedPhrase
9615
+ ? [{ key: exports.LocalStorageItems.EncryptedStandardSeedPhrase, value: reWrappedSeedPhrase, walletId }]
9616
+ : []),
9617
+ ...(reWrappedPrimaryShare
9618
+ ? [{ key: exports.LocalStorageItems.PrimaryDeviceKeyShare, value: reWrappedPrimaryShare, walletId }]
9619
+ : []),
9620
+ ...(reWrappedBackupShare ? [{ key: exports.LocalStorageItems.BackupDeviceKeyShare, value: reWrappedBackupShare, walletId }] : []),
9621
+ ]);
9622
+ // Reset the rate-limit window on success so a normal change does not count against future ones.
9623
+ await this.localStorageService.delete(exports.V2KeyNames.PasswordResetAttempts);
9499
9624
  return true;
9500
9625
  }
9501
9626
  catch (error) {
@@ -9548,20 +9673,7 @@ class WalletService extends Base {
9548
9673
  }
9549
9674
  const parsedEncryptedDevicePrivateKey = safeJsonParse(encryptedDevicePrivateKey);
9550
9675
  if (this.deviceAuthType === exports.AuthType.Password && input.authenticationOptions.password) {
9551
- try {
9552
- await this.handleUpdateToV2({
9553
- password: input.authenticationOptions.password,
9554
- walletId: input.walletId,
9555
- });
9556
- }
9557
- catch (error) {
9558
- logger.error('SDK::WalletService::initAddNewDevice::handleUpdateToV2::error', error);
9559
- throw new WallabyError({
9560
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
9561
- statusCode: 500,
9562
- errorCode: exports.ErrorResponseCodes.sdk_unknown_error,
9563
- });
9564
- }
9676
+ await this.migrateToV2Safe({ password: input.authenticationOptions.password, walletId: input.walletId });
9565
9677
  }
9566
9678
  const storedEncryptedBackupShare = await this.localStorageService.fetch(exports.LocalStorageItems.BackupDeviceKeyShare, { walletId });
9567
9679
  if (!storedEncryptedBackupShare) {
@@ -9659,6 +9771,7 @@ class WalletService extends Base {
9659
9771
  shares: [backUpResponse.share],
9660
9772
  credentialsKeyPair,
9661
9773
  encryptedBackupShare: input.encryptedBackupShare,
9774
+ devicePrivateKey: decryptedDevicePrivateKey,
9662
9775
  });
9663
9776
  return { success: true, reference: backUpResponse.reference };
9664
9777
  }
@@ -9677,20 +9790,7 @@ class WalletService extends Base {
9677
9790
  });
9678
9791
  }
9679
9792
  if (this.deviceAuthType === exports.AuthType.Password && input.authenticationOptions.password) {
9680
- try {
9681
- await this.handleUpdateToV2({
9682
- password: input.authenticationOptions.password,
9683
- walletId: input.walletId,
9684
- });
9685
- }
9686
- catch (error) {
9687
- logger.error('SDK::WalletService::generateWalletAddresses::handleUpdateToV2::error', error);
9688
- throw new WallabyError({
9689
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
9690
- statusCode: 500,
9691
- errorCode: exports.ErrorResponseCodes.sdk_unknown_error,
9692
- });
9693
- }
9793
+ await this.migrateToV2Safe({ password: input.authenticationOptions.password, walletId: input.walletId });
9694
9794
  }
9695
9795
  try {
9696
9796
  const walletOperationAuth = await this.prepareWalletOperationAuth({
@@ -9715,6 +9815,23 @@ class WalletService extends Base {
9715
9815
  throw error;
9716
9816
  }
9717
9817
  }
9818
+ /**
9819
+ * Wraps handleUpdateToV2 with the standard user-facing error. All call sites that gate on
9820
+ * `AuthType.Password` should go through here so the error message stays consistent.
9821
+ */
9822
+ async migrateToV2Safe({ password, walletId }) {
9823
+ try {
9824
+ await this.handleUpdateToV2({ password, walletId });
9825
+ }
9826
+ catch (error) {
9827
+ logger.error('SDK::WalletService::migrateToV2Safe::error', error);
9828
+ throw new WallabyError({
9829
+ message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
9830
+ statusCode: 500,
9831
+ errorCode: exports.ErrorResponseCodes.sdk_unknown_error,
9832
+ });
9833
+ }
9834
+ }
9718
9835
  /**
9719
9836
  * Detects and migrates legacy/v1 storage items to v2 format.
9720
9837
  * This function should be called in methods that use password as input when v2 items are missing.
@@ -9723,13 +9840,7 @@ class WalletService extends Base {
9723
9840
  */
9724
9841
  async handleUpdateToV2({ password, walletId }) {
9725
9842
  const migrationStartTime = Date.now();
9726
- if (this.migrationAttempts > 5) {
9727
- throw new WallabyError({
9728
- message: 'Too many migration attempts. Please try again later.',
9729
- statusCode: 429,
9730
- errorCode: exports.ErrorResponseCodes.sdk_too_many_requests,
9731
- });
9732
- }
9843
+ await this.assertUnderRateLimit(exports.V2KeyNames.MigrationAttempts, 'Too many migration attempts. Please try again later.');
9733
9844
  try {
9734
9845
  if (!password) {
9735
9846
  throw new WallabyError({
@@ -9800,7 +9911,7 @@ class WalletService extends Base {
9800
9911
  }
9801
9912
  }
9802
9913
  // Increment counter after V2 validation to avoid counting when migration not needed
9803
- this.migrationAttempts += 1;
9914
+ await this.recordRateAttempt(exports.V2KeyNames.MigrationAttempts);
9804
9915
  let decryptedSeedPhrase;
9805
9916
  let decryptedPrivateKey;
9806
9917
  // Check for legacy format: `{item}_{userId}`
@@ -9853,7 +9964,10 @@ class WalletService extends Base {
9853
9964
  try {
9854
9965
  // Decrypt V1 items using storage service method (handles double encryption)
9855
9966
  logger.log('Attempting to decrypt V1 items during migration...');
9856
- logger.log('getV1DecryptedSeedPhrase should be called with password and clientSalt:', { password, clientSalt });
9967
+ logger.log('getV1DecryptedSeedPhrase should be called with password and clientSalt:', {
9968
+ hasPassword: !!password,
9969
+ hasClientSalt: !!clientSalt,
9970
+ });
9857
9971
  decryptedSeedPhrase = await this.localStorageService.getV1DecryptedSeedPhrase(password, clientSalt);
9858
9972
  // For V1 format, private key is encrypted with just the password (not salt+password like legacy)
9859
9973
  decryptedPrivateKey = await this.localStorageService.getDecryptedV1PrivateKey(password);
@@ -10318,6 +10432,10 @@ class WalletService extends Base {
10318
10432
  }
10319
10433
  }
10320
10434
  }
10435
+ // ponytail: soft client-side guardrail against runaway retries; server-side rate limiting is the real control.
10436
+ // Counters are persisted (sliding window) so rebuilding the service no longer resets them. Tune freely.
10437
+ WalletService.RATE_LIMIT_MAX = 5;
10438
+ WalletService.RATE_LIMIT_WINDOW_MS = 30 * 60000; // 30 min
10321
10439
  __decorate([
10322
10440
  WithLock('create'),
10323
10441
  __metadata("design:type", Function),
@@ -10350,10 +10468,10 @@ __decorate([
10350
10468
  ], WalletService.prototype, "handleUpdateToV2", null);
10351
10469
 
10352
10470
  class WalletDataService extends Base {
10353
- constructor(config) {
10354
- super(config);
10471
+ constructor(config, ports = {}) {
10472
+ super(config, ports);
10355
10473
  this.userId = config.userId;
10356
- this.walletService = new WalletService(config);
10474
+ this.walletService = new WalletService(config, ports);
10357
10475
  }
10358
10476
  /**
10359
10477
  * @description Validates the wallet address info for a given blockchain.
@@ -10600,20 +10718,7 @@ class WalletDataService extends Base {
10600
10718
  });
10601
10719
  }
10602
10720
  if (this.deviceAuthType === exports.AuthType.Password && authenticationOptions.password) {
10603
- try {
10604
- await this.walletService.handleUpdateToV2({
10605
- password: authenticationOptions.password,
10606
- walletId: walletId,
10607
- });
10608
- }
10609
- catch (error) {
10610
- logger.error('SDK::WalletDataService::addNewChainAndTokenToWallet::handleUpdateToV2::error', error);
10611
- throw new WallabyError({
10612
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
10613
- statusCode: 500,
10614
- errorCode: exports.ErrorResponseCodes.sdk_unknown_error,
10615
- });
10616
- }
10721
+ await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
10617
10722
  }
10618
10723
  try {
10619
10724
  const addressInfo = await this.walletService.generateWalletAddresses({
@@ -10687,8 +10792,8 @@ class WalletDataService extends Base {
10687
10792
  }
10688
10793
 
10689
10794
  class Utils extends Base {
10690
- constructor(config) {
10691
- super(config);
10795
+ constructor(config, ports = {}) {
10796
+ super(config, ports);
10692
10797
  /**
10693
10798
  *
10694
10799
  * Decrypts user private key
@@ -10721,7 +10826,7 @@ class Utils extends Base {
10721
10826
  return undefined;
10722
10827
  }
10723
10828
  };
10724
- this.auth = new AuthService(config);
10829
+ this.auth = new AuthService(config, ports);
10725
10830
  }
10726
10831
  /**
10727
10832
  *
@@ -10814,179 +10919,6 @@ class Utils extends Base {
10814
10919
  }
10815
10920
  }
10816
10921
 
10817
- const MerchantsRoutes = {
10818
- create: {
10819
- fullPath: '/merchants',
10820
- method: exports.RequestMethod.Post,
10821
- requiresAccessToken: false,
10822
- },
10823
- update: {
10824
- fullPath: ({ merchantId }) => `/merchants/${merchantId}`,
10825
- method: exports.RequestMethod.Put,
10826
- requiresAccessToken: false,
10827
- },
10828
- getMerchantData: {
10829
- fullPath: ({ merchantId }) => `/merchants/${merchantId}`,
10830
- method: exports.RequestMethod.Get,
10831
- requiresAccessToken: false,
10832
- },
10833
- list: {
10834
- fullPath: '/merchants',
10835
- method: exports.RequestMethod.Get,
10836
- requiresAccessToken: false,
10837
- },
10838
- getAssets: {
10839
- fullPath: () => `/users/merchant/assets`,
10840
- method: exports.RequestMethod.Get,
10841
- requiresAccessToken: true,
10842
- },
10843
- addAsset: {
10844
- fullPath: ({ merchantId, configId }) => `/merchants/${merchantId}/assets/${configId}`,
10845
- method: exports.RequestMethod.Post,
10846
- requiresAccessToken: false,
10847
- },
10848
- deleteAsset: {
10849
- fullPath: ({ merchantId, configId }) => `/merchants/${merchantId}/assets/${configId}`,
10850
- method: exports.RequestMethod.Delete,
10851
- requiresAccessToken: false,
10852
- },
10853
- };
10854
-
10855
- class Merchants extends Base {
10856
- constructor(config) {
10857
- super(config);
10858
- }
10859
- /**
10860
- * @description
10861
- * Retrieves the merchant ID from access token `aud` claim.
10862
- * Even though merchantId is possibly undefined. If an access token is not stored on device, the request will most likely
10863
- * not have it in headers and will fail with 401 regardless.
10864
- *
10865
- * @returns { string | undefined } Merchant ID
10866
- */
10867
- async _getMerchantId() {
10868
- const accessToken = await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken);
10869
- if (!accessToken)
10870
- return;
10871
- const jwtDecoded = jwtDecode.jwtDecode(accessToken);
10872
- return jwtDecoded.aud;
10873
- }
10874
- /**
10875
- *
10876
- * @public
10877
- * List of all merchants in the system
10878
- * @returns { ListMerchantsResponse } Array of all merchants
10879
- */
10880
- async list() {
10881
- try {
10882
- const response = await this.request(MerchantsRoutes.list, {
10883
- payload: {},
10884
- });
10885
- return response;
10886
- }
10887
- catch (error) {
10888
- logger.error('SDK::Merchants::list::error', error);
10889
- return Promise.reject(error);
10890
- }
10891
- }
10892
- /**
10893
- *
10894
- * @public
10895
- * Allows to create a new merchant
10896
- * @returns { Merchant } Merchant data
10897
- */
10898
- async create({ name }) {
10899
- try {
10900
- const response = await this.request(MerchantsRoutes.create, {
10901
- payload: { name },
10902
- });
10903
- return response;
10904
- }
10905
- catch (error) {
10906
- logger.error('SDK::Merchants::list::error', error);
10907
- return Promise.reject(error);
10908
- }
10909
- }
10910
- /**
10911
- *
10912
- * @public
10913
- * Allows to update merchant data
10914
- * @returns { Merchant } Merchant data
10915
- */
10916
- async update({ name, status }) {
10917
- try {
10918
- const merchantId = await this._getMerchantId();
10919
- const response = await this.request(MerchantsRoutes.update, {
10920
- payload: { merchantId, name, status },
10921
- });
10922
- return response;
10923
- }
10924
- catch (error) {
10925
- logger.error('SDK::Merchants::list::error', error);
10926
- return Promise.reject(error);
10927
- }
10928
- }
10929
- /**
10930
- *
10931
- * @public
10932
- * @returns { Merchant } Merchant data
10933
- */
10934
- async getMerchantData() {
10935
- try {
10936
- const merchantId = await this._getMerchantId();
10937
- const response = await this.request(MerchantsRoutes.getMerchantData, {
10938
- payload: { merchantId },
10939
- });
10940
- return response.merchant;
10941
- }
10942
- catch (error) {
10943
- logger.error('SDK::Merchants::list::error', error);
10944
- return Promise.reject(error);
10945
- }
10946
- }
10947
- /**
10948
- *
10949
- * @public
10950
- * @returns { MerchantAsset[] } List of merchant assets
10951
- */
10952
- async getAssets() {
10953
- try {
10954
- const response = await this.request(MerchantsRoutes.getAssets);
10955
- return response.merchantAssets;
10956
- }
10957
- catch (error) {
10958
- logger.error('SDK::Merchants::list::error', error);
10959
- return Promise.reject(error);
10960
- }
10961
- }
10962
- async addAsset({ configId }) {
10963
- try {
10964
- const merchantId = await this._getMerchantId();
10965
- const response = await this.request(MerchantsRoutes.addAsset, {
10966
- payload: { merchantId, configId },
10967
- });
10968
- return response;
10969
- }
10970
- catch (error) {
10971
- logger.error('SDK::Merchants::list::error', error);
10972
- return Promise.reject(error);
10973
- }
10974
- }
10975
- async deleteAsset({ configId }) {
10976
- try {
10977
- const merchantId = await this._getMerchantId();
10978
- const response = await this.request(MerchantsRoutes.deleteAsset, {
10979
- payload: { merchantId, configId },
10980
- });
10981
- return response;
10982
- }
10983
- catch (error) {
10984
- logger.error('SDK::Merchants::list::error', error);
10985
- return Promise.reject(error);
10986
- }
10987
- }
10988
- }
10989
-
10990
10922
  /**
10991
10923
  * HttpApi provides direct access to all REST API endpoints.
10992
10924
  * This class extends the Base class and includes the generated API client
@@ -11001,16 +10933,16 @@ class HttpApi extends Base {
11001
10933
  * @param config - The Wallaby configuration object
11002
10934
  * @public
11003
10935
  */
11004
- constructor(config) {
11005
- super(config);
10936
+ constructor(config, ports = {}) {
10937
+ super(config, ports);
11006
10938
  }
11007
10939
  }
11008
10940
 
11009
10941
  class Swap extends Base {
11010
- constructor(config) {
11011
- super(config);
11012
- this.authService = new AuthService(config);
11013
- this.walletService = new WalletService(config);
10942
+ constructor(config, ports = {}) {
10943
+ super(config, ports);
10944
+ this.authService = new AuthService(config, ports);
10945
+ this.walletService = new WalletService(config, ports);
11014
10946
  }
11015
10947
  /**
11016
10948
  * Gets a swap quote between two assets, including fees, min output, and slippage limits.
@@ -11067,20 +10999,7 @@ class Swap extends Base {
11067
10999
  try {
11068
11000
  // Only attempt migration if we have password auth and V2 storage might be incomplete
11069
11001
  if (this.deviceAuthType === exports.AuthType.Password && authenticationOptions.password) {
11070
- try {
11071
- await this.walletService.handleUpdateToV2({
11072
- password: authenticationOptions.password,
11073
- walletId: walletId,
11074
- });
11075
- }
11076
- catch (error) {
11077
- logger.error('SDK::Swap::executeSwap::handleUpdateToV2::error', error);
11078
- throw new WallabyError({
11079
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
11080
- statusCode: 500,
11081
- errorCode: exports.ErrorResponseCodes.sdk_unknown_error,
11082
- });
11083
- }
11002
+ await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
11084
11003
  }
11085
11004
  const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareSwapAuth(authenticationOptions, walletId);
11086
11005
  let swapResponse;
@@ -11276,8 +11195,8 @@ const sanitizeSuiObjectId = (objectId) => {
11276
11195
  };
11277
11196
 
11278
11197
  class System extends Base {
11279
- constructor(config) {
11280
- super(config);
11198
+ constructor(config, ports = {}) {
11199
+ super(config, ports);
11281
11200
  }
11282
11201
  /**
11283
11202
  * @public
@@ -11470,10 +11389,10 @@ class System extends Base {
11470
11389
  }
11471
11390
 
11472
11391
  class Transactions extends Base {
11473
- constructor(config) {
11474
- super(config);
11475
- this.authService = new AuthService(config);
11476
- this.walletService = new WalletService(config);
11392
+ constructor(config, ports = {}) {
11393
+ super(config, ports);
11394
+ this.authService = new AuthService(config, ports);
11395
+ this.walletService = new WalletService(config, ports);
11477
11396
  this.userId = config.userId;
11478
11397
  }
11479
11398
  /**
@@ -11596,20 +11515,7 @@ class Transactions extends Base {
11596
11515
  try {
11597
11516
  // Only attempt migration if we have password auth and V2 storage might be incomplete
11598
11517
  if (this.deviceAuthType === exports.AuthType.Password && authenticationOptions.password) {
11599
- try {
11600
- await this.walletService.handleUpdateToV2({
11601
- password: authenticationOptions.password,
11602
- walletId: walletId,
11603
- });
11604
- }
11605
- catch (error) {
11606
- logger.error('SDK::Transactions::transfer::handleUpdateToV2::error', error);
11607
- throw new WallabyError({
11608
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
11609
- statusCode: 500,
11610
- errorCode: exports.ErrorResponseCodes.sdk_unknown_error,
11611
- });
11612
- }
11518
+ await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
11613
11519
  }
11614
11520
  const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareTransactionAuth(authenticationOptions, walletId);
11615
11521
  let transferResponse;
@@ -11697,20 +11603,7 @@ class Transactions extends Base {
11697
11603
  }
11698
11604
  // Only attempt migration if we have password auth and V2 storage might be incomplete
11699
11605
  if (this.deviceAuthType === exports.AuthType.Password && authenticationOptions.password) {
11700
- try {
11701
- await this.walletService.handleUpdateToV2({
11702
- password: authenticationOptions.password,
11703
- walletId: walletId,
11704
- });
11705
- }
11706
- catch (error) {
11707
- logger.error('SDK::Transactions::createAllowance::handleUpdateToV2::error', error);
11708
- throw new WallabyError({
11709
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
11710
- statusCode: 500,
11711
- errorCode: exports.ErrorResponseCodes.sdk_unknown_error,
11712
- });
11713
- }
11606
+ await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
11714
11607
  }
11715
11608
  const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareTransactionAuth(authenticationOptions, walletId);
11716
11609
  const { message, signature } = signatureMessage;
@@ -11775,20 +11668,7 @@ class Transactions extends Base {
11775
11668
  try {
11776
11669
  // Only attempt migration if we have password auth and V2 storage might be incomplete
11777
11670
  if (this.deviceAuthType === exports.AuthType.Password && authenticationOptions.password) {
11778
- try {
11779
- await this.walletService.handleUpdateToV2({
11780
- password: authenticationOptions.password,
11781
- walletId: walletId,
11782
- });
11783
- }
11784
- catch (error) {
11785
- logger.error('SDK::Transactions::resolvePendingTransaction::handleUpdateToV2::error', error);
11786
- throw new WallabyError({
11787
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
11788
- statusCode: 500,
11789
- errorCode: exports.ErrorResponseCodes.sdk_unknown_error,
11790
- });
11791
- }
11671
+ await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
11792
11672
  }
11793
11673
  const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareTransactionAuth(authenticationOptions, walletId);
11794
11674
  if (!readyForTransportSeedPhrase && !hasShares) {
@@ -11953,16 +11833,15 @@ class Wallaby {
11953
11833
  * @param {string} [config.clientAuthToken] - A web token generated by the client for authorization.
11954
11834
  * @public
11955
11835
  */
11956
- constructor(config) {
11957
- this.wallet = new WalletService(config);
11958
- this.walletData = new WalletDataService(config);
11959
- this.utils = new Utils(config);
11960
- this.auth = new AuthService(config);
11961
- this.system = new System(config);
11962
- this.transactions = new Transactions(config);
11963
- this.swap = new Swap(config);
11964
- this.merchants = new Merchants(config);
11965
- this.httpApi = new HttpApi(config);
11836
+ constructor(config, ports = {}) {
11837
+ this.wallet = new WalletService(config, ports);
11838
+ this.walletData = new WalletDataService(config, ports);
11839
+ this.utils = new Utils(config, ports);
11840
+ this.auth = new AuthService(config, ports);
11841
+ this.system = new System(config, ports);
11842
+ this.transactions = new Transactions(config, ports);
11843
+ this.swap = new Swap(config, ports);
11844
+ this.httpApi = new HttpApi(config, ports);
11966
11845
  }
11967
11846
  get version() {
11968
11847
  return currentPackageVersion;