wallaby-cash 3.5.0 → 3.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -344,6 +344,8 @@ exports.V2KeyNames = void 0;
344
344
  V2KeyNames["LastMigratedAt"] = "wsdk_last_migrated_at";
345
345
  V2KeyNames["PasswordResetAttempts"] = "wsdk_password_reset_attempts";
346
346
  V2KeyNames["MigrationAttempts"] = "wsdk_migration_attempts";
347
+ V2KeyNames["CredentialConversionInProgress"] = "credential-conversion-in-progress";
348
+ V2KeyNames["PendingCommit"] = "pending-commit";
347
349
  })(exports.V2KeyNames || (exports.V2KeyNames = {}));
348
350
 
349
351
  exports.ErrorResponseCodes = void 0;
@@ -599,6 +601,7 @@ const defaultEnvironment = (_a = browser$1.env.NODE_ENV) !== null && _a !== void
599
601
  * Please pass the network value in the WallabyConfigOptions object to override it for production-mainnet.
600
602
  */
601
603
  const defaultNetwork = 'testnet';
604
+ const isTest = browser$1.env.NODE_ENV === 'test';
602
605
  const DEFAULT_ENTROPY_BYTES$1 = 32;
603
606
  const PBKDF2_ITERATIONS = 131072;
604
607
  const DEFAULT_HOSTNAME = 'https://www.republic.com';
@@ -624,7 +627,7 @@ const env = {
624
627
  isNative: !isWeb,
625
628
  isWeb,
626
629
  };
627
- const currentPackageVersion = "3.3.0" ;
630
+ const currentPackageVersion = "3.5.2" ;
628
631
 
629
632
  /**
630
633
  * Storage keys adapter for Storage interface across different platforms.
@@ -3537,7 +3540,7 @@ const createPrivateKey = (entropy) => {
3537
3540
  }
3538
3541
  // Check byte diversity. This catches genuinely broken inputs (all-zeros, all-same-byte)
3539
3542
  // without false-positiving on 32-byte KDF output (~30 unique bytes expected).
3540
- // ponytail: the sampled Shannon-entropy check was removed (WAL-1465) — it's unsound for
3543
+ // the sampled Shannon-entropy check was removed (WAL-1465) — it's unsound for
3541
3544
  // 32 samples (max measurable = log2(32) ≈ 5 bits/byte vs a 4-bit threshold), so deterministic
3542
3545
  // KDF output could be rejected, permanently locking the user out.
3543
3546
  const uniqueBytes = new Set(entropy);
@@ -4418,24 +4421,166 @@ function pbkdf2Sync(password, salt, iterations, keylen, digest) {
4418
4421
  });
4419
4422
  }
4420
4423
 
4424
+ /**
4425
+ * Pure crypto core (WAL-1469). Module-level functions with no logging, no storage,
4426
+ * no network, and no hidden state: every input (including key material) is a parameter.
4427
+ *
4428
+ * The formats produced/consumed here are pinned by the known-answer tests in
4429
+ * src/tests/kat/ — real user data encrypted in the field depends on them, so any
4430
+ * change to these functions must keep those tests green, and any format change
4431
+ * needs an explicit versioned migration.
4432
+ */
4421
4433
  // Version marker prepended to values wrapped by the master key, so wrapped vs raw is deterministic.
4422
4434
  const MASTER_KEY_WRAP_PREFIX = 'wsdkmk:v1:';
4423
4435
  // crypto-js AES.encrypt with a string passphrase emits an OpenSSL "Salted__" header; its base64 always
4424
4436
  // starts with this. Used to recognize legacy wrapped values stored before MASTER_KEY_WRAP_PREFIX existed.
4425
4437
  const LEGACY_CRYPTOJS_PREFIX = 'U2FsdGVkX1';
4438
+ // `satisfies keyof` ties these literal lists to the generated DTOs, so a field
4439
+ // rename/removal there fails the build here instead of silently going stale.
4440
+ const ENCRYPTED_PAYLOAD_FIELDS = [
4441
+ 'iv',
4442
+ 'ephemPublicKey',
4443
+ 'ciphertext',
4444
+ 'mac',
4445
+ ];
4446
+ // v is a version number for the symmetric encryption format, so it is not a string field.
4447
+ const SYMMETRIC_PAYLOAD_FIELDS = ['iv', 'ciphertext', 'tag'];
4448
+ // API is the trust boundary: confirm every named field is a non-empty string.
4449
+ function hasNonEmptyStringFields(payload, fields) {
4450
+ return (!!payload &&
4451
+ typeof payload === 'object' &&
4452
+ fields.every((field) => {
4453
+ const value = payload[field];
4454
+ return typeof value === 'string' && value.length > 0;
4455
+ }));
4456
+ }
4457
+ /**
4458
+ * True when the payload matches the ECIES envelope { iv, ephemPublicKey, ciphertext, mac }.
4459
+ */
4460
+ function isEciesPayload(payload) {
4461
+ return hasNonEmptyStringFields(payload, ENCRYPTED_PAYLOAD_FIELDS);
4462
+ }
4463
+ /**
4464
+ * True when the payload matches the symmetric envelope { v, iv, ciphertext, tag } with numeric v.
4465
+ */
4466
+ function isSymmetricPayload(payload) {
4467
+ return (hasNonEmptyStringFields(payload, SYMMETRIC_PAYLOAD_FIELDS) &&
4468
+ typeof payload.v === 'number');
4469
+ }
4470
+ /**
4471
+ * Validate that a private key is the correct length and not weak.
4472
+ */
4473
+ function validatePrivateKey(privateKey) {
4474
+ if (!/^0x[0-9a-fA-F]{64}$/.test(privateKey)) {
4475
+ throw new Error('Invalid private key: must be a 32-byte hex string');
4476
+ }
4477
+ // A valid key is a scalar in [1, n-1] that projects onto the secp256k1 curve.
4478
+ // isValidPrivateKey does that range check (and is what getPublicKey runs under the hood).
4479
+ if (!secp256k1.utils.isValidPrivateKey(privateKey.slice(2))) {
4480
+ throw new Error('Invalid private key: outside secp256k1 scalar range');
4481
+ }
4482
+ }
4483
+ /**
4484
+ * Validate that a public key is the correct length and format.
4485
+ */
4486
+ function validatePublicKey(publicKey) {
4487
+ if (!/^[0-9a-fA-F]{128}$/.test(publicKey)) {
4488
+ throw new Error('Invalid public key: must be a 64-byte raw uncompressed hex string');
4489
+ }
4490
+ const uniqueChars = new Set(publicKey);
4491
+ if (uniqueChars.size <= 8) {
4492
+ throw new Error('Weak public key: too few unique characters');
4493
+ }
4494
+ }
4495
+ /**
4496
+ * Validate that a salt is sufficiently long and not weak.
4497
+ */
4498
+ function validateSalt(salt) {
4499
+ if (utf8ToBytes$1(salt).length < 16) {
4500
+ throw new Error('Salt is too short: must be at least 16 bytes');
4501
+ }
4502
+ const uniqueChars = new Set(salt);
4503
+ if (uniqueChars.size <= 6) {
4504
+ throw new Error('Weak salt: too few unique characters');
4505
+ }
4506
+ }
4507
+ /**
4508
+ * Accept an Encrypted payload either as the object or its JSON.stringify'd storage form.
4509
+ */
4510
+ function parseEncrypted(value) {
4511
+ return typeof value === 'string' ? JSON.parse(value) : value;
4512
+ }
4513
+ /**
4514
+ * Derives a key pair from a password and salt: NFKC-normalize + trim, then
4515
+ * PBKDF2-SHA256 (PBKDF2_ITERATIONS) into a createIdentity keypair.
4516
+ */
4517
+ function deriveKeyPairFromPassword({ password, salt }) {
4518
+ validateSalt(salt);
4519
+ // Compatibility Composition
4520
+ // Prevents different Unicode representations of "same" password
4521
+ // Also trim whitespace for security consistency
4522
+ const normalizedPassword = password.normalize('NFKC').trim();
4523
+ const encryptionKey = pbkdf2Sync(utf8ToBytes$1(normalizedPassword), utf8ToBytes$1(salt), PBKDF2_ITERATIONS, DEFAULT_ENTROPY_BYTES$1, 'sha256');
4524
+ return createIdentity(encryptionKey);
4525
+ }
4526
+ /**
4527
+ * Derives a key pair from passkey PRF input key material.
4528
+ */
4529
+ function deriveKeyPairFromPasskey({ inputKeyMaterial }) {
4530
+ return createIdentity(inputKeyMaterial);
4531
+ }
4532
+ /**
4533
+ * crypto-js AES with a string passphrase (OpenSSL salted format). This is the legacy
4534
+ * V1 storage cipher and the primitive under the master-key wrap; kept only for
4535
+ * backward compatibility with data already encrypted in the field.
4536
+ */
4537
+ function legacyAesEncrypt(data, passphrase) {
4538
+ return cryptoJs.AES.encrypt(data, passphrase).toString();
4539
+ }
4540
+ function legacyAesDecrypt(cipherText, passphrase) {
4541
+ return cryptoJs.AES.decrypt(cipherText, passphrase).toString(cryptoJs.enc.Utf8);
4542
+ }
4543
+ /**
4544
+ * Wraps a value with the master key, prefixed with the format version marker.
4545
+ */
4546
+ function wrapWithMasterKey(data, masterKey) {
4547
+ return MASTER_KEY_WRAP_PREFIX + legacyAesEncrypt(typeof data === 'string' ? data : JSON.stringify(data), masterKey);
4548
+ }
4549
+ /**
4550
+ * Determines deterministically whether a stored value was wrapped by the master key,
4551
+ * without inferring from decrypt behavior. Returns true for values carrying the version
4552
+ * marker, or legacy crypto-js ciphertext stored before the marker existed.
4553
+ */
4554
+ function isMasterKeyWrapped(value) {
4555
+ return value.startsWith(MASTER_KEY_WRAP_PREFIX) || value.startsWith(LEGACY_CRYPTOJS_PREFIX);
4556
+ }
4557
+ /**
4558
+ * Unwraps a master-key-wrapped value (current prefixed format or legacy unprefixed blob).
4559
+ * Returns the parsed object for JSON payloads, the raw string otherwise, and undefined
4560
+ * when the ciphertext decrypts to nothing. Throws on malformed ciphertext (crypto-js
4561
+ * "Malformed UTF-8 data") — callers translate/log.
4562
+ */
4563
+ function unwrapWithMasterKey(cipherText, masterKey) {
4564
+ const ciphertext = cipherText.startsWith(MASTER_KEY_WRAP_PREFIX) ? cipherText.slice(MASTER_KEY_WRAP_PREFIX.length) : cipherText;
4565
+ const decrypted = legacyAesDecrypt(ciphertext, masterKey);
4566
+ if (decrypted) {
4567
+ return isJsonString(decrypted) ? safeJsonParse(decrypted) : decrypted;
4568
+ }
4569
+ return undefined;
4570
+ }
4571
+
4572
+ /**
4573
+ * Impure shell over the pure crypto core (./cipher-core). This class only adds
4574
+ * logging, user-facing error translation, and the master-key constant; all crypto
4575
+ * and format logic lives in cipher-core and is pinned by the KATs in src/tests/kat/.
4576
+ */
4426
4577
  class Cipher {
4427
4578
  constructor() { }
4428
4579
  /**
4429
4580
  * Validate that a private key is the correct length and not weak.
4430
4581
  */
4431
4582
  validatePrivateKey(privateKey) {
4432
- if (!/^0x[0-9a-fA-F]{64}$/.test(privateKey)) {
4433
- throw new Error('Invalid private key: must be a 32-byte hex string');
4434
- }
4435
- const uniqueChars = new Set(privateKey.slice(2)); // Remove '0x' prefix
4436
- if (uniqueChars.size <= 8) {
4437
- throw new Error('Weak private key: too few unique characters');
4438
- }
4583
+ validatePrivateKey(privateKey);
4439
4584
  }
4440
4585
  /**
4441
4586
  * @description For an additional layer of security, this function returns a master key from a constant MASTER_ENCRYPTION_KEY.
@@ -4453,8 +4598,7 @@ class Cipher {
4453
4598
  * @returns The encrypted data as a string.
4454
4599
  */
4455
4600
  encryptWithMasterKey({ data }) {
4456
- const ciphertext = cryptoJs.AES.encrypt(typeof data === 'string' ? data : JSON.stringify(data), this.getMasterKey().key).toString();
4457
- return MASTER_KEY_WRAP_PREFIX + ciphertext;
4601
+ return wrapWithMasterKey(data, this.getMasterKey().key);
4458
4602
  }
4459
4603
  /**
4460
4604
  * @description Determines deterministically whether a stored value was wrapped by the master key,
@@ -4462,16 +4606,13 @@ class Cipher {
4462
4606
  * legacy crypto-js ciphertext stored before the marker existed. Everything else is treated as raw.
4463
4607
  */
4464
4608
  isWrappedByMasterKey(value) {
4465
- return value.startsWith(MASTER_KEY_WRAP_PREFIX) || value.startsWith(LEGACY_CRYPTOJS_PREFIX);
4609
+ return isMasterKeyWrapped(value);
4466
4610
  }
4467
4611
  decryptWithMasterKey({ cipherText }) {
4468
- const ciphertext = cipherText.startsWith(MASTER_KEY_WRAP_PREFIX)
4469
- ? cipherText.slice(MASTER_KEY_WRAP_PREFIX.length)
4470
- : cipherText;
4471
4612
  try {
4472
- const decrypted = cryptoJs.AES.decrypt(ciphertext, this.getMasterKey().key).toString(cryptoJs.enc.Utf8);
4473
- if (decrypted) {
4474
- return isJsonString(decrypted) ? safeJsonParse(decrypted) : decrypted;
4613
+ const decrypted = unwrapWithMasterKey(cipherText, this.getMasterKey().key);
4614
+ if (decrypted !== undefined) {
4615
+ return decrypted;
4475
4616
  }
4476
4617
  }
4477
4618
  catch (error) {
@@ -4486,25 +4627,13 @@ class Cipher {
4486
4627
  * Validate that a public key is the correct length and format.
4487
4628
  */
4488
4629
  validatePublicKey(publicKey) {
4489
- if (!/^[0-9a-fA-F]{128}$/.test(publicKey)) {
4490
- throw new Error('Invalid public key: must be a 64-byte raw uncompressed hex string');
4491
- }
4492
- const uniqueChars = new Set(publicKey);
4493
- if (uniqueChars.size <= 8) {
4494
- throw new Error('Weak public key: too few unique characters');
4495
- }
4630
+ validatePublicKey(publicKey);
4496
4631
  }
4497
4632
  /**
4498
4633
  * Validate that a salt is sufficiently long and not weak.
4499
4634
  */
4500
4635
  validateSalt(salt) {
4501
- if (utf8ToBytes$1(salt).length < 16) {
4502
- throw new Error('Salt is too short: must be at least 16 bytes');
4503
- }
4504
- const uniqueChars = new Set(salt);
4505
- if (uniqueChars.size <= 6) {
4506
- throw new Error('Weak salt: too few unique characters');
4507
- }
4636
+ validateSalt(salt);
4508
4637
  }
4509
4638
  /**
4510
4639
  * @description Signs a message using the provided private key.
@@ -4551,10 +4680,7 @@ class Cipher {
4551
4680
  async decrypt({ cipherText, decryptionKey }) {
4552
4681
  try {
4553
4682
  this.validatePrivateKey(decryptionKey);
4554
- if (typeof cipherText === 'string') {
4555
- cipherText = JSON.parse(cipherText);
4556
- }
4557
- const decrypted = await decryptWithPrivateKey(decryptionKey, cipherText);
4683
+ const decrypted = await decryptWithPrivateKey(decryptionKey, parseEncrypted(cipherText));
4558
4684
  return decrypted;
4559
4685
  }
4560
4686
  catch (error) {
@@ -4789,8 +4915,7 @@ class Cipher {
4789
4915
  * @returns {Promise<{ privateKey: string; publicKey: string }>} The derived key pair.
4790
4916
  */
4791
4917
  async deriveKeyPairFromPasskey({ inputKeyMaterial }) {
4792
- const identityFromInputKey = createIdentity(inputKeyMaterial);
4793
- return identityFromInputKey;
4918
+ return deriveKeyPairFromPasskey({ inputKeyMaterial });
4794
4919
  }
4795
4920
  /**
4796
4921
  * @description Derives a key pair from the provided password and salt.
@@ -4799,14 +4924,7 @@ class Cipher {
4799
4924
  * @returns {Promise<{ privateKey: string; publicKey: string }>} The derived key pair.
4800
4925
  */
4801
4926
  async deriveKeyPairFromPassword({ password, salt }) {
4802
- this.validateSalt(salt);
4803
- // Compatibility Composition
4804
- // Prevents different Unicode representations of "same" password
4805
- // Also trim whitespace for security consistency
4806
- const normalizedPassword = password.normalize('NFKC').trim();
4807
- const encryptionKey = pbkdf2Sync(utf8ToBytes$1(normalizedPassword), utf8ToBytes$1(salt), PBKDF2_ITERATIONS, DEFAULT_ENTROPY_BYTES$1, 'sha256');
4808
- const encryptionKeyPair = createIdentity(encryptionKey);
4809
- return encryptionKeyPair;
4927
+ return deriveKeyPairFromPassword({ password, salt });
4810
4928
  }
4811
4929
  }
4812
4930
 
@@ -4848,6 +4966,14 @@ class StorageService {
4848
4966
  return;
4849
4967
  }
4850
4968
  async fetch(key, options) {
4969
+ var _a;
4970
+ // Recover once per session; memoize the promise so concurrent first-fetches all await the same
4971
+ // recovery instead of racing past it and reading pre-recovery storage. recoverCommit uses
4972
+ // getItem/removeItem (not fetch), so there's no recursion. Swallow errors: recovery is
4973
+ // best-effort and a failure must not wedge every subsequent fetch.
4974
+ await ((_a = this._walRecovery) !== null && _a !== void 0 ? _a : (this._walRecovery = this.recoverCommit().catch((error) => {
4975
+ logger.error('SDK::StorageService::fetch::wal recovery failed', error);
4976
+ })));
4851
4977
  let storageKey;
4852
4978
  if (this._walletSpecificKeys.includes(key)) {
4853
4979
  if (!(options === null || options === void 0 ? void 0 : options.walletId)) {
@@ -4907,6 +5033,75 @@ class StorageService {
4907
5033
  async saveInBulk(data) {
4908
5034
  await Promise.all(data.map((item) => this.save(item.key, item.value, { walletId: item.walletId })));
4909
5035
  }
5036
+ // Compute the final storage key the same way save/fetch/delete do.
5037
+ _computeRawKey(key, walletId) {
5038
+ let storageKey;
5039
+ if (this._walletSpecificKeys.includes(key)) {
5040
+ if (!walletId)
5041
+ throw new Error(`A walletId is required to compute key: ${key}`);
5042
+ storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}:${walletId}`;
5043
+ }
5044
+ else {
5045
+ storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}`;
5046
+ }
5047
+ return isWeb ? storageKey : normalizeKey(storageKey);
5048
+ }
5049
+ _serializeValue(key, value) {
5050
+ if (this._keysProtectedByMasterKey.includes(key)) {
5051
+ return this.cipher.encryptWithMasterKey({ data: value });
5052
+ }
5053
+ return typeof value === 'string' ? value : JSON.stringify(value);
5054
+ }
5055
+ async _applyWAL(record) {
5056
+ for (const { rawKey, value } of record.writes) {
5057
+ await this.setItem(rawKey, value);
5058
+ }
5059
+ for (const rawKey of record.deletes) {
5060
+ await this.removeItem(rawKey);
5061
+ }
5062
+ }
5063
+ // Atomically commit a batch of writes and deletes via a write-ahead log.
5064
+ // The WAL record is written in a single setItem before any credential key is
5065
+ // touched. A crash between that write and the individual setItem calls leaves
5066
+ // the WAL in place; recoverCommit() finishes the batch on the next call.
5067
+ async commitBatch(writes, deletes) {
5068
+ const record = {
5069
+ writes: writes.map(({ key, value, walletId }) => ({
5070
+ rawKey: this._computeRawKey(key, walletId),
5071
+ value: this._serializeValue(key, value),
5072
+ })),
5073
+ deletes: (deletes !== null && deletes !== void 0 ? deletes : []).map(({ key, walletId }) => this._computeRawKey(key, walletId)),
5074
+ };
5075
+ // Finish any dangling WAL from a prior partially-applied commit before writing a new one —
5076
+ // otherwise this setItem clobbers it and those half-written credentials become unrecoverable.
5077
+ await this.recoverCommit();
5078
+ const walKey = this._computeRawKey(exports.V2KeyNames.PendingCommit);
5079
+ await this.setItem(walKey, JSON.stringify(record));
5080
+ await this._applyWAL(record);
5081
+ await this.removeItem(walKey);
5082
+ }
5083
+ // Re-apply a pending WAL commit if the process was killed mid-batch.
5084
+ // Call at the start of any operation that writes credential blobs.
5085
+ async recoverCommit() {
5086
+ const walKey = this._computeRawKey(exports.V2KeyNames.PendingCommit);
5087
+ const raw = await this.getItem(walKey);
5088
+ if (!raw)
5089
+ return;
5090
+ let record;
5091
+ try {
5092
+ record = safeJsonParse(raw);
5093
+ }
5094
+ catch (error) {
5095
+ // Corrupt/unparseable WAL can never be replayed — discard so it doesn't wedge every fetch.
5096
+ logger.error('SDK::StorageService::recoverCommit::corrupt WAL, discarding', error);
5097
+ await this.removeItem(walKey);
5098
+ return;
5099
+ }
5100
+ // _applyWAL is idempotent. If it throws (transient storage error) keep the WAL and let the
5101
+ // caller retry — don't delete the only record needed to finish the batch. Remove only on success.
5102
+ await this._applyWAL(record);
5103
+ await this.removeItem(walKey);
5104
+ }
4910
5105
  async delete(key, options) {
4911
5106
  let storageKey;
4912
5107
  if (this._walletSpecificKeys.includes(key)) {
@@ -5191,6 +5386,8 @@ class StorageService {
5191
5386
  exports.V2KeyNames.ClientAuthToken,
5192
5387
  exports.V2KeyNames.PasswordResetAttempts,
5193
5388
  exports.V2KeyNames.MigrationAttempts,
5389
+ exports.V2KeyNames.CredentialConversionInProgress,
5390
+ exports.V2KeyNames.PendingCommit,
5194
5391
  ];
5195
5392
  await Promise.all(userKeysToRemove.map((key) => this.delete(key)));
5196
5393
  if (walletId) {
@@ -5237,11 +5434,11 @@ class StorageService {
5237
5434
  * @param jwt - The JWT string to check. If null, the function will return true.
5238
5435
  * @returns `true` if the JWT has expired or is null, otherwise `false`.
5239
5436
  */
5240
- function jwtHasExpired(jwt, now = Date.now) {
5437
+ function jwtHasExpired(jwt) {
5241
5438
  if (!jwt) {
5242
5439
  return true;
5243
5440
  }
5244
- return millisecondsToJWTTimeout(jwt, now) <= 0;
5441
+ return millisecondsToJWTTimeout(jwt) <= 0;
5245
5442
  }
5246
5443
  function jwtHasSameUser(jwt, userId) {
5247
5444
  if (!jwt || !userId) {
@@ -5261,11 +5458,11 @@ function userIsMfaVerified(jwt) {
5261
5458
  * @param thresholdSeconds - Number of seconds before expiry to consider "near expiry".
5262
5459
  * @returns `true` if the JWT expires within `thresholdSeconds` seconds, otherwise `false`.
5263
5460
  */
5264
- function isJwtNearExpiry(jwt, thresholdSeconds, now = Date.now) {
5461
+ function isJwtNearExpiry(jwt, thresholdSeconds) {
5265
5462
  if (!jwt) {
5266
5463
  return false;
5267
5464
  }
5268
- return millisecondsToJWTTimeout(jwt, now) <= thresholdSeconds * 1000;
5465
+ return millisecondsToJWTTimeout(jwt) <= thresholdSeconds * 1000;
5269
5466
  }
5270
5467
  /**
5271
5468
  * Calculates the remaining time in milliseconds until a given JWT expires.
@@ -5273,11 +5470,11 @@ function isJwtNearExpiry(jwt, thresholdSeconds, now = Date.now) {
5273
5470
  * @param jwt - The JWT string to decode and check.
5274
5471
  * @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.
5275
5472
  */
5276
- function millisecondsToJWTTimeout(jwt, now = Date.now) {
5473
+ function millisecondsToJWTTimeout(jwt) {
5277
5474
  const jwtDecoded = jwtDecode.jwtDecode(jwt);
5278
5475
  const jwtExpirationTimeSeconds = jwtDecoded.exp;
5279
5476
  const jwtExpirationTimeMilliseconds = (jwtExpirationTimeSeconds !== null && jwtExpirationTimeSeconds !== void 0 ? jwtExpirationTimeSeconds : 0) * 1000;
5280
- const timeNowMilliseconds = now();
5477
+ const timeNowMilliseconds = Date.now();
5281
5478
  return jwtExpirationTimeMilliseconds - timeNowMilliseconds;
5282
5479
  }
5283
5480
 
@@ -5340,7 +5537,23 @@ class LockManagerService {
5340
5537
  * @returns Promise that resolves with the operation result
5341
5538
  */
5342
5539
  async withLock(key, operation) {
5343
- // Check if this operation is already locked
5540
+ // On web, use the Web Locks API so the lock serializes across browser tabs too.
5541
+ // `ifAvailable: true` preserves the throw-fast contract: a held lock yields a null
5542
+ // lock instead of waiting, so we surface the same "already in progress" error.
5543
+ // Gate on a real browser (window+document) rather than navigator.locks alone:
5544
+ // modern Node ships a process-global navigator.locks, which would defeat the
5545
+ // in-process semantics the native/Node fallback (and existing tests) rely on.
5546
+ const isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined';
5547
+ const locks = isBrowser && typeof navigator !== 'undefined' ? navigator.locks : undefined;
5548
+ if (locks) {
5549
+ return locks.request(key, { ifAvailable: true }, async (lock) => {
5550
+ if (!lock) {
5551
+ throw new Error(`Operation '${key}' is already in progress. Please wait for it to complete.`);
5552
+ }
5553
+ return operation();
5554
+ });
5555
+ }
5556
+ // in-process Set fallback for native/Node (no tabs, single JS context => sufficient).
5344
5557
  if (this.activeLocks.has(key)) {
5345
5558
  throw new Error(`Operation '${key}' is already in progress. Please wait for it to complete.`);
5346
5559
  }
@@ -5348,8 +5561,7 @@ class LockManagerService {
5348
5561
  this.activeLocks.add(key);
5349
5562
  try {
5350
5563
  // Execute the operation
5351
- const result = await operation();
5352
- return result;
5564
+ return await operation();
5353
5565
  }
5354
5566
  finally {
5355
5567
  // Always release the lock
@@ -6925,9 +7137,12 @@ function shouldClearTokensAfterRefreshFailure(error) {
6925
7137
 
6926
7138
  // Module-level dedupe manager for token refresh to ensure only one refresh request per user/environment/network at a time
6927
7139
  const refreshDedupeManager = new DedupeManagerService();
7140
+ // one origin-wide lock manager shared by every service instance, so WalletService/AuthService/etc.
7141
+ // actually contend. Global lock keys (no per-user scoping); add scoping only if multiple users share one process.
7142
+ const sharedLockManager = new LockManagerService();
6928
7143
  class Base {
6929
- constructor(config, ports = {}) {
6930
- var _a, _b, _c, _d, _e;
7144
+ constructor(config) {
7145
+ var _a, _b;
6931
7146
  const sanitizedConfig = sanitizeConfig(config);
6932
7147
  this.apiKey = sanitizedConfig.apiKey;
6933
7148
  this.baseUrl = sanitizedConfig.baseUrl;
@@ -6938,10 +7153,8 @@ class Base {
6938
7153
  env.isNative = this.options.platform === 'ios' || this.options.platform === 'android';
6939
7154
  env.isWeb = !env.isNative;
6940
7155
  }
6941
- this.cipher = (_b = ports.cipher) !== null && _b !== void 0 ? _b : new Cipher();
6942
- this.transport = (_c = ports.transport) !== null && _c !== void 0 ? _c : ((...args) => fetch(...args));
6943
- this.clock = (_d = ports.clock) !== null && _d !== void 0 ? _d : { now: () => Date.now() };
6944
- this.lockManager = new LockManagerService();
7156
+ this.cipher = new Cipher();
7157
+ this.lockManager = sharedLockManager;
6945
7158
  this._initializeClientAuthToken(sanitizedConfig.clientAuthToken);
6946
7159
  this.request = this.request.bind(this);
6947
7160
  // The generated API client includes /api/v1 in each path, so strip it from
@@ -6954,7 +7167,6 @@ class Base {
6954
7167
  secure: true, // Enable security worker for all requests by default
6955
7168
  },
6956
7169
  securityWorker: this.securityWorker.bind(this),
6957
- customFetch: this.transport,
6958
7170
  });
6959
7171
  /**
6960
7172
  * This intercepts all API responses and transforms errors into WallabyError format.
@@ -6999,7 +7211,7 @@ class Base {
6999
7211
  return attemptRequest(false);
7000
7212
  };
7001
7213
  this.api = new Api(httpClient);
7002
- this.api.http.setSecurityData(Object.assign({ 'x-api-key': config.apiKey, 'x-client-jwt': config.clientAuthToken }, (_e = this.options) === null || _e === void 0 ? void 0 : _e.headers));
7214
+ 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));
7003
7215
  }
7004
7216
  set setClientAuthToken(token) {
7005
7217
  this._initializeClientAuthToken(token);
@@ -7064,6 +7276,7 @@ class Base {
7064
7276
  * @protected
7065
7277
  */
7066
7278
  get localStorageService() {
7279
+ var _a;
7067
7280
  if (!this.clientAuthToken) {
7068
7281
  throw new WallabyError({
7069
7282
  message: 'A client authentication token (JWT) is required',
@@ -7071,11 +7284,13 @@ class Base {
7071
7284
  errorCode: exports.ErrorResponseCodes.sdk_missing_parameter,
7072
7285
  });
7073
7286
  }
7074
- return new StorageService({
7287
+ // Cached: StorageService depends only on deviceStorage/userId/environment, all stable
7288
+ // after construction. Recreating it per access reset the WAL `_walRecovered` flag.
7289
+ return ((_a = this._localStorageService) !== null && _a !== void 0 ? _a : (this._localStorageService = new StorageService({
7075
7290
  deviceStorage: this.deviceLocalStorage,
7076
7291
  userId: this.userId,
7077
7292
  environment: this.settings.environment,
7078
- });
7293
+ })));
7079
7294
  }
7080
7295
  /**
7081
7296
  * Fetches a new access/refresh token pair using the stored refresh token.
@@ -7118,7 +7333,7 @@ class Base {
7118
7333
  // Proactive token refresh: if access token is near expiry, refresh before making the request
7119
7334
  if (route !== AuthRoutes.refreshAccessToken && !retried) {
7120
7335
  const accessToken = await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken);
7121
- if (accessToken && isJwtNearExpiry(accessToken, 60, this.clock.now)) {
7336
+ if (accessToken && isJwtNearExpiry(accessToken, 60)) {
7122
7337
  await this._performTokenRefresh();
7123
7338
  }
7124
7339
  }
@@ -7142,7 +7357,7 @@ class Base {
7142
7357
  fetchOptions.body = JSON.stringify(options.payload);
7143
7358
  }
7144
7359
  logger.debug(`SDK::Base::${route.method}::Request`, { path: fullUrl, payload: options === null || options === void 0 ? void 0 : options.payload });
7145
- const response = await this.transport(fullUrl, fetchOptions);
7360
+ const response = await fetch(fullUrl, fetchOptions);
7146
7361
  const contentType = response.headers.get('content-type');
7147
7362
  let data;
7148
7363
  if (contentType === null || contentType === void 0 ? void 0 : contentType.includes('application/json')) {
@@ -7213,7 +7428,7 @@ class Base {
7213
7428
  }
7214
7429
  async _getRequestHeaders() {
7215
7430
  const accessToken = await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken);
7216
- if (jwtHasExpired(this.clientAuthToken, this.clock.now)) {
7431
+ if (!isTest && jwtHasExpired(this.clientAuthToken)) {
7217
7432
  throw new WallabyError({
7218
7433
  message: 'Auth token has expired',
7219
7434
  statusCode: 401,
@@ -7235,7 +7450,7 @@ class Base {
7235
7450
  // Proactive token refresh before building headers for the generated client
7236
7451
  try {
7237
7452
  const accessToken = await this.localStorageService.fetch(exports.LocalStorageItems.AccessToken);
7238
- if (accessToken && isJwtNearExpiry(accessToken, 60, this.clock.now)) {
7453
+ if (accessToken && isJwtNearExpiry(accessToken, 60)) {
7239
7454
  await this._performTokenRefresh();
7240
7455
  }
7241
7456
  }
@@ -7616,8 +7831,8 @@ function decodeBase64URL(base64url) {
7616
7831
  }
7617
7832
 
7618
7833
  class PasskeyService {
7619
- constructor(userId, storageService, request, cipher = new Cipher()) {
7620
- this.cipher = cipher;
7834
+ constructor(userId, storageService, request) {
7835
+ this.cipher = new Cipher();
7621
7836
  this.localStorageService = storageService;
7622
7837
  this.userId = userId;
7623
7838
  this.request = request;
@@ -8130,8 +8345,16 @@ function WithLock(lockKey) {
8130
8345
  }
8131
8346
  const originalMethod = descriptor.value;
8132
8347
  descriptor.value = async function (...args) {
8348
+ var _a, _b, _c, _d, _e;
8133
8349
  const lockManager = this.lockManager;
8134
- const key = lockKey || `${target.constructor.name}:${propertyKey}`;
8350
+ const operation = lockKey || `${target.constructor.name}:${propertyKey}`;
8351
+ // Scope the lock key by user/environment/network so a process-wide shared
8352
+ // LockManagerService doesn't make two instances for different users (or the
8353
+ // same user on a different env/network, with distinct storage namespaces)
8354
+ // spuriously block each other with "already in progress".
8355
+ const environment = (_b = (_a = this.options) === null || _a === void 0 ? void 0 : _a.environment) !== null && _b !== void 0 ? _b : defaultEnvironment;
8356
+ const network = (_d = (_c = this.options) === null || _c === void 0 ? void 0 : _c.network) !== null && _d !== void 0 ? _d : defaultNetwork;
8357
+ const key = `${(_e = this.userId) !== null && _e !== void 0 ? _e : 'anon'}:${environment}:${network}:${operation}`;
8135
8358
  return lockManager.withLock(key, () => originalMethod.apply(this, args));
8136
8359
  };
8137
8360
  return descriptor;
@@ -8139,10 +8362,10 @@ function WithLock(lockKey) {
8139
8362
  }
8140
8363
 
8141
8364
  class AuthService extends Base {
8142
- constructor(config, ports = {}) {
8143
- super(config, ports);
8365
+ constructor(config) {
8366
+ super(config);
8144
8367
  this.getUserSalt = this.getUserSalt.bind(this);
8145
- this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request, this.cipher);
8368
+ this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request);
8146
8369
  }
8147
8370
  /**
8148
8371
  * @description
@@ -8671,25 +8894,13 @@ __decorate([
8671
8894
  __metadata("design:returntype", Promise)
8672
8895
  ], AuthService.prototype, "storeDeviceKeyPair", null);
8673
8896
 
8674
- const ENCRYPTED_PAYLOAD_FIELDS = ['iv', 'ephemPublicKey', 'ciphertext', 'mac'];
8675
- // Backup share may be ECIES or symmetric ({ iv, ciphertext, mac, tag }) — both share these three fields.
8676
- const SYMMETRIC_PAYLOAD_FIELDS = ['iv', 'ciphertext', 'mac', 'tag'];
8677
- // API is the trust boundary: confirm every named field is a non-empty string.
8678
- function hasNonEmptyStringFields(payload, fields) {
8679
- return (!!payload &&
8680
- typeof payload === 'object' &&
8681
- fields.every((field) => {
8682
- const value = payload[field];
8683
- return typeof value === 'string' && value.length > 0;
8684
- }));
8685
- }
8686
8897
  /**
8687
8898
  * Fail fast if an encrypted payload from the API does not match the expected
8688
8899
  * ECIES structure ({ iv, ephemPublicKey, ciphertext, mac }). See the contract
8689
8900
  * note on `handleKeySharesFromResponse`.
8690
8901
  */
8691
8902
  function assertEncryptedPayloadShape(encrypted) {
8692
- if (!hasNonEmptyStringFields(encrypted, ENCRYPTED_PAYLOAD_FIELDS)) {
8903
+ if (!isEciesPayload(encrypted)) {
8693
8904
  throw new WallabyError({
8694
8905
  message: 'Encrypted share does not match the expected { iv, ephemPublicKey, ciphertext, mac } format.',
8695
8906
  statusCode: 422,
@@ -8718,20 +8929,18 @@ function assertSharesPayloadShape(shares) {
8718
8929
  * shape-check it. It may be ECIES or symmetric, so accept either variant.
8719
8930
  */
8720
8931
  function assertBackupSharePayloadShape(encrypted) {
8721
- const isEcies = hasNonEmptyStringFields(encrypted, ENCRYPTED_PAYLOAD_FIELDS);
8722
- const isSymmetric = hasNonEmptyStringFields(encrypted, SYMMETRIC_PAYLOAD_FIELDS);
8723
- if (!isEcies && !isSymmetric) {
8932
+ if (!isEciesPayload(encrypted) && !isSymmetricPayload(encrypted)) {
8724
8933
  throw new WallabyError({
8725
- message: 'Encrypted backup share does not match the expected ECIES ({ iv, ephemPublicKey, ciphertext, mac }) or symmetric ({ iv, ciphertext, mac, tag }) format.',
8934
+ message: 'Encrypted backup share does not match the expected ECIES ({ iv, ephemPublicKey, ciphertext, mac }) or symmetric ({ v, iv, ciphertext, tag }) format.',
8726
8935
  statusCode: 422,
8727
8936
  errorCode: exports.ErrorResponseCodes.sdk_invalid_parameter,
8728
8937
  });
8729
8938
  }
8730
8939
  }
8731
8940
  class WalletHandlersService extends Base {
8732
- constructor(config, ports = {}) {
8733
- super(config, ports);
8734
- this.authService = new AuthService(config, ports);
8941
+ constructor(config) {
8942
+ super(config);
8943
+ this.authService = new AuthService(config);
8735
8944
  this.userId = config.userId;
8736
8945
  }
8737
8946
  async handleImportWallet(deviceAuthKeys, importWalletInput) {
@@ -9037,12 +9246,12 @@ class WalletHandlersService extends Base {
9037
9246
  }
9038
9247
 
9039
9248
  class WalletService extends Base {
9040
- constructor(config, ports = {}) {
9041
- super(config, ports);
9042
- this.authService = new AuthService(config, ports);
9043
- this.handlers = new WalletHandlersService(config, ports);
9249
+ constructor(config) {
9250
+ super(config);
9251
+ this.authService = new AuthService(config);
9252
+ this.handlers = new WalletHandlersService(config);
9044
9253
  this.userId = config.userId;
9045
- this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request, this.cipher);
9254
+ this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request);
9046
9255
  }
9047
9256
  /**
9048
9257
  * Reads the persisted sliding-window rate-limit state for a counter key.
@@ -9563,7 +9772,7 @@ class WalletService extends Base {
9563
9772
  password: newPassword,
9564
9773
  salt: clientSalt,
9565
9774
  });
9566
- if (!newCredentialsKeyPair.publicKey) {
9775
+ if (!newCredentialsKeyPair.publicKey || !newCredentialsKeyPair.privateKey) {
9567
9776
  throw new WallabyError({
9568
9777
  message: 'Could not derive keys for new password.',
9569
9778
  statusCode: 500,
@@ -9586,6 +9795,9 @@ class WalletService extends Base {
9586
9795
  errorCode: exports.ErrorResponseCodes.sdk_unknown_error,
9587
9796
  });
9588
9797
  }
9798
+ // Round-trip validate: decrypt the re-wrapped blob with the new key before committing.
9799
+ // Catches a malformed re-encryption before it overwrites the live credential.
9800
+ await this.assertRoundTrip(reWrappedDevicePrivateKey, newCredentialsKeyPair.privateKey, 'device key');
9589
9801
  const reWrappedSeedPhrase = encryptedSeedPhraseString
9590
9802
  ? await this.cipher.flipEncryptedData({
9591
9803
  cipherText: safeJsonParse(encryptedSeedPhraseString),
@@ -9607,9 +9819,13 @@ class WalletService extends Base {
9607
9819
  encryptionKey: newCredentialsKeyPair.publicKey,
9608
9820
  })
9609
9821
  : null;
9610
- // Commit all re-wrapped blobs in one batch so a partial failure cannot leave the device
9611
- // in a half-migrated state (some items under the new password, others under the old).
9612
- await this.localStorageService.saveInBulk([
9822
+ if (reWrappedSeedPhrase)
9823
+ await this.assertRoundTrip(reWrappedSeedPhrase, newCredentialsKeyPair.privateKey, 'seed phrase');
9824
+ if (reWrappedPrimaryShare)
9825
+ await this.assertRoundTrip(reWrappedPrimaryShare, newCredentialsKeyPair.privateKey, 'primary share');
9826
+ if (reWrappedBackupShare)
9827
+ await this.assertRoundTrip(reWrappedBackupShare, newCredentialsKeyPair.privateKey, 'backup share');
9828
+ await this.localStorageService.commitBatch([
9613
9829
  { key: exports.LocalStorageItems.EncryptedDevicePrivateKey, value: reWrappedDevicePrivateKey },
9614
9830
  ...(reWrappedSeedPhrase
9615
9831
  ? [{ key: exports.LocalStorageItems.EncryptedStandardSeedPhrase, value: reWrappedSeedPhrase, walletId }]
@@ -9832,6 +10048,24 @@ class WalletService extends Base {
9832
10048
  });
9833
10049
  }
9834
10050
  }
10051
+ /**
10052
+ * Assert a decrypted private key is valid secp256k1 key material. If it isn't, the stored value is
10053
+ * corrupted (or a wrong password decrypted to non-key garbage) — surface a clear, distinct error
10054
+ * instead of letting the raw validation message escape or collapsing into a misleading "wrong password".
10055
+ */
10056
+ assertValidDeviceKey(privateKey) {
10057
+ try {
10058
+ this.cipher.validatePrivateKey(privateKey);
10059
+ }
10060
+ catch (error) {
10061
+ logger.error('SDK::WalletService::assertValidDeviceKey::decrypted private key is not valid key material', error);
10062
+ throw new WallabyError({
10063
+ message: 'Could not access your device key — your stored wallet credentials appear to be corrupted.',
10064
+ statusCode: 500,
10065
+ errorCode: exports.ErrorResponseCodes.sdk_private_key_decryption_failed,
10066
+ });
10067
+ }
10068
+ }
9835
10069
  /**
9836
10070
  * Detects and migrates legacy/v1 storage items to v2 format.
9837
10071
  * This function should be called in methods that use password as input when v2 items are missing.
@@ -9919,10 +10153,9 @@ class WalletService extends Base {
9919
10153
  // getDecryptedV1PrivateKey checks for both v1 and legacy formats internally
9920
10154
  const legacyDecryptedPrivateKey = await this.localStorageService.getDecryptedV1PrivateKey(password);
9921
10155
  if (legacyEncryptedSeed && legacyDecryptedPrivateKey) {
9922
- const legacyPublicKey = publicKeyByPrivateKey(legacyDecryptedPrivateKey);
10156
+ this.assertValidDeviceKey(legacyDecryptedPrivateKey);
9923
10157
  logger.info('SDK::WalletService::handleUpdateToV2::Found legacy storage items, attempting migration', {
9924
10158
  storageFormat: 'legacy',
9925
- devicePublicKey: legacyPublicKey.substring(0, 16) + '...',
9926
10159
  });
9927
10160
  try {
9928
10161
  // Decrypt legacy items using password/salt combination
@@ -9954,12 +10187,13 @@ class WalletService extends Base {
9954
10187
  const v1EncryptedSeed = await this.localStorageService.getEncryptedSeedPhrase(exports.SeedPhraseType.Standard, walletId);
9955
10188
  const v1EncryptedPrivateKey = await this.localStorageService.getEncryptedPrivateKey();
9956
10189
  if (v1EncryptedSeed && v1EncryptedPrivateKey) {
9957
- // Get public key before decryption for logging
9958
10190
  decryptedPrivateKey = await this.localStorageService.getDecryptedV1PrivateKey(password);
9959
- const v1PublicKey = decryptedPrivateKey ? publicKeyByPrivateKey(decryptedPrivateKey) : 'unknown';
10191
+ // Validate the decrypted private key before proceeding with migration
10192
+ if (decryptedPrivateKey)
10193
+ this.assertValidDeviceKey(decryptedPrivateKey);
9960
10194
  logger.info('SDK::WalletService::handleUpdateToV2::Found V1 storage items, attempting migration', {
9961
10195
  storageFormat: 'v1',
9962
- devicePublicKey: v1PublicKey.substring(0, 16) + '...',
10196
+ validPrivateKey: !!decryptedPrivateKey,
9963
10197
  });
9964
10198
  try {
9965
10199
  // Decrypt V1 items using storage service method (handles double encryption)
@@ -10194,7 +10428,28 @@ class WalletService extends Base {
10194
10428
  * @returns { boolean } whether the operation was successful
10195
10429
  */
10196
10430
  async convertToPasskey(input) {
10431
+ let passkeyRegistered = false;
10197
10432
  try {
10433
+ // Recover an interrupted conversion BEFORE reading any credential blob. A prior attempt may have
10434
+ // already rewrapped EncryptedDevicePrivateKey to passkey form (addNewPasskey persists it outside
10435
+ // this method's atomic commit), which the password can no longer decrypt — and deriving the passkey
10436
+ // key to decrypt it needs the device key itself (circular). The marker stashes the original
10437
+ // password-encrypted device key; restore it so the rest of the flow runs as a fresh conversion.
10438
+ const rawConversionMarker = (await this.localStorageService.fetch(exports.V2KeyNames.CredentialConversionInProgress));
10439
+ const existingConversionMarker = rawConversionMarker
10440
+ ? safeJsonParse(rawConversionMarker)
10441
+ : undefined;
10442
+ // Restore the stashed device key whenever a marker carries one — independent of walletId. The
10443
+ // device key is per-user (not wallet-scoped), so a conversion interrupted on a different wallet
10444
+ // leaves the shared device key passkey-wrapped too. Restoring is idempotent (rewrites the
10445
+ // original password-encrypted blob) and stops a second wallet's conversion from destroying the
10446
+ // first's recovery state. v2 only — a v1 wallet's untouched v1 key still decrypts.
10447
+ if (existingConversionMarker === null || existingConversionMarker === void 0 ? void 0 : existingConversionMarker.encryptedDevicePrivateKey) {
10448
+ await this.localStorageService.save(exports.LocalStorageItems.EncryptedDevicePrivateKey, existingConversionMarker.encryptedDevicePrivateKey);
10449
+ }
10450
+ if ((existingConversionMarker === null || existingConversionMarker === void 0 ? void 0 : existingConversionMarker.walletId) === input.walletId) {
10451
+ logger.info('SDK::WalletService::convertToPasskey::resuming interrupted conversion');
10452
+ }
10198
10453
  const v2EncryptedPriv = await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedDevicePrivateKey);
10199
10454
  const v2EncryptedSeed = await this.localStorageService.fetch(exports.LocalStorageItems.EncryptedStandardSeedPhrase, {
10200
10455
  walletId: input.walletId,
@@ -10243,6 +10498,10 @@ class WalletService extends Base {
10243
10498
  });
10244
10499
  }
10245
10500
  const clientPublicKey = publicKeyByPrivateKey(decryptedClientAuthPrivKey);
10501
+ // Write-ahead marker: set before the unrevocable passkey registration so an interrupted
10502
+ // conversion can be resumed on the next attempt. Stash the original password-encrypted device
10503
+ // key so resume survives addNewPasskey rewrapping the stored device key to passkey form.
10504
+ await this.localStorageService.save(exports.V2KeyNames.CredentialConversionInProgress, Object.assign({ walletId: input.walletId }, (v2EncryptedPriv ? { encryptedDevicePrivateKey: v2EncryptedPriv } : {})));
10246
10505
  const authentication = await this.passkeyService.addNewPasskey({
10247
10506
  deviceKeyPair: {
10248
10507
  publicKey: clientPublicKey,
@@ -10250,6 +10509,7 @@ class WalletService extends Base {
10250
10509
  },
10251
10510
  getSignature: this.authService.getSignature.bind(this),
10252
10511
  });
10512
+ passkeyRegistered = true;
10253
10513
  const prfValue = authentication.prfValue;
10254
10514
  if (!prfValue || !(prfValue instanceof Uint8Array) || prfValue.length === 0) {
10255
10515
  logger.error('SDK::WalletService::convertToPasskey::prfValue is required and must be a non-empty Uint8Array');
@@ -10346,8 +10606,13 @@ class WalletService extends Base {
10346
10606
  storeOneKeyShareWithWallaby: true,
10347
10607
  },
10348
10608
  });
10349
- // Delete the old password-encrypted seed phrase since import stored the new passkey-encrypted version
10350
- await this.localStorageService.delete(exports.LocalStorageItems.EncryptedStandardSeedPhrase, { walletId: input.walletId });
10609
+ // idempotent — on retry (marker present, primary now passkey-encrypted so
10610
+ // decryptedPrimaryShare is undefined → Branch A re-enters), handleImportWallet re-shares
10611
+ // safely; this atomic delete clears the stale seed + marker together.
10612
+ await this.localStorageService.commitBatch([], [
10613
+ { key: exports.LocalStorageItems.EncryptedStandardSeedPhrase, walletId: input.walletId },
10614
+ { key: exports.V2KeyNames.CredentialConversionInProgress },
10615
+ ]);
10351
10616
  logger.info('SDK::WalletService::convertToPasskey::Wallet imported and converted successfully, old seed phrase removed');
10352
10617
  return { authentication, seedPhrase: decryptedSeedPhrase };
10353
10618
  }
@@ -10365,6 +10630,24 @@ class WalletService extends Base {
10365
10630
  privateKey: decryptedClientAuthPrivKey,
10366
10631
  },
10367
10632
  });
10633
+ // assertRoundTrip below only strips the outer (passkey) layer — validate the inner (device key) layer here.
10634
+ const outerDecrypted = await this.cipher.decrypt({
10635
+ cipherText: encryptedPrimaryShare,
10636
+ decryptionKey: passkeyDerivedKeyPair.privateKey,
10637
+ });
10638
+ const innerDecrypted = outerDecrypted
10639
+ ? await this.cipher.decrypt({
10640
+ cipherText: safeJsonParse(outerDecrypted),
10641
+ decryptionKey: decryptedClientAuthPrivKey,
10642
+ })
10643
+ : null;
10644
+ if (innerDecrypted !== decryptedPrimaryShare) {
10645
+ throw new WallabyError({
10646
+ message: 'Re-wrap validation failed for primary share: inner layer round-trip mismatch. Aborting to prevent credential corruption.',
10647
+ statusCode: 500,
10648
+ errorCode: exports.ErrorResponseCodes.sdk_unknown_error,
10649
+ });
10650
+ }
10368
10651
  convertedShares.push({
10369
10652
  key: exports.V2KeyNames.PrimaryDeviceKeyShare,
10370
10653
  value: encryptedPrimaryShare,
@@ -10383,9 +10666,16 @@ class WalletService extends Base {
10383
10666
  walletId: input.walletId,
10384
10667
  });
10385
10668
  }
10386
- await this.localStorageService.saveInBulk(convertedShares);
10669
+ // Round-trip validate each re-encrypted blob (outer layer only) before writing.
10670
+ // A failed decrypt here means re-encryption produced an unreadable blob — abort before overwriting live credentials.
10671
+ for (const share of convertedShares) {
10672
+ await this.assertRoundTrip(share.value, passkeyDerivedKeyPair.privateKey, share.key);
10673
+ }
10674
+ await this.localStorageService.commitBatch(convertedShares, [
10675
+ ...(v2EncryptedSeed ? [{ key: exports.LocalStorageItems.EncryptedStandardSeedPhrase, walletId: input.walletId }] : []),
10676
+ { key: exports.V2KeyNames.CredentialConversionInProgress },
10677
+ ]);
10387
10678
  if (v2EncryptedSeed) {
10388
- await this.localStorageService.delete(exports.LocalStorageItems.EncryptedStandardSeedPhrase, { walletId: input.walletId });
10389
10679
  logger.info('SDK::WalletService::convertToPasskey::Seed phrase removed from device storage after conversion to passkey');
10390
10680
  }
10391
10681
  if (!decryptedSeedPhrase && decryptedPrimaryShare) {
@@ -10428,11 +10718,30 @@ class WalletService extends Base {
10428
10718
  }
10429
10719
  catch (error) {
10430
10720
  logger.error('SDK::WalletService::convertToPasskey::error', error);
10721
+ // Only clear the marker if the passkey was not yet registered. After registration the
10722
+ // marker must survive for roll-forward on the next attempt.
10723
+ if (!passkeyRegistered) {
10724
+ await this.localStorageService.delete(exports.V2KeyNames.CredentialConversionInProgress);
10725
+ }
10431
10726
  throw error;
10432
10727
  }
10433
10728
  }
10729
+ // shared guard — decrypt-tests a re-wrapped blob before any write so a malformed
10730
+ // re-encryption is caught before it overwrites the live credential.
10731
+ async assertRoundTrip(blob, decryptionKey, label) {
10732
+ try {
10733
+ await this.cipher.decrypt({ cipherText: blob, decryptionKey });
10734
+ }
10735
+ catch (_a) {
10736
+ throw new WallabyError({
10737
+ message: `Re-wrap validation failed for ${label}: decryption of the re-encrypted blob failed. Aborting to prevent credential corruption.`,
10738
+ statusCode: 500,
10739
+ errorCode: exports.ErrorResponseCodes.sdk_unknown_error,
10740
+ });
10741
+ }
10742
+ }
10434
10743
  }
10435
- // ponytail: soft client-side guardrail against runaway retries; server-side rate limiting is the real control.
10744
+ // soft client-side guardrail against runaway retries; server-side rate limiting is the real control.
10436
10745
  // Counters are persisted (sliding window) so rebuilding the service no longer resets them. Tune freely.
10437
10746
  WalletService.RATE_LIMIT_MAX = 5;
10438
10747
  WalletService.RATE_LIMIT_WINDOW_MS = 30 * 60000; // 30 min
@@ -10455,7 +10764,7 @@ __decorate([
10455
10764
  __metadata("design:returntype", Promise)
10456
10765
  ], WalletService.prototype, "recover", null);
10457
10766
  __decorate([
10458
- WithLock('changePassword'),
10767
+ WithLock('credential-rewrap'),
10459
10768
  __metadata("design:type", Function),
10460
10769
  __metadata("design:paramtypes", [Object]),
10461
10770
  __metadata("design:returntype", Promise)
@@ -10466,12 +10775,18 @@ __decorate([
10466
10775
  __metadata("design:paramtypes", [Object]),
10467
10776
  __metadata("design:returntype", Promise)
10468
10777
  ], WalletService.prototype, "handleUpdateToV2", null);
10778
+ __decorate([
10779
+ WithLock('credential-rewrap'),
10780
+ __metadata("design:type", Function),
10781
+ __metadata("design:paramtypes", [Object]),
10782
+ __metadata("design:returntype", Promise)
10783
+ ], WalletService.prototype, "convertToPasskey", null);
10469
10784
 
10470
10785
  class WalletDataService extends Base {
10471
- constructor(config, ports = {}) {
10472
- super(config, ports);
10786
+ constructor(config) {
10787
+ super(config);
10473
10788
  this.userId = config.userId;
10474
- this.walletService = new WalletService(config, ports);
10789
+ this.walletService = new WalletService(config);
10475
10790
  }
10476
10791
  /**
10477
10792
  * @description Validates the wallet address info for a given blockchain.
@@ -10792,8 +11107,8 @@ class WalletDataService extends Base {
10792
11107
  }
10793
11108
 
10794
11109
  class Utils extends Base {
10795
- constructor(config, ports = {}) {
10796
- super(config, ports);
11110
+ constructor(config) {
11111
+ super(config);
10797
11112
  /**
10798
11113
  *
10799
11114
  * Decrypts user private key
@@ -10826,7 +11141,7 @@ class Utils extends Base {
10826
11141
  return undefined;
10827
11142
  }
10828
11143
  };
10829
- this.auth = new AuthService(config, ports);
11144
+ this.auth = new AuthService(config);
10830
11145
  }
10831
11146
  /**
10832
11147
  *
@@ -10933,16 +11248,16 @@ class HttpApi extends Base {
10933
11248
  * @param config - The Wallaby configuration object
10934
11249
  * @public
10935
11250
  */
10936
- constructor(config, ports = {}) {
10937
- super(config, ports);
11251
+ constructor(config) {
11252
+ super(config);
10938
11253
  }
10939
11254
  }
10940
11255
 
10941
11256
  class Swap extends Base {
10942
- constructor(config, ports = {}) {
10943
- super(config, ports);
10944
- this.authService = new AuthService(config, ports);
10945
- this.walletService = new WalletService(config, ports);
11257
+ constructor(config) {
11258
+ super(config);
11259
+ this.authService = new AuthService(config);
11260
+ this.walletService = new WalletService(config);
10946
11261
  }
10947
11262
  /**
10948
11263
  * Gets a swap quote between two assets, including fees, min output, and slippage limits.
@@ -11194,9 +11509,30 @@ const sanitizeSuiObjectId = (objectId) => {
11194
11509
  return objectId.split('::')[0];
11195
11510
  };
11196
11511
 
11512
+ /**
11513
+ * Extracts the asset symbol from a fully-qualified Sui coin type.
11514
+ *
11515
+ * A Sui coin type has the shape `<package>::<module>::<TYPE>`, where the final
11516
+ * segment is the coin's struct name and doubles as its symbol.
11517
+ *
11518
+ * @param objectId - The Sui object id / coin type. Example input:
11519
+ * "0xc91acfb75009c5ff2fd57c54f3caaee12ad1fbe997681334adc0b574fc277a07::icorgi::ICORGI"
11520
+ * @returns The symbol (e.g. "ICORGI"), or undefined when the id carries no
11521
+ * `::module::TYPE` suffix to derive it from.
11522
+ */
11523
+ const extractSuiAssetSymbol = (objectId) => {
11524
+ var _a;
11525
+ if (!objectId || !objectId.includes('::')) {
11526
+ return undefined;
11527
+ }
11528
+ const segments = objectId.split('::');
11529
+ const symbol = (_a = segments[segments.length - 1]) === null || _a === void 0 ? void 0 : _a.trim();
11530
+ return symbol || undefined;
11531
+ };
11532
+
11197
11533
  class System extends Base {
11198
- constructor(config, ports = {}) {
11199
- super(config, ports);
11534
+ constructor(config) {
11535
+ super(config);
11200
11536
  }
11201
11537
  /**
11202
11538
  * @public
@@ -11282,6 +11618,9 @@ class System extends Base {
11282
11618
  * @param {BlockchainName} blockchain - The name of the blockchain.
11283
11619
  * @param {string} contractAddress - The contract address of the token (optional for non-SUI blockchains).
11284
11620
  * @param {string} suiObjectId - The SUI object ID of the token (optional for SUI blockchain).
11621
+ * @param {string} assetSymbol - The asset symbol; disambiguates new SUI assets. For SUI it is
11622
+ * optional: when omitted, it is derived from the `::module::TYPE` suffix of `suiObjectId`
11623
+ * (which is otherwise trimmed off before the request is sent).
11285
11624
  *
11286
11625
  * @returns {Promise<{ decimals: number; symbol: string; name: string; tokenContractAddress: string }>} A promise that resolves to an object containing token information.
11287
11626
  *
@@ -11290,18 +11629,19 @@ class System extends Base {
11290
11629
  * @throws Will throw an error if `contractAddress` is not provided for non-SUI blockchains.
11291
11630
  * @throws Will throw an error if the response is invalid or contains an error.
11292
11631
  */
11293
- async fetchTokenInfo({ blockchain, contractAddress, suiObjectId, }) {
11632
+ async fetchTokenInfo({ blockchain, contractAddress, suiObjectId, assetSymbol, }) {
11294
11633
  try {
11295
11634
  const validatedContractAddress = this.validateContractAddress({
11296
11635
  blockchain,
11297
11636
  contractAddress,
11298
11637
  suiObjectId,
11299
11638
  });
11639
+ // For SUI, the coin symbol is the last segment of the coin type
11640
+ // (`<package>::<module>::<TYPE>`), which sanitizeSuiObjectId strips out.
11641
+ // Derive it so callers don't have to pass assetSymbol explicitly.
11642
+ const resolvedAssetSymbol = assetSymbol !== null && assetSymbol !== void 0 ? assetSymbol : (blockchain === exports.BlockchainName.Sui ? extractSuiAssetSymbol(suiObjectId) : undefined);
11300
11643
  const response = await this.request(SystemRoutes.fetchTokenInfo, {
11301
- queryParams: {
11302
- chainName: blockchain,
11303
- tokenContractAddress: validatedContractAddress,
11304
- },
11644
+ queryParams: Object.assign({ chainName: blockchain, tokenContractAddress: validatedContractAddress }, (resolvedAssetSymbol ? { assetSymbol: resolvedAssetSymbol } : {})),
11305
11645
  });
11306
11646
  return response;
11307
11647
  }
@@ -11389,10 +11729,10 @@ class System extends Base {
11389
11729
  }
11390
11730
 
11391
11731
  class Transactions extends Base {
11392
- constructor(config, ports = {}) {
11393
- super(config, ports);
11394
- this.authService = new AuthService(config, ports);
11395
- this.walletService = new WalletService(config, ports);
11732
+ constructor(config) {
11733
+ super(config);
11734
+ this.authService = new AuthService(config);
11735
+ this.walletService = new WalletService(config);
11396
11736
  this.userId = config.userId;
11397
11737
  }
11398
11738
  /**
@@ -11833,15 +12173,15 @@ class Wallaby {
11833
12173
  * @param {string} [config.clientAuthToken] - A web token generated by the client for authorization.
11834
12174
  * @public
11835
12175
  */
11836
- constructor(config, ports = {}) {
11837
- this.wallet = new WalletService(config, ports);
11838
- this.walletData = new WalletDataService(config, ports);
11839
- this.utils = new Utils(config, ports);
11840
- this.auth = new AuthService(config, ports);
11841
- this.system = new System(config, ports);
11842
- this.transactions = new Transactions(config, ports);
11843
- this.swap = new Swap(config, ports);
11844
- this.httpApi = new HttpApi(config, ports);
12176
+ constructor(config) {
12177
+ this.wallet = new WalletService(config);
12178
+ this.walletData = new WalletDataService(config);
12179
+ this.utils = new Utils(config);
12180
+ this.auth = new AuthService(config);
12181
+ this.system = new System(config);
12182
+ this.transactions = new Transactions(config);
12183
+ this.swap = new Swap(config);
12184
+ this.httpApi = new HttpApi(config);
11845
12185
  }
11846
12186
  get version() {
11847
12187
  return currentPackageVersion;