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.js CHANGED
@@ -315,6 +315,8 @@ var V2KeyNames;
315
315
  V2KeyNames["LastMigratedAt"] = "wsdk_last_migrated_at";
316
316
  V2KeyNames["PasswordResetAttempts"] = "wsdk_password_reset_attempts";
317
317
  V2KeyNames["MigrationAttempts"] = "wsdk_migration_attempts";
318
+ V2KeyNames["CredentialConversionInProgress"] = "credential-conversion-in-progress";
319
+ V2KeyNames["PendingCommit"] = "pending-commit";
318
320
  })(V2KeyNames || (V2KeyNames = {}));
319
321
 
320
322
  var ErrorResponseCodes;
@@ -570,6 +572,7 @@ const defaultEnvironment = (_a = browser$1.env.NODE_ENV) !== null && _a !== void
570
572
  * Please pass the network value in the WallabyConfigOptions object to override it for production-mainnet.
571
573
  */
572
574
  const defaultNetwork = 'testnet';
575
+ const isTest = browser$1.env.NODE_ENV === 'test';
573
576
  const DEFAULT_ENTROPY_BYTES$1 = 32;
574
577
  const PBKDF2_ITERATIONS = 131072;
575
578
  const DEFAULT_HOSTNAME = 'https://www.republic.com';
@@ -595,7 +598,7 @@ const env = {
595
598
  isNative: !isWeb,
596
599
  isWeb,
597
600
  };
598
- const currentPackageVersion = "3.3.0" ;
601
+ const currentPackageVersion = "3.5.2" ;
599
602
 
600
603
  /**
601
604
  * Storage keys adapter for Storage interface across different platforms.
@@ -3508,7 +3511,7 @@ const createPrivateKey = (entropy) => {
3508
3511
  }
3509
3512
  // Check byte diversity. This catches genuinely broken inputs (all-zeros, all-same-byte)
3510
3513
  // without false-positiving on 32-byte KDF output (~30 unique bytes expected).
3511
- // ponytail: the sampled Shannon-entropy check was removed (WAL-1465) — it's unsound for
3514
+ // the sampled Shannon-entropy check was removed (WAL-1465) — it's unsound for
3512
3515
  // 32 samples (max measurable = log2(32) ≈ 5 bits/byte vs a 4-bit threshold), so deterministic
3513
3516
  // KDF output could be rejected, permanently locking the user out.
3514
3517
  const uniqueBytes = new Set(entropy);
@@ -4389,24 +4392,166 @@ function pbkdf2Sync(password, salt, iterations, keylen, digest) {
4389
4392
  });
4390
4393
  }
4391
4394
 
4395
+ /**
4396
+ * Pure crypto core (WAL-1469). Module-level functions with no logging, no storage,
4397
+ * no network, and no hidden state: every input (including key material) is a parameter.
4398
+ *
4399
+ * The formats produced/consumed here are pinned by the known-answer tests in
4400
+ * src/tests/kat/ — real user data encrypted in the field depends on them, so any
4401
+ * change to these functions must keep those tests green, and any format change
4402
+ * needs an explicit versioned migration.
4403
+ */
4392
4404
  // Version marker prepended to values wrapped by the master key, so wrapped vs raw is deterministic.
4393
4405
  const MASTER_KEY_WRAP_PREFIX = 'wsdkmk:v1:';
4394
4406
  // crypto-js AES.encrypt with a string passphrase emits an OpenSSL "Salted__" header; its base64 always
4395
4407
  // starts with this. Used to recognize legacy wrapped values stored before MASTER_KEY_WRAP_PREFIX existed.
4396
4408
  const LEGACY_CRYPTOJS_PREFIX = 'U2FsdGVkX1';
4409
+ // `satisfies keyof` ties these literal lists to the generated DTOs, so a field
4410
+ // rename/removal there fails the build here instead of silently going stale.
4411
+ const ENCRYPTED_PAYLOAD_FIELDS = [
4412
+ 'iv',
4413
+ 'ephemPublicKey',
4414
+ 'ciphertext',
4415
+ 'mac',
4416
+ ];
4417
+ // v is a version number for the symmetric encryption format, so it is not a string field.
4418
+ const SYMMETRIC_PAYLOAD_FIELDS = ['iv', 'ciphertext', 'tag'];
4419
+ // API is the trust boundary: confirm every named field is a non-empty string.
4420
+ function hasNonEmptyStringFields(payload, fields) {
4421
+ return (!!payload &&
4422
+ typeof payload === 'object' &&
4423
+ fields.every((field) => {
4424
+ const value = payload[field];
4425
+ return typeof value === 'string' && value.length > 0;
4426
+ }));
4427
+ }
4428
+ /**
4429
+ * True when the payload matches the ECIES envelope { iv, ephemPublicKey, ciphertext, mac }.
4430
+ */
4431
+ function isEciesPayload(payload) {
4432
+ return hasNonEmptyStringFields(payload, ENCRYPTED_PAYLOAD_FIELDS);
4433
+ }
4434
+ /**
4435
+ * True when the payload matches the symmetric envelope { v, iv, ciphertext, tag } with numeric v.
4436
+ */
4437
+ function isSymmetricPayload(payload) {
4438
+ return (hasNonEmptyStringFields(payload, SYMMETRIC_PAYLOAD_FIELDS) &&
4439
+ typeof payload.v === 'number');
4440
+ }
4441
+ /**
4442
+ * Validate that a private key is the correct length and not weak.
4443
+ */
4444
+ function validatePrivateKey(privateKey) {
4445
+ if (!/^0x[0-9a-fA-F]{64}$/.test(privateKey)) {
4446
+ throw new Error('Invalid private key: must be a 32-byte hex string');
4447
+ }
4448
+ // A valid key is a scalar in [1, n-1] that projects onto the secp256k1 curve.
4449
+ // isValidPrivateKey does that range check (and is what getPublicKey runs under the hood).
4450
+ if (!secp256k1.utils.isValidPrivateKey(privateKey.slice(2))) {
4451
+ throw new Error('Invalid private key: outside secp256k1 scalar range');
4452
+ }
4453
+ }
4454
+ /**
4455
+ * Validate that a public key is the correct length and format.
4456
+ */
4457
+ function validatePublicKey(publicKey) {
4458
+ if (!/^[0-9a-fA-F]{128}$/.test(publicKey)) {
4459
+ throw new Error('Invalid public key: must be a 64-byte raw uncompressed hex string');
4460
+ }
4461
+ const uniqueChars = new Set(publicKey);
4462
+ if (uniqueChars.size <= 8) {
4463
+ throw new Error('Weak public key: too few unique characters');
4464
+ }
4465
+ }
4466
+ /**
4467
+ * Validate that a salt is sufficiently long and not weak.
4468
+ */
4469
+ function validateSalt(salt) {
4470
+ if (utf8ToBytes$1(salt).length < 16) {
4471
+ throw new Error('Salt is too short: must be at least 16 bytes');
4472
+ }
4473
+ const uniqueChars = new Set(salt);
4474
+ if (uniqueChars.size <= 6) {
4475
+ throw new Error('Weak salt: too few unique characters');
4476
+ }
4477
+ }
4478
+ /**
4479
+ * Accept an Encrypted payload either as the object or its JSON.stringify'd storage form.
4480
+ */
4481
+ function parseEncrypted(value) {
4482
+ return typeof value === 'string' ? JSON.parse(value) : value;
4483
+ }
4484
+ /**
4485
+ * Derives a key pair from a password and salt: NFKC-normalize + trim, then
4486
+ * PBKDF2-SHA256 (PBKDF2_ITERATIONS) into a createIdentity keypair.
4487
+ */
4488
+ function deriveKeyPairFromPassword({ password, salt }) {
4489
+ validateSalt(salt);
4490
+ // Compatibility Composition
4491
+ // Prevents different Unicode representations of "same" password
4492
+ // Also trim whitespace for security consistency
4493
+ const normalizedPassword = password.normalize('NFKC').trim();
4494
+ const encryptionKey = pbkdf2Sync(utf8ToBytes$1(normalizedPassword), utf8ToBytes$1(salt), PBKDF2_ITERATIONS, DEFAULT_ENTROPY_BYTES$1, 'sha256');
4495
+ return createIdentity(encryptionKey);
4496
+ }
4497
+ /**
4498
+ * Derives a key pair from passkey PRF input key material.
4499
+ */
4500
+ function deriveKeyPairFromPasskey({ inputKeyMaterial }) {
4501
+ return createIdentity(inputKeyMaterial);
4502
+ }
4503
+ /**
4504
+ * crypto-js AES with a string passphrase (OpenSSL salted format). This is the legacy
4505
+ * V1 storage cipher and the primitive under the master-key wrap; kept only for
4506
+ * backward compatibility with data already encrypted in the field.
4507
+ */
4508
+ function legacyAesEncrypt(data, passphrase) {
4509
+ return AES.encrypt(data, passphrase).toString();
4510
+ }
4511
+ function legacyAesDecrypt(cipherText, passphrase) {
4512
+ return AES.decrypt(cipherText, passphrase).toString(enc.Utf8);
4513
+ }
4514
+ /**
4515
+ * Wraps a value with the master key, prefixed with the format version marker.
4516
+ */
4517
+ function wrapWithMasterKey(data, masterKey) {
4518
+ return MASTER_KEY_WRAP_PREFIX + legacyAesEncrypt(typeof data === 'string' ? data : JSON.stringify(data), masterKey);
4519
+ }
4520
+ /**
4521
+ * Determines deterministically whether a stored value was wrapped by the master key,
4522
+ * without inferring from decrypt behavior. Returns true for values carrying the version
4523
+ * marker, or legacy crypto-js ciphertext stored before the marker existed.
4524
+ */
4525
+ function isMasterKeyWrapped(value) {
4526
+ return value.startsWith(MASTER_KEY_WRAP_PREFIX) || value.startsWith(LEGACY_CRYPTOJS_PREFIX);
4527
+ }
4528
+ /**
4529
+ * Unwraps a master-key-wrapped value (current prefixed format or legacy unprefixed blob).
4530
+ * Returns the parsed object for JSON payloads, the raw string otherwise, and undefined
4531
+ * when the ciphertext decrypts to nothing. Throws on malformed ciphertext (crypto-js
4532
+ * "Malformed UTF-8 data") — callers translate/log.
4533
+ */
4534
+ function unwrapWithMasterKey(cipherText, masterKey) {
4535
+ const ciphertext = cipherText.startsWith(MASTER_KEY_WRAP_PREFIX) ? cipherText.slice(MASTER_KEY_WRAP_PREFIX.length) : cipherText;
4536
+ const decrypted = legacyAesDecrypt(ciphertext, masterKey);
4537
+ if (decrypted) {
4538
+ return isJsonString(decrypted) ? safeJsonParse(decrypted) : decrypted;
4539
+ }
4540
+ return undefined;
4541
+ }
4542
+
4543
+ /**
4544
+ * Impure shell over the pure crypto core (./cipher-core). This class only adds
4545
+ * logging, user-facing error translation, and the master-key constant; all crypto
4546
+ * and format logic lives in cipher-core and is pinned by the KATs in src/tests/kat/.
4547
+ */
4397
4548
  class Cipher {
4398
4549
  constructor() { }
4399
4550
  /**
4400
4551
  * Validate that a private key is the correct length and not weak.
4401
4552
  */
4402
4553
  validatePrivateKey(privateKey) {
4403
- if (!/^0x[0-9a-fA-F]{64}$/.test(privateKey)) {
4404
- throw new Error('Invalid private key: must be a 32-byte hex string');
4405
- }
4406
- const uniqueChars = new Set(privateKey.slice(2)); // Remove '0x' prefix
4407
- if (uniqueChars.size <= 8) {
4408
- throw new Error('Weak private key: too few unique characters');
4409
- }
4554
+ validatePrivateKey(privateKey);
4410
4555
  }
4411
4556
  /**
4412
4557
  * @description For an additional layer of security, this function returns a master key from a constant MASTER_ENCRYPTION_KEY.
@@ -4424,8 +4569,7 @@ class Cipher {
4424
4569
  * @returns The encrypted data as a string.
4425
4570
  */
4426
4571
  encryptWithMasterKey({ data }) {
4427
- const ciphertext = AES.encrypt(typeof data === 'string' ? data : JSON.stringify(data), this.getMasterKey().key).toString();
4428
- return MASTER_KEY_WRAP_PREFIX + ciphertext;
4572
+ return wrapWithMasterKey(data, this.getMasterKey().key);
4429
4573
  }
4430
4574
  /**
4431
4575
  * @description Determines deterministically whether a stored value was wrapped by the master key,
@@ -4433,16 +4577,13 @@ class Cipher {
4433
4577
  * legacy crypto-js ciphertext stored before the marker existed. Everything else is treated as raw.
4434
4578
  */
4435
4579
  isWrappedByMasterKey(value) {
4436
- return value.startsWith(MASTER_KEY_WRAP_PREFIX) || value.startsWith(LEGACY_CRYPTOJS_PREFIX);
4580
+ return isMasterKeyWrapped(value);
4437
4581
  }
4438
4582
  decryptWithMasterKey({ cipherText }) {
4439
- const ciphertext = cipherText.startsWith(MASTER_KEY_WRAP_PREFIX)
4440
- ? cipherText.slice(MASTER_KEY_WRAP_PREFIX.length)
4441
- : cipherText;
4442
4583
  try {
4443
- const decrypted = AES.decrypt(ciphertext, this.getMasterKey().key).toString(enc.Utf8);
4444
- if (decrypted) {
4445
- return isJsonString(decrypted) ? safeJsonParse(decrypted) : decrypted;
4584
+ const decrypted = unwrapWithMasterKey(cipherText, this.getMasterKey().key);
4585
+ if (decrypted !== undefined) {
4586
+ return decrypted;
4446
4587
  }
4447
4588
  }
4448
4589
  catch (error) {
@@ -4457,25 +4598,13 @@ class Cipher {
4457
4598
  * Validate that a public key is the correct length and format.
4458
4599
  */
4459
4600
  validatePublicKey(publicKey) {
4460
- if (!/^[0-9a-fA-F]{128}$/.test(publicKey)) {
4461
- throw new Error('Invalid public key: must be a 64-byte raw uncompressed hex string');
4462
- }
4463
- const uniqueChars = new Set(publicKey);
4464
- if (uniqueChars.size <= 8) {
4465
- throw new Error('Weak public key: too few unique characters');
4466
- }
4601
+ validatePublicKey(publicKey);
4467
4602
  }
4468
4603
  /**
4469
4604
  * Validate that a salt is sufficiently long and not weak.
4470
4605
  */
4471
4606
  validateSalt(salt) {
4472
- if (utf8ToBytes$1(salt).length < 16) {
4473
- throw new Error('Salt is too short: must be at least 16 bytes');
4474
- }
4475
- const uniqueChars = new Set(salt);
4476
- if (uniqueChars.size <= 6) {
4477
- throw new Error('Weak salt: too few unique characters');
4478
- }
4607
+ validateSalt(salt);
4479
4608
  }
4480
4609
  /**
4481
4610
  * @description Signs a message using the provided private key.
@@ -4522,10 +4651,7 @@ class Cipher {
4522
4651
  async decrypt({ cipherText, decryptionKey }) {
4523
4652
  try {
4524
4653
  this.validatePrivateKey(decryptionKey);
4525
- if (typeof cipherText === 'string') {
4526
- cipherText = JSON.parse(cipherText);
4527
- }
4528
- const decrypted = await decryptWithPrivateKey(decryptionKey, cipherText);
4654
+ const decrypted = await decryptWithPrivateKey(decryptionKey, parseEncrypted(cipherText));
4529
4655
  return decrypted;
4530
4656
  }
4531
4657
  catch (error) {
@@ -4760,8 +4886,7 @@ class Cipher {
4760
4886
  * @returns {Promise<{ privateKey: string; publicKey: string }>} The derived key pair.
4761
4887
  */
4762
4888
  async deriveKeyPairFromPasskey({ inputKeyMaterial }) {
4763
- const identityFromInputKey = createIdentity(inputKeyMaterial);
4764
- return identityFromInputKey;
4889
+ return deriveKeyPairFromPasskey({ inputKeyMaterial });
4765
4890
  }
4766
4891
  /**
4767
4892
  * @description Derives a key pair from the provided password and salt.
@@ -4770,14 +4895,7 @@ class Cipher {
4770
4895
  * @returns {Promise<{ privateKey: string; publicKey: string }>} The derived key pair.
4771
4896
  */
4772
4897
  async deriveKeyPairFromPassword({ password, salt }) {
4773
- this.validateSalt(salt);
4774
- // Compatibility Composition
4775
- // Prevents different Unicode representations of "same" password
4776
- // Also trim whitespace for security consistency
4777
- const normalizedPassword = password.normalize('NFKC').trim();
4778
- const encryptionKey = pbkdf2Sync(utf8ToBytes$1(normalizedPassword), utf8ToBytes$1(salt), PBKDF2_ITERATIONS, DEFAULT_ENTROPY_BYTES$1, 'sha256');
4779
- const encryptionKeyPair = createIdentity(encryptionKey);
4780
- return encryptionKeyPair;
4898
+ return deriveKeyPairFromPassword({ password, salt });
4781
4899
  }
4782
4900
  }
4783
4901
 
@@ -4819,6 +4937,14 @@ class StorageService {
4819
4937
  return;
4820
4938
  }
4821
4939
  async fetch(key, options) {
4940
+ var _a;
4941
+ // Recover once per session; memoize the promise so concurrent first-fetches all await the same
4942
+ // recovery instead of racing past it and reading pre-recovery storage. recoverCommit uses
4943
+ // getItem/removeItem (not fetch), so there's no recursion. Swallow errors: recovery is
4944
+ // best-effort and a failure must not wedge every subsequent fetch.
4945
+ await ((_a = this._walRecovery) !== null && _a !== void 0 ? _a : (this._walRecovery = this.recoverCommit().catch((error) => {
4946
+ logger.error('SDK::StorageService::fetch::wal recovery failed', error);
4947
+ })));
4822
4948
  let storageKey;
4823
4949
  if (this._walletSpecificKeys.includes(key)) {
4824
4950
  if (!(options === null || options === void 0 ? void 0 : options.walletId)) {
@@ -4878,6 +5004,75 @@ class StorageService {
4878
5004
  async saveInBulk(data) {
4879
5005
  await Promise.all(data.map((item) => this.save(item.key, item.value, { walletId: item.walletId })));
4880
5006
  }
5007
+ // Compute the final storage key the same way save/fetch/delete do.
5008
+ _computeRawKey(key, walletId) {
5009
+ let storageKey;
5010
+ if (this._walletSpecificKeys.includes(key)) {
5011
+ if (!walletId)
5012
+ throw new Error(`A walletId is required to compute key: ${key}`);
5013
+ storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}:${walletId}`;
5014
+ }
5015
+ else {
5016
+ storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}`;
5017
+ }
5018
+ return isWeb ? storageKey : normalizeKey(storageKey);
5019
+ }
5020
+ _serializeValue(key, value) {
5021
+ if (this._keysProtectedByMasterKey.includes(key)) {
5022
+ return this.cipher.encryptWithMasterKey({ data: value });
5023
+ }
5024
+ return typeof value === 'string' ? value : JSON.stringify(value);
5025
+ }
5026
+ async _applyWAL(record) {
5027
+ for (const { rawKey, value } of record.writes) {
5028
+ await this.setItem(rawKey, value);
5029
+ }
5030
+ for (const rawKey of record.deletes) {
5031
+ await this.removeItem(rawKey);
5032
+ }
5033
+ }
5034
+ // Atomically commit a batch of writes and deletes via a write-ahead log.
5035
+ // The WAL record is written in a single setItem before any credential key is
5036
+ // touched. A crash between that write and the individual setItem calls leaves
5037
+ // the WAL in place; recoverCommit() finishes the batch on the next call.
5038
+ async commitBatch(writes, deletes) {
5039
+ const record = {
5040
+ writes: writes.map(({ key, value, walletId }) => ({
5041
+ rawKey: this._computeRawKey(key, walletId),
5042
+ value: this._serializeValue(key, value),
5043
+ })),
5044
+ deletes: (deletes !== null && deletes !== void 0 ? deletes : []).map(({ key, walletId }) => this._computeRawKey(key, walletId)),
5045
+ };
5046
+ // Finish any dangling WAL from a prior partially-applied commit before writing a new one —
5047
+ // otherwise this setItem clobbers it and those half-written credentials become unrecoverable.
5048
+ await this.recoverCommit();
5049
+ const walKey = this._computeRawKey(V2KeyNames.PendingCommit);
5050
+ await this.setItem(walKey, JSON.stringify(record));
5051
+ await this._applyWAL(record);
5052
+ await this.removeItem(walKey);
5053
+ }
5054
+ // Re-apply a pending WAL commit if the process was killed mid-batch.
5055
+ // Call at the start of any operation that writes credential blobs.
5056
+ async recoverCommit() {
5057
+ const walKey = this._computeRawKey(V2KeyNames.PendingCommit);
5058
+ const raw = await this.getItem(walKey);
5059
+ if (!raw)
5060
+ return;
5061
+ let record;
5062
+ try {
5063
+ record = safeJsonParse(raw);
5064
+ }
5065
+ catch (error) {
5066
+ // Corrupt/unparseable WAL can never be replayed — discard so it doesn't wedge every fetch.
5067
+ logger.error('SDK::StorageService::recoverCommit::corrupt WAL, discarding', error);
5068
+ await this.removeItem(walKey);
5069
+ return;
5070
+ }
5071
+ // _applyWAL is idempotent. If it throws (transient storage error) keep the WAL and let the
5072
+ // caller retry — don't delete the only record needed to finish the batch. Remove only on success.
5073
+ await this._applyWAL(record);
5074
+ await this.removeItem(walKey);
5075
+ }
4881
5076
  async delete(key, options) {
4882
5077
  let storageKey;
4883
5078
  if (this._walletSpecificKeys.includes(key)) {
@@ -5162,6 +5357,8 @@ class StorageService {
5162
5357
  V2KeyNames.ClientAuthToken,
5163
5358
  V2KeyNames.PasswordResetAttempts,
5164
5359
  V2KeyNames.MigrationAttempts,
5360
+ V2KeyNames.CredentialConversionInProgress,
5361
+ V2KeyNames.PendingCommit,
5165
5362
  ];
5166
5363
  await Promise.all(userKeysToRemove.map((key) => this.delete(key)));
5167
5364
  if (walletId) {
@@ -5208,11 +5405,11 @@ class StorageService {
5208
5405
  * @param jwt - The JWT string to check. If null, the function will return true.
5209
5406
  * @returns `true` if the JWT has expired or is null, otherwise `false`.
5210
5407
  */
5211
- function jwtHasExpired(jwt, now = Date.now) {
5408
+ function jwtHasExpired(jwt) {
5212
5409
  if (!jwt) {
5213
5410
  return true;
5214
5411
  }
5215
- return millisecondsToJWTTimeout(jwt, now) <= 0;
5412
+ return millisecondsToJWTTimeout(jwt) <= 0;
5216
5413
  }
5217
5414
  function jwtHasSameUser(jwt, userId) {
5218
5415
  if (!jwt || !userId) {
@@ -5232,11 +5429,11 @@ function userIsMfaVerified(jwt) {
5232
5429
  * @param thresholdSeconds - Number of seconds before expiry to consider "near expiry".
5233
5430
  * @returns `true` if the JWT expires within `thresholdSeconds` seconds, otherwise `false`.
5234
5431
  */
5235
- function isJwtNearExpiry(jwt, thresholdSeconds, now = Date.now) {
5432
+ function isJwtNearExpiry(jwt, thresholdSeconds) {
5236
5433
  if (!jwt) {
5237
5434
  return false;
5238
5435
  }
5239
- return millisecondsToJWTTimeout(jwt, now) <= thresholdSeconds * 1000;
5436
+ return millisecondsToJWTTimeout(jwt) <= thresholdSeconds * 1000;
5240
5437
  }
5241
5438
  /**
5242
5439
  * Calculates the remaining time in milliseconds until a given JWT expires.
@@ -5244,11 +5441,11 @@ function isJwtNearExpiry(jwt, thresholdSeconds, now = Date.now) {
5244
5441
  * @param jwt - The JWT string to decode and check.
5245
5442
  * @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.
5246
5443
  */
5247
- function millisecondsToJWTTimeout(jwt, now = Date.now) {
5444
+ function millisecondsToJWTTimeout(jwt) {
5248
5445
  const jwtDecoded = jwtDecode(jwt);
5249
5446
  const jwtExpirationTimeSeconds = jwtDecoded.exp;
5250
5447
  const jwtExpirationTimeMilliseconds = (jwtExpirationTimeSeconds !== null && jwtExpirationTimeSeconds !== void 0 ? jwtExpirationTimeSeconds : 0) * 1000;
5251
- const timeNowMilliseconds = now();
5448
+ const timeNowMilliseconds = Date.now();
5252
5449
  return jwtExpirationTimeMilliseconds - timeNowMilliseconds;
5253
5450
  }
5254
5451
 
@@ -5311,7 +5508,23 @@ class LockManagerService {
5311
5508
  * @returns Promise that resolves with the operation result
5312
5509
  */
5313
5510
  async withLock(key, operation) {
5314
- // Check if this operation is already locked
5511
+ // On web, use the Web Locks API so the lock serializes across browser tabs too.
5512
+ // `ifAvailable: true` preserves the throw-fast contract: a held lock yields a null
5513
+ // lock instead of waiting, so we surface the same "already in progress" error.
5514
+ // Gate on a real browser (window+document) rather than navigator.locks alone:
5515
+ // modern Node ships a process-global navigator.locks, which would defeat the
5516
+ // in-process semantics the native/Node fallback (and existing tests) rely on.
5517
+ const isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined';
5518
+ const locks = isBrowser && typeof navigator !== 'undefined' ? navigator.locks : undefined;
5519
+ if (locks) {
5520
+ return locks.request(key, { ifAvailable: true }, async (lock) => {
5521
+ if (!lock) {
5522
+ throw new Error(`Operation '${key}' is already in progress. Please wait for it to complete.`);
5523
+ }
5524
+ return operation();
5525
+ });
5526
+ }
5527
+ // in-process Set fallback for native/Node (no tabs, single JS context => sufficient).
5315
5528
  if (this.activeLocks.has(key)) {
5316
5529
  throw new Error(`Operation '${key}' is already in progress. Please wait for it to complete.`);
5317
5530
  }
@@ -5319,8 +5532,7 @@ class LockManagerService {
5319
5532
  this.activeLocks.add(key);
5320
5533
  try {
5321
5534
  // Execute the operation
5322
- const result = await operation();
5323
- return result;
5535
+ return await operation();
5324
5536
  }
5325
5537
  finally {
5326
5538
  // Always release the lock
@@ -6896,9 +7108,12 @@ function shouldClearTokensAfterRefreshFailure(error) {
6896
7108
 
6897
7109
  // Module-level dedupe manager for token refresh to ensure only one refresh request per user/environment/network at a time
6898
7110
  const refreshDedupeManager = new DedupeManagerService();
7111
+ // one origin-wide lock manager shared by every service instance, so WalletService/AuthService/etc.
7112
+ // actually contend. Global lock keys (no per-user scoping); add scoping only if multiple users share one process.
7113
+ const sharedLockManager = new LockManagerService();
6899
7114
  class Base {
6900
- constructor(config, ports = {}) {
6901
- var _a, _b, _c, _d, _e;
7115
+ constructor(config) {
7116
+ var _a, _b;
6902
7117
  const sanitizedConfig = sanitizeConfig(config);
6903
7118
  this.apiKey = sanitizedConfig.apiKey;
6904
7119
  this.baseUrl = sanitizedConfig.baseUrl;
@@ -6909,10 +7124,8 @@ class Base {
6909
7124
  env.isNative = this.options.platform === 'ios' || this.options.platform === 'android';
6910
7125
  env.isWeb = !env.isNative;
6911
7126
  }
6912
- this.cipher = (_b = ports.cipher) !== null && _b !== void 0 ? _b : new Cipher();
6913
- this.transport = (_c = ports.transport) !== null && _c !== void 0 ? _c : ((...args) => fetch(...args));
6914
- this.clock = (_d = ports.clock) !== null && _d !== void 0 ? _d : { now: () => Date.now() };
6915
- this.lockManager = new LockManagerService();
7127
+ this.cipher = new Cipher();
7128
+ this.lockManager = sharedLockManager;
6916
7129
  this._initializeClientAuthToken(sanitizedConfig.clientAuthToken);
6917
7130
  this.request = this.request.bind(this);
6918
7131
  // The generated API client includes /api/v1 in each path, so strip it from
@@ -6925,7 +7138,6 @@ class Base {
6925
7138
  secure: true, // Enable security worker for all requests by default
6926
7139
  },
6927
7140
  securityWorker: this.securityWorker.bind(this),
6928
- customFetch: this.transport,
6929
7141
  });
6930
7142
  /**
6931
7143
  * This intercepts all API responses and transforms errors into WallabyError format.
@@ -6970,7 +7182,7 @@ class Base {
6970
7182
  return attemptRequest(false);
6971
7183
  };
6972
7184
  this.api = new Api(httpClient);
6973
- this.api.http.setSecurityData(Object.assign({ 'x-api-key': config.apiKey, 'x-client-jwt': config.clientAuthToken }, (_e = this.options) === null || _e === void 0 ? void 0 : _e.headers));
7185
+ 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));
6974
7186
  }
6975
7187
  set setClientAuthToken(token) {
6976
7188
  this._initializeClientAuthToken(token);
@@ -7035,6 +7247,7 @@ class Base {
7035
7247
  * @protected
7036
7248
  */
7037
7249
  get localStorageService() {
7250
+ var _a;
7038
7251
  if (!this.clientAuthToken) {
7039
7252
  throw new WallabyError({
7040
7253
  message: 'A client authentication token (JWT) is required',
@@ -7042,11 +7255,13 @@ class Base {
7042
7255
  errorCode: ErrorResponseCodes.sdk_missing_parameter,
7043
7256
  });
7044
7257
  }
7045
- return new StorageService({
7258
+ // Cached: StorageService depends only on deviceStorage/userId/environment, all stable
7259
+ // after construction. Recreating it per access reset the WAL `_walRecovered` flag.
7260
+ return ((_a = this._localStorageService) !== null && _a !== void 0 ? _a : (this._localStorageService = new StorageService({
7046
7261
  deviceStorage: this.deviceLocalStorage,
7047
7262
  userId: this.userId,
7048
7263
  environment: this.settings.environment,
7049
- });
7264
+ })));
7050
7265
  }
7051
7266
  /**
7052
7267
  * Fetches a new access/refresh token pair using the stored refresh token.
@@ -7089,7 +7304,7 @@ class Base {
7089
7304
  // Proactive token refresh: if access token is near expiry, refresh before making the request
7090
7305
  if (route !== AuthRoutes.refreshAccessToken && !retried) {
7091
7306
  const accessToken = await this.localStorageService.fetch(LocalStorageItems.AccessToken);
7092
- if (accessToken && isJwtNearExpiry(accessToken, 60, this.clock.now)) {
7307
+ if (accessToken && isJwtNearExpiry(accessToken, 60)) {
7093
7308
  await this._performTokenRefresh();
7094
7309
  }
7095
7310
  }
@@ -7113,7 +7328,7 @@ class Base {
7113
7328
  fetchOptions.body = JSON.stringify(options.payload);
7114
7329
  }
7115
7330
  logger.debug(`SDK::Base::${route.method}::Request`, { path: fullUrl, payload: options === null || options === void 0 ? void 0 : options.payload });
7116
- const response = await this.transport(fullUrl, fetchOptions);
7331
+ const response = await fetch(fullUrl, fetchOptions);
7117
7332
  const contentType = response.headers.get('content-type');
7118
7333
  let data;
7119
7334
  if (contentType === null || contentType === void 0 ? void 0 : contentType.includes('application/json')) {
@@ -7184,7 +7399,7 @@ class Base {
7184
7399
  }
7185
7400
  async _getRequestHeaders() {
7186
7401
  const accessToken = await this.localStorageService.fetch(LocalStorageItems.AccessToken);
7187
- if (jwtHasExpired(this.clientAuthToken, this.clock.now)) {
7402
+ if (!isTest && jwtHasExpired(this.clientAuthToken)) {
7188
7403
  throw new WallabyError({
7189
7404
  message: 'Auth token has expired',
7190
7405
  statusCode: 401,
@@ -7206,7 +7421,7 @@ class Base {
7206
7421
  // Proactive token refresh before building headers for the generated client
7207
7422
  try {
7208
7423
  const accessToken = await this.localStorageService.fetch(LocalStorageItems.AccessToken);
7209
- if (accessToken && isJwtNearExpiry(accessToken, 60, this.clock.now)) {
7424
+ if (accessToken && isJwtNearExpiry(accessToken, 60)) {
7210
7425
  await this._performTokenRefresh();
7211
7426
  }
7212
7427
  }
@@ -7696,8 +7911,8 @@ function decodeBase64URL(base64url) {
7696
7911
  }
7697
7912
 
7698
7913
  let PasskeyService$1 = class PasskeyService {
7699
- constructor(userId, storageService, request, cipher = new Cipher()) {
7700
- this.cipher = cipher;
7914
+ constructor(userId, storageService, request) {
7915
+ this.cipher = new Cipher();
7701
7916
  this.localStorageService = storageService;
7702
7917
  this.userId = userId;
7703
7918
  this.request = request;
@@ -8221,8 +8436,16 @@ function WithLock(lockKey) {
8221
8436
  }
8222
8437
  const originalMethod = descriptor.value;
8223
8438
  descriptor.value = async function (...args) {
8439
+ var _a, _b, _c, _d, _e;
8224
8440
  const lockManager = this.lockManager;
8225
- const key = lockKey || `${target.constructor.name}:${propertyKey}`;
8441
+ const operation = lockKey || `${target.constructor.name}:${propertyKey}`;
8442
+ // Scope the lock key by user/environment/network so a process-wide shared
8443
+ // LockManagerService doesn't make two instances for different users (or the
8444
+ // same user on a different env/network, with distinct storage namespaces)
8445
+ // spuriously block each other with "already in progress".
8446
+ const environment = (_b = (_a = this.options) === null || _a === void 0 ? void 0 : _a.environment) !== null && _b !== void 0 ? _b : defaultEnvironment;
8447
+ const network = (_d = (_c = this.options) === null || _c === void 0 ? void 0 : _c.network) !== null && _d !== void 0 ? _d : defaultNetwork;
8448
+ const key = `${(_e = this.userId) !== null && _e !== void 0 ? _e : 'anon'}:${environment}:${network}:${operation}`;
8226
8449
  return lockManager.withLock(key, () => originalMethod.apply(this, args));
8227
8450
  };
8228
8451
  return descriptor;
@@ -8230,10 +8453,10 @@ function WithLock(lockKey) {
8230
8453
  }
8231
8454
 
8232
8455
  class AuthService extends Base {
8233
- constructor(config, ports = {}) {
8234
- super(config, ports);
8456
+ constructor(config) {
8457
+ super(config);
8235
8458
  this.getUserSalt = this.getUserSalt.bind(this);
8236
- this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request, this.cipher);
8459
+ this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request);
8237
8460
  }
8238
8461
  /**
8239
8462
  * @description
@@ -8762,25 +8985,13 @@ __decorate([
8762
8985
  __metadata("design:returntype", Promise)
8763
8986
  ], AuthService.prototype, "storeDeviceKeyPair", null);
8764
8987
 
8765
- const ENCRYPTED_PAYLOAD_FIELDS = ['iv', 'ephemPublicKey', 'ciphertext', 'mac'];
8766
- // Backup share may be ECIES or symmetric ({ iv, ciphertext, mac, tag }) — both share these three fields.
8767
- const SYMMETRIC_PAYLOAD_FIELDS = ['iv', 'ciphertext', 'mac', 'tag'];
8768
- // API is the trust boundary: confirm every named field is a non-empty string.
8769
- function hasNonEmptyStringFields(payload, fields) {
8770
- return (!!payload &&
8771
- typeof payload === 'object' &&
8772
- fields.every((field) => {
8773
- const value = payload[field];
8774
- return typeof value === 'string' && value.length > 0;
8775
- }));
8776
- }
8777
8988
  /**
8778
8989
  * Fail fast if an encrypted payload from the API does not match the expected
8779
8990
  * ECIES structure ({ iv, ephemPublicKey, ciphertext, mac }). See the contract
8780
8991
  * note on `handleKeySharesFromResponse`.
8781
8992
  */
8782
8993
  function assertEncryptedPayloadShape(encrypted) {
8783
- if (!hasNonEmptyStringFields(encrypted, ENCRYPTED_PAYLOAD_FIELDS)) {
8994
+ if (!isEciesPayload(encrypted)) {
8784
8995
  throw new WallabyError({
8785
8996
  message: 'Encrypted share does not match the expected { iv, ephemPublicKey, ciphertext, mac } format.',
8786
8997
  statusCode: 422,
@@ -8809,20 +9020,18 @@ function assertSharesPayloadShape(shares) {
8809
9020
  * shape-check it. It may be ECIES or symmetric, so accept either variant.
8810
9021
  */
8811
9022
  function assertBackupSharePayloadShape(encrypted) {
8812
- const isEcies = hasNonEmptyStringFields(encrypted, ENCRYPTED_PAYLOAD_FIELDS);
8813
- const isSymmetric = hasNonEmptyStringFields(encrypted, SYMMETRIC_PAYLOAD_FIELDS);
8814
- if (!isEcies && !isSymmetric) {
9023
+ if (!isEciesPayload(encrypted) && !isSymmetricPayload(encrypted)) {
8815
9024
  throw new WallabyError({
8816
- message: 'Encrypted backup share does not match the expected ECIES ({ iv, ephemPublicKey, ciphertext, mac }) or symmetric ({ iv, ciphertext, mac, tag }) format.',
9025
+ message: 'Encrypted backup share does not match the expected ECIES ({ iv, ephemPublicKey, ciphertext, mac }) or symmetric ({ v, iv, ciphertext, tag }) format.',
8817
9026
  statusCode: 422,
8818
9027
  errorCode: ErrorResponseCodes.sdk_invalid_parameter,
8819
9028
  });
8820
9029
  }
8821
9030
  }
8822
9031
  class WalletHandlersService extends Base {
8823
- constructor(config, ports = {}) {
8824
- super(config, ports);
8825
- this.authService = new AuthService(config, ports);
9032
+ constructor(config) {
9033
+ super(config);
9034
+ this.authService = new AuthService(config);
8826
9035
  this.userId = config.userId;
8827
9036
  }
8828
9037
  async handleImportWallet(deviceAuthKeys, importWalletInput) {
@@ -9128,12 +9337,12 @@ class WalletHandlersService extends Base {
9128
9337
  }
9129
9338
 
9130
9339
  class WalletService extends Base {
9131
- constructor(config, ports = {}) {
9132
- super(config, ports);
9133
- this.authService = new AuthService(config, ports);
9134
- this.handlers = new WalletHandlersService(config, ports);
9340
+ constructor(config) {
9341
+ super(config);
9342
+ this.authService = new AuthService(config);
9343
+ this.handlers = new WalletHandlersService(config);
9135
9344
  this.userId = config.userId;
9136
- this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request, this.cipher);
9345
+ this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request);
9137
9346
  }
9138
9347
  /**
9139
9348
  * Reads the persisted sliding-window rate-limit state for a counter key.
@@ -9654,7 +9863,7 @@ class WalletService extends Base {
9654
9863
  password: newPassword,
9655
9864
  salt: clientSalt,
9656
9865
  });
9657
- if (!newCredentialsKeyPair.publicKey) {
9866
+ if (!newCredentialsKeyPair.publicKey || !newCredentialsKeyPair.privateKey) {
9658
9867
  throw new WallabyError({
9659
9868
  message: 'Could not derive keys for new password.',
9660
9869
  statusCode: 500,
@@ -9677,6 +9886,9 @@ class WalletService extends Base {
9677
9886
  errorCode: ErrorResponseCodes.sdk_unknown_error,
9678
9887
  });
9679
9888
  }
9889
+ // Round-trip validate: decrypt the re-wrapped blob with the new key before committing.
9890
+ // Catches a malformed re-encryption before it overwrites the live credential.
9891
+ await this.assertRoundTrip(reWrappedDevicePrivateKey, newCredentialsKeyPair.privateKey, 'device key');
9680
9892
  const reWrappedSeedPhrase = encryptedSeedPhraseString
9681
9893
  ? await this.cipher.flipEncryptedData({
9682
9894
  cipherText: safeJsonParse(encryptedSeedPhraseString),
@@ -9698,9 +9910,13 @@ class WalletService extends Base {
9698
9910
  encryptionKey: newCredentialsKeyPair.publicKey,
9699
9911
  })
9700
9912
  : null;
9701
- // Commit all re-wrapped blobs in one batch so a partial failure cannot leave the device
9702
- // in a half-migrated state (some items under the new password, others under the old).
9703
- await this.localStorageService.saveInBulk([
9913
+ if (reWrappedSeedPhrase)
9914
+ await this.assertRoundTrip(reWrappedSeedPhrase, newCredentialsKeyPair.privateKey, 'seed phrase');
9915
+ if (reWrappedPrimaryShare)
9916
+ await this.assertRoundTrip(reWrappedPrimaryShare, newCredentialsKeyPair.privateKey, 'primary share');
9917
+ if (reWrappedBackupShare)
9918
+ await this.assertRoundTrip(reWrappedBackupShare, newCredentialsKeyPair.privateKey, 'backup share');
9919
+ await this.localStorageService.commitBatch([
9704
9920
  { key: LocalStorageItems.EncryptedDevicePrivateKey, value: reWrappedDevicePrivateKey },
9705
9921
  ...(reWrappedSeedPhrase
9706
9922
  ? [{ key: LocalStorageItems.EncryptedStandardSeedPhrase, value: reWrappedSeedPhrase, walletId }]
@@ -9923,6 +10139,24 @@ class WalletService extends Base {
9923
10139
  });
9924
10140
  }
9925
10141
  }
10142
+ /**
10143
+ * Assert a decrypted private key is valid secp256k1 key material. If it isn't, the stored value is
10144
+ * corrupted (or a wrong password decrypted to non-key garbage) — surface a clear, distinct error
10145
+ * instead of letting the raw validation message escape or collapsing into a misleading "wrong password".
10146
+ */
10147
+ assertValidDeviceKey(privateKey) {
10148
+ try {
10149
+ this.cipher.validatePrivateKey(privateKey);
10150
+ }
10151
+ catch (error) {
10152
+ logger.error('SDK::WalletService::assertValidDeviceKey::decrypted private key is not valid key material', error);
10153
+ throw new WallabyError({
10154
+ message: 'Could not access your device key — your stored wallet credentials appear to be corrupted.',
10155
+ statusCode: 500,
10156
+ errorCode: ErrorResponseCodes.sdk_private_key_decryption_failed,
10157
+ });
10158
+ }
10159
+ }
9926
10160
  /**
9927
10161
  * Detects and migrates legacy/v1 storage items to v2 format.
9928
10162
  * This function should be called in methods that use password as input when v2 items are missing.
@@ -10010,10 +10244,9 @@ class WalletService extends Base {
10010
10244
  // getDecryptedV1PrivateKey checks for both v1 and legacy formats internally
10011
10245
  const legacyDecryptedPrivateKey = await this.localStorageService.getDecryptedV1PrivateKey(password);
10012
10246
  if (legacyEncryptedSeed && legacyDecryptedPrivateKey) {
10013
- const legacyPublicKey = publicKeyByPrivateKey(legacyDecryptedPrivateKey);
10247
+ this.assertValidDeviceKey(legacyDecryptedPrivateKey);
10014
10248
  logger.info('SDK::WalletService::handleUpdateToV2::Found legacy storage items, attempting migration', {
10015
10249
  storageFormat: 'legacy',
10016
- devicePublicKey: legacyPublicKey.substring(0, 16) + '...',
10017
10250
  });
10018
10251
  try {
10019
10252
  // Decrypt legacy items using password/salt combination
@@ -10045,12 +10278,13 @@ class WalletService extends Base {
10045
10278
  const v1EncryptedSeed = await this.localStorageService.getEncryptedSeedPhrase(SeedPhraseType.Standard, walletId);
10046
10279
  const v1EncryptedPrivateKey = await this.localStorageService.getEncryptedPrivateKey();
10047
10280
  if (v1EncryptedSeed && v1EncryptedPrivateKey) {
10048
- // Get public key before decryption for logging
10049
10281
  decryptedPrivateKey = await this.localStorageService.getDecryptedV1PrivateKey(password);
10050
- const v1PublicKey = decryptedPrivateKey ? publicKeyByPrivateKey(decryptedPrivateKey) : 'unknown';
10282
+ // Validate the decrypted private key before proceeding with migration
10283
+ if (decryptedPrivateKey)
10284
+ this.assertValidDeviceKey(decryptedPrivateKey);
10051
10285
  logger.info('SDK::WalletService::handleUpdateToV2::Found V1 storage items, attempting migration', {
10052
10286
  storageFormat: 'v1',
10053
- devicePublicKey: v1PublicKey.substring(0, 16) + '...',
10287
+ validPrivateKey: !!decryptedPrivateKey,
10054
10288
  });
10055
10289
  try {
10056
10290
  // Decrypt V1 items using storage service method (handles double encryption)
@@ -10285,7 +10519,28 @@ class WalletService extends Base {
10285
10519
  * @returns { boolean } whether the operation was successful
10286
10520
  */
10287
10521
  async convertToPasskey(input) {
10522
+ let passkeyRegistered = false;
10288
10523
  try {
10524
+ // Recover an interrupted conversion BEFORE reading any credential blob. A prior attempt may have
10525
+ // already rewrapped EncryptedDevicePrivateKey to passkey form (addNewPasskey persists it outside
10526
+ // this method's atomic commit), which the password can no longer decrypt — and deriving the passkey
10527
+ // key to decrypt it needs the device key itself (circular). The marker stashes the original
10528
+ // password-encrypted device key; restore it so the rest of the flow runs as a fresh conversion.
10529
+ const rawConversionMarker = (await this.localStorageService.fetch(V2KeyNames.CredentialConversionInProgress));
10530
+ const existingConversionMarker = rawConversionMarker
10531
+ ? safeJsonParse(rawConversionMarker)
10532
+ : undefined;
10533
+ // Restore the stashed device key whenever a marker carries one — independent of walletId. The
10534
+ // device key is per-user (not wallet-scoped), so a conversion interrupted on a different wallet
10535
+ // leaves the shared device key passkey-wrapped too. Restoring is idempotent (rewrites the
10536
+ // original password-encrypted blob) and stops a second wallet's conversion from destroying the
10537
+ // first's recovery state. v2 only — a v1 wallet's untouched v1 key still decrypts.
10538
+ if (existingConversionMarker === null || existingConversionMarker === void 0 ? void 0 : existingConversionMarker.encryptedDevicePrivateKey) {
10539
+ await this.localStorageService.save(LocalStorageItems.EncryptedDevicePrivateKey, existingConversionMarker.encryptedDevicePrivateKey);
10540
+ }
10541
+ if ((existingConversionMarker === null || existingConversionMarker === void 0 ? void 0 : existingConversionMarker.walletId) === input.walletId) {
10542
+ logger.info('SDK::WalletService::convertToPasskey::resuming interrupted conversion');
10543
+ }
10289
10544
  const v2EncryptedPriv = await this.localStorageService.fetch(LocalStorageItems.EncryptedDevicePrivateKey);
10290
10545
  const v2EncryptedSeed = await this.localStorageService.fetch(LocalStorageItems.EncryptedStandardSeedPhrase, {
10291
10546
  walletId: input.walletId,
@@ -10334,6 +10589,10 @@ class WalletService extends Base {
10334
10589
  });
10335
10590
  }
10336
10591
  const clientPublicKey = publicKeyByPrivateKey(decryptedClientAuthPrivKey);
10592
+ // Write-ahead marker: set before the unrevocable passkey registration so an interrupted
10593
+ // conversion can be resumed on the next attempt. Stash the original password-encrypted device
10594
+ // key so resume survives addNewPasskey rewrapping the stored device key to passkey form.
10595
+ await this.localStorageService.save(V2KeyNames.CredentialConversionInProgress, Object.assign({ walletId: input.walletId }, (v2EncryptedPriv ? { encryptedDevicePrivateKey: v2EncryptedPriv } : {})));
10337
10596
  const authentication = await this.passkeyService.addNewPasskey({
10338
10597
  deviceKeyPair: {
10339
10598
  publicKey: clientPublicKey,
@@ -10341,6 +10600,7 @@ class WalletService extends Base {
10341
10600
  },
10342
10601
  getSignature: this.authService.getSignature.bind(this),
10343
10602
  });
10603
+ passkeyRegistered = true;
10344
10604
  const prfValue = authentication.prfValue;
10345
10605
  if (!prfValue || !(prfValue instanceof Uint8Array) || prfValue.length === 0) {
10346
10606
  logger.error('SDK::WalletService::convertToPasskey::prfValue is required and must be a non-empty Uint8Array');
@@ -10437,8 +10697,13 @@ class WalletService extends Base {
10437
10697
  storeOneKeyShareWithWallaby: true,
10438
10698
  },
10439
10699
  });
10440
- // Delete the old password-encrypted seed phrase since import stored the new passkey-encrypted version
10441
- await this.localStorageService.delete(LocalStorageItems.EncryptedStandardSeedPhrase, { walletId: input.walletId });
10700
+ // idempotent — on retry (marker present, primary now passkey-encrypted so
10701
+ // decryptedPrimaryShare is undefined → Branch A re-enters), handleImportWallet re-shares
10702
+ // safely; this atomic delete clears the stale seed + marker together.
10703
+ await this.localStorageService.commitBatch([], [
10704
+ { key: LocalStorageItems.EncryptedStandardSeedPhrase, walletId: input.walletId },
10705
+ { key: V2KeyNames.CredentialConversionInProgress },
10706
+ ]);
10442
10707
  logger.info('SDK::WalletService::convertToPasskey::Wallet imported and converted successfully, old seed phrase removed');
10443
10708
  return { authentication, seedPhrase: decryptedSeedPhrase };
10444
10709
  }
@@ -10456,6 +10721,24 @@ class WalletService extends Base {
10456
10721
  privateKey: decryptedClientAuthPrivKey,
10457
10722
  },
10458
10723
  });
10724
+ // assertRoundTrip below only strips the outer (passkey) layer — validate the inner (device key) layer here.
10725
+ const outerDecrypted = await this.cipher.decrypt({
10726
+ cipherText: encryptedPrimaryShare,
10727
+ decryptionKey: passkeyDerivedKeyPair.privateKey,
10728
+ });
10729
+ const innerDecrypted = outerDecrypted
10730
+ ? await this.cipher.decrypt({
10731
+ cipherText: safeJsonParse(outerDecrypted),
10732
+ decryptionKey: decryptedClientAuthPrivKey,
10733
+ })
10734
+ : null;
10735
+ if (innerDecrypted !== decryptedPrimaryShare) {
10736
+ throw new WallabyError({
10737
+ message: 'Re-wrap validation failed for primary share: inner layer round-trip mismatch. Aborting to prevent credential corruption.',
10738
+ statusCode: 500,
10739
+ errorCode: ErrorResponseCodes.sdk_unknown_error,
10740
+ });
10741
+ }
10459
10742
  convertedShares.push({
10460
10743
  key: V2KeyNames.PrimaryDeviceKeyShare,
10461
10744
  value: encryptedPrimaryShare,
@@ -10474,9 +10757,16 @@ class WalletService extends Base {
10474
10757
  walletId: input.walletId,
10475
10758
  });
10476
10759
  }
10477
- await this.localStorageService.saveInBulk(convertedShares);
10760
+ // Round-trip validate each re-encrypted blob (outer layer only) before writing.
10761
+ // A failed decrypt here means re-encryption produced an unreadable blob — abort before overwriting live credentials.
10762
+ for (const share of convertedShares) {
10763
+ await this.assertRoundTrip(share.value, passkeyDerivedKeyPair.privateKey, share.key);
10764
+ }
10765
+ await this.localStorageService.commitBatch(convertedShares, [
10766
+ ...(v2EncryptedSeed ? [{ key: LocalStorageItems.EncryptedStandardSeedPhrase, walletId: input.walletId }] : []),
10767
+ { key: V2KeyNames.CredentialConversionInProgress },
10768
+ ]);
10478
10769
  if (v2EncryptedSeed) {
10479
- await this.localStorageService.delete(LocalStorageItems.EncryptedStandardSeedPhrase, { walletId: input.walletId });
10480
10770
  logger.info('SDK::WalletService::convertToPasskey::Seed phrase removed from device storage after conversion to passkey');
10481
10771
  }
10482
10772
  if (!decryptedSeedPhrase && decryptedPrimaryShare) {
@@ -10519,11 +10809,30 @@ class WalletService extends Base {
10519
10809
  }
10520
10810
  catch (error) {
10521
10811
  logger.error('SDK::WalletService::convertToPasskey::error', error);
10812
+ // Only clear the marker if the passkey was not yet registered. After registration the
10813
+ // marker must survive for roll-forward on the next attempt.
10814
+ if (!passkeyRegistered) {
10815
+ await this.localStorageService.delete(V2KeyNames.CredentialConversionInProgress);
10816
+ }
10522
10817
  throw error;
10523
10818
  }
10524
10819
  }
10820
+ // shared guard — decrypt-tests a re-wrapped blob before any write so a malformed
10821
+ // re-encryption is caught before it overwrites the live credential.
10822
+ async assertRoundTrip(blob, decryptionKey, label) {
10823
+ try {
10824
+ await this.cipher.decrypt({ cipherText: blob, decryptionKey });
10825
+ }
10826
+ catch (_a) {
10827
+ throw new WallabyError({
10828
+ message: `Re-wrap validation failed for ${label}: decryption of the re-encrypted blob failed. Aborting to prevent credential corruption.`,
10829
+ statusCode: 500,
10830
+ errorCode: ErrorResponseCodes.sdk_unknown_error,
10831
+ });
10832
+ }
10833
+ }
10525
10834
  }
10526
- // ponytail: soft client-side guardrail against runaway retries; server-side rate limiting is the real control.
10835
+ // soft client-side guardrail against runaway retries; server-side rate limiting is the real control.
10527
10836
  // Counters are persisted (sliding window) so rebuilding the service no longer resets them. Tune freely.
10528
10837
  WalletService.RATE_LIMIT_MAX = 5;
10529
10838
  WalletService.RATE_LIMIT_WINDOW_MS = 30 * 60000; // 30 min
@@ -10546,7 +10855,7 @@ __decorate([
10546
10855
  __metadata("design:returntype", Promise)
10547
10856
  ], WalletService.prototype, "recover", null);
10548
10857
  __decorate([
10549
- WithLock('changePassword'),
10858
+ WithLock('credential-rewrap'),
10550
10859
  __metadata("design:type", Function),
10551
10860
  __metadata("design:paramtypes", [Object]),
10552
10861
  __metadata("design:returntype", Promise)
@@ -10557,12 +10866,18 @@ __decorate([
10557
10866
  __metadata("design:paramtypes", [Object]),
10558
10867
  __metadata("design:returntype", Promise)
10559
10868
  ], WalletService.prototype, "handleUpdateToV2", null);
10869
+ __decorate([
10870
+ WithLock('credential-rewrap'),
10871
+ __metadata("design:type", Function),
10872
+ __metadata("design:paramtypes", [Object]),
10873
+ __metadata("design:returntype", Promise)
10874
+ ], WalletService.prototype, "convertToPasskey", null);
10560
10875
 
10561
10876
  class WalletDataService extends Base {
10562
- constructor(config, ports = {}) {
10563
- super(config, ports);
10877
+ constructor(config) {
10878
+ super(config);
10564
10879
  this.userId = config.userId;
10565
- this.walletService = new WalletService(config, ports);
10880
+ this.walletService = new WalletService(config);
10566
10881
  }
10567
10882
  /**
10568
10883
  * @description Validates the wallet address info for a given blockchain.
@@ -10883,8 +11198,8 @@ class WalletDataService extends Base {
10883
11198
  }
10884
11199
 
10885
11200
  class Utils extends Base {
10886
- constructor(config, ports = {}) {
10887
- super(config, ports);
11201
+ constructor(config) {
11202
+ super(config);
10888
11203
  /**
10889
11204
  *
10890
11205
  * Decrypts user private key
@@ -10917,7 +11232,7 @@ class Utils extends Base {
10917
11232
  return undefined;
10918
11233
  }
10919
11234
  };
10920
- this.auth = new AuthService(config, ports);
11235
+ this.auth = new AuthService(config);
10921
11236
  }
10922
11237
  /**
10923
11238
  *
@@ -11024,16 +11339,16 @@ class HttpApi extends Base {
11024
11339
  * @param config - The Wallaby configuration object
11025
11340
  * @public
11026
11341
  */
11027
- constructor(config, ports = {}) {
11028
- super(config, ports);
11342
+ constructor(config) {
11343
+ super(config);
11029
11344
  }
11030
11345
  }
11031
11346
 
11032
11347
  class Swap extends Base {
11033
- constructor(config, ports = {}) {
11034
- super(config, ports);
11035
- this.authService = new AuthService(config, ports);
11036
- this.walletService = new WalletService(config, ports);
11348
+ constructor(config) {
11349
+ super(config);
11350
+ this.authService = new AuthService(config);
11351
+ this.walletService = new WalletService(config);
11037
11352
  }
11038
11353
  /**
11039
11354
  * Gets a swap quote between two assets, including fees, min output, and slippage limits.
@@ -11285,9 +11600,30 @@ const sanitizeSuiObjectId = (objectId) => {
11285
11600
  return objectId.split('::')[0];
11286
11601
  };
11287
11602
 
11603
+ /**
11604
+ * Extracts the asset symbol from a fully-qualified Sui coin type.
11605
+ *
11606
+ * A Sui coin type has the shape `<package>::<module>::<TYPE>`, where the final
11607
+ * segment is the coin's struct name and doubles as its symbol.
11608
+ *
11609
+ * @param objectId - The Sui object id / coin type. Example input:
11610
+ * "0xc91acfb75009c5ff2fd57c54f3caaee12ad1fbe997681334adc0b574fc277a07::icorgi::ICORGI"
11611
+ * @returns The symbol (e.g. "ICORGI"), or undefined when the id carries no
11612
+ * `::module::TYPE` suffix to derive it from.
11613
+ */
11614
+ const extractSuiAssetSymbol = (objectId) => {
11615
+ var _a;
11616
+ if (!objectId || !objectId.includes('::')) {
11617
+ return undefined;
11618
+ }
11619
+ const segments = objectId.split('::');
11620
+ const symbol = (_a = segments[segments.length - 1]) === null || _a === void 0 ? void 0 : _a.trim();
11621
+ return symbol || undefined;
11622
+ };
11623
+
11288
11624
  class System extends Base {
11289
- constructor(config, ports = {}) {
11290
- super(config, ports);
11625
+ constructor(config) {
11626
+ super(config);
11291
11627
  }
11292
11628
  /**
11293
11629
  * @public
@@ -11373,6 +11709,9 @@ class System extends Base {
11373
11709
  * @param {BlockchainName} blockchain - The name of the blockchain.
11374
11710
  * @param {string} contractAddress - The contract address of the token (optional for non-SUI blockchains).
11375
11711
  * @param {string} suiObjectId - The SUI object ID of the token (optional for SUI blockchain).
11712
+ * @param {string} assetSymbol - The asset symbol; disambiguates new SUI assets. For SUI it is
11713
+ * optional: when omitted, it is derived from the `::module::TYPE` suffix of `suiObjectId`
11714
+ * (which is otherwise trimmed off before the request is sent).
11376
11715
  *
11377
11716
  * @returns {Promise<{ decimals: number; symbol: string; name: string; tokenContractAddress: string }>} A promise that resolves to an object containing token information.
11378
11717
  *
@@ -11381,18 +11720,19 @@ class System extends Base {
11381
11720
  * @throws Will throw an error if `contractAddress` is not provided for non-SUI blockchains.
11382
11721
  * @throws Will throw an error if the response is invalid or contains an error.
11383
11722
  */
11384
- async fetchTokenInfo({ blockchain, contractAddress, suiObjectId, }) {
11723
+ async fetchTokenInfo({ blockchain, contractAddress, suiObjectId, assetSymbol, }) {
11385
11724
  try {
11386
11725
  const validatedContractAddress = this.validateContractAddress({
11387
11726
  blockchain,
11388
11727
  contractAddress,
11389
11728
  suiObjectId,
11390
11729
  });
11730
+ // For SUI, the coin symbol is the last segment of the coin type
11731
+ // (`<package>::<module>::<TYPE>`), which sanitizeSuiObjectId strips out.
11732
+ // Derive it so callers don't have to pass assetSymbol explicitly.
11733
+ const resolvedAssetSymbol = assetSymbol !== null && assetSymbol !== void 0 ? assetSymbol : (blockchain === BlockchainName.Sui ? extractSuiAssetSymbol(suiObjectId) : undefined);
11391
11734
  const response = await this.request(SystemRoutes.fetchTokenInfo, {
11392
- queryParams: {
11393
- chainName: blockchain,
11394
- tokenContractAddress: validatedContractAddress,
11395
- },
11735
+ queryParams: Object.assign({ chainName: blockchain, tokenContractAddress: validatedContractAddress }, (resolvedAssetSymbol ? { assetSymbol: resolvedAssetSymbol } : {})),
11396
11736
  });
11397
11737
  return response;
11398
11738
  }
@@ -11480,10 +11820,10 @@ class System extends Base {
11480
11820
  }
11481
11821
 
11482
11822
  class Transactions extends Base {
11483
- constructor(config, ports = {}) {
11484
- super(config, ports);
11485
- this.authService = new AuthService(config, ports);
11486
- this.walletService = new WalletService(config, ports);
11823
+ constructor(config) {
11824
+ super(config);
11825
+ this.authService = new AuthService(config);
11826
+ this.walletService = new WalletService(config);
11487
11827
  this.userId = config.userId;
11488
11828
  }
11489
11829
  /**
@@ -11924,15 +12264,15 @@ class Wallaby {
11924
12264
  * @param {string} [config.clientAuthToken] - A web token generated by the client for authorization.
11925
12265
  * @public
11926
12266
  */
11927
- constructor(config, ports = {}) {
11928
- this.wallet = new WalletService(config, ports);
11929
- this.walletData = new WalletDataService(config, ports);
11930
- this.utils = new Utils(config, ports);
11931
- this.auth = new AuthService(config, ports);
11932
- this.system = new System(config, ports);
11933
- this.transactions = new Transactions(config, ports);
11934
- this.swap = new Swap(config, ports);
11935
- this.httpApi = new HttpApi(config, ports);
12267
+ constructor(config) {
12268
+ this.wallet = new WalletService(config);
12269
+ this.walletData = new WalletDataService(config);
12270
+ this.utils = new Utils(config);
12271
+ this.auth = new AuthService(config);
12272
+ this.system = new System(config);
12273
+ this.transactions = new Transactions(config);
12274
+ this.swap = new Swap(config);
12275
+ this.httpApi = new HttpApi(config);
11936
12276
  }
11937
12277
  get version() {
11938
12278
  return currentPackageVersion;