wallaby-cash 3.3.0 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -313,6 +313,10 @@ var V2KeyNames;
313
313
  V2KeyNames["WallabyAuthPubKey"] = "wallaby-auth-pub-key";
314
314
  V2KeyNames["MigrationVersion"] = "wsdk_migrated_with_version";
315
315
  V2KeyNames["LastMigratedAt"] = "wsdk_last_migrated_at";
316
+ V2KeyNames["PasswordResetAttempts"] = "wsdk_password_reset_attempts";
317
+ V2KeyNames["MigrationAttempts"] = "wsdk_migration_attempts";
318
+ V2KeyNames["CredentialConversionInProgress"] = "credential-conversion-in-progress";
319
+ V2KeyNames["PendingCommit"] = "pending-commit";
316
320
  })(V2KeyNames || (V2KeyNames = {}));
317
321
 
318
322
  var ErrorResponseCodes;
@@ -591,10 +595,10 @@ const MASTER_ENCRYPTION_KEY = '9fa9d3f3c77c20d3a50a08e5299644be29f6e6206ef3479fe
591
595
  const isWeb = typeof window !== 'undefined' && typeof document !== 'undefined';
592
596
  const env = {
593
597
  platform: 'web',
594
- isNative: false,
598
+ isNative: !isWeb,
595
599
  isWeb,
596
600
  };
597
- const currentPackageVersion = "3.3.0" ;
601
+ const currentPackageVersion = "3.4.0" ;
598
602
 
599
603
  /**
600
604
  * Storage keys adapter for Storage interface across different platforms.
@@ -3495,7 +3499,6 @@ const keccak256$1 = (() => {
3495
3499
  })();
3496
3500
 
3497
3501
  const DEFAULT_ENTROPY_BYTES = 32;
3498
- const MINIMUM_SHANNON_ENTROPY = 4;
3499
3502
  /**
3500
3503
  * creates a new private key
3501
3504
  * @param { Uint8Array } entropy - optional entropy to create the private key
@@ -3506,25 +3509,15 @@ const createPrivateKey = (entropy) => {
3506
3509
  if (!(entropy instanceof Uint8Array) || entropy.length < DEFAULT_ENTROPY_BYTES) {
3507
3510
  throw new Error(`entropy must be a Uint8Array of at least ${DEFAULT_ENTROPY_BYTES} bytes`);
3508
3511
  }
3509
- // Check byte diversity
3512
+ // Check byte diversity. This catches genuinely broken inputs (all-zeros, all-same-byte)
3513
+ // without false-positiving on 32-byte KDF output (~30 unique bytes expected).
3514
+ // the sampled Shannon-entropy check was removed (WAL-1465) — it's unsound for
3515
+ // 32 samples (max measurable = log2(32) ≈ 5 bits/byte vs a 4-bit threshold), so deterministic
3516
+ // KDF output could be rejected, permanently locking the user out.
3510
3517
  const uniqueBytes = new Set(entropy);
3511
3518
  if (uniqueBytes.size < Math.min(8, entropy.length / 4)) {
3512
3519
  throw new Error(`entropy is too repetitive (only ${uniqueBytes.size} unique byte values)`);
3513
3520
  }
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
3521
  const outerHex = keccak256$1(entropy);
3529
3522
  return addLeading0x(bytesToHex$1(outerHex));
3530
3523
  }
@@ -4399,6 +4392,11 @@ function pbkdf2Sync(password, salt, iterations, keylen, digest) {
4399
4392
  });
4400
4393
  }
4401
4394
 
4395
+ // Version marker prepended to values wrapped by the master key, so wrapped vs raw is deterministic.
4396
+ const MASTER_KEY_WRAP_PREFIX = 'wsdkmk:v1:';
4397
+ // crypto-js AES.encrypt with a string passphrase emits an OpenSSL "Salted__" header; its base64 always
4398
+ // starts with this. Used to recognize legacy wrapped values stored before MASTER_KEY_WRAP_PREFIX existed.
4399
+ const LEGACY_CRYPTOJS_PREFIX = 'U2FsdGVkX1';
4402
4400
  class Cipher {
4403
4401
  constructor() { }
4404
4402
  /**
@@ -4429,11 +4427,23 @@ class Cipher {
4429
4427
  * @returns The encrypted data as a string.
4430
4428
  */
4431
4429
  encryptWithMasterKey({ data }) {
4432
- return AES.encrypt(typeof data === 'string' ? data : JSON.stringify(data), this.getMasterKey().key).toString();
4430
+ const ciphertext = AES.encrypt(typeof data === 'string' ? data : JSON.stringify(data), this.getMasterKey().key).toString();
4431
+ return MASTER_KEY_WRAP_PREFIX + ciphertext;
4432
+ }
4433
+ /**
4434
+ * @description Determines deterministically whether a stored value was wrapped by the master key,
4435
+ * without inferring from decrypt behavior. Returns true for values carrying the version marker, or
4436
+ * legacy crypto-js ciphertext stored before the marker existed. Everything else is treated as raw.
4437
+ */
4438
+ isWrappedByMasterKey(value) {
4439
+ return value.startsWith(MASTER_KEY_WRAP_PREFIX) || value.startsWith(LEGACY_CRYPTOJS_PREFIX);
4433
4440
  }
4434
4441
  decryptWithMasterKey({ cipherText }) {
4442
+ const ciphertext = cipherText.startsWith(MASTER_KEY_WRAP_PREFIX)
4443
+ ? cipherText.slice(MASTER_KEY_WRAP_PREFIX.length)
4444
+ : cipherText;
4435
4445
  try {
4436
- const decrypted = AES.decrypt(cipherText, this.getMasterKey().key).toString(enc.Utf8);
4446
+ const decrypted = AES.decrypt(ciphertext, this.getMasterKey().key).toString(enc.Utf8);
4437
4447
  if (decrypted) {
4438
4448
  return isJsonString(decrypted) ? safeJsonParse(decrypted) : decrypted;
4439
4449
  }
@@ -4551,6 +4561,8 @@ class Cipher {
4551
4561
  }
4552
4562
  derivedKeyPair = await this.deriveKeyPairFromPasskey({ inputKeyMaterial: options.prfValue });
4553
4563
  return derivedKeyPair;
4564
+ default:
4565
+ throw new Error(`Unknown AuthType: ${options.authType}`);
4554
4566
  }
4555
4567
  }
4556
4568
  catch (error) {
@@ -4810,6 +4822,14 @@ class StorageService {
4810
4822
  return;
4811
4823
  }
4812
4824
  async fetch(key, options) {
4825
+ var _a;
4826
+ // Recover once per session; memoize the promise so concurrent first-fetches all await the same
4827
+ // recovery instead of racing past it and reading pre-recovery storage. recoverCommit uses
4828
+ // getItem/removeItem (not fetch), so there's no recursion. Swallow errors: recovery is
4829
+ // best-effort and a failure must not wedge every subsequent fetch.
4830
+ await ((_a = this._walRecovery) !== null && _a !== void 0 ? _a : (this._walRecovery = this.recoverCommit().catch((error) => {
4831
+ logger.error('SDK::StorageService::fetch::wal recovery failed', error);
4832
+ })));
4813
4833
  let storageKey;
4814
4834
  if (this._walletSpecificKeys.includes(key)) {
4815
4835
  if (!(options === null || options === void 0 ? void 0 : options.walletId)) {
@@ -4820,7 +4840,7 @@ class StorageService {
4820
4840
  else {
4821
4841
  storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}`;
4822
4842
  }
4823
- if (!isWeb) {
4843
+ if (env.isNative) {
4824
4844
  storageKey = normalizeKey(storageKey);
4825
4845
  }
4826
4846
  const item = await this.getItem(storageKey);
@@ -4829,14 +4849,11 @@ class StorageService {
4829
4849
  return undefined;
4830
4850
  }
4831
4851
  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;
4852
+ // Raw legacy value stored before master-key wrapping: return as-is instead of attempting decrypt.
4853
+ if (!this.cipher.isWrappedByMasterKey(item)) {
4854
+ return item;
4839
4855
  }
4856
+ const unwrapped = this.cipher.decryptWithMasterKey({ cipherText: item });
4840
4857
  if (!unwrapped) {
4841
4858
  logger.error(`Failed to decrypt item with key ${storageKey}`);
4842
4859
  return undefined;
@@ -4856,7 +4873,7 @@ class StorageService {
4856
4873
  else {
4857
4874
  storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}`;
4858
4875
  }
4859
- if (!isWeb) {
4876
+ if (env.isNative) {
4860
4877
  storageKey = normalizeKey(storageKey);
4861
4878
  }
4862
4879
  let valueToStore;
@@ -4872,6 +4889,75 @@ class StorageService {
4872
4889
  async saveInBulk(data) {
4873
4890
  await Promise.all(data.map((item) => this.save(item.key, item.value, { walletId: item.walletId })));
4874
4891
  }
4892
+ // Compute the final storage key the same way save/fetch/delete do.
4893
+ _computeRawKey(key, walletId) {
4894
+ let storageKey;
4895
+ if (this._walletSpecificKeys.includes(key)) {
4896
+ if (!walletId)
4897
+ throw new Error(`A walletId is required to compute key: ${key}`);
4898
+ storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}:${walletId}`;
4899
+ }
4900
+ else {
4901
+ storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}`;
4902
+ }
4903
+ return isWeb ? storageKey : normalizeKey(storageKey);
4904
+ }
4905
+ _serializeValue(key, value) {
4906
+ if (this._keysProtectedByMasterKey.includes(key)) {
4907
+ return this.cipher.encryptWithMasterKey({ data: value });
4908
+ }
4909
+ return typeof value === 'string' ? value : JSON.stringify(value);
4910
+ }
4911
+ async _applyWAL(record) {
4912
+ for (const { rawKey, value } of record.writes) {
4913
+ await this.setItem(rawKey, value);
4914
+ }
4915
+ for (const rawKey of record.deletes) {
4916
+ await this.removeItem(rawKey);
4917
+ }
4918
+ }
4919
+ // Atomically commit a batch of writes and deletes via a write-ahead log.
4920
+ // The WAL record is written in a single setItem before any credential key is
4921
+ // touched. A crash between that write and the individual setItem calls leaves
4922
+ // the WAL in place; recoverCommit() finishes the batch on the next call.
4923
+ async commitBatch(writes, deletes) {
4924
+ const record = {
4925
+ writes: writes.map(({ key, value, walletId }) => ({
4926
+ rawKey: this._computeRawKey(key, walletId),
4927
+ value: this._serializeValue(key, value),
4928
+ })),
4929
+ deletes: (deletes !== null && deletes !== void 0 ? deletes : []).map(({ key, walletId }) => this._computeRawKey(key, walletId)),
4930
+ };
4931
+ // Finish any dangling WAL from a prior partially-applied commit before writing a new one —
4932
+ // otherwise this setItem clobbers it and those half-written credentials become unrecoverable.
4933
+ await this.recoverCommit();
4934
+ const walKey = this._computeRawKey(V2KeyNames.PendingCommit);
4935
+ await this.setItem(walKey, JSON.stringify(record));
4936
+ await this._applyWAL(record);
4937
+ await this.removeItem(walKey);
4938
+ }
4939
+ // Re-apply a pending WAL commit if the process was killed mid-batch.
4940
+ // Call at the start of any operation that writes credential blobs.
4941
+ async recoverCommit() {
4942
+ const walKey = this._computeRawKey(V2KeyNames.PendingCommit);
4943
+ const raw = await this.getItem(walKey);
4944
+ if (!raw)
4945
+ return;
4946
+ let record;
4947
+ try {
4948
+ record = safeJsonParse(raw);
4949
+ }
4950
+ catch (error) {
4951
+ // Corrupt/unparseable WAL can never be replayed — discard so it doesn't wedge every fetch.
4952
+ logger.error('SDK::StorageService::recoverCommit::corrupt WAL, discarding', error);
4953
+ await this.removeItem(walKey);
4954
+ return;
4955
+ }
4956
+ // _applyWAL is idempotent. If it throws (transient storage error) keep the WAL and let the
4957
+ // caller retry — don't delete the only record needed to finish the batch. Remove only on success.
4958
+ await this._applyWAL(record);
4959
+ await this.removeItem(walKey);
4960
+ }
4875
4961
  async delete(key, options) {
4876
4962
  let storageKey;
4877
4963
  if (this._walletSpecificKeys.includes(key)) {
@@ -4883,7 +4969,7 @@ class StorageService {
4883
4969
  else {
4884
4970
  storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}`;
4885
4971
  }
4886
- if (!isWeb) {
4972
+ if (env.isNative) {
4887
4973
  storageKey = normalizeKey(storageKey);
4888
4974
  }
4889
4975
  return await this.removeItem(storageKey);
@@ -5148,11 +5234,16 @@ class StorageService {
5148
5234
  LocalStorageItems.AccessToken,
5149
5235
  LocalStorageItems.RefreshToken,
5150
5236
  V2KeyNames.EncryptedDevicePrivateKey,
5237
+ V2KeyNames.ClientAuthPublicKey,
5151
5238
  V2KeyNames.WallabyAuthPubKey,
5152
5239
  V2KeyNames.PasskeyCredential,
5153
5240
  V2KeyNames.MigrationVersion,
5154
5241
  V2KeyNames.LastMigratedAt,
5155
5242
  V2KeyNames.ClientAuthToken,
5243
+ V2KeyNames.PasswordResetAttempts,
5244
+ V2KeyNames.MigrationAttempts,
5245
+ V2KeyNames.CredentialConversionInProgress,
5246
+ V2KeyNames.PendingCommit,
5156
5247
  ];
5157
5248
  await Promise.all(userKeysToRemove.map((key) => this.delete(key)));
5158
5249
  if (walletId) {
@@ -5284,6 +5375,11 @@ const AuthRoutes = {
5284
5375
  method: RequestMethod.Get,
5285
5376
  requiresAccessToken: true,
5286
5377
  },
5378
+ issueJwtToken: {
5379
+ fullPath: '/auth/issue-jwt-token',
5380
+ method: RequestMethod.Post,
5381
+ requiresAccessToken: false,
5382
+ },
5287
5383
  };
5288
5384
 
5289
5385
  class LockManagerService {
@@ -7980,7 +8076,6 @@ let PasskeyService$1 = class PasskeyService {
7980
8076
  }
7981
8077
  logger.log('SDK::PasskeyService::register:: getting signature', {
7982
8078
  message: challengeResponse.message,
7983
- privateKey: deviceKeyPair.privateKey,
7984
8079
  });
7985
8080
  const { signature, message } = await this.cipher.sign({
7986
8081
  message: challengeResponse.message,
@@ -8637,7 +8732,7 @@ class AuthService extends Base {
8637
8732
  data: deviceKeyPair.privateKey,
8638
8733
  encryptionKey: credentialsKeyPair.publicKey,
8639
8734
  });
8640
- this.localStorageService.saveInBulk([
8735
+ await this.localStorageService.saveInBulk([
8641
8736
  {
8642
8737
  key: LocalStorageItems.EncryptedDevicePrivateKey,
8643
8738
  value: encryptedDevicePrivKey,
@@ -8708,6 +8803,24 @@ class AuthService extends Base {
8708
8803
  valid: true,
8709
8804
  };
8710
8805
  }
8806
+ /**
8807
+ * @description Exchanges the client JWT (set at SDK initialisation) for a
8808
+ * Wallaby access + refresh token pair. Tokens are persisted to storage so
8809
+ * subsequent SDK calls use them automatically.
8810
+ * @returns {Promise<IssueJWTTokenResponseDto>} The issued access/refresh tokens and basic user info.
8811
+ */
8812
+ async exchangeClientToken() {
8813
+ try {
8814
+ const response = await this.request(AuthRoutes.issueJwtToken);
8815
+ await this.localStorageService.save(LocalStorageItems.AccessToken, response.accessToken);
8816
+ await this.localStorageService.save(LocalStorageItems.RefreshToken, response.refreshToken);
8817
+ return response;
8818
+ }
8819
+ catch (error) {
8820
+ logger.error('SDK::Auth::exchangeClientToken::error', error);
8821
+ throw error;
8822
+ }
8823
+ }
8711
8824
  }
8712
8825
  __decorate([
8713
8826
  WithLock('signUp'),
@@ -8728,6 +8841,63 @@ __decorate([
8728
8841
  __metadata("design:returntype", Promise)
8729
8842
  ], AuthService.prototype, "storeDeviceKeyPair", null);
8730
8843
 
8844
+ const ENCRYPTED_PAYLOAD_FIELDS = ['iv', 'ephemPublicKey', 'ciphertext', 'mac'];
8845
+ // Backup share may be ECIES or symmetric ({ iv, ciphertext, mac, tag }) — both share these three fields.
8846
+ const SYMMETRIC_PAYLOAD_FIELDS = ['iv', 'ciphertext', 'mac', 'tag'];
8847
+ // API is the trust boundary: confirm every named field is a non-empty string.
8848
+ function hasNonEmptyStringFields(payload, fields) {
8849
+ return (!!payload &&
8850
+ typeof payload === 'object' &&
8851
+ fields.every((field) => {
8852
+ const value = payload[field];
8853
+ return typeof value === 'string' && value.length > 0;
8854
+ }));
8855
+ }
8856
+ /**
8857
+ * Fail fast if an encrypted payload from the API does not match the expected
8858
+ * ECIES structure ({ iv, ephemPublicKey, ciphertext, mac }). See the contract
8859
+ * note on `handleKeySharesFromResponse`.
8860
+ */
8861
+ function assertEncryptedPayloadShape(encrypted) {
8862
+ if (!hasNonEmptyStringFields(encrypted, ENCRYPTED_PAYLOAD_FIELDS)) {
8863
+ throw new WallabyError({
8864
+ message: 'Encrypted share does not match the expected { iv, ephemPublicKey, ciphertext, mac } format.',
8865
+ statusCode: 422,
8866
+ errorCode: ErrorResponseCodes.sdk_invalid_parameter,
8867
+ });
8868
+ }
8869
+ }
8870
+ /**
8871
+ * Shape-assert every share returned by the API. Empty arrays are rejected here
8872
+ * so callers get a clean error instead of crashing on `shares[0]`.
8873
+ */
8874
+ function assertSharesPayloadShape(shares) {
8875
+ if (!shares.length) {
8876
+ throw new WallabyError({
8877
+ message: 'No key shares were returned from the API.',
8878
+ statusCode: 422,
8879
+ errorCode: ErrorResponseCodes.sdk_invalid_parameter,
8880
+ });
8881
+ }
8882
+ for (const share of shares) {
8883
+ assertEncryptedPayloadShape(share.encrypted);
8884
+ }
8885
+ }
8886
+ /**
8887
+ * The backup share is stored as-is (the device can't peel it), so we only
8888
+ * shape-check it. It may be ECIES or symmetric, so accept either variant.
8889
+ */
8890
+ function assertBackupSharePayloadShape(encrypted) {
8891
+ const isEcies = hasNonEmptyStringFields(encrypted, ENCRYPTED_PAYLOAD_FIELDS);
8892
+ const isSymmetric = hasNonEmptyStringFields(encrypted, SYMMETRIC_PAYLOAD_FIELDS);
8893
+ if (!isEcies && !isSymmetric) {
8894
+ throw new WallabyError({
8895
+ message: 'Encrypted backup share does not match the expected ECIES ({ iv, ephemPublicKey, ciphertext, mac }) or symmetric ({ iv, ciphertext, mac, tag }) format.',
8896
+ statusCode: 422,
8897
+ errorCode: ErrorResponseCodes.sdk_invalid_parameter,
8898
+ });
8899
+ }
8900
+ }
8731
8901
  class WalletHandlersService extends Base {
8732
8902
  constructor(config) {
8733
8903
  super(config);
@@ -8808,6 +8978,7 @@ class WalletHandlersService extends Base {
8808
8978
  shares: importWalletRequest.shares,
8809
8979
  credentialsKeyPair,
8810
8980
  encryptedBackupShare: importWalletRequest.encryptedBackupShare,
8981
+ devicePrivateKey: deviceAuthKeys.privateKey,
8811
8982
  });
8812
8983
  }
8813
8984
  return Object.assign({}, importWalletRequest);
@@ -8894,6 +9065,7 @@ class WalletHandlersService extends Base {
8894
9065
  shares: walletCreationResponse.shares,
8895
9066
  credentialsKeyPair,
8896
9067
  encryptedBackupShare: walletCreationResponse.encryptedBackupShare,
9068
+ devicePrivateKey: deviceAuthKeys.privateKey,
8897
9069
  });
8898
9070
  }
8899
9071
  return Object.assign(Object.assign({}, walletCreationResponse), { standardSeedPhrase: decryptedSeedPhrase });
@@ -8909,8 +9081,41 @@ class WalletHandlersService extends Base {
8909
9081
  });
8910
9082
  }
8911
9083
  }
8912
- async handleKeySharesFromResponse({ walletId, shares, credentialsKeyPair, encryptedBackupShare, }) {
9084
+ /**
9085
+ * Encrypted share format contract (WAL-1467)
9086
+ * --------------------------------------------------------------------------
9087
+ * Every flow that ingests shares from the API (import, create, recover,
9088
+ * addNewDevice) routes through here, so the contract is asserted in one place.
9089
+ *
9090
+ * The API returns the main device share as `shares[0]`, an ECIES payload
9091
+ * ({ iv, ephemPublicKey, ciphertext, mac }) wrapped to the device public key,
9092
+ * so it MUST peel with the device private key. `encryptedBackupShare` is an
9093
+ * already-wrapped blob (ECIES or symmetric) that the device cannot decrypt, so
9094
+ * it is stored as-is.
9095
+ *
9096
+ * We shape-assert every share (and the backup share) here, at ingestion, so a
9097
+ * server-side wrapping change fails loudly now instead of silently breaking
9098
+ * export/recovery later.
9099
+ */
9100
+ async handleKeySharesFromResponse({ walletId, shares, credentialsKeyPair, encryptedBackupShare, devicePrivateKey, }) {
8913
9101
  try {
9102
+ assertSharesPayloadShape(shares);
9103
+ assertBackupSharePayloadShape(encryptedBackupShare);
9104
+ // Decrypt-test the contract: shares[0] is wrapped to the device public key and must peel with the device private key.
9105
+ try {
9106
+ await this.cipher.decrypt({
9107
+ cipherText: shares[0].encrypted,
9108
+ decryptionKey: devicePrivateKey,
9109
+ });
9110
+ }
9111
+ catch (error) {
9112
+ throw new WallabyError({
9113
+ message: 'Device-wrapped key share (shares[0]) could not be decrypted with the device private key; the share wrapping format may have changed.',
9114
+ statusCode: 422,
9115
+ errorCode: ErrorResponseCodes.sdk_key_share_decryption_failed,
9116
+ cause: error,
9117
+ });
9118
+ }
8914
9119
  const encryptedWithCredentialsKeyShare = await this.cipher.encrypt({
8915
9120
  data: JSON.stringify(shares[0].encrypted),
8916
9121
  encryptionKey: credentialsKeyPair.publicKey,
@@ -9004,13 +9209,42 @@ class WalletHandlersService extends Base {
9004
9209
  class WalletService extends Base {
9005
9210
  constructor(config) {
9006
9211
  super(config);
9007
- this.passwordResetAttempts = 0;
9008
- this.migrationAttempts = 0;
9009
9212
  this.authService = new AuthService(config);
9010
9213
  this.handlers = new WalletHandlersService(config);
9011
9214
  this.userId = config.userId;
9012
9215
  this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request);
9013
9216
  }
9217
+ /**
9218
+ * Reads the persisted sliding-window rate-limit state for a counter key.
9219
+ * Returns a fresh window ({ count: 0 }) when none is stored or the window has expired.
9220
+ */
9221
+ async getRateState(key) {
9222
+ const now = Date.now();
9223
+ const raw = await this.localStorageService.fetch(key);
9224
+ const state = raw ? safeJsonParse(raw) : undefined;
9225
+ if (!state || now - state.windowStart > WalletService.RATE_LIMIT_WINDOW_MS) {
9226
+ return { count: 0, windowStart: now };
9227
+ }
9228
+ return state;
9229
+ }
9230
+ /** Increments and persists the counter (resetting an expired window). Returns the new count. */
9231
+ async recordRateAttempt(key) {
9232
+ const state = await this.getRateState(key);
9233
+ state.count += 1;
9234
+ await this.localStorageService.save(key, JSON.stringify(state));
9235
+ return state.count;
9236
+ }
9237
+ /** Throws a 429 when the counter is already over the limit, without incrementing it. */
9238
+ async assertUnderRateLimit(key, message) {
9239
+ const { count } = await this.getRateState(key);
9240
+ if (count > WalletService.RATE_LIMIT_MAX) {
9241
+ throw new WallabyError({
9242
+ message,
9243
+ statusCode: 429,
9244
+ errorCode: ErrorResponseCodes.sdk_too_many_requests,
9245
+ });
9246
+ }
9247
+ }
9014
9248
  /**
9015
9249
  * @public
9016
9250
  * @returns {boolean} Returns true if the device has a seed phrase.
@@ -9116,20 +9350,7 @@ class WalletService extends Base {
9116
9350
  });
9117
9351
  }
9118
9352
  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
- }
9353
+ await this.migrateToV2Safe({ password: authenticationOptions.password, walletId });
9133
9354
  }
9134
9355
  const encryptedSeed = await this.localStorageService.fetch(LocalStorageItems.EncryptedStandardSeedPhrase, { walletId });
9135
9356
  const encryptedPrimaryDeviceShare = await this.localStorageService.fetch(LocalStorageItems.PrimaryDeviceKeyShare, {
@@ -9372,6 +9593,7 @@ class WalletService extends Base {
9372
9593
  shares: recoverWithSeedPhraseResponse.shares,
9373
9594
  credentialsKeyPair,
9374
9595
  encryptedBackupShare: recoverWithSeedPhraseResponse.encryptedBackupShare,
9596
+ devicePrivateKey: deviceAuthKeyPair.privateKey,
9375
9597
  });
9376
9598
  }
9377
9599
  await this.authService.storeDeviceKeyPair({
@@ -9435,6 +9657,7 @@ class WalletService extends Base {
9435
9657
  shares: recoverWithSeedPhraseResponse.shares,
9436
9658
  credentialsKeyPair,
9437
9659
  encryptedBackupShare: recoverWithSeedPhraseResponse.encryptedBackupShare,
9660
+ devicePrivateKey: deviceAuthKeyPair.privateKey,
9438
9661
  });
9439
9662
  }
9440
9663
  await this.authService.storeDeviceKeyPair({
@@ -9467,8 +9690,7 @@ class WalletService extends Base {
9467
9690
  */
9468
9691
  async changePassword({ walletId, oldPassword, newPassword, }) {
9469
9692
  try {
9470
- this.passwordResetAttempts += 1;
9471
- if (this.passwordResetAttempts > 5) {
9693
+ if ((await this.recordRateAttempt(V2KeyNames.PasswordResetAttempts)) > WalletService.RATE_LIMIT_MAX) {
9472
9694
  throw new WallabyError({
9473
9695
  message: 'Too many password change attempts. Please try again later.',
9474
9696
  statusCode: 429,
@@ -9477,20 +9699,7 @@ class WalletService extends Base {
9477
9699
  }
9478
9700
  if (this.deviceAuthType === AuthType.Password && oldPassword) {
9479
9701
  // 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
- }
9702
+ await this.migrateToV2Safe({ password: oldPassword, walletId });
9494
9703
  }
9495
9704
  const encryptedDevicePrivateKeyString = await this.localStorageService.fetch(V2KeyNames.EncryptedDevicePrivateKey);
9496
9705
  const encryptedSeedPhraseString = await this.localStorageService.fetch(V2KeyNames.EncryptedStandardSeedPhrase, {
@@ -9524,7 +9733,7 @@ class WalletService extends Base {
9524
9733
  password: newPassword,
9525
9734
  salt: clientSalt,
9526
9735
  });
9527
- if (!newCredentialsKeyPair.publicKey) {
9736
+ if (!newCredentialsKeyPair.publicKey || !newCredentialsKeyPair.privateKey) {
9528
9737
  throw new WallabyError({
9529
9738
  message: 'Could not derive keys for new password.',
9530
9739
  statusCode: 500,
@@ -9547,40 +9756,48 @@ class WalletService extends Base {
9547
9756
  errorCode: ErrorResponseCodes.sdk_unknown_error,
9548
9757
  });
9549
9758
  }
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,
9759
+ // Round-trip validate: decrypt the re-wrapped blob with the new key before committing.
9760
+ // Catches a malformed re-encryption before it overwrites the live credential.
9761
+ await this.assertRoundTrip(reWrappedDevicePrivateKey, newCredentialsKeyPair.privateKey, 'device key');
9762
+ const reWrappedSeedPhrase = encryptedSeedPhraseString
9763
+ ? await this.cipher.flipEncryptedData({
9764
+ cipherText: safeJsonParse(encryptedSeedPhraseString),
9555
9765
  decryptionKey: oldCredentialsKeyPair.privateKey,
9556
9766
  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,
9767
+ })
9768
+ : null;
9769
+ const reWrappedPrimaryShare = encryptedPrimaryShareString
9770
+ ? await this.cipher.flipEncryptedData({
9771
+ cipherText: safeJsonParse(encryptedPrimaryShareString),
9566
9772
  decryptionKey: oldCredentialsKeyPair.privateKey,
9567
9773
  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,
9774
+ })
9775
+ : null;
9776
+ const reWrappedBackupShare = encryptedBackupShareString
9777
+ ? await this.cipher.flipEncryptedData({
9778
+ cipherText: safeJsonParse(encryptedBackupShareString),
9577
9779
  decryptionKey: oldCredentialsKeyPair.privateKey,
9578
9780
  encryptionKey: newCredentialsKeyPair.publicKey,
9579
- });
9580
- await this.localStorageService.save(LocalStorageItems.BackupDeviceKeyShare, reWrappedBackupShare, {
9581
- walletId,
9582
- });
9583
- }
9781
+ })
9782
+ : null;
9783
+ if (reWrappedSeedPhrase)
9784
+ await this.assertRoundTrip(reWrappedSeedPhrase, newCredentialsKeyPair.privateKey, 'seed phrase');
9785
+ if (reWrappedPrimaryShare)
9786
+ await this.assertRoundTrip(reWrappedPrimaryShare, newCredentialsKeyPair.privateKey, 'primary share');
9787
+ if (reWrappedBackupShare)
9788
+ await this.assertRoundTrip(reWrappedBackupShare, newCredentialsKeyPair.privateKey, 'backup share');
9789
+ await this.localStorageService.commitBatch([
9790
+ { key: LocalStorageItems.EncryptedDevicePrivateKey, value: reWrappedDevicePrivateKey },
9791
+ ...(reWrappedSeedPhrase
9792
+ ? [{ key: LocalStorageItems.EncryptedStandardSeedPhrase, value: reWrappedSeedPhrase, walletId }]
9793
+ : []),
9794
+ ...(reWrappedPrimaryShare
9795
+ ? [{ key: LocalStorageItems.PrimaryDeviceKeyShare, value: reWrappedPrimaryShare, walletId }]
9796
+ : []),
9797
+ ...(reWrappedBackupShare ? [{ key: LocalStorageItems.BackupDeviceKeyShare, value: reWrappedBackupShare, walletId }] : []),
9798
+ ]);
9799
+ // Reset the rate-limit window on success so a normal change does not count against future ones.
9800
+ await this.localStorageService.delete(V2KeyNames.PasswordResetAttempts);
9584
9801
  return true;
9585
9802
  }
9586
9803
  catch (error) {
@@ -9633,20 +9850,7 @@ class WalletService extends Base {
9633
9850
  }
9634
9851
  const parsedEncryptedDevicePrivateKey = safeJsonParse(encryptedDevicePrivateKey);
9635
9852
  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
- }
9853
+ await this.migrateToV2Safe({ password: input.authenticationOptions.password, walletId: input.walletId });
9650
9854
  }
9651
9855
  const storedEncryptedBackupShare = await this.localStorageService.fetch(LocalStorageItems.BackupDeviceKeyShare, { walletId });
9652
9856
  if (!storedEncryptedBackupShare) {
@@ -9744,6 +9948,7 @@ class WalletService extends Base {
9744
9948
  shares: [backUpResponse.share],
9745
9949
  credentialsKeyPair,
9746
9950
  encryptedBackupShare: input.encryptedBackupShare,
9951
+ devicePrivateKey: decryptedDevicePrivateKey,
9747
9952
  });
9748
9953
  return { success: true, reference: backUpResponse.reference };
9749
9954
  }
@@ -9762,20 +9967,7 @@ class WalletService extends Base {
9762
9967
  });
9763
9968
  }
9764
9969
  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
- }
9970
+ await this.migrateToV2Safe({ password: input.authenticationOptions.password, walletId: input.walletId });
9779
9971
  }
9780
9972
  try {
9781
9973
  const walletOperationAuth = await this.prepareWalletOperationAuth({
@@ -9800,6 +9992,23 @@ class WalletService extends Base {
9800
9992
  throw error;
9801
9993
  }
9802
9994
  }
9995
+ /**
9996
+ * Wraps handleUpdateToV2 with the standard user-facing error. All call sites that gate on
9997
+ * `AuthType.Password` should go through here so the error message stays consistent.
9998
+ */
9999
+ async migrateToV2Safe({ password, walletId }) {
10000
+ try {
10001
+ await this.handleUpdateToV2({ password, walletId });
10002
+ }
10003
+ catch (error) {
10004
+ logger.error('SDK::WalletService::migrateToV2Safe::error', error);
10005
+ throw new WallabyError({
10006
+ message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
10007
+ statusCode: 500,
10008
+ errorCode: ErrorResponseCodes.sdk_unknown_error,
10009
+ });
10010
+ }
10011
+ }
9803
10012
  /**
9804
10013
  * Detects and migrates legacy/v1 storage items to v2 format.
9805
10014
  * This function should be called in methods that use password as input when v2 items are missing.
@@ -9808,13 +10017,7 @@ class WalletService extends Base {
9808
10017
  */
9809
10018
  async handleUpdateToV2({ password, walletId }) {
9810
10019
  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
- }
10020
+ await this.assertUnderRateLimit(V2KeyNames.MigrationAttempts, 'Too many migration attempts. Please try again later.');
9818
10021
  try {
9819
10022
  if (!password) {
9820
10023
  throw new WallabyError({
@@ -9885,7 +10088,7 @@ class WalletService extends Base {
9885
10088
  }
9886
10089
  }
9887
10090
  // Increment counter after V2 validation to avoid counting when migration not needed
9888
- this.migrationAttempts += 1;
10091
+ await this.recordRateAttempt(V2KeyNames.MigrationAttempts);
9889
10092
  let decryptedSeedPhrase;
9890
10093
  let decryptedPrivateKey;
9891
10094
  // Check for legacy format: `{item}_{userId}`
@@ -9938,7 +10141,10 @@ class WalletService extends Base {
9938
10141
  try {
9939
10142
  // Decrypt V1 items using storage service method (handles double encryption)
9940
10143
  logger.log('Attempting to decrypt V1 items during migration...');
9941
- logger.log('getV1DecryptedSeedPhrase should be called with password and clientSalt:', { password, clientSalt });
10144
+ logger.log('getV1DecryptedSeedPhrase should be called with password and clientSalt:', {
10145
+ hasPassword: !!password,
10146
+ hasClientSalt: !!clientSalt,
10147
+ });
9942
10148
  decryptedSeedPhrase = await this.localStorageService.getV1DecryptedSeedPhrase(password, clientSalt);
9943
10149
  // For V1 format, private key is encrypted with just the password (not salt+password like legacy)
9944
10150
  decryptedPrivateKey = await this.localStorageService.getDecryptedV1PrivateKey(password);
@@ -10165,7 +10371,28 @@ class WalletService extends Base {
10165
10371
  * @returns { boolean } whether the operation was successful
10166
10372
  */
10167
10373
  async convertToPasskey(input) {
10374
+ let passkeyRegistered = false;
10168
10375
  try {
10376
+ // Recover an interrupted conversion BEFORE reading any credential blob. A prior attempt may have
10377
+ // already rewrapped EncryptedDevicePrivateKey to passkey form (addNewPasskey persists it outside
10378
+ // this method's atomic commit), which the password can no longer decrypt — and deriving the passkey
10379
+ // key to decrypt it needs the device key itself (circular). The marker stashes the original
10380
+ // password-encrypted device key; restore it so the rest of the flow runs as a fresh conversion.
10381
+ const rawConversionMarker = (await this.localStorageService.fetch(V2KeyNames.CredentialConversionInProgress));
10382
+ const existingConversionMarker = rawConversionMarker
10383
+ ? safeJsonParse(rawConversionMarker)
10384
+ : undefined;
10385
+ // Restore the stashed device key whenever a marker carries one — independent of walletId. The
10386
+ // device key is per-user (not wallet-scoped), so a conversion interrupted on a different wallet
10387
+ // leaves the shared device key passkey-wrapped too. Restoring is idempotent (rewrites the
10388
+ // original password-encrypted blob) and stops a second wallet's conversion from destroying the
10389
+ // first's recovery state. v2 only — a v1 wallet's untouched v1 key still decrypts.
10390
+ if (existingConversionMarker === null || existingConversionMarker === void 0 ? void 0 : existingConversionMarker.encryptedDevicePrivateKey) {
10391
+ await this.localStorageService.save(LocalStorageItems.EncryptedDevicePrivateKey, existingConversionMarker.encryptedDevicePrivateKey);
10392
+ }
10393
+ if ((existingConversionMarker === null || existingConversionMarker === void 0 ? void 0 : existingConversionMarker.walletId) === input.walletId) {
10394
+ logger.info('SDK::WalletService::convertToPasskey::resuming interrupted conversion');
10395
+ }
10169
10396
  const v2EncryptedPriv = await this.localStorageService.fetch(LocalStorageItems.EncryptedDevicePrivateKey);
10170
10397
  const v2EncryptedSeed = await this.localStorageService.fetch(LocalStorageItems.EncryptedStandardSeedPhrase, {
10171
10398
  walletId: input.walletId,
@@ -10214,6 +10441,10 @@ class WalletService extends Base {
10214
10441
  });
10215
10442
  }
10216
10443
  const clientPublicKey = publicKeyByPrivateKey(decryptedClientAuthPrivKey);
10444
+ // Write-ahead marker: set before the unrevocable passkey registration so an interrupted
10445
+ // conversion can be resumed on the next attempt. Stash the original password-encrypted device
10446
+ // key so resume survives addNewPasskey rewrapping the stored device key to passkey form.
10447
+ await this.localStorageService.save(V2KeyNames.CredentialConversionInProgress, Object.assign({ walletId: input.walletId }, (v2EncryptedPriv ? { encryptedDevicePrivateKey: v2EncryptedPriv } : {})));
10217
10448
  const authentication = await this.passkeyService.addNewPasskey({
10218
10449
  deviceKeyPair: {
10219
10450
  publicKey: clientPublicKey,
@@ -10221,6 +10452,7 @@ class WalletService extends Base {
10221
10452
  },
10222
10453
  getSignature: this.authService.getSignature.bind(this),
10223
10454
  });
10455
+ passkeyRegistered = true;
10224
10456
  const prfValue = authentication.prfValue;
10225
10457
  if (!prfValue || !(prfValue instanceof Uint8Array) || prfValue.length === 0) {
10226
10458
  logger.error('SDK::WalletService::convertToPasskey::prfValue is required and must be a non-empty Uint8Array');
@@ -10317,8 +10549,13 @@ class WalletService extends Base {
10317
10549
  storeOneKeyShareWithWallaby: true,
10318
10550
  },
10319
10551
  });
10320
- // Delete the old password-encrypted seed phrase since import stored the new passkey-encrypted version
10321
- await this.localStorageService.delete(LocalStorageItems.EncryptedStandardSeedPhrase, { walletId: input.walletId });
10552
+ // idempotent — on retry (marker present, primary now passkey-encrypted so
10553
+ // decryptedPrimaryShare is undefined → Branch A re-enters), handleImportWallet re-shares
10554
+ // safely; this atomic delete clears the stale seed + marker together.
10555
+ await this.localStorageService.commitBatch([], [
10556
+ { key: LocalStorageItems.EncryptedStandardSeedPhrase, walletId: input.walletId },
10557
+ { key: V2KeyNames.CredentialConversionInProgress },
10558
+ ]);
10322
10559
  logger.info('SDK::WalletService::convertToPasskey::Wallet imported and converted successfully, old seed phrase removed');
10323
10560
  return { authentication, seedPhrase: decryptedSeedPhrase };
10324
10561
  }
@@ -10336,6 +10573,24 @@ class WalletService extends Base {
10336
10573
  privateKey: decryptedClientAuthPrivKey,
10337
10574
  },
10338
10575
  });
10576
+ // assertRoundTrip below only strips the outer (passkey) layer — validate the inner (device key) layer here.
10577
+ const outerDecrypted = await this.cipher.decrypt({
10578
+ cipherText: encryptedPrimaryShare,
10579
+ decryptionKey: passkeyDerivedKeyPair.privateKey,
10580
+ });
10581
+ const innerDecrypted = outerDecrypted
10582
+ ? await this.cipher.decrypt({
10583
+ cipherText: safeJsonParse(outerDecrypted),
10584
+ decryptionKey: decryptedClientAuthPrivKey,
10585
+ })
10586
+ : null;
10587
+ if (innerDecrypted !== decryptedPrimaryShare) {
10588
+ throw new WallabyError({
10589
+ message: 'Re-wrap validation failed for primary share: inner layer round-trip mismatch. Aborting to prevent credential corruption.',
10590
+ statusCode: 500,
10591
+ errorCode: ErrorResponseCodes.sdk_unknown_error,
10592
+ });
10593
+ }
10339
10594
  convertedShares.push({
10340
10595
  key: V2KeyNames.PrimaryDeviceKeyShare,
10341
10596
  value: encryptedPrimaryShare,
@@ -10354,9 +10609,16 @@ class WalletService extends Base {
10354
10609
  walletId: input.walletId,
10355
10610
  });
10356
10611
  }
10357
- await this.localStorageService.saveInBulk(convertedShares);
10612
+ // Round-trip validate each re-encrypted blob (outer layer only) before writing.
10613
+ // A failed decrypt here means re-encryption produced an unreadable blob — abort before overwriting live credentials.
10614
+ for (const share of convertedShares) {
10615
+ await this.assertRoundTrip(share.value, passkeyDerivedKeyPair.privateKey, share.key);
10616
+ }
10617
+ await this.localStorageService.commitBatch(convertedShares, [
10618
+ ...(v2EncryptedSeed ? [{ key: LocalStorageItems.EncryptedStandardSeedPhrase, walletId: input.walletId }] : []),
10619
+ { key: V2KeyNames.CredentialConversionInProgress },
10620
+ ]);
10358
10621
  if (v2EncryptedSeed) {
10359
- await this.localStorageService.delete(LocalStorageItems.EncryptedStandardSeedPhrase, { walletId: input.walletId });
10360
10622
  logger.info('SDK::WalletService::convertToPasskey::Seed phrase removed from device storage after conversion to passkey');
10361
10623
  }
10362
10624
  if (!decryptedSeedPhrase && decryptedPrimaryShare) {
@@ -10399,10 +10661,33 @@ class WalletService extends Base {
10399
10661
  }
10400
10662
  catch (error) {
10401
10663
  logger.error('SDK::WalletService::convertToPasskey::error', error);
10664
+ // Only clear the marker if the passkey was not yet registered. After registration the
10665
+ // marker must survive for roll-forward on the next attempt.
10666
+ if (!passkeyRegistered) {
10667
+ await this.localStorageService.delete(V2KeyNames.CredentialConversionInProgress);
10668
+ }
10402
10669
  throw error;
10403
10670
  }
10404
10671
  }
10672
+ // shared guard — decrypt-tests a re-wrapped blob before any write so a malformed
10673
+ // re-encryption is caught before it overwrites the live credential.
10674
+ async assertRoundTrip(blob, decryptionKey, label) {
10675
+ try {
10676
+ await this.cipher.decrypt({ cipherText: blob, decryptionKey });
10677
+ }
10678
+ catch (_a) {
10679
+ throw new WallabyError({
10680
+ message: `Re-wrap validation failed for ${label}: decryption of the re-encrypted blob failed. Aborting to prevent credential corruption.`,
10681
+ statusCode: 500,
10682
+ errorCode: ErrorResponseCodes.sdk_unknown_error,
10683
+ });
10684
+ }
10685
+ }
10405
10686
  }
10687
+ // soft client-side guardrail against runaway retries; server-side rate limiting is the real control.
10688
+ // Counters are persisted (sliding window) so rebuilding the service no longer resets them. Tune freely.
10689
+ WalletService.RATE_LIMIT_MAX = 5;
10690
+ WalletService.RATE_LIMIT_WINDOW_MS = 30 * 60000; // 30 min
10406
10691
  __decorate([
10407
10692
  WithLock('create'),
10408
10693
  __metadata("design:type", Function),
@@ -10422,7 +10707,7 @@ __decorate([
10422
10707
  __metadata("design:returntype", Promise)
10423
10708
  ], WalletService.prototype, "recover", null);
10424
10709
  __decorate([
10425
- WithLock('changePassword'),
10710
+ WithLock('credential-rewrap'),
10426
10711
  __metadata("design:type", Function),
10427
10712
  __metadata("design:paramtypes", [Object]),
10428
10713
  __metadata("design:returntype", Promise)
@@ -10433,6 +10718,12 @@ __decorate([
10433
10718
  __metadata("design:paramtypes", [Object]),
10434
10719
  __metadata("design:returntype", Promise)
10435
10720
  ], WalletService.prototype, "handleUpdateToV2", null);
10721
+ __decorate([
10722
+ WithLock('credential-rewrap'),
10723
+ __metadata("design:type", Function),
10724
+ __metadata("design:paramtypes", [Object]),
10725
+ __metadata("design:returntype", Promise)
10726
+ ], WalletService.prototype, "convertToPasskey", null);
10436
10727
 
10437
10728
  class WalletDataService extends Base {
10438
10729
  constructor(config) {
@@ -10685,20 +10976,7 @@ class WalletDataService extends Base {
10685
10976
  });
10686
10977
  }
10687
10978
  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
- }
10979
+ await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
10702
10980
  }
10703
10981
  try {
10704
10982
  const addressInfo = await this.walletService.generateWalletAddresses({
@@ -10899,179 +11177,6 @@ class Utils extends Base {
10899
11177
  }
10900
11178
  }
10901
11179
 
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
11180
  /**
11076
11181
  * HttpApi provides direct access to all REST API endpoints.
11077
11182
  * This class extends the Base class and includes the generated API client
@@ -11152,20 +11257,7 @@ class Swap extends Base {
11152
11257
  try {
11153
11258
  // Only attempt migration if we have password auth and V2 storage might be incomplete
11154
11259
  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
- }
11260
+ await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
11169
11261
  }
11170
11262
  const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareSwapAuth(authenticationOptions, walletId);
11171
11263
  let swapResponse;
@@ -11360,6 +11452,27 @@ const sanitizeSuiObjectId = (objectId) => {
11360
11452
  return objectId.split('::')[0];
11361
11453
  };
11362
11454
 
11455
+ /**
11456
+ * Extracts the asset symbol from a fully-qualified Sui coin type.
11457
+ *
11458
+ * A Sui coin type has the shape `<package>::<module>::<TYPE>`, where the final
11459
+ * segment is the coin's struct name and doubles as its symbol.
11460
+ *
11461
+ * @param objectId - The Sui object id / coin type. Example input:
11462
+ * "0xc91acfb75009c5ff2fd57c54f3caaee12ad1fbe997681334adc0b574fc277a07::icorgi::ICORGI"
11463
+ * @returns The symbol (e.g. "ICORGI"), or undefined when the id carries no
11464
+ * `::module::TYPE` suffix to derive it from.
11465
+ */
11466
+ const extractSuiAssetSymbol = (objectId) => {
11467
+ var _a;
11468
+ if (!objectId || !objectId.includes('::')) {
11469
+ return undefined;
11470
+ }
11471
+ const segments = objectId.split('::');
11472
+ const symbol = (_a = segments[segments.length - 1]) === null || _a === void 0 ? void 0 : _a.trim();
11473
+ return symbol || undefined;
11474
+ };
11475
+
11363
11476
  class System extends Base {
11364
11477
  constructor(config) {
11365
11478
  super(config);
@@ -11448,6 +11561,9 @@ class System extends Base {
11448
11561
  * @param {BlockchainName} blockchain - The name of the blockchain.
11449
11562
  * @param {string} contractAddress - The contract address of the token (optional for non-SUI blockchains).
11450
11563
  * @param {string} suiObjectId - The SUI object ID of the token (optional for SUI blockchain).
11564
+ * @param {string} assetSymbol - The asset symbol; disambiguates new SUI assets. For SUI it is
11565
+ * optional: when omitted, it is derived from the `::module::TYPE` suffix of `suiObjectId`
11566
+ * (which is otherwise trimmed off before the request is sent).
11451
11567
  *
11452
11568
  * @returns {Promise<{ decimals: number; symbol: string; name: string; tokenContractAddress: string }>} A promise that resolves to an object containing token information.
11453
11569
  *
@@ -11456,18 +11572,19 @@ class System extends Base {
11456
11572
  * @throws Will throw an error if `contractAddress` is not provided for non-SUI blockchains.
11457
11573
  * @throws Will throw an error if the response is invalid or contains an error.
11458
11574
  */
11459
- async fetchTokenInfo({ blockchain, contractAddress, suiObjectId, }) {
11575
+ async fetchTokenInfo({ blockchain, contractAddress, suiObjectId, assetSymbol, }) {
11460
11576
  try {
11461
11577
  const validatedContractAddress = this.validateContractAddress({
11462
11578
  blockchain,
11463
11579
  contractAddress,
11464
11580
  suiObjectId,
11465
11581
  });
11582
+ // For SUI, the coin symbol is the last segment of the coin type
11583
+ // (`<package>::<module>::<TYPE>`), which sanitizeSuiObjectId strips out.
11584
+ // Derive it so callers don't have to pass assetSymbol explicitly.
11585
+ const resolvedAssetSymbol = assetSymbol !== null && assetSymbol !== void 0 ? assetSymbol : (blockchain === BlockchainName.Sui ? extractSuiAssetSymbol(suiObjectId) : undefined);
11466
11586
  const response = await this.request(SystemRoutes.fetchTokenInfo, {
11467
- queryParams: {
11468
- chainName: blockchain,
11469
- tokenContractAddress: validatedContractAddress,
11470
- },
11587
+ queryParams: Object.assign({ chainName: blockchain, tokenContractAddress: validatedContractAddress }, (resolvedAssetSymbol ? { assetSymbol: resolvedAssetSymbol } : {})),
11471
11588
  });
11472
11589
  return response;
11473
11590
  }
@@ -11681,20 +11798,7 @@ class Transactions extends Base {
11681
11798
  try {
11682
11799
  // Only attempt migration if we have password auth and V2 storage might be incomplete
11683
11800
  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
- }
11801
+ await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
11698
11802
  }
11699
11803
  const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareTransactionAuth(authenticationOptions, walletId);
11700
11804
  let transferResponse;
@@ -11782,20 +11886,7 @@ class Transactions extends Base {
11782
11886
  }
11783
11887
  // Only attempt migration if we have password auth and V2 storage might be incomplete
11784
11888
  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
- }
11889
+ await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
11799
11890
  }
11800
11891
  const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareTransactionAuth(authenticationOptions, walletId);
11801
11892
  const { message, signature } = signatureMessage;
@@ -11860,20 +11951,7 @@ class Transactions extends Base {
11860
11951
  try {
11861
11952
  // Only attempt migration if we have password auth and V2 storage might be incomplete
11862
11953
  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
- }
11954
+ await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
11877
11955
  }
11878
11956
  const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareTransactionAuth(authenticationOptions, walletId);
11879
11957
  if (!readyForTransportSeedPhrase && !hasShares) {
@@ -12046,7 +12124,6 @@ class Wallaby {
12046
12124
  this.system = new System(config);
12047
12125
  this.transactions = new Transactions(config);
12048
12126
  this.swap = new Swap(config);
12049
- this.merchants = new Merchants(config);
12050
12127
  this.httpApi = new HttpApi(config);
12051
12128
  }
12052
12129
  get version() {