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.js CHANGED
@@ -313,6 +313,8 @@ 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";
316
318
  })(V2KeyNames || (V2KeyNames = {}));
317
319
 
318
320
  var ErrorResponseCodes;
@@ -568,7 +570,6 @@ const defaultEnvironment = (_a = browser$1.env.NODE_ENV) !== null && _a !== void
568
570
  * Please pass the network value in the WallabyConfigOptions object to override it for production-mainnet.
569
571
  */
570
572
  const defaultNetwork = 'testnet';
571
- const isTest = browser$1.env.NODE_ENV === 'test';
572
573
  const DEFAULT_ENTROPY_BYTES$1 = 32;
573
574
  const PBKDF2_ITERATIONS = 131072;
574
575
  const DEFAULT_HOSTNAME = 'https://www.republic.com';
@@ -591,7 +592,7 @@ const MASTER_ENCRYPTION_KEY = '9fa9d3f3c77c20d3a50a08e5299644be29f6e6206ef3479fe
591
592
  const isWeb = typeof window !== 'undefined' && typeof document !== 'undefined';
592
593
  const env = {
593
594
  platform: 'web',
594
- isNative: false,
595
+ isNative: !isWeb,
595
596
  isWeb,
596
597
  };
597
598
  const currentPackageVersion = "3.3.0" ;
@@ -3495,7 +3496,6 @@ const keccak256$1 = (() => {
3495
3496
  })();
3496
3497
 
3497
3498
  const DEFAULT_ENTROPY_BYTES = 32;
3498
- const MINIMUM_SHANNON_ENTROPY = 4;
3499
3499
  /**
3500
3500
  * creates a new private key
3501
3501
  * @param { Uint8Array } entropy - optional entropy to create the private key
@@ -3506,25 +3506,15 @@ const createPrivateKey = (entropy) => {
3506
3506
  if (!(entropy instanceof Uint8Array) || entropy.length < DEFAULT_ENTROPY_BYTES) {
3507
3507
  throw new Error(`entropy must be a Uint8Array of at least ${DEFAULT_ENTROPY_BYTES} bytes`);
3508
3508
  }
3509
- // Check byte diversity
3509
+ // Check byte diversity. This catches genuinely broken inputs (all-zeros, all-same-byte)
3510
+ // without false-positiving on 32-byte KDF output (~30 unique bytes expected).
3511
+ // ponytail: the sampled Shannon-entropy check was removed (WAL-1465) — it's unsound for
3512
+ // 32 samples (max measurable = log2(32) ≈ 5 bits/byte vs a 4-bit threshold), so deterministic
3513
+ // KDF output could be rejected, permanently locking the user out.
3510
3514
  const uniqueBytes = new Set(entropy);
3511
3515
  if (uniqueBytes.size < Math.min(8, entropy.length / 4)) {
3512
3516
  throw new Error(`entropy is too repetitive (only ${uniqueBytes.size} unique byte values)`);
3513
3517
  }
3514
- // Estimate Shannon entropy
3515
- const byteCounts = new Uint32Array(256);
3516
- entropy.forEach((b) => byteCounts[b]++);
3517
- const total = entropy.length;
3518
- let shannonEntropy = 0;
3519
- for (let i = 0; i < 256; i++) {
3520
- if (byteCounts[i] > 0) {
3521
- const p = byteCounts[i] / total;
3522
- shannonEntropy -= p * Math.log2(p);
3523
- }
3524
- }
3525
- if (shannonEntropy < MINIMUM_SHANNON_ENTROPY) {
3526
- throw new Error(`entropy has low Shannon entropy (${shannonEntropy.toFixed(2)} bits/byte)`);
3527
- }
3528
3518
  const outerHex = keccak256$1(entropy);
3529
3519
  return addLeading0x(bytesToHex$1(outerHex));
3530
3520
  }
@@ -4399,6 +4389,11 @@ function pbkdf2Sync(password, salt, iterations, keylen, digest) {
4399
4389
  });
4400
4390
  }
4401
4391
 
4392
+ // Version marker prepended to values wrapped by the master key, so wrapped vs raw is deterministic.
4393
+ const MASTER_KEY_WRAP_PREFIX = 'wsdkmk:v1:';
4394
+ // crypto-js AES.encrypt with a string passphrase emits an OpenSSL "Salted__" header; its base64 always
4395
+ // starts with this. Used to recognize legacy wrapped values stored before MASTER_KEY_WRAP_PREFIX existed.
4396
+ const LEGACY_CRYPTOJS_PREFIX = 'U2FsdGVkX1';
4402
4397
  class Cipher {
4403
4398
  constructor() { }
4404
4399
  /**
@@ -4429,11 +4424,23 @@ class Cipher {
4429
4424
  * @returns The encrypted data as a string.
4430
4425
  */
4431
4426
  encryptWithMasterKey({ data }) {
4432
- return AES.encrypt(typeof data === 'string' ? data : JSON.stringify(data), this.getMasterKey().key).toString();
4427
+ const ciphertext = AES.encrypt(typeof data === 'string' ? data : JSON.stringify(data), this.getMasterKey().key).toString();
4428
+ return MASTER_KEY_WRAP_PREFIX + ciphertext;
4429
+ }
4430
+ /**
4431
+ * @description Determines deterministically whether a stored value was wrapped by the master key,
4432
+ * without inferring from decrypt behavior. Returns true for values carrying the version marker, or
4433
+ * legacy crypto-js ciphertext stored before the marker existed. Everything else is treated as raw.
4434
+ */
4435
+ isWrappedByMasterKey(value) {
4436
+ return value.startsWith(MASTER_KEY_WRAP_PREFIX) || value.startsWith(LEGACY_CRYPTOJS_PREFIX);
4433
4437
  }
4434
4438
  decryptWithMasterKey({ cipherText }) {
4439
+ const ciphertext = cipherText.startsWith(MASTER_KEY_WRAP_PREFIX)
4440
+ ? cipherText.slice(MASTER_KEY_WRAP_PREFIX.length)
4441
+ : cipherText;
4435
4442
  try {
4436
- const decrypted = AES.decrypt(cipherText, this.getMasterKey().key).toString(enc.Utf8);
4443
+ const decrypted = AES.decrypt(ciphertext, this.getMasterKey().key).toString(enc.Utf8);
4437
4444
  if (decrypted) {
4438
4445
  return isJsonString(decrypted) ? safeJsonParse(decrypted) : decrypted;
4439
4446
  }
@@ -4551,6 +4558,8 @@ class Cipher {
4551
4558
  }
4552
4559
  derivedKeyPair = await this.deriveKeyPairFromPasskey({ inputKeyMaterial: options.prfValue });
4553
4560
  return derivedKeyPair;
4561
+ default:
4562
+ throw new Error(`Unknown AuthType: ${options.authType}`);
4554
4563
  }
4555
4564
  }
4556
4565
  catch (error) {
@@ -4820,7 +4829,7 @@ class StorageService {
4820
4829
  else {
4821
4830
  storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}`;
4822
4831
  }
4823
- if (!isWeb) {
4832
+ if (env.isNative) {
4824
4833
  storageKey = normalizeKey(storageKey);
4825
4834
  }
4826
4835
  const item = await this.getItem(storageKey);
@@ -4829,14 +4838,11 @@ class StorageService {
4829
4838
  return undefined;
4830
4839
  }
4831
4840
  if (this._keysProtectedByMasterKey.includes(key)) {
4832
- let unwrapped;
4833
- // Temp fix to unblock prod issue. Need a more permanent solution.
4834
- try {
4835
- unwrapped = this.cipher.decryptWithMasterKey({ cipherText: item });
4836
- }
4837
- catch (_a) {
4838
- unwrapped = item;
4841
+ // Raw legacy value stored before master-key wrapping: return as-is instead of attempting decrypt.
4842
+ if (!this.cipher.isWrappedByMasterKey(item)) {
4843
+ return item;
4839
4844
  }
4845
+ const unwrapped = this.cipher.decryptWithMasterKey({ cipherText: item });
4840
4846
  if (!unwrapped) {
4841
4847
  logger.error(`Failed to decrypt item with key ${storageKey}`);
4842
4848
  return undefined;
@@ -4856,7 +4862,7 @@ class StorageService {
4856
4862
  else {
4857
4863
  storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}`;
4858
4864
  }
4859
- if (!isWeb) {
4865
+ if (env.isNative) {
4860
4866
  storageKey = normalizeKey(storageKey);
4861
4867
  }
4862
4868
  let valueToStore;
@@ -4883,7 +4889,7 @@ class StorageService {
4883
4889
  else {
4884
4890
  storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}`;
4885
4891
  }
4886
- if (!isWeb) {
4892
+ if (env.isNative) {
4887
4893
  storageKey = normalizeKey(storageKey);
4888
4894
  }
4889
4895
  return await this.removeItem(storageKey);
@@ -5148,11 +5154,14 @@ class StorageService {
5148
5154
  LocalStorageItems.AccessToken,
5149
5155
  LocalStorageItems.RefreshToken,
5150
5156
  V2KeyNames.EncryptedDevicePrivateKey,
5157
+ V2KeyNames.ClientAuthPublicKey,
5151
5158
  V2KeyNames.WallabyAuthPubKey,
5152
5159
  V2KeyNames.PasskeyCredential,
5153
5160
  V2KeyNames.MigrationVersion,
5154
5161
  V2KeyNames.LastMigratedAt,
5155
5162
  V2KeyNames.ClientAuthToken,
5163
+ V2KeyNames.PasswordResetAttempts,
5164
+ V2KeyNames.MigrationAttempts,
5156
5165
  ];
5157
5166
  await Promise.all(userKeysToRemove.map((key) => this.delete(key)));
5158
5167
  if (walletId) {
@@ -5199,11 +5208,11 @@ class StorageService {
5199
5208
  * @param jwt - The JWT string to check. If null, the function will return true.
5200
5209
  * @returns `true` if the JWT has expired or is null, otherwise `false`.
5201
5210
  */
5202
- function jwtHasExpired(jwt) {
5211
+ function jwtHasExpired(jwt, now = Date.now) {
5203
5212
  if (!jwt) {
5204
5213
  return true;
5205
5214
  }
5206
- return millisecondsToJWTTimeout(jwt) <= 0;
5215
+ return millisecondsToJWTTimeout(jwt, now) <= 0;
5207
5216
  }
5208
5217
  function jwtHasSameUser(jwt, userId) {
5209
5218
  if (!jwt || !userId) {
@@ -5223,11 +5232,11 @@ function userIsMfaVerified(jwt) {
5223
5232
  * @param thresholdSeconds - Number of seconds before expiry to consider "near expiry".
5224
5233
  * @returns `true` if the JWT expires within `thresholdSeconds` seconds, otherwise `false`.
5225
5234
  */
5226
- function isJwtNearExpiry(jwt, thresholdSeconds) {
5235
+ function isJwtNearExpiry(jwt, thresholdSeconds, now = Date.now) {
5227
5236
  if (!jwt) {
5228
5237
  return false;
5229
5238
  }
5230
- return millisecondsToJWTTimeout(jwt) <= thresholdSeconds * 1000;
5239
+ return millisecondsToJWTTimeout(jwt, now) <= thresholdSeconds * 1000;
5231
5240
  }
5232
5241
  /**
5233
5242
  * Calculates the remaining time in milliseconds until a given JWT expires.
@@ -5235,11 +5244,11 @@ function isJwtNearExpiry(jwt, thresholdSeconds) {
5235
5244
  * @param jwt - The JWT string to decode and check.
5236
5245
  * @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.
5237
5246
  */
5238
- function millisecondsToJWTTimeout(jwt) {
5247
+ function millisecondsToJWTTimeout(jwt, now = Date.now) {
5239
5248
  const jwtDecoded = jwtDecode(jwt);
5240
5249
  const jwtExpirationTimeSeconds = jwtDecoded.exp;
5241
5250
  const jwtExpirationTimeMilliseconds = (jwtExpirationTimeSeconds !== null && jwtExpirationTimeSeconds !== void 0 ? jwtExpirationTimeSeconds : 0) * 1000;
5242
- const timeNowMilliseconds = Date.now();
5251
+ const timeNowMilliseconds = now();
5243
5252
  return jwtExpirationTimeMilliseconds - timeNowMilliseconds;
5244
5253
  }
5245
5254
 
@@ -5284,6 +5293,11 @@ const AuthRoutes = {
5284
5293
  method: RequestMethod.Get,
5285
5294
  requiresAccessToken: true,
5286
5295
  },
5296
+ issueJwtToken: {
5297
+ fullPath: '/auth/issue-jwt-token',
5298
+ method: RequestMethod.Post,
5299
+ requiresAccessToken: false,
5300
+ },
5287
5301
  };
5288
5302
 
5289
5303
  class LockManagerService {
@@ -6883,8 +6897,8 @@ function shouldClearTokensAfterRefreshFailure(error) {
6883
6897
  // Module-level dedupe manager for token refresh to ensure only one refresh request per user/environment/network at a time
6884
6898
  const refreshDedupeManager = new DedupeManagerService();
6885
6899
  class Base {
6886
- constructor(config) {
6887
- var _a, _b;
6900
+ constructor(config, ports = {}) {
6901
+ var _a, _b, _c, _d, _e;
6888
6902
  const sanitizedConfig = sanitizeConfig(config);
6889
6903
  this.apiKey = sanitizedConfig.apiKey;
6890
6904
  this.baseUrl = sanitizedConfig.baseUrl;
@@ -6895,7 +6909,9 @@ class Base {
6895
6909
  env.isNative = this.options.platform === 'ios' || this.options.platform === 'android';
6896
6910
  env.isWeb = !env.isNative;
6897
6911
  }
6898
- this.cipher = new Cipher();
6912
+ this.cipher = (_b = ports.cipher) !== null && _b !== void 0 ? _b : new Cipher();
6913
+ this.transport = (_c = ports.transport) !== null && _c !== void 0 ? _c : ((...args) => fetch(...args));
6914
+ this.clock = (_d = ports.clock) !== null && _d !== void 0 ? _d : { now: () => Date.now() };
6899
6915
  this.lockManager = new LockManagerService();
6900
6916
  this._initializeClientAuthToken(sanitizedConfig.clientAuthToken);
6901
6917
  this.request = this.request.bind(this);
@@ -6909,6 +6925,7 @@ class Base {
6909
6925
  secure: true, // Enable security worker for all requests by default
6910
6926
  },
6911
6927
  securityWorker: this.securityWorker.bind(this),
6928
+ customFetch: this.transport,
6912
6929
  });
6913
6930
  /**
6914
6931
  * This intercepts all API responses and transforms errors into WallabyError format.
@@ -6953,7 +6970,7 @@ class Base {
6953
6970
  return attemptRequest(false);
6954
6971
  };
6955
6972
  this.api = new Api(httpClient);
6956
- 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));
6973
+ 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));
6957
6974
  }
6958
6975
  set setClientAuthToken(token) {
6959
6976
  this._initializeClientAuthToken(token);
@@ -7072,7 +7089,7 @@ class Base {
7072
7089
  // Proactive token refresh: if access token is near expiry, refresh before making the request
7073
7090
  if (route !== AuthRoutes.refreshAccessToken && !retried) {
7074
7091
  const accessToken = await this.localStorageService.fetch(LocalStorageItems.AccessToken);
7075
- if (accessToken && isJwtNearExpiry(accessToken, 60)) {
7092
+ if (accessToken && isJwtNearExpiry(accessToken, 60, this.clock.now)) {
7076
7093
  await this._performTokenRefresh();
7077
7094
  }
7078
7095
  }
@@ -7096,7 +7113,7 @@ class Base {
7096
7113
  fetchOptions.body = JSON.stringify(options.payload);
7097
7114
  }
7098
7115
  logger.debug(`SDK::Base::${route.method}::Request`, { path: fullUrl, payload: options === null || options === void 0 ? void 0 : options.payload });
7099
- const response = await fetch(fullUrl, fetchOptions);
7116
+ const response = await this.transport(fullUrl, fetchOptions);
7100
7117
  const contentType = response.headers.get('content-type');
7101
7118
  let data;
7102
7119
  if (contentType === null || contentType === void 0 ? void 0 : contentType.includes('application/json')) {
@@ -7167,7 +7184,7 @@ class Base {
7167
7184
  }
7168
7185
  async _getRequestHeaders() {
7169
7186
  const accessToken = await this.localStorageService.fetch(LocalStorageItems.AccessToken);
7170
- if (!isTest && jwtHasExpired(this.clientAuthToken)) {
7187
+ if (jwtHasExpired(this.clientAuthToken, this.clock.now)) {
7171
7188
  throw new WallabyError({
7172
7189
  message: 'Auth token has expired',
7173
7190
  statusCode: 401,
@@ -7189,7 +7206,7 @@ class Base {
7189
7206
  // Proactive token refresh before building headers for the generated client
7190
7207
  try {
7191
7208
  const accessToken = await this.localStorageService.fetch(LocalStorageItems.AccessToken);
7192
- if (accessToken && isJwtNearExpiry(accessToken, 60)) {
7209
+ if (accessToken && isJwtNearExpiry(accessToken, 60, this.clock.now)) {
7193
7210
  await this._performTokenRefresh();
7194
7211
  }
7195
7212
  }
@@ -7679,8 +7696,8 @@ function decodeBase64URL(base64url) {
7679
7696
  }
7680
7697
 
7681
7698
  let PasskeyService$1 = class PasskeyService {
7682
- constructor(userId, storageService, request) {
7683
- this.cipher = new Cipher();
7699
+ constructor(userId, storageService, request, cipher = new Cipher()) {
7700
+ this.cipher = cipher;
7684
7701
  this.localStorageService = storageService;
7685
7702
  this.userId = userId;
7686
7703
  this.request = request;
@@ -7980,7 +7997,6 @@ let PasskeyService$1 = class PasskeyService {
7980
7997
  }
7981
7998
  logger.log('SDK::PasskeyService::register:: getting signature', {
7982
7999
  message: challengeResponse.message,
7983
- privateKey: deviceKeyPair.privateKey,
7984
8000
  });
7985
8001
  const { signature, message } = await this.cipher.sign({
7986
8002
  message: challengeResponse.message,
@@ -8214,10 +8230,10 @@ function WithLock(lockKey) {
8214
8230
  }
8215
8231
 
8216
8232
  class AuthService extends Base {
8217
- constructor(config) {
8218
- super(config);
8233
+ constructor(config, ports = {}) {
8234
+ super(config, ports);
8219
8235
  this.getUserSalt = this.getUserSalt.bind(this);
8220
- this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request);
8236
+ this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request, this.cipher);
8221
8237
  }
8222
8238
  /**
8223
8239
  * @description
@@ -8637,7 +8653,7 @@ class AuthService extends Base {
8637
8653
  data: deviceKeyPair.privateKey,
8638
8654
  encryptionKey: credentialsKeyPair.publicKey,
8639
8655
  });
8640
- this.localStorageService.saveInBulk([
8656
+ await this.localStorageService.saveInBulk([
8641
8657
  {
8642
8658
  key: LocalStorageItems.EncryptedDevicePrivateKey,
8643
8659
  value: encryptedDevicePrivKey,
@@ -8708,6 +8724,24 @@ class AuthService extends Base {
8708
8724
  valid: true,
8709
8725
  };
8710
8726
  }
8727
+ /**
8728
+ * @description Exchanges the client JWT (set at SDK initialisation) for a
8729
+ * Wallaby access + refresh token pair. Tokens are persisted to storage so
8730
+ * subsequent SDK calls use them automatically.
8731
+ * @returns {Promise<IssueJWTTokenResponseDto>} The issued access/refresh tokens and basic user info.
8732
+ */
8733
+ async exchangeClientToken() {
8734
+ try {
8735
+ const response = await this.request(AuthRoutes.issueJwtToken);
8736
+ await this.localStorageService.save(LocalStorageItems.AccessToken, response.accessToken);
8737
+ await this.localStorageService.save(LocalStorageItems.RefreshToken, response.refreshToken);
8738
+ return response;
8739
+ }
8740
+ catch (error) {
8741
+ logger.error('SDK::Auth::exchangeClientToken::error', error);
8742
+ throw error;
8743
+ }
8744
+ }
8711
8745
  }
8712
8746
  __decorate([
8713
8747
  WithLock('signUp'),
@@ -8728,10 +8762,67 @@ __decorate([
8728
8762
  __metadata("design:returntype", Promise)
8729
8763
  ], AuthService.prototype, "storeDeviceKeyPair", null);
8730
8764
 
8765
+ const ENCRYPTED_PAYLOAD_FIELDS = ['iv', 'ephemPublicKey', 'ciphertext', 'mac'];
8766
+ // Backup share may be ECIES or symmetric ({ iv, ciphertext, mac, tag }) — both share these three fields.
8767
+ const SYMMETRIC_PAYLOAD_FIELDS = ['iv', 'ciphertext', 'mac', 'tag'];
8768
+ // API is the trust boundary: confirm every named field is a non-empty string.
8769
+ function hasNonEmptyStringFields(payload, fields) {
8770
+ return (!!payload &&
8771
+ typeof payload === 'object' &&
8772
+ fields.every((field) => {
8773
+ const value = payload[field];
8774
+ return typeof value === 'string' && value.length > 0;
8775
+ }));
8776
+ }
8777
+ /**
8778
+ * Fail fast if an encrypted payload from the API does not match the expected
8779
+ * ECIES structure ({ iv, ephemPublicKey, ciphertext, mac }). See the contract
8780
+ * note on `handleKeySharesFromResponse`.
8781
+ */
8782
+ function assertEncryptedPayloadShape(encrypted) {
8783
+ if (!hasNonEmptyStringFields(encrypted, ENCRYPTED_PAYLOAD_FIELDS)) {
8784
+ throw new WallabyError({
8785
+ message: 'Encrypted share does not match the expected { iv, ephemPublicKey, ciphertext, mac } format.',
8786
+ statusCode: 422,
8787
+ errorCode: ErrorResponseCodes.sdk_invalid_parameter,
8788
+ });
8789
+ }
8790
+ }
8791
+ /**
8792
+ * Shape-assert every share returned by the API. Empty arrays are rejected here
8793
+ * so callers get a clean error instead of crashing on `shares[0]`.
8794
+ */
8795
+ function assertSharesPayloadShape(shares) {
8796
+ if (!shares.length) {
8797
+ throw new WallabyError({
8798
+ message: 'No key shares were returned from the API.',
8799
+ statusCode: 422,
8800
+ errorCode: ErrorResponseCodes.sdk_invalid_parameter,
8801
+ });
8802
+ }
8803
+ for (const share of shares) {
8804
+ assertEncryptedPayloadShape(share.encrypted);
8805
+ }
8806
+ }
8807
+ /**
8808
+ * The backup share is stored as-is (the device can't peel it), so we only
8809
+ * shape-check it. It may be ECIES or symmetric, so accept either variant.
8810
+ */
8811
+ function assertBackupSharePayloadShape(encrypted) {
8812
+ const isEcies = hasNonEmptyStringFields(encrypted, ENCRYPTED_PAYLOAD_FIELDS);
8813
+ const isSymmetric = hasNonEmptyStringFields(encrypted, SYMMETRIC_PAYLOAD_FIELDS);
8814
+ if (!isEcies && !isSymmetric) {
8815
+ throw new WallabyError({
8816
+ message: 'Encrypted backup share does not match the expected ECIES ({ iv, ephemPublicKey, ciphertext, mac }) or symmetric ({ iv, ciphertext, mac, tag }) format.',
8817
+ statusCode: 422,
8818
+ errorCode: ErrorResponseCodes.sdk_invalid_parameter,
8819
+ });
8820
+ }
8821
+ }
8731
8822
  class WalletHandlersService extends Base {
8732
- constructor(config) {
8733
- super(config);
8734
- this.authService = new AuthService(config);
8823
+ constructor(config, ports = {}) {
8824
+ super(config, ports);
8825
+ this.authService = new AuthService(config, ports);
8735
8826
  this.userId = config.userId;
8736
8827
  }
8737
8828
  async handleImportWallet(deviceAuthKeys, importWalletInput) {
@@ -8808,6 +8899,7 @@ class WalletHandlersService extends Base {
8808
8899
  shares: importWalletRequest.shares,
8809
8900
  credentialsKeyPair,
8810
8901
  encryptedBackupShare: importWalletRequest.encryptedBackupShare,
8902
+ devicePrivateKey: deviceAuthKeys.privateKey,
8811
8903
  });
8812
8904
  }
8813
8905
  return Object.assign({}, importWalletRequest);
@@ -8894,6 +8986,7 @@ class WalletHandlersService extends Base {
8894
8986
  shares: walletCreationResponse.shares,
8895
8987
  credentialsKeyPair,
8896
8988
  encryptedBackupShare: walletCreationResponse.encryptedBackupShare,
8989
+ devicePrivateKey: deviceAuthKeys.privateKey,
8897
8990
  });
8898
8991
  }
8899
8992
  return Object.assign(Object.assign({}, walletCreationResponse), { standardSeedPhrase: decryptedSeedPhrase });
@@ -8909,8 +9002,41 @@ class WalletHandlersService extends Base {
8909
9002
  });
8910
9003
  }
8911
9004
  }
8912
- async handleKeySharesFromResponse({ walletId, shares, credentialsKeyPair, encryptedBackupShare, }) {
9005
+ /**
9006
+ * Encrypted share format contract (WAL-1467)
9007
+ * --------------------------------------------------------------------------
9008
+ * Every flow that ingests shares from the API (import, create, recover,
9009
+ * addNewDevice) routes through here, so the contract is asserted in one place.
9010
+ *
9011
+ * The API returns the main device share as `shares[0]`, an ECIES payload
9012
+ * ({ iv, ephemPublicKey, ciphertext, mac }) wrapped to the device public key,
9013
+ * so it MUST peel with the device private key. `encryptedBackupShare` is an
9014
+ * already-wrapped blob (ECIES or symmetric) that the device cannot decrypt, so
9015
+ * it is stored as-is.
9016
+ *
9017
+ * We shape-assert every share (and the backup share) here, at ingestion, so a
9018
+ * server-side wrapping change fails loudly now instead of silently breaking
9019
+ * export/recovery later.
9020
+ */
9021
+ async handleKeySharesFromResponse({ walletId, shares, credentialsKeyPair, encryptedBackupShare, devicePrivateKey, }) {
8913
9022
  try {
9023
+ assertSharesPayloadShape(shares);
9024
+ assertBackupSharePayloadShape(encryptedBackupShare);
9025
+ // Decrypt-test the contract: shares[0] is wrapped to the device public key and must peel with the device private key.
9026
+ try {
9027
+ await this.cipher.decrypt({
9028
+ cipherText: shares[0].encrypted,
9029
+ decryptionKey: devicePrivateKey,
9030
+ });
9031
+ }
9032
+ catch (error) {
9033
+ throw new WallabyError({
9034
+ message: 'Device-wrapped key share (shares[0]) could not be decrypted with the device private key; the share wrapping format may have changed.',
9035
+ statusCode: 422,
9036
+ errorCode: ErrorResponseCodes.sdk_key_share_decryption_failed,
9037
+ cause: error,
9038
+ });
9039
+ }
8914
9040
  const encryptedWithCredentialsKeyShare = await this.cipher.encrypt({
8915
9041
  data: JSON.stringify(shares[0].encrypted),
8916
9042
  encryptionKey: credentialsKeyPair.publicKey,
@@ -9002,14 +9128,43 @@ class WalletHandlersService extends Base {
9002
9128
  }
9003
9129
 
9004
9130
  class WalletService extends Base {
9005
- constructor(config) {
9006
- super(config);
9007
- this.passwordResetAttempts = 0;
9008
- this.migrationAttempts = 0;
9009
- this.authService = new AuthService(config);
9010
- this.handlers = new WalletHandlersService(config);
9131
+ constructor(config, ports = {}) {
9132
+ super(config, ports);
9133
+ this.authService = new AuthService(config, ports);
9134
+ this.handlers = new WalletHandlersService(config, ports);
9011
9135
  this.userId = config.userId;
9012
- this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request);
9136
+ this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request, this.cipher);
9137
+ }
9138
+ /**
9139
+ * Reads the persisted sliding-window rate-limit state for a counter key.
9140
+ * Returns a fresh window ({ count: 0 }) when none is stored or the window has expired.
9141
+ */
9142
+ async getRateState(key) {
9143
+ const now = Date.now();
9144
+ const raw = await this.localStorageService.fetch(key);
9145
+ const state = raw ? safeJsonParse(raw) : undefined;
9146
+ if (!state || now - state.windowStart > WalletService.RATE_LIMIT_WINDOW_MS) {
9147
+ return { count: 0, windowStart: now };
9148
+ }
9149
+ return state;
9150
+ }
9151
+ /** Increments and persists the counter (resetting an expired window). Returns the new count. */
9152
+ async recordRateAttempt(key) {
9153
+ const state = await this.getRateState(key);
9154
+ state.count += 1;
9155
+ await this.localStorageService.save(key, JSON.stringify(state));
9156
+ return state.count;
9157
+ }
9158
+ /** Throws a 429 when the counter is already over the limit, without incrementing it. */
9159
+ async assertUnderRateLimit(key, message) {
9160
+ const { count } = await this.getRateState(key);
9161
+ if (count > WalletService.RATE_LIMIT_MAX) {
9162
+ throw new WallabyError({
9163
+ message,
9164
+ statusCode: 429,
9165
+ errorCode: ErrorResponseCodes.sdk_too_many_requests,
9166
+ });
9167
+ }
9013
9168
  }
9014
9169
  /**
9015
9170
  * @public
@@ -9116,20 +9271,7 @@ class WalletService extends Base {
9116
9271
  });
9117
9272
  }
9118
9273
  if (this.deviceAuthType === AuthType.Password && authenticationOptions.password) {
9119
- try {
9120
- await this.handleUpdateToV2({
9121
- password: authenticationOptions.password,
9122
- walletId: walletId,
9123
- });
9124
- }
9125
- catch (error) {
9126
- logger.error('SDK::WalletService::export::handleUpdateToV2::error', error);
9127
- throw new WallabyError({
9128
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
9129
- statusCode: 500,
9130
- errorCode: ErrorResponseCodes.sdk_unknown_error,
9131
- });
9132
- }
9274
+ await this.migrateToV2Safe({ password: authenticationOptions.password, walletId });
9133
9275
  }
9134
9276
  const encryptedSeed = await this.localStorageService.fetch(LocalStorageItems.EncryptedStandardSeedPhrase, { walletId });
9135
9277
  const encryptedPrimaryDeviceShare = await this.localStorageService.fetch(LocalStorageItems.PrimaryDeviceKeyShare, {
@@ -9372,6 +9514,7 @@ class WalletService extends Base {
9372
9514
  shares: recoverWithSeedPhraseResponse.shares,
9373
9515
  credentialsKeyPair,
9374
9516
  encryptedBackupShare: recoverWithSeedPhraseResponse.encryptedBackupShare,
9517
+ devicePrivateKey: deviceAuthKeyPair.privateKey,
9375
9518
  });
9376
9519
  }
9377
9520
  await this.authService.storeDeviceKeyPair({
@@ -9435,6 +9578,7 @@ class WalletService extends Base {
9435
9578
  shares: recoverWithSeedPhraseResponse.shares,
9436
9579
  credentialsKeyPair,
9437
9580
  encryptedBackupShare: recoverWithSeedPhraseResponse.encryptedBackupShare,
9581
+ devicePrivateKey: deviceAuthKeyPair.privateKey,
9438
9582
  });
9439
9583
  }
9440
9584
  await this.authService.storeDeviceKeyPair({
@@ -9467,8 +9611,7 @@ class WalletService extends Base {
9467
9611
  */
9468
9612
  async changePassword({ walletId, oldPassword, newPassword, }) {
9469
9613
  try {
9470
- this.passwordResetAttempts += 1;
9471
- if (this.passwordResetAttempts > 5) {
9614
+ if ((await this.recordRateAttempt(V2KeyNames.PasswordResetAttempts)) > WalletService.RATE_LIMIT_MAX) {
9472
9615
  throw new WallabyError({
9473
9616
  message: 'Too many password change attempts. Please try again later.',
9474
9617
  statusCode: 429,
@@ -9477,20 +9620,7 @@ class WalletService extends Base {
9477
9620
  }
9478
9621
  if (this.deviceAuthType === AuthType.Password && oldPassword) {
9479
9622
  // Handle migration to V2 first then change the password to the new one.
9480
- try {
9481
- await this.handleUpdateToV2({
9482
- password: oldPassword,
9483
- walletId,
9484
- });
9485
- }
9486
- catch (error) {
9487
- logger.error('SDK::WalletService::changePassword::handleUpdateToV2::error', error);
9488
- throw new WallabyError({
9489
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
9490
- statusCode: 500,
9491
- errorCode: ErrorResponseCodes.sdk_unknown_error,
9492
- });
9493
- }
9623
+ await this.migrateToV2Safe({ password: oldPassword, walletId });
9494
9624
  }
9495
9625
  const encryptedDevicePrivateKeyString = await this.localStorageService.fetch(V2KeyNames.EncryptedDevicePrivateKey);
9496
9626
  const encryptedSeedPhraseString = await this.localStorageService.fetch(V2KeyNames.EncryptedStandardSeedPhrase, {
@@ -9547,40 +9677,41 @@ class WalletService extends Base {
9547
9677
  errorCode: ErrorResponseCodes.sdk_unknown_error,
9548
9678
  });
9549
9679
  }
9550
- await this.localStorageService.save(LocalStorageItems.EncryptedDevicePrivateKey, reWrappedDevicePrivateKey);
9551
- if (encryptedSeedPhraseString) {
9552
- const parsedSeed = safeJsonParse(encryptedSeedPhraseString);
9553
- const reWrappedSeedPhrase = await this.cipher.flipEncryptedData({
9554
- cipherText: parsedSeed,
9680
+ const reWrappedSeedPhrase = encryptedSeedPhraseString
9681
+ ? await this.cipher.flipEncryptedData({
9682
+ cipherText: safeJsonParse(encryptedSeedPhraseString),
9555
9683
  decryptionKey: oldCredentialsKeyPair.privateKey,
9556
9684
  encryptionKey: newCredentialsKeyPair.publicKey,
9557
- });
9558
- await this.localStorageService.save(LocalStorageItems.EncryptedStandardSeedPhrase, reWrappedSeedPhrase, {
9559
- walletId,
9560
- });
9561
- }
9562
- if (encryptedPrimaryShareString) {
9563
- const parsedPrimaryShare = safeJsonParse(encryptedPrimaryShareString);
9564
- const reWrappedPrimaryShare = await this.cipher.flipEncryptedData({
9565
- cipherText: parsedPrimaryShare,
9685
+ })
9686
+ : null;
9687
+ const reWrappedPrimaryShare = encryptedPrimaryShareString
9688
+ ? await this.cipher.flipEncryptedData({
9689
+ cipherText: safeJsonParse(encryptedPrimaryShareString),
9566
9690
  decryptionKey: oldCredentialsKeyPair.privateKey,
9567
9691
  encryptionKey: newCredentialsKeyPair.publicKey,
9568
- });
9569
- await this.localStorageService.save(LocalStorageItems.PrimaryDeviceKeyShare, reWrappedPrimaryShare, {
9570
- walletId,
9571
- });
9572
- }
9573
- if (encryptedBackupShareString) {
9574
- const parsedBackupShare = safeJsonParse(encryptedBackupShareString);
9575
- const reWrappedBackupShare = await this.cipher.flipEncryptedData({
9576
- cipherText: parsedBackupShare,
9692
+ })
9693
+ : null;
9694
+ const reWrappedBackupShare = encryptedBackupShareString
9695
+ ? await this.cipher.flipEncryptedData({
9696
+ cipherText: safeJsonParse(encryptedBackupShareString),
9577
9697
  decryptionKey: oldCredentialsKeyPair.privateKey,
9578
9698
  encryptionKey: newCredentialsKeyPair.publicKey,
9579
- });
9580
- await this.localStorageService.save(LocalStorageItems.BackupDeviceKeyShare, reWrappedBackupShare, {
9581
- walletId,
9582
- });
9583
- }
9699
+ })
9700
+ : null;
9701
+ // Commit all re-wrapped blobs in one batch so a partial failure cannot leave the device
9702
+ // in a half-migrated state (some items under the new password, others under the old).
9703
+ await this.localStorageService.saveInBulk([
9704
+ { key: LocalStorageItems.EncryptedDevicePrivateKey, value: reWrappedDevicePrivateKey },
9705
+ ...(reWrappedSeedPhrase
9706
+ ? [{ key: LocalStorageItems.EncryptedStandardSeedPhrase, value: reWrappedSeedPhrase, walletId }]
9707
+ : []),
9708
+ ...(reWrappedPrimaryShare
9709
+ ? [{ key: LocalStorageItems.PrimaryDeviceKeyShare, value: reWrappedPrimaryShare, walletId }]
9710
+ : []),
9711
+ ...(reWrappedBackupShare ? [{ key: LocalStorageItems.BackupDeviceKeyShare, value: reWrappedBackupShare, walletId }] : []),
9712
+ ]);
9713
+ // Reset the rate-limit window on success so a normal change does not count against future ones.
9714
+ await this.localStorageService.delete(V2KeyNames.PasswordResetAttempts);
9584
9715
  return true;
9585
9716
  }
9586
9717
  catch (error) {
@@ -9633,20 +9764,7 @@ class WalletService extends Base {
9633
9764
  }
9634
9765
  const parsedEncryptedDevicePrivateKey = safeJsonParse(encryptedDevicePrivateKey);
9635
9766
  if (this.deviceAuthType === AuthType.Password && input.authenticationOptions.password) {
9636
- try {
9637
- await this.handleUpdateToV2({
9638
- password: input.authenticationOptions.password,
9639
- walletId: input.walletId,
9640
- });
9641
- }
9642
- catch (error) {
9643
- logger.error('SDK::WalletService::initAddNewDevice::handleUpdateToV2::error', error);
9644
- throw new WallabyError({
9645
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
9646
- statusCode: 500,
9647
- errorCode: ErrorResponseCodes.sdk_unknown_error,
9648
- });
9649
- }
9767
+ await this.migrateToV2Safe({ password: input.authenticationOptions.password, walletId: input.walletId });
9650
9768
  }
9651
9769
  const storedEncryptedBackupShare = await this.localStorageService.fetch(LocalStorageItems.BackupDeviceKeyShare, { walletId });
9652
9770
  if (!storedEncryptedBackupShare) {
@@ -9744,6 +9862,7 @@ class WalletService extends Base {
9744
9862
  shares: [backUpResponse.share],
9745
9863
  credentialsKeyPair,
9746
9864
  encryptedBackupShare: input.encryptedBackupShare,
9865
+ devicePrivateKey: decryptedDevicePrivateKey,
9747
9866
  });
9748
9867
  return { success: true, reference: backUpResponse.reference };
9749
9868
  }
@@ -9762,20 +9881,7 @@ class WalletService extends Base {
9762
9881
  });
9763
9882
  }
9764
9883
  if (this.deviceAuthType === AuthType.Password && input.authenticationOptions.password) {
9765
- try {
9766
- await this.handleUpdateToV2({
9767
- password: input.authenticationOptions.password,
9768
- walletId: input.walletId,
9769
- });
9770
- }
9771
- catch (error) {
9772
- logger.error('SDK::WalletService::generateWalletAddresses::handleUpdateToV2::error', error);
9773
- throw new WallabyError({
9774
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
9775
- statusCode: 500,
9776
- errorCode: ErrorResponseCodes.sdk_unknown_error,
9777
- });
9778
- }
9884
+ await this.migrateToV2Safe({ password: input.authenticationOptions.password, walletId: input.walletId });
9779
9885
  }
9780
9886
  try {
9781
9887
  const walletOperationAuth = await this.prepareWalletOperationAuth({
@@ -9800,6 +9906,23 @@ class WalletService extends Base {
9800
9906
  throw error;
9801
9907
  }
9802
9908
  }
9909
+ /**
9910
+ * Wraps handleUpdateToV2 with the standard user-facing error. All call sites that gate on
9911
+ * `AuthType.Password` should go through here so the error message stays consistent.
9912
+ */
9913
+ async migrateToV2Safe({ password, walletId }) {
9914
+ try {
9915
+ await this.handleUpdateToV2({ password, walletId });
9916
+ }
9917
+ catch (error) {
9918
+ logger.error('SDK::WalletService::migrateToV2Safe::error', error);
9919
+ throw new WallabyError({
9920
+ message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
9921
+ statusCode: 500,
9922
+ errorCode: ErrorResponseCodes.sdk_unknown_error,
9923
+ });
9924
+ }
9925
+ }
9803
9926
  /**
9804
9927
  * Detects and migrates legacy/v1 storage items to v2 format.
9805
9928
  * This function should be called in methods that use password as input when v2 items are missing.
@@ -9808,13 +9931,7 @@ class WalletService extends Base {
9808
9931
  */
9809
9932
  async handleUpdateToV2({ password, walletId }) {
9810
9933
  const migrationStartTime = Date.now();
9811
- if (this.migrationAttempts > 5) {
9812
- throw new WallabyError({
9813
- message: 'Too many migration attempts. Please try again later.',
9814
- statusCode: 429,
9815
- errorCode: ErrorResponseCodes.sdk_too_many_requests,
9816
- });
9817
- }
9934
+ await this.assertUnderRateLimit(V2KeyNames.MigrationAttempts, 'Too many migration attempts. Please try again later.');
9818
9935
  try {
9819
9936
  if (!password) {
9820
9937
  throw new WallabyError({
@@ -9885,7 +10002,7 @@ class WalletService extends Base {
9885
10002
  }
9886
10003
  }
9887
10004
  // Increment counter after V2 validation to avoid counting when migration not needed
9888
- this.migrationAttempts += 1;
10005
+ await this.recordRateAttempt(V2KeyNames.MigrationAttempts);
9889
10006
  let decryptedSeedPhrase;
9890
10007
  let decryptedPrivateKey;
9891
10008
  // Check for legacy format: `{item}_{userId}`
@@ -9938,7 +10055,10 @@ class WalletService extends Base {
9938
10055
  try {
9939
10056
  // Decrypt V1 items using storage service method (handles double encryption)
9940
10057
  logger.log('Attempting to decrypt V1 items during migration...');
9941
- logger.log('getV1DecryptedSeedPhrase should be called with password and clientSalt:', { password, clientSalt });
10058
+ logger.log('getV1DecryptedSeedPhrase should be called with password and clientSalt:', {
10059
+ hasPassword: !!password,
10060
+ hasClientSalt: !!clientSalt,
10061
+ });
9942
10062
  decryptedSeedPhrase = await this.localStorageService.getV1DecryptedSeedPhrase(password, clientSalt);
9943
10063
  // For V1 format, private key is encrypted with just the password (not salt+password like legacy)
9944
10064
  decryptedPrivateKey = await this.localStorageService.getDecryptedV1PrivateKey(password);
@@ -10403,6 +10523,10 @@ class WalletService extends Base {
10403
10523
  }
10404
10524
  }
10405
10525
  }
10526
+ // ponytail: soft client-side guardrail against runaway retries; server-side rate limiting is the real control.
10527
+ // Counters are persisted (sliding window) so rebuilding the service no longer resets them. Tune freely.
10528
+ WalletService.RATE_LIMIT_MAX = 5;
10529
+ WalletService.RATE_LIMIT_WINDOW_MS = 30 * 60000; // 30 min
10406
10530
  __decorate([
10407
10531
  WithLock('create'),
10408
10532
  __metadata("design:type", Function),
@@ -10435,10 +10559,10 @@ __decorate([
10435
10559
  ], WalletService.prototype, "handleUpdateToV2", null);
10436
10560
 
10437
10561
  class WalletDataService extends Base {
10438
- constructor(config) {
10439
- super(config);
10562
+ constructor(config, ports = {}) {
10563
+ super(config, ports);
10440
10564
  this.userId = config.userId;
10441
- this.walletService = new WalletService(config);
10565
+ this.walletService = new WalletService(config, ports);
10442
10566
  }
10443
10567
  /**
10444
10568
  * @description Validates the wallet address info for a given blockchain.
@@ -10685,20 +10809,7 @@ class WalletDataService extends Base {
10685
10809
  });
10686
10810
  }
10687
10811
  if (this.deviceAuthType === AuthType.Password && authenticationOptions.password) {
10688
- try {
10689
- await this.walletService.handleUpdateToV2({
10690
- password: authenticationOptions.password,
10691
- walletId: walletId,
10692
- });
10693
- }
10694
- catch (error) {
10695
- logger.error('SDK::WalletDataService::addNewChainAndTokenToWallet::handleUpdateToV2::error', error);
10696
- throw new WallabyError({
10697
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
10698
- statusCode: 500,
10699
- errorCode: ErrorResponseCodes.sdk_unknown_error,
10700
- });
10701
- }
10812
+ await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
10702
10813
  }
10703
10814
  try {
10704
10815
  const addressInfo = await this.walletService.generateWalletAddresses({
@@ -10772,8 +10883,8 @@ class WalletDataService extends Base {
10772
10883
  }
10773
10884
 
10774
10885
  class Utils extends Base {
10775
- constructor(config) {
10776
- super(config);
10886
+ constructor(config, ports = {}) {
10887
+ super(config, ports);
10777
10888
  /**
10778
10889
  *
10779
10890
  * Decrypts user private key
@@ -10806,7 +10917,7 @@ class Utils extends Base {
10806
10917
  return undefined;
10807
10918
  }
10808
10919
  };
10809
- this.auth = new AuthService(config);
10920
+ this.auth = new AuthService(config, ports);
10810
10921
  }
10811
10922
  /**
10812
10923
  *
@@ -10899,179 +11010,6 @@ class Utils extends Base {
10899
11010
  }
10900
11011
  }
10901
11012
 
10902
- const MerchantsRoutes = {
10903
- create: {
10904
- fullPath: '/merchants',
10905
- method: RequestMethod.Post,
10906
- requiresAccessToken: false,
10907
- },
10908
- update: {
10909
- fullPath: ({ merchantId }) => `/merchants/${merchantId}`,
10910
- method: RequestMethod.Put,
10911
- requiresAccessToken: false,
10912
- },
10913
- getMerchantData: {
10914
- fullPath: ({ merchantId }) => `/merchants/${merchantId}`,
10915
- method: RequestMethod.Get,
10916
- requiresAccessToken: false,
10917
- },
10918
- list: {
10919
- fullPath: '/merchants',
10920
- method: RequestMethod.Get,
10921
- requiresAccessToken: false,
10922
- },
10923
- getAssets: {
10924
- fullPath: () => `/users/merchant/assets`,
10925
- method: RequestMethod.Get,
10926
- requiresAccessToken: true,
10927
- },
10928
- addAsset: {
10929
- fullPath: ({ merchantId, configId }) => `/merchants/${merchantId}/assets/${configId}`,
10930
- method: RequestMethod.Post,
10931
- requiresAccessToken: false,
10932
- },
10933
- deleteAsset: {
10934
- fullPath: ({ merchantId, configId }) => `/merchants/${merchantId}/assets/${configId}`,
10935
- method: RequestMethod.Delete,
10936
- requiresAccessToken: false,
10937
- },
10938
- };
10939
-
10940
- class Merchants extends Base {
10941
- constructor(config) {
10942
- super(config);
10943
- }
10944
- /**
10945
- * @description
10946
- * Retrieves the merchant ID from access token `aud` claim.
10947
- * Even though merchantId is possibly undefined. If an access token is not stored on device, the request will most likely
10948
- * not have it in headers and will fail with 401 regardless.
10949
- *
10950
- * @returns { string | undefined } Merchant ID
10951
- */
10952
- async _getMerchantId() {
10953
- const accessToken = await this.localStorageService.fetch(LocalStorageItems.AccessToken);
10954
- if (!accessToken)
10955
- return;
10956
- const jwtDecoded = jwtDecode(accessToken);
10957
- return jwtDecoded.aud;
10958
- }
10959
- /**
10960
- *
10961
- * @public
10962
- * List of all merchants in the system
10963
- * @returns { ListMerchantsResponse } Array of all merchants
10964
- */
10965
- async list() {
10966
- try {
10967
- const response = await this.request(MerchantsRoutes.list, {
10968
- payload: {},
10969
- });
10970
- return response;
10971
- }
10972
- catch (error) {
10973
- logger.error('SDK::Merchants::list::error', error);
10974
- return Promise.reject(error);
10975
- }
10976
- }
10977
- /**
10978
- *
10979
- * @public
10980
- * Allows to create a new merchant
10981
- * @returns { Merchant } Merchant data
10982
- */
10983
- async create({ name }) {
10984
- try {
10985
- const response = await this.request(MerchantsRoutes.create, {
10986
- payload: { name },
10987
- });
10988
- return response;
10989
- }
10990
- catch (error) {
10991
- logger.error('SDK::Merchants::list::error', error);
10992
- return Promise.reject(error);
10993
- }
10994
- }
10995
- /**
10996
- *
10997
- * @public
10998
- * Allows to update merchant data
10999
- * @returns { Merchant } Merchant data
11000
- */
11001
- async update({ name, status }) {
11002
- try {
11003
- const merchantId = await this._getMerchantId();
11004
- const response = await this.request(MerchantsRoutes.update, {
11005
- payload: { merchantId, name, status },
11006
- });
11007
- return response;
11008
- }
11009
- catch (error) {
11010
- logger.error('SDK::Merchants::list::error', error);
11011
- return Promise.reject(error);
11012
- }
11013
- }
11014
- /**
11015
- *
11016
- * @public
11017
- * @returns { Merchant } Merchant data
11018
- */
11019
- async getMerchantData() {
11020
- try {
11021
- const merchantId = await this._getMerchantId();
11022
- const response = await this.request(MerchantsRoutes.getMerchantData, {
11023
- payload: { merchantId },
11024
- });
11025
- return response.merchant;
11026
- }
11027
- catch (error) {
11028
- logger.error('SDK::Merchants::list::error', error);
11029
- return Promise.reject(error);
11030
- }
11031
- }
11032
- /**
11033
- *
11034
- * @public
11035
- * @returns { MerchantAsset[] } List of merchant assets
11036
- */
11037
- async getAssets() {
11038
- try {
11039
- const response = await this.request(MerchantsRoutes.getAssets);
11040
- return response.merchantAssets;
11041
- }
11042
- catch (error) {
11043
- logger.error('SDK::Merchants::list::error', error);
11044
- return Promise.reject(error);
11045
- }
11046
- }
11047
- async addAsset({ configId }) {
11048
- try {
11049
- const merchantId = await this._getMerchantId();
11050
- const response = await this.request(MerchantsRoutes.addAsset, {
11051
- payload: { merchantId, configId },
11052
- });
11053
- return response;
11054
- }
11055
- catch (error) {
11056
- logger.error('SDK::Merchants::list::error', error);
11057
- return Promise.reject(error);
11058
- }
11059
- }
11060
- async deleteAsset({ configId }) {
11061
- try {
11062
- const merchantId = await this._getMerchantId();
11063
- const response = await this.request(MerchantsRoutes.deleteAsset, {
11064
- payload: { merchantId, configId },
11065
- });
11066
- return response;
11067
- }
11068
- catch (error) {
11069
- logger.error('SDK::Merchants::list::error', error);
11070
- return Promise.reject(error);
11071
- }
11072
- }
11073
- }
11074
-
11075
11013
  /**
11076
11014
  * HttpApi provides direct access to all REST API endpoints.
11077
11015
  * This class extends the Base class and includes the generated API client
@@ -11086,16 +11024,16 @@ class HttpApi extends Base {
11086
11024
  * @param config - The Wallaby configuration object
11087
11025
  * @public
11088
11026
  */
11089
- constructor(config) {
11090
- super(config);
11027
+ constructor(config, ports = {}) {
11028
+ super(config, ports);
11091
11029
  }
11092
11030
  }
11093
11031
 
11094
11032
  class Swap extends Base {
11095
- constructor(config) {
11096
- super(config);
11097
- this.authService = new AuthService(config);
11098
- this.walletService = new WalletService(config);
11033
+ constructor(config, ports = {}) {
11034
+ super(config, ports);
11035
+ this.authService = new AuthService(config, ports);
11036
+ this.walletService = new WalletService(config, ports);
11099
11037
  }
11100
11038
  /**
11101
11039
  * Gets a swap quote between two assets, including fees, min output, and slippage limits.
@@ -11152,20 +11090,7 @@ class Swap extends Base {
11152
11090
  try {
11153
11091
  // Only attempt migration if we have password auth and V2 storage might be incomplete
11154
11092
  if (this.deviceAuthType === AuthType.Password && authenticationOptions.password) {
11155
- try {
11156
- await this.walletService.handleUpdateToV2({
11157
- password: authenticationOptions.password,
11158
- walletId: walletId,
11159
- });
11160
- }
11161
- catch (error) {
11162
- logger.error('SDK::Swap::executeSwap::handleUpdateToV2::error', error);
11163
- throw new WallabyError({
11164
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
11165
- statusCode: 500,
11166
- errorCode: ErrorResponseCodes.sdk_unknown_error,
11167
- });
11168
- }
11093
+ await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
11169
11094
  }
11170
11095
  const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareSwapAuth(authenticationOptions, walletId);
11171
11096
  let swapResponse;
@@ -11361,8 +11286,8 @@ const sanitizeSuiObjectId = (objectId) => {
11361
11286
  };
11362
11287
 
11363
11288
  class System extends Base {
11364
- constructor(config) {
11365
- super(config);
11289
+ constructor(config, ports = {}) {
11290
+ super(config, ports);
11366
11291
  }
11367
11292
  /**
11368
11293
  * @public
@@ -11555,10 +11480,10 @@ class System extends Base {
11555
11480
  }
11556
11481
 
11557
11482
  class Transactions extends Base {
11558
- constructor(config) {
11559
- super(config);
11560
- this.authService = new AuthService(config);
11561
- this.walletService = new WalletService(config);
11483
+ constructor(config, ports = {}) {
11484
+ super(config, ports);
11485
+ this.authService = new AuthService(config, ports);
11486
+ this.walletService = new WalletService(config, ports);
11562
11487
  this.userId = config.userId;
11563
11488
  }
11564
11489
  /**
@@ -11681,20 +11606,7 @@ class Transactions extends Base {
11681
11606
  try {
11682
11607
  // Only attempt migration if we have password auth and V2 storage might be incomplete
11683
11608
  if (this.deviceAuthType === AuthType.Password && authenticationOptions.password) {
11684
- try {
11685
- await this.walletService.handleUpdateToV2({
11686
- password: authenticationOptions.password,
11687
- walletId: walletId,
11688
- });
11689
- }
11690
- catch (error) {
11691
- logger.error('SDK::Transactions::transfer::handleUpdateToV2::error', error);
11692
- throw new WallabyError({
11693
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
11694
- statusCode: 500,
11695
- errorCode: ErrorResponseCodes.sdk_unknown_error,
11696
- });
11697
- }
11609
+ await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
11698
11610
  }
11699
11611
  const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareTransactionAuth(authenticationOptions, walletId);
11700
11612
  let transferResponse;
@@ -11782,20 +11694,7 @@ class Transactions extends Base {
11782
11694
  }
11783
11695
  // Only attempt migration if we have password auth and V2 storage might be incomplete
11784
11696
  if (this.deviceAuthType === AuthType.Password && authenticationOptions.password) {
11785
- try {
11786
- await this.walletService.handleUpdateToV2({
11787
- password: authenticationOptions.password,
11788
- walletId: walletId,
11789
- });
11790
- }
11791
- catch (error) {
11792
- logger.error('SDK::Transactions::createAllowance::handleUpdateToV2::error', error);
11793
- throw new WallabyError({
11794
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
11795
- statusCode: 500,
11796
- errorCode: ErrorResponseCodes.sdk_unknown_error,
11797
- });
11798
- }
11697
+ await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
11799
11698
  }
11800
11699
  const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareTransactionAuth(authenticationOptions, walletId);
11801
11700
  const { message, signature } = signatureMessage;
@@ -11860,20 +11759,7 @@ class Transactions extends Base {
11860
11759
  try {
11861
11760
  // Only attempt migration if we have password auth and V2 storage might be incomplete
11862
11761
  if (this.deviceAuthType === AuthType.Password && authenticationOptions.password) {
11863
- try {
11864
- await this.walletService.handleUpdateToV2({
11865
- password: authenticationOptions.password,
11866
- walletId: walletId,
11867
- });
11868
- }
11869
- catch (error) {
11870
- logger.error('SDK::Transactions::resolvePendingTransaction::handleUpdateToV2::error', error);
11871
- throw new WallabyError({
11872
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
11873
- statusCode: 500,
11874
- errorCode: ErrorResponseCodes.sdk_unknown_error,
11875
- });
11876
- }
11762
+ await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
11877
11763
  }
11878
11764
  const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareTransactionAuth(authenticationOptions, walletId);
11879
11765
  if (!readyForTransportSeedPhrase && !hasShares) {
@@ -12038,16 +11924,15 @@ class Wallaby {
12038
11924
  * @param {string} [config.clientAuthToken] - A web token generated by the client for authorization.
12039
11925
  * @public
12040
11926
  */
12041
- constructor(config) {
12042
- this.wallet = new WalletService(config);
12043
- this.walletData = new WalletDataService(config);
12044
- this.utils = new Utils(config);
12045
- this.auth = new AuthService(config);
12046
- this.system = new System(config);
12047
- this.transactions = new Transactions(config);
12048
- this.swap = new Swap(config);
12049
- this.merchants = new Merchants(config);
12050
- this.httpApi = new HttpApi(config);
11927
+ constructor(config, ports = {}) {
11928
+ this.wallet = new WalletService(config, ports);
11929
+ this.walletData = new WalletDataService(config, ports);
11930
+ this.utils = new Utils(config, ports);
11931
+ this.auth = new AuthService(config, ports);
11932
+ this.system = new System(config, ports);
11933
+ this.transactions = new Transactions(config, ports);
11934
+ this.swap = new Swap(config, ports);
11935
+ this.httpApi = new HttpApi(config, ports);
12051
11936
  }
12052
11937
  get version() {
12053
11938
  return currentPackageVersion;