wallaby-cash 3.4.0 → 3.5.1

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/base.d.ts CHANGED
@@ -13,6 +13,7 @@ export declare abstract class Base {
13
13
  protected options?: WallabyConfigOptions;
14
14
  protected lockManager: LockManagerService;
15
15
  protected cipher: Cipher;
16
+ private _localStorageService?;
16
17
  protected api: GeneratedApiClient<any>;
17
18
  constructor(config: WallabyConfig);
18
19
  set setClientAuthToken(token: string);
package/dist/index.cjs.js CHANGED
@@ -627,7 +627,7 @@ const env = {
627
627
  isNative: !isWeb,
628
628
  isWeb,
629
629
  };
630
- const currentPackageVersion = "3.4.0" ;
630
+ const currentPackageVersion = "3.5.1" ;
631
631
 
632
632
  /**
633
633
  * Storage keys adapter for Storage interface across different platforms.
@@ -4421,24 +4421,166 @@ function pbkdf2Sync(password, salt, iterations, keylen, digest) {
4421
4421
  });
4422
4422
  }
4423
4423
 
4424
+ /**
4425
+ * Pure crypto core (WAL-1469). Module-level functions with no logging, no storage,
4426
+ * no network, and no hidden state: every input (including key material) is a parameter.
4427
+ *
4428
+ * The formats produced/consumed here are pinned by the known-answer tests in
4429
+ * src/tests/kat/ — real user data encrypted in the field depends on them, so any
4430
+ * change to these functions must keep those tests green, and any format change
4431
+ * needs an explicit versioned migration.
4432
+ */
4424
4433
  // Version marker prepended to values wrapped by the master key, so wrapped vs raw is deterministic.
4425
4434
  const MASTER_KEY_WRAP_PREFIX = 'wsdkmk:v1:';
4426
4435
  // crypto-js AES.encrypt with a string passphrase emits an OpenSSL "Salted__" header; its base64 always
4427
4436
  // starts with this. Used to recognize legacy wrapped values stored before MASTER_KEY_WRAP_PREFIX existed.
4428
4437
  const LEGACY_CRYPTOJS_PREFIX = 'U2FsdGVkX1';
4438
+ // `satisfies keyof` ties these literal lists to the generated DTOs, so a field
4439
+ // rename/removal there fails the build here instead of silently going stale.
4440
+ const ENCRYPTED_PAYLOAD_FIELDS = [
4441
+ 'iv',
4442
+ 'ephemPublicKey',
4443
+ 'ciphertext',
4444
+ 'mac',
4445
+ ];
4446
+ // v is a version number for the symmetric encryption format, so it is not a string field.
4447
+ const SYMMETRIC_PAYLOAD_FIELDS = ['iv', 'ciphertext', 'tag'];
4448
+ // API is the trust boundary: confirm every named field is a non-empty string.
4449
+ function hasNonEmptyStringFields(payload, fields) {
4450
+ return (!!payload &&
4451
+ typeof payload === 'object' &&
4452
+ fields.every((field) => {
4453
+ const value = payload[field];
4454
+ return typeof value === 'string' && value.length > 0;
4455
+ }));
4456
+ }
4457
+ /**
4458
+ * True when the payload matches the ECIES envelope { iv, ephemPublicKey, ciphertext, mac }.
4459
+ */
4460
+ function isEciesPayload(payload) {
4461
+ return hasNonEmptyStringFields(payload, ENCRYPTED_PAYLOAD_FIELDS);
4462
+ }
4463
+ /**
4464
+ * True when the payload matches the symmetric envelope { v, iv, ciphertext, tag } with numeric v.
4465
+ */
4466
+ function isSymmetricPayload(payload) {
4467
+ return (hasNonEmptyStringFields(payload, SYMMETRIC_PAYLOAD_FIELDS) &&
4468
+ typeof payload.v === 'number');
4469
+ }
4470
+ /**
4471
+ * Validate that a private key is the correct length and not weak.
4472
+ */
4473
+ function validatePrivateKey(privateKey) {
4474
+ if (!/^0x[0-9a-fA-F]{64}$/.test(privateKey)) {
4475
+ throw new Error('Invalid private key: must be a 32-byte hex string');
4476
+ }
4477
+ // A valid key is a scalar in [1, n-1] that projects onto the secp256k1 curve.
4478
+ // isValidPrivateKey does that range check (and is what getPublicKey runs under the hood).
4479
+ if (!secp256k1.utils.isValidPrivateKey(privateKey.slice(2))) {
4480
+ throw new Error('Invalid private key: outside secp256k1 scalar range');
4481
+ }
4482
+ }
4483
+ /**
4484
+ * Validate that a public key is the correct length and format.
4485
+ */
4486
+ function validatePublicKey(publicKey) {
4487
+ if (!/^[0-9a-fA-F]{128}$/.test(publicKey)) {
4488
+ throw new Error('Invalid public key: must be a 64-byte raw uncompressed hex string');
4489
+ }
4490
+ const uniqueChars = new Set(publicKey);
4491
+ if (uniqueChars.size <= 8) {
4492
+ throw new Error('Weak public key: too few unique characters');
4493
+ }
4494
+ }
4495
+ /**
4496
+ * Validate that a salt is sufficiently long and not weak.
4497
+ */
4498
+ function validateSalt(salt) {
4499
+ if (utf8ToBytes$1(salt).length < 16) {
4500
+ throw new Error('Salt is too short: must be at least 16 bytes');
4501
+ }
4502
+ const uniqueChars = new Set(salt);
4503
+ if (uniqueChars.size <= 6) {
4504
+ throw new Error('Weak salt: too few unique characters');
4505
+ }
4506
+ }
4507
+ /**
4508
+ * Accept an Encrypted payload either as the object or its JSON.stringify'd storage form.
4509
+ */
4510
+ function parseEncrypted(value) {
4511
+ return typeof value === 'string' ? JSON.parse(value) : value;
4512
+ }
4513
+ /**
4514
+ * Derives a key pair from a password and salt: NFKC-normalize + trim, then
4515
+ * PBKDF2-SHA256 (PBKDF2_ITERATIONS) into a createIdentity keypair.
4516
+ */
4517
+ function deriveKeyPairFromPassword({ password, salt }) {
4518
+ validateSalt(salt);
4519
+ // Compatibility Composition
4520
+ // Prevents different Unicode representations of "same" password
4521
+ // Also trim whitespace for security consistency
4522
+ const normalizedPassword = password.normalize('NFKC').trim();
4523
+ const encryptionKey = pbkdf2Sync(utf8ToBytes$1(normalizedPassword), utf8ToBytes$1(salt), PBKDF2_ITERATIONS, DEFAULT_ENTROPY_BYTES$1, 'sha256');
4524
+ return createIdentity(encryptionKey);
4525
+ }
4526
+ /**
4527
+ * Derives a key pair from passkey PRF input key material.
4528
+ */
4529
+ function deriveKeyPairFromPasskey({ inputKeyMaterial }) {
4530
+ return createIdentity(inputKeyMaterial);
4531
+ }
4532
+ /**
4533
+ * crypto-js AES with a string passphrase (OpenSSL salted format). This is the legacy
4534
+ * V1 storage cipher and the primitive under the master-key wrap; kept only for
4535
+ * backward compatibility with data already encrypted in the field.
4536
+ */
4537
+ function legacyAesEncrypt(data, passphrase) {
4538
+ return cryptoJs.AES.encrypt(data, passphrase).toString();
4539
+ }
4540
+ function legacyAesDecrypt(cipherText, passphrase) {
4541
+ return cryptoJs.AES.decrypt(cipherText, passphrase).toString(cryptoJs.enc.Utf8);
4542
+ }
4543
+ /**
4544
+ * Wraps a value with the master key, prefixed with the format version marker.
4545
+ */
4546
+ function wrapWithMasterKey(data, masterKey) {
4547
+ return MASTER_KEY_WRAP_PREFIX + legacyAesEncrypt(typeof data === 'string' ? data : JSON.stringify(data), masterKey);
4548
+ }
4549
+ /**
4550
+ * Determines deterministically whether a stored value was wrapped by the master key,
4551
+ * without inferring from decrypt behavior. Returns true for values carrying the version
4552
+ * marker, or legacy crypto-js ciphertext stored before the marker existed.
4553
+ */
4554
+ function isMasterKeyWrapped(value) {
4555
+ return value.startsWith(MASTER_KEY_WRAP_PREFIX) || value.startsWith(LEGACY_CRYPTOJS_PREFIX);
4556
+ }
4557
+ /**
4558
+ * Unwraps a master-key-wrapped value (current prefixed format or legacy unprefixed blob).
4559
+ * Returns the parsed object for JSON payloads, the raw string otherwise, and undefined
4560
+ * when the ciphertext decrypts to nothing. Throws on malformed ciphertext (crypto-js
4561
+ * "Malformed UTF-8 data") — callers translate/log.
4562
+ */
4563
+ function unwrapWithMasterKey(cipherText, masterKey) {
4564
+ const ciphertext = cipherText.startsWith(MASTER_KEY_WRAP_PREFIX) ? cipherText.slice(MASTER_KEY_WRAP_PREFIX.length) : cipherText;
4565
+ const decrypted = legacyAesDecrypt(ciphertext, masterKey);
4566
+ if (decrypted) {
4567
+ return isJsonString(decrypted) ? safeJsonParse(decrypted) : decrypted;
4568
+ }
4569
+ return undefined;
4570
+ }
4571
+
4572
+ /**
4573
+ * Impure shell over the pure crypto core (./cipher-core). This class only adds
4574
+ * logging, user-facing error translation, and the master-key constant; all crypto
4575
+ * and format logic lives in cipher-core and is pinned by the KATs in src/tests/kat/.
4576
+ */
4429
4577
  class Cipher {
4430
4578
  constructor() { }
4431
4579
  /**
4432
4580
  * Validate that a private key is the correct length and not weak.
4433
4581
  */
4434
4582
  validatePrivateKey(privateKey) {
4435
- if (!/^0x[0-9a-fA-F]{64}$/.test(privateKey)) {
4436
- throw new Error('Invalid private key: must be a 32-byte hex string');
4437
- }
4438
- const uniqueChars = new Set(privateKey.slice(2)); // Remove '0x' prefix
4439
- if (uniqueChars.size <= 8) {
4440
- throw new Error('Weak private key: too few unique characters');
4441
- }
4583
+ validatePrivateKey(privateKey);
4442
4584
  }
4443
4585
  /**
4444
4586
  * @description For an additional layer of security, this function returns a master key from a constant MASTER_ENCRYPTION_KEY.
@@ -4456,8 +4598,7 @@ class Cipher {
4456
4598
  * @returns The encrypted data as a string.
4457
4599
  */
4458
4600
  encryptWithMasterKey({ data }) {
4459
- const ciphertext = cryptoJs.AES.encrypt(typeof data === 'string' ? data : JSON.stringify(data), this.getMasterKey().key).toString();
4460
- return MASTER_KEY_WRAP_PREFIX + ciphertext;
4601
+ return wrapWithMasterKey(data, this.getMasterKey().key);
4461
4602
  }
4462
4603
  /**
4463
4604
  * @description Determines deterministically whether a stored value was wrapped by the master key,
@@ -4465,16 +4606,13 @@ class Cipher {
4465
4606
  * legacy crypto-js ciphertext stored before the marker existed. Everything else is treated as raw.
4466
4607
  */
4467
4608
  isWrappedByMasterKey(value) {
4468
- return value.startsWith(MASTER_KEY_WRAP_PREFIX) || value.startsWith(LEGACY_CRYPTOJS_PREFIX);
4609
+ return isMasterKeyWrapped(value);
4469
4610
  }
4470
4611
  decryptWithMasterKey({ cipherText }) {
4471
- const ciphertext = cipherText.startsWith(MASTER_KEY_WRAP_PREFIX)
4472
- ? cipherText.slice(MASTER_KEY_WRAP_PREFIX.length)
4473
- : cipherText;
4474
4612
  try {
4475
- const decrypted = cryptoJs.AES.decrypt(ciphertext, this.getMasterKey().key).toString(cryptoJs.enc.Utf8);
4476
- if (decrypted) {
4477
- return isJsonString(decrypted) ? safeJsonParse(decrypted) : decrypted;
4613
+ const decrypted = unwrapWithMasterKey(cipherText, this.getMasterKey().key);
4614
+ if (decrypted !== undefined) {
4615
+ return decrypted;
4478
4616
  }
4479
4617
  }
4480
4618
  catch (error) {
@@ -4489,25 +4627,13 @@ class Cipher {
4489
4627
  * Validate that a public key is the correct length and format.
4490
4628
  */
4491
4629
  validatePublicKey(publicKey) {
4492
- if (!/^[0-9a-fA-F]{128}$/.test(publicKey)) {
4493
- throw new Error('Invalid public key: must be a 64-byte raw uncompressed hex string');
4494
- }
4495
- const uniqueChars = new Set(publicKey);
4496
- if (uniqueChars.size <= 8) {
4497
- throw new Error('Weak public key: too few unique characters');
4498
- }
4630
+ validatePublicKey(publicKey);
4499
4631
  }
4500
4632
  /**
4501
4633
  * Validate that a salt is sufficiently long and not weak.
4502
4634
  */
4503
4635
  validateSalt(salt) {
4504
- if (utf8ToBytes$1(salt).length < 16) {
4505
- throw new Error('Salt is too short: must be at least 16 bytes');
4506
- }
4507
- const uniqueChars = new Set(salt);
4508
- if (uniqueChars.size <= 6) {
4509
- throw new Error('Weak salt: too few unique characters');
4510
- }
4636
+ validateSalt(salt);
4511
4637
  }
4512
4638
  /**
4513
4639
  * @description Signs a message using the provided private key.
@@ -4554,10 +4680,7 @@ class Cipher {
4554
4680
  async decrypt({ cipherText, decryptionKey }) {
4555
4681
  try {
4556
4682
  this.validatePrivateKey(decryptionKey);
4557
- if (typeof cipherText === 'string') {
4558
- cipherText = JSON.parse(cipherText);
4559
- }
4560
- const decrypted = await decryptWithPrivateKey(decryptionKey, cipherText);
4683
+ const decrypted = await decryptWithPrivateKey(decryptionKey, parseEncrypted(cipherText));
4561
4684
  return decrypted;
4562
4685
  }
4563
4686
  catch (error) {
@@ -4792,8 +4915,7 @@ class Cipher {
4792
4915
  * @returns {Promise<{ privateKey: string; publicKey: string }>} The derived key pair.
4793
4916
  */
4794
4917
  async deriveKeyPairFromPasskey({ inputKeyMaterial }) {
4795
- const identityFromInputKey = createIdentity(inputKeyMaterial);
4796
- return identityFromInputKey;
4918
+ return deriveKeyPairFromPasskey({ inputKeyMaterial });
4797
4919
  }
4798
4920
  /**
4799
4921
  * @description Derives a key pair from the provided password and salt.
@@ -4802,14 +4924,7 @@ class Cipher {
4802
4924
  * @returns {Promise<{ privateKey: string; publicKey: string }>} The derived key pair.
4803
4925
  */
4804
4926
  async deriveKeyPairFromPassword({ password, salt }) {
4805
- this.validateSalt(salt);
4806
- // Compatibility Composition
4807
- // Prevents different Unicode representations of "same" password
4808
- // Also trim whitespace for security consistency
4809
- const normalizedPassword = password.normalize('NFKC').trim();
4810
- const encryptionKey = pbkdf2Sync(utf8ToBytes$1(normalizedPassword), utf8ToBytes$1(salt), PBKDF2_ITERATIONS, DEFAULT_ENTROPY_BYTES$1, 'sha256');
4811
- const encryptionKeyPair = createIdentity(encryptionKey);
4812
- return encryptionKeyPair;
4927
+ return deriveKeyPairFromPassword({ password, salt });
4813
4928
  }
4814
4929
  }
4815
4930
 
@@ -5422,7 +5537,23 @@ class LockManagerService {
5422
5537
  * @returns Promise that resolves with the operation result
5423
5538
  */
5424
5539
  async withLock(key, operation) {
5425
- // Check if this operation is already locked
5540
+ // On web, use the Web Locks API so the lock serializes across browser tabs too.
5541
+ // `ifAvailable: true` preserves the throw-fast contract: a held lock yields a null
5542
+ // lock instead of waiting, so we surface the same "already in progress" error.
5543
+ // Gate on a real browser (window+document) rather than navigator.locks alone:
5544
+ // modern Node ships a process-global navigator.locks, which would defeat the
5545
+ // in-process semantics the native/Node fallback (and existing tests) rely on.
5546
+ const isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined';
5547
+ const locks = isBrowser && typeof navigator !== 'undefined' ? navigator.locks : undefined;
5548
+ if (locks) {
5549
+ return locks.request(key, { ifAvailable: true }, async (lock) => {
5550
+ if (!lock) {
5551
+ throw new Error(`Operation '${key}' is already in progress. Please wait for it to complete.`);
5552
+ }
5553
+ return operation();
5554
+ });
5555
+ }
5556
+ // in-process Set fallback for native/Node (no tabs, single JS context => sufficient).
5426
5557
  if (this.activeLocks.has(key)) {
5427
5558
  throw new Error(`Operation '${key}' is already in progress. Please wait for it to complete.`);
5428
5559
  }
@@ -5430,8 +5561,7 @@ class LockManagerService {
5430
5561
  this.activeLocks.add(key);
5431
5562
  try {
5432
5563
  // Execute the operation
5433
- const result = await operation();
5434
- return result;
5564
+ return await operation();
5435
5565
  }
5436
5566
  finally {
5437
5567
  // Always release the lock
@@ -7007,6 +7137,9 @@ function shouldClearTokensAfterRefreshFailure(error) {
7007
7137
 
7008
7138
  // Module-level dedupe manager for token refresh to ensure only one refresh request per user/environment/network at a time
7009
7139
  const refreshDedupeManager = new DedupeManagerService();
7140
+ // one origin-wide lock manager shared by every service instance, so WalletService/AuthService/etc.
7141
+ // actually contend. Global lock keys (no per-user scoping); add scoping only if multiple users share one process.
7142
+ const sharedLockManager = new LockManagerService();
7010
7143
  class Base {
7011
7144
  constructor(config) {
7012
7145
  var _a, _b;
@@ -7021,7 +7154,7 @@ class Base {
7021
7154
  env.isWeb = !env.isNative;
7022
7155
  }
7023
7156
  this.cipher = new Cipher();
7024
- this.lockManager = new LockManagerService();
7157
+ this.lockManager = sharedLockManager;
7025
7158
  this._initializeClientAuthToken(sanitizedConfig.clientAuthToken);
7026
7159
  this.request = this.request.bind(this);
7027
7160
  // The generated API client includes /api/v1 in each path, so strip it from
@@ -7143,6 +7276,7 @@ class Base {
7143
7276
  * @protected
7144
7277
  */
7145
7278
  get localStorageService() {
7279
+ var _a;
7146
7280
  if (!this.clientAuthToken) {
7147
7281
  throw new WallabyError({
7148
7282
  message: 'A client authentication token (JWT) is required',
@@ -7150,11 +7284,13 @@ class Base {
7150
7284
  errorCode: exports.ErrorResponseCodes.sdk_missing_parameter,
7151
7285
  });
7152
7286
  }
7153
- return new StorageService({
7287
+ // Cached: StorageService depends only on deviceStorage/userId/environment, all stable
7288
+ // after construction. Recreating it per access reset the WAL `_walRecovered` flag.
7289
+ return ((_a = this._localStorageService) !== null && _a !== void 0 ? _a : (this._localStorageService = new StorageService({
7154
7290
  deviceStorage: this.deviceLocalStorage,
7155
7291
  userId: this.userId,
7156
7292
  environment: this.settings.environment,
7157
- });
7293
+ })));
7158
7294
  }
7159
7295
  /**
7160
7296
  * Fetches a new access/refresh token pair using the stored refresh token.
@@ -8209,8 +8345,16 @@ function WithLock(lockKey) {
8209
8345
  }
8210
8346
  const originalMethod = descriptor.value;
8211
8347
  descriptor.value = async function (...args) {
8348
+ var _a, _b, _c, _d, _e;
8212
8349
  const lockManager = this.lockManager;
8213
- const key = lockKey || `${target.constructor.name}:${propertyKey}`;
8350
+ const operation = lockKey || `${target.constructor.name}:${propertyKey}`;
8351
+ // Scope the lock key by user/environment/network so a process-wide shared
8352
+ // LockManagerService doesn't make two instances for different users (or the
8353
+ // same user on a different env/network, with distinct storage namespaces)
8354
+ // spuriously block each other with "already in progress".
8355
+ const environment = (_b = (_a = this.options) === null || _a === void 0 ? void 0 : _a.environment) !== null && _b !== void 0 ? _b : defaultEnvironment;
8356
+ const network = (_d = (_c = this.options) === null || _c === void 0 ? void 0 : _c.network) !== null && _d !== void 0 ? _d : defaultNetwork;
8357
+ const key = `${(_e = this.userId) !== null && _e !== void 0 ? _e : 'anon'}:${environment}:${network}:${operation}`;
8214
8358
  return lockManager.withLock(key, () => originalMethod.apply(this, args));
8215
8359
  };
8216
8360
  return descriptor;
@@ -8750,25 +8894,13 @@ __decorate([
8750
8894
  __metadata("design:returntype", Promise)
8751
8895
  ], AuthService.prototype, "storeDeviceKeyPair", null);
8752
8896
 
8753
- const ENCRYPTED_PAYLOAD_FIELDS = ['iv', 'ephemPublicKey', 'ciphertext', 'mac'];
8754
- // Backup share may be ECIES or symmetric ({ iv, ciphertext, mac, tag }) — both share these three fields.
8755
- const SYMMETRIC_PAYLOAD_FIELDS = ['iv', 'ciphertext', 'mac', 'tag'];
8756
- // API is the trust boundary: confirm every named field is a non-empty string.
8757
- function hasNonEmptyStringFields(payload, fields) {
8758
- return (!!payload &&
8759
- typeof payload === 'object' &&
8760
- fields.every((field) => {
8761
- const value = payload[field];
8762
- return typeof value === 'string' && value.length > 0;
8763
- }));
8764
- }
8765
8897
  /**
8766
8898
  * Fail fast if an encrypted payload from the API does not match the expected
8767
8899
  * ECIES structure ({ iv, ephemPublicKey, ciphertext, mac }). See the contract
8768
8900
  * note on `handleKeySharesFromResponse`.
8769
8901
  */
8770
8902
  function assertEncryptedPayloadShape(encrypted) {
8771
- if (!hasNonEmptyStringFields(encrypted, ENCRYPTED_PAYLOAD_FIELDS)) {
8903
+ if (!isEciesPayload(encrypted)) {
8772
8904
  throw new WallabyError({
8773
8905
  message: 'Encrypted share does not match the expected { iv, ephemPublicKey, ciphertext, mac } format.',
8774
8906
  statusCode: 422,
@@ -8797,11 +8929,9 @@ function assertSharesPayloadShape(shares) {
8797
8929
  * shape-check it. It may be ECIES or symmetric, so accept either variant.
8798
8930
  */
8799
8931
  function assertBackupSharePayloadShape(encrypted) {
8800
- const isEcies = hasNonEmptyStringFields(encrypted, ENCRYPTED_PAYLOAD_FIELDS);
8801
- const isSymmetric = hasNonEmptyStringFields(encrypted, SYMMETRIC_PAYLOAD_FIELDS);
8802
- if (!isEcies && !isSymmetric) {
8932
+ if (!isEciesPayload(encrypted) && !isSymmetricPayload(encrypted)) {
8803
8933
  throw new WallabyError({
8804
- message: 'Encrypted backup share does not match the expected ECIES ({ iv, ephemPublicKey, ciphertext, mac }) or symmetric ({ iv, ciphertext, mac, tag }) format.',
8934
+ message: 'Encrypted backup share does not match the expected ECIES ({ iv, ephemPublicKey, ciphertext, mac }) or symmetric ({ v, iv, ciphertext, tag }) format.',
8805
8935
  statusCode: 422,
8806
8936
  errorCode: exports.ErrorResponseCodes.sdk_invalid_parameter,
8807
8937
  });
@@ -9918,6 +10048,24 @@ class WalletService extends Base {
9918
10048
  });
9919
10049
  }
9920
10050
  }
10051
+ /**
10052
+ * Assert a decrypted private key is valid secp256k1 key material. If it isn't, the stored value is
10053
+ * corrupted (or a wrong password decrypted to non-key garbage) — surface a clear, distinct error
10054
+ * instead of letting the raw validation message escape or collapsing into a misleading "wrong password".
10055
+ */
10056
+ assertValidDeviceKey(privateKey) {
10057
+ try {
10058
+ this.cipher.validatePrivateKey(privateKey);
10059
+ }
10060
+ catch (error) {
10061
+ logger.error('SDK::WalletService::assertValidDeviceKey::decrypted private key is not valid key material', error);
10062
+ throw new WallabyError({
10063
+ message: 'Could not access your device key — your stored wallet credentials appear to be corrupted.',
10064
+ statusCode: 500,
10065
+ errorCode: exports.ErrorResponseCodes.sdk_private_key_decryption_failed,
10066
+ });
10067
+ }
10068
+ }
9921
10069
  /**
9922
10070
  * Detects and migrates legacy/v1 storage items to v2 format.
9923
10071
  * This function should be called in methods that use password as input when v2 items are missing.
@@ -10005,10 +10153,9 @@ class WalletService extends Base {
10005
10153
  // getDecryptedV1PrivateKey checks for both v1 and legacy formats internally
10006
10154
  const legacyDecryptedPrivateKey = await this.localStorageService.getDecryptedV1PrivateKey(password);
10007
10155
  if (legacyEncryptedSeed && legacyDecryptedPrivateKey) {
10008
- const legacyPublicKey = publicKeyByPrivateKey(legacyDecryptedPrivateKey);
10156
+ this.assertValidDeviceKey(legacyDecryptedPrivateKey);
10009
10157
  logger.info('SDK::WalletService::handleUpdateToV2::Found legacy storage items, attempting migration', {
10010
10158
  storageFormat: 'legacy',
10011
- devicePublicKey: legacyPublicKey.substring(0, 16) + '...',
10012
10159
  });
10013
10160
  try {
10014
10161
  // Decrypt legacy items using password/salt combination
@@ -10040,12 +10187,13 @@ class WalletService extends Base {
10040
10187
  const v1EncryptedSeed = await this.localStorageService.getEncryptedSeedPhrase(exports.SeedPhraseType.Standard, walletId);
10041
10188
  const v1EncryptedPrivateKey = await this.localStorageService.getEncryptedPrivateKey();
10042
10189
  if (v1EncryptedSeed && v1EncryptedPrivateKey) {
10043
- // Get public key before decryption for logging
10044
10190
  decryptedPrivateKey = await this.localStorageService.getDecryptedV1PrivateKey(password);
10045
- const v1PublicKey = decryptedPrivateKey ? publicKeyByPrivateKey(decryptedPrivateKey) : 'unknown';
10191
+ // Validate the decrypted private key before proceeding with migration
10192
+ if (decryptedPrivateKey)
10193
+ this.assertValidDeviceKey(decryptedPrivateKey);
10046
10194
  logger.info('SDK::WalletService::handleUpdateToV2::Found V1 storage items, attempting migration', {
10047
10195
  storageFormat: 'v1',
10048
- devicePublicKey: v1PublicKey.substring(0, 16) + '...',
10196
+ validPrivateKey: !!decryptedPrivateKey,
10049
10197
  });
10050
10198
  try {
10051
10199
  // Decrypt V1 items using storage service method (handles double encryption)