@metamask-previews/profile-sync-controller 12.0.0-preview-cabccf7 → 12.0.0-preview-7a1bf6a5
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/controllers/authentication/auth-snap-requests.cjs +37 -1
- package/dist/controllers/authentication/auth-snap-requests.cjs.map +1 -1
- package/dist/controllers/authentication/auth-snap-requests.d.cts +13 -0
- package/dist/controllers/authentication/auth-snap-requests.d.cts.map +1 -1
- package/dist/controllers/authentication/auth-snap-requests.d.mts +13 -0
- package/dist/controllers/authentication/auth-snap-requests.d.mts.map +1 -1
- package/dist/controllers/authentication/auth-snap-requests.mjs +34 -0
- package/dist/controllers/authentication/auth-snap-requests.mjs.map +1 -1
- package/dist/controllers/user-storage/UserStorageController.cjs +59 -2
- package/dist/controllers/user-storage/UserStorageController.cjs.map +1 -1
- package/dist/controllers/user-storage/UserStorageController.d.cts +2 -2
- package/dist/controllers/user-storage/UserStorageController.d.cts.map +1 -1
- package/dist/controllers/user-storage/UserStorageController.d.mts +2 -2
- package/dist/controllers/user-storage/UserStorageController.d.mts.map +1 -1
- package/dist/controllers/user-storage/UserStorageController.mjs +60 -3
- package/dist/controllers/user-storage/UserStorageController.mjs.map +1 -1
- package/dist/controllers/user-storage/mocks/mockStorage.cjs +3 -1
- package/dist/controllers/user-storage/mocks/mockStorage.cjs.map +1 -1
- package/dist/controllers/user-storage/mocks/mockStorage.d.cts +2 -0
- package/dist/controllers/user-storage/mocks/mockStorage.d.cts.map +1 -1
- package/dist/controllers/user-storage/mocks/mockStorage.d.mts +2 -0
- package/dist/controllers/user-storage/mocks/mockStorage.d.mts.map +1 -1
- package/dist/controllers/user-storage/mocks/mockStorage.mjs +2 -0
- package/dist/controllers/user-storage/mocks/mockStorage.mjs.map +1 -1
- package/dist/controllers/user-storage/network-syncing/controller-integration.cjs +1 -3
- package/dist/controllers/user-storage/network-syncing/controller-integration.cjs.map +1 -1
- package/dist/controllers/user-storage/network-syncing/controller-integration.d.cts.map +1 -1
- package/dist/controllers/user-storage/network-syncing/controller-integration.d.mts.map +1 -1
- package/dist/controllers/user-storage/network-syncing/controller-integration.mjs +1 -3
- package/dist/controllers/user-storage/network-syncing/controller-integration.mjs.map +1 -1
- package/dist/sdk/mocks/userstorage.cjs +3 -2
- package/dist/sdk/mocks/userstorage.cjs.map +1 -1
- package/dist/sdk/mocks/userstorage.d.cts +1 -0
- package/dist/sdk/mocks/userstorage.d.cts.map +1 -1
- package/dist/sdk/mocks/userstorage.d.mts +1 -0
- package/dist/sdk/mocks/userstorage.d.mts.map +1 -1
- package/dist/sdk/mocks/userstorage.mjs +2 -1
- package/dist/sdk/mocks/userstorage.mjs.map +1 -1
- package/dist/sdk/user-storage.cjs +80 -44
- package/dist/sdk/user-storage.cjs.map +1 -1
- package/dist/sdk/user-storage.d.cts +34 -2
- package/dist/sdk/user-storage.d.cts.map +1 -1
- package/dist/sdk/user-storage.d.mts +34 -2
- package/dist/sdk/user-storage.d.mts.map +1 -1
- package/dist/sdk/user-storage.mjs +81 -45
- package/dist/sdk/user-storage.mjs.map +1 -1
- package/dist/shared/encryption/encryption.cjs.map +1 -1
- package/dist/shared/encryption/encryption.mjs.map +1 -1
- package/dist/shared/storage-schema.cjs +5 -2
- package/dist/shared/storage-schema.cjs.map +1 -1
- package/dist/shared/storage-schema.d.cts +4 -1
- package/dist/shared/storage-schema.d.cts.map +1 -1
- package/dist/shared/storage-schema.d.mts +4 -1
- package/dist/shared/storage-schema.d.mts.map +1 -1
- package/dist/shared/storage-schema.mjs +4 -1
- package/dist/shared/storage-schema.mjs.map +1 -1
- package/package.json +2 -1
|
@@ -9,14 +9,17 @@ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (
|
|
|
9
9
|
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
10
10
|
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
11
11
|
};
|
|
12
|
-
var _UserStorageController_instances, _UserStorageController_env, _UserStorageController_userStorage, _UserStorageController_auth, _UserStorageController_config, _UserStorageController_isUnlocked, _UserStorageController_storageKeyCache, _UserStorageController_keyringController, _UserStorageController_nativeScryptCrypto, _UserStorageController_registerMessageHandlers, _UserStorageController__snapSignMessageCache, _UserStorageController_snapSignMessage, _UserStorageController_setIsProfileSyncingUpdateLoading;
|
|
12
|
+
var _UserStorageController_instances, _UserStorageController_env, _UserStorageController_userStorage, _UserStorageController_auth, _UserStorageController_config, _UserStorageController_isUnlocked, _UserStorageController_storageKeyCache, _UserStorageController_keyringController, _UserStorageController_nativeScryptCrypto, _UserStorageController_registerMessageHandlers, _UserStorageController__snapSignMessageCache, _UserStorageController_snapSignMessage, _UserStorageController__snapEncryptionKeyCache, _UserStorageController_snapGetEncryptionPublicKey, _UserStorageController__snapDecryptMessageCache, _UserStorageController_snapDecryptMessage, _UserStorageController_setIsProfileSyncingUpdateLoading;
|
|
13
13
|
import { BaseController } from "@metamask/base-controller";
|
|
14
|
+
import { encrypt as ERC1024Encrypt } from "@metamask/eth-sig-util";
|
|
15
|
+
import { hexToBytes } from "@noble/hashes/utils";
|
|
14
16
|
import { saveInternalAccountToUserStorage, syncInternalAccountsWithUserStorage } from "./account-syncing/controller-integration.mjs";
|
|
15
17
|
import { setupAccountSyncingSubscriptions } from "./account-syncing/setup-subscriptions.mjs";
|
|
16
18
|
import { BACKUPANDSYNC_FEATURES } from "./constants.mjs";
|
|
17
19
|
import { performMainNetworkSync, startNetworkSyncing } from "./network-syncing/controller-integration.mjs";
|
|
18
20
|
import { Env, UserStorage } from "../../sdk/index.mjs";
|
|
19
|
-
import {
|
|
21
|
+
import { byteArrayToBase64 } from "../../shared/encryption/utils.mjs";
|
|
22
|
+
import { createSnapDecryptMessageRequest, createSnapEncryptionPublicKeyRequest, createSnapSignMessageRequest } from "../authentication/auth-snap-requests.mjs";
|
|
20
23
|
const controllerName = 'UserStorageController';
|
|
21
24
|
export const defaultState = {
|
|
22
25
|
isProfileSyncingEnabled: true,
|
|
@@ -108,6 +111,8 @@ class UserStorageController extends BaseController {
|
|
|
108
111
|
});
|
|
109
112
|
_UserStorageController_nativeScryptCrypto.set(this, undefined);
|
|
110
113
|
_UserStorageController__snapSignMessageCache.set(this, {});
|
|
114
|
+
_UserStorageController__snapEncryptionKeyCache.set(this, null);
|
|
115
|
+
_UserStorageController__snapDecryptMessageCache.set(this, {});
|
|
111
116
|
__classPrivateFieldGet(this, _UserStorageController_env, "f").isNetworkSyncingEnabled = Boolean(env?.isNetworkSyncingEnabled);
|
|
112
117
|
__classPrivateFieldSet(this, _UserStorageController_config, config, "f");
|
|
113
118
|
__classPrivateFieldSet(this, _UserStorageController_userStorage, new UserStorage({
|
|
@@ -119,6 +124,23 @@ class UserStorageController extends BaseController {
|
|
|
119
124
|
},
|
|
120
125
|
signMessage: (message) => __classPrivateFieldGet(this, _UserStorageController_instances, "m", _UserStorageController_snapSignMessage).call(this, message),
|
|
121
126
|
},
|
|
127
|
+
encryption: {
|
|
128
|
+
getEncryptionPublicKey: async () => {
|
|
129
|
+
return await __classPrivateFieldGet(this, _UserStorageController_instances, "m", _UserStorageController_snapGetEncryptionPublicKey).call(this);
|
|
130
|
+
},
|
|
131
|
+
decryptMessage: async (ciphertext) => {
|
|
132
|
+
return await __classPrivateFieldGet(this, _UserStorageController_instances, "m", _UserStorageController_snapDecryptMessage).call(this, ciphertext);
|
|
133
|
+
},
|
|
134
|
+
encryptMessage: async (message, publicKeyHex) => {
|
|
135
|
+
const erc1024Payload = ERC1024Encrypt({
|
|
136
|
+
// eth-sig-util expects the public key to be in base64 format
|
|
137
|
+
publicKey: byteArrayToBase64(hexToBytes(publicKeyHex)),
|
|
138
|
+
data: message,
|
|
139
|
+
version: 'x25519-xsalsa20-poly1305',
|
|
140
|
+
});
|
|
141
|
+
return JSON.stringify(erc1024Payload);
|
|
142
|
+
},
|
|
143
|
+
},
|
|
122
144
|
}, {
|
|
123
145
|
storage: {
|
|
124
146
|
getStorageKey: async (message) => __classPrivateFieldGet(this, _UserStorageController_storageKeyCache, "f")[message] ?? null,
|
|
@@ -339,7 +361,7 @@ class UserStorageController extends BaseController {
|
|
|
339
361
|
});
|
|
340
362
|
}
|
|
341
363
|
}
|
|
342
|
-
_UserStorageController_env = new WeakMap(), _UserStorageController_userStorage = new WeakMap(), _UserStorageController_auth = new WeakMap(), _UserStorageController_config = new WeakMap(), _UserStorageController_isUnlocked = new WeakMap(), _UserStorageController_storageKeyCache = new WeakMap(), _UserStorageController_keyringController = new WeakMap(), _UserStorageController_nativeScryptCrypto = new WeakMap(), _UserStorageController__snapSignMessageCache = new WeakMap(), _UserStorageController_instances = new WeakSet(), _UserStorageController_registerMessageHandlers = function _UserStorageController_registerMessageHandlers() {
|
|
364
|
+
_UserStorageController_env = new WeakMap(), _UserStorageController_userStorage = new WeakMap(), _UserStorageController_auth = new WeakMap(), _UserStorageController_config = new WeakMap(), _UserStorageController_isUnlocked = new WeakMap(), _UserStorageController_storageKeyCache = new WeakMap(), _UserStorageController_keyringController = new WeakMap(), _UserStorageController_nativeScryptCrypto = new WeakMap(), _UserStorageController__snapSignMessageCache = new WeakMap(), _UserStorageController__snapEncryptionKeyCache = new WeakMap(), _UserStorageController__snapDecryptMessageCache = new WeakMap(), _UserStorageController_instances = new WeakSet(), _UserStorageController_registerMessageHandlers = function _UserStorageController_registerMessageHandlers() {
|
|
343
365
|
this.messagingSystem.registerActionHandler('UserStorageController:performGetStorage', this.performGetStorage.bind(this));
|
|
344
366
|
this.messagingSystem.registerActionHandler('UserStorageController:performGetStorageAllFeatureEntries', this.performGetStorageAllFeatureEntries.bind(this));
|
|
345
367
|
this.messagingSystem.registerActionHandler('UserStorageController:performSetStorage', this.performSetStorage.bind(this));
|
|
@@ -364,6 +386,41 @@ async function _UserStorageController_snapSignMessage(message) {
|
|
|
364
386
|
const result = (await this.messagingSystem.call('SnapController:handleRequest', createSnapSignMessageRequest(message)));
|
|
365
387
|
__classPrivateFieldGet(this, _UserStorageController__snapSignMessageCache, "f")[message] = result;
|
|
366
388
|
return result;
|
|
389
|
+
}, _UserStorageController_snapGetEncryptionPublicKey =
|
|
390
|
+
/**
|
|
391
|
+
* Get an encryption public key from the snap
|
|
392
|
+
*
|
|
393
|
+
* @returns The encryption public key used by the snap
|
|
394
|
+
*/
|
|
395
|
+
async function _UserStorageController_snapGetEncryptionPublicKey() {
|
|
396
|
+
if (__classPrivateFieldGet(this, _UserStorageController__snapEncryptionKeyCache, "f")) {
|
|
397
|
+
return __classPrivateFieldGet(this, _UserStorageController__snapEncryptionKeyCache, "f");
|
|
398
|
+
}
|
|
399
|
+
if (!__classPrivateFieldGet(this, _UserStorageController_isUnlocked, "f")) {
|
|
400
|
+
throw new Error('#snapGetEncryptionPublicKey - unable to call snap, wallet is locked');
|
|
401
|
+
}
|
|
402
|
+
const result = (await this.messagingSystem.call('SnapController:handleRequest', createSnapEncryptionPublicKeyRequest()));
|
|
403
|
+
__classPrivateFieldSet(this, _UserStorageController__snapEncryptionKeyCache, result, "f");
|
|
404
|
+
return result;
|
|
405
|
+
}, _UserStorageController_snapDecryptMessage =
|
|
406
|
+
/**
|
|
407
|
+
* Calls the snap to attempt to decrypt the message.
|
|
408
|
+
*
|
|
409
|
+
* @param ciphertext - the encrypted text to decrypt.
|
|
410
|
+
* @returns The decrypted message, if decryption was possible.
|
|
411
|
+
*/
|
|
412
|
+
async function _UserStorageController_snapDecryptMessage(ciphertext) {
|
|
413
|
+
if (__classPrivateFieldGet(this, _UserStorageController__snapDecryptMessageCache, "f")[ciphertext]) {
|
|
414
|
+
return __classPrivateFieldGet(this, _UserStorageController__snapDecryptMessageCache, "f")[ciphertext];
|
|
415
|
+
}
|
|
416
|
+
if (!__classPrivateFieldGet(this, _UserStorageController_isUnlocked, "f")) {
|
|
417
|
+
throw new Error('#snapDecryptMessage - unable to call snap, wallet is locked');
|
|
418
|
+
}
|
|
419
|
+
const result = (await this.messagingSystem.call('SnapController:handleRequest', createSnapDecryptMessageRequest(ciphertext)));
|
|
420
|
+
if (result) {
|
|
421
|
+
__classPrivateFieldGet(this, _UserStorageController__snapDecryptMessageCache, "f")[ciphertext] = result;
|
|
422
|
+
}
|
|
423
|
+
return result;
|
|
367
424
|
}, _UserStorageController_setIsProfileSyncingUpdateLoading = function _UserStorageController_setIsProfileSyncingUpdateLoading(isProfileSyncingUpdateLoading) {
|
|
368
425
|
this.update((state) => {
|
|
369
426
|
state.isProfileSyncingUpdateLoading = isProfileSyncingUpdateLoading;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"UserStorageController.mjs","sourceRoot":"","sources":["../../../src/controllers/user-storage/UserStorageController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAYA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAiB3D,OAAO,EACL,gCAAgC,EAChC,mCAAmC,EACpC,qDAAiD;AAClD,OAAO,EAAE,gCAAgC,EAAE,kDAA8C;AACzF,OAAO,EAAE,sBAAsB,EAAE,wBAAoB;AACrD,OAAO,EACL,sBAAsB,EACtB,mBAAmB,EACpB,qDAAiD;AAClD,OAAO,EAAE,GAAG,EAAE,WAAW,EAAE,4BAAkB;AAO7C,OAAO,EAAE,4BAA4B,EAAE,iDAA6C;AAQpF,MAAM,cAAc,GAAG,uBAAuB,CAAC;AAoC/C,MAAM,CAAC,MAAM,YAAY,GAA+B;IACtD,uBAAuB,EAAE,IAAI;IAC7B,6BAA6B,EAAE,KAAK;IACpC,uBAAuB,EAAE,IAAI;IAC7B,kCAAkC,EAAE,KAAK;IACzC,mCAAmC,EAAE,KAAK;IAC1C,0BAA0B,EAAE,KAAK;CAClC,CAAC;AAEF,MAAM,QAAQ,GAA8C;IAC1D,uBAAuB,EAAE;QACvB,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,IAAI;KAChB;IACD,6BAA6B,EAAE;QAC7B,OAAO,EAAE,KAAK;QACd,SAAS,EAAE,KAAK;KACjB;IACD,uBAAu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A6B,GAAG,6BAA6B,CAAC;IACtE,CAAC,CAAC,CAAC;AACL,CAAC;eAtXkB,qBAAqB","sourcesContent":["import type {\n AccountsControllerListAccountsAction,\n AccountsControllerUpdateAccountMetadataAction,\n AccountsControllerAccountRenamedEvent,\n AccountsControllerAccountAddedEvent,\n} from '@metamask/accounts-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedMessenger,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport {\n type KeyringControllerGetStateAction,\n type KeyringControllerLockEvent,\n type KeyringControllerUnlockEvent,\n type KeyringControllerWithKeyringAction,\n} from '@metamask/keyring-controller';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport type {\n NetworkControllerAddNetworkAction,\n NetworkControllerGetStateAction,\n NetworkControllerNetworkRemovedEvent,\n NetworkControllerRemoveNetworkAction,\n NetworkControllerUpdateNetworkAction,\n} from '@metamask/network-controller';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\n\nimport {\n saveInternalAccountToUserStorage,\n syncInternalAccountsWithUserStorage,\n} from './account-syncing/controller-integration';\nimport { setupAccountSyncingSubscriptions } from './account-syncing/setup-subscriptions';\nimport { BACKUPANDSYNC_FEATURES } from './constants';\nimport {\n performMainNetworkSync,\n startNetworkSyncing,\n} from './network-syncing/controller-integration';\nimport { Env, UserStorage } from '../../sdk';\nimport type { UserStorageFeatureKeys } from '../../shared/storage-schema';\nimport {\n type UserStoragePathWithFeatureAndKey,\n type UserStoragePathWithFeatureOnly,\n} from '../../shared/storage-schema';\nimport type { NativeScrypt } from '../../shared/types/encryption';\nimport { createSnapSignMessageRequest } from '../authentication/auth-snap-requests';\nimport type {\n AuthenticationControllerGetBearerToken,\n AuthenticationControllerGetSessionProfile,\n AuthenticationControllerIsSignedIn,\n AuthenticationControllerPerformSignIn,\n} from '../authentication/AuthenticationController';\n\nconst controllerName = 'UserStorageController';\n\n// State\nexport type UserStorageControllerState = {\n /**\n * Condition used by UI and to determine if we can use some of the User Storage methods.\n */\n isProfileSyncingEnabled: boolean;\n /**\n * Loading state for the profile syncing update\n */\n isProfileSyncingUpdateLoading: boolean;\n /**\n * Condition used by UI to determine if account syncing is enabled.\n */\n isAccountSyncingEnabled: boolean;\n /**\n * Condition used to determine if account syncing has been dispatched at least once.\n * This is used for event listeners to determine if they should be triggered.\n * This is also used in E2E tests for verification purposes.\n */\n hasAccountSyncingSyncedAtLeastOnce: boolean;\n /**\n * Condition used by UI to determine if account syncing is ready to be dispatched.\n */\n isAccountSyncingReadyToBeDispatched: boolean;\n /**\n * Condition used by UI to determine if account syncing is in progress.\n */\n isAccountSyncingInProgress: boolean;\n /**\n * Condition used to ensure that we do not perform any network sync mutations until we have synced at least once\n */\n hasNetworkSyncingSyncedAtLeastOnce?: boolean;\n};\n\nexport const defaultState: UserStorageControllerState = {\n isProfileSyncingEnabled: true,\n isProfileSyncingUpdateLoading: false,\n isAccountSyncingEnabled: true,\n hasAccountSyncingSyncedAtLeastOnce: false,\n isAccountSyncingReadyToBeDispatched: false,\n isAccountSyncingInProgress: false,\n};\n\nconst metadata: StateMetadata<UserStorageControllerState> = {\n isProfileSyncingEnabled: {\n persist: true,\n anonymous: true,\n },\n isProfileSyncingUpdateLoading: {\n persist: false,\n anonymous: false,\n },\n isAccountSyncingEnabled: {\n persist: true,\n anonymous: true,\n },\n hasAccountSyncingSyncedAtLeastOnce: {\n persist: true,\n anonymous: false,\n },\n isAccountSyncingReadyToBeDispatched: {\n persist: true,\n anonymous: false,\n },\n isAccountSyncingInProgress: {\n persist: false,\n anonymous: false,\n },\n hasNetworkSyncingSyncedAtLeastOnce: {\n persist: true,\n anonymous: false,\n },\n};\n\ntype ControllerConfig = {\n accountSyncing?: {\n maxNumberOfAccountsToAdd?: number;\n /**\n * Callback that fires when account sync adds an account.\n * This is used for analytics.\n */\n onAccountAdded?: (profileId: string) => void;\n\n /**\n * Callback that fires when account sync updates the name of an account.\n * This is used for analytics.\n */\n onAccountNameUpdated?: (profileId: string) => void;\n\n /**\n * Callback that fires when an erroneous situation happens during account sync.\n * This is used for analytics.\n */\n onAccountSyncErroneousSituation?: (\n profileId: string,\n situationMessage: string,\n sentryContext?: Record<string, unknown>,\n ) => void;\n };\n\n networkSyncing?: {\n maxNumberOfNetworksToAdd?: number;\n /**\n * Callback that fires when network sync adds a network\n * This is used for analytics.\n *\n * @param profileId - ID for a given User (shared cross devices once authenticated)\n * @param chainId - Chain ID for the network added (in hex)\n */\n onNetworkAdded?: (profileId: string, chainId: string) => void;\n /**\n * Callback that fires when network sync updates a network\n * This is used for analytics.\n *\n * @param profileId - ID for a given User (shared cross devices once authenticated)\n * @param chainId - Chain ID for the network added (in hex)\n */\n onNetworkUpdated?: (profileId: string, chainId: string) => void;\n /**\n * Callback that fires when network sync deletes a network\n * This is used for analytics.\n *\n * @param profileId - ID for a given User (shared cross devices once authenticated)\n * @param chainId - Chain ID for the network added (in hex)\n */\n onNetworkRemoved?: (profileId: string, chainId: string) => void;\n };\n};\n\n// Messenger Actions\ntype CreateActionsObj<Controller extends keyof UserStorageController> = {\n [K in Controller]: {\n type: `${typeof controllerName}:${K}`;\n handler: UserStorageController[K];\n };\n};\ntype ActionsObj = CreateActionsObj<\n | 'performGetStorage'\n | 'performGetStorageAllFeatureEntries'\n | 'performSetStorage'\n | 'performBatchSetStorage'\n | 'performDeleteStorage'\n | 'performBatchDeleteStorage'\n | 'getStorageKey'\n>;\nexport type UserStorageControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n UserStorageControllerState\n>;\nexport type Actions =\n | ActionsObj[keyof ActionsObj]\n | UserStorageControllerGetStateAction;\nexport type UserStorageControllerPerformGetStorage =\n ActionsObj['performGetStorage'];\nexport type UserStorageControllerPerformGetStorageAllFeatureEntries =\n ActionsObj['performGetStorageAllFeatureEntries'];\nexport type UserStorageControllerPerformSetStorage =\n ActionsObj['performSetStorage'];\nexport type UserStorageControllerPerformBatchSetStorage =\n ActionsObj['performBatchSetStorage'];\nexport type UserStorageControllerPerformDeleteStorage =\n ActionsObj['performDeleteStorage'];\nexport type UserStorageControllerPerformBatchDeleteStorage =\n ActionsObj['performBatchDeleteStorage'];\nexport type UserStorageControllerGetStorageKey = ActionsObj['getStorageKey'];\n\nexport type AllowedActions =\n // Keyring Requests\n | KeyringControllerGetStateAction\n // Snap Requests\n | HandleSnapRequest\n // Auth Requests\n | AuthenticationControllerGetBearerToken\n | AuthenticationControllerGetSessionProfile\n | AuthenticationControllerPerformSignIn\n | AuthenticationControllerIsSignedIn\n // Account Syncing\n | AccountsControllerListAccountsAction\n | AccountsControllerUpdateAccountMetadataAction\n | KeyringControllerWithKeyringAction\n // Network Syncing\n | NetworkControllerGetStateAction\n | NetworkControllerAddNetworkAction\n | NetworkControllerRemoveNetworkAction\n | NetworkControllerUpdateNetworkAction;\n\n// Messenger events\nexport type UserStorageControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n UserStorageControllerState\n>;\n\nexport type Events = UserStorageControllerStateChangeEvent;\n\nexport type AllowedEvents =\n | UserStorageControllerStateChangeEvent\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent\n // Account Syncing Events\n | AccountsControllerAccountAddedEvent\n | AccountsControllerAccountRenamedEvent\n // Network Syncing Events\n | NetworkControllerNetworkRemovedEvent;\n\n// Messenger\nexport type UserStorageControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n Actions | AllowedActions,\n Events | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Reusable controller that allows any team to store synchronized data for a given user.\n * These can be settings shared cross MetaMask clients, or data we want to persist when uninstalling/reinstalling.\n *\n * NOTE:\n * - data stored on UserStorage is FULLY encrypted, with the only keys stored/managed on the client.\n * - No one can access this data unless they are have the SRP and are able to run the signing snap.\n */\nexport default class UserStorageController extends BaseController<\n typeof controllerName,\n UserStorageControllerState,\n UserStorageControllerMessenger\n> {\n // This is replaced with the actual value in the constructor\n // We will remove this once the feature will be released\n readonly #env = {\n isNetworkSyncingEnabled: false,\n };\n\n readonly #userStorage: UserStorage;\n\n readonly #auth = {\n getProfileId: async () => {\n const sessionProfile = await this.messagingSystem.call(\n 'AuthenticationController:getSessionProfile',\n );\n return sessionProfile?.profileId;\n },\n isSignedIn: () => {\n return this.messagingSystem.call('AuthenticationController:isSignedIn');\n },\n signIn: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:performSignIn',\n );\n },\n };\n\n readonly #config?: ControllerConfig;\n\n #isUnlocked = false;\n\n #storageKeyCache: Record<`metamask:${string}`, string> = {};\n\n readonly #keyringController = {\n setupLockedStateSubscriptions: () => {\n const { isUnlocked } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n this.#isUnlocked = isUnlocked;\n\n this.messagingSystem.subscribe('KeyringController:unlock', () => {\n this.#isUnlocked = true;\n });\n\n this.messagingSystem.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n },\n };\n\n readonly #nativeScryptCrypto: NativeScrypt | undefined = undefined;\n\n constructor({\n messenger,\n state,\n env,\n config,\n nativeScryptCrypto,\n }: {\n messenger: UserStorageControllerMessenger;\n state?: UserStorageControllerState;\n config?: ControllerConfig;\n env?: {\n isNetworkSyncingEnabled?: boolean;\n };\n nativeScryptCrypto?: NativeScrypt;\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n this.#env.isNetworkSyncingEnabled = Boolean(env?.isNetworkSyncingEnabled);\n this.#config = config;\n\n this.#userStorage = new UserStorage(\n {\n env: Env.PRD,\n auth: {\n getAccessToken: () =>\n this.messagingSystem.call(\n 'AuthenticationController:getBearerToken',\n ),\n getUserProfile: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:getSessionProfile',\n );\n },\n signMessage: (message) =>\n this.#snapSignMessage(message as `metamask:${string}`),\n },\n },\n {\n storage: {\n getStorageKey: async (message) =>\n this.#storageKeyCache[message] ?? null,\n setStorageKey: async (message, key) => {\n this.#storageKeyCache[message] = key;\n },\n },\n },\n );\n\n this.#keyringController.setupLockedStateSubscriptions();\n this.#registerMessageHandlers();\n this.#nativeScryptCrypto = nativeScryptCrypto;\n\n // Account Syncing\n setupAccountSyncingSubscriptions({\n getUserStorageControllerInstance: () => this,\n getMessenger: () => this.messagingSystem,\n });\n\n // Network Syncing\n if (this.#env.isNetworkSyncingEnabled) {\n startNetworkSyncing({\n messenger,\n getUserStorageControllerInstance: () => this,\n isMutationSyncBlocked: () =>\n !this.state.hasNetworkSyncingSyncedAtLeastOnce,\n });\n }\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performGetStorage',\n this.performGetStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performGetStorageAllFeatureEntries',\n this.performGetStorageAllFeatureEntries.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performSetStorage',\n this.performSetStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performBatchSetStorage',\n this.performBatchSetStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performDeleteStorage',\n this.performDeleteStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performBatchDeleteStorage',\n this.performBatchDeleteStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:getStorageKey',\n this.getStorageKey.bind(this),\n );\n }\n\n /**\n * Allows retrieval of stored data. Data stored is string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @returns the decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorage(\n path: UserStoragePathWithFeatureAndKey,\n ): Promise<string | null> {\n return await this.#userStorage.getItem(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n });\n }\n\n /**\n * Allows retrieval of all stored data for a specific feature. Data stored is formatted as an array of strings.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @returns the array of decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorageAllFeatureEntries(\n path: UserStoragePathWithFeatureOnly,\n ): Promise<string[] | null> {\n return await this.#userStorage.getAllFeatureItems(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n });\n }\n\n /**\n * Allows storage of user data. Data stored must be string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param value - The string data you want to store.\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performSetStorage(\n path: UserStoragePathWithFeatureAndKey,\n value: string,\n ): Promise<void> {\n return await this.#userStorage.setItem(path, value, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n });\n }\n\n /**\n * Allows storage of multiple user data entries for one specific feature. Data stored must be string formatted.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @param values - data to store, in the form of an array of `[entryKey, entryValue]` pairs\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performBatchSetStorage<\n FeatureName extends UserStoragePathWithFeatureOnly,\n >(\n path: FeatureName,\n values: [UserStorageFeatureKeys<FeatureName>, string][],\n ): Promise<void> {\n return await this.#userStorage.batchSetItems(path, values, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n });\n }\n\n /**\n * Allows deletion of user data. Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @returns nothing. NOTE that an error is thrown if fails to delete data.\n */\n public async performDeleteStorage(\n path: UserStoragePathWithFeatureAndKey,\n ): Promise<void> {\n return await this.#userStorage.deleteItem(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n });\n }\n\n /**\n * Allows deletion of all user data entries for a specific feature.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @returns nothing. NOTE that an error is thrown if fails to delete data.\n */\n public async performDeleteStorageAllFeatureEntries(\n path: UserStoragePathWithFeatureOnly,\n ): Promise<void> {\n return await this.#userStorage.deleteAllFeatureItems(path);\n }\n\n /**\n * Allows delete of multiple user data entries for one specific feature. Data deleted must be string formatted.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @param values - data to store, in the form of an array of entryKey[]\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performBatchDeleteStorage<\n FeatureName extends UserStoragePathWithFeatureOnly,\n >(\n path: FeatureName,\n values: UserStorageFeatureKeys<FeatureName>[],\n ): Promise<void> {\n return await this.#userStorage.batchDeleteItems(path, values);\n }\n\n /**\n * Retrieves the storage key, for internal use only!\n *\n * @returns the storage key\n */\n public async getStorageKey(): Promise<string> {\n return await this.#userStorage.getStorageKey();\n }\n\n /**\n * Flushes the storage key cache.\n * CAUTION: This is only public for testing purposes.\n * It should not be used in production code.\n */\n public flushStorageKeyCache(): void {\n this.#storageKeyCache = {};\n }\n\n #_snapSignMessageCache: Record<`metamask:${string}`, string> = {};\n\n /**\n * Signs a specific message using an underlying auth snap.\n *\n * @param message - A specific tagged message to sign.\n * @returns A Signature created by the snap.\n */\n async #snapSignMessage(message: `metamask:${string}`): Promise<string> {\n if (this.#_snapSignMessageCache[message]) {\n return this.#_snapSignMessageCache[message];\n }\n\n if (!this.#isUnlocked) {\n throw new Error(\n '#snapSignMessage - unable to call snap, wallet is locked',\n );\n }\n\n const result = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n createSnapSignMessageRequest(message),\n )) as string;\n\n this.#_snapSignMessageCache[message] = result;\n\n return result;\n }\n\n public async setIsBackupAndSyncFeatureEnabled(\n feature: keyof typeof BACKUPANDSYNC_FEATURES,\n enabled: boolean,\n ): Promise<void> {\n try {\n this.#setIsProfileSyncingUpdateLoading(true);\n\n if (enabled) {\n // If any of the features are enabled, we need to ensure the user is signed in\n const isSignedIn = this.#auth.isSignedIn();\n if (!isSignedIn) {\n await this.#auth.signIn();\n }\n }\n\n this.update((state) => {\n if (feature === BACKUPANDSYNC_FEATURES.main) {\n state.isProfileSyncingEnabled = enabled;\n }\n\n if (feature === BACKUPANDSYNC_FEATURES.accountSyncing) {\n state.isAccountSyncingEnabled = enabled;\n }\n });\n } catch (e) {\n // istanbul ignore next\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n // istanbul ignore next\n throw new Error(\n `${controllerName} - failed to ${enabled ? 'enable' : 'disable'} ${feature} - ${errorMessage}`,\n );\n } finally {\n this.#setIsProfileSyncingUpdateLoading(false);\n }\n }\n\n #setIsProfileSyncingUpdateLoading(\n isProfileSyncingUpdateLoading: boolean,\n ): void {\n this.update((state) => {\n state.isProfileSyncingUpdateLoading = isProfileSyncingUpdateLoading;\n });\n }\n\n async setHasAccountSyncingSyncedAtLeastOnce(\n hasAccountSyncingSyncedAtLeastOnce: boolean,\n ): Promise<void> {\n this.update((state) => {\n state.hasAccountSyncingSyncedAtLeastOnce =\n hasAccountSyncingSyncedAtLeastOnce;\n });\n }\n\n async setIsAccountSyncingReadyToBeDispatched(\n isAccountSyncingReadyToBeDispatched: boolean,\n ): Promise<void> {\n this.update((state) => {\n state.isAccountSyncingReadyToBeDispatched =\n isAccountSyncingReadyToBeDispatched;\n });\n }\n\n async setIsAccountSyncingInProgress(\n isAccountSyncingInProgress: boolean,\n ): Promise<void> {\n this.update((state) => {\n state.isAccountSyncingInProgress = isAccountSyncingInProgress;\n });\n }\n\n /**\n * Syncs the internal accounts list with the user storage accounts list.\n * This method is used to make sure that the internal accounts list is up-to-date with the user storage accounts list and vice-versa.\n * It will add new accounts to the internal accounts list, update/merge conflicting names and re-upload the results in some cases to the user storage.\n */\n async syncInternalAccountsWithUserStorage(): Promise<void> {\n const profileId = await this.#auth.getProfileId();\n\n await syncInternalAccountsWithUserStorage(\n {\n maxNumberOfAccountsToAdd:\n this.#config?.accountSyncing?.maxNumberOfAccountsToAdd,\n onAccountAdded: () =>\n this.#config?.accountSyncing?.onAccountAdded?.(profileId),\n onAccountNameUpdated: () =>\n this.#config?.accountSyncing?.onAccountNameUpdated?.(profileId),\n onAccountSyncErroneousSituation: (situationMessage, sentryContext) =>\n this.#config?.accountSyncing?.onAccountSyncErroneousSituation?.(\n profileId,\n situationMessage,\n sentryContext,\n ),\n },\n {\n getMessenger: () => this.messagingSystem,\n getUserStorageControllerInstance: () => this,\n },\n );\n }\n\n /**\n * Saves an individual internal account to the user storage.\n *\n * @param internalAccount - The internal account to save\n */\n async saveInternalAccountToUserStorage(\n internalAccount: InternalAccount,\n ): Promise<void> {\n await saveInternalAccountToUserStorage(internalAccount, {\n getMessenger: () => this.messagingSystem,\n getUserStorageControllerInstance: () => this,\n });\n }\n\n async syncNetworks() {\n if (!this.#env.isNetworkSyncingEnabled) {\n return;\n }\n\n const profileId = await this.#auth.getProfileId();\n\n await performMainNetworkSync({\n messenger: this.messagingSystem,\n getUserStorageControllerInstance: () => this,\n maxNetworksToAdd: this.#config?.networkSyncing?.maxNumberOfNetworksToAdd,\n onNetworkAdded: (cId) =>\n this.#config?.networkSyncing?.onNetworkAdded?.(profileId, cId),\n onNetworkUpdated: (cId) =>\n this.#config?.networkSyncing?.onNetworkUpdated?.(profileId, cId),\n onNetworkRemoved: (cId) =>\n this.#config?.networkSyncing?.onNetworkRemoved?.(profileId, cId),\n });\n\n this.update((s) => {\n s.hasNetworkSyncingSyncedAtLeastOnce = true;\n });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"UserStorageController.mjs","sourceRoot":"","sources":["../../../src/controllers/user-storage/UserStorageController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAYA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,EAAE,OAAO,IAAI,cAAc,EAAE,+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IACtE,CAAC,CAAC,CAAC;AACL,CAAC;eAlckB,qBAAqB","sourcesContent":["import type {\n AccountsControllerAccountAddedEvent,\n AccountsControllerAccountRenamedEvent,\n AccountsControllerListAccountsAction,\n AccountsControllerUpdateAccountMetadataAction,\n} from '@metamask/accounts-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedMessenger,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport { encrypt as ERC1024Encrypt } from '@metamask/eth-sig-util';\nimport {\n type KeyringControllerGetStateAction,\n type KeyringControllerLockEvent,\n type KeyringControllerUnlockEvent,\n type KeyringControllerWithKeyringAction,\n} from '@metamask/keyring-controller';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport type {\n NetworkControllerAddNetworkAction,\n NetworkControllerGetStateAction,\n NetworkControllerNetworkRemovedEvent,\n NetworkControllerRemoveNetworkAction,\n NetworkControllerUpdateNetworkAction,\n} from '@metamask/network-controller';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\nimport { hexToBytes } from '@noble/hashes/utils';\n\nimport {\n saveInternalAccountToUserStorage,\n syncInternalAccountsWithUserStorage,\n} from './account-syncing/controller-integration';\nimport { setupAccountSyncingSubscriptions } from './account-syncing/setup-subscriptions';\nimport { BACKUPANDSYNC_FEATURES } from './constants';\nimport {\n performMainNetworkSync,\n startNetworkSyncing,\n} from './network-syncing/controller-integration';\nimport { Env, UserStorage } from '../../sdk';\nimport { byteArrayToBase64 } from '../../shared/encryption/utils';\nimport type { UserStorageFeatureKeys } from '../../shared/storage-schema';\nimport {\n type UserStoragePathWithFeatureAndKey,\n type UserStoragePathWithFeatureOnly,\n} from '../../shared/storage-schema';\nimport type { NativeScrypt } from '../../shared/types/encryption';\nimport type {\n AuthenticationControllerGetBearerToken,\n AuthenticationControllerGetSessionProfile,\n AuthenticationControllerIsSignedIn,\n AuthenticationControllerPerformSignIn,\n} from '../authentication';\nimport {\n createSnapDecryptMessageRequest,\n createSnapEncryptionPublicKeyRequest,\n createSnapSignMessageRequest,\n} from '../authentication/auth-snap-requests';\n\nconst controllerName = 'UserStorageController';\n\n// State\nexport type UserStorageControllerState = {\n /**\n * Condition used by UI and to determine if we can use some of the User Storage methods.\n */\n isProfileSyncingEnabled: boolean;\n /**\n * Loading state for the profile syncing update\n */\n isProfileSyncingUpdateLoading: boolean;\n /**\n * Condition used by UI to determine if account syncing is enabled.\n */\n isAccountSyncingEnabled: boolean;\n /**\n * Condition used to determine if account syncing has been dispatched at least once.\n * This is used for event listeners to determine if they should be triggered.\n * This is also used in E2E tests for verification purposes.\n */\n hasAccountSyncingSyncedAtLeastOnce: boolean;\n /**\n * Condition used by UI to determine if account syncing is ready to be dispatched.\n */\n isAccountSyncingReadyToBeDispatched: boolean;\n /**\n * Condition used by UI to determine if account syncing is in progress.\n */\n isAccountSyncingInProgress: boolean;\n /**\n * Condition used to ensure that we do not perform any network sync mutations until we have synced at least once\n */\n hasNetworkSyncingSyncedAtLeastOnce?: boolean;\n};\n\nexport const defaultState: UserStorageControllerState = {\n isProfileSyncingEnabled: true,\n isProfileSyncingUpdateLoading: false,\n isAccountSyncingEnabled: true,\n hasAccountSyncingSyncedAtLeastOnce: false,\n isAccountSyncingReadyToBeDispatched: false,\n isAccountSyncingInProgress: false,\n};\n\nconst metadata: StateMetadata<UserStorageControllerState> = {\n isProfileSyncingEnabled: {\n persist: true,\n anonymous: true,\n },\n isProfileSyncingUpdateLoading: {\n persist: false,\n anonymous: false,\n },\n isAccountSyncingEnabled: {\n persist: true,\n anonymous: true,\n },\n hasAccountSyncingSyncedAtLeastOnce: {\n persist: true,\n anonymous: false,\n },\n isAccountSyncingReadyToBeDispatched: {\n persist: true,\n anonymous: false,\n },\n isAccountSyncingInProgress: {\n persist: false,\n anonymous: false,\n },\n hasNetworkSyncingSyncedAtLeastOnce: {\n persist: true,\n anonymous: false,\n },\n};\n\ntype ControllerConfig = {\n accountSyncing?: {\n maxNumberOfAccountsToAdd?: number;\n /**\n * Callback that fires when account sync adds an account.\n * This is used for analytics.\n */\n onAccountAdded?: (profileId: string) => void;\n\n /**\n * Callback that fires when account sync updates the name of an account.\n * This is used for analytics.\n */\n onAccountNameUpdated?: (profileId: string) => void;\n\n /**\n * Callback that fires when an erroneous situation happens during account sync.\n * This is used for analytics.\n */\n onAccountSyncErroneousSituation?: (\n profileId: string,\n situationMessage: string,\n sentryContext?: Record<string, unknown>,\n ) => void;\n };\n\n networkSyncing?: {\n maxNumberOfNetworksToAdd?: number;\n /**\n * Callback that fires when network sync adds a network\n * This is used for analytics.\n *\n * @param profileId - ID for a given User (shared cross devices once authenticated)\n * @param chainId - Chain ID for the network added (in hex)\n */\n onNetworkAdded?: (profileId: string, chainId: string) => void;\n /**\n * Callback that fires when network sync updates a network\n * This is used for analytics.\n *\n * @param profileId - ID for a given User (shared cross devices once authenticated)\n * @param chainId - Chain ID for the network added (in hex)\n */\n onNetworkUpdated?: (profileId: string, chainId: string) => void;\n /**\n * Callback that fires when network sync deletes a network\n * This is used for analytics.\n *\n * @param profileId - ID for a given User (shared cross devices once authenticated)\n * @param chainId - Chain ID for the network added (in hex)\n */\n onNetworkRemoved?: (profileId: string, chainId: string) => void;\n };\n};\n\n// Messenger Actions\ntype CreateActionsObj<Controller extends keyof UserStorageController> = {\n [K in Controller]: {\n type: `${typeof controllerName}:${K}`;\n handler: UserStorageController[K];\n };\n};\ntype ActionsObj = CreateActionsObj<\n | 'performGetStorage'\n | 'performGetStorageAllFeatureEntries'\n | 'performSetStorage'\n | 'performBatchSetStorage'\n | 'performDeleteStorage'\n | 'performBatchDeleteStorage'\n | 'getStorageKey'\n>;\nexport type UserStorageControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n UserStorageControllerState\n>;\nexport type Actions =\n | ActionsObj[keyof ActionsObj]\n | UserStorageControllerGetStateAction;\nexport type UserStorageControllerPerformGetStorage =\n ActionsObj['performGetStorage'];\nexport type UserStorageControllerPerformGetStorageAllFeatureEntries =\n ActionsObj['performGetStorageAllFeatureEntries'];\nexport type UserStorageControllerPerformSetStorage =\n ActionsObj['performSetStorage'];\nexport type UserStorageControllerPerformBatchSetStorage =\n ActionsObj['performBatchSetStorage'];\nexport type UserStorageControllerPerformDeleteStorage =\n ActionsObj['performDeleteStorage'];\nexport type UserStorageControllerPerformBatchDeleteStorage =\n ActionsObj['performBatchDeleteStorage'];\nexport type UserStorageControllerGetStorageKey = ActionsObj['getStorageKey'];\n\nexport type AllowedActions =\n // Keyring Requests\n | KeyringControllerGetStateAction\n // Snap Requests\n | HandleSnapRequest\n // Auth Requests\n | AuthenticationControllerGetBearerToken\n | AuthenticationControllerGetSessionProfile\n | AuthenticationControllerPerformSignIn\n | AuthenticationControllerIsSignedIn\n // Account Syncing\n | AccountsControllerListAccountsAction\n | AccountsControllerUpdateAccountMetadataAction\n | KeyringControllerWithKeyringAction\n // Network Syncing\n | NetworkControllerGetStateAction\n | NetworkControllerAddNetworkAction\n | NetworkControllerRemoveNetworkAction\n | NetworkControllerUpdateNetworkAction;\n\n// Messenger events\nexport type UserStorageControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n UserStorageControllerState\n>;\n\nexport type Events = UserStorageControllerStateChangeEvent;\n\nexport type AllowedEvents =\n | UserStorageControllerStateChangeEvent\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent\n // Account Syncing Events\n | AccountsControllerAccountAddedEvent\n | AccountsControllerAccountRenamedEvent\n // Network Syncing Events\n | NetworkControllerNetworkRemovedEvent;\n\n// Messenger\nexport type UserStorageControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n Actions | AllowedActions,\n Events | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Reusable controller that allows any team to store synchronized data for a given user.\n * These can be settings shared cross MetaMask clients, or data we want to persist when uninstalling/reinstalling.\n *\n * NOTE:\n * - data stored on UserStorage is FULLY encrypted, with the only keys stored/managed on the client.\n * - No one can access this data unless they are have the SRP and are able to run the signing snap.\n */\nexport default class UserStorageController extends BaseController<\n typeof controllerName,\n UserStorageControllerState,\n UserStorageControllerMessenger\n> {\n // This is replaced with the actual value in the constructor\n // We will remove this once the feature will be released\n readonly #env = {\n isNetworkSyncingEnabled: false,\n };\n\n readonly #userStorage: UserStorage;\n\n readonly #auth = {\n getProfileId: async () => {\n const sessionProfile = await this.messagingSystem.call(\n 'AuthenticationController:getSessionProfile',\n );\n return sessionProfile?.profileId;\n },\n isSignedIn: () => {\n return this.messagingSystem.call('AuthenticationController:isSignedIn');\n },\n signIn: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:performSignIn',\n );\n },\n };\n\n readonly #config?: ControllerConfig;\n\n #isUnlocked = false;\n\n #storageKeyCache: Record<`metamask:${string}`, string> = {};\n\n readonly #keyringController = {\n setupLockedStateSubscriptions: () => {\n const { isUnlocked } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n this.#isUnlocked = isUnlocked;\n\n this.messagingSystem.subscribe('KeyringController:unlock', () => {\n this.#isUnlocked = true;\n });\n\n this.messagingSystem.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n },\n };\n\n readonly #nativeScryptCrypto: NativeScrypt | undefined = undefined;\n\n constructor({\n messenger,\n state,\n env,\n config,\n nativeScryptCrypto,\n }: {\n messenger: UserStorageControllerMessenger;\n state?: UserStorageControllerState;\n config?: ControllerConfig;\n env?: {\n isNetworkSyncingEnabled?: boolean;\n };\n nativeScryptCrypto?: NativeScrypt;\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n this.#env.isNetworkSyncingEnabled = Boolean(env?.isNetworkSyncingEnabled);\n this.#config = config;\n\n this.#userStorage = new UserStorage(\n {\n env: Env.PRD,\n auth: {\n getAccessToken: () =>\n this.messagingSystem.call(\n 'AuthenticationController:getBearerToken',\n ),\n getUserProfile: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:getSessionProfile',\n );\n },\n signMessage: (message) =>\n this.#snapSignMessage(message as `metamask:${string}`),\n },\n encryption: {\n getEncryptionPublicKey: async () => {\n return await this.#snapGetEncryptionPublicKey();\n },\n decryptMessage: async (ciphertext: string) => {\n return await this.#snapDecryptMessage(ciphertext);\n },\n encryptMessage: async (message: string, publicKeyHex: string) => {\n const erc1024Payload = ERC1024Encrypt({\n // eth-sig-util expects the public key to be in base64 format\n publicKey: byteArrayToBase64(hexToBytes(publicKeyHex)),\n data: message,\n version: 'x25519-xsalsa20-poly1305',\n });\n return JSON.stringify(erc1024Payload);\n },\n },\n },\n {\n storage: {\n getStorageKey: async (message) =>\n this.#storageKeyCache[message] ?? null,\n setStorageKey: async (message, key) => {\n this.#storageKeyCache[message] = key;\n },\n },\n },\n );\n\n this.#keyringController.setupLockedStateSubscriptions();\n this.#registerMessageHandlers();\n this.#nativeScryptCrypto = nativeScryptCrypto;\n\n // Account Syncing\n setupAccountSyncingSubscriptions({\n getUserStorageControllerInstance: () => this,\n getMessenger: () => this.messagingSystem,\n });\n\n // Network Syncing\n if (this.#env.isNetworkSyncingEnabled) {\n startNetworkSyncing({\n messenger,\n getUserStorageControllerInstance: () => this,\n isMutationSyncBlocked: () =>\n !this.state.hasNetworkSyncingSyncedAtLeastOnce,\n });\n }\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performGetStorage',\n this.performGetStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performGetStorageAllFeatureEntries',\n this.performGetStorageAllFeatureEntries.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performSetStorage',\n this.performSetStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performBatchSetStorage',\n this.performBatchSetStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performDeleteStorage',\n this.performDeleteStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performBatchDeleteStorage',\n this.performBatchDeleteStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:getStorageKey',\n this.getStorageKey.bind(this),\n );\n }\n\n /**\n * Allows retrieval of stored data. Data stored is string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @returns the decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorage(\n path: UserStoragePathWithFeatureAndKey,\n ): Promise<string | null> {\n return await this.#userStorage.getItem(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n });\n }\n\n /**\n * Allows retrieval of all stored data for a specific feature. Data stored is formatted as an array of strings.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @returns the array of decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorageAllFeatureEntries(\n path: UserStoragePathWithFeatureOnly,\n ): Promise<string[] | null> {\n return await this.#userStorage.getAllFeatureItems(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n });\n }\n\n /**\n * Allows storage of user data. Data stored must be string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param value - The string data you want to store.\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performSetStorage(\n path: UserStoragePathWithFeatureAndKey,\n value: string,\n ): Promise<void> {\n return await this.#userStorage.setItem(path, value, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n });\n }\n\n /**\n * Allows storage of multiple user data entries for one specific feature. Data stored must be string formatted.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @param values - data to store, in the form of an array of `[entryKey, entryValue]` pairs\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performBatchSetStorage<\n FeatureName extends UserStoragePathWithFeatureOnly,\n >(\n path: FeatureName,\n values: [UserStorageFeatureKeys<FeatureName>, string][],\n ): Promise<void> {\n return await this.#userStorage.batchSetItems(path, values, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n });\n }\n\n /**\n * Allows deletion of user data. Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @returns nothing. NOTE that an error is thrown if fails to delete data.\n */\n public async performDeleteStorage(\n path: UserStoragePathWithFeatureAndKey,\n ): Promise<void> {\n return await this.#userStorage.deleteItem(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n });\n }\n\n /**\n * Allows deletion of all user data entries for a specific feature.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @returns nothing. NOTE that an error is thrown if fails to delete data.\n */\n public async performDeleteStorageAllFeatureEntries(\n path: UserStoragePathWithFeatureOnly,\n ): Promise<void> {\n return await this.#userStorage.deleteAllFeatureItems(path);\n }\n\n /**\n * Allows delete of multiple user data entries for one specific feature. Data deleted must be string formatted.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @param values - data to store, in the form of an array of entryKey[]\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performBatchDeleteStorage<\n FeatureName extends UserStoragePathWithFeatureOnly,\n >(\n path: FeatureName,\n values: UserStorageFeatureKeys<FeatureName>[],\n ): Promise<void> {\n return await this.#userStorage.batchDeleteItems(path, values);\n }\n\n /**\n * Retrieves the storage key, for internal use only!\n *\n * @returns the storage key\n */\n public async getStorageKey(): Promise<string> {\n return await this.#userStorage.getStorageKey();\n }\n\n /**\n * Flushes the storage key cache.\n * CAUTION: This is only public for testing purposes.\n * It should not be used in production code.\n */\n public flushStorageKeyCache(): void {\n this.#storageKeyCache = {};\n }\n\n #_snapSignMessageCache: Record<`metamask:${string}`, string> = {};\n\n /**\n * Signs a specific message using an underlying auth snap.\n *\n * @param message - A specific tagged message to sign.\n * @returns A Signature created by the snap.\n */\n async #snapSignMessage(message: `metamask:${string}`): Promise<string> {\n if (this.#_snapSignMessageCache[message]) {\n return this.#_snapSignMessageCache[message];\n }\n\n if (!this.#isUnlocked) {\n throw new Error(\n '#snapSignMessage - unable to call snap, wallet is locked',\n );\n }\n\n const result = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n createSnapSignMessageRequest(message),\n )) as string;\n\n this.#_snapSignMessageCache[message] = result;\n\n return result;\n }\n\n #_snapEncryptionKeyCache: string | null = null;\n\n /**\n * Get an encryption public key from the snap\n *\n * @returns The encryption public key used by the snap\n */\n async #snapGetEncryptionPublicKey(): Promise<string> {\n if (this.#_snapEncryptionKeyCache) {\n return this.#_snapEncryptionKeyCache;\n }\n\n if (!this.#isUnlocked) {\n throw new Error(\n '#snapGetEncryptionPublicKey - unable to call snap, wallet is locked',\n );\n }\n\n const result = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n createSnapEncryptionPublicKeyRequest(),\n )) as string;\n\n this.#_snapEncryptionKeyCache = result;\n\n return result;\n }\n\n #_snapDecryptMessageCache: Record<string, string> = {};\n\n /**\n * Calls the snap to attempt to decrypt the message.\n *\n * @param ciphertext - the encrypted text to decrypt.\n * @returns The decrypted message, if decryption was possible.\n */\n async #snapDecryptMessage(ciphertext: string): Promise<string> {\n if (this.#_snapDecryptMessageCache[ciphertext]) {\n return this.#_snapDecryptMessageCache[ciphertext];\n }\n\n if (!this.#isUnlocked) {\n throw new Error(\n '#snapDecryptMessage - unable to call snap, wallet is locked',\n );\n }\n\n const result = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n createSnapDecryptMessageRequest(ciphertext),\n )) as string;\n\n if (result) {\n this.#_snapDecryptMessageCache[ciphertext] = result;\n }\n\n return result;\n }\n\n public async setIsBackupAndSyncFeatureEnabled(\n feature: keyof typeof BACKUPANDSYNC_FEATURES,\n enabled: boolean,\n ): Promise<void> {\n try {\n this.#setIsProfileSyncingUpdateLoading(true);\n\n if (enabled) {\n // If any of the features are enabled, we need to ensure the user is signed in\n const isSignedIn = this.#auth.isSignedIn();\n if (!isSignedIn) {\n await this.#auth.signIn();\n }\n }\n\n this.update((state) => {\n if (feature === BACKUPANDSYNC_FEATURES.main) {\n state.isProfileSyncingEnabled = enabled;\n }\n\n if (feature === BACKUPANDSYNC_FEATURES.accountSyncing) {\n state.isAccountSyncingEnabled = enabled;\n }\n });\n } catch (e) {\n // istanbul ignore next\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n // istanbul ignore next\n throw new Error(\n `${controllerName} - failed to ${enabled ? 'enable' : 'disable'} ${feature} - ${errorMessage}`,\n );\n } finally {\n this.#setIsProfileSyncingUpdateLoading(false);\n }\n }\n\n #setIsProfileSyncingUpdateLoading(\n isProfileSyncingUpdateLoading: boolean,\n ): void {\n this.update((state) => {\n state.isProfileSyncingUpdateLoading = isProfileSyncingUpdateLoading;\n });\n }\n\n async setHasAccountSyncingSyncedAtLeastOnce(\n hasAccountSyncingSyncedAtLeastOnce: boolean,\n ): Promise<void> {\n this.update((state) => {\n state.hasAccountSyncingSyncedAtLeastOnce =\n hasAccountSyncingSyncedAtLeastOnce;\n });\n }\n\n async setIsAccountSyncingReadyToBeDispatched(\n isAccountSyncingReadyToBeDispatched: boolean,\n ): Promise<void> {\n this.update((state) => {\n state.isAccountSyncingReadyToBeDispatched =\n isAccountSyncingReadyToBeDispatched;\n });\n }\n\n async setIsAccountSyncingInProgress(\n isAccountSyncingInProgress: boolean,\n ): Promise<void> {\n this.update((state) => {\n state.isAccountSyncingInProgress = isAccountSyncingInProgress;\n });\n }\n\n /**\n * Syncs the internal accounts list with the user storage accounts list.\n * This method is used to make sure that the internal accounts list is up-to-date with the user storage accounts list and vice-versa.\n * It will add new accounts to the internal accounts list, update/merge conflicting names and re-upload the results in some cases to the user storage.\n */\n async syncInternalAccountsWithUserStorage(): Promise<void> {\n const profileId = await this.#auth.getProfileId();\n\n await syncInternalAccountsWithUserStorage(\n {\n maxNumberOfAccountsToAdd:\n this.#config?.accountSyncing?.maxNumberOfAccountsToAdd,\n onAccountAdded: () =>\n this.#config?.accountSyncing?.onAccountAdded?.(profileId),\n onAccountNameUpdated: () =>\n this.#config?.accountSyncing?.onAccountNameUpdated?.(profileId),\n onAccountSyncErroneousSituation: (situationMessage, sentryContext) =>\n this.#config?.accountSyncing?.onAccountSyncErroneousSituation?.(\n profileId,\n situationMessage,\n sentryContext,\n ),\n },\n {\n getMessenger: () => this.messagingSystem,\n getUserStorageControllerInstance: () => this,\n },\n );\n }\n\n /**\n * Saves an individual internal account to the user storage.\n *\n * @param internalAccount - The internal account to save\n */\n async saveInternalAccountToUserStorage(\n internalAccount: InternalAccount,\n ): Promise<void> {\n await saveInternalAccountToUserStorage(internalAccount, {\n getMessenger: () => this.messagingSystem,\n getUserStorageControllerInstance: () => this,\n });\n }\n\n async syncNetworks() {\n if (!this.#env.isNetworkSyncingEnabled) {\n return;\n }\n\n const profileId = await this.#auth.getProfileId();\n\n await performMainNetworkSync({\n messenger: this.messagingSystem,\n getUserStorageControllerInstance: () => this,\n maxNetworksToAdd: this.#config?.networkSyncing?.maxNumberOfNetworksToAdd,\n onNetworkAdded: (cId) =>\n this.#config?.networkSyncing?.onNetworkAdded?.(profileId, cId),\n onNetworkUpdated: (cId) =>\n this.#config?.networkSyncing?.onNetworkUpdated?.(profileId, cId),\n onNetworkRemoved: (cId) =>\n this.#config?.networkSyncing?.onNetworkRemoved?.(profileId, cId),\n });\n\n this.update((s) => {\n s.hasNetworkSyncingSyncedAtLeastOnce = true;\n });\n }\n}\n"]}
|
|
@@ -23,11 +23,13 @@ var __importStar = (this && this.__importStar) || function (mod) {
|
|
|
23
23
|
return result;
|
|
24
24
|
};
|
|
25
25
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
26
|
-
exports.MOCK_ENCRYPTED_STORAGE_DATA = exports.MOCK_STORAGE_DATA = exports.MOCK_STORAGE_KEY = exports.MOCK_STORAGE_KEY_SIGNATURE = void 0;
|
|
26
|
+
exports.MOCK_ENCRYPTED_STORAGE_DATA = exports.MOCK_ENCRYPTION_PUBLIC_KEY = exports.MOCK_ENCRYPTION_PRIVATE_KEY = exports.MOCK_STORAGE_DATA = exports.MOCK_STORAGE_KEY = exports.MOCK_STORAGE_KEY_SIGNATURE = void 0;
|
|
27
27
|
const encryption_1 = __importStar(require("../../../shared/encryption/index.cjs"));
|
|
28
28
|
exports.MOCK_STORAGE_KEY_SIGNATURE = 'mockStorageKey';
|
|
29
29
|
exports.MOCK_STORAGE_KEY = (0, encryption_1.createSHA256Hash)(exports.MOCK_STORAGE_KEY_SIGNATURE);
|
|
30
30
|
exports.MOCK_STORAGE_DATA = JSON.stringify({ hello: 'world' });
|
|
31
|
+
exports.MOCK_ENCRYPTION_PRIVATE_KEY = '29411742c5cf3d7eb1a0cf57230488900e86778c876078fb87164ec6864841cd';
|
|
32
|
+
exports.MOCK_ENCRYPTION_PUBLIC_KEY = '37a3160dda3e0086a89974854f1ba7c3e6b1bc960e06311bcc4c15264d95ee36';
|
|
31
33
|
// NOTE - using encryption.encryptString directly in fixtures causes issues on mobile.
|
|
32
34
|
// This is because this fixture is getting added in at run time. Will be improved once we support multiple exports
|
|
33
35
|
let cachedMockEncryptedData;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mockStorage.cjs","sourceRoot":"","sources":["../../../../src/controllers/user-storage/mocks/mockStorage.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,mFAA0E;AAE7D,QAAA,0BAA0B,GAAG,gBAAgB,CAAC;AAC9C,QAAA,gBAAgB,GAAG,IAAA,6BAAgB,EAAC,kCAA0B,CAAC,CAAC;AAChE,QAAA,iBAAiB,GAAG,IAAI,CAAC,SAAS,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"mockStorage.cjs","sourceRoot":"","sources":["../../../../src/controllers/user-storage/mocks/mockStorage.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,mFAA0E;AAE7D,QAAA,0BAA0B,GAAG,gBAAgB,CAAC;AAC9C,QAAA,gBAAgB,GAAG,IAAA,6BAAgB,EAAC,kCAA0B,CAAC,CAAC;AAChE,QAAA,iBAAiB,GAAG,IAAI,CAAC,SAAS,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;AACvD,QAAA,2BAA2B,GACtC,kEAAkE,CAAC;AACxD,QAAA,0BAA0B,GACrC,kEAAkE,CAAC;AAErE,sFAAsF;AACtF,kHAAkH;AAClH,IAAI,uBAA+B,CAAC;AAC7B,MAAM,2BAA2B,GAAG,KAAK,EAAE,IAAa,EAAE,EAAE,CACjE,CAAC,uBAAuB,KAAvB,uBAAuB,GAAK,MAAM,oBAAU,CAAC,aAAa,CACzD,IAAI,IAAI,yBAAiB,EACzB,wBAAgB,CACjB,EAAC,CAAC;AAJQ,QAAA,2BAA2B,+BAInC","sourcesContent":["import encryption, { createSHA256Hash } from '../../../shared/encryption';\n\nexport const MOCK_STORAGE_KEY_SIGNATURE = 'mockStorageKey';\nexport const MOCK_STORAGE_KEY = createSHA256Hash(MOCK_STORAGE_KEY_SIGNATURE);\nexport const MOCK_STORAGE_DATA = JSON.stringify({ hello: 'world' });\nexport const MOCK_ENCRYPTION_PRIVATE_KEY =\n '29411742c5cf3d7eb1a0cf57230488900e86778c876078fb87164ec6864841cd';\nexport const MOCK_ENCRYPTION_PUBLIC_KEY =\n '37a3160dda3e0086a89974854f1ba7c3e6b1bc960e06311bcc4c15264d95ee36';\n\n// NOTE - using encryption.encryptString directly in fixtures causes issues on mobile.\n// This is because this fixture is getting added in at run time. Will be improved once we support multiple exports\nlet cachedMockEncryptedData: string;\nexport const MOCK_ENCRYPTED_STORAGE_DATA = async (data?: string) =>\n (cachedMockEncryptedData ??= await encryption.encryptString(\n data ?? MOCK_STORAGE_DATA,\n MOCK_STORAGE_KEY,\n ));\n"]}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
export declare const MOCK_STORAGE_KEY_SIGNATURE = "mockStorageKey";
|
|
2
2
|
export declare const MOCK_STORAGE_KEY: string;
|
|
3
3
|
export declare const MOCK_STORAGE_DATA: string;
|
|
4
|
+
export declare const MOCK_ENCRYPTION_PRIVATE_KEY = "29411742c5cf3d7eb1a0cf57230488900e86778c876078fb87164ec6864841cd";
|
|
5
|
+
export declare const MOCK_ENCRYPTION_PUBLIC_KEY = "37a3160dda3e0086a89974854f1ba7c3e6b1bc960e06311bcc4c15264d95ee36";
|
|
4
6
|
export declare const MOCK_ENCRYPTED_STORAGE_DATA: (data?: string) => Promise<string>;
|
|
5
7
|
//# sourceMappingURL=mockStorage.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mockStorage.d.cts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/mocks/mockStorage.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,0BAA0B,mBAAmB,CAAC;AAC3D,eAAO,MAAM,gBAAgB,QAA+C,CAAC;AAC7E,eAAO,MAAM,iBAAiB,QAAqC,CAAC;
|
|
1
|
+
{"version":3,"file":"mockStorage.d.cts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/mocks/mockStorage.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,0BAA0B,mBAAmB,CAAC;AAC3D,eAAO,MAAM,gBAAgB,QAA+C,CAAC;AAC7E,eAAO,MAAM,iBAAiB,QAAqC,CAAC;AACpE,eAAO,MAAM,2BAA2B,qEAC4B,CAAC;AACrE,eAAO,MAAM,0BAA0B,qEAC6B,CAAC;AAKrE,eAAO,MAAM,2BAA2B,UAAiB,MAAM,oBAI3D,CAAC"}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
export declare const MOCK_STORAGE_KEY_SIGNATURE = "mockStorageKey";
|
|
2
2
|
export declare const MOCK_STORAGE_KEY: string;
|
|
3
3
|
export declare const MOCK_STORAGE_DATA: string;
|
|
4
|
+
export declare const MOCK_ENCRYPTION_PRIVATE_KEY = "29411742c5cf3d7eb1a0cf57230488900e86778c876078fb87164ec6864841cd";
|
|
5
|
+
export declare const MOCK_ENCRYPTION_PUBLIC_KEY = "37a3160dda3e0086a89974854f1ba7c3e6b1bc960e06311bcc4c15264d95ee36";
|
|
4
6
|
export declare const MOCK_ENCRYPTED_STORAGE_DATA: (data?: string) => Promise<string>;
|
|
5
7
|
//# sourceMappingURL=mockStorage.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mockStorage.d.mts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/mocks/mockStorage.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,0BAA0B,mBAAmB,CAAC;AAC3D,eAAO,MAAM,gBAAgB,QAA+C,CAAC;AAC7E,eAAO,MAAM,iBAAiB,QAAqC,CAAC;
|
|
1
|
+
{"version":3,"file":"mockStorage.d.mts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/mocks/mockStorage.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,0BAA0B,mBAAmB,CAAC;AAC3D,eAAO,MAAM,gBAAgB,QAA+C,CAAC;AAC7E,eAAO,MAAM,iBAAiB,QAAqC,CAAC;AACpE,eAAO,MAAM,2BAA2B,qEAC4B,CAAC;AACrE,eAAO,MAAM,0BAA0B,qEAC6B,CAAC;AAKrE,eAAO,MAAM,2BAA2B,UAAiB,MAAM,oBAI3D,CAAC"}
|
|
@@ -2,6 +2,8 @@ import encryption, { createSHA256Hash } from "../../../shared/encryption/index.m
|
|
|
2
2
|
export const MOCK_STORAGE_KEY_SIGNATURE = 'mockStorageKey';
|
|
3
3
|
export const MOCK_STORAGE_KEY = createSHA256Hash(MOCK_STORAGE_KEY_SIGNATURE);
|
|
4
4
|
export const MOCK_STORAGE_DATA = JSON.stringify({ hello: 'world' });
|
|
5
|
+
export const MOCK_ENCRYPTION_PRIVATE_KEY = '29411742c5cf3d7eb1a0cf57230488900e86778c876078fb87164ec6864841cd';
|
|
6
|
+
export const MOCK_ENCRYPTION_PUBLIC_KEY = '37a3160dda3e0086a89974854f1ba7c3e6b1bc960e06311bcc4c15264d95ee36';
|
|
5
7
|
// NOTE - using encryption.encryptString directly in fixtures causes issues on mobile.
|
|
6
8
|
// This is because this fixture is getting added in at run time. Will be improved once we support multiple exports
|
|
7
9
|
let cachedMockEncryptedData;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mockStorage.mjs","sourceRoot":"","sources":["../../../../src/controllers/user-storage/mocks/mockStorage.ts"],"names":[],"mappings":"AAAA,OAAO,UAAU,EAAE,EAAE,gBAAgB,EAAE,6CAAmC;AAE1E,MAAM,CAAC,MAAM,0BAA0B,GAAG,gBAAgB,CAAC;AAC3D,MAAM,CAAC,MAAM,gBAAgB,GAAG,gBAAgB,CAAC,0BAA0B,CAAC,CAAC;AAC7E,MAAM,CAAC,MAAM,iBAAiB,GAAG,IAAI,CAAC,SAAS,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"mockStorage.mjs","sourceRoot":"","sources":["../../../../src/controllers/user-storage/mocks/mockStorage.ts"],"names":[],"mappings":"AAAA,OAAO,UAAU,EAAE,EAAE,gBAAgB,EAAE,6CAAmC;AAE1E,MAAM,CAAC,MAAM,0BAA0B,GAAG,gBAAgB,CAAC;AAC3D,MAAM,CAAC,MAAM,gBAAgB,GAAG,gBAAgB,CAAC,0BAA0B,CAAC,CAAC;AAC7E,MAAM,CAAC,MAAM,iBAAiB,GAAG,IAAI,CAAC,SAAS,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;AACpE,MAAM,CAAC,MAAM,2BAA2B,GACtC,kEAAkE,CAAC;AACrE,MAAM,CAAC,MAAM,0BAA0B,GACrC,kEAAkE,CAAC;AAErE,sFAAsF;AACtF,kHAAkH;AAClH,IAAI,uBAA+B,CAAC;AACpC,MAAM,CAAC,MAAM,2BAA2B,GAAG,KAAK,EAAE,IAAa,EAAE,EAAE,CACjE,CAAC,uBAAuB,KAAvB,uBAAuB,GAAK,MAAM,UAAU,CAAC,aAAa,CACzD,IAAI,IAAI,iBAAiB,EACzB,gBAAgB,CACjB,EAAC,CAAC","sourcesContent":["import encryption, { createSHA256Hash } from '../../../shared/encryption';\n\nexport const MOCK_STORAGE_KEY_SIGNATURE = 'mockStorageKey';\nexport const MOCK_STORAGE_KEY = createSHA256Hash(MOCK_STORAGE_KEY_SIGNATURE);\nexport const MOCK_STORAGE_DATA = JSON.stringify({ hello: 'world' });\nexport const MOCK_ENCRYPTION_PRIVATE_KEY =\n '29411742c5cf3d7eb1a0cf57230488900e86778c876078fb87164ec6864841cd';\nexport const MOCK_ENCRYPTION_PUBLIC_KEY =\n '37a3160dda3e0086a89974854f1ba7c3e6b1bc960e06311bcc4c15264d95ee36';\n\n// NOTE - using encryption.encryptString directly in fixtures causes issues on mobile.\n// This is because this fixture is getting added in at run time. Will be improved once we support multiple exports\nlet cachedMockEncryptedData: string;\nexport const MOCK_ENCRYPTED_STORAGE_DATA = async (data?: string) =>\n (cachedMockEncryptedData ??= await encryption.encryptString(\n data ?? MOCK_STORAGE_DATA,\n MOCK_STORAGE_KEY,\n ));\n"]}
|
|
@@ -30,9 +30,7 @@ exports.isMainNetworkSyncInProgress = false;
|
|
|
30
30
|
function startNetworkSyncing(props) {
|
|
31
31
|
const { messenger, isMutationSyncBlocked, getUserStorageControllerInstance } = props;
|
|
32
32
|
try {
|
|
33
|
-
messenger.subscribe('NetworkController:networkRemoved',
|
|
34
|
-
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
|
35
|
-
async (networkConfiguration) => {
|
|
33
|
+
messenger.subscribe('NetworkController:networkRemoved', async (networkConfiguration) => {
|
|
36
34
|
try {
|
|
37
35
|
// If blocked (e.g. we have not yet performed a main-sync), then we should not perform any mutations
|
|
38
36
|
if (isMutationSyncBlocked()) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"controller-integration.cjs","sourceRoot":"","sources":["../../../../src/controllers/user-storage/network-syncing/controller-integration.ts"],"names":[],"mappings":";;;;;;AACA,wDAA2B;AAE3B,+DAA8D;AAC9D,6CAAkD;AAClD,6CAAkD;AAClD,yDAAsE;AACtE,qEAAkE;AAmBlE;;;GAGG;AACH,2BAA2B;AAC3B,uDAAuD;AAC5C,QAAA,2BAA2B,GAAG,KAAK,CAAC;AAE/C;;;;;;;;;GASG;AACH,SAAgB,mBAAmB,CAAC,KAA+B;IACjE,MAAM,EAAE,SAAS,EAAE,qBAAqB,EAAE,gCAAgC,EAAE,GAC1E,KAAK,CAAC;IACR,IAAI;QACF,SAAS,CAAC,SAAS,CACjB,kCAAkC;QAElC,kEAAkE;QAClE,KAAK,EAAE,oBAAoB,EAAE,EAAE;YAC7B,IAAI;gBACF,oGAAoG;gBACpG,IAAI,qBAAqB,EAAE,EAAE;oBAC3B,OAAO;iBACR;gBAED,yEAAyE;gBACzE,kCAAkC;gBAClC,IAAI,mCAA2B,EAAE;oBAC/B,OAAO;iBACR;gBAED,MAAM,IAAA,8BAAa,EAAC,oBAAoB,EAAE;oBACxC,gCAAgC;iBACjC,CAAC,CAAC;aACJ;YAAC,MAAM;gBACN,qBAAqB;aACtB;QACH,CAAC,CACF,CAAC;KACH;IAAC,OAAO,CAAC,EAAE;QACV,kBAAG,CAAC,IAAI,CAAC,2CAA2C,EAAE,CAAC,CAAC,CAAC;KAC1D;AACH,CAAC;AAhCD,kDAgCC;AAED;;;;;;;;;GASG;AACI,MAAM,qBAAqB,GAAG,KAAK,EAAE,KAK3C,EAAE,EAAE;IACH,MAAM,EACJ,SAAS,EACT,4BAA4B,EAC5B,uBAAuB,EACvB,uBAAuB,GACxB,GAAG,KAAK,CAAC;IAEV,MAAM,EAAE,mBAAmB,EAAE,2BAA2B,EAAE,GACxD,IAAA,+CAAwB,EAAC;Q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oBACf,yDAAyD;iBAC1D;aACF;YAED,+DAA+D;YAC/D,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE;gBACrB,kBAAG,CAAC,KAAK,CACP,mEAAmE,EACnE,MAAM,CACP,CAAC;aACH;SACF;QAED,wBAAwB;QACxB,IACE,cAAc,EAAE,qBAAqB;YACrC,cAAc,CAAC,qBAAqB,CAAC,MAAM,GAAG,CAAC,EAC/C;YACA,MAAM,MAAM,GAAc,EAAE,CAAC;YAC7B,cAAc,CAAC,qBAAqB,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE;gBACjD,IAAI;oBACF,SAAS,CAAC,IAAI,CAAC,iCAAiC,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC;oBAC7D,gBAAgB,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;iBAC/B;gBAAC,OAAO,CAAC,EAAE;oBACV,gEAAgE;oBAChE,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;oBACf,yDAAyD;iBAC1D;YACH,CAAC,CAAC,CAAC;YAEH,+DAA+D;YAC/D,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE;gBACrB,kBAAG,CAAC,KAAK,CACP,mEAAmE,EACnE,MAAM,CACP,CAAC;aACH;SACF;KACF;IAAC,OAAO,CAAC,EAAE;QACV,iEAAiE;QACjE,kBAAG,CAAC,KAAK,CAAC,iCAAiC,EAAE,CAAC,CAAC,CAAC;QAChD,qBAAqB;KACtB;YAAS;QACR,mCAA2B,GAAG,KAAK,CAAC;KACrC;AACH,CAAC;AAhJD,wDAgJC","sourcesContent":["import type { NetworkConfiguration } from '@metamask/network-controller';\nimport log from 'loglevel';\n\nimport { getBoundedNetworksToAdd } from './add-network-utils';\nimport { getAllRemoteNetworks } from './services';\nimport { findNetworksToUpdate } from './sync-all';\nimport { batchUpdateNetworks, deleteNetwork } from './sync-mutations';\nimport { createUpdateNetworkProps } from './update-network-utils';\nimport type UserStorageController from '../UserStorageController';\nimport type { UserStorageControllerMessenger } from '../UserStorageController';\n\ntype StartNetworkSyncingProps = {\n messenger: UserStorageControllerMessenger;\n getUserStorageControllerInstance: () => UserStorageController;\n isMutationSyncBlocked: () => boolean;\n};\n\ntype PerformMainNetworkSyncProps = {\n messenger: UserStorageControllerMessenger;\n getUserStorageControllerInstance: () => UserStorageController;\n maxNetworksToAdd?: number;\n onNetworkAdded?: (chainId: string) => void;\n onNetworkUpdated?: (chainId: string) => void;\n onNetworkRemoved?: (chainId: string) => void;\n};\n\n/**\n * Global in-mem cache to signify that the network syncing is in progress\n * Ensures that listeners do not fire during main sync (prevent double requests)\n */\n// Exported to help testing\n// eslint-disable-next-line import-x/no-mutable-exports\nexport let isMainNetworkSyncInProgress = false;\n\n/**\n * Initialize and setup events to listen to for network syncing\n * We will be listening to:\n * - Remove Event, to indicate that we need to remote network from remote\n *\n * We will not be listening to:\n * - Add/Update events are not required, as we can sync these during the main sync\n *\n * @param props - parameters used for initializing and enabling network syncing\n */\nexport function startNetworkSyncing(props: StartNetworkSyncingProps) {\n const { messenger, isMutationSyncBlocked, getUserStorageControllerInstance } =\n props;\n try {\n messenger.subscribe(\n 'NetworkController:networkRemoved',\n\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async (networkConfiguration) => {\n try {\n // If blocked (e.g. we have not yet performed a main-sync), then we should not perform any mutations\n if (isMutationSyncBlocked()) {\n return;\n }\n\n // As main sync is in progress, it will already local and remote networks\n // So no need to re-process again.\n if (isMainNetworkSyncInProgress) {\n return;\n }\n\n await deleteNetwork(networkConfiguration, {\n getUserStorageControllerInstance,\n });\n } catch {\n // Silently fail sync\n }\n },\n );\n } catch (e) {\n log.warn('NetworkSyncing, event subscription failed', e);\n }\n}\n\n/**\n * method that will dispatch the `NetworkController:updateNetwork` action.\n * transforms and corrects the network configuration (and RPCs) we pass through.\n *\n * @param props - properties\n * @param props.messenger - messenger to call the action\n * @param props.originalNetworkConfiguration - original network config (from network controller state)\n * @param props.newNetworkConfiguration - new network config (from remote)\n * @param props.selectedNetworkClientId - currently selected network client id\n */\nexport const dispatchUpdateNetwork = async (props: {\n messenger: UserStorageControllerMessenger;\n originalNetworkConfiguration: NetworkConfiguration;\n newNetworkConfiguration: NetworkConfiguration;\n selectedNetworkClientId: string;\n}) => {\n const {\n messenger,\n originalNetworkConfiguration,\n newNetworkConfiguration,\n selectedNetworkClientId,\n } = props;\n\n const { updateNetworkFields, newSelectedRpcEndpointIndex } =\n createUpdateNetworkProps({\n originalNetworkConfiguration,\n newNetworkConfiguration,\n selectedNetworkClientId,\n });\n\n await messenger.call(\n 'NetworkController:updateNetwork',\n updateNetworkFields.chainId,\n updateNetworkFields,\n { replacementSelectedRpcEndpointIndex: newSelectedRpcEndpointIndex },\n );\n};\n\n/**\n * Action to perform the main network sync.\n * It will fetch local networks and remote networks, then determines which networks (local and remote) to add/update\n *\n * @param props - parameters used for this main sync\n */\nexport async function performMainNetworkSync(\n props: PerformMainNetworkSyncProps,\n) {\n const {\n messenger,\n maxNetworksToAdd,\n onNetworkAdded,\n onNetworkRemoved,\n onNetworkUpdated,\n getUserStorageControllerInstance,\n } = props;\n\n // Edge-Case, we do not want to re-run the main-sync if it already is in progress\n /* istanbul ignore if - this is not testable */\n if (isMainNetworkSyncInProgress) {\n return;\n }\n\n isMainNetworkSyncInProgress = true;\n try {\n const networkControllerState = messenger.call('NetworkController:getState');\n const localNetworks = Object.values(\n networkControllerState.networkConfigurationsByChainId ?? {},\n );\n\n const remoteNetworks = await getAllRemoteNetworks({\n getUserStorageControllerInstance,\n });\n const networkChanges = findNetworksToUpdate({\n localNetworks,\n remoteNetworks,\n });\n\n log.debug('performMainNetworkSync() - Network Syncing Started', {\n localNetworks,\n remoteNetworks,\n networkChanges,\n });\n\n // Update Remote\n if (\n networkChanges?.remoteNetworksToUpdate &&\n networkChanges.remoteNetworksToUpdate.length > 0\n ) {\n await batchUpdateNetworks(networkChanges?.remoteNetworksToUpdate, {\n getUserStorageControllerInstance,\n });\n }\n\n // Add missing local networks\n const boundedNetworkedToAdd =\n networkChanges?.missingLocalNetworks &&\n getBoundedNetworksToAdd(\n localNetworks,\n networkChanges.missingLocalNetworks,\n maxNetworksToAdd,\n );\n if (boundedNetworkedToAdd && boundedNetworkedToAdd.length > 0) {\n const errors: unknown[] = [];\n boundedNetworkedToAdd.forEach((n) => {\n try {\n messenger.call('NetworkController:addNetwork', n);\n onNetworkAdded?.(n.chainId);\n } catch (e) {\n /* istanbul ignore next - allocates logs, do not need to test */\n errors.push(e);\n // Silently fail, we can try this again on next main sync\n }\n });\n\n /* istanbul ignore if - only logs errors, not useful to test */\n if (errors.length > 0) {\n log.error(\n 'performMainNetworkSync() - NetworkController:addNetwork failures',\n errors,\n );\n }\n }\n\n // Update local networks\n if (\n networkChanges?.localNetworksToUpdate &&\n networkChanges.localNetworksToUpdate.length > 0\n ) {\n const errors: unknown[] = [];\n for (const n of networkChanges.localNetworksToUpdate) {\n try {\n await dispatchUpdateNetwork({\n messenger,\n originalNetworkConfiguration:\n networkControllerState.networkConfigurationsByChainId[n.chainId],\n newNetworkConfiguration: n,\n selectedNetworkClientId:\n networkControllerState.selectedNetworkClientId,\n });\n onNetworkUpdated?.(n.chainId);\n } catch (e) {\n /* istanbul ignore next - allocates logs, do not need to test */\n errors.push(e);\n // Silently fail, we can try this again on next main sync\n }\n }\n\n /* istanbul ignore if - only logs errors, not useful to test */\n if (errors.length > 0) {\n log.error(\n 'performMainNetworkSync() - NetworkController:updateNetwork failed',\n errors,\n );\n }\n }\n\n // Remove local networks\n if (\n networkChanges?.localNetworksToRemove &&\n networkChanges.localNetworksToRemove.length > 0\n ) {\n const errors: unknown[] = [];\n networkChanges.localNetworksToRemove.forEach((n) => {\n try {\n messenger.call('NetworkController:removeNetwork', n.chainId);\n onNetworkRemoved?.(n.chainId);\n } catch (e) {\n /* istanbul ignore next - allocates logs, do not need to test */\n errors.push(e);\n // Silently fail, we can try this again on next main sync\n }\n });\n\n /* istanbul ignore if - only logs errors, not useful to test */\n if (errors.length > 0) {\n log.error(\n 'performMainNetworkSync() - NetworkController:removeNetwork failed',\n errors,\n );\n }\n }\n } catch (e) {\n /* istanbul ignore next - only logs errors, not useful to test */\n log.error('performMainNetworkSync() failed', e);\n // Silently fail sync\n } finally {\n isMainNetworkSyncInProgress = false;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"controller-integration.cjs","sourceRoot":"","sources":["../../../../src/controllers/user-storage/network-syncing/controller-integration.ts"],"names":[],"mappings":";;;;;;AACA,wDAA2B;AAE3B,+DAA8D;AAC9D,6CAAkD;AAClD,6CAAkD;AAClD,yDAAsE;AACtE,qEAAkE;AAmBlE;;;GAGG;AACH,2BAA2B;AAC3B,uDAAuD;AAC5C,QAAA,2BAA2B,GAAG,KAAK,CAAC;AAE/C;;;;;;;;;GASG;AACH,SAAgB,mBAAmB,CAAC,KAA+B;IACjE,MAAM,EAAE,SAAS,EAAE,qBAAqB,EAAE,gCAAgC,EAAE,GAC1E,KAAK,CAAC;IACR,IAAI;QACF,SAAS,CAAC,SAAS,CACjB,kCAAkC,EAClC,KAAK,EAAE,oBAAoB,EAAE,EAAE;YAC7B,IAAI;gBACF,oGAAoG;gBACpG,IAAI,qBAAqB,EAAE,EAAE;oBAC3B,OAAO;iBACR;gBAED,yEAAyE;gBACzE,kCAAkC;gBAClC,IAAI,mCAA2B,EAAE;oBAC/B,OAAO;iBACR;gBAED,MAAM,IAAA,8BAAa,EAAC,oBAAoB,EAAE;oBACxC,gCAAgC;iBACjC,CAAC,CAAC;aACJ;YAAC,MAAM;gBACN,qBAAqB;aACtB;QACH,CAAC,CACF,CAAC;KACH;IAAC,OAAO,CAAC,EAAE;QACV,kBAAG,CAAC,IAAI,CAAC,2CAA2C,EAAE,CAAC,CAAC,CAAC;KAC1D;AACH,CAAC;AA9BD,kDA8BC;AAED;;;;;;;;;GASG;AACI,MAAM,qBAAqB,GAAG,KAAK,EAAE,KAK3C,EAAE,EAAE;IACH,MAAM,EACJ,SAAS,EACT,4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E,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;iBAC/B;gBAAC,OAAO,CAAC,EAAE;oBACV,gEAAgE;oBAChE,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;oBACf,yDAAyD;iBAC1D;aACF;YAED,+DAA+D;YAC/D,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE;gBACrB,kBAAG,CAAC,KAAK,CACP,mEAAmE,EACnE,MAAM,CACP,CAAC;aACH;SACF;QAED,wBAAwB;QACxB,IACE,cAAc,EAAE,qBAAqB;YACrC,cAAc,CAAC,qBAAqB,CAAC,MAAM,GAAG,CAAC,EAC/C;YACA,MAAM,MAAM,GAAc,EAAE,CAAC;YAC7B,cAAc,CAAC,qBAAqB,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE;gBACjD,IAAI;oBACF,SAAS,CAAC,IAAI,CAAC,iCAAiC,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC;oBAC7D,gBAAgB,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;iBAC/B;gBAAC,OAAO,CAAC,EAAE;oBACV,gEAAgE;oBAChE,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;oBACf,yDAAyD;iBAC1D;YACH,CAAC,CAAC,CAAC;YAEH,+DAA+D;YAC/D,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE;gBACrB,kBAAG,CAAC,KAAK,CACP,mEAAmE,EACnE,MAAM,CACP,CAAC;aACH;SACF;KACF;IAAC,OAAO,CAAC,EAAE;QACV,iEAAiE;QACjE,kBAAG,CAAC,KAAK,CAAC,iCAAiC,EAAE,CAAC,CAAC,CAAC;QAChD,qBAAqB;KACtB;YAAS;QACR,mCAA2B,GAAG,KAAK,CAAC;KACrC;AACH,CAAC;AAhJD,wDAgJC","sourcesContent":["import type { NetworkConfiguration } from '@metamask/network-controller';\nimport log from 'loglevel';\n\nimport { getBoundedNetworksToAdd } from './add-network-utils';\nimport { getAllRemoteNetworks } from './services';\nimport { findNetworksToUpdate } from './sync-all';\nimport { batchUpdateNetworks, deleteNetwork } from './sync-mutations';\nimport { createUpdateNetworkProps } from './update-network-utils';\nimport type UserStorageController from '../UserStorageController';\nimport type { UserStorageControllerMessenger } from '../UserStorageController';\n\ntype StartNetworkSyncingProps = {\n messenger: UserStorageControllerMessenger;\n getUserStorageControllerInstance: () => UserStorageController;\n isMutationSyncBlocked: () => boolean;\n};\n\ntype PerformMainNetworkSyncProps = {\n messenger: UserStorageControllerMessenger;\n getUserStorageControllerInstance: () => UserStorageController;\n maxNetworksToAdd?: number;\n onNetworkAdded?: (chainId: string) => void;\n onNetworkUpdated?: (chainId: string) => void;\n onNetworkRemoved?: (chainId: string) => void;\n};\n\n/**\n * Global in-mem cache to signify that the network syncing is in progress\n * Ensures that listeners do not fire during main sync (prevent double requests)\n */\n// Exported to help testing\n// eslint-disable-next-line import-x/no-mutable-exports\nexport let isMainNetworkSyncInProgress = false;\n\n/**\n * Initialize and setup events to listen to for network syncing\n * We will be listening to:\n * - Remove Event, to indicate that we need to remote network from remote\n *\n * We will not be listening to:\n * - Add/Update events are not required, as we can sync these during the main sync\n *\n * @param props - parameters used for initializing and enabling network syncing\n */\nexport function startNetworkSyncing(props: StartNetworkSyncingProps) {\n const { messenger, isMutationSyncBlocked, getUserStorageControllerInstance } =\n props;\n try {\n messenger.subscribe(\n 'NetworkController:networkRemoved',\n async (networkConfiguration) => {\n try {\n // If blocked (e.g. we have not yet performed a main-sync), then we should not perform any mutations\n if (isMutationSyncBlocked()) {\n return;\n }\n\n // As main sync is in progress, it will already local and remote networks\n // So no need to re-process again.\n if (isMainNetworkSyncInProgress) {\n return;\n }\n\n await deleteNetwork(networkConfiguration, {\n getUserStorageControllerInstance,\n });\n } catch {\n // Silently fail sync\n }\n },\n );\n } catch (e) {\n log.warn('NetworkSyncing, event subscription failed', e);\n }\n}\n\n/**\n * method that will dispatch the `NetworkController:updateNetwork` action.\n * transforms and corrects the network configuration (and RPCs) we pass through.\n *\n * @param props - properties\n * @param props.messenger - messenger to call the action\n * @param props.originalNetworkConfiguration - original network config (from network controller state)\n * @param props.newNetworkConfiguration - new network config (from remote)\n * @param props.selectedNetworkClientId - currently selected network client id\n */\nexport const dispatchUpdateNetwork = async (props: {\n messenger: UserStorageControllerMessenger;\n originalNetworkConfiguration: NetworkConfiguration;\n newNetworkConfiguration: NetworkConfiguration;\n selectedNetworkClientId: string;\n}) => {\n const {\n messenger,\n originalNetworkConfiguration,\n newNetworkConfiguration,\n selectedNetworkClientId,\n } = props;\n\n const { updateNetworkFields, newSelectedRpcEndpointIndex } =\n createUpdateNetworkProps({\n originalNetworkConfiguration,\n newNetworkConfiguration,\n selectedNetworkClientId,\n });\n\n await messenger.call(\n 'NetworkController:updateNetwork',\n updateNetworkFields.chainId,\n updateNetworkFields,\n { replacementSelectedRpcEndpointIndex: newSelectedRpcEndpointIndex },\n );\n};\n\n/**\n * Action to perform the main network sync.\n * It will fetch local networks and remote networks, then determines which networks (local and remote) to add/update\n *\n * @param props - parameters used for this main sync\n */\nexport async function performMainNetworkSync(\n props: PerformMainNetworkSyncProps,\n) {\n const {\n messenger,\n maxNetworksToAdd,\n onNetworkAdded,\n onNetworkRemoved,\n onNetworkUpdated,\n getUserStorageControllerInstance,\n } = props;\n\n // Edge-Case, we do not want to re-run the main-sync if it already is in progress\n /* istanbul ignore if - this is not testable */\n if (isMainNetworkSyncInProgress) {\n return;\n }\n\n isMainNetworkSyncInProgress = true;\n try {\n const networkControllerState = messenger.call('NetworkController:getState');\n const localNetworks = Object.values(\n networkControllerState.networkConfigurationsByChainId ?? {},\n );\n\n const remoteNetworks = await getAllRemoteNetworks({\n getUserStorageControllerInstance,\n });\n const networkChanges = findNetworksToUpdate({\n localNetworks,\n remoteNetworks,\n });\n\n log.debug('performMainNetworkSync() - Network Syncing Started', {\n localNetworks,\n remoteNetworks,\n networkChanges,\n });\n\n // Update Remote\n if (\n networkChanges?.remoteNetworksToUpdate &&\n networkChanges.remoteNetworksToUpdate.length > 0\n ) {\n await batchUpdateNetworks(networkChanges?.remoteNetworksToUpdate, {\n getUserStorageControllerInstance,\n });\n }\n\n // Add missing local networks\n const boundedNetworkedToAdd =\n networkChanges?.missingLocalNetworks &&\n getBoundedNetworksToAdd(\n localNetworks,\n networkChanges.missingLocalNetworks,\n maxNetworksToAdd,\n );\n if (boundedNetworkedToAdd && boundedNetworkedToAdd.length > 0) {\n const errors: unknown[] = [];\n boundedNetworkedToAdd.forEach((n) => {\n try {\n messenger.call('NetworkController:addNetwork', n);\n onNetworkAdded?.(n.chainId);\n } catch (e) {\n /* istanbul ignore next - allocates logs, do not need to test */\n errors.push(e);\n // Silently fail, we can try this again on next main sync\n }\n });\n\n /* istanbul ignore if - only logs errors, not useful to test */\n if (errors.length > 0) {\n log.error(\n 'performMainNetworkSync() - NetworkController:addNetwork failures',\n errors,\n );\n }\n }\n\n // Update local networks\n if (\n networkChanges?.localNetworksToUpdate &&\n networkChanges.localNetworksToUpdate.length > 0\n ) {\n const errors: unknown[] = [];\n for (const n of networkChanges.localNetworksToUpdate) {\n try {\n await dispatchUpdateNetwork({\n messenger,\n originalNetworkConfiguration:\n networkControllerState.networkConfigurationsByChainId[n.chainId],\n newNetworkConfiguration: n,\n selectedNetworkClientId:\n networkControllerState.selectedNetworkClientId,\n });\n onNetworkUpdated?.(n.chainId);\n } catch (e) {\n /* istanbul ignore next - allocates logs, do not need to test */\n errors.push(e);\n // Silently fail, we can try this again on next main sync\n }\n }\n\n /* istanbul ignore if - only logs errors, not useful to test */\n if (errors.length > 0) {\n log.error(\n 'performMainNetworkSync() - NetworkController:updateNetwork failed',\n errors,\n );\n }\n }\n\n // Remove local networks\n if (\n networkChanges?.localNetworksToRemove &&\n networkChanges.localNetworksToRemove.length > 0\n ) {\n const errors: unknown[] = [];\n networkChanges.localNetworksToRemove.forEach((n) => {\n try {\n messenger.call('NetworkController:removeNetwork', n.chainId);\n onNetworkRemoved?.(n.chainId);\n } catch (e) {\n /* istanbul ignore next - allocates logs, do not need to test */\n errors.push(e);\n // Silently fail, we can try this again on next main sync\n }\n });\n\n /* istanbul ignore if - only logs errors, not useful to test */\n if (errors.length > 0) {\n log.error(\n 'performMainNetworkSync() - NetworkController:removeNetwork failed',\n errors,\n );\n }\n }\n } catch (e) {\n /* istanbul ignore next - only logs errors, not useful to test */\n log.error('performMainNetworkSync() failed', e);\n // Silently fail sync\n } finally {\n isMainNetworkSyncInProgress = false;\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"controller-integration.d.cts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/network-syncing/controller-integration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,qCAAqC;AAQzE,OAAO,KAAK,qBAAqB,qCAAiC;AAClE,OAAO,KAAK,EAAE,8BAA8B,EAAE,qCAAiC;AAE/E,KAAK,wBAAwB,GAAG;IAC9B,SAAS,EAAE,8BAA8B,CAAC;IAC1C,gCAAgC,EAAE,MAAM,qBAAqB,CAAC;IAC9D,qBAAqB,EAAE,MAAM,OAAO,CAAC;CACtC,CAAC;AAEF,KAAK,2BAA2B,GAAG;IACjC,SAAS,EAAE,8BAA8B,CAAC;IAC1C,gCAAgC,EAAE,MAAM,qBAAqB,CAAC;IAC9D,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,cAAc,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;IAC3C,gBAAgB,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;IAC7C,gBAAgB,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;CAC9C,CAAC;AAEF;;;GAGG;AAGH,eAAO,IAAI,2BAA2B,SAAQ,CAAC;AAE/C;;;;;;;;;GASG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,wBAAwB,
|
|
1
|
+
{"version":3,"file":"controller-integration.d.cts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/network-syncing/controller-integration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,qCAAqC;AAQzE,OAAO,KAAK,qBAAqB,qCAAiC;AAClE,OAAO,KAAK,EAAE,8BAA8B,EAAE,qCAAiC;AAE/E,KAAK,wBAAwB,GAAG;IAC9B,SAAS,EAAE,8BAA8B,CAAC;IAC1C,gCAAgC,EAAE,MAAM,qBAAqB,CAAC;IAC9D,qBAAqB,EAAE,MAAM,OAAO,CAAC;CACtC,CAAC;AAEF,KAAK,2BAA2B,GAAG;IACjC,SAAS,EAAE,8BAA8B,CAAC;IAC1C,gCAAgC,EAAE,MAAM,qBAAqB,CAAC;IAC9D,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,cAAc,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;IAC3C,gBAAgB,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;IAC7C,gBAAgB,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;CAC9C,CAAC;AAEF;;;GAGG;AAGH,eAAO,IAAI,2BAA2B,SAAQ,CAAC;AAE/C;;;;;;;;;GASG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,wBAAwB,QA8BlE;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,qBAAqB,UAAiB;IACjD,SAAS,EAAE,8BAA8B,CAAC;IAC1C,4BAA4B,EAAE,oBAAoB,CAAC;IACnD,uBAAuB,EAAE,oBAAoB,CAAC;IAC9C,uBAAuB,EAAE,MAAM,CAAC;CACjC,kBAqBA,CAAC;AAEF;;;;;GAKG;AACH,wBAAsB,sBAAsB,CAC1C,KAAK,EAAE,2BAA2B,iBA+InC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"controller-integration.d.mts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/network-syncing/controller-integration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,qCAAqC;AAQzE,OAAO,KAAK,qBAAqB,qCAAiC;AAClE,OAAO,KAAK,EAAE,8BAA8B,EAAE,qCAAiC;AAE/E,KAAK,wBAAwB,GAAG;IAC9B,SAAS,EAAE,8BAA8B,CAAC;IAC1C,gCAAgC,EAAE,MAAM,qBAAqB,CAAC;IAC9D,qBAAqB,EAAE,MAAM,OAAO,CAAC;CACtC,CAAC;AAEF,KAAK,2BAA2B,GAAG;IACjC,SAAS,EAAE,8BAA8B,CAAC;IAC1C,gCAAgC,EAAE,MAAM,qBAAqB,CAAC;IAC9D,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,cAAc,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;IAC3C,gBAAgB,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;IAC7C,gBAAgB,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;CAC9C,CAAC;AAEF;;;GAGG;AAGH,eAAO,IAAI,2BAA2B,SAAQ,CAAC;AAE/C;;;;;;;;;GASG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,wBAAwB,
|
|
1
|
+
{"version":3,"file":"controller-integration.d.mts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/network-syncing/controller-integration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,qCAAqC;AAQzE,OAAO,KAAK,qBAAqB,qCAAiC;AAClE,OAAO,KAAK,EAAE,8BAA8B,EAAE,qCAAiC;AAE/E,KAAK,wBAAwB,GAAG;IAC9B,SAAS,EAAE,8BAA8B,CAAC;IAC1C,gCAAgC,EAAE,MAAM,qBAAqB,CAAC;IAC9D,qBAAqB,EAAE,MAAM,OAAO,CAAC;CACtC,CAAC;AAEF,KAAK,2BAA2B,GAAG;IACjC,SAAS,EAAE,8BAA8B,CAAC;IAC1C,gCAAgC,EAAE,MAAM,qBAAqB,CAAC;IAC9D,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,cAAc,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;IAC3C,gBAAgB,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;IAC7C,gBAAgB,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;CAC9C,CAAC;AAEF;;;GAGG;AAGH,eAAO,IAAI,2BAA2B,SAAQ,CAAC;AAE/C;;;;;;;;;GASG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,wBAAwB,QA8BlE;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,qBAAqB,UAAiB;IACjD,SAAS,EAAE,8BAA8B,CAAC;IAC1C,4BAA4B,EAAE,oBAAoB,CAAC;IACnD,uBAAuB,EAAE,oBAAoB,CAAC;IAC9C,uBAAuB,EAAE,MAAM,CAAC;CACjC,kBAqBA,CAAC;AAEF;;;;;GAKG;AACH,wBAAsB,sBAAsB,CAC1C,KAAK,EAAE,2BAA2B,iBA+InC"}
|
|
@@ -31,9 +31,7 @@ export let isMainNetworkSyncInProgress = false;
|
|
|
31
31
|
export function startNetworkSyncing(props) {
|
|
32
32
|
const { messenger, isMutationSyncBlocked, getUserStorageControllerInstance } = props;
|
|
33
33
|
try {
|
|
34
|
-
messenger.subscribe('NetworkController:networkRemoved',
|
|
35
|
-
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
|
36
|
-
async (networkConfiguration) => {
|
|
34
|
+
messenger.subscribe('NetworkController:networkRemoved', async (networkConfiguration) => {
|
|
37
35
|
try {
|
|
38
36
|
// If blocked (e.g. we have not yet performed a main-sync), then we should not perform any mutations
|
|
39
37
|
if (isMutationSyncBlocked()) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"controller-integration.mjs","sourceRoot":"","sources":["../../../../src/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,yDAAyD;iBAC1D;aACF;YAED,+DAA+D;YAC/D,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE;gBACrB,GAAG,CAAC,KAAK,CACP,mEAAmE,EACnE,MAAM,CACP,CAAC;aACH;SACF;QAED,wBAAwB;QACxB,IACE,cAAc,EAAE,qBAAqB;YACrC,cAAc,CAAC,qBAAqB,CAAC,MAAM,GAAG,CAAC,EAC/C;YACA,MAAM,MAAM,GAAc,EAAE,CAAC;YAC7B,cAAc,CAAC,qBAAqB,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE;gBACjD,IAAI;oBACF,SAAS,CAAC,IAAI,CAAC,iCAAiC,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC;oBAC7D,gBAAgB,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;iBAC/B;gBAAC,OAAO,CAAC,EAAE;oBACV,gEAAgE;oBAChE,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;oBACf,yDAAyD;iBAC1D;YACH,CAAC,CAAC,CAAC;YAEH,+DAA+D;YAC/D,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE;gBACrB,GAAG,CAAC,KAAK,CACP,mEAAmE,EACnE,MAAM,CACP,CAAC;aACH;SACF;KACF;IAAC,OAAO,CAAC,EAAE;QACV,iEAAiE;QACjE,GAAG,CAAC,KAAK,CAAC,iCAAiC,EAAE,CAAC,CAAC,CAAC;QAChD,qBAAqB;KACtB;YAAS;QACR,2BAA2B,GAAG,KAAK,CAAC;KACrC;AACH,CAAC","sourcesContent":["import type { NetworkConfiguration } from '@metamask/network-controller';\nimport log from 'loglevel';\n\nimport { getBoundedNetworksToAdd } from './add-network-utils';\nimport { getAllRemoteNetworks } from './services';\nimport { findNetworksToUpdate } from './sync-all';\nimport { batchUpdateNetworks, deleteNetwork } from './sync-mutations';\nimport { createUpdateNetworkProps } from './update-network-utils';\nimport type UserStorageController from '../UserStorageController';\nimport type { UserStorageControllerMessenger } from '../UserStorageController';\n\ntype StartNetworkSyncingProps = {\n messenger: UserStorageControllerMessenger;\n getUserStorageControllerInstance: () => UserStorageController;\n isMutationSyncBlocked: () => boolean;\n};\n\ntype PerformMainNetworkSyncProps = {\n messenger: UserStorageControllerMessenger;\n getUserStorageControllerInstance: () => UserStorageController;\n maxNetworksToAdd?: number;\n onNetworkAdded?: (chainId: string) => void;\n onNetworkUpdated?: (chainId: string) => void;\n onNetworkRemoved?: (chainId: string) => void;\n};\n\n/**\n * Global in-mem cache to signify that the network syncing is in progress\n * Ensures that listeners do not fire during main sync (prevent double requests)\n */\n// Exported to help testing\n// eslint-disable-next-line import-x/no-mutable-exports\nexport let isMainNetworkSyncInProgress = false;\n\n/**\n * Initialize and setup events to listen to for network syncing\n * We will be listening to:\n * - Remove Event, to indicate that we need to remote network from remote\n *\n * We will not be listening to:\n * - Add/Update events are not required, as we can sync these during the main sync\n *\n * @param props - parameters used for initializing and enabling network syncing\n */\nexport function startNetworkSyncing(props: StartNetworkSyncingProps) {\n const { messenger, isMutationSyncBlocked, getUserStorageControllerInstance } =\n props;\n try {\n messenger.subscribe(\n 'NetworkController:networkRemoved',\n\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async (networkConfiguration) => {\n try {\n // If blocked (e.g. we have not yet performed a main-sync), then we should not perform any mutations\n if (isMutationSyncBlocked()) {\n return;\n }\n\n // As main sync is in progress, it will already local and remote networks\n // So no need to re-process again.\n if (isMainNetworkSyncInProgress) {\n return;\n }\n\n await deleteNetwork(networkConfiguration, {\n getUserStorageControllerInstance,\n });\n } catch {\n // Silently fail sync\n }\n },\n );\n } catch (e) {\n log.warn('NetworkSyncing, event subscription failed', e);\n }\n}\n\n/**\n * method that will dispatch the `NetworkController:updateNetwork` action.\n * transforms and corrects the network configuration (and RPCs) we pass through.\n *\n * @param props - properties\n * @param props.messenger - messenger to call the action\n * @param props.originalNetworkConfiguration - original network config (from network controller state)\n * @param props.newNetworkConfiguration - new network config (from remote)\n * @param props.selectedNetworkClientId - currently selected network client id\n */\nexport const dispatchUpdateNetwork = async (props: {\n messenger: UserStorageControllerMessenger;\n originalNetworkConfiguration: NetworkConfiguration;\n newNetworkConfiguration: NetworkConfiguration;\n selectedNetworkClientId: string;\n}) => {\n const {\n messenger,\n originalNetworkConfiguration,\n newNetworkConfiguration,\n selectedNetworkClientId,\n } = props;\n\n const { updateNetworkFields, newSelectedRpcEndpointIndex } =\n createUpdateNetworkProps({\n originalNetworkConfiguration,\n newNetworkConfiguration,\n selectedNetworkClientId,\n });\n\n await messenger.call(\n 'NetworkController:updateNetwork',\n updateNetworkFields.chainId,\n updateNetworkFields,\n { replacementSelectedRpcEndpointIndex: newSelectedRpcEndpointIndex },\n );\n};\n\n/**\n * Action to perform the main network sync.\n * It will fetch local networks and remote networks, then determines which networks (local and remote) to add/update\n *\n * @param props - parameters used for this main sync\n */\nexport async function performMainNetworkSync(\n props: PerformMainNetworkSyncProps,\n) {\n const {\n messenger,\n maxNetworksToAdd,\n onNetworkAdded,\n onNetworkRemoved,\n onNetworkUpdated,\n getUserStorageControllerInstance,\n } = props;\n\n // Edge-Case, we do not want to re-run the main-sync if it already is in progress\n /* istanbul ignore if - this is not testable */\n if (isMainNetworkSyncInProgress) {\n return;\n }\n\n isMainNetworkSyncInProgress = true;\n try {\n const networkControllerState = messenger.call('NetworkController:getState');\n const localNetworks = Object.values(\n networkControllerState.networkConfigurationsByChainId ?? {},\n );\n\n const remoteNetworks = await getAllRemoteNetworks({\n getUserStorageControllerInstance,\n });\n const networkChanges = findNetworksToUpdate({\n localNetworks,\n remoteNetworks,\n });\n\n log.debug('performMainNetworkSync() - Network Syncing Started', {\n localNetworks,\n remoteNetworks,\n networkChanges,\n });\n\n // Update Remote\n if (\n networkChanges?.remoteNetworksToUpdate &&\n networkChanges.remoteNetworksToUpdate.length > 0\n ) {\n await batchUpdateNetworks(networkChanges?.remoteNetworksToUpdate, {\n getUserStorageControllerInstance,\n });\n }\n\n // Add missing local networks\n const boundedNetworkedToAdd =\n networkChanges?.missingLocalNetworks &&\n getBoundedNetworksToAdd(\n localNetworks,\n networkChanges.missingLocalNetworks,\n maxNetworksToAdd,\n );\n if (boundedNetworkedToAdd && boundedNetworkedToAdd.length > 0) {\n const errors: unknown[] = [];\n boundedNetworkedToAdd.forEach((n) => {\n try {\n messenger.call('NetworkController:addNetwork', n);\n onNetworkAdded?.(n.chainId);\n } catch (e) {\n /* istanbul ignore next - allocates logs, do not need to test */\n errors.push(e);\n // Silently fail, we can try this again on next main sync\n }\n });\n\n /* istanbul ignore if - only logs errors, not useful to test */\n if (errors.length > 0) {\n log.error(\n 'performMainNetworkSync() - NetworkController:addNetwork failures',\n errors,\n );\n }\n }\n\n // Update local networks\n if (\n networkChanges?.localNetworksToUpdate &&\n networkChanges.localNetworksToUpdate.length > 0\n ) {\n const errors: unknown[] = [];\n for (const n of networkChanges.localNetworksToUpdate) {\n try {\n await dispatchUpdateNetwork({\n messenger,\n originalNetworkConfiguration:\n networkControllerState.networkConfigurationsByChainId[n.chainId],\n newNetworkConfiguration: n,\n selectedNetworkClientId:\n networkControllerState.selectedNetworkClientId,\n });\n onNetworkUpdated?.(n.chainId);\n } catch (e) {\n /* istanbul ignore next - allocates logs, do not need to test */\n errors.push(e);\n // Silently fail, we can try this again on next main sync\n }\n }\n\n /* istanbul ignore if - only logs errors, not useful to test */\n if (errors.length > 0) {\n log.error(\n 'performMainNetworkSync() - NetworkController:updateNetwork failed',\n errors,\n );\n }\n }\n\n // Remove local networks\n if (\n networkChanges?.localNetworksToRemove &&\n networkChanges.localNetworksToRemove.length > 0\n ) {\n const errors: unknown[] = [];\n networkChanges.localNetworksToRemove.forEach((n) => {\n try {\n messenger.call('NetworkController:removeNetwork', n.chainId);\n onNetworkRemoved?.(n.chainId);\n } catch (e) {\n /* istanbul ignore next - allocates logs, do not need to test */\n errors.push(e);\n // Silently fail, we can try this again on next main sync\n }\n });\n\n /* istanbul ignore if - only logs errors, not useful to test */\n if (errors.length > 0) {\n log.error(\n 'performMainNetworkSync() - NetworkController:removeNetwork failed',\n errors,\n );\n }\n }\n } catch (e) {\n /* istanbul ignore next - only logs errors, not useful to test */\n log.error('performMainNetworkSync() failed', e);\n // Silently fail sync\n } finally {\n isMainNetworkSyncInProgress = false;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"controller-integration.mjs","sourceRoot":"","sources":["../../../../src/controllers/user-storage/network-syncing/controller-integration.ts"],"names":[],"mappings":";;;;;;AACA,OAAO,IAAG,iBAAiB;;AAE3B,OAAO,EAAE,uBAAuB,EAAE,gCAA4B;AAC9D,OAAO,EAAE,oBAAoB,EAAE,uBAAmB;AAClD,OAAO,EAAE,oBAAoB,EAAE,uBAAmB;AAClD,OAAO,EAAE,mBAAmB,EAAE,aAAa,EAAE,6BAAyB;AACtE,OAAO,EAAE,wBAAwB,EAAE,mCAA+B;AAmBlE;;;GAGG;AACH,2BAA2B;AAC3B,uDAAuD;AACvD,MAAM,CAAC,IAAI,2BAA2B,GAAG,KAAK,CAAC;AAE/C;;;;;;;;;GASG;AACH,MAAM,UAAU,mBAAmB,CAAC,KAA+B;IACjE,MAAM,EAAE,SAAS,EAAE,qBAAqB,EAAE,gCAAgC,EAAE,GAC1E,KAAK,CAAC;IACR,IAAI;QACF,SAAS,CAAC,SAAS,CACjB,kCAAkC,EAClC,KAAK,EAAE,oBAAoB,EAAE,EAAE;YAC7B,IAAI;gBACF,oGAAoG;gBACpG,IAAI,qBAAqB,EAAE,EAAE;oBAC3B,OAAO;iBACR;gBAED,yEAAyE;gBACzE,kCAAkC;gBAClC,IAAI,2BAA2B,EAAE;oBAC/B,OAAO;iBACR;gBAED,MAAM,aAAa,CAAC,oBAAoB,EAAE;oBACxC,gCAAgC;iBACjC,CAAC,CAAC;aACJ;YAAC,MAAM;gBACN,qBAAqB;aACtB;QACH,CAAC,CACF,CAAC;KACH;IAAC,OAAO,CAAC,EAAE;QACV,GAAG,CAAC,IAAI,CAAC,2CAA2C,EAAE,CAAC,CAAC,CAA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C1B,uBAAuB,EACrB,sBAAsB,CAAC,uBAAuB;qBACjD,CAAC,CAAC;oBACH,gBAAgB,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;iBAC/B;gBAAC,OAAO,CAAC,EAAE;oBACV,gEAAgE;oBAChE,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;oBACf,yDAAyD;iBAC1D;aACF;YAED,+DAA+D;YAC/D,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE;gBACrB,GAAG,CAAC,KAAK,CACP,mEAAmE,EACnE,MAAM,CACP,CAAC;aACH;SACF;QAED,wBAAwB;QACxB,IACE,cAAc,EAAE,qBAAqB;YACrC,cAAc,CAAC,qBAAqB,CAAC,MAAM,GAAG,CAAC,EAC/C;YACA,MAAM,MAAM,GAAc,EAAE,CAAC;YAC7B,cAAc,CAAC,qBAAqB,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE;gBACjD,IAAI;oBACF,SAAS,CAAC,IAAI,CAAC,iCAAiC,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC;oBAC7D,gBAAgB,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;iBAC/B;gBAAC,OAAO,CAAC,EAAE;oBACV,gEAAgE;oBAChE,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;oBACf,yDAAyD;iBAC1D;YACH,CAAC,CAAC,CAAC;YAEH,+DAA+D;YAC/D,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE;gBACrB,GAAG,CAAC,KAAK,CACP,mEAAmE,EACnE,MAAM,CACP,CAAC;aACH;SACF;KACF;IAAC,OAAO,CAAC,EAAE;QACV,iEAAiE;QACjE,GAAG,CAAC,KAAK,CAAC,iCAAiC,EAAE,CAAC,CAAC,CAAC;QAChD,qBAAqB;KACtB;YAAS;QACR,2BAA2B,GAAG,KAAK,CAAC;KACrC;AACH,CAAC","sourcesContent":["import type { NetworkConfiguration } from '@metamask/network-controller';\nimport log from 'loglevel';\n\nimport { getBoundedNetworksToAdd } from './add-network-utils';\nimport { getAllRemoteNetworks } from './services';\nimport { findNetworksToUpdate } from './sync-all';\nimport { batchUpdateNetworks, deleteNetwork } from './sync-mutations';\nimport { createUpdateNetworkProps } from './update-network-utils';\nimport type UserStorageController from '../UserStorageController';\nimport type { UserStorageControllerMessenger } from '../UserStorageController';\n\ntype StartNetworkSyncingProps = {\n messenger: UserStorageControllerMessenger;\n getUserStorageControllerInstance: () => UserStorageController;\n isMutationSyncBlocked: () => boolean;\n};\n\ntype PerformMainNetworkSyncProps = {\n messenger: UserStorageControllerMessenger;\n getUserStorageControllerInstance: () => UserStorageController;\n maxNetworksToAdd?: number;\n onNetworkAdded?: (chainId: string) => void;\n onNetworkUpdated?: (chainId: string) => void;\n onNetworkRemoved?: (chainId: string) => void;\n};\n\n/**\n * Global in-mem cache to signify that the network syncing is in progress\n * Ensures that listeners do not fire during main sync (prevent double requests)\n */\n// Exported to help testing\n// eslint-disable-next-line import-x/no-mutable-exports\nexport let isMainNetworkSyncInProgress = false;\n\n/**\n * Initialize and setup events to listen to for network syncing\n * We will be listening to:\n * - Remove Event, to indicate that we need to remote network from remote\n *\n * We will not be listening to:\n * - Add/Update events are not required, as we can sync these during the main sync\n *\n * @param props - parameters used for initializing and enabling network syncing\n */\nexport function startNetworkSyncing(props: StartNetworkSyncingProps) {\n const { messenger, isMutationSyncBlocked, getUserStorageControllerInstance } =\n props;\n try {\n messenger.subscribe(\n 'NetworkController:networkRemoved',\n async (networkConfiguration) => {\n try {\n // If blocked (e.g. we have not yet performed a main-sync), then we should not perform any mutations\n if (isMutationSyncBlocked()) {\n return;\n }\n\n // As main sync is in progress, it will already local and remote networks\n // So no need to re-process again.\n if (isMainNetworkSyncInProgress) {\n return;\n }\n\n await deleteNetwork(networkConfiguration, {\n getUserStorageControllerInstance,\n });\n } catch {\n // Silently fail sync\n }\n },\n );\n } catch (e) {\n log.warn('NetworkSyncing, event subscription failed', e);\n }\n}\n\n/**\n * method that will dispatch the `NetworkController:updateNetwork` action.\n * transforms and corrects the network configuration (and RPCs) we pass through.\n *\n * @param props - properties\n * @param props.messenger - messenger to call the action\n * @param props.originalNetworkConfiguration - original network config (from network controller state)\n * @param props.newNetworkConfiguration - new network config (from remote)\n * @param props.selectedNetworkClientId - currently selected network client id\n */\nexport const dispatchUpdateNetwork = async (props: {\n messenger: UserStorageControllerMessenger;\n originalNetworkConfiguration: NetworkConfiguration;\n newNetworkConfiguration: NetworkConfiguration;\n selectedNetworkClientId: string;\n}) => {\n const {\n messenger,\n originalNetworkConfiguration,\n newNetworkConfiguration,\n selectedNetworkClientId,\n } = props;\n\n const { updateNetworkFields, newSelectedRpcEndpointIndex } =\n createUpdateNetworkProps({\n originalNetworkConfiguration,\n newNetworkConfiguration,\n selectedNetworkClientId,\n });\n\n await messenger.call(\n 'NetworkController:updateNetwork',\n updateNetworkFields.chainId,\n updateNetworkFields,\n { replacementSelectedRpcEndpointIndex: newSelectedRpcEndpointIndex },\n );\n};\n\n/**\n * Action to perform the main network sync.\n * It will fetch local networks and remote networks, then determines which networks (local and remote) to add/update\n *\n * @param props - parameters used for this main sync\n */\nexport async function performMainNetworkSync(\n props: PerformMainNetworkSyncProps,\n) {\n const {\n messenger,\n maxNetworksToAdd,\n onNetworkAdded,\n onNetworkRemoved,\n onNetworkUpdated,\n getUserStorageControllerInstance,\n } = props;\n\n // Edge-Case, we do not want to re-run the main-sync if it already is in progress\n /* istanbul ignore if - this is not testable */\n if (isMainNetworkSyncInProgress) {\n return;\n }\n\n isMainNetworkSyncInProgress = true;\n try {\n const networkControllerState = messenger.call('NetworkController:getState');\n const localNetworks = Object.values(\n networkControllerState.networkConfigurationsByChainId ?? {},\n );\n\n const remoteNetworks = await getAllRemoteNetworks({\n getUserStorageControllerInstance,\n });\n const networkChanges = findNetworksToUpdate({\n localNetworks,\n remoteNetworks,\n });\n\n log.debug('performMainNetworkSync() - Network Syncing Started', {\n localNetworks,\n remoteNetworks,\n networkChanges,\n });\n\n // Update Remote\n if (\n networkChanges?.remoteNetworksToUpdate &&\n networkChanges.remoteNetworksToUpdate.length > 0\n ) {\n await batchUpdateNetworks(networkChanges?.remoteNetworksToUpdate, {\n getUserStorageControllerInstance,\n });\n }\n\n // Add missing local networks\n const boundedNetworkedToAdd =\n networkChanges?.missingLocalNetworks &&\n getBoundedNetworksToAdd(\n localNetworks,\n networkChanges.missingLocalNetworks,\n maxNetworksToAdd,\n );\n if (boundedNetworkedToAdd && boundedNetworkedToAdd.length > 0) {\n const errors: unknown[] = [];\n boundedNetworkedToAdd.forEach((n) => {\n try {\n messenger.call('NetworkController:addNetwork', n);\n onNetworkAdded?.(n.chainId);\n } catch (e) {\n /* istanbul ignore next - allocates logs, do not need to test */\n errors.push(e);\n // Silently fail, we can try this again on next main sync\n }\n });\n\n /* istanbul ignore if - only logs errors, not useful to test */\n if (errors.length > 0) {\n log.error(\n 'performMainNetworkSync() - NetworkController:addNetwork failures',\n errors,\n );\n }\n }\n\n // Update local networks\n if (\n networkChanges?.localNetworksToUpdate &&\n networkChanges.localNetworksToUpdate.length > 0\n ) {\n const errors: unknown[] = [];\n for (const n of networkChanges.localNetworksToUpdate) {\n try {\n await dispatchUpdateNetwork({\n messenger,\n originalNetworkConfiguration:\n networkControllerState.networkConfigurationsByChainId[n.chainId],\n newNetworkConfiguration: n,\n selectedNetworkClientId:\n networkControllerState.selectedNetworkClientId,\n });\n onNetworkUpdated?.(n.chainId);\n } catch (e) {\n /* istanbul ignore next - allocates logs, do not need to test */\n errors.push(e);\n // Silently fail, we can try this again on next main sync\n }\n }\n\n /* istanbul ignore if - only logs errors, not useful to test */\n if (errors.length > 0) {\n log.error(\n 'performMainNetworkSync() - NetworkController:updateNetwork failed',\n errors,\n );\n }\n }\n\n // Remove local networks\n if (\n networkChanges?.localNetworksToRemove &&\n networkChanges.localNetworksToRemove.length > 0\n ) {\n const errors: unknown[] = [];\n networkChanges.localNetworksToRemove.forEach((n) => {\n try {\n messenger.call('NetworkController:removeNetwork', n.chainId);\n onNetworkRemoved?.(n.chainId);\n } catch (e) {\n /* istanbul ignore next - allocates logs, do not need to test */\n errors.push(e);\n // Silently fail, we can try this again on next main sync\n }\n });\n\n /* istanbul ignore if - only logs errors, not useful to test */\n if (errors.length > 0) {\n log.error(\n 'performMainNetworkSync() - NetworkController:removeNetwork failed',\n errors,\n );\n }\n }\n } catch (e) {\n /* istanbul ignore next - only logs errors, not useful to test */\n log.error('performMainNetworkSync() failed', e);\n // Silently fail sync\n } finally {\n isMainNetworkSyncInProgress = false;\n }\n}\n"]}
|
|
@@ -23,7 +23,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
|
|
|
23
23
|
return result;
|
|
24
24
|
};
|
|
25
25
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
26
|
-
exports.MOCK_STORAGE_RESPONSE = exports.MOCK_NOTIFICATIONS_DATA_ENCRYPTED = exports.MOCK_NOTIFICATIONS_DATA = exports.MOCK_STORAGE_KEY = exports.MOCK_STORAGE_URL_ALL_FEATURE_ENTRIES = exports.MOCK_STORAGE_URL = void 0;
|
|
26
|
+
exports.MOCK_STORAGE_RESPONSE = exports.MOCK_NOTIFICATIONS_DATA_ENCRYPTED = exports.MOCK_NOTIFICATIONS_DATA = exports.MOCK_STORAGE_KEY = exports.MOCK_STORAGE_KEY_SIGNATURE = exports.MOCK_STORAGE_URL_ALL_FEATURE_ENTRIES = exports.MOCK_STORAGE_URL = void 0;
|
|
27
27
|
const encryption_1 = __importStar(require("../../shared/encryption/index.cjs"));
|
|
28
28
|
const env_1 = require("../../shared/env.cjs");
|
|
29
29
|
const storage_schema_1 = require("../../shared/storage-schema.cjs");
|
|
@@ -31,7 +31,8 @@ const user_storage_1 = require("../user-storage.cjs");
|
|
|
31
31
|
// Example mock notifications storage entry (wildcard)
|
|
32
32
|
exports.MOCK_STORAGE_URL = (0, user_storage_1.STORAGE_URL)(env_1.Env.PRD, `${storage_schema_1.USER_STORAGE_FEATURE_NAMES.notifications}.notification_settings`);
|
|
33
33
|
exports.MOCK_STORAGE_URL_ALL_FEATURE_ENTRIES = (0, user_storage_1.STORAGE_URL)(env_1.Env.PRD, storage_schema_1.USER_STORAGE_FEATURE_NAMES.notifications);
|
|
34
|
-
exports.
|
|
34
|
+
exports.MOCK_STORAGE_KEY_SIGNATURE = 'mockStorageKey';
|
|
35
|
+
exports.MOCK_STORAGE_KEY = (0, encryption_1.createSHA256Hash)(exports.MOCK_STORAGE_KEY_SIGNATURE);
|
|
35
36
|
exports.MOCK_NOTIFICATIONS_DATA = '{ is_compact: false }';
|
|
36
37
|
const MOCK_NOTIFICATIONS_DATA_ENCRYPTED = async (data) => await encryption_1.default.encryptString(data ?? exports.MOCK_NOTIFICATIONS_DATA, exports.MOCK_STORAGE_KEY);
|
|
37
38
|
exports.MOCK_NOTIFICATIONS_DATA_ENCRYPTED = MOCK_NOTIFICATIONS_DATA_ENCRYPTED;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"userstorage.cjs","sourceRoot":"","sources":["../../../src/sdk/mocks/userstorage.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,gFAAuE;AACvE,8CAAuC;AACvC,oEAAyE;AACzE,sDAA8C;AAE9C,sDAAsD;AACzC,QAAA,gBAAgB,GAAG,IAAA,0BAAW,EACzC,SAAG,CAAC,GAAG,EACP,GAAG,2CAA0B,CAAC,aAAa,wBAAwB,CACpE,CAAC;AACW,QAAA,oCAAoC,GAAG,IAAA,0BAAW,EAC7D,SAAG,CAAC,GAAG,EACP,2CAA0B,CAAC,aAAa,CACzC,CAAC;AAEW,QAAA,gBAAgB,GAAG,IAAA,6BAAgB,EAAC,
|
|
1
|
+
{"version":3,"file":"userstorage.cjs","sourceRoot":"","sources":["../../../src/sdk/mocks/userstorage.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,gFAAuE;AACvE,8CAAuC;AACvC,oEAAyE;AACzE,sDAA8C;AAE9C,sDAAsD;AACzC,QAAA,gBAAgB,GAAG,IAAA,0BAAW,EACzC,SAAG,CAAC,GAAG,EACP,GAAG,2CAA0B,CAAC,aAAa,wBAAwB,CACpE,CAAC;AACW,QAAA,oCAAoC,GAAG,IAAA,0BAAW,EAC7D,SAAG,CAAC,GAAG,EACP,2CAA0B,CAAC,aAAa,CACzC,CAAC;AAEW,QAAA,0BAA0B,GAAG,gBAAgB,CAAC;AAC9C,QAAA,gBAAgB,GAAG,IAAA,6BAAgB,EAAC,kCAA0B,CAAC,CAAC;AAChE,QAAA,uBAAuB,GAAG,uBAAuB,CAAC;AACxD,MAAM,iCAAiC,GAAG,KAAK,EAAE,IAAa,EAAE,EAAE,CACvE,MAAM,oBAAU,CAAC,aAAa,CAC5B,IAAI,IAAI,+BAAuB,EAC/B,wBAAgB,CACjB,CAAC;AAJS,QAAA,iCAAiC,qCAI1C;AAEG,MAAM,qBAAqB,GAAG,KAAK,EAAE,IAAa,EAAE,EAAE,CAAC,CAAC;IAC7D,SAAS,EAAE,kEAAkE;IAC7E,IAAI,EAAE,MAAM,IAAA,yCAAiC,EAAC,IAAI,CAAC;CACpD,CAAC,CAAC;AAHU,QAAA,qBAAqB,yBAG/B","sourcesContent":["import encryption, { createSHA256Hash } from '../../shared/encryption';\nimport { Env } from '../../shared/env';\nimport { USER_STORAGE_FEATURE_NAMES } from '../../shared/storage-schema';\nimport { STORAGE_URL } from '../user-storage';\n\n// Example mock notifications storage entry (wildcard)\nexport const MOCK_STORAGE_URL = STORAGE_URL(\n Env.PRD,\n `${USER_STORAGE_FEATURE_NAMES.notifications}.notification_settings`,\n);\nexport const MOCK_STORAGE_URL_ALL_FEATURE_ENTRIES = STORAGE_URL(\n Env.PRD,\n USER_STORAGE_FEATURE_NAMES.notifications,\n);\n\nexport const MOCK_STORAGE_KEY_SIGNATURE = 'mockStorageKey';\nexport const MOCK_STORAGE_KEY = createSHA256Hash(MOCK_STORAGE_KEY_SIGNATURE);\nexport const MOCK_NOTIFICATIONS_DATA = '{ is_compact: false }';\nexport const MOCK_NOTIFICATIONS_DATA_ENCRYPTED = async (data?: string) =>\n await encryption.encryptString(\n data ?? MOCK_NOTIFICATIONS_DATA,\n MOCK_STORAGE_KEY,\n );\n\nexport const MOCK_STORAGE_RESPONSE = async (data?: string) => ({\n HashedKey: '8485d2c14c333ebca415140a276adaf546619b0efc204586b73a5d400a18a5e2',\n Data: await MOCK_NOTIFICATIONS_DATA_ENCRYPTED(data),\n});\n"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export declare const MOCK_STORAGE_URL: string;
|
|
2
2
|
export declare const MOCK_STORAGE_URL_ALL_FEATURE_ENTRIES: string;
|
|
3
|
+
export declare const MOCK_STORAGE_KEY_SIGNATURE = "mockStorageKey";
|
|
3
4
|
export declare const MOCK_STORAGE_KEY: string;
|
|
4
5
|
export declare const MOCK_NOTIFICATIONS_DATA = "{ is_compact: false }";
|
|
5
6
|
export declare const MOCK_NOTIFICATIONS_DATA_ENCRYPTED: (data?: string) => Promise<string>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"userstorage.d.cts","sourceRoot":"","sources":["../../../src/sdk/mocks/userstorage.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,gBAAgB,QAG5B,CAAC;AACF,eAAO,MAAM,oCAAoC,QAGhD,CAAC;AAEF,eAAO,MAAM,gBAAgB,
|
|
1
|
+
{"version":3,"file":"userstorage.d.cts","sourceRoot":"","sources":["../../../src/sdk/mocks/userstorage.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,gBAAgB,QAG5B,CAAC;AACF,eAAO,MAAM,oCAAoC,QAGhD,CAAC;AAEF,eAAO,MAAM,0BAA0B,mBAAmB,CAAC;AAC3D,eAAO,MAAM,gBAAgB,QAA+C,CAAC;AAC7E,eAAO,MAAM,uBAAuB,0BAA0B,CAAC;AAC/D,eAAO,MAAM,iCAAiC,UAAiB,MAAM,oBAIlE,CAAC;AAEJ,eAAO,MAAM,qBAAqB,UAAiB,MAAM;;;EAGvD,CAAC"}
|