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.esm.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
  }
@@ -7587,8 +7802,8 @@ function decodeBase64URL(base64url) {
7587
7802
  }
7588
7803
 
7589
7804
  class PasskeyService {
7590
- constructor(userId, storageService, request, cipher = new Cipher()) {
7591
- this.cipher = cipher;
7805
+ constructor(userId, storageService, request) {
7806
+ this.cipher = new Cipher();
7592
7807
  this.localStorageService = storageService;
7593
7808
  this.userId = userId;
7594
7809
  this.request = request;
@@ -8101,8 +8316,16 @@ function WithLock(lockKey) {
8101
8316
  }
8102
8317
  const originalMethod = descriptor.value;
8103
8318
  descriptor.value = async function (...args) {
8319
+ var _a, _b, _c, _d, _e;
8104
8320
  const lockManager = this.lockManager;
8105
- const key = lockKey || `${target.constructor.name}:${propertyKey}`;
8321
+ const operation = lockKey || `${target.constructor.name}:${propertyKey}`;
8322
+ // Scope the lock key by user/environment/network so a process-wide shared
8323
+ // LockManagerService doesn't make two instances for different users (or the
8324
+ // same user on a different env/network, with distinct storage namespaces)
8325
+ // spuriously block each other with "already in progress".
8326
+ const environment = (_b = (_a = this.options) === null || _a === void 0 ? void 0 : _a.environment) !== null && _b !== void 0 ? _b : defaultEnvironment;
8327
+ const network = (_d = (_c = this.options) === null || _c === void 0 ? void 0 : _c.network) !== null && _d !== void 0 ? _d : defaultNetwork;
8328
+ const key = `${(_e = this.userId) !== null && _e !== void 0 ? _e : 'anon'}:${environment}:${network}:${operation}`;
8106
8329
  return lockManager.withLock(key, () => originalMethod.apply(this, args));
8107
8330
  };
8108
8331
  return descriptor;
@@ -8110,10 +8333,10 @@ function WithLock(lockKey) {
8110
8333
  }
8111
8334
 
8112
8335
  class AuthService extends Base {
8113
- constructor(config, ports = {}) {
8114
- super(config, ports);
8336
+ constructor(config) {
8337
+ super(config);
8115
8338
  this.getUserSalt = this.getUserSalt.bind(this);
8116
- this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request, this.cipher);
8339
+ this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request);
8117
8340
  }
8118
8341
  /**
8119
8342
  * @description
@@ -8642,25 +8865,13 @@ __decorate([
8642
8865
  __metadata("design:returntype", Promise)
8643
8866
  ], AuthService.prototype, "storeDeviceKeyPair", null);
8644
8867
 
8645
- const ENCRYPTED_PAYLOAD_FIELDS = ['iv', 'ephemPublicKey', 'ciphertext', 'mac'];
8646
- // Backup share may be ECIES or symmetric ({ iv, ciphertext, mac, tag }) — both share these three fields.
8647
- const SYMMETRIC_PAYLOAD_FIELDS = ['iv', 'ciphertext', 'mac', 'tag'];
8648
- // API is the trust boundary: confirm every named field is a non-empty string.
8649
- function hasNonEmptyStringFields(payload, fields) {
8650
- return (!!payload &&
8651
- typeof payload === 'object' &&
8652
- fields.every((field) => {
8653
- const value = payload[field];
8654
- return typeof value === 'string' && value.length > 0;
8655
- }));
8656
- }
8657
8868
  /**
8658
8869
  * Fail fast if an encrypted payload from the API does not match the expected
8659
8870
  * ECIES structure ({ iv, ephemPublicKey, ciphertext, mac }). See the contract
8660
8871
  * note on `handleKeySharesFromResponse`.
8661
8872
  */
8662
8873
  function assertEncryptedPayloadShape(encrypted) {
8663
- if (!hasNonEmptyStringFields(encrypted, ENCRYPTED_PAYLOAD_FIELDS)) {
8874
+ if (!isEciesPayload(encrypted)) {
8664
8875
  throw new WallabyError({
8665
8876
  message: 'Encrypted share does not match the expected { iv, ephemPublicKey, ciphertext, mac } format.',
8666
8877
  statusCode: 422,
@@ -8689,20 +8900,18 @@ function assertSharesPayloadShape(shares) {
8689
8900
  * shape-check it. It may be ECIES or symmetric, so accept either variant.
8690
8901
  */
8691
8902
  function assertBackupSharePayloadShape(encrypted) {
8692
- const isEcies = hasNonEmptyStringFields(encrypted, ENCRYPTED_PAYLOAD_FIELDS);
8693
- const isSymmetric = hasNonEmptyStringFields(encrypted, SYMMETRIC_PAYLOAD_FIELDS);
8694
- if (!isEcies && !isSymmetric) {
8903
+ if (!isEciesPayload(encrypted) && !isSymmetricPayload(encrypted)) {
8695
8904
  throw new WallabyError({
8696
- message: 'Encrypted backup share does not match the expected ECIES ({ iv, ephemPublicKey, ciphertext, mac }) or symmetric ({ iv, ciphertext, mac, tag }) format.',
8905
+ message: 'Encrypted backup share does not match the expected ECIES ({ iv, ephemPublicKey, ciphertext, mac }) or symmetric ({ v, iv, ciphertext, tag }) format.',
8697
8906
  statusCode: 422,
8698
8907
  errorCode: ErrorResponseCodes.sdk_invalid_parameter,
8699
8908
  });
8700
8909
  }
8701
8910
  }
8702
8911
  class WalletHandlersService extends Base {
8703
- constructor(config, ports = {}) {
8704
- super(config, ports);
8705
- this.authService = new AuthService(config, ports);
8912
+ constructor(config) {
8913
+ super(config);
8914
+ this.authService = new AuthService(config);
8706
8915
  this.userId = config.userId;
8707
8916
  }
8708
8917
  async handleImportWallet(deviceAuthKeys, importWalletInput) {
@@ -9008,12 +9217,12 @@ class WalletHandlersService extends Base {
9008
9217
  }
9009
9218
 
9010
9219
  class WalletService extends Base {
9011
- constructor(config, ports = {}) {
9012
- super(config, ports);
9013
- this.authService = new AuthService(config, ports);
9014
- this.handlers = new WalletHandlersService(config, ports);
9220
+ constructor(config) {
9221
+ super(config);
9222
+ this.authService = new AuthService(config);
9223
+ this.handlers = new WalletHandlersService(config);
9015
9224
  this.userId = config.userId;
9016
- this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request, this.cipher);
9225
+ this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request);
9017
9226
  }
9018
9227
  /**
9019
9228
  * Reads the persisted sliding-window rate-limit state for a counter key.
@@ -9534,7 +9743,7 @@ class WalletService extends Base {
9534
9743
  password: newPassword,
9535
9744
  salt: clientSalt,
9536
9745
  });
9537
- if (!newCredentialsKeyPair.publicKey) {
9746
+ if (!newCredentialsKeyPair.publicKey || !newCredentialsKeyPair.privateKey) {
9538
9747
  throw new WallabyError({
9539
9748
  message: 'Could not derive keys for new password.',
9540
9749
  statusCode: 500,
@@ -9557,6 +9766,9 @@ class WalletService extends Base {
9557
9766
  errorCode: ErrorResponseCodes.sdk_unknown_error,
9558
9767
  });
9559
9768
  }
9769
+ // Round-trip validate: decrypt the re-wrapped blob with the new key before committing.
9770
+ // Catches a malformed re-encryption before it overwrites the live credential.
9771
+ await this.assertRoundTrip(reWrappedDevicePrivateKey, newCredentialsKeyPair.privateKey, 'device key');
9560
9772
  const reWrappedSeedPhrase = encryptedSeedPhraseString
9561
9773
  ? await this.cipher.flipEncryptedData({
9562
9774
  cipherText: safeJsonParse(encryptedSeedPhraseString),
@@ -9578,9 +9790,13 @@ class WalletService extends Base {
9578
9790
  encryptionKey: newCredentialsKeyPair.publicKey,
9579
9791
  })
9580
9792
  : null;
9581
- // Commit all re-wrapped blobs in one batch so a partial failure cannot leave the device
9582
- // in a half-migrated state (some items under the new password, others under the old).
9583
- await this.localStorageService.saveInBulk([
9793
+ if (reWrappedSeedPhrase)
9794
+ await this.assertRoundTrip(reWrappedSeedPhrase, newCredentialsKeyPair.privateKey, 'seed phrase');
9795
+ if (reWrappedPrimaryShare)
9796
+ await this.assertRoundTrip(reWrappedPrimaryShare, newCredentialsKeyPair.privateKey, 'primary share');
9797
+ if (reWrappedBackupShare)
9798
+ await this.assertRoundTrip(reWrappedBackupShare, newCredentialsKeyPair.privateKey, 'backup share');
9799
+ await this.localStorageService.commitBatch([
9584
9800
  { key: LocalStorageItems.EncryptedDevicePrivateKey, value: reWrappedDevicePrivateKey },
9585
9801
  ...(reWrappedSeedPhrase
9586
9802
  ? [{ key: LocalStorageItems.EncryptedStandardSeedPhrase, value: reWrappedSeedPhrase, walletId }]
@@ -9803,6 +10019,24 @@ class WalletService extends Base {
9803
10019
  });
9804
10020
  }
9805
10021
  }
10022
+ /**
10023
+ * Assert a decrypted private key is valid secp256k1 key material. If it isn't, the stored value is
10024
+ * corrupted (or a wrong password decrypted to non-key garbage) — surface a clear, distinct error
10025
+ * instead of letting the raw validation message escape or collapsing into a misleading "wrong password".
10026
+ */
10027
+ assertValidDeviceKey(privateKey) {
10028
+ try {
10029
+ this.cipher.validatePrivateKey(privateKey);
10030
+ }
10031
+ catch (error) {
10032
+ logger.error('SDK::WalletService::assertValidDeviceKey::decrypted private key is not valid key material', error);
10033
+ throw new WallabyError({
10034
+ message: 'Could not access your device key — your stored wallet credentials appear to be corrupted.',
10035
+ statusCode: 500,
10036
+ errorCode: ErrorResponseCodes.sdk_private_key_decryption_failed,
10037
+ });
10038
+ }
10039
+ }
9806
10040
  /**
9807
10041
  * Detects and migrates legacy/v1 storage items to v2 format.
9808
10042
  * This function should be called in methods that use password as input when v2 items are missing.
@@ -9890,10 +10124,9 @@ class WalletService extends Base {
9890
10124
  // getDecryptedV1PrivateKey checks for both v1 and legacy formats internally
9891
10125
  const legacyDecryptedPrivateKey = await this.localStorageService.getDecryptedV1PrivateKey(password);
9892
10126
  if (legacyEncryptedSeed && legacyDecryptedPrivateKey) {
9893
- const legacyPublicKey = publicKeyByPrivateKey(legacyDecryptedPrivateKey);
10127
+ this.assertValidDeviceKey(legacyDecryptedPrivateKey);
9894
10128
  logger.info('SDK::WalletService::handleUpdateToV2::Found legacy storage items, attempting migration', {
9895
10129
  storageFormat: 'legacy',
9896
- devicePublicKey: legacyPublicKey.substring(0, 16) + '...',
9897
10130
  });
9898
10131
  try {
9899
10132
  // Decrypt legacy items using password/salt combination
@@ -9925,12 +10158,13 @@ class WalletService extends Base {
9925
10158
  const v1EncryptedSeed = await this.localStorageService.getEncryptedSeedPhrase(SeedPhraseType.Standard, walletId);
9926
10159
  const v1EncryptedPrivateKey = await this.localStorageService.getEncryptedPrivateKey();
9927
10160
  if (v1EncryptedSeed && v1EncryptedPrivateKey) {
9928
- // Get public key before decryption for logging
9929
10161
  decryptedPrivateKey = await this.localStorageService.getDecryptedV1PrivateKey(password);
9930
- const v1PublicKey = decryptedPrivateKey ? publicKeyByPrivateKey(decryptedPrivateKey) : 'unknown';
10162
+ // Validate the decrypted private key before proceeding with migration
10163
+ if (decryptedPrivateKey)
10164
+ this.assertValidDeviceKey(decryptedPrivateKey);
9931
10165
  logger.info('SDK::WalletService::handleUpdateToV2::Found V1 storage items, attempting migration', {
9932
10166
  storageFormat: 'v1',
9933
- devicePublicKey: v1PublicKey.substring(0, 16) + '...',
10167
+ validPrivateKey: !!decryptedPrivateKey,
9934
10168
  });
9935
10169
  try {
9936
10170
  // Decrypt V1 items using storage service method (handles double encryption)
@@ -10165,7 +10399,28 @@ class WalletService extends Base {
10165
10399
  * @returns { boolean } whether the operation was successful
10166
10400
  */
10167
10401
  async convertToPasskey(input) {
10402
+ let passkeyRegistered = false;
10168
10403
  try {
10404
+ // Recover an interrupted conversion BEFORE reading any credential blob. A prior attempt may have
10405
+ // already rewrapped EncryptedDevicePrivateKey to passkey form (addNewPasskey persists it outside
10406
+ // this method's atomic commit), which the password can no longer decrypt — and deriving the passkey
10407
+ // key to decrypt it needs the device key itself (circular). The marker stashes the original
10408
+ // password-encrypted device key; restore it so the rest of the flow runs as a fresh conversion.
10409
+ const rawConversionMarker = (await this.localStorageService.fetch(V2KeyNames.CredentialConversionInProgress));
10410
+ const existingConversionMarker = rawConversionMarker
10411
+ ? safeJsonParse(rawConversionMarker)
10412
+ : undefined;
10413
+ // Restore the stashed device key whenever a marker carries one — independent of walletId. The
10414
+ // device key is per-user (not wallet-scoped), so a conversion interrupted on a different wallet
10415
+ // leaves the shared device key passkey-wrapped too. Restoring is idempotent (rewrites the
10416
+ // original password-encrypted blob) and stops a second wallet's conversion from destroying the
10417
+ // first's recovery state. v2 only — a v1 wallet's untouched v1 key still decrypts.
10418
+ if (existingConversionMarker === null || existingConversionMarker === void 0 ? void 0 : existingConversionMarker.encryptedDevicePrivateKey) {
10419
+ await this.localStorageService.save(LocalStorageItems.EncryptedDevicePrivateKey, existingConversionMarker.encryptedDevicePrivateKey);
10420
+ }
10421
+ if ((existingConversionMarker === null || existingConversionMarker === void 0 ? void 0 : existingConversionMarker.walletId) === input.walletId) {
10422
+ logger.info('SDK::WalletService::convertToPasskey::resuming interrupted conversion');
10423
+ }
10169
10424
  const v2EncryptedPriv = await this.localStorageService.fetch(LocalStorageItems.EncryptedDevicePrivateKey);
10170
10425
  const v2EncryptedSeed = await this.localStorageService.fetch(LocalStorageItems.EncryptedStandardSeedPhrase, {
10171
10426
  walletId: input.walletId,
@@ -10214,6 +10469,10 @@ class WalletService extends Base {
10214
10469
  });
10215
10470
  }
10216
10471
  const clientPublicKey = publicKeyByPrivateKey(decryptedClientAuthPrivKey);
10472
+ // Write-ahead marker: set before the unrevocable passkey registration so an interrupted
10473
+ // conversion can be resumed on the next attempt. Stash the original password-encrypted device
10474
+ // key so resume survives addNewPasskey rewrapping the stored device key to passkey form.
10475
+ await this.localStorageService.save(V2KeyNames.CredentialConversionInProgress, Object.assign({ walletId: input.walletId }, (v2EncryptedPriv ? { encryptedDevicePrivateKey: v2EncryptedPriv } : {})));
10217
10476
  const authentication = await this.passkeyService.addNewPasskey({
10218
10477
  deviceKeyPair: {
10219
10478
  publicKey: clientPublicKey,
@@ -10221,6 +10480,7 @@ class WalletService extends Base {
10221
10480
  },
10222
10481
  getSignature: this.authService.getSignature.bind(this),
10223
10482
  });
10483
+ passkeyRegistered = true;
10224
10484
  const prfValue = authentication.prfValue;
10225
10485
  if (!prfValue || !(prfValue instanceof Uint8Array) || prfValue.length === 0) {
10226
10486
  logger.error('SDK::WalletService::convertToPasskey::prfValue is required and must be a non-empty Uint8Array');
@@ -10317,8 +10577,13 @@ class WalletService extends Base {
10317
10577
  storeOneKeyShareWithWallaby: true,
10318
10578
  },
10319
10579
  });
10320
- // Delete the old password-encrypted seed phrase since import stored the new passkey-encrypted version
10321
- await this.localStorageService.delete(LocalStorageItems.EncryptedStandardSeedPhrase, { walletId: input.walletId });
10580
+ // idempotent — on retry (marker present, primary now passkey-encrypted so
10581
+ // decryptedPrimaryShare is undefined → Branch A re-enters), handleImportWallet re-shares
10582
+ // safely; this atomic delete clears the stale seed + marker together.
10583
+ await this.localStorageService.commitBatch([], [
10584
+ { key: LocalStorageItems.EncryptedStandardSeedPhrase, walletId: input.walletId },
10585
+ { key: V2KeyNames.CredentialConversionInProgress },
10586
+ ]);
10322
10587
  logger.info('SDK::WalletService::convertToPasskey::Wallet imported and converted successfully, old seed phrase removed');
10323
10588
  return { authentication, seedPhrase: decryptedSeedPhrase };
10324
10589
  }
@@ -10336,6 +10601,24 @@ class WalletService extends Base {
10336
10601
  privateKey: decryptedClientAuthPrivKey,
10337
10602
  },
10338
10603
  });
10604
+ // assertRoundTrip below only strips the outer (passkey) layer — validate the inner (device key) layer here.
10605
+ const outerDecrypted = await this.cipher.decrypt({
10606
+ cipherText: encryptedPrimaryShare,
10607
+ decryptionKey: passkeyDerivedKeyPair.privateKey,
10608
+ });
10609
+ const innerDecrypted = outerDecrypted
10610
+ ? await this.cipher.decrypt({
10611
+ cipherText: safeJsonParse(outerDecrypted),
10612
+ decryptionKey: decryptedClientAuthPrivKey,
10613
+ })
10614
+ : null;
10615
+ if (innerDecrypted !== decryptedPrimaryShare) {
10616
+ throw new WallabyError({
10617
+ message: 'Re-wrap validation failed for primary share: inner layer round-trip mismatch. Aborting to prevent credential corruption.',
10618
+ statusCode: 500,
10619
+ errorCode: ErrorResponseCodes.sdk_unknown_error,
10620
+ });
10621
+ }
10339
10622
  convertedShares.push({
10340
10623
  key: V2KeyNames.PrimaryDeviceKeyShare,
10341
10624
  value: encryptedPrimaryShare,
@@ -10354,9 +10637,16 @@ class WalletService extends Base {
10354
10637
  walletId: input.walletId,
10355
10638
  });
10356
10639
  }
10357
- await this.localStorageService.saveInBulk(convertedShares);
10640
+ // Round-trip validate each re-encrypted blob (outer layer only) before writing.
10641
+ // A failed decrypt here means re-encryption produced an unreadable blob — abort before overwriting live credentials.
10642
+ for (const share of convertedShares) {
10643
+ await this.assertRoundTrip(share.value, passkeyDerivedKeyPair.privateKey, share.key);
10644
+ }
10645
+ await this.localStorageService.commitBatch(convertedShares, [
10646
+ ...(v2EncryptedSeed ? [{ key: LocalStorageItems.EncryptedStandardSeedPhrase, walletId: input.walletId }] : []),
10647
+ { key: V2KeyNames.CredentialConversionInProgress },
10648
+ ]);
10358
10649
  if (v2EncryptedSeed) {
10359
- await this.localStorageService.delete(LocalStorageItems.EncryptedStandardSeedPhrase, { walletId: input.walletId });
10360
10650
  logger.info('SDK::WalletService::convertToPasskey::Seed phrase removed from device storage after conversion to passkey');
10361
10651
  }
10362
10652
  if (!decryptedSeedPhrase && decryptedPrimaryShare) {
@@ -10399,11 +10689,30 @@ class WalletService extends Base {
10399
10689
  }
10400
10690
  catch (error) {
10401
10691
  logger.error('SDK::WalletService::convertToPasskey::error', error);
10692
+ // Only clear the marker if the passkey was not yet registered. After registration the
10693
+ // marker must survive for roll-forward on the next attempt.
10694
+ if (!passkeyRegistered) {
10695
+ await this.localStorageService.delete(V2KeyNames.CredentialConversionInProgress);
10696
+ }
10402
10697
  throw error;
10403
10698
  }
10404
10699
  }
10700
+ // shared guard — decrypt-tests a re-wrapped blob before any write so a malformed
10701
+ // re-encryption is caught before it overwrites the live credential.
10702
+ async assertRoundTrip(blob, decryptionKey, label) {
10703
+ try {
10704
+ await this.cipher.decrypt({ cipherText: blob, decryptionKey });
10705
+ }
10706
+ catch (_a) {
10707
+ throw new WallabyError({
10708
+ message: `Re-wrap validation failed for ${label}: decryption of the re-encrypted blob failed. Aborting to prevent credential corruption.`,
10709
+ statusCode: 500,
10710
+ errorCode: ErrorResponseCodes.sdk_unknown_error,
10711
+ });
10712
+ }
10713
+ }
10405
10714
  }
10406
- // ponytail: soft client-side guardrail against runaway retries; server-side rate limiting is the real control.
10715
+ // soft client-side guardrail against runaway retries; server-side rate limiting is the real control.
10407
10716
  // Counters are persisted (sliding window) so rebuilding the service no longer resets them. Tune freely.
10408
10717
  WalletService.RATE_LIMIT_MAX = 5;
10409
10718
  WalletService.RATE_LIMIT_WINDOW_MS = 30 * 60000; // 30 min
@@ -10426,7 +10735,7 @@ __decorate([
10426
10735
  __metadata("design:returntype", Promise)
10427
10736
  ], WalletService.prototype, "recover", null);
10428
10737
  __decorate([
10429
- WithLock('changePassword'),
10738
+ WithLock('credential-rewrap'),
10430
10739
  __metadata("design:type", Function),
10431
10740
  __metadata("design:paramtypes", [Object]),
10432
10741
  __metadata("design:returntype", Promise)
@@ -10437,12 +10746,18 @@ __decorate([
10437
10746
  __metadata("design:paramtypes", [Object]),
10438
10747
  __metadata("design:returntype", Promise)
10439
10748
  ], WalletService.prototype, "handleUpdateToV2", null);
10749
+ __decorate([
10750
+ WithLock('credential-rewrap'),
10751
+ __metadata("design:type", Function),
10752
+ __metadata("design:paramtypes", [Object]),
10753
+ __metadata("design:returntype", Promise)
10754
+ ], WalletService.prototype, "convertToPasskey", null);
10440
10755
 
10441
10756
  class WalletDataService extends Base {
10442
- constructor(config, ports = {}) {
10443
- super(config, ports);
10757
+ constructor(config) {
10758
+ super(config);
10444
10759
  this.userId = config.userId;
10445
- this.walletService = new WalletService(config, ports);
10760
+ this.walletService = new WalletService(config);
10446
10761
  }
10447
10762
  /**
10448
10763
  * @description Validates the wallet address info for a given blockchain.
@@ -10763,8 +11078,8 @@ class WalletDataService extends Base {
10763
11078
  }
10764
11079
 
10765
11080
  class Utils extends Base {
10766
- constructor(config, ports = {}) {
10767
- super(config, ports);
11081
+ constructor(config) {
11082
+ super(config);
10768
11083
  /**
10769
11084
  *
10770
11085
  * Decrypts user private key
@@ -10797,7 +11112,7 @@ class Utils extends Base {
10797
11112
  return undefined;
10798
11113
  }
10799
11114
  };
10800
- this.auth = new AuthService(config, ports);
11115
+ this.auth = new AuthService(config);
10801
11116
  }
10802
11117
  /**
10803
11118
  *
@@ -10904,16 +11219,16 @@ class HttpApi extends Base {
10904
11219
  * @param config - The Wallaby configuration object
10905
11220
  * @public
10906
11221
  */
10907
- constructor(config, ports = {}) {
10908
- super(config, ports);
11222
+ constructor(config) {
11223
+ super(config);
10909
11224
  }
10910
11225
  }
10911
11226
 
10912
11227
  class Swap extends Base {
10913
- constructor(config, ports = {}) {
10914
- super(config, ports);
10915
- this.authService = new AuthService(config, ports);
10916
- this.walletService = new WalletService(config, ports);
11228
+ constructor(config) {
11229
+ super(config);
11230
+ this.authService = new AuthService(config);
11231
+ this.walletService = new WalletService(config);
10917
11232
  }
10918
11233
  /**
10919
11234
  * Gets a swap quote between two assets, including fees, min output, and slippage limits.
@@ -11165,9 +11480,30 @@ const sanitizeSuiObjectId = (objectId) => {
11165
11480
  return objectId.split('::')[0];
11166
11481
  };
11167
11482
 
11483
+ /**
11484
+ * Extracts the asset symbol from a fully-qualified Sui coin type.
11485
+ *
11486
+ * A Sui coin type has the shape `<package>::<module>::<TYPE>`, where the final
11487
+ * segment is the coin's struct name and doubles as its symbol.
11488
+ *
11489
+ * @param objectId - The Sui object id / coin type. Example input:
11490
+ * "0xc91acfb75009c5ff2fd57c54f3caaee12ad1fbe997681334adc0b574fc277a07::icorgi::ICORGI"
11491
+ * @returns The symbol (e.g. "ICORGI"), or undefined when the id carries no
11492
+ * `::module::TYPE` suffix to derive it from.
11493
+ */
11494
+ const extractSuiAssetSymbol = (objectId) => {
11495
+ var _a;
11496
+ if (!objectId || !objectId.includes('::')) {
11497
+ return undefined;
11498
+ }
11499
+ const segments = objectId.split('::');
11500
+ const symbol = (_a = segments[segments.length - 1]) === null || _a === void 0 ? void 0 : _a.trim();
11501
+ return symbol || undefined;
11502
+ };
11503
+
11168
11504
  class System extends Base {
11169
- constructor(config, ports = {}) {
11170
- super(config, ports);
11505
+ constructor(config) {
11506
+ super(config);
11171
11507
  }
11172
11508
  /**
11173
11509
  * @public
@@ -11253,6 +11589,9 @@ class System extends Base {
11253
11589
  * @param {BlockchainName} blockchain - The name of the blockchain.
11254
11590
  * @param {string} contractAddress - The contract address of the token (optional for non-SUI blockchains).
11255
11591
  * @param {string} suiObjectId - The SUI object ID of the token (optional for SUI blockchain).
11592
+ * @param {string} assetSymbol - The asset symbol; disambiguates new SUI assets. For SUI it is
11593
+ * optional: when omitted, it is derived from the `::module::TYPE` suffix of `suiObjectId`
11594
+ * (which is otherwise trimmed off before the request is sent).
11256
11595
  *
11257
11596
  * @returns {Promise<{ decimals: number; symbol: string; name: string; tokenContractAddress: string }>} A promise that resolves to an object containing token information.
11258
11597
  *
@@ -11261,18 +11600,19 @@ class System extends Base {
11261
11600
  * @throws Will throw an error if `contractAddress` is not provided for non-SUI blockchains.
11262
11601
  * @throws Will throw an error if the response is invalid or contains an error.
11263
11602
  */
11264
- async fetchTokenInfo({ blockchain, contractAddress, suiObjectId, }) {
11603
+ async fetchTokenInfo({ blockchain, contractAddress, suiObjectId, assetSymbol, }) {
11265
11604
  try {
11266
11605
  const validatedContractAddress = this.validateContractAddress({
11267
11606
  blockchain,
11268
11607
  contractAddress,
11269
11608
  suiObjectId,
11270
11609
  });
11610
+ // For SUI, the coin symbol is the last segment of the coin type
11611
+ // (`<package>::<module>::<TYPE>`), which sanitizeSuiObjectId strips out.
11612
+ // Derive it so callers don't have to pass assetSymbol explicitly.
11613
+ const resolvedAssetSymbol = assetSymbol !== null && assetSymbol !== void 0 ? assetSymbol : (blockchain === BlockchainName.Sui ? extractSuiAssetSymbol(suiObjectId) : undefined);
11271
11614
  const response = await this.request(SystemRoutes.fetchTokenInfo, {
11272
- queryParams: {
11273
- chainName: blockchain,
11274
- tokenContractAddress: validatedContractAddress,
11275
- },
11615
+ queryParams: Object.assign({ chainName: blockchain, tokenContractAddress: validatedContractAddress }, (resolvedAssetSymbol ? { assetSymbol: resolvedAssetSymbol } : {})),
11276
11616
  });
11277
11617
  return response;
11278
11618
  }
@@ -11360,10 +11700,10 @@ class System extends Base {
11360
11700
  }
11361
11701
 
11362
11702
  class Transactions extends Base {
11363
- constructor(config, ports = {}) {
11364
- super(config, ports);
11365
- this.authService = new AuthService(config, ports);
11366
- this.walletService = new WalletService(config, ports);
11703
+ constructor(config) {
11704
+ super(config);
11705
+ this.authService = new AuthService(config);
11706
+ this.walletService = new WalletService(config);
11367
11707
  this.userId = config.userId;
11368
11708
  }
11369
11709
  /**
@@ -11804,15 +12144,15 @@ class Wallaby {
11804
12144
  * @param {string} [config.clientAuthToken] - A web token generated by the client for authorization.
11805
12145
  * @public
11806
12146
  */
11807
- constructor(config, ports = {}) {
11808
- this.wallet = new WalletService(config, ports);
11809
- this.walletData = new WalletDataService(config, ports);
11810
- this.utils = new Utils(config, ports);
11811
- this.auth = new AuthService(config, ports);
11812
- this.system = new System(config, ports);
11813
- this.transactions = new Transactions(config, ports);
11814
- this.swap = new Swap(config, ports);
11815
- this.httpApi = new HttpApi(config, ports);
12147
+ constructor(config) {
12148
+ this.wallet = new WalletService(config);
12149
+ this.walletData = new WalletDataService(config);
12150
+ this.utils = new Utils(config);
12151
+ this.auth = new AuthService(config);
12152
+ this.system = new System(config);
12153
+ this.transactions = new Transactions(config);
12154
+ this.swap = new Swap(config);
12155
+ this.httpApi = new HttpApi(config);
11816
12156
  }
11817
12157
  get version() {
11818
12158
  return currentPackageVersion;