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.esm.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;
@@ -543,7 +545,7 @@ const global$1 = (typeof global !== "undefined" ? global :
543
545
  typeof self !== "undefined" ? self :
544
546
  typeof window !== "undefined" ? window : {});
545
547
 
546
- var env = {};
548
+ var env$1 = {};
547
549
 
548
550
  // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js
549
551
  var performance = global$1.performance || {};
@@ -555,7 +557,7 @@ performance.now ||
555
557
  function(){ return (new Date()).getTime() };
556
558
 
557
559
  var browser$1 = {
558
- env: env};
560
+ env: env$1};
559
561
 
560
562
  var _a;
561
563
  /**
@@ -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';
@@ -589,6 +590,11 @@ const MASTER_ENCRYPTION_KEY = '9fa9d3f3c77c20d3a50a08e5299644be29f6e6206ef3479fe
589
590
  { type: 'public-key', alg: PublicKeyCredentialAlgorithm.ES256 },
590
591
  ];
591
592
  const isWeb = typeof window !== 'undefined' && typeof document !== 'undefined';
593
+ const env = {
594
+ platform: 'web',
595
+ isNative: !isWeb,
596
+ isWeb,
597
+ };
592
598
  const currentPackageVersion = "3.3.0" ;
593
599
 
594
600
  /**
@@ -3490,7 +3496,6 @@ const keccak256$1 = (() => {
3490
3496
  })();
3491
3497
 
3492
3498
  const DEFAULT_ENTROPY_BYTES = 32;
3493
- const MINIMUM_SHANNON_ENTROPY = 4;
3494
3499
  /**
3495
3500
  * creates a new private key
3496
3501
  * @param { Uint8Array } entropy - optional entropy to create the private key
@@ -3501,25 +3506,15 @@ const createPrivateKey = (entropy) => {
3501
3506
  if (!(entropy instanceof Uint8Array) || entropy.length < DEFAULT_ENTROPY_BYTES) {
3502
3507
  throw new Error(`entropy must be a Uint8Array of at least ${DEFAULT_ENTROPY_BYTES} bytes`);
3503
3508
  }
3504
- // 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.
3505
3514
  const uniqueBytes = new Set(entropy);
3506
3515
  if (uniqueBytes.size < Math.min(8, entropy.length / 4)) {
3507
3516
  throw new Error(`entropy is too repetitive (only ${uniqueBytes.size} unique byte values)`);
3508
3517
  }
3509
- // Estimate Shannon entropy
3510
- const byteCounts = new Uint32Array(256);
3511
- entropy.forEach((b) => byteCounts[b]++);
3512
- const total = entropy.length;
3513
- let shannonEntropy = 0;
3514
- for (let i = 0; i < 256; i++) {
3515
- if (byteCounts[i] > 0) {
3516
- const p = byteCounts[i] / total;
3517
- shannonEntropy -= p * Math.log2(p);
3518
- }
3519
- }
3520
- if (shannonEntropy < MINIMUM_SHANNON_ENTROPY) {
3521
- throw new Error(`entropy has low Shannon entropy (${shannonEntropy.toFixed(2)} bits/byte)`);
3522
- }
3523
3518
  const outerHex = keccak256$1(entropy);
3524
3519
  return addLeading0x(bytesToHex$1(outerHex));
3525
3520
  }
@@ -4394,6 +4389,11 @@ function pbkdf2Sync(password, salt, iterations, keylen, digest) {
4394
4389
  });
4395
4390
  }
4396
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';
4397
4397
  class Cipher {
4398
4398
  constructor() { }
4399
4399
  /**
@@ -4424,11 +4424,23 @@ class Cipher {
4424
4424
  * @returns The encrypted data as a string.
4425
4425
  */
4426
4426
  encryptWithMasterKey({ data }) {
4427
- 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);
4428
4437
  }
4429
4438
  decryptWithMasterKey({ cipherText }) {
4439
+ const ciphertext = cipherText.startsWith(MASTER_KEY_WRAP_PREFIX)
4440
+ ? cipherText.slice(MASTER_KEY_WRAP_PREFIX.length)
4441
+ : cipherText;
4430
4442
  try {
4431
- const decrypted = AES.decrypt(cipherText, this.getMasterKey().key).toString(enc.Utf8);
4443
+ const decrypted = AES.decrypt(ciphertext, this.getMasterKey().key).toString(enc.Utf8);
4432
4444
  if (decrypted) {
4433
4445
  return isJsonString(decrypted) ? safeJsonParse(decrypted) : decrypted;
4434
4446
  }
@@ -4546,6 +4558,8 @@ class Cipher {
4546
4558
  }
4547
4559
  derivedKeyPair = await this.deriveKeyPairFromPasskey({ inputKeyMaterial: options.prfValue });
4548
4560
  return derivedKeyPair;
4561
+ default:
4562
+ throw new Error(`Unknown AuthType: ${options.authType}`);
4549
4563
  }
4550
4564
  }
4551
4565
  catch (error) {
@@ -4815,7 +4829,7 @@ class StorageService {
4815
4829
  else {
4816
4830
  storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}`;
4817
4831
  }
4818
- if (!isWeb) {
4832
+ if (env.isNative) {
4819
4833
  storageKey = normalizeKey(storageKey);
4820
4834
  }
4821
4835
  const item = await this.getItem(storageKey);
@@ -4824,14 +4838,11 @@ class StorageService {
4824
4838
  return undefined;
4825
4839
  }
4826
4840
  if (this._keysProtectedByMasterKey.includes(key)) {
4827
- let unwrapped;
4828
- // Temp fix to unblock prod issue. Need a more permanent solution.
4829
- try {
4830
- unwrapped = this.cipher.decryptWithMasterKey({ cipherText: item });
4831
- }
4832
- catch (_a) {
4833
- unwrapped = item;
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;
4834
4844
  }
4845
+ const unwrapped = this.cipher.decryptWithMasterKey({ cipherText: item });
4835
4846
  if (!unwrapped) {
4836
4847
  logger.error(`Failed to decrypt item with key ${storageKey}`);
4837
4848
  return undefined;
@@ -4851,7 +4862,7 @@ class StorageService {
4851
4862
  else {
4852
4863
  storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}`;
4853
4864
  }
4854
- if (!isWeb) {
4865
+ if (env.isNative) {
4855
4866
  storageKey = normalizeKey(storageKey);
4856
4867
  }
4857
4868
  let valueToStore;
@@ -4878,7 +4889,7 @@ class StorageService {
4878
4889
  else {
4879
4890
  storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}`;
4880
4891
  }
4881
- if (!isWeb) {
4892
+ if (env.isNative) {
4882
4893
  storageKey = normalizeKey(storageKey);
4883
4894
  }
4884
4895
  return await this.removeItem(storageKey);
@@ -5143,11 +5154,14 @@ class StorageService {
5143
5154
  LocalStorageItems.AccessToken,
5144
5155
  LocalStorageItems.RefreshToken,
5145
5156
  V2KeyNames.EncryptedDevicePrivateKey,
5157
+ V2KeyNames.ClientAuthPublicKey,
5146
5158
  V2KeyNames.WallabyAuthPubKey,
5147
5159
  V2KeyNames.PasskeyCredential,
5148
5160
  V2KeyNames.MigrationVersion,
5149
5161
  V2KeyNames.LastMigratedAt,
5150
5162
  V2KeyNames.ClientAuthToken,
5163
+ V2KeyNames.PasswordResetAttempts,
5164
+ V2KeyNames.MigrationAttempts,
5151
5165
  ];
5152
5166
  await Promise.all(userKeysToRemove.map((key) => this.delete(key)));
5153
5167
  if (walletId) {
@@ -5194,11 +5208,11 @@ class StorageService {
5194
5208
  * @param jwt - The JWT string to check. If null, the function will return true.
5195
5209
  * @returns `true` if the JWT has expired or is null, otherwise `false`.
5196
5210
  */
5197
- function jwtHasExpired(jwt) {
5211
+ function jwtHasExpired(jwt, now = Date.now) {
5198
5212
  if (!jwt) {
5199
5213
  return true;
5200
5214
  }
5201
- return millisecondsToJWTTimeout(jwt) <= 0;
5215
+ return millisecondsToJWTTimeout(jwt, now) <= 0;
5202
5216
  }
5203
5217
  function jwtHasSameUser(jwt, userId) {
5204
5218
  if (!jwt || !userId) {
@@ -5218,11 +5232,11 @@ function userIsMfaVerified(jwt) {
5218
5232
  * @param thresholdSeconds - Number of seconds before expiry to consider "near expiry".
5219
5233
  * @returns `true` if the JWT expires within `thresholdSeconds` seconds, otherwise `false`.
5220
5234
  */
5221
- function isJwtNearExpiry(jwt, thresholdSeconds) {
5235
+ function isJwtNearExpiry(jwt, thresholdSeconds, now = Date.now) {
5222
5236
  if (!jwt) {
5223
5237
  return false;
5224
5238
  }
5225
- return millisecondsToJWTTimeout(jwt) <= thresholdSeconds * 1000;
5239
+ return millisecondsToJWTTimeout(jwt, now) <= thresholdSeconds * 1000;
5226
5240
  }
5227
5241
  /**
5228
5242
  * Calculates the remaining time in milliseconds until a given JWT expires.
@@ -5230,11 +5244,11 @@ function isJwtNearExpiry(jwt, thresholdSeconds) {
5230
5244
  * @param jwt - The JWT string to decode and check.
5231
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.
5232
5246
  */
5233
- function millisecondsToJWTTimeout(jwt) {
5247
+ function millisecondsToJWTTimeout(jwt, now = Date.now) {
5234
5248
  const jwtDecoded = jwtDecode(jwt);
5235
5249
  const jwtExpirationTimeSeconds = jwtDecoded.exp;
5236
5250
  const jwtExpirationTimeMilliseconds = (jwtExpirationTimeSeconds !== null && jwtExpirationTimeSeconds !== void 0 ? jwtExpirationTimeSeconds : 0) * 1000;
5237
- const timeNowMilliseconds = Date.now();
5251
+ const timeNowMilliseconds = now();
5238
5252
  return jwtExpirationTimeMilliseconds - timeNowMilliseconds;
5239
5253
  }
5240
5254
 
@@ -5279,6 +5293,11 @@ const AuthRoutes = {
5279
5293
  method: RequestMethod.Get,
5280
5294
  requiresAccessToken: true,
5281
5295
  },
5296
+ issueJwtToken: {
5297
+ fullPath: '/auth/issue-jwt-token',
5298
+ method: RequestMethod.Post,
5299
+ requiresAccessToken: false,
5300
+ },
5282
5301
  };
5283
5302
 
5284
5303
  class LockManagerService {
@@ -6878,18 +6897,21 @@ function shouldClearTokensAfterRefreshFailure(error) {
6878
6897
  // Module-level dedupe manager for token refresh to ensure only one refresh request per user/environment/network at a time
6879
6898
  const refreshDedupeManager = new DedupeManagerService();
6880
6899
  class Base {
6881
- constructor(config) {
6882
- var _a, _b;
6900
+ constructor(config, ports = {}) {
6901
+ var _a, _b, _c, _d, _e;
6883
6902
  const sanitizedConfig = sanitizeConfig(config);
6884
6903
  this.apiKey = sanitizedConfig.apiKey;
6885
6904
  this.baseUrl = sanitizedConfig.baseUrl;
6886
6905
  this.userId = sanitizedConfig.userId;
6887
6906
  this.options = sanitizedConfig.options;
6888
6907
  if ((_a = this.options) === null || _a === void 0 ? void 0 : _a.platform) {
6889
- this.options.platform;
6890
- this.options.platform === 'ios' || this.options.platform === 'android';
6908
+ env.platform = this.options.platform;
6909
+ env.isNative = this.options.platform === 'ios' || this.options.platform === 'android';
6910
+ env.isWeb = !env.isNative;
6891
6911
  }
6892
- 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() };
6893
6915
  this.lockManager = new LockManagerService();
6894
6916
  this._initializeClientAuthToken(sanitizedConfig.clientAuthToken);
6895
6917
  this.request = this.request.bind(this);
@@ -6903,6 +6925,7 @@ class Base {
6903
6925
  secure: true, // Enable security worker for all requests by default
6904
6926
  },
6905
6927
  securityWorker: this.securityWorker.bind(this),
6928
+ customFetch: this.transport,
6906
6929
  });
6907
6930
  /**
6908
6931
  * This intercepts all API responses and transforms errors into WallabyError format.
@@ -6947,7 +6970,7 @@ class Base {
6947
6970
  return attemptRequest(false);
6948
6971
  };
6949
6972
  this.api = new Api(httpClient);
6950
- 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));
6951
6974
  }
6952
6975
  set setClientAuthToken(token) {
6953
6976
  this._initializeClientAuthToken(token);
@@ -7066,7 +7089,7 @@ class Base {
7066
7089
  // Proactive token refresh: if access token is near expiry, refresh before making the request
7067
7090
  if (route !== AuthRoutes.refreshAccessToken && !retried) {
7068
7091
  const accessToken = await this.localStorageService.fetch(LocalStorageItems.AccessToken);
7069
- if (accessToken && isJwtNearExpiry(accessToken, 60)) {
7092
+ if (accessToken && isJwtNearExpiry(accessToken, 60, this.clock.now)) {
7070
7093
  await this._performTokenRefresh();
7071
7094
  }
7072
7095
  }
@@ -7090,7 +7113,7 @@ class Base {
7090
7113
  fetchOptions.body = JSON.stringify(options.payload);
7091
7114
  }
7092
7115
  logger.debug(`SDK::Base::${route.method}::Request`, { path: fullUrl, payload: options === null || options === void 0 ? void 0 : options.payload });
7093
- const response = await fetch(fullUrl, fetchOptions);
7116
+ const response = await this.transport(fullUrl, fetchOptions);
7094
7117
  const contentType = response.headers.get('content-type');
7095
7118
  let data;
7096
7119
  if (contentType === null || contentType === void 0 ? void 0 : contentType.includes('application/json')) {
@@ -7161,7 +7184,7 @@ class Base {
7161
7184
  }
7162
7185
  async _getRequestHeaders() {
7163
7186
  const accessToken = await this.localStorageService.fetch(LocalStorageItems.AccessToken);
7164
- if (!isTest && jwtHasExpired(this.clientAuthToken)) {
7187
+ if (jwtHasExpired(this.clientAuthToken, this.clock.now)) {
7165
7188
  throw new WallabyError({
7166
7189
  message: 'Auth token has expired',
7167
7190
  statusCode: 401,
@@ -7183,7 +7206,7 @@ class Base {
7183
7206
  // Proactive token refresh before building headers for the generated client
7184
7207
  try {
7185
7208
  const accessToken = await this.localStorageService.fetch(LocalStorageItems.AccessToken);
7186
- if (accessToken && isJwtNearExpiry(accessToken, 60)) {
7209
+ if (accessToken && isJwtNearExpiry(accessToken, 60, this.clock.now)) {
7187
7210
  await this._performTokenRefresh();
7188
7211
  }
7189
7212
  }
@@ -7542,6 +7565,17 @@ function normalizeAndPadBase64(s) {
7542
7565
  function decodeBase64String(s) {
7543
7566
  return toUint8Array(normalizeAndPadBase64(s));
7544
7567
  }
7568
+ /**
7569
+ * Single-decode only: decode base64 (or base64url) to bytes. No round-trip double-decode.
7570
+ */
7571
+ function base64ToUint8Array(base64) {
7572
+ try {
7573
+ return toUint8Array(base64);
7574
+ }
7575
+ catch (_a) {
7576
+ return decodeBase64String(base64);
7577
+ }
7578
+ }
7545
7579
  function decodeBase64URL(base64url) {
7546
7580
  const padded = normalizeAndPadBase64(base64url);
7547
7581
  const binary = atob(padded);
@@ -7552,32 +7586,9 @@ function decodeBase64URL(base64url) {
7552
7586
  return bytes;
7553
7587
  }
7554
7588
 
7555
- /**
7556
- * Web: round-trip with uint8ArrayToBase64 (which does btoa(fromUint8Array(bytes, true))).
7557
- * Single decode first; if the result looks like a base64 string, decode again to get original bytes.
7558
- */
7559
- function base64ToUint8Array(base64) {
7560
- try {
7561
- const first = toUint8Array(base64);
7562
- const asStr = String.fromCharCode.apply(null, first);
7563
- if (/^[A-Za-z0-9+/\-_=]*$/.test(asStr) && asStr.length >= 4) {
7564
- try {
7565
- return decodeBase64String(asStr);
7566
- }
7567
- catch (_a) {
7568
- // fall through
7569
- }
7570
- }
7571
- return first;
7572
- }
7573
- catch (_b) {
7574
- return decodeBase64String(base64);
7575
- }
7576
- }
7577
-
7578
7589
  class PasskeyService {
7579
- constructor(userId, storageService, request) {
7580
- this.cipher = new Cipher();
7590
+ constructor(userId, storageService, request, cipher = new Cipher()) {
7591
+ this.cipher = cipher;
7581
7592
  this.localStorageService = storageService;
7582
7593
  this.userId = userId;
7583
7594
  this.request = request;
@@ -7877,7 +7888,6 @@ class PasskeyService {
7877
7888
  }
7878
7889
  logger.log('SDK::PasskeyService::register:: getting signature', {
7879
7890
  message: challengeResponse.message,
7880
- privateKey: deviceKeyPair.privateKey,
7881
7891
  });
7882
7892
  const { signature, message } = await this.cipher.sign({
7883
7893
  message: challengeResponse.message,
@@ -8100,10 +8110,10 @@ function WithLock(lockKey) {
8100
8110
  }
8101
8111
 
8102
8112
  class AuthService extends Base {
8103
- constructor(config) {
8104
- super(config);
8113
+ constructor(config, ports = {}) {
8114
+ super(config, ports);
8105
8115
  this.getUserSalt = this.getUserSalt.bind(this);
8106
- this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request);
8116
+ this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request, this.cipher);
8107
8117
  }
8108
8118
  /**
8109
8119
  * @description
@@ -8523,7 +8533,7 @@ class AuthService extends Base {
8523
8533
  data: deviceKeyPair.privateKey,
8524
8534
  encryptionKey: credentialsKeyPair.publicKey,
8525
8535
  });
8526
- this.localStorageService.saveInBulk([
8536
+ await this.localStorageService.saveInBulk([
8527
8537
  {
8528
8538
  key: LocalStorageItems.EncryptedDevicePrivateKey,
8529
8539
  value: encryptedDevicePrivKey,
@@ -8594,6 +8604,24 @@ class AuthService extends Base {
8594
8604
  valid: true,
8595
8605
  };
8596
8606
  }
8607
+ /**
8608
+ * @description Exchanges the client JWT (set at SDK initialisation) for a
8609
+ * Wallaby access + refresh token pair. Tokens are persisted to storage so
8610
+ * subsequent SDK calls use them automatically.
8611
+ * @returns {Promise<IssueJWTTokenResponseDto>} The issued access/refresh tokens and basic user info.
8612
+ */
8613
+ async exchangeClientToken() {
8614
+ try {
8615
+ const response = await this.request(AuthRoutes.issueJwtToken);
8616
+ await this.localStorageService.save(LocalStorageItems.AccessToken, response.accessToken);
8617
+ await this.localStorageService.save(LocalStorageItems.RefreshToken, response.refreshToken);
8618
+ return response;
8619
+ }
8620
+ catch (error) {
8621
+ logger.error('SDK::Auth::exchangeClientToken::error', error);
8622
+ throw error;
8623
+ }
8624
+ }
8597
8625
  }
8598
8626
  __decorate([
8599
8627
  WithLock('signUp'),
@@ -8614,10 +8642,67 @@ __decorate([
8614
8642
  __metadata("design:returntype", Promise)
8615
8643
  ], AuthService.prototype, "storeDeviceKeyPair", null);
8616
8644
 
8645
+ const ENCRYPTED_PAYLOAD_FIELDS = ['iv', 'ephemPublicKey', 'ciphertext', 'mac'];
8646
+ // Backup share may be ECIES or symmetric ({ iv, ciphertext, mac, tag }) — both share these three fields.
8647
+ const SYMMETRIC_PAYLOAD_FIELDS = ['iv', 'ciphertext', 'mac', 'tag'];
8648
+ // API is the trust boundary: confirm every named field is a non-empty string.
8649
+ function hasNonEmptyStringFields(payload, fields) {
8650
+ return (!!payload &&
8651
+ typeof payload === 'object' &&
8652
+ fields.every((field) => {
8653
+ const value = payload[field];
8654
+ return typeof value === 'string' && value.length > 0;
8655
+ }));
8656
+ }
8657
+ /**
8658
+ * Fail fast if an encrypted payload from the API does not match the expected
8659
+ * ECIES structure ({ iv, ephemPublicKey, ciphertext, mac }). See the contract
8660
+ * note on `handleKeySharesFromResponse`.
8661
+ */
8662
+ function assertEncryptedPayloadShape(encrypted) {
8663
+ if (!hasNonEmptyStringFields(encrypted, ENCRYPTED_PAYLOAD_FIELDS)) {
8664
+ throw new WallabyError({
8665
+ message: 'Encrypted share does not match the expected { iv, ephemPublicKey, ciphertext, mac } format.',
8666
+ statusCode: 422,
8667
+ errorCode: ErrorResponseCodes.sdk_invalid_parameter,
8668
+ });
8669
+ }
8670
+ }
8671
+ /**
8672
+ * Shape-assert every share returned by the API. Empty arrays are rejected here
8673
+ * so callers get a clean error instead of crashing on `shares[0]`.
8674
+ */
8675
+ function assertSharesPayloadShape(shares) {
8676
+ if (!shares.length) {
8677
+ throw new WallabyError({
8678
+ message: 'No key shares were returned from the API.',
8679
+ statusCode: 422,
8680
+ errorCode: ErrorResponseCodes.sdk_invalid_parameter,
8681
+ });
8682
+ }
8683
+ for (const share of shares) {
8684
+ assertEncryptedPayloadShape(share.encrypted);
8685
+ }
8686
+ }
8687
+ /**
8688
+ * The backup share is stored as-is (the device can't peel it), so we only
8689
+ * shape-check it. It may be ECIES or symmetric, so accept either variant.
8690
+ */
8691
+ function assertBackupSharePayloadShape(encrypted) {
8692
+ const isEcies = hasNonEmptyStringFields(encrypted, ENCRYPTED_PAYLOAD_FIELDS);
8693
+ const isSymmetric = hasNonEmptyStringFields(encrypted, SYMMETRIC_PAYLOAD_FIELDS);
8694
+ if (!isEcies && !isSymmetric) {
8695
+ throw new WallabyError({
8696
+ message: 'Encrypted backup share does not match the expected ECIES ({ iv, ephemPublicKey, ciphertext, mac }) or symmetric ({ iv, ciphertext, mac, tag }) format.',
8697
+ statusCode: 422,
8698
+ errorCode: ErrorResponseCodes.sdk_invalid_parameter,
8699
+ });
8700
+ }
8701
+ }
8617
8702
  class WalletHandlersService extends Base {
8618
- constructor(config) {
8619
- super(config);
8620
- this.authService = new AuthService(config);
8703
+ constructor(config, ports = {}) {
8704
+ super(config, ports);
8705
+ this.authService = new AuthService(config, ports);
8621
8706
  this.userId = config.userId;
8622
8707
  }
8623
8708
  async handleImportWallet(deviceAuthKeys, importWalletInput) {
@@ -8694,6 +8779,7 @@ class WalletHandlersService extends Base {
8694
8779
  shares: importWalletRequest.shares,
8695
8780
  credentialsKeyPair,
8696
8781
  encryptedBackupShare: importWalletRequest.encryptedBackupShare,
8782
+ devicePrivateKey: deviceAuthKeys.privateKey,
8697
8783
  });
8698
8784
  }
8699
8785
  return Object.assign({}, importWalletRequest);
@@ -8780,6 +8866,7 @@ class WalletHandlersService extends Base {
8780
8866
  shares: walletCreationResponse.shares,
8781
8867
  credentialsKeyPair,
8782
8868
  encryptedBackupShare: walletCreationResponse.encryptedBackupShare,
8869
+ devicePrivateKey: deviceAuthKeys.privateKey,
8783
8870
  });
8784
8871
  }
8785
8872
  return Object.assign(Object.assign({}, walletCreationResponse), { standardSeedPhrase: decryptedSeedPhrase });
@@ -8795,8 +8882,41 @@ class WalletHandlersService extends Base {
8795
8882
  });
8796
8883
  }
8797
8884
  }
8798
- async handleKeySharesFromResponse({ walletId, shares, credentialsKeyPair, encryptedBackupShare, }) {
8885
+ /**
8886
+ * Encrypted share format contract (WAL-1467)
8887
+ * --------------------------------------------------------------------------
8888
+ * Every flow that ingests shares from the API (import, create, recover,
8889
+ * addNewDevice) routes through here, so the contract is asserted in one place.
8890
+ *
8891
+ * The API returns the main device share as `shares[0]`, an ECIES payload
8892
+ * ({ iv, ephemPublicKey, ciphertext, mac }) wrapped to the device public key,
8893
+ * so it MUST peel with the device private key. `encryptedBackupShare` is an
8894
+ * already-wrapped blob (ECIES or symmetric) that the device cannot decrypt, so
8895
+ * it is stored as-is.
8896
+ *
8897
+ * We shape-assert every share (and the backup share) here, at ingestion, so a
8898
+ * server-side wrapping change fails loudly now instead of silently breaking
8899
+ * export/recovery later.
8900
+ */
8901
+ async handleKeySharesFromResponse({ walletId, shares, credentialsKeyPair, encryptedBackupShare, devicePrivateKey, }) {
8799
8902
  try {
8903
+ assertSharesPayloadShape(shares);
8904
+ assertBackupSharePayloadShape(encryptedBackupShare);
8905
+ // Decrypt-test the contract: shares[0] is wrapped to the device public key and must peel with the device private key.
8906
+ try {
8907
+ await this.cipher.decrypt({
8908
+ cipherText: shares[0].encrypted,
8909
+ decryptionKey: devicePrivateKey,
8910
+ });
8911
+ }
8912
+ catch (error) {
8913
+ throw new WallabyError({
8914
+ message: 'Device-wrapped key share (shares[0]) could not be decrypted with the device private key; the share wrapping format may have changed.',
8915
+ statusCode: 422,
8916
+ errorCode: ErrorResponseCodes.sdk_key_share_decryption_failed,
8917
+ cause: error,
8918
+ });
8919
+ }
8800
8920
  const encryptedWithCredentialsKeyShare = await this.cipher.encrypt({
8801
8921
  data: JSON.stringify(shares[0].encrypted),
8802
8922
  encryptionKey: credentialsKeyPair.publicKey,
@@ -8888,14 +9008,43 @@ class WalletHandlersService extends Base {
8888
9008
  }
8889
9009
 
8890
9010
  class WalletService extends Base {
8891
- constructor(config) {
8892
- super(config);
8893
- this.passwordResetAttempts = 0;
8894
- this.migrationAttempts = 0;
8895
- this.authService = new AuthService(config);
8896
- this.handlers = new WalletHandlersService(config);
9011
+ constructor(config, ports = {}) {
9012
+ super(config, ports);
9013
+ this.authService = new AuthService(config, ports);
9014
+ this.handlers = new WalletHandlersService(config, ports);
8897
9015
  this.userId = config.userId;
8898
- this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request);
9016
+ this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request, this.cipher);
9017
+ }
9018
+ /**
9019
+ * Reads the persisted sliding-window rate-limit state for a counter key.
9020
+ * Returns a fresh window ({ count: 0 }) when none is stored or the window has expired.
9021
+ */
9022
+ async getRateState(key) {
9023
+ const now = Date.now();
9024
+ const raw = await this.localStorageService.fetch(key);
9025
+ const state = raw ? safeJsonParse(raw) : undefined;
9026
+ if (!state || now - state.windowStart > WalletService.RATE_LIMIT_WINDOW_MS) {
9027
+ return { count: 0, windowStart: now };
9028
+ }
9029
+ return state;
9030
+ }
9031
+ /** Increments and persists the counter (resetting an expired window). Returns the new count. */
9032
+ async recordRateAttempt(key) {
9033
+ const state = await this.getRateState(key);
9034
+ state.count += 1;
9035
+ await this.localStorageService.save(key, JSON.stringify(state));
9036
+ return state.count;
9037
+ }
9038
+ /** Throws a 429 when the counter is already over the limit, without incrementing it. */
9039
+ async assertUnderRateLimit(key, message) {
9040
+ const { count } = await this.getRateState(key);
9041
+ if (count > WalletService.RATE_LIMIT_MAX) {
9042
+ throw new WallabyError({
9043
+ message,
9044
+ statusCode: 429,
9045
+ errorCode: ErrorResponseCodes.sdk_too_many_requests,
9046
+ });
9047
+ }
8899
9048
  }
8900
9049
  /**
8901
9050
  * @public
@@ -9002,20 +9151,7 @@ class WalletService extends Base {
9002
9151
  });
9003
9152
  }
9004
9153
  if (this.deviceAuthType === AuthType.Password && authenticationOptions.password) {
9005
- try {
9006
- await this.handleUpdateToV2({
9007
- password: authenticationOptions.password,
9008
- walletId: walletId,
9009
- });
9010
- }
9011
- catch (error) {
9012
- logger.error('SDK::WalletService::export::handleUpdateToV2::error', error);
9013
- throw new WallabyError({
9014
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
9015
- statusCode: 500,
9016
- errorCode: ErrorResponseCodes.sdk_unknown_error,
9017
- });
9018
- }
9154
+ await this.migrateToV2Safe({ password: authenticationOptions.password, walletId });
9019
9155
  }
9020
9156
  const encryptedSeed = await this.localStorageService.fetch(LocalStorageItems.EncryptedStandardSeedPhrase, { walletId });
9021
9157
  const encryptedPrimaryDeviceShare = await this.localStorageService.fetch(LocalStorageItems.PrimaryDeviceKeyShare, {
@@ -9258,6 +9394,7 @@ class WalletService extends Base {
9258
9394
  shares: recoverWithSeedPhraseResponse.shares,
9259
9395
  credentialsKeyPair,
9260
9396
  encryptedBackupShare: recoverWithSeedPhraseResponse.encryptedBackupShare,
9397
+ devicePrivateKey: deviceAuthKeyPair.privateKey,
9261
9398
  });
9262
9399
  }
9263
9400
  await this.authService.storeDeviceKeyPair({
@@ -9321,6 +9458,7 @@ class WalletService extends Base {
9321
9458
  shares: recoverWithSeedPhraseResponse.shares,
9322
9459
  credentialsKeyPair,
9323
9460
  encryptedBackupShare: recoverWithSeedPhraseResponse.encryptedBackupShare,
9461
+ devicePrivateKey: deviceAuthKeyPair.privateKey,
9324
9462
  });
9325
9463
  }
9326
9464
  await this.authService.storeDeviceKeyPair({
@@ -9353,8 +9491,7 @@ class WalletService extends Base {
9353
9491
  */
9354
9492
  async changePassword({ walletId, oldPassword, newPassword, }) {
9355
9493
  try {
9356
- this.passwordResetAttempts += 1;
9357
- if (this.passwordResetAttempts > 5) {
9494
+ if ((await this.recordRateAttempt(V2KeyNames.PasswordResetAttempts)) > WalletService.RATE_LIMIT_MAX) {
9358
9495
  throw new WallabyError({
9359
9496
  message: 'Too many password change attempts. Please try again later.',
9360
9497
  statusCode: 429,
@@ -9363,20 +9500,7 @@ class WalletService extends Base {
9363
9500
  }
9364
9501
  if (this.deviceAuthType === AuthType.Password && oldPassword) {
9365
9502
  // Handle migration to V2 first then change the password to the new one.
9366
- try {
9367
- await this.handleUpdateToV2({
9368
- password: oldPassword,
9369
- walletId,
9370
- });
9371
- }
9372
- catch (error) {
9373
- logger.error('SDK::WalletService::changePassword::handleUpdateToV2::error', error);
9374
- throw new WallabyError({
9375
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
9376
- statusCode: 500,
9377
- errorCode: ErrorResponseCodes.sdk_unknown_error,
9378
- });
9379
- }
9503
+ await this.migrateToV2Safe({ password: oldPassword, walletId });
9380
9504
  }
9381
9505
  const encryptedDevicePrivateKeyString = await this.localStorageService.fetch(V2KeyNames.EncryptedDevicePrivateKey);
9382
9506
  const encryptedSeedPhraseString = await this.localStorageService.fetch(V2KeyNames.EncryptedStandardSeedPhrase, {
@@ -9433,40 +9557,41 @@ class WalletService extends Base {
9433
9557
  errorCode: ErrorResponseCodes.sdk_unknown_error,
9434
9558
  });
9435
9559
  }
9436
- await this.localStorageService.save(LocalStorageItems.EncryptedDevicePrivateKey, reWrappedDevicePrivateKey);
9437
- if (encryptedSeedPhraseString) {
9438
- const parsedSeed = safeJsonParse(encryptedSeedPhraseString);
9439
- const reWrappedSeedPhrase = await this.cipher.flipEncryptedData({
9440
- cipherText: parsedSeed,
9560
+ const reWrappedSeedPhrase = encryptedSeedPhraseString
9561
+ ? await this.cipher.flipEncryptedData({
9562
+ cipherText: safeJsonParse(encryptedSeedPhraseString),
9441
9563
  decryptionKey: oldCredentialsKeyPair.privateKey,
9442
9564
  encryptionKey: newCredentialsKeyPair.publicKey,
9443
- });
9444
- await this.localStorageService.save(LocalStorageItems.EncryptedStandardSeedPhrase, reWrappedSeedPhrase, {
9445
- walletId,
9446
- });
9447
- }
9448
- if (encryptedPrimaryShareString) {
9449
- const parsedPrimaryShare = safeJsonParse(encryptedPrimaryShareString);
9450
- const reWrappedPrimaryShare = await this.cipher.flipEncryptedData({
9451
- cipherText: parsedPrimaryShare,
9565
+ })
9566
+ : null;
9567
+ const reWrappedPrimaryShare = encryptedPrimaryShareString
9568
+ ? await this.cipher.flipEncryptedData({
9569
+ cipherText: safeJsonParse(encryptedPrimaryShareString),
9452
9570
  decryptionKey: oldCredentialsKeyPair.privateKey,
9453
9571
  encryptionKey: newCredentialsKeyPair.publicKey,
9454
- });
9455
- await this.localStorageService.save(LocalStorageItems.PrimaryDeviceKeyShare, reWrappedPrimaryShare, {
9456
- walletId,
9457
- });
9458
- }
9459
- if (encryptedBackupShareString) {
9460
- const parsedBackupShare = safeJsonParse(encryptedBackupShareString);
9461
- const reWrappedBackupShare = await this.cipher.flipEncryptedData({
9462
- cipherText: parsedBackupShare,
9572
+ })
9573
+ : null;
9574
+ const reWrappedBackupShare = encryptedBackupShareString
9575
+ ? await this.cipher.flipEncryptedData({
9576
+ cipherText: safeJsonParse(encryptedBackupShareString),
9463
9577
  decryptionKey: oldCredentialsKeyPair.privateKey,
9464
9578
  encryptionKey: newCredentialsKeyPair.publicKey,
9465
- });
9466
- await this.localStorageService.save(LocalStorageItems.BackupDeviceKeyShare, reWrappedBackupShare, {
9467
- walletId,
9468
- });
9469
- }
9579
+ })
9580
+ : null;
9581
+ // Commit all re-wrapped blobs in one batch so a partial failure cannot leave the device
9582
+ // in a half-migrated state (some items under the new password, others under the old).
9583
+ await this.localStorageService.saveInBulk([
9584
+ { key: LocalStorageItems.EncryptedDevicePrivateKey, value: reWrappedDevicePrivateKey },
9585
+ ...(reWrappedSeedPhrase
9586
+ ? [{ key: LocalStorageItems.EncryptedStandardSeedPhrase, value: reWrappedSeedPhrase, walletId }]
9587
+ : []),
9588
+ ...(reWrappedPrimaryShare
9589
+ ? [{ key: LocalStorageItems.PrimaryDeviceKeyShare, value: reWrappedPrimaryShare, walletId }]
9590
+ : []),
9591
+ ...(reWrappedBackupShare ? [{ key: LocalStorageItems.BackupDeviceKeyShare, value: reWrappedBackupShare, walletId }] : []),
9592
+ ]);
9593
+ // Reset the rate-limit window on success so a normal change does not count against future ones.
9594
+ await this.localStorageService.delete(V2KeyNames.PasswordResetAttempts);
9470
9595
  return true;
9471
9596
  }
9472
9597
  catch (error) {
@@ -9519,20 +9644,7 @@ class WalletService extends Base {
9519
9644
  }
9520
9645
  const parsedEncryptedDevicePrivateKey = safeJsonParse(encryptedDevicePrivateKey);
9521
9646
  if (this.deviceAuthType === AuthType.Password && input.authenticationOptions.password) {
9522
- try {
9523
- await this.handleUpdateToV2({
9524
- password: input.authenticationOptions.password,
9525
- walletId: input.walletId,
9526
- });
9527
- }
9528
- catch (error) {
9529
- logger.error('SDK::WalletService::initAddNewDevice::handleUpdateToV2::error', error);
9530
- throw new WallabyError({
9531
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
9532
- statusCode: 500,
9533
- errorCode: ErrorResponseCodes.sdk_unknown_error,
9534
- });
9535
- }
9647
+ await this.migrateToV2Safe({ password: input.authenticationOptions.password, walletId: input.walletId });
9536
9648
  }
9537
9649
  const storedEncryptedBackupShare = await this.localStorageService.fetch(LocalStorageItems.BackupDeviceKeyShare, { walletId });
9538
9650
  if (!storedEncryptedBackupShare) {
@@ -9630,6 +9742,7 @@ class WalletService extends Base {
9630
9742
  shares: [backUpResponse.share],
9631
9743
  credentialsKeyPair,
9632
9744
  encryptedBackupShare: input.encryptedBackupShare,
9745
+ devicePrivateKey: decryptedDevicePrivateKey,
9633
9746
  });
9634
9747
  return { success: true, reference: backUpResponse.reference };
9635
9748
  }
@@ -9648,20 +9761,7 @@ class WalletService extends Base {
9648
9761
  });
9649
9762
  }
9650
9763
  if (this.deviceAuthType === AuthType.Password && input.authenticationOptions.password) {
9651
- try {
9652
- await this.handleUpdateToV2({
9653
- password: input.authenticationOptions.password,
9654
- walletId: input.walletId,
9655
- });
9656
- }
9657
- catch (error) {
9658
- logger.error('SDK::WalletService::generateWalletAddresses::handleUpdateToV2::error', error);
9659
- throw new WallabyError({
9660
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
9661
- statusCode: 500,
9662
- errorCode: ErrorResponseCodes.sdk_unknown_error,
9663
- });
9664
- }
9764
+ await this.migrateToV2Safe({ password: input.authenticationOptions.password, walletId: input.walletId });
9665
9765
  }
9666
9766
  try {
9667
9767
  const walletOperationAuth = await this.prepareWalletOperationAuth({
@@ -9686,6 +9786,23 @@ class WalletService extends Base {
9686
9786
  throw error;
9687
9787
  }
9688
9788
  }
9789
+ /**
9790
+ * Wraps handleUpdateToV2 with the standard user-facing error. All call sites that gate on
9791
+ * `AuthType.Password` should go through here so the error message stays consistent.
9792
+ */
9793
+ async migrateToV2Safe({ password, walletId }) {
9794
+ try {
9795
+ await this.handleUpdateToV2({ password, walletId });
9796
+ }
9797
+ catch (error) {
9798
+ logger.error('SDK::WalletService::migrateToV2Safe::error', error);
9799
+ throw new WallabyError({
9800
+ message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
9801
+ statusCode: 500,
9802
+ errorCode: ErrorResponseCodes.sdk_unknown_error,
9803
+ });
9804
+ }
9805
+ }
9689
9806
  /**
9690
9807
  * Detects and migrates legacy/v1 storage items to v2 format.
9691
9808
  * This function should be called in methods that use password as input when v2 items are missing.
@@ -9694,13 +9811,7 @@ class WalletService extends Base {
9694
9811
  */
9695
9812
  async handleUpdateToV2({ password, walletId }) {
9696
9813
  const migrationStartTime = Date.now();
9697
- if (this.migrationAttempts > 5) {
9698
- throw new WallabyError({
9699
- message: 'Too many migration attempts. Please try again later.',
9700
- statusCode: 429,
9701
- errorCode: ErrorResponseCodes.sdk_too_many_requests,
9702
- });
9703
- }
9814
+ await this.assertUnderRateLimit(V2KeyNames.MigrationAttempts, 'Too many migration attempts. Please try again later.');
9704
9815
  try {
9705
9816
  if (!password) {
9706
9817
  throw new WallabyError({
@@ -9771,7 +9882,7 @@ class WalletService extends Base {
9771
9882
  }
9772
9883
  }
9773
9884
  // Increment counter after V2 validation to avoid counting when migration not needed
9774
- this.migrationAttempts += 1;
9885
+ await this.recordRateAttempt(V2KeyNames.MigrationAttempts);
9775
9886
  let decryptedSeedPhrase;
9776
9887
  let decryptedPrivateKey;
9777
9888
  // Check for legacy format: `{item}_{userId}`
@@ -9824,7 +9935,10 @@ class WalletService extends Base {
9824
9935
  try {
9825
9936
  // Decrypt V1 items using storage service method (handles double encryption)
9826
9937
  logger.log('Attempting to decrypt V1 items during migration...');
9827
- logger.log('getV1DecryptedSeedPhrase should be called with password and clientSalt:', { password, clientSalt });
9938
+ logger.log('getV1DecryptedSeedPhrase should be called with password and clientSalt:', {
9939
+ hasPassword: !!password,
9940
+ hasClientSalt: !!clientSalt,
9941
+ });
9828
9942
  decryptedSeedPhrase = await this.localStorageService.getV1DecryptedSeedPhrase(password, clientSalt);
9829
9943
  // For V1 format, private key is encrypted with just the password (not salt+password like legacy)
9830
9944
  decryptedPrivateKey = await this.localStorageService.getDecryptedV1PrivateKey(password);
@@ -10289,6 +10403,10 @@ class WalletService extends Base {
10289
10403
  }
10290
10404
  }
10291
10405
  }
10406
+ // ponytail: soft client-side guardrail against runaway retries; server-side rate limiting is the real control.
10407
+ // Counters are persisted (sliding window) so rebuilding the service no longer resets them. Tune freely.
10408
+ WalletService.RATE_LIMIT_MAX = 5;
10409
+ WalletService.RATE_LIMIT_WINDOW_MS = 30 * 60000; // 30 min
10292
10410
  __decorate([
10293
10411
  WithLock('create'),
10294
10412
  __metadata("design:type", Function),
@@ -10321,10 +10439,10 @@ __decorate([
10321
10439
  ], WalletService.prototype, "handleUpdateToV2", null);
10322
10440
 
10323
10441
  class WalletDataService extends Base {
10324
- constructor(config) {
10325
- super(config);
10442
+ constructor(config, ports = {}) {
10443
+ super(config, ports);
10326
10444
  this.userId = config.userId;
10327
- this.walletService = new WalletService(config);
10445
+ this.walletService = new WalletService(config, ports);
10328
10446
  }
10329
10447
  /**
10330
10448
  * @description Validates the wallet address info for a given blockchain.
@@ -10571,20 +10689,7 @@ class WalletDataService extends Base {
10571
10689
  });
10572
10690
  }
10573
10691
  if (this.deviceAuthType === AuthType.Password && authenticationOptions.password) {
10574
- try {
10575
- await this.walletService.handleUpdateToV2({
10576
- password: authenticationOptions.password,
10577
- walletId: walletId,
10578
- });
10579
- }
10580
- catch (error) {
10581
- logger.error('SDK::WalletDataService::addNewChainAndTokenToWallet::handleUpdateToV2::error', error);
10582
- throw new WallabyError({
10583
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
10584
- statusCode: 500,
10585
- errorCode: ErrorResponseCodes.sdk_unknown_error,
10586
- });
10587
- }
10692
+ await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
10588
10693
  }
10589
10694
  try {
10590
10695
  const addressInfo = await this.walletService.generateWalletAddresses({
@@ -10658,8 +10763,8 @@ class WalletDataService extends Base {
10658
10763
  }
10659
10764
 
10660
10765
  class Utils extends Base {
10661
- constructor(config) {
10662
- super(config);
10766
+ constructor(config, ports = {}) {
10767
+ super(config, ports);
10663
10768
  /**
10664
10769
  *
10665
10770
  * Decrypts user private key
@@ -10692,7 +10797,7 @@ class Utils extends Base {
10692
10797
  return undefined;
10693
10798
  }
10694
10799
  };
10695
- this.auth = new AuthService(config);
10800
+ this.auth = new AuthService(config, ports);
10696
10801
  }
10697
10802
  /**
10698
10803
  *
@@ -10785,179 +10890,6 @@ class Utils extends Base {
10785
10890
  }
10786
10891
  }
10787
10892
 
10788
- const MerchantsRoutes = {
10789
- create: {
10790
- fullPath: '/merchants',
10791
- method: RequestMethod.Post,
10792
- requiresAccessToken: false,
10793
- },
10794
- update: {
10795
- fullPath: ({ merchantId }) => `/merchants/${merchantId}`,
10796
- method: RequestMethod.Put,
10797
- requiresAccessToken: false,
10798
- },
10799
- getMerchantData: {
10800
- fullPath: ({ merchantId }) => `/merchants/${merchantId}`,
10801
- method: RequestMethod.Get,
10802
- requiresAccessToken: false,
10803
- },
10804
- list: {
10805
- fullPath: '/merchants',
10806
- method: RequestMethod.Get,
10807
- requiresAccessToken: false,
10808
- },
10809
- getAssets: {
10810
- fullPath: () => `/users/merchant/assets`,
10811
- method: RequestMethod.Get,
10812
- requiresAccessToken: true,
10813
- },
10814
- addAsset: {
10815
- fullPath: ({ merchantId, configId }) => `/merchants/${merchantId}/assets/${configId}`,
10816
- method: RequestMethod.Post,
10817
- requiresAccessToken: false,
10818
- },
10819
- deleteAsset: {
10820
- fullPath: ({ merchantId, configId }) => `/merchants/${merchantId}/assets/${configId}`,
10821
- method: RequestMethod.Delete,
10822
- requiresAccessToken: false,
10823
- },
10824
- };
10825
-
10826
- class Merchants extends Base {
10827
- constructor(config) {
10828
- super(config);
10829
- }
10830
- /**
10831
- * @description
10832
- * Retrieves the merchant ID from access token `aud` claim.
10833
- * Even though merchantId is possibly undefined. If an access token is not stored on device, the request will most likely
10834
- * not have it in headers and will fail with 401 regardless.
10835
- *
10836
- * @returns { string | undefined } Merchant ID
10837
- */
10838
- async _getMerchantId() {
10839
- const accessToken = await this.localStorageService.fetch(LocalStorageItems.AccessToken);
10840
- if (!accessToken)
10841
- return;
10842
- const jwtDecoded = jwtDecode(accessToken);
10843
- return jwtDecoded.aud;
10844
- }
10845
- /**
10846
- *
10847
- * @public
10848
- * List of all merchants in the system
10849
- * @returns { ListMerchantsResponse } Array of all merchants
10850
- */
10851
- async list() {
10852
- try {
10853
- const response = await this.request(MerchantsRoutes.list, {
10854
- payload: {},
10855
- });
10856
- return response;
10857
- }
10858
- catch (error) {
10859
- logger.error('SDK::Merchants::list::error', error);
10860
- return Promise.reject(error);
10861
- }
10862
- }
10863
- /**
10864
- *
10865
- * @public
10866
- * Allows to create a new merchant
10867
- * @returns { Merchant } Merchant data
10868
- */
10869
- async create({ name }) {
10870
- try {
10871
- const response = await this.request(MerchantsRoutes.create, {
10872
- payload: { name },
10873
- });
10874
- return response;
10875
- }
10876
- catch (error) {
10877
- logger.error('SDK::Merchants::list::error', error);
10878
- return Promise.reject(error);
10879
- }
10880
- }
10881
- /**
10882
- *
10883
- * @public
10884
- * Allows to update merchant data
10885
- * @returns { Merchant } Merchant data
10886
- */
10887
- async update({ name, status }) {
10888
- try {
10889
- const merchantId = await this._getMerchantId();
10890
- const response = await this.request(MerchantsRoutes.update, {
10891
- payload: { merchantId, name, status },
10892
- });
10893
- return response;
10894
- }
10895
- catch (error) {
10896
- logger.error('SDK::Merchants::list::error', error);
10897
- return Promise.reject(error);
10898
- }
10899
- }
10900
- /**
10901
- *
10902
- * @public
10903
- * @returns { Merchant } Merchant data
10904
- */
10905
- async getMerchantData() {
10906
- try {
10907
- const merchantId = await this._getMerchantId();
10908
- const response = await this.request(MerchantsRoutes.getMerchantData, {
10909
- payload: { merchantId },
10910
- });
10911
- return response.merchant;
10912
- }
10913
- catch (error) {
10914
- logger.error('SDK::Merchants::list::error', error);
10915
- return Promise.reject(error);
10916
- }
10917
- }
10918
- /**
10919
- *
10920
- * @public
10921
- * @returns { MerchantAsset[] } List of merchant assets
10922
- */
10923
- async getAssets() {
10924
- try {
10925
- const response = await this.request(MerchantsRoutes.getAssets);
10926
- return response.merchantAssets;
10927
- }
10928
- catch (error) {
10929
- logger.error('SDK::Merchants::list::error', error);
10930
- return Promise.reject(error);
10931
- }
10932
- }
10933
- async addAsset({ configId }) {
10934
- try {
10935
- const merchantId = await this._getMerchantId();
10936
- const response = await this.request(MerchantsRoutes.addAsset, {
10937
- payload: { merchantId, configId },
10938
- });
10939
- return response;
10940
- }
10941
- catch (error) {
10942
- logger.error('SDK::Merchants::list::error', error);
10943
- return Promise.reject(error);
10944
- }
10945
- }
10946
- async deleteAsset({ configId }) {
10947
- try {
10948
- const merchantId = await this._getMerchantId();
10949
- const response = await this.request(MerchantsRoutes.deleteAsset, {
10950
- payload: { merchantId, configId },
10951
- });
10952
- return response;
10953
- }
10954
- catch (error) {
10955
- logger.error('SDK::Merchants::list::error', error);
10956
- return Promise.reject(error);
10957
- }
10958
- }
10959
- }
10960
-
10961
10893
  /**
10962
10894
  * HttpApi provides direct access to all REST API endpoints.
10963
10895
  * This class extends the Base class and includes the generated API client
@@ -10972,16 +10904,16 @@ class HttpApi extends Base {
10972
10904
  * @param config - The Wallaby configuration object
10973
10905
  * @public
10974
10906
  */
10975
- constructor(config) {
10976
- super(config);
10907
+ constructor(config, ports = {}) {
10908
+ super(config, ports);
10977
10909
  }
10978
10910
  }
10979
10911
 
10980
10912
  class Swap extends Base {
10981
- constructor(config) {
10982
- super(config);
10983
- this.authService = new AuthService(config);
10984
- this.walletService = new WalletService(config);
10913
+ constructor(config, ports = {}) {
10914
+ super(config, ports);
10915
+ this.authService = new AuthService(config, ports);
10916
+ this.walletService = new WalletService(config, ports);
10985
10917
  }
10986
10918
  /**
10987
10919
  * Gets a swap quote between two assets, including fees, min output, and slippage limits.
@@ -11038,20 +10970,7 @@ class Swap extends Base {
11038
10970
  try {
11039
10971
  // Only attempt migration if we have password auth and V2 storage might be incomplete
11040
10972
  if (this.deviceAuthType === AuthType.Password && authenticationOptions.password) {
11041
- try {
11042
- await this.walletService.handleUpdateToV2({
11043
- password: authenticationOptions.password,
11044
- walletId: walletId,
11045
- });
11046
- }
11047
- catch (error) {
11048
- logger.error('SDK::Swap::executeSwap::handleUpdateToV2::error', error);
11049
- throw new WallabyError({
11050
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
11051
- statusCode: 500,
11052
- errorCode: ErrorResponseCodes.sdk_unknown_error,
11053
- });
11054
- }
10973
+ await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
11055
10974
  }
11056
10975
  const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareSwapAuth(authenticationOptions, walletId);
11057
10976
  let swapResponse;
@@ -11247,8 +11166,8 @@ const sanitizeSuiObjectId = (objectId) => {
11247
11166
  };
11248
11167
 
11249
11168
  class System extends Base {
11250
- constructor(config) {
11251
- super(config);
11169
+ constructor(config, ports = {}) {
11170
+ super(config, ports);
11252
11171
  }
11253
11172
  /**
11254
11173
  * @public
@@ -11441,10 +11360,10 @@ class System extends Base {
11441
11360
  }
11442
11361
 
11443
11362
  class Transactions extends Base {
11444
- constructor(config) {
11445
- super(config);
11446
- this.authService = new AuthService(config);
11447
- this.walletService = new WalletService(config);
11363
+ constructor(config, ports = {}) {
11364
+ super(config, ports);
11365
+ this.authService = new AuthService(config, ports);
11366
+ this.walletService = new WalletService(config, ports);
11448
11367
  this.userId = config.userId;
11449
11368
  }
11450
11369
  /**
@@ -11567,20 +11486,7 @@ class Transactions extends Base {
11567
11486
  try {
11568
11487
  // Only attempt migration if we have password auth and V2 storage might be incomplete
11569
11488
  if (this.deviceAuthType === AuthType.Password && authenticationOptions.password) {
11570
- try {
11571
- await this.walletService.handleUpdateToV2({
11572
- password: authenticationOptions.password,
11573
- walletId: walletId,
11574
- });
11575
- }
11576
- catch (error) {
11577
- logger.error('SDK::Transactions::transfer::handleUpdateToV2::error', error);
11578
- throw new WallabyError({
11579
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
11580
- statusCode: 500,
11581
- errorCode: ErrorResponseCodes.sdk_unknown_error,
11582
- });
11583
- }
11489
+ await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
11584
11490
  }
11585
11491
  const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareTransactionAuth(authenticationOptions, walletId);
11586
11492
  let transferResponse;
@@ -11668,20 +11574,7 @@ class Transactions extends Base {
11668
11574
  }
11669
11575
  // Only attempt migration if we have password auth and V2 storage might be incomplete
11670
11576
  if (this.deviceAuthType === AuthType.Password && authenticationOptions.password) {
11671
- try {
11672
- await this.walletService.handleUpdateToV2({
11673
- password: authenticationOptions.password,
11674
- walletId: walletId,
11675
- });
11676
- }
11677
- catch (error) {
11678
- logger.error('SDK::Transactions::createAllowance::handleUpdateToV2::error', error);
11679
- throw new WallabyError({
11680
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
11681
- statusCode: 500,
11682
- errorCode: ErrorResponseCodes.sdk_unknown_error,
11683
- });
11684
- }
11577
+ await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
11685
11578
  }
11686
11579
  const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareTransactionAuth(authenticationOptions, walletId);
11687
11580
  const { message, signature } = signatureMessage;
@@ -11746,20 +11639,7 @@ class Transactions extends Base {
11746
11639
  try {
11747
11640
  // Only attempt migration if we have password auth and V2 storage might be incomplete
11748
11641
  if (this.deviceAuthType === AuthType.Password && authenticationOptions.password) {
11749
- try {
11750
- await this.walletService.handleUpdateToV2({
11751
- password: authenticationOptions.password,
11752
- walletId: walletId,
11753
- });
11754
- }
11755
- catch (error) {
11756
- logger.error('SDK::Transactions::resolvePendingTransaction::handleUpdateToV2::error', error);
11757
- throw new WallabyError({
11758
- message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
11759
- statusCode: 500,
11760
- errorCode: ErrorResponseCodes.sdk_unknown_error,
11761
- });
11762
- }
11642
+ await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
11763
11643
  }
11764
11644
  const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareTransactionAuth(authenticationOptions, walletId);
11765
11645
  if (!readyForTransportSeedPhrase && !hasShares) {
@@ -11924,16 +11804,15 @@ class Wallaby {
11924
11804
  * @param {string} [config.clientAuthToken] - A web token generated by the client for authorization.
11925
11805
  * @public
11926
11806
  */
11927
- constructor(config) {
11928
- this.wallet = new WalletService(config);
11929
- this.walletData = new WalletDataService(config);
11930
- this.utils = new Utils(config);
11931
- this.auth = new AuthService(config);
11932
- this.system = new System(config);
11933
- this.transactions = new Transactions(config);
11934
- this.swap = new Swap(config);
11935
- this.merchants = new Merchants(config);
11936
- this.httpApi = new HttpApi(config);
11807
+ constructor(config, ports = {}) {
11808
+ this.wallet = new WalletService(config, ports);
11809
+ this.walletData = new WalletDataService(config, ports);
11810
+ this.utils = new Utils(config, ports);
11811
+ this.auth = new AuthService(config, ports);
11812
+ this.system = new System(config, ports);
11813
+ this.transactions = new Transactions(config, ports);
11814
+ this.swap = new Swap(config, ports);
11815
+ this.httpApi = new HttpApi(config, ports);
11937
11816
  }
11938
11817
  get version() {
11939
11818
  return currentPackageVersion;