wallaby-cash 3.2.1 → 3.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/eth-crypto-utils/createIdentity.d.ts +0 -1
- package/dist/generated/api.d.ts +689 -143
- package/dist/helpers/base64.d.ts +5 -4
- package/dist/index.cjs.js +602 -430
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +1 -8
- package/dist/index.esm.js +602 -430
- package/dist/index.esm.js.map +1 -1
- package/dist/index.js +582 -404
- package/dist/index.js.map +1 -1
- package/dist/lib/auth/auth.service.d.ts +8 -1
- package/dist/lib/index.d.ts +0 -1
- package/dist/lib/system/index.d.ts +5 -1
- package/dist/lib/transactions/index.d.ts +19 -13
- package/dist/lib/utils/cipher.service.d.ts +6 -0
- package/dist/lib/utils/extract-sui-asset-symbol.d.ts +12 -0
- package/dist/lib/utils/storage.service.d.ts +13 -0
- package/dist/lib/wallet/wallet-handlers.service.d.ts +18 -1
- package/dist/lib/wallet/wallet.service.d.ts +20 -2
- package/dist/package.json +8 -5
- package/dist/routes/auth.d.ts +5 -0
- package/dist/routes/transactions.d.ts +15 -0
- package/dist/types/storage.d.ts +5 -1
- package/package.json +8 -5
- package/dist/lib/merchants/index.d.ts +0 -59
- package/dist/routes/merchants.d.ts +0 -48
package/dist/index.js
CHANGED
|
@@ -313,6 +313,10 @@ var V2KeyNames;
|
|
|
313
313
|
V2KeyNames["WallabyAuthPubKey"] = "wallaby-auth-pub-key";
|
|
314
314
|
V2KeyNames["MigrationVersion"] = "wsdk_migrated_with_version";
|
|
315
315
|
V2KeyNames["LastMigratedAt"] = "wsdk_last_migrated_at";
|
|
316
|
+
V2KeyNames["PasswordResetAttempts"] = "wsdk_password_reset_attempts";
|
|
317
|
+
V2KeyNames["MigrationAttempts"] = "wsdk_migration_attempts";
|
|
318
|
+
V2KeyNames["CredentialConversionInProgress"] = "credential-conversion-in-progress";
|
|
319
|
+
V2KeyNames["PendingCommit"] = "pending-commit";
|
|
316
320
|
})(V2KeyNames || (V2KeyNames = {}));
|
|
317
321
|
|
|
318
322
|
var ErrorResponseCodes;
|
|
@@ -591,10 +595,10 @@ const MASTER_ENCRYPTION_KEY = '9fa9d3f3c77c20d3a50a08e5299644be29f6e6206ef3479fe
|
|
|
591
595
|
const isWeb = typeof window !== 'undefined' && typeof document !== 'undefined';
|
|
592
596
|
const env = {
|
|
593
597
|
platform: 'web',
|
|
594
|
-
isNative:
|
|
598
|
+
isNative: !isWeb,
|
|
595
599
|
isWeb,
|
|
596
600
|
};
|
|
597
|
-
const currentPackageVersion = "3.
|
|
601
|
+
const currentPackageVersion = "3.4.0" ;
|
|
598
602
|
|
|
599
603
|
/**
|
|
600
604
|
* Storage keys adapter for Storage interface across different platforms.
|
|
@@ -3495,7 +3499,6 @@ const keccak256$1 = (() => {
|
|
|
3495
3499
|
})();
|
|
3496
3500
|
|
|
3497
3501
|
const DEFAULT_ENTROPY_BYTES = 32;
|
|
3498
|
-
const MINIMUM_SHANNON_ENTROPY = 4;
|
|
3499
3502
|
/**
|
|
3500
3503
|
* creates a new private key
|
|
3501
3504
|
* @param { Uint8Array } entropy - optional entropy to create the private key
|
|
@@ -3506,25 +3509,15 @@ const createPrivateKey = (entropy) => {
|
|
|
3506
3509
|
if (!(entropy instanceof Uint8Array) || entropy.length < DEFAULT_ENTROPY_BYTES) {
|
|
3507
3510
|
throw new Error(`entropy must be a Uint8Array of at least ${DEFAULT_ENTROPY_BYTES} bytes`);
|
|
3508
3511
|
}
|
|
3509
|
-
// Check byte diversity
|
|
3512
|
+
// Check byte diversity. This catches genuinely broken inputs (all-zeros, all-same-byte)
|
|
3513
|
+
// without false-positiving on 32-byte KDF output (~30 unique bytes expected).
|
|
3514
|
+
// the sampled Shannon-entropy check was removed (WAL-1465) — it's unsound for
|
|
3515
|
+
// 32 samples (max measurable = log2(32) ≈ 5 bits/byte vs a 4-bit threshold), so deterministic
|
|
3516
|
+
// KDF output could be rejected, permanently locking the user out.
|
|
3510
3517
|
const uniqueBytes = new Set(entropy);
|
|
3511
3518
|
if (uniqueBytes.size < Math.min(8, entropy.length / 4)) {
|
|
3512
3519
|
throw new Error(`entropy is too repetitive (only ${uniqueBytes.size} unique byte values)`);
|
|
3513
3520
|
}
|
|
3514
|
-
// Estimate Shannon entropy
|
|
3515
|
-
const byteCounts = new Uint32Array(256);
|
|
3516
|
-
entropy.forEach((b) => byteCounts[b]++);
|
|
3517
|
-
const total = entropy.length;
|
|
3518
|
-
let shannonEntropy = 0;
|
|
3519
|
-
for (let i = 0; i < 256; i++) {
|
|
3520
|
-
if (byteCounts[i] > 0) {
|
|
3521
|
-
const p = byteCounts[i] / total;
|
|
3522
|
-
shannonEntropy -= p * Math.log2(p);
|
|
3523
|
-
}
|
|
3524
|
-
}
|
|
3525
|
-
if (shannonEntropy < MINIMUM_SHANNON_ENTROPY) {
|
|
3526
|
-
throw new Error(`entropy has low Shannon entropy (${shannonEntropy.toFixed(2)} bits/byte)`);
|
|
3527
|
-
}
|
|
3528
3521
|
const outerHex = keccak256$1(entropy);
|
|
3529
3522
|
return addLeading0x(bytesToHex$1(outerHex));
|
|
3530
3523
|
}
|
|
@@ -4399,6 +4392,11 @@ function pbkdf2Sync(password, salt, iterations, keylen, digest) {
|
|
|
4399
4392
|
});
|
|
4400
4393
|
}
|
|
4401
4394
|
|
|
4395
|
+
// Version marker prepended to values wrapped by the master key, so wrapped vs raw is deterministic.
|
|
4396
|
+
const MASTER_KEY_WRAP_PREFIX = 'wsdkmk:v1:';
|
|
4397
|
+
// crypto-js AES.encrypt with a string passphrase emits an OpenSSL "Salted__" header; its base64 always
|
|
4398
|
+
// starts with this. Used to recognize legacy wrapped values stored before MASTER_KEY_WRAP_PREFIX existed.
|
|
4399
|
+
const LEGACY_CRYPTOJS_PREFIX = 'U2FsdGVkX1';
|
|
4402
4400
|
class Cipher {
|
|
4403
4401
|
constructor() { }
|
|
4404
4402
|
/**
|
|
@@ -4429,17 +4427,34 @@ class Cipher {
|
|
|
4429
4427
|
* @returns The encrypted data as a string.
|
|
4430
4428
|
*/
|
|
4431
4429
|
encryptWithMasterKey({ data }) {
|
|
4432
|
-
|
|
4430
|
+
const ciphertext = AES.encrypt(typeof data === 'string' ? data : JSON.stringify(data), this.getMasterKey().key).toString();
|
|
4431
|
+
return MASTER_KEY_WRAP_PREFIX + ciphertext;
|
|
4432
|
+
}
|
|
4433
|
+
/**
|
|
4434
|
+
* @description Determines deterministically whether a stored value was wrapped by the master key,
|
|
4435
|
+
* without inferring from decrypt behavior. Returns true for values carrying the version marker, or
|
|
4436
|
+
* legacy crypto-js ciphertext stored before the marker existed. Everything else is treated as raw.
|
|
4437
|
+
*/
|
|
4438
|
+
isWrappedByMasterKey(value) {
|
|
4439
|
+
return value.startsWith(MASTER_KEY_WRAP_PREFIX) || value.startsWith(LEGACY_CRYPTOJS_PREFIX);
|
|
4433
4440
|
}
|
|
4434
4441
|
decryptWithMasterKey({ cipherText }) {
|
|
4435
|
-
const
|
|
4436
|
-
|
|
4437
|
-
|
|
4442
|
+
const ciphertext = cipherText.startsWith(MASTER_KEY_WRAP_PREFIX)
|
|
4443
|
+
? cipherText.slice(MASTER_KEY_WRAP_PREFIX.length)
|
|
4444
|
+
: cipherText;
|
|
4445
|
+
try {
|
|
4446
|
+
const decrypted = AES.decrypt(ciphertext, this.getMasterKey().key).toString(enc.Utf8);
|
|
4447
|
+
if (decrypted) {
|
|
4448
|
+
return isJsonString(decrypted) ? safeJsonParse(decrypted) : decrypted;
|
|
4449
|
+
}
|
|
4438
4450
|
}
|
|
4439
|
-
|
|
4440
|
-
|
|
4451
|
+
catch (error) {
|
|
4452
|
+
// crypto-js throws "Malformed UTF-8 data" when the ciphertext can't be decrypted
|
|
4453
|
+
logger.error('Decryption failed with master key', error);
|
|
4441
4454
|
return undefined;
|
|
4442
4455
|
}
|
|
4456
|
+
logger.error('Decryption failed with master key');
|
|
4457
|
+
return undefined;
|
|
4443
4458
|
}
|
|
4444
4459
|
/**
|
|
4445
4460
|
* Validate that a public key is the correct length and format.
|
|
@@ -4546,6 +4561,8 @@ class Cipher {
|
|
|
4546
4561
|
}
|
|
4547
4562
|
derivedKeyPair = await this.deriveKeyPairFromPasskey({ inputKeyMaterial: options.prfValue });
|
|
4548
4563
|
return derivedKeyPair;
|
|
4564
|
+
default:
|
|
4565
|
+
throw new Error(`Unknown AuthType: ${options.authType}`);
|
|
4549
4566
|
}
|
|
4550
4567
|
}
|
|
4551
4568
|
catch (error) {
|
|
@@ -4805,6 +4822,14 @@ class StorageService {
|
|
|
4805
4822
|
return;
|
|
4806
4823
|
}
|
|
4807
4824
|
async fetch(key, options) {
|
|
4825
|
+
var _a;
|
|
4826
|
+
// Recover once per session; memoize the promise so concurrent first-fetches all await the same
|
|
4827
|
+
// recovery instead of racing past it and reading pre-recovery storage. recoverCommit uses
|
|
4828
|
+
// getItem/removeItem (not fetch), so there's no recursion. Swallow errors: recovery is
|
|
4829
|
+
// best-effort and a failure must not wedge every subsequent fetch.
|
|
4830
|
+
await ((_a = this._walRecovery) !== null && _a !== void 0 ? _a : (this._walRecovery = this.recoverCommit().catch((error) => {
|
|
4831
|
+
logger.error('SDK::StorageService::fetch::wal recovery failed', error);
|
|
4832
|
+
})));
|
|
4808
4833
|
let storageKey;
|
|
4809
4834
|
if (this._walletSpecificKeys.includes(key)) {
|
|
4810
4835
|
if (!(options === null || options === void 0 ? void 0 : options.walletId)) {
|
|
@@ -4815,7 +4840,7 @@ class StorageService {
|
|
|
4815
4840
|
else {
|
|
4816
4841
|
storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}`;
|
|
4817
4842
|
}
|
|
4818
|
-
if (
|
|
4843
|
+
if (env.isNative) {
|
|
4819
4844
|
storageKey = normalizeKey(storageKey);
|
|
4820
4845
|
}
|
|
4821
4846
|
const item = await this.getItem(storageKey);
|
|
@@ -4824,14 +4849,11 @@ class StorageService {
|
|
|
4824
4849
|
return undefined;
|
|
4825
4850
|
}
|
|
4826
4851
|
if (this._keysProtectedByMasterKey.includes(key)) {
|
|
4827
|
-
|
|
4828
|
-
|
|
4829
|
-
|
|
4830
|
-
unwrapped = this.cipher.decryptWithMasterKey({ cipherText: item });
|
|
4831
|
-
}
|
|
4832
|
-
catch (_a) {
|
|
4833
|
-
unwrapped = item;
|
|
4852
|
+
// Raw legacy value stored before master-key wrapping: return as-is instead of attempting decrypt.
|
|
4853
|
+
if (!this.cipher.isWrappedByMasterKey(item)) {
|
|
4854
|
+
return item;
|
|
4834
4855
|
}
|
|
4856
|
+
const unwrapped = this.cipher.decryptWithMasterKey({ cipherText: item });
|
|
4835
4857
|
if (!unwrapped) {
|
|
4836
4858
|
logger.error(`Failed to decrypt item with key ${storageKey}`);
|
|
4837
4859
|
return undefined;
|
|
@@ -4851,7 +4873,7 @@ class StorageService {
|
|
|
4851
4873
|
else {
|
|
4852
4874
|
storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}`;
|
|
4853
4875
|
}
|
|
4854
|
-
if (
|
|
4876
|
+
if (env.isNative) {
|
|
4855
4877
|
storageKey = normalizeKey(storageKey);
|
|
4856
4878
|
}
|
|
4857
4879
|
let valueToStore;
|
|
@@ -4867,6 +4889,75 @@ class StorageService {
|
|
|
4867
4889
|
async saveInBulk(data) {
|
|
4868
4890
|
await Promise.all(data.map((item) => this.save(item.key, item.value, { walletId: item.walletId })));
|
|
4869
4891
|
}
|
|
4892
|
+
// Compute the final storage key the same way save/fetch/delete do.
|
|
4893
|
+
_computeRawKey(key, walletId) {
|
|
4894
|
+
let storageKey;
|
|
4895
|
+
if (this._walletSpecificKeys.includes(key)) {
|
|
4896
|
+
if (!walletId)
|
|
4897
|
+
throw new Error(`A walletId is required to compute key: ${key}`);
|
|
4898
|
+
storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}:${walletId}`;
|
|
4899
|
+
}
|
|
4900
|
+
else {
|
|
4901
|
+
storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}`;
|
|
4902
|
+
}
|
|
4903
|
+
return isWeb ? storageKey : normalizeKey(storageKey);
|
|
4904
|
+
}
|
|
4905
|
+
_serializeValue(key, value) {
|
|
4906
|
+
if (this._keysProtectedByMasterKey.includes(key)) {
|
|
4907
|
+
return this.cipher.encryptWithMasterKey({ data: value });
|
|
4908
|
+
}
|
|
4909
|
+
return typeof value === 'string' ? value : JSON.stringify(value);
|
|
4910
|
+
}
|
|
4911
|
+
async _applyWAL(record) {
|
|
4912
|
+
for (const { rawKey, value } of record.writes) {
|
|
4913
|
+
await this.setItem(rawKey, value);
|
|
4914
|
+
}
|
|
4915
|
+
for (const rawKey of record.deletes) {
|
|
4916
|
+
await this.removeItem(rawKey);
|
|
4917
|
+
}
|
|
4918
|
+
}
|
|
4919
|
+
// Atomically commit a batch of writes and deletes via a write-ahead log.
|
|
4920
|
+
// The WAL record is written in a single setItem before any credential key is
|
|
4921
|
+
// touched. A crash between that write and the individual setItem calls leaves
|
|
4922
|
+
// the WAL in place; recoverCommit() finishes the batch on the next call.
|
|
4923
|
+
async commitBatch(writes, deletes) {
|
|
4924
|
+
const record = {
|
|
4925
|
+
writes: writes.map(({ key, value, walletId }) => ({
|
|
4926
|
+
rawKey: this._computeRawKey(key, walletId),
|
|
4927
|
+
value: this._serializeValue(key, value),
|
|
4928
|
+
})),
|
|
4929
|
+
deletes: (deletes !== null && deletes !== void 0 ? deletes : []).map(({ key, walletId }) => this._computeRawKey(key, walletId)),
|
|
4930
|
+
};
|
|
4931
|
+
// Finish any dangling WAL from a prior partially-applied commit before writing a new one —
|
|
4932
|
+
// otherwise this setItem clobbers it and those half-written credentials become unrecoverable.
|
|
4933
|
+
await this.recoverCommit();
|
|
4934
|
+
const walKey = this._computeRawKey(V2KeyNames.PendingCommit);
|
|
4935
|
+
await this.setItem(walKey, JSON.stringify(record));
|
|
4936
|
+
await this._applyWAL(record);
|
|
4937
|
+
await this.removeItem(walKey);
|
|
4938
|
+
}
|
|
4939
|
+
// Re-apply a pending WAL commit if the process was killed mid-batch.
|
|
4940
|
+
// Call at the start of any operation that writes credential blobs.
|
|
4941
|
+
async recoverCommit() {
|
|
4942
|
+
const walKey = this._computeRawKey(V2KeyNames.PendingCommit);
|
|
4943
|
+
const raw = await this.getItem(walKey);
|
|
4944
|
+
if (!raw)
|
|
4945
|
+
return;
|
|
4946
|
+
let record;
|
|
4947
|
+
try {
|
|
4948
|
+
record = safeJsonParse(raw);
|
|
4949
|
+
}
|
|
4950
|
+
catch (error) {
|
|
4951
|
+
// Corrupt/unparseable WAL can never be replayed — discard so it doesn't wedge every fetch.
|
|
4952
|
+
logger.error('SDK::StorageService::recoverCommit::corrupt WAL, discarding', error);
|
|
4953
|
+
await this.removeItem(walKey);
|
|
4954
|
+
return;
|
|
4955
|
+
}
|
|
4956
|
+
// _applyWAL is idempotent. If it throws (transient storage error) keep the WAL and let the
|
|
4957
|
+
// caller retry — don't delete the only record needed to finish the batch. Remove only on success.
|
|
4958
|
+
await this._applyWAL(record);
|
|
4959
|
+
await this.removeItem(walKey);
|
|
4960
|
+
}
|
|
4870
4961
|
async delete(key, options) {
|
|
4871
4962
|
let storageKey;
|
|
4872
4963
|
if (this._walletSpecificKeys.includes(key)) {
|
|
@@ -4878,7 +4969,7 @@ class StorageService {
|
|
|
4878
4969
|
else {
|
|
4879
4970
|
storageKey = `wsdk:v2:${this.shortenedEnv}:${key}:${this.userId}`;
|
|
4880
4971
|
}
|
|
4881
|
-
if (
|
|
4972
|
+
if (env.isNative) {
|
|
4882
4973
|
storageKey = normalizeKey(storageKey);
|
|
4883
4974
|
}
|
|
4884
4975
|
return await this.removeItem(storageKey);
|
|
@@ -5143,11 +5234,16 @@ class StorageService {
|
|
|
5143
5234
|
LocalStorageItems.AccessToken,
|
|
5144
5235
|
LocalStorageItems.RefreshToken,
|
|
5145
5236
|
V2KeyNames.EncryptedDevicePrivateKey,
|
|
5237
|
+
V2KeyNames.ClientAuthPublicKey,
|
|
5146
5238
|
V2KeyNames.WallabyAuthPubKey,
|
|
5147
5239
|
V2KeyNames.PasskeyCredential,
|
|
5148
5240
|
V2KeyNames.MigrationVersion,
|
|
5149
5241
|
V2KeyNames.LastMigratedAt,
|
|
5150
5242
|
V2KeyNames.ClientAuthToken,
|
|
5243
|
+
V2KeyNames.PasswordResetAttempts,
|
|
5244
|
+
V2KeyNames.MigrationAttempts,
|
|
5245
|
+
V2KeyNames.CredentialConversionInProgress,
|
|
5246
|
+
V2KeyNames.PendingCommit,
|
|
5151
5247
|
];
|
|
5152
5248
|
await Promise.all(userKeysToRemove.map((key) => this.delete(key)));
|
|
5153
5249
|
if (walletId) {
|
|
@@ -5279,6 +5375,11 @@ const AuthRoutes = {
|
|
|
5279
5375
|
method: RequestMethod.Get,
|
|
5280
5376
|
requiresAccessToken: true,
|
|
5281
5377
|
},
|
|
5378
|
+
issueJwtToken: {
|
|
5379
|
+
fullPath: '/auth/issue-jwt-token',
|
|
5380
|
+
method: RequestMethod.Post,
|
|
5381
|
+
requiresAccessToken: false,
|
|
5382
|
+
},
|
|
5282
5383
|
};
|
|
5283
5384
|
|
|
5284
5385
|
class LockManagerService {
|
|
@@ -5658,6 +5759,16 @@ class Api {
|
|
|
5658
5759
|
* @secure
|
|
5659
5760
|
*/
|
|
5660
5761
|
signIn: (data, params = {}) => this.http.request(Object.assign({ path: `/api/v1/auth/sign-in`, method: "POST", body: data, secure: true, type: ContentType.Json, format: "json" }, params)),
|
|
5762
|
+
/**
|
|
5763
|
+
* No description
|
|
5764
|
+
*
|
|
5765
|
+
* @tags Auth
|
|
5766
|
+
* @name IssueJwtToken
|
|
5767
|
+
* @summary Issue a Wallaby JWT token for a user using only x-api-key and x-client-jwt headers. Requires mfaVerified and that the user belongs to the API key merchant.
|
|
5768
|
+
* @request POST:/api/v1/auth/issue-jwt-token
|
|
5769
|
+
* @secure
|
|
5770
|
+
*/
|
|
5771
|
+
issueJwtToken: (params = {}) => this.http.request(Object.assign({ path: `/api/v1/auth/issue-jwt-token`, method: "POST", secure: true, format: "json" }, params)),
|
|
5661
5772
|
/**
|
|
5662
5773
|
* No description
|
|
5663
5774
|
*
|
|
@@ -6156,6 +6267,20 @@ class Api {
|
|
|
6156
6267
|
if (params === void 0) { params = {}; }
|
|
6157
6268
|
return this.http.request(Object.assign({ path: `/api/v1/wallets/${walletId}/assets`, method: "GET", query: query, secure: true, format: "json" }, params));
|
|
6158
6269
|
},
|
|
6270
|
+
/**
|
|
6271
|
+
* No description
|
|
6272
|
+
*
|
|
6273
|
+
* @tags Wallets
|
|
6274
|
+
* @name GetWalletAddresses
|
|
6275
|
+
* @summary Get all assets that exist in a certain wallet, by specifying a wallet ID
|
|
6276
|
+
* @request GET:/api/v1/wallets/{walletId}/addresses
|
|
6277
|
+
* @secure
|
|
6278
|
+
*/
|
|
6279
|
+
getWalletAddresses: (_a, params) => {
|
|
6280
|
+
var { walletId } = _a, query = __rest(_a, ["walletId"]);
|
|
6281
|
+
if (params === void 0) { params = {}; }
|
|
6282
|
+
return this.http.request(Object.assign({ path: `/api/v1/wallets/${walletId}/addresses`, method: "GET", query: query, secure: true, format: "json" }, params));
|
|
6283
|
+
},
|
|
6159
6284
|
/**
|
|
6160
6285
|
* No description
|
|
6161
6286
|
*
|
|
@@ -6355,23 +6480,35 @@ class Api {
|
|
|
6355
6480
|
/**
|
|
6356
6481
|
* No description
|
|
6357
6482
|
*
|
|
6358
|
-
* @tags Transactions, Transactions
|
|
6483
|
+
* @tags Transactions, Transactions
|
|
6359
6484
|
* @name DetectTransferRestriction
|
|
6360
6485
|
* @summary Request to detect whether there is a transfer restriction on a particular transaction
|
|
6361
6486
|
* @request GET:/api/v1/transactions/detect-transfers-restrictions
|
|
6487
|
+
* @deprecated
|
|
6362
6488
|
* @secure
|
|
6363
6489
|
*/
|
|
6364
6490
|
detectTransferRestriction: (query, params = {}) => this.http.request(Object.assign({ path: `/api/v1/transactions/detect-transfers-restrictions`, method: "GET", query: query, secure: true, format: "json" }, params)),
|
|
6365
6491
|
/**
|
|
6366
6492
|
* No description
|
|
6367
6493
|
*
|
|
6368
|
-
* @tags Transactions, Transactions
|
|
6494
|
+
* @tags Transactions, Transactions
|
|
6369
6495
|
* @name FetchMessageForTransferRestriction
|
|
6370
6496
|
* @summary Request restriction message by providing a restriction code
|
|
6371
6497
|
* @request GET:/api/v1/transactions/transfer-restriction-message
|
|
6498
|
+
* @deprecated
|
|
6372
6499
|
* @secure
|
|
6373
6500
|
*/
|
|
6374
6501
|
fetchMessageForTransferRestriction: (query, params = {}) => this.http.request(Object.assign({ path: `/api/v1/transactions/transfer-restriction-message`, method: "GET", query: query, secure: true, format: "json" }, params)),
|
|
6502
|
+
/**
|
|
6503
|
+
* No description
|
|
6504
|
+
*
|
|
6505
|
+
* @tags Transactions, Transactions
|
|
6506
|
+
* @name GetRestriction
|
|
6507
|
+
* @summary Request to detect whether there is a transfer restriction on a particular transaction
|
|
6508
|
+
* @request GET:/api/v1/transactions/restriction
|
|
6509
|
+
* @secure
|
|
6510
|
+
*/
|
|
6511
|
+
getRestriction: (query, params = {}) => this.http.request(Object.assign({ path: `/api/v1/transactions/restriction`, method: "GET", query: query, secure: true, format: "json" }, params)),
|
|
6375
6512
|
/**
|
|
6376
6513
|
* No description
|
|
6377
6514
|
*
|
|
@@ -7346,7 +7483,22 @@ const TransactionsRoutes = {
|
|
|
7346
7483
|
requiresAccessToken: true,
|
|
7347
7484
|
},
|
|
7348
7485
|
getTransactions: {
|
|
7349
|
-
fullPath: '/
|
|
7486
|
+
fullPath: '/transactions',
|
|
7487
|
+
method: RequestMethod.Get,
|
|
7488
|
+
requiresAccessToken: true,
|
|
7489
|
+
},
|
|
7490
|
+
detectTransferRestrictions: {
|
|
7491
|
+
fullPath: '/transactions/detect-transfers-restrictions',
|
|
7492
|
+
method: RequestMethod.Get,
|
|
7493
|
+
requiresAccessToken: true,
|
|
7494
|
+
},
|
|
7495
|
+
transferRestrictionMessage: {
|
|
7496
|
+
fullPath: '/transactions/transfer-restriction-message',
|
|
7497
|
+
method: RequestMethod.Get,
|
|
7498
|
+
requiresAccessToken: true,
|
|
7499
|
+
},
|
|
7500
|
+
restriction: {
|
|
7501
|
+
fullPath: '/transactions/restriction',
|
|
7350
7502
|
method: RequestMethod.Get,
|
|
7351
7503
|
requiresAccessToken: true,
|
|
7352
7504
|
},
|
|
@@ -7924,7 +8076,6 @@ let PasskeyService$1 = class PasskeyService {
|
|
|
7924
8076
|
}
|
|
7925
8077
|
logger.log('SDK::PasskeyService::register:: getting signature', {
|
|
7926
8078
|
message: challengeResponse.message,
|
|
7927
|
-
privateKey: deviceKeyPair.privateKey,
|
|
7928
8079
|
});
|
|
7929
8080
|
const { signature, message } = await this.cipher.sign({
|
|
7930
8081
|
message: challengeResponse.message,
|
|
@@ -8581,7 +8732,7 @@ class AuthService extends Base {
|
|
|
8581
8732
|
data: deviceKeyPair.privateKey,
|
|
8582
8733
|
encryptionKey: credentialsKeyPair.publicKey,
|
|
8583
8734
|
});
|
|
8584
|
-
this.localStorageService.saveInBulk([
|
|
8735
|
+
await this.localStorageService.saveInBulk([
|
|
8585
8736
|
{
|
|
8586
8737
|
key: LocalStorageItems.EncryptedDevicePrivateKey,
|
|
8587
8738
|
value: encryptedDevicePrivKey,
|
|
@@ -8652,6 +8803,24 @@ class AuthService extends Base {
|
|
|
8652
8803
|
valid: true,
|
|
8653
8804
|
};
|
|
8654
8805
|
}
|
|
8806
|
+
/**
|
|
8807
|
+
* @description Exchanges the client JWT (set at SDK initialisation) for a
|
|
8808
|
+
* Wallaby access + refresh token pair. Tokens are persisted to storage so
|
|
8809
|
+
* subsequent SDK calls use them automatically.
|
|
8810
|
+
* @returns {Promise<IssueJWTTokenResponseDto>} The issued access/refresh tokens and basic user info.
|
|
8811
|
+
*/
|
|
8812
|
+
async exchangeClientToken() {
|
|
8813
|
+
try {
|
|
8814
|
+
const response = await this.request(AuthRoutes.issueJwtToken);
|
|
8815
|
+
await this.localStorageService.save(LocalStorageItems.AccessToken, response.accessToken);
|
|
8816
|
+
await this.localStorageService.save(LocalStorageItems.RefreshToken, response.refreshToken);
|
|
8817
|
+
return response;
|
|
8818
|
+
}
|
|
8819
|
+
catch (error) {
|
|
8820
|
+
logger.error('SDK::Auth::exchangeClientToken::error', error);
|
|
8821
|
+
throw error;
|
|
8822
|
+
}
|
|
8823
|
+
}
|
|
8655
8824
|
}
|
|
8656
8825
|
__decorate([
|
|
8657
8826
|
WithLock('signUp'),
|
|
@@ -8672,6 +8841,63 @@ __decorate([
|
|
|
8672
8841
|
__metadata("design:returntype", Promise)
|
|
8673
8842
|
], AuthService.prototype, "storeDeviceKeyPair", null);
|
|
8674
8843
|
|
|
8844
|
+
const ENCRYPTED_PAYLOAD_FIELDS = ['iv', 'ephemPublicKey', 'ciphertext', 'mac'];
|
|
8845
|
+
// Backup share may be ECIES or symmetric ({ iv, ciphertext, mac, tag }) — both share these three fields.
|
|
8846
|
+
const SYMMETRIC_PAYLOAD_FIELDS = ['iv', 'ciphertext', 'mac', 'tag'];
|
|
8847
|
+
// API is the trust boundary: confirm every named field is a non-empty string.
|
|
8848
|
+
function hasNonEmptyStringFields(payload, fields) {
|
|
8849
|
+
return (!!payload &&
|
|
8850
|
+
typeof payload === 'object' &&
|
|
8851
|
+
fields.every((field) => {
|
|
8852
|
+
const value = payload[field];
|
|
8853
|
+
return typeof value === 'string' && value.length > 0;
|
|
8854
|
+
}));
|
|
8855
|
+
}
|
|
8856
|
+
/**
|
|
8857
|
+
* Fail fast if an encrypted payload from the API does not match the expected
|
|
8858
|
+
* ECIES structure ({ iv, ephemPublicKey, ciphertext, mac }). See the contract
|
|
8859
|
+
* note on `handleKeySharesFromResponse`.
|
|
8860
|
+
*/
|
|
8861
|
+
function assertEncryptedPayloadShape(encrypted) {
|
|
8862
|
+
if (!hasNonEmptyStringFields(encrypted, ENCRYPTED_PAYLOAD_FIELDS)) {
|
|
8863
|
+
throw new WallabyError({
|
|
8864
|
+
message: 'Encrypted share does not match the expected { iv, ephemPublicKey, ciphertext, mac } format.',
|
|
8865
|
+
statusCode: 422,
|
|
8866
|
+
errorCode: ErrorResponseCodes.sdk_invalid_parameter,
|
|
8867
|
+
});
|
|
8868
|
+
}
|
|
8869
|
+
}
|
|
8870
|
+
/**
|
|
8871
|
+
* Shape-assert every share returned by the API. Empty arrays are rejected here
|
|
8872
|
+
* so callers get a clean error instead of crashing on `shares[0]`.
|
|
8873
|
+
*/
|
|
8874
|
+
function assertSharesPayloadShape(shares) {
|
|
8875
|
+
if (!shares.length) {
|
|
8876
|
+
throw new WallabyError({
|
|
8877
|
+
message: 'No key shares were returned from the API.',
|
|
8878
|
+
statusCode: 422,
|
|
8879
|
+
errorCode: ErrorResponseCodes.sdk_invalid_parameter,
|
|
8880
|
+
});
|
|
8881
|
+
}
|
|
8882
|
+
for (const share of shares) {
|
|
8883
|
+
assertEncryptedPayloadShape(share.encrypted);
|
|
8884
|
+
}
|
|
8885
|
+
}
|
|
8886
|
+
/**
|
|
8887
|
+
* The backup share is stored as-is (the device can't peel it), so we only
|
|
8888
|
+
* shape-check it. It may be ECIES or symmetric, so accept either variant.
|
|
8889
|
+
*/
|
|
8890
|
+
function assertBackupSharePayloadShape(encrypted) {
|
|
8891
|
+
const isEcies = hasNonEmptyStringFields(encrypted, ENCRYPTED_PAYLOAD_FIELDS);
|
|
8892
|
+
const isSymmetric = hasNonEmptyStringFields(encrypted, SYMMETRIC_PAYLOAD_FIELDS);
|
|
8893
|
+
if (!isEcies && !isSymmetric) {
|
|
8894
|
+
throw new WallabyError({
|
|
8895
|
+
message: 'Encrypted backup share does not match the expected ECIES ({ iv, ephemPublicKey, ciphertext, mac }) or symmetric ({ iv, ciphertext, mac, tag }) format.',
|
|
8896
|
+
statusCode: 422,
|
|
8897
|
+
errorCode: ErrorResponseCodes.sdk_invalid_parameter,
|
|
8898
|
+
});
|
|
8899
|
+
}
|
|
8900
|
+
}
|
|
8675
8901
|
class WalletHandlersService extends Base {
|
|
8676
8902
|
constructor(config) {
|
|
8677
8903
|
super(config);
|
|
@@ -8752,6 +8978,7 @@ class WalletHandlersService extends Base {
|
|
|
8752
8978
|
shares: importWalletRequest.shares,
|
|
8753
8979
|
credentialsKeyPair,
|
|
8754
8980
|
encryptedBackupShare: importWalletRequest.encryptedBackupShare,
|
|
8981
|
+
devicePrivateKey: deviceAuthKeys.privateKey,
|
|
8755
8982
|
});
|
|
8756
8983
|
}
|
|
8757
8984
|
return Object.assign({}, importWalletRequest);
|
|
@@ -8838,6 +9065,7 @@ class WalletHandlersService extends Base {
|
|
|
8838
9065
|
shares: walletCreationResponse.shares,
|
|
8839
9066
|
credentialsKeyPair,
|
|
8840
9067
|
encryptedBackupShare: walletCreationResponse.encryptedBackupShare,
|
|
9068
|
+
devicePrivateKey: deviceAuthKeys.privateKey,
|
|
8841
9069
|
});
|
|
8842
9070
|
}
|
|
8843
9071
|
return Object.assign(Object.assign({}, walletCreationResponse), { standardSeedPhrase: decryptedSeedPhrase });
|
|
@@ -8853,8 +9081,41 @@ class WalletHandlersService extends Base {
|
|
|
8853
9081
|
});
|
|
8854
9082
|
}
|
|
8855
9083
|
}
|
|
8856
|
-
|
|
9084
|
+
/**
|
|
9085
|
+
* Encrypted share format contract (WAL-1467)
|
|
9086
|
+
* --------------------------------------------------------------------------
|
|
9087
|
+
* Every flow that ingests shares from the API (import, create, recover,
|
|
9088
|
+
* addNewDevice) routes through here, so the contract is asserted in one place.
|
|
9089
|
+
*
|
|
9090
|
+
* The API returns the main device share as `shares[0]`, an ECIES payload
|
|
9091
|
+
* ({ iv, ephemPublicKey, ciphertext, mac }) wrapped to the device public key,
|
|
9092
|
+
* so it MUST peel with the device private key. `encryptedBackupShare` is an
|
|
9093
|
+
* already-wrapped blob (ECIES or symmetric) that the device cannot decrypt, so
|
|
9094
|
+
* it is stored as-is.
|
|
9095
|
+
*
|
|
9096
|
+
* We shape-assert every share (and the backup share) here, at ingestion, so a
|
|
9097
|
+
* server-side wrapping change fails loudly now instead of silently breaking
|
|
9098
|
+
* export/recovery later.
|
|
9099
|
+
*/
|
|
9100
|
+
async handleKeySharesFromResponse({ walletId, shares, credentialsKeyPair, encryptedBackupShare, devicePrivateKey, }) {
|
|
8857
9101
|
try {
|
|
9102
|
+
assertSharesPayloadShape(shares);
|
|
9103
|
+
assertBackupSharePayloadShape(encryptedBackupShare);
|
|
9104
|
+
// Decrypt-test the contract: shares[0] is wrapped to the device public key and must peel with the device private key.
|
|
9105
|
+
try {
|
|
9106
|
+
await this.cipher.decrypt({
|
|
9107
|
+
cipherText: shares[0].encrypted,
|
|
9108
|
+
decryptionKey: devicePrivateKey,
|
|
9109
|
+
});
|
|
9110
|
+
}
|
|
9111
|
+
catch (error) {
|
|
9112
|
+
throw new WallabyError({
|
|
9113
|
+
message: 'Device-wrapped key share (shares[0]) could not be decrypted with the device private key; the share wrapping format may have changed.',
|
|
9114
|
+
statusCode: 422,
|
|
9115
|
+
errorCode: ErrorResponseCodes.sdk_key_share_decryption_failed,
|
|
9116
|
+
cause: error,
|
|
9117
|
+
});
|
|
9118
|
+
}
|
|
8858
9119
|
const encryptedWithCredentialsKeyShare = await this.cipher.encrypt({
|
|
8859
9120
|
data: JSON.stringify(shares[0].encrypted),
|
|
8860
9121
|
encryptionKey: credentialsKeyPair.publicKey,
|
|
@@ -8948,13 +9209,42 @@ class WalletHandlersService extends Base {
|
|
|
8948
9209
|
class WalletService extends Base {
|
|
8949
9210
|
constructor(config) {
|
|
8950
9211
|
super(config);
|
|
8951
|
-
this.passwordResetAttempts = 0;
|
|
8952
|
-
this.migrationAttempts = 0;
|
|
8953
9212
|
this.authService = new AuthService(config);
|
|
8954
9213
|
this.handlers = new WalletHandlersService(config);
|
|
8955
9214
|
this.userId = config.userId;
|
|
8956
9215
|
this.passkeyService = new PasskeyService(config.userId, this.localStorageService, this.request);
|
|
8957
9216
|
}
|
|
9217
|
+
/**
|
|
9218
|
+
* Reads the persisted sliding-window rate-limit state for a counter key.
|
|
9219
|
+
* Returns a fresh window ({ count: 0 }) when none is stored or the window has expired.
|
|
9220
|
+
*/
|
|
9221
|
+
async getRateState(key) {
|
|
9222
|
+
const now = Date.now();
|
|
9223
|
+
const raw = await this.localStorageService.fetch(key);
|
|
9224
|
+
const state = raw ? safeJsonParse(raw) : undefined;
|
|
9225
|
+
if (!state || now - state.windowStart > WalletService.RATE_LIMIT_WINDOW_MS) {
|
|
9226
|
+
return { count: 0, windowStart: now };
|
|
9227
|
+
}
|
|
9228
|
+
return state;
|
|
9229
|
+
}
|
|
9230
|
+
/** Increments and persists the counter (resetting an expired window). Returns the new count. */
|
|
9231
|
+
async recordRateAttempt(key) {
|
|
9232
|
+
const state = await this.getRateState(key);
|
|
9233
|
+
state.count += 1;
|
|
9234
|
+
await this.localStorageService.save(key, JSON.stringify(state));
|
|
9235
|
+
return state.count;
|
|
9236
|
+
}
|
|
9237
|
+
/** Throws a 429 when the counter is already over the limit, without incrementing it. */
|
|
9238
|
+
async assertUnderRateLimit(key, message) {
|
|
9239
|
+
const { count } = await this.getRateState(key);
|
|
9240
|
+
if (count > WalletService.RATE_LIMIT_MAX) {
|
|
9241
|
+
throw new WallabyError({
|
|
9242
|
+
message,
|
|
9243
|
+
statusCode: 429,
|
|
9244
|
+
errorCode: ErrorResponseCodes.sdk_too_many_requests,
|
|
9245
|
+
});
|
|
9246
|
+
}
|
|
9247
|
+
}
|
|
8958
9248
|
/**
|
|
8959
9249
|
* @public
|
|
8960
9250
|
* @returns {boolean} Returns true if the device has a seed phrase.
|
|
@@ -9060,20 +9350,7 @@ class WalletService extends Base {
|
|
|
9060
9350
|
});
|
|
9061
9351
|
}
|
|
9062
9352
|
if (this.deviceAuthType === AuthType.Password && authenticationOptions.password) {
|
|
9063
|
-
|
|
9064
|
-
await this.handleUpdateToV2({
|
|
9065
|
-
password: authenticationOptions.password,
|
|
9066
|
-
walletId: walletId,
|
|
9067
|
-
});
|
|
9068
|
-
}
|
|
9069
|
-
catch (error) {
|
|
9070
|
-
logger.error('SDK::WalletService::export::handleUpdateToV2::error', error);
|
|
9071
|
-
throw new WallabyError({
|
|
9072
|
-
message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
|
|
9073
|
-
statusCode: 500,
|
|
9074
|
-
errorCode: ErrorResponseCodes.sdk_unknown_error,
|
|
9075
|
-
});
|
|
9076
|
-
}
|
|
9353
|
+
await this.migrateToV2Safe({ password: authenticationOptions.password, walletId });
|
|
9077
9354
|
}
|
|
9078
9355
|
const encryptedSeed = await this.localStorageService.fetch(LocalStorageItems.EncryptedStandardSeedPhrase, { walletId });
|
|
9079
9356
|
const encryptedPrimaryDeviceShare = await this.localStorageService.fetch(LocalStorageItems.PrimaryDeviceKeyShare, {
|
|
@@ -9316,6 +9593,7 @@ class WalletService extends Base {
|
|
|
9316
9593
|
shares: recoverWithSeedPhraseResponse.shares,
|
|
9317
9594
|
credentialsKeyPair,
|
|
9318
9595
|
encryptedBackupShare: recoverWithSeedPhraseResponse.encryptedBackupShare,
|
|
9596
|
+
devicePrivateKey: deviceAuthKeyPair.privateKey,
|
|
9319
9597
|
});
|
|
9320
9598
|
}
|
|
9321
9599
|
await this.authService.storeDeviceKeyPair({
|
|
@@ -9379,6 +9657,7 @@ class WalletService extends Base {
|
|
|
9379
9657
|
shares: recoverWithSeedPhraseResponse.shares,
|
|
9380
9658
|
credentialsKeyPair,
|
|
9381
9659
|
encryptedBackupShare: recoverWithSeedPhraseResponse.encryptedBackupShare,
|
|
9660
|
+
devicePrivateKey: deviceAuthKeyPair.privateKey,
|
|
9382
9661
|
});
|
|
9383
9662
|
}
|
|
9384
9663
|
await this.authService.storeDeviceKeyPair({
|
|
@@ -9411,8 +9690,7 @@ class WalletService extends Base {
|
|
|
9411
9690
|
*/
|
|
9412
9691
|
async changePassword({ walletId, oldPassword, newPassword, }) {
|
|
9413
9692
|
try {
|
|
9414
|
-
this.
|
|
9415
|
-
if (this.passwordResetAttempts > 5) {
|
|
9693
|
+
if ((await this.recordRateAttempt(V2KeyNames.PasswordResetAttempts)) > WalletService.RATE_LIMIT_MAX) {
|
|
9416
9694
|
throw new WallabyError({
|
|
9417
9695
|
message: 'Too many password change attempts. Please try again later.',
|
|
9418
9696
|
statusCode: 429,
|
|
@@ -9421,20 +9699,7 @@ class WalletService extends Base {
|
|
|
9421
9699
|
}
|
|
9422
9700
|
if (this.deviceAuthType === AuthType.Password && oldPassword) {
|
|
9423
9701
|
// Handle migration to V2 first then change the password to the new one.
|
|
9424
|
-
|
|
9425
|
-
await this.handleUpdateToV2({
|
|
9426
|
-
password: oldPassword,
|
|
9427
|
-
walletId,
|
|
9428
|
-
});
|
|
9429
|
-
}
|
|
9430
|
-
catch (error) {
|
|
9431
|
-
logger.error('SDK::WalletService::changePassword::handleUpdateToV2::error', error);
|
|
9432
|
-
throw new WallabyError({
|
|
9433
|
-
message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
|
|
9434
|
-
statusCode: 500,
|
|
9435
|
-
errorCode: ErrorResponseCodes.sdk_unknown_error,
|
|
9436
|
-
});
|
|
9437
|
-
}
|
|
9702
|
+
await this.migrateToV2Safe({ password: oldPassword, walletId });
|
|
9438
9703
|
}
|
|
9439
9704
|
const encryptedDevicePrivateKeyString = await this.localStorageService.fetch(V2KeyNames.EncryptedDevicePrivateKey);
|
|
9440
9705
|
const encryptedSeedPhraseString = await this.localStorageService.fetch(V2KeyNames.EncryptedStandardSeedPhrase, {
|
|
@@ -9468,7 +9733,7 @@ class WalletService extends Base {
|
|
|
9468
9733
|
password: newPassword,
|
|
9469
9734
|
salt: clientSalt,
|
|
9470
9735
|
});
|
|
9471
|
-
if (!newCredentialsKeyPair.publicKey) {
|
|
9736
|
+
if (!newCredentialsKeyPair.publicKey || !newCredentialsKeyPair.privateKey) {
|
|
9472
9737
|
throw new WallabyError({
|
|
9473
9738
|
message: 'Could not derive keys for new password.',
|
|
9474
9739
|
statusCode: 500,
|
|
@@ -9480,40 +9745,59 @@ class WalletService extends Base {
|
|
|
9480
9745
|
decryptionKey: oldCredentialsKeyPair.privateKey,
|
|
9481
9746
|
encryptionKey: newCredentialsKeyPair.publicKey,
|
|
9482
9747
|
});
|
|
9483
|
-
|
|
9484
|
-
|
|
9485
|
-
|
|
9486
|
-
|
|
9487
|
-
|
|
9488
|
-
|
|
9489
|
-
|
|
9490
|
-
|
|
9491
|
-
|
|
9492
|
-
walletId,
|
|
9748
|
+
// Guard against persisting an empty/invalid re-wrap, which would lock the user out of
|
|
9749
|
+
// their device private key (the one mandatory item) under the new password. The type says
|
|
9750
|
+
// this is always defined, but we defend against a runtime contract violation regardless.
|
|
9751
|
+
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
|
|
9752
|
+
if (!reWrappedDevicePrivateKey) {
|
|
9753
|
+
throw new WallabyError({
|
|
9754
|
+
message: 'Failed to re-wrap device private key during password change.',
|
|
9755
|
+
statusCode: 500,
|
|
9756
|
+
errorCode: ErrorResponseCodes.sdk_unknown_error,
|
|
9493
9757
|
});
|
|
9494
9758
|
}
|
|
9495
|
-
|
|
9496
|
-
|
|
9497
|
-
|
|
9498
|
-
|
|
9759
|
+
// Round-trip validate: decrypt the re-wrapped blob with the new key before committing.
|
|
9760
|
+
// Catches a malformed re-encryption before it overwrites the live credential.
|
|
9761
|
+
await this.assertRoundTrip(reWrappedDevicePrivateKey, newCredentialsKeyPair.privateKey, 'device key');
|
|
9762
|
+
const reWrappedSeedPhrase = encryptedSeedPhraseString
|
|
9763
|
+
? await this.cipher.flipEncryptedData({
|
|
9764
|
+
cipherText: safeJsonParse(encryptedSeedPhraseString),
|
|
9499
9765
|
decryptionKey: oldCredentialsKeyPair.privateKey,
|
|
9500
9766
|
encryptionKey: newCredentialsKeyPair.publicKey,
|
|
9501
|
-
})
|
|
9502
|
-
|
|
9503
|
-
|
|
9504
|
-
|
|
9505
|
-
|
|
9506
|
-
if (encryptedBackupShareString) {
|
|
9507
|
-
const parsedBackupShare = safeJsonParse(encryptedBackupShareString);
|
|
9508
|
-
const reWrappedBackupShare = await this.cipher.flipEncryptedData({
|
|
9509
|
-
cipherText: parsedBackupShare,
|
|
9767
|
+
})
|
|
9768
|
+
: null;
|
|
9769
|
+
const reWrappedPrimaryShare = encryptedPrimaryShareString
|
|
9770
|
+
? await this.cipher.flipEncryptedData({
|
|
9771
|
+
cipherText: safeJsonParse(encryptedPrimaryShareString),
|
|
9510
9772
|
decryptionKey: oldCredentialsKeyPair.privateKey,
|
|
9511
9773
|
encryptionKey: newCredentialsKeyPair.publicKey,
|
|
9512
|
-
})
|
|
9513
|
-
|
|
9514
|
-
|
|
9515
|
-
|
|
9516
|
-
|
|
9774
|
+
})
|
|
9775
|
+
: null;
|
|
9776
|
+
const reWrappedBackupShare = encryptedBackupShareString
|
|
9777
|
+
? await this.cipher.flipEncryptedData({
|
|
9778
|
+
cipherText: safeJsonParse(encryptedBackupShareString),
|
|
9779
|
+
decryptionKey: oldCredentialsKeyPair.privateKey,
|
|
9780
|
+
encryptionKey: newCredentialsKeyPair.publicKey,
|
|
9781
|
+
})
|
|
9782
|
+
: null;
|
|
9783
|
+
if (reWrappedSeedPhrase)
|
|
9784
|
+
await this.assertRoundTrip(reWrappedSeedPhrase, newCredentialsKeyPair.privateKey, 'seed phrase');
|
|
9785
|
+
if (reWrappedPrimaryShare)
|
|
9786
|
+
await this.assertRoundTrip(reWrappedPrimaryShare, newCredentialsKeyPair.privateKey, 'primary share');
|
|
9787
|
+
if (reWrappedBackupShare)
|
|
9788
|
+
await this.assertRoundTrip(reWrappedBackupShare, newCredentialsKeyPair.privateKey, 'backup share');
|
|
9789
|
+
await this.localStorageService.commitBatch([
|
|
9790
|
+
{ key: LocalStorageItems.EncryptedDevicePrivateKey, value: reWrappedDevicePrivateKey },
|
|
9791
|
+
...(reWrappedSeedPhrase
|
|
9792
|
+
? [{ key: LocalStorageItems.EncryptedStandardSeedPhrase, value: reWrappedSeedPhrase, walletId }]
|
|
9793
|
+
: []),
|
|
9794
|
+
...(reWrappedPrimaryShare
|
|
9795
|
+
? [{ key: LocalStorageItems.PrimaryDeviceKeyShare, value: reWrappedPrimaryShare, walletId }]
|
|
9796
|
+
: []),
|
|
9797
|
+
...(reWrappedBackupShare ? [{ key: LocalStorageItems.BackupDeviceKeyShare, value: reWrappedBackupShare, walletId }] : []),
|
|
9798
|
+
]);
|
|
9799
|
+
// Reset the rate-limit window on success so a normal change does not count against future ones.
|
|
9800
|
+
await this.localStorageService.delete(V2KeyNames.PasswordResetAttempts);
|
|
9517
9801
|
return true;
|
|
9518
9802
|
}
|
|
9519
9803
|
catch (error) {
|
|
@@ -9566,20 +9850,7 @@ class WalletService extends Base {
|
|
|
9566
9850
|
}
|
|
9567
9851
|
const parsedEncryptedDevicePrivateKey = safeJsonParse(encryptedDevicePrivateKey);
|
|
9568
9852
|
if (this.deviceAuthType === AuthType.Password && input.authenticationOptions.password) {
|
|
9569
|
-
|
|
9570
|
-
await this.handleUpdateToV2({
|
|
9571
|
-
password: input.authenticationOptions.password,
|
|
9572
|
-
walletId: input.walletId,
|
|
9573
|
-
});
|
|
9574
|
-
}
|
|
9575
|
-
catch (error) {
|
|
9576
|
-
logger.error('SDK::WalletService::initAddNewDevice::handleUpdateToV2::error', error);
|
|
9577
|
-
throw new WallabyError({
|
|
9578
|
-
message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
|
|
9579
|
-
statusCode: 500,
|
|
9580
|
-
errorCode: ErrorResponseCodes.sdk_unknown_error,
|
|
9581
|
-
});
|
|
9582
|
-
}
|
|
9853
|
+
await this.migrateToV2Safe({ password: input.authenticationOptions.password, walletId: input.walletId });
|
|
9583
9854
|
}
|
|
9584
9855
|
const storedEncryptedBackupShare = await this.localStorageService.fetch(LocalStorageItems.BackupDeviceKeyShare, { walletId });
|
|
9585
9856
|
if (!storedEncryptedBackupShare) {
|
|
@@ -9677,6 +9948,7 @@ class WalletService extends Base {
|
|
|
9677
9948
|
shares: [backUpResponse.share],
|
|
9678
9949
|
credentialsKeyPair,
|
|
9679
9950
|
encryptedBackupShare: input.encryptedBackupShare,
|
|
9951
|
+
devicePrivateKey: decryptedDevicePrivateKey,
|
|
9680
9952
|
});
|
|
9681
9953
|
return { success: true, reference: backUpResponse.reference };
|
|
9682
9954
|
}
|
|
@@ -9695,20 +9967,7 @@ class WalletService extends Base {
|
|
|
9695
9967
|
});
|
|
9696
9968
|
}
|
|
9697
9969
|
if (this.deviceAuthType === AuthType.Password && input.authenticationOptions.password) {
|
|
9698
|
-
|
|
9699
|
-
await this.handleUpdateToV2({
|
|
9700
|
-
password: input.authenticationOptions.password,
|
|
9701
|
-
walletId: input.walletId,
|
|
9702
|
-
});
|
|
9703
|
-
}
|
|
9704
|
-
catch (error) {
|
|
9705
|
-
logger.error('SDK::WalletService::generateWalletAddresses::handleUpdateToV2::error', error);
|
|
9706
|
-
throw new WallabyError({
|
|
9707
|
-
message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
|
|
9708
|
-
statusCode: 500,
|
|
9709
|
-
errorCode: ErrorResponseCodes.sdk_unknown_error,
|
|
9710
|
-
});
|
|
9711
|
-
}
|
|
9970
|
+
await this.migrateToV2Safe({ password: input.authenticationOptions.password, walletId: input.walletId });
|
|
9712
9971
|
}
|
|
9713
9972
|
try {
|
|
9714
9973
|
const walletOperationAuth = await this.prepareWalletOperationAuth({
|
|
@@ -9733,6 +9992,23 @@ class WalletService extends Base {
|
|
|
9733
9992
|
throw error;
|
|
9734
9993
|
}
|
|
9735
9994
|
}
|
|
9995
|
+
/**
|
|
9996
|
+
* Wraps handleUpdateToV2 with the standard user-facing error. All call sites that gate on
|
|
9997
|
+
* `AuthType.Password` should go through here so the error message stays consistent.
|
|
9998
|
+
*/
|
|
9999
|
+
async migrateToV2Safe({ password, walletId }) {
|
|
10000
|
+
try {
|
|
10001
|
+
await this.handleUpdateToV2({ password, walletId });
|
|
10002
|
+
}
|
|
10003
|
+
catch (error) {
|
|
10004
|
+
logger.error('SDK::WalletService::migrateToV2Safe::error', error);
|
|
10005
|
+
throw new WallabyError({
|
|
10006
|
+
message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
|
|
10007
|
+
statusCode: 500,
|
|
10008
|
+
errorCode: ErrorResponseCodes.sdk_unknown_error,
|
|
10009
|
+
});
|
|
10010
|
+
}
|
|
10011
|
+
}
|
|
9736
10012
|
/**
|
|
9737
10013
|
* Detects and migrates legacy/v1 storage items to v2 format.
|
|
9738
10014
|
* This function should be called in methods that use password as input when v2 items are missing.
|
|
@@ -9741,13 +10017,7 @@ class WalletService extends Base {
|
|
|
9741
10017
|
*/
|
|
9742
10018
|
async handleUpdateToV2({ password, walletId }) {
|
|
9743
10019
|
const migrationStartTime = Date.now();
|
|
9744
|
-
|
|
9745
|
-
throw new WallabyError({
|
|
9746
|
-
message: 'Too many migration attempts. Please try again later.',
|
|
9747
|
-
statusCode: 429,
|
|
9748
|
-
errorCode: ErrorResponseCodes.sdk_too_many_requests,
|
|
9749
|
-
});
|
|
9750
|
-
}
|
|
10020
|
+
await this.assertUnderRateLimit(V2KeyNames.MigrationAttempts, 'Too many migration attempts. Please try again later.');
|
|
9751
10021
|
try {
|
|
9752
10022
|
if (!password) {
|
|
9753
10023
|
throw new WallabyError({
|
|
@@ -9818,7 +10088,7 @@ class WalletService extends Base {
|
|
|
9818
10088
|
}
|
|
9819
10089
|
}
|
|
9820
10090
|
// Increment counter after V2 validation to avoid counting when migration not needed
|
|
9821
|
-
this.
|
|
10091
|
+
await this.recordRateAttempt(V2KeyNames.MigrationAttempts);
|
|
9822
10092
|
let decryptedSeedPhrase;
|
|
9823
10093
|
let decryptedPrivateKey;
|
|
9824
10094
|
// Check for legacy format: `{item}_{userId}`
|
|
@@ -9871,7 +10141,10 @@ class WalletService extends Base {
|
|
|
9871
10141
|
try {
|
|
9872
10142
|
// Decrypt V1 items using storage service method (handles double encryption)
|
|
9873
10143
|
logger.log('Attempting to decrypt V1 items during migration...');
|
|
9874
|
-
logger.log('getV1DecryptedSeedPhrase should be called with password and clientSalt:', {
|
|
10144
|
+
logger.log('getV1DecryptedSeedPhrase should be called with password and clientSalt:', {
|
|
10145
|
+
hasPassword: !!password,
|
|
10146
|
+
hasClientSalt: !!clientSalt,
|
|
10147
|
+
});
|
|
9875
10148
|
decryptedSeedPhrase = await this.localStorageService.getV1DecryptedSeedPhrase(password, clientSalt);
|
|
9876
10149
|
// For V1 format, private key is encrypted with just the password (not salt+password like legacy)
|
|
9877
10150
|
decryptedPrivateKey = await this.localStorageService.getDecryptedV1PrivateKey(password);
|
|
@@ -10098,7 +10371,28 @@ class WalletService extends Base {
|
|
|
10098
10371
|
* @returns { boolean } whether the operation was successful
|
|
10099
10372
|
*/
|
|
10100
10373
|
async convertToPasskey(input) {
|
|
10374
|
+
let passkeyRegistered = false;
|
|
10101
10375
|
try {
|
|
10376
|
+
// Recover an interrupted conversion BEFORE reading any credential blob. A prior attempt may have
|
|
10377
|
+
// already rewrapped EncryptedDevicePrivateKey to passkey form (addNewPasskey persists it outside
|
|
10378
|
+
// this method's atomic commit), which the password can no longer decrypt — and deriving the passkey
|
|
10379
|
+
// key to decrypt it needs the device key itself (circular). The marker stashes the original
|
|
10380
|
+
// password-encrypted device key; restore it so the rest of the flow runs as a fresh conversion.
|
|
10381
|
+
const rawConversionMarker = (await this.localStorageService.fetch(V2KeyNames.CredentialConversionInProgress));
|
|
10382
|
+
const existingConversionMarker = rawConversionMarker
|
|
10383
|
+
? safeJsonParse(rawConversionMarker)
|
|
10384
|
+
: undefined;
|
|
10385
|
+
// Restore the stashed device key whenever a marker carries one — independent of walletId. The
|
|
10386
|
+
// device key is per-user (not wallet-scoped), so a conversion interrupted on a different wallet
|
|
10387
|
+
// leaves the shared device key passkey-wrapped too. Restoring is idempotent (rewrites the
|
|
10388
|
+
// original password-encrypted blob) and stops a second wallet's conversion from destroying the
|
|
10389
|
+
// first's recovery state. v2 only — a v1 wallet's untouched v1 key still decrypts.
|
|
10390
|
+
if (existingConversionMarker === null || existingConversionMarker === void 0 ? void 0 : existingConversionMarker.encryptedDevicePrivateKey) {
|
|
10391
|
+
await this.localStorageService.save(LocalStorageItems.EncryptedDevicePrivateKey, existingConversionMarker.encryptedDevicePrivateKey);
|
|
10392
|
+
}
|
|
10393
|
+
if ((existingConversionMarker === null || existingConversionMarker === void 0 ? void 0 : existingConversionMarker.walletId) === input.walletId) {
|
|
10394
|
+
logger.info('SDK::WalletService::convertToPasskey::resuming interrupted conversion');
|
|
10395
|
+
}
|
|
10102
10396
|
const v2EncryptedPriv = await this.localStorageService.fetch(LocalStorageItems.EncryptedDevicePrivateKey);
|
|
10103
10397
|
const v2EncryptedSeed = await this.localStorageService.fetch(LocalStorageItems.EncryptedStandardSeedPhrase, {
|
|
10104
10398
|
walletId: input.walletId,
|
|
@@ -10147,6 +10441,10 @@ class WalletService extends Base {
|
|
|
10147
10441
|
});
|
|
10148
10442
|
}
|
|
10149
10443
|
const clientPublicKey = publicKeyByPrivateKey(decryptedClientAuthPrivKey);
|
|
10444
|
+
// Write-ahead marker: set before the unrevocable passkey registration so an interrupted
|
|
10445
|
+
// conversion can be resumed on the next attempt. Stash the original password-encrypted device
|
|
10446
|
+
// key so resume survives addNewPasskey rewrapping the stored device key to passkey form.
|
|
10447
|
+
await this.localStorageService.save(V2KeyNames.CredentialConversionInProgress, Object.assign({ walletId: input.walletId }, (v2EncryptedPriv ? { encryptedDevicePrivateKey: v2EncryptedPriv } : {})));
|
|
10150
10448
|
const authentication = await this.passkeyService.addNewPasskey({
|
|
10151
10449
|
deviceKeyPair: {
|
|
10152
10450
|
publicKey: clientPublicKey,
|
|
@@ -10154,6 +10452,7 @@ class WalletService extends Base {
|
|
|
10154
10452
|
},
|
|
10155
10453
|
getSignature: this.authService.getSignature.bind(this),
|
|
10156
10454
|
});
|
|
10455
|
+
passkeyRegistered = true;
|
|
10157
10456
|
const prfValue = authentication.prfValue;
|
|
10158
10457
|
if (!prfValue || !(prfValue instanceof Uint8Array) || prfValue.length === 0) {
|
|
10159
10458
|
logger.error('SDK::WalletService::convertToPasskey::prfValue is required and must be a non-empty Uint8Array');
|
|
@@ -10250,8 +10549,13 @@ class WalletService extends Base {
|
|
|
10250
10549
|
storeOneKeyShareWithWallaby: true,
|
|
10251
10550
|
},
|
|
10252
10551
|
});
|
|
10253
|
-
//
|
|
10254
|
-
|
|
10552
|
+
// idempotent — on retry (marker present, primary now passkey-encrypted so
|
|
10553
|
+
// decryptedPrimaryShare is undefined → Branch A re-enters), handleImportWallet re-shares
|
|
10554
|
+
// safely; this atomic delete clears the stale seed + marker together.
|
|
10555
|
+
await this.localStorageService.commitBatch([], [
|
|
10556
|
+
{ key: LocalStorageItems.EncryptedStandardSeedPhrase, walletId: input.walletId },
|
|
10557
|
+
{ key: V2KeyNames.CredentialConversionInProgress },
|
|
10558
|
+
]);
|
|
10255
10559
|
logger.info('SDK::WalletService::convertToPasskey::Wallet imported and converted successfully, old seed phrase removed');
|
|
10256
10560
|
return { authentication, seedPhrase: decryptedSeedPhrase };
|
|
10257
10561
|
}
|
|
@@ -10269,6 +10573,24 @@ class WalletService extends Base {
|
|
|
10269
10573
|
privateKey: decryptedClientAuthPrivKey,
|
|
10270
10574
|
},
|
|
10271
10575
|
});
|
|
10576
|
+
// assertRoundTrip below only strips the outer (passkey) layer — validate the inner (device key) layer here.
|
|
10577
|
+
const outerDecrypted = await this.cipher.decrypt({
|
|
10578
|
+
cipherText: encryptedPrimaryShare,
|
|
10579
|
+
decryptionKey: passkeyDerivedKeyPair.privateKey,
|
|
10580
|
+
});
|
|
10581
|
+
const innerDecrypted = outerDecrypted
|
|
10582
|
+
? await this.cipher.decrypt({
|
|
10583
|
+
cipherText: safeJsonParse(outerDecrypted),
|
|
10584
|
+
decryptionKey: decryptedClientAuthPrivKey,
|
|
10585
|
+
})
|
|
10586
|
+
: null;
|
|
10587
|
+
if (innerDecrypted !== decryptedPrimaryShare) {
|
|
10588
|
+
throw new WallabyError({
|
|
10589
|
+
message: 'Re-wrap validation failed for primary share: inner layer round-trip mismatch. Aborting to prevent credential corruption.',
|
|
10590
|
+
statusCode: 500,
|
|
10591
|
+
errorCode: ErrorResponseCodes.sdk_unknown_error,
|
|
10592
|
+
});
|
|
10593
|
+
}
|
|
10272
10594
|
convertedShares.push({
|
|
10273
10595
|
key: V2KeyNames.PrimaryDeviceKeyShare,
|
|
10274
10596
|
value: encryptedPrimaryShare,
|
|
@@ -10287,9 +10609,16 @@ class WalletService extends Base {
|
|
|
10287
10609
|
walletId: input.walletId,
|
|
10288
10610
|
});
|
|
10289
10611
|
}
|
|
10290
|
-
|
|
10612
|
+
// Round-trip validate each re-encrypted blob (outer layer only) before writing.
|
|
10613
|
+
// A failed decrypt here means re-encryption produced an unreadable blob — abort before overwriting live credentials.
|
|
10614
|
+
for (const share of convertedShares) {
|
|
10615
|
+
await this.assertRoundTrip(share.value, passkeyDerivedKeyPair.privateKey, share.key);
|
|
10616
|
+
}
|
|
10617
|
+
await this.localStorageService.commitBatch(convertedShares, [
|
|
10618
|
+
...(v2EncryptedSeed ? [{ key: LocalStorageItems.EncryptedStandardSeedPhrase, walletId: input.walletId }] : []),
|
|
10619
|
+
{ key: V2KeyNames.CredentialConversionInProgress },
|
|
10620
|
+
]);
|
|
10291
10621
|
if (v2EncryptedSeed) {
|
|
10292
|
-
await this.localStorageService.delete(LocalStorageItems.EncryptedStandardSeedPhrase, { walletId: input.walletId });
|
|
10293
10622
|
logger.info('SDK::WalletService::convertToPasskey::Seed phrase removed from device storage after conversion to passkey');
|
|
10294
10623
|
}
|
|
10295
10624
|
if (!decryptedSeedPhrase && decryptedPrimaryShare) {
|
|
@@ -10332,10 +10661,33 @@ class WalletService extends Base {
|
|
|
10332
10661
|
}
|
|
10333
10662
|
catch (error) {
|
|
10334
10663
|
logger.error('SDK::WalletService::convertToPasskey::error', error);
|
|
10664
|
+
// Only clear the marker if the passkey was not yet registered. After registration the
|
|
10665
|
+
// marker must survive for roll-forward on the next attempt.
|
|
10666
|
+
if (!passkeyRegistered) {
|
|
10667
|
+
await this.localStorageService.delete(V2KeyNames.CredentialConversionInProgress);
|
|
10668
|
+
}
|
|
10335
10669
|
throw error;
|
|
10336
10670
|
}
|
|
10337
10671
|
}
|
|
10672
|
+
// shared guard — decrypt-tests a re-wrapped blob before any write so a malformed
|
|
10673
|
+
// re-encryption is caught before it overwrites the live credential.
|
|
10674
|
+
async assertRoundTrip(blob, decryptionKey, label) {
|
|
10675
|
+
try {
|
|
10676
|
+
await this.cipher.decrypt({ cipherText: blob, decryptionKey });
|
|
10677
|
+
}
|
|
10678
|
+
catch (_a) {
|
|
10679
|
+
throw new WallabyError({
|
|
10680
|
+
message: `Re-wrap validation failed for ${label}: decryption of the re-encrypted blob failed. Aborting to prevent credential corruption.`,
|
|
10681
|
+
statusCode: 500,
|
|
10682
|
+
errorCode: ErrorResponseCodes.sdk_unknown_error,
|
|
10683
|
+
});
|
|
10684
|
+
}
|
|
10685
|
+
}
|
|
10338
10686
|
}
|
|
10687
|
+
// soft client-side guardrail against runaway retries; server-side rate limiting is the real control.
|
|
10688
|
+
// Counters are persisted (sliding window) so rebuilding the service no longer resets them. Tune freely.
|
|
10689
|
+
WalletService.RATE_LIMIT_MAX = 5;
|
|
10690
|
+
WalletService.RATE_LIMIT_WINDOW_MS = 30 * 60000; // 30 min
|
|
10339
10691
|
__decorate([
|
|
10340
10692
|
WithLock('create'),
|
|
10341
10693
|
__metadata("design:type", Function),
|
|
@@ -10355,7 +10707,7 @@ __decorate([
|
|
|
10355
10707
|
__metadata("design:returntype", Promise)
|
|
10356
10708
|
], WalletService.prototype, "recover", null);
|
|
10357
10709
|
__decorate([
|
|
10358
|
-
WithLock('
|
|
10710
|
+
WithLock('credential-rewrap'),
|
|
10359
10711
|
__metadata("design:type", Function),
|
|
10360
10712
|
__metadata("design:paramtypes", [Object]),
|
|
10361
10713
|
__metadata("design:returntype", Promise)
|
|
@@ -10366,6 +10718,12 @@ __decorate([
|
|
|
10366
10718
|
__metadata("design:paramtypes", [Object]),
|
|
10367
10719
|
__metadata("design:returntype", Promise)
|
|
10368
10720
|
], WalletService.prototype, "handleUpdateToV2", null);
|
|
10721
|
+
__decorate([
|
|
10722
|
+
WithLock('credential-rewrap'),
|
|
10723
|
+
__metadata("design:type", Function),
|
|
10724
|
+
__metadata("design:paramtypes", [Object]),
|
|
10725
|
+
__metadata("design:returntype", Promise)
|
|
10726
|
+
], WalletService.prototype, "convertToPasskey", null);
|
|
10369
10727
|
|
|
10370
10728
|
class WalletDataService extends Base {
|
|
10371
10729
|
constructor(config) {
|
|
@@ -10618,20 +10976,7 @@ class WalletDataService extends Base {
|
|
|
10618
10976
|
});
|
|
10619
10977
|
}
|
|
10620
10978
|
if (this.deviceAuthType === AuthType.Password && authenticationOptions.password) {
|
|
10621
|
-
|
|
10622
|
-
await this.walletService.handleUpdateToV2({
|
|
10623
|
-
password: authenticationOptions.password,
|
|
10624
|
-
walletId: walletId,
|
|
10625
|
-
});
|
|
10626
|
-
}
|
|
10627
|
-
catch (error) {
|
|
10628
|
-
logger.error('SDK::WalletDataService::addNewChainAndTokenToWallet::handleUpdateToV2::error', error);
|
|
10629
|
-
throw new WallabyError({
|
|
10630
|
-
message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
|
|
10631
|
-
statusCode: 500,
|
|
10632
|
-
errorCode: ErrorResponseCodes.sdk_unknown_error,
|
|
10633
|
-
});
|
|
10634
|
-
}
|
|
10979
|
+
await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
|
|
10635
10980
|
}
|
|
10636
10981
|
try {
|
|
10637
10982
|
const addressInfo = await this.walletService.generateWalletAddresses({
|
|
@@ -10832,179 +11177,6 @@ class Utils extends Base {
|
|
|
10832
11177
|
}
|
|
10833
11178
|
}
|
|
10834
11179
|
|
|
10835
|
-
const MerchantsRoutes = {
|
|
10836
|
-
create: {
|
|
10837
|
-
fullPath: '/merchants',
|
|
10838
|
-
method: RequestMethod.Post,
|
|
10839
|
-
requiresAccessToken: false,
|
|
10840
|
-
},
|
|
10841
|
-
update: {
|
|
10842
|
-
fullPath: ({ merchantId }) => `/merchants/${merchantId}`,
|
|
10843
|
-
method: RequestMethod.Put,
|
|
10844
|
-
requiresAccessToken: false,
|
|
10845
|
-
},
|
|
10846
|
-
getMerchantData: {
|
|
10847
|
-
fullPath: ({ merchantId }) => `/merchants/${merchantId}`,
|
|
10848
|
-
method: RequestMethod.Get,
|
|
10849
|
-
requiresAccessToken: false,
|
|
10850
|
-
},
|
|
10851
|
-
list: {
|
|
10852
|
-
fullPath: '/merchants',
|
|
10853
|
-
method: RequestMethod.Get,
|
|
10854
|
-
requiresAccessToken: false,
|
|
10855
|
-
},
|
|
10856
|
-
getAssets: {
|
|
10857
|
-
fullPath: () => `/users/merchant/assets`,
|
|
10858
|
-
method: RequestMethod.Get,
|
|
10859
|
-
requiresAccessToken: true,
|
|
10860
|
-
},
|
|
10861
|
-
addAsset: {
|
|
10862
|
-
fullPath: ({ merchantId, configId }) => `/merchants/${merchantId}/assets/${configId}`,
|
|
10863
|
-
method: RequestMethod.Post,
|
|
10864
|
-
requiresAccessToken: false,
|
|
10865
|
-
},
|
|
10866
|
-
deleteAsset: {
|
|
10867
|
-
fullPath: ({ merchantId, configId }) => `/merchants/${merchantId}/assets/${configId}`,
|
|
10868
|
-
method: RequestMethod.Delete,
|
|
10869
|
-
requiresAccessToken: false,
|
|
10870
|
-
},
|
|
10871
|
-
};
|
|
10872
|
-
|
|
10873
|
-
class Merchants extends Base {
|
|
10874
|
-
constructor(config) {
|
|
10875
|
-
super(config);
|
|
10876
|
-
}
|
|
10877
|
-
/**
|
|
10878
|
-
* @description
|
|
10879
|
-
* Retrieves the merchant ID from access token `aud` claim.
|
|
10880
|
-
* Even though merchantId is possibly undefined. If an access token is not stored on device, the request will most likely
|
|
10881
|
-
* not have it in headers and will fail with 401 regardless.
|
|
10882
|
-
*
|
|
10883
|
-
* @returns { string | undefined } Merchant ID
|
|
10884
|
-
*/
|
|
10885
|
-
async _getMerchantId() {
|
|
10886
|
-
const accessToken = await this.localStorageService.fetch(LocalStorageItems.AccessToken);
|
|
10887
|
-
if (!accessToken)
|
|
10888
|
-
return;
|
|
10889
|
-
const jwtDecoded = jwtDecode(accessToken);
|
|
10890
|
-
return jwtDecoded.aud;
|
|
10891
|
-
}
|
|
10892
|
-
/**
|
|
10893
|
-
*
|
|
10894
|
-
* @public
|
|
10895
|
-
* List of all merchants in the system
|
|
10896
|
-
* @returns { ListMerchantsResponse } Array of all merchants
|
|
10897
|
-
*/
|
|
10898
|
-
async list() {
|
|
10899
|
-
try {
|
|
10900
|
-
const response = await this.request(MerchantsRoutes.list, {
|
|
10901
|
-
payload: {},
|
|
10902
|
-
});
|
|
10903
|
-
return response;
|
|
10904
|
-
}
|
|
10905
|
-
catch (error) {
|
|
10906
|
-
logger.error('SDK::Merchants::list::error', error);
|
|
10907
|
-
return Promise.reject(error);
|
|
10908
|
-
}
|
|
10909
|
-
}
|
|
10910
|
-
/**
|
|
10911
|
-
*
|
|
10912
|
-
* @public
|
|
10913
|
-
* Allows to create a new merchant
|
|
10914
|
-
* @returns { Merchant } Merchant data
|
|
10915
|
-
*/
|
|
10916
|
-
async create({ name }) {
|
|
10917
|
-
try {
|
|
10918
|
-
const response = await this.request(MerchantsRoutes.create, {
|
|
10919
|
-
payload: { name },
|
|
10920
|
-
});
|
|
10921
|
-
return response;
|
|
10922
|
-
}
|
|
10923
|
-
catch (error) {
|
|
10924
|
-
logger.error('SDK::Merchants::list::error', error);
|
|
10925
|
-
return Promise.reject(error);
|
|
10926
|
-
}
|
|
10927
|
-
}
|
|
10928
|
-
/**
|
|
10929
|
-
*
|
|
10930
|
-
* @public
|
|
10931
|
-
* Allows to update merchant data
|
|
10932
|
-
* @returns { Merchant } Merchant data
|
|
10933
|
-
*/
|
|
10934
|
-
async update({ name, status }) {
|
|
10935
|
-
try {
|
|
10936
|
-
const merchantId = await this._getMerchantId();
|
|
10937
|
-
const response = await this.request(MerchantsRoutes.update, {
|
|
10938
|
-
payload: { merchantId, name, status },
|
|
10939
|
-
});
|
|
10940
|
-
return response;
|
|
10941
|
-
}
|
|
10942
|
-
catch (error) {
|
|
10943
|
-
logger.error('SDK::Merchants::list::error', error);
|
|
10944
|
-
return Promise.reject(error);
|
|
10945
|
-
}
|
|
10946
|
-
}
|
|
10947
|
-
/**
|
|
10948
|
-
*
|
|
10949
|
-
* @public
|
|
10950
|
-
* @returns { Merchant } Merchant data
|
|
10951
|
-
*/
|
|
10952
|
-
async getMerchantData() {
|
|
10953
|
-
try {
|
|
10954
|
-
const merchantId = await this._getMerchantId();
|
|
10955
|
-
const response = await this.request(MerchantsRoutes.getMerchantData, {
|
|
10956
|
-
payload: { merchantId },
|
|
10957
|
-
});
|
|
10958
|
-
return response.merchant;
|
|
10959
|
-
}
|
|
10960
|
-
catch (error) {
|
|
10961
|
-
logger.error('SDK::Merchants::list::error', error);
|
|
10962
|
-
return Promise.reject(error);
|
|
10963
|
-
}
|
|
10964
|
-
}
|
|
10965
|
-
/**
|
|
10966
|
-
*
|
|
10967
|
-
* @public
|
|
10968
|
-
* @returns { MerchantAsset[] } List of merchant assets
|
|
10969
|
-
*/
|
|
10970
|
-
async getAssets() {
|
|
10971
|
-
try {
|
|
10972
|
-
const response = await this.request(MerchantsRoutes.getAssets);
|
|
10973
|
-
return response.merchantAssets;
|
|
10974
|
-
}
|
|
10975
|
-
catch (error) {
|
|
10976
|
-
logger.error('SDK::Merchants::list::error', error);
|
|
10977
|
-
return Promise.reject(error);
|
|
10978
|
-
}
|
|
10979
|
-
}
|
|
10980
|
-
async addAsset({ configId }) {
|
|
10981
|
-
try {
|
|
10982
|
-
const merchantId = await this._getMerchantId();
|
|
10983
|
-
const response = await this.request(MerchantsRoutes.addAsset, {
|
|
10984
|
-
payload: { merchantId, configId },
|
|
10985
|
-
});
|
|
10986
|
-
return response;
|
|
10987
|
-
}
|
|
10988
|
-
catch (error) {
|
|
10989
|
-
logger.error('SDK::Merchants::list::error', error);
|
|
10990
|
-
return Promise.reject(error);
|
|
10991
|
-
}
|
|
10992
|
-
}
|
|
10993
|
-
async deleteAsset({ configId }) {
|
|
10994
|
-
try {
|
|
10995
|
-
const merchantId = await this._getMerchantId();
|
|
10996
|
-
const response = await this.request(MerchantsRoutes.deleteAsset, {
|
|
10997
|
-
payload: { merchantId, configId },
|
|
10998
|
-
});
|
|
10999
|
-
return response;
|
|
11000
|
-
}
|
|
11001
|
-
catch (error) {
|
|
11002
|
-
logger.error('SDK::Merchants::list::error', error);
|
|
11003
|
-
return Promise.reject(error);
|
|
11004
|
-
}
|
|
11005
|
-
}
|
|
11006
|
-
}
|
|
11007
|
-
|
|
11008
11180
|
/**
|
|
11009
11181
|
* HttpApi provides direct access to all REST API endpoints.
|
|
11010
11182
|
* This class extends the Base class and includes the generated API client
|
|
@@ -11085,20 +11257,7 @@ class Swap extends Base {
|
|
|
11085
11257
|
try {
|
|
11086
11258
|
// Only attempt migration if we have password auth and V2 storage might be incomplete
|
|
11087
11259
|
if (this.deviceAuthType === AuthType.Password && authenticationOptions.password) {
|
|
11088
|
-
|
|
11089
|
-
await this.walletService.handleUpdateToV2({
|
|
11090
|
-
password: authenticationOptions.password,
|
|
11091
|
-
walletId: walletId,
|
|
11092
|
-
});
|
|
11093
|
-
}
|
|
11094
|
-
catch (error) {
|
|
11095
|
-
logger.error('SDK::Swap::executeSwap::handleUpdateToV2::error', error);
|
|
11096
|
-
throw new WallabyError({
|
|
11097
|
-
message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
|
|
11098
|
-
statusCode: 500,
|
|
11099
|
-
errorCode: ErrorResponseCodes.sdk_unknown_error,
|
|
11100
|
-
});
|
|
11101
|
-
}
|
|
11260
|
+
await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
|
|
11102
11261
|
}
|
|
11103
11262
|
const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareSwapAuth(authenticationOptions, walletId);
|
|
11104
11263
|
let swapResponse;
|
|
@@ -11127,6 +11286,7 @@ class Swap extends Base {
|
|
|
11127
11286
|
});
|
|
11128
11287
|
}
|
|
11129
11288
|
else {
|
|
11289
|
+
// Unreachable in practice: prepareSwapAuth throws sdk_seed_phrase_not_found before we get here; kept as a defensive guard.
|
|
11130
11290
|
throw new WallabyError({
|
|
11131
11291
|
message: 'No valid seed option found on this device.',
|
|
11132
11292
|
statusCode: 400,
|
|
@@ -11292,6 +11452,27 @@ const sanitizeSuiObjectId = (objectId) => {
|
|
|
11292
11452
|
return objectId.split('::')[0];
|
|
11293
11453
|
};
|
|
11294
11454
|
|
|
11455
|
+
/**
|
|
11456
|
+
* Extracts the asset symbol from a fully-qualified Sui coin type.
|
|
11457
|
+
*
|
|
11458
|
+
* A Sui coin type has the shape `<package>::<module>::<TYPE>`, where the final
|
|
11459
|
+
* segment is the coin's struct name and doubles as its symbol.
|
|
11460
|
+
*
|
|
11461
|
+
* @param objectId - The Sui object id / coin type. Example input:
|
|
11462
|
+
* "0xc91acfb75009c5ff2fd57c54f3caaee12ad1fbe997681334adc0b574fc277a07::icorgi::ICORGI"
|
|
11463
|
+
* @returns The symbol (e.g. "ICORGI"), or undefined when the id carries no
|
|
11464
|
+
* `::module::TYPE` suffix to derive it from.
|
|
11465
|
+
*/
|
|
11466
|
+
const extractSuiAssetSymbol = (objectId) => {
|
|
11467
|
+
var _a;
|
|
11468
|
+
if (!objectId || !objectId.includes('::')) {
|
|
11469
|
+
return undefined;
|
|
11470
|
+
}
|
|
11471
|
+
const segments = objectId.split('::');
|
|
11472
|
+
const symbol = (_a = segments[segments.length - 1]) === null || _a === void 0 ? void 0 : _a.trim();
|
|
11473
|
+
return symbol || undefined;
|
|
11474
|
+
};
|
|
11475
|
+
|
|
11295
11476
|
class System extends Base {
|
|
11296
11477
|
constructor(config) {
|
|
11297
11478
|
super(config);
|
|
@@ -11380,6 +11561,9 @@ class System extends Base {
|
|
|
11380
11561
|
* @param {BlockchainName} blockchain - The name of the blockchain.
|
|
11381
11562
|
* @param {string} contractAddress - The contract address of the token (optional for non-SUI blockchains).
|
|
11382
11563
|
* @param {string} suiObjectId - The SUI object ID of the token (optional for SUI blockchain).
|
|
11564
|
+
* @param {string} assetSymbol - The asset symbol; disambiguates new SUI assets. For SUI it is
|
|
11565
|
+
* optional: when omitted, it is derived from the `::module::TYPE` suffix of `suiObjectId`
|
|
11566
|
+
* (which is otherwise trimmed off before the request is sent).
|
|
11383
11567
|
*
|
|
11384
11568
|
* @returns {Promise<{ decimals: number; symbol: string; name: string; tokenContractAddress: string }>} A promise that resolves to an object containing token information.
|
|
11385
11569
|
*
|
|
@@ -11388,18 +11572,19 @@ class System extends Base {
|
|
|
11388
11572
|
* @throws Will throw an error if `contractAddress` is not provided for non-SUI blockchains.
|
|
11389
11573
|
* @throws Will throw an error if the response is invalid or contains an error.
|
|
11390
11574
|
*/
|
|
11391
|
-
async fetchTokenInfo({ blockchain, contractAddress, suiObjectId, }) {
|
|
11575
|
+
async fetchTokenInfo({ blockchain, contractAddress, suiObjectId, assetSymbol, }) {
|
|
11392
11576
|
try {
|
|
11393
11577
|
const validatedContractAddress = this.validateContractAddress({
|
|
11394
11578
|
blockchain,
|
|
11395
11579
|
contractAddress,
|
|
11396
11580
|
suiObjectId,
|
|
11397
11581
|
});
|
|
11582
|
+
// For SUI, the coin symbol is the last segment of the coin type
|
|
11583
|
+
// (`<package>::<module>::<TYPE>`), which sanitizeSuiObjectId strips out.
|
|
11584
|
+
// Derive it so callers don't have to pass assetSymbol explicitly.
|
|
11585
|
+
const resolvedAssetSymbol = assetSymbol !== null && assetSymbol !== void 0 ? assetSymbol : (blockchain === BlockchainName.Sui ? extractSuiAssetSymbol(suiObjectId) : undefined);
|
|
11398
11586
|
const response = await this.request(SystemRoutes.fetchTokenInfo, {
|
|
11399
|
-
queryParams: {
|
|
11400
|
-
chainName: blockchain,
|
|
11401
|
-
tokenContractAddress: validatedContractAddress,
|
|
11402
|
-
},
|
|
11587
|
+
queryParams: Object.assign({ chainName: blockchain, tokenContractAddress: validatedContractAddress }, (resolvedAssetSymbol ? { assetSymbol: resolvedAssetSymbol } : {})),
|
|
11403
11588
|
});
|
|
11404
11589
|
return response;
|
|
11405
11590
|
}
|
|
@@ -11548,27 +11733,54 @@ class Transactions extends Base {
|
|
|
11548
11733
|
/**
|
|
11549
11734
|
*
|
|
11550
11735
|
* @public
|
|
11551
|
-
* @param {
|
|
11552
|
-
* @
|
|
11553
|
-
* @param {TokenStandard} tokenStandard an optional param used when dealing with non native assets
|
|
11554
|
-
* @returns {Promise<{ address: string; transactions: Transaction[] }>}
|
|
11736
|
+
* @param {GetTransactionsParams} params - Query parameters for filtering and paginating transactions
|
|
11737
|
+
* @returns {GetTransactionsResponseDto} Paginated list of transactions matching the given criteria
|
|
11555
11738
|
*/
|
|
11556
|
-
async getTransactions(
|
|
11739
|
+
async getTransactions(params) {
|
|
11557
11740
|
try {
|
|
11558
|
-
|
|
11559
|
-
|
|
11560
|
-
address,
|
|
11561
|
-
tokenSymbol: symbol,
|
|
11562
|
-
tokenType: tokenStandard,
|
|
11563
|
-
},
|
|
11741
|
+
return await this.request(TransactionsRoutes.getTransactions, {
|
|
11742
|
+
queryParams: params,
|
|
11564
11743
|
});
|
|
11565
|
-
return response;
|
|
11566
11744
|
}
|
|
11567
11745
|
catch (error) {
|
|
11568
11746
|
logger.error('SDK::Transactions::getTransactions::error', error);
|
|
11569
11747
|
throw error;
|
|
11570
11748
|
}
|
|
11571
11749
|
}
|
|
11750
|
+
/**
|
|
11751
|
+
*
|
|
11752
|
+
* @public
|
|
11753
|
+
* @param {GetRestrictionParams} params - Parameters to detect transfer restrictions (addresses, asset, value)
|
|
11754
|
+
* - {string} fromAddress
|
|
11755
|
+
* - {string} toAddress
|
|
11756
|
+
* - {string} amount
|
|
11757
|
+
* - [string] assetId
|
|
11758
|
+
* - [string] contractAddress
|
|
11759
|
+
* - [BlockchainName] blockchainName
|
|
11760
|
+
* @returns {Promise<DetectRestrictionResponseDto>}
|
|
11761
|
+
* Detection result; when transfer is blocked, also includes the human-readable restriction message and a boolean canTransfer
|
|
11762
|
+
*/
|
|
11763
|
+
async getRestriction(params) {
|
|
11764
|
+
try {
|
|
11765
|
+
const hasAssetId = Boolean(params.assetId);
|
|
11766
|
+
const hasContractAndChain = Boolean(params.contractAddress && params.blockchainName);
|
|
11767
|
+
if (!hasAssetId && !hasContractAndChain) {
|
|
11768
|
+
throw new WallabyError({
|
|
11769
|
+
message: 'Either assetId or both contractAddress and blockchainName must be provided.',
|
|
11770
|
+
statusCode: 400,
|
|
11771
|
+
errorCode: ErrorResponseCodes.sdk_missing_parameter,
|
|
11772
|
+
});
|
|
11773
|
+
}
|
|
11774
|
+
const restrictionData = await this.request(TransactionsRoutes.restriction, {
|
|
11775
|
+
queryParams: Object.assign(Object.assign(Object.assign({ fromAddress: params.fromAddress, toAddress: params.toAddress, amount: params.amount }, (params.assetId && { assetId: params.assetId })), (params.contractAddress && { contractAddress: params.contractAddress })), (params.blockchainName && { blockchainName: params.blockchainName })),
|
|
11776
|
+
});
|
|
11777
|
+
return restrictionData;
|
|
11778
|
+
}
|
|
11779
|
+
catch (error) {
|
|
11780
|
+
logger.error('SDK::Transactions::getRestriction::error', error);
|
|
11781
|
+
throw error;
|
|
11782
|
+
}
|
|
11783
|
+
}
|
|
11572
11784
|
/**
|
|
11573
11785
|
*
|
|
11574
11786
|
* @public
|
|
@@ -11586,20 +11798,7 @@ class Transactions extends Base {
|
|
|
11586
11798
|
try {
|
|
11587
11799
|
// Only attempt migration if we have password auth and V2 storage might be incomplete
|
|
11588
11800
|
if (this.deviceAuthType === AuthType.Password && authenticationOptions.password) {
|
|
11589
|
-
|
|
11590
|
-
await this.walletService.handleUpdateToV2({
|
|
11591
|
-
password: authenticationOptions.password,
|
|
11592
|
-
walletId: walletId,
|
|
11593
|
-
});
|
|
11594
|
-
}
|
|
11595
|
-
catch (error) {
|
|
11596
|
-
logger.error('SDK::Transactions::transfer::handleUpdateToV2::error', error);
|
|
11597
|
-
throw new WallabyError({
|
|
11598
|
-
message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
|
|
11599
|
-
statusCode: 500,
|
|
11600
|
-
errorCode: ErrorResponseCodes.sdk_unknown_error,
|
|
11601
|
-
});
|
|
11602
|
-
}
|
|
11801
|
+
await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
|
|
11603
11802
|
}
|
|
11604
11803
|
const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareTransactionAuth(authenticationOptions, walletId);
|
|
11605
11804
|
let transferResponse;
|
|
@@ -11687,20 +11886,7 @@ class Transactions extends Base {
|
|
|
11687
11886
|
}
|
|
11688
11887
|
// Only attempt migration if we have password auth and V2 storage might be incomplete
|
|
11689
11888
|
if (this.deviceAuthType === AuthType.Password && authenticationOptions.password) {
|
|
11690
|
-
|
|
11691
|
-
await this.walletService.handleUpdateToV2({
|
|
11692
|
-
password: authenticationOptions.password,
|
|
11693
|
-
walletId: walletId,
|
|
11694
|
-
});
|
|
11695
|
-
}
|
|
11696
|
-
catch (error) {
|
|
11697
|
-
logger.error('SDK::Transactions::createAllowance::handleUpdateToV2::error', error);
|
|
11698
|
-
throw new WallabyError({
|
|
11699
|
-
message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
|
|
11700
|
-
statusCode: 500,
|
|
11701
|
-
errorCode: ErrorResponseCodes.sdk_unknown_error,
|
|
11702
|
-
});
|
|
11703
|
-
}
|
|
11889
|
+
await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
|
|
11704
11890
|
}
|
|
11705
11891
|
const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareTransactionAuth(authenticationOptions, walletId);
|
|
11706
11892
|
const { message, signature } = signatureMessage;
|
|
@@ -11765,20 +11951,7 @@ class Transactions extends Base {
|
|
|
11765
11951
|
try {
|
|
11766
11952
|
// Only attempt migration if we have password auth and V2 storage might be incomplete
|
|
11767
11953
|
if (this.deviceAuthType === AuthType.Password && authenticationOptions.password) {
|
|
11768
|
-
|
|
11769
|
-
await this.walletService.handleUpdateToV2({
|
|
11770
|
-
password: authenticationOptions.password,
|
|
11771
|
-
walletId: walletId,
|
|
11772
|
-
});
|
|
11773
|
-
}
|
|
11774
|
-
catch (error) {
|
|
11775
|
-
logger.error('SDK::Transactions::resolvePendingTransaction::handleUpdateToV2::error', error);
|
|
11776
|
-
throw new WallabyError({
|
|
11777
|
-
message: 'Error accessing user wallet on this device. Please ensure the password is correct and try again.',
|
|
11778
|
-
statusCode: 500,
|
|
11779
|
-
errorCode: ErrorResponseCodes.sdk_unknown_error,
|
|
11780
|
-
});
|
|
11781
|
-
}
|
|
11954
|
+
await this.walletService.migrateToV2Safe({ password: authenticationOptions.password, walletId });
|
|
11782
11955
|
}
|
|
11783
11956
|
const { deviceAuthPublicKey, signatureMessage, readyForTransportSeedPhrase, sharesEncryptedWithWallabyPubKey, hasShares } = await this.prepareTransactionAuth(authenticationOptions, walletId);
|
|
11784
11957
|
if (!readyForTransportSeedPhrase && !hasShares) {
|
|
@@ -11903,6 +12076,12 @@ class Transactions extends Base {
|
|
|
11903
12076
|
});
|
|
11904
12077
|
}
|
|
11905
12078
|
}
|
|
12079
|
+
__decorate([
|
|
12080
|
+
WithLock('transaction-restriction-message'),
|
|
12081
|
+
__metadata("design:type", Function),
|
|
12082
|
+
__metadata("design:paramtypes", [Object]),
|
|
12083
|
+
__metadata("design:returntype", Promise)
|
|
12084
|
+
], Transactions.prototype, "getRestriction", null);
|
|
11906
12085
|
__decorate([
|
|
11907
12086
|
WithLock('transfer'),
|
|
11908
12087
|
__metadata("design:type", Function),
|
|
@@ -11945,7 +12124,6 @@ class Wallaby {
|
|
|
11945
12124
|
this.system = new System(config);
|
|
11946
12125
|
this.transactions = new Transactions(config);
|
|
11947
12126
|
this.swap = new Swap(config);
|
|
11948
|
-
this.merchants = new Merchants(config);
|
|
11949
12127
|
this.httpApi = new HttpApi(config);
|
|
11950
12128
|
}
|
|
11951
12129
|
get version() {
|