@metamask-previews/profile-sync-controller 17.0.0-preview-e11fb169 → 17.1.0-preview-7dcef379

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.
Files changed (24) hide show
  1. package/CHANGELOG.md +10 -1
  2. package/dist/controllers/user-storage/UserStorageController.cjs +2 -0
  3. package/dist/controllers/user-storage/UserStorageController.cjs.map +1 -1
  4. package/dist/controllers/user-storage/UserStorageController.d.cts +4 -2
  5. package/dist/controllers/user-storage/UserStorageController.d.cts.map +1 -1
  6. package/dist/controllers/user-storage/UserStorageController.d.mts +4 -2
  7. package/dist/controllers/user-storage/UserStorageController.d.mts.map +1 -1
  8. package/dist/controllers/user-storage/UserStorageController.mjs +2 -0
  9. package/dist/controllers/user-storage/UserStorageController.mjs.map +1 -1
  10. package/dist/controllers/user-storage/account-syncing/setup-subscriptions.cjs +13 -3
  11. package/dist/controllers/user-storage/account-syncing/setup-subscriptions.cjs.map +1 -1
  12. package/dist/controllers/user-storage/account-syncing/setup-subscriptions.d.cts.map +1 -1
  13. package/dist/controllers/user-storage/account-syncing/setup-subscriptions.d.mts.map +1 -1
  14. package/dist/controllers/user-storage/account-syncing/setup-subscriptions.mjs +13 -3
  15. package/dist/controllers/user-storage/account-syncing/setup-subscriptions.mjs.map +1 -1
  16. package/dist/shared/utils/event-queue.cjs +24 -0
  17. package/dist/shared/utils/event-queue.cjs.map +1 -0
  18. package/dist/shared/utils/event-queue.d.cts +6 -0
  19. package/dist/shared/utils/event-queue.d.cts.map +1 -0
  20. package/dist/shared/utils/event-queue.d.mts +6 -0
  21. package/dist/shared/utils/event-queue.d.mts.map +1 -0
  22. package/dist/shared/utils/event-queue.mjs +20 -0
  23. package/dist/shared/utils/event-queue.mjs.map +1 -0
  24. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [17.1.0]
11
+
12
+ ### Added
13
+
14
+ - Add `EventQueue` class util to guarantee the order of some user-storage updates ([#5937](https://github.com/MetaMask/core/pull/5937))
15
+ - Add an instance of `EventQueue` to `UserStorageController`
16
+ - Event subscriptions for `AccountsController:accountAdded` and `AccountsController:accountRenamed` are now pushing their callbacks to the `UserStorageController` instance of `EventQueue`, so that we stay in control of the order these callbacks are fulfilled.
17
+
10
18
  ## [17.0.0]
11
19
 
12
20
  ### Added
@@ -614,7 +622,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
614
622
 
615
623
  - Initial release
616
624
 
617
- [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@17.0.0...HEAD
625
+ [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@17.1.0...HEAD
626
+ [17.1.0]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@17.0.0...@metamask/profile-sync-controller@17.1.0
618
627
  [17.0.0]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@16.0.0...@metamask/profile-sync-controller@17.0.0
619
628
  [16.0.0]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@15.0.0...@metamask/profile-sync-controller@16.0.0
620
629
  [15.0.0]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@14.0.0...@metamask/profile-sync-controller@15.0.0
@@ -20,6 +20,7 @@ const setup_subscriptions_1 = require("./account-syncing/setup-subscriptions.cjs
20
20
  const constants_1 = require("./constants.cjs");
21
21
  const controller_integration_2 = require("./network-syncing/controller-integration.cjs");
22
22
  const sdk_1 = require("../../sdk/index.cjs");
23
+ const event_queue_1 = require("../../shared/utils/event-queue.cjs");
23
24
  const auth_snap_requests_1 = require("../authentication/auth-snap-requests.cjs");
24
25
  const controllerName = 'UserStorageController';
25
26
  exports.defaultState = {
@@ -111,6 +112,7 @@ class UserStorageController extends base_controller_1.BaseController {
111
112
  },
112
113
  });
113
114
  _UserStorageController_nativeScryptCrypto.set(this, undefined);
115
+ this.eventQueue = new event_queue_1.EventQueue();
114
116
  _UserStorageController__snapSignMessageCache.set(this, {});
115
117
  __classPrivateFieldGet(this, _UserStorageController_env, "f").isNetworkSyncingEnabled = Boolean(env?.isNetworkSyncingEnabled);
116
118
  __classPrivateFieldSet(this, _UserStorageController_config, config, "f");
@@ -1 +1 @@
1
- {"version":3,"file":"UserStorageController.cjs","sourceRoot":"","sources":["../../../src/controllers/user-storage/UserStorageController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAYA,+DAA2D;AAC3D,qEAMsC;AAWtC,yFAGkD;AAClD,mFAAyF;AACzF,+CAAqD;AACrD,yFAGkD;AAClD,6CAA6C;AAO7C,iFAAoF;AAQpF,MAAM,cAAc,GAAG,uBAAuB,CAAC;AAoClC,QAAA,YAAY,GAA+B;IACtD,sBAAsB,EAAE,IAAI;IAC5B,4BAA4B,EAAE,KAAK;IACnC,uBAAuB,EAAE,IAAI;IAC7B,kCAAkC,EAAE,KAAK;IACzC,mCAAmC,EAAE,KAAK;IAC1C,0BAA0B,EAAE,KAAK;CAClC,CAAC;AAEF,MAAM,QAAQ,GAA8C;IAC1D,sBAAsB,EAAE;QACtB,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,IAAI;KAChB;IACD,4BAA4B,EAAE;QAC5B,OAAO,EAAE,KAAK;QACd,SAAS,EAAE,KAAK;KACjB;IACD,uBAAuB,EAAE;QACvB,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,IAAI;KAChB;IACD,kCAAkC,EAAE;QAClC,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;KACjB;IACD,mCAAmC,EAAE;QACnC,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;KACjB;IACD,0BAA0B,EAAE;QAC1B,OAAO,EAAE,KAAK;QACd,SAAS,EAAE,KAAK;KACjB;IACD,kCAAkC,EAAE;QAClC,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;KACjB;CACF,CA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,CAAC,IAAI,CAAC,IAAI,CAAC,CACrC,CAAC;IAEF,IAAI,CAAC,eAAe,CAAC,qBAAqB,CACxC,iDAAiD,EACjD,IAAI,CAAC,yBAAyB,CAAC,IAAI,CAAC,IAAI,CAAC,CAC1C,CAAC;IAEF,IAAI,CAAC,eAAe,CAAC,qBAAqB,CACxC,qCAAqC,EACrC,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,CAC9B,CAAC;AACJ,CAAC;AAuLD;;;;;;;GAOG;AACH,KAAK,iDACH,OAA6B,EAC7B,eAAwB;IAExB,kGAAkG;IAClG,IAAI,uBAAA,IAAI,oDAAuB,CAAC,OAAO,CAAC,EAAE;QACxC,OAAO,uBAAA,IAAI,oDAAuB,CAAC,OAAO,CAAC,CAAC;KAC7C;IAED,IAAI,CAAC,uBAAA,IAAI,yCAAY,EAAE;QACrB,MAAM,IAAI,KAAK,CACb,0DAA0D,CAC3D,CAAC;KACH;IAED,MAAM,MAAM,GAAG,CAAC,MAAM,IAAI,CAAC,eAAe,CAAC,IAAI,CAC7C,8BAA8B,EAC9B,IAAA,iDAA4B,EAAC,OAAO,EAAE,eAAe,CAAC,CACvD,CAAW,CAAC;IAEb,uBAAA,IAAI,oDAAuB,CAAC,OAAO,CAAC,GAAG,MAAM,CAAC;IAE9C,OAAO,MAAM,CAAC;AAChB,CAAC,2HAuCC,4BAAqC;IAErC,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,4BAA4B,GAAG,4BAA4B,CAAC;IACpE,CAAC,CAAC,CAAC;AACL,CAAC;kBAhbkB,qBAAqB","sourcesContent":["import type {\n AccountsControllerListAccountsAction,\n AccountsControllerUpdateAccountMetadataAction,\n AccountsControllerAccountRenamedEvent,\n AccountsControllerUpdateAccountsAction,\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 KeyringTypes,\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 isBackupAndSyncEnabled: boolean;\n /**\n * Loading state for the backup and sync update\n */\n isBackupAndSyncUpdateLoading: 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 isBackupAndSyncEnabled: true,\n isBackupAndSyncUpdateLoading: false,\n isAccountSyncingEnabled: true,\n hasAccountSyncingSyncedAtLeastOnce: false,\n isAccountSyncingReadyToBeDispatched: false,\n isAccountSyncingInProgress: false,\n};\n\nconst metadata: StateMetadata<UserStorageControllerState> = {\n isBackupAndSyncEnabled: {\n persist: true,\n anonymous: true,\n },\n isBackupAndSyncUpdateLoading: {\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 | AccountsControllerUpdateAccountsAction\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 | 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 (entropySourceId?: string) => {\n const sessionProfile = await this.messagingSystem.call(\n 'AuthenticationController:getSessionProfile',\n entropySourceId,\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: (entropySourceId?: string) =>\n this.messagingSystem.call(\n 'AuthenticationController:getBearerToken',\n entropySourceId,\n ),\n getUserProfile: async (entropySourceId?: string) => {\n return await this.messagingSystem.call(\n 'AuthenticationController:getSessionProfile',\n entropySourceId,\n );\n },\n signMessage: (message: string, entropySourceId?: string) =>\n this.#snapSignMessage(\n message as `metamask:${string}`,\n entropySourceId,\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 * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns the decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorage(\n path: UserStoragePathWithFeatureAndKey,\n entropySourceId?: string,\n ): Promise<string | null> {\n return await this.#userStorage.getItem(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n entropySourceId,\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 * @param entropySourceId - The entropy source ID used to generate the encryption key.\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 entropySourceId?: string,\n ): Promise<string[] | null> {\n return await this.#userStorage.getAllFeatureItems(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n entropySourceId,\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 * @param entropySourceId - The entropy source ID used to generate the encryption key.\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 entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.setItem(path, value, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n entropySourceId,\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 * @param entropySourceId - The entropy source ID used to generate the encryption key.\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 entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.batchSetItems(path, values, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n entropySourceId,\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 * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to delete data.\n */\n public async performDeleteStorage(\n path: UserStoragePathWithFeatureAndKey,\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.deleteItem(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n entropySourceId,\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 * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to delete data.\n */\n public async performDeleteStorageAllFeatureEntries(\n path: UserStoragePathWithFeatureOnly,\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.deleteAllFeatureItems(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\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 * @param entropySourceId - The entropy source ID used to generate the encryption key.\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 entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.batchDeleteItems(path, values, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\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 /**\n * Lists all the available HD keyring metadata IDs.\n * These IDs can be used in a multi-SRP context to segregate data specific to different SRPs.\n *\n * @returns A promise that resolves to an array of HD keyring metadata IDs.\n */\n async listEntropySources() {\n if (!this.#isUnlocked) {\n throw new Error(\n 'listEntropySources - unable to list entropy sources, wallet is locked',\n );\n }\n\n const { keyrings } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n return keyrings\n .filter((keyring) => keyring.type === KeyringTypes.hd.toString())\n .map((keyring) => keyring.metadata.id);\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 * @param entropySourceId - The entropy source ID used to derive the key,\n * when multiple sources are available (Multi-SRP).\n * @returns A Signature created by the snap.\n */\n async #snapSignMessage(\n message: `metamask:${string}`,\n entropySourceId?: string,\n ): Promise<string> {\n // the message is SRP specific already, so there's no need to use the entropySourceId in the cache\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, entropySourceId),\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.#setIsBackupAndSyncUpdateLoading(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.isBackupAndSyncEnabled = 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.#setIsBackupAndSyncUpdateLoading(false);\n }\n }\n\n #setIsBackupAndSyncUpdateLoading(\n isBackupAndSyncUpdateLoading: boolean,\n ): void {\n this.update((state) => {\n state.isBackupAndSyncUpdateLoading = isBackupAndSyncUpdateLoading;\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 entropySourceIds = await this.listEntropySources();\n\n try {\n for (const entropySourceId of entropySourceIds) {\n const profileId = await this.#auth.getProfileId(entropySourceId);\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: (\n situationMessage,\n sentryContext,\n ) =>\n this.#config?.accountSyncing?.onAccountSyncErroneousSituation?.(\n profileId,\n situationMessage,\n sentryContext,\n ),\n },\n {\n getMessenger: () => this.messagingSystem,\n getUserStorageControllerInstance: () => this,\n },\n entropySourceId,\n );\n }\n\n // We do this here and not in the finally statement because we want to make sure that\n // the accounts are saved / updated / deleted at least once before we set this flag\n await this.setHasAccountSyncingSyncedAtLeastOnce(true);\n } catch (e) {\n // Silently fail for now\n // istanbul ignore next\n console.error(e);\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.cjs","sourceRoot":"","sources":["../../../src/controllers/user-storage/UserStorageController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAaA,+DAA2D;AAC3D,qEAMsC;AAWtC,yFAGkD;AAClD,mFAAyF;AACzF,+CAAqD;AACrD,yFAGkD;AAClD,6CAA6C;AAO7C,oEAA4D;AAC5D,iFAAoF;AAQpF,MAAM,cAAc,GAAG,uBAAuB,CAAC;AAoClC,QAAA,YAAY,GAA+B;IACtD,sBAAsB,EAAE,IAAI;IAC5B,4BAA4B,EAAE,KAAK;IACnC,uBAAuB,EAAE,IAAI;IAC7B,kCAAkC,EAAE,KAAK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AC3D,CAAC;KACH;IAED,MAAM,MAAM,GAAG,CAAC,MAAM,IAAI,CAAC,eAAe,CAAC,IAAI,CAC7C,8BAA8B,EAC9B,IAAA,iDAA4B,EAAC,OAAO,EAAE,eAAe,CAAC,CACvD,CAAW,CAAC;IAEb,uBAAA,IAAI,oDAAuB,CAAC,OAAO,CAAC,GAAG,MAAM,CAAC;IAE9C,OAAO,MAAM,CAAC;AAChB,CAAC,2HAuCC,4BAAqC;IAErC,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,4BAA4B,GAAG,4BAA4B,CAAC;IACpE,CAAC,CAAC,CAAC;AACL,CAAC;kBAlbkB,qBAAqB","sourcesContent":["import type {\n AccountsControllerListAccountsAction,\n AccountsControllerUpdateAccountMetadataAction,\n AccountsControllerAccountRenamedEvent,\n AccountsControllerAccountAddedEvent,\n AccountsControllerUpdateAccountsAction,\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 KeyringTypes,\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 { EventQueue } from '../../shared/utils/event-queue';\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 isBackupAndSyncEnabled: boolean;\n /**\n * Loading state for the backup and sync update\n */\n isBackupAndSyncUpdateLoading: 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 isBackupAndSyncEnabled: true,\n isBackupAndSyncUpdateLoading: false,\n isAccountSyncingEnabled: true,\n hasAccountSyncingSyncedAtLeastOnce: false,\n isAccountSyncingReadyToBeDispatched: false,\n isAccountSyncingInProgress: false,\n};\n\nconst metadata: StateMetadata<UserStorageControllerState> = {\n isBackupAndSyncEnabled: {\n persist: true,\n anonymous: true,\n },\n isBackupAndSyncUpdateLoading: {\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 | AccountsControllerUpdateAccountsAction\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 | AccountsControllerAccountRenamedEvent\n | AccountsControllerAccountAddedEvent\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 (entropySourceId?: string) => {\n const sessionProfile = await this.messagingSystem.call(\n 'AuthenticationController:getSessionProfile',\n entropySourceId,\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 eventQueue = new EventQueue();\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: (entropySourceId?: string) =>\n this.messagingSystem.call(\n 'AuthenticationController:getBearerToken',\n entropySourceId,\n ),\n getUserProfile: async (entropySourceId?: string) => {\n return await this.messagingSystem.call(\n 'AuthenticationController:getSessionProfile',\n entropySourceId,\n );\n },\n signMessage: (message: string, entropySourceId?: string) =>\n this.#snapSignMessage(\n message as `metamask:${string}`,\n entropySourceId,\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 * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns the decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorage(\n path: UserStoragePathWithFeatureAndKey,\n entropySourceId?: string,\n ): Promise<string | null> {\n return await this.#userStorage.getItem(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n entropySourceId,\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 * @param entropySourceId - The entropy source ID used to generate the encryption key.\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 entropySourceId?: string,\n ): Promise<string[] | null> {\n return await this.#userStorage.getAllFeatureItems(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n entropySourceId,\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 * @param entropySourceId - The entropy source ID used to generate the encryption key.\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 entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.setItem(path, value, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n entropySourceId,\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 * @param entropySourceId - The entropy source ID used to generate the encryption key.\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 entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.batchSetItems(path, values, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n entropySourceId,\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 * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to delete data.\n */\n public async performDeleteStorage(\n path: UserStoragePathWithFeatureAndKey,\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.deleteItem(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n entropySourceId,\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 * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to delete data.\n */\n public async performDeleteStorageAllFeatureEntries(\n path: UserStoragePathWithFeatureOnly,\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.deleteAllFeatureItems(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\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 * @param entropySourceId - The entropy source ID used to generate the encryption key.\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 entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.batchDeleteItems(path, values, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\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 /**\n * Lists all the available HD keyring metadata IDs.\n * These IDs can be used in a multi-SRP context to segregate data specific to different SRPs.\n *\n * @returns A promise that resolves to an array of HD keyring metadata IDs.\n */\n async listEntropySources() {\n if (!this.#isUnlocked) {\n throw new Error(\n 'listEntropySources - unable to list entropy sources, wallet is locked',\n );\n }\n\n const { keyrings } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n return keyrings\n .filter((keyring) => keyring.type === KeyringTypes.hd.toString())\n .map((keyring) => keyring.metadata.id);\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 * @param entropySourceId - The entropy source ID used to derive the key,\n * when multiple sources are available (Multi-SRP).\n * @returns A Signature created by the snap.\n */\n async #snapSignMessage(\n message: `metamask:${string}`,\n entropySourceId?: string,\n ): Promise<string> {\n // the message is SRP specific already, so there's no need to use the entropySourceId in the cache\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, entropySourceId),\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.#setIsBackupAndSyncUpdateLoading(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.isBackupAndSyncEnabled = 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.#setIsBackupAndSyncUpdateLoading(false);\n }\n }\n\n #setIsBackupAndSyncUpdateLoading(\n isBackupAndSyncUpdateLoading: boolean,\n ): void {\n this.update((state) => {\n state.isBackupAndSyncUpdateLoading = isBackupAndSyncUpdateLoading;\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 entropySourceIds = await this.listEntropySources();\n\n try {\n for (const entropySourceId of entropySourceIds) {\n const profileId = await this.#auth.getProfileId(entropySourceId);\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: (\n situationMessage,\n sentryContext,\n ) =>\n this.#config?.accountSyncing?.onAccountSyncErroneousSituation?.(\n profileId,\n situationMessage,\n sentryContext,\n ),\n },\n {\n getMessenger: () => this.messagingSystem,\n getUserStorageControllerInstance: () => this,\n },\n entropySourceId,\n );\n }\n\n // We do this here and not in the finally statement because we want to make sure that\n // the accounts are saved / updated / deleted at least once before we set this flag\n await this.setHasAccountSyncingSyncedAtLeastOnce(true);\n } catch (e) {\n // Silently fail for now\n // istanbul ignore next\n console.error(e);\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,4 +1,4 @@
1
- import type { AccountsControllerListAccountsAction, AccountsControllerUpdateAccountMetadataAction, AccountsControllerAccountRenamedEvent, AccountsControllerUpdateAccountsAction } from "@metamask/accounts-controller";
1
+ import type { AccountsControllerListAccountsAction, AccountsControllerUpdateAccountMetadataAction, AccountsControllerAccountRenamedEvent, AccountsControllerAccountAddedEvent, AccountsControllerUpdateAccountsAction } from "@metamask/accounts-controller";
2
2
  import type { ControllerGetStateAction, ControllerStateChangeEvent, RestrictedMessenger } from "@metamask/base-controller";
3
3
  import { BaseController } from "@metamask/base-controller";
4
4
  import { type KeyringControllerGetStateAction, type KeyringControllerLockEvent, type KeyringControllerUnlockEvent, type KeyringControllerWithKeyringAction } from "@metamask/keyring-controller";
@@ -9,6 +9,7 @@ import { BACKUPANDSYNC_FEATURES } from "./constants.cjs";
9
9
  import type { UserStorageFeatureKeys } from "../../shared/storage-schema.cjs";
10
10
  import { type UserStoragePathWithFeatureAndKey, type UserStoragePathWithFeatureOnly } from "../../shared/storage-schema.cjs";
11
11
  import type { NativeScrypt } from "../../shared/types/encryption.cjs";
12
+ import { EventQueue } from "../../shared/utils/event-queue.cjs";
12
13
  import type { AuthenticationControllerGetBearerToken, AuthenticationControllerGetSessionProfile, AuthenticationControllerIsSignedIn, AuthenticationControllerPerformSignIn } from "../authentication/AuthenticationController.cjs";
13
14
  declare const controllerName = "UserStorageController";
14
15
  export type UserStorageControllerState = {
@@ -110,7 +111,7 @@ export type UserStorageControllerGetStorageKey = ActionsObj['getStorageKey'];
110
111
  export type AllowedActions = KeyringControllerGetStateAction | HandleSnapRequest | AuthenticationControllerGetBearerToken | AuthenticationControllerGetSessionProfile | AuthenticationControllerPerformSignIn | AuthenticationControllerIsSignedIn | AccountsControllerListAccountsAction | AccountsControllerUpdateAccountMetadataAction | AccountsControllerUpdateAccountsAction | KeyringControllerWithKeyringAction | NetworkControllerGetStateAction | NetworkControllerAddNetworkAction | NetworkControllerRemoveNetworkAction | NetworkControllerUpdateNetworkAction;
111
112
  export type UserStorageControllerStateChangeEvent = ControllerStateChangeEvent<typeof controllerName, UserStorageControllerState>;
112
113
  export type Events = UserStorageControllerStateChangeEvent;
113
- export type AllowedEvents = UserStorageControllerStateChangeEvent | KeyringControllerLockEvent | KeyringControllerUnlockEvent | AccountsControllerAccountRenamedEvent | NetworkControllerNetworkRemovedEvent;
114
+ export type AllowedEvents = UserStorageControllerStateChangeEvent | KeyringControllerLockEvent | KeyringControllerUnlockEvent | AccountsControllerAccountRenamedEvent | AccountsControllerAccountAddedEvent | NetworkControllerNetworkRemovedEvent;
114
115
  export type UserStorageControllerMessenger = RestrictedMessenger<typeof controllerName, Actions | AllowedActions, Events | AllowedEvents, AllowedActions['type'], AllowedEvents['type']>;
115
116
  /**
116
117
  * Reusable controller that allows any team to store synchronized data for a given user.
@@ -122,6 +123,7 @@ export type UserStorageControllerMessenger = RestrictedMessenger<typeof controll
122
123
  */
123
124
  export default class UserStorageController extends BaseController<typeof controllerName, UserStorageControllerState, UserStorageControllerMessenger> {
124
125
  #private;
126
+ eventQueue: EventQueue;
125
127
  constructor({ messenger, state, env, config, nativeScryptCrypto, }: {
126
128
  messenger: UserStorageControllerMessenger;
127
129
  state?: UserStorageControllerState;
@@ -1 +1 @@
1
- {"version":3,"file":"UserStorageController.d.cts","sourceRoot":"","sources":["../../../src/controllers/user-storage/UserStorageController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,oCAA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ACU,qCAAqC,CAChD,IAAI,EAAE,8BAA8B,EACpC,eAAe,CAAC,EAAE,MAAM,GACvB,OAAO,CAAC,IAAI,CAAC;IAOhB;;;;;;;;OAQG;IACU,yBAAyB,CACpC,WAAW,SAAS,8BAA8B,EAElD,IAAI,EAAE,WAAW,EACjB,MAAM,EAAE,sBAAsB,CAAC,WAAW,CAAC,EAAE,EAC7C,eAAe,CAAC,EAAE,MAAM,GACvB,OAAO,CAAC,IAAI,CAAC;IAOhB;;;;OAIG;IACU,aAAa,IAAI,OAAO,CAAC,MAAM,CAAC;IAI7C;;;;OAIG;IACI,oBAAoB,IAAI,IAAI;IAInC;;;;;OAKG;IACG,kBAAkB;IAkDX,gCAAgC,CAC3C,OAAO,EAAE,MAAM,OAAO,sBAAsB,EAC5C,OAAO,EAAE,OAAO,GACf,OAAO,CAAC,IAAI,CAAC;IAyCV,qCAAqC,CACzC,kCAAkC,EAAE,OAAO,GAC1C,OAAO,CAAC,IAAI,CAAC;IAOV,sCAAsC,CAC1C,mCAAmC,EAAE,OAAO,GAC3C,OAAO,CAAC,IAAI,CAAC;IAOV,6BAA6B,CACjC,0BAA0B,EAAE,OAAO,GAClC,OAAO,CAAC,IAAI,CAAC;IAMhB;;;;OAIG;IACG,mCAAmC,IAAI,OAAO,CAAC,IAAI,CAAC;IA2C1D;;;;OAIG;IACG,gCAAgC,CACpC,eAAe,EAAE,eAAe,GAC/B,OAAO,CAAC,IAAI,CAAC;IAOV,YAAY;CAuBnB"}
1
+ {"version":3,"file":"UserStorageController.d.cts","sourceRoot":"","sources":["../../../src/controllers/user-storage/UserStorageController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,oCAAoC,EACpC,6CAA6C,EAC7C,qCAAqC,EACrC,mCAAmC,EACnC,sCAAsC,EACvC,sCAAsC;AACvC,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAC1B,mBAAmB,EAEpB,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC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hB;;;;;;;;OAQG;IACU,yBAAyB,CACpC,WAAW,SAAS,8BAA8B,EAElD,IAAI,EAAE,WAAW,EACjB,MAAM,EAAE,sBAAsB,CAAC,WAAW,CAAC,EAAE,EAC7C,eAAe,CAAC,EAAE,MAAM,GACvB,OAAO,CAAC,IAAI,CAAC;IAOhB;;;;OAIG;IACU,aAAa,IAAI,OAAO,CAAC,MAAM,CAAC;IAI7C;;;;OAIG;IACI,oBAAoB,IAAI,IAAI;IAInC;;;;;OAKG;IACG,kBAAkB;IAkDX,gCAAgC,CAC3C,OAAO,EAAE,MAAM,OAAO,sBAAsB,EAC5C,OAAO,EAAE,OAAO,GACf,OAAO,CAAC,IAAI,CAAC;IAyCV,qCAAqC,CACzC,kCAAkC,EAAE,OAAO,GAC1C,OAAO,CAAC,IAAI,CAAC;IAOV,sCAAsC,CAC1C,mCAAmC,EAAE,OAAO,GAC3C,OAAO,CAAC,IAAI,CAAC;IAOV,6BAA6B,CACjC,0BAA0B,EAAE,OAAO,GAClC,OAAO,CAAC,IAAI,CAAC;IAMhB;;;;OAIG;IACG,mCAAmC,IAAI,OAAO,CAAC,IAAI,CAAC;IA2C1D;;;;OAIG;IACG,gCAAgC,CACpC,eAAe,EAAE,eAAe,GAC/B,OAAO,CAAC,IAAI,CAAC;IAOV,YAAY;CAuBnB"}
@@ -1,4 +1,4 @@
1
- import type { AccountsControllerListAccountsAction, AccountsControllerUpdateAccountMetadataAction, AccountsControllerAccountRenamedEvent, AccountsControllerUpdateAccountsAction } from "@metamask/accounts-controller";
1
+ import type { AccountsControllerListAccountsAction, AccountsControllerUpdateAccountMetadataAction, AccountsControllerAccountRenamedEvent, AccountsControllerAccountAddedEvent, AccountsControllerUpdateAccountsAction } from "@metamask/accounts-controller";
2
2
  import type { ControllerGetStateAction, ControllerStateChangeEvent, RestrictedMessenger } from "@metamask/base-controller";
3
3
  import { BaseController } from "@metamask/base-controller";
4
4
  import { type KeyringControllerGetStateAction, type KeyringControllerLockEvent, type KeyringControllerUnlockEvent, type KeyringControllerWithKeyringAction } from "@metamask/keyring-controller";
@@ -9,6 +9,7 @@ import { BACKUPANDSYNC_FEATURES } from "./constants.mjs";
9
9
  import type { UserStorageFeatureKeys } from "../../shared/storage-schema.mjs";
10
10
  import { type UserStoragePathWithFeatureAndKey, type UserStoragePathWithFeatureOnly } from "../../shared/storage-schema.mjs";
11
11
  import type { NativeScrypt } from "../../shared/types/encryption.mjs";
12
+ import { EventQueue } from "../../shared/utils/event-queue.mjs";
12
13
  import type { AuthenticationControllerGetBearerToken, AuthenticationControllerGetSessionProfile, AuthenticationControllerIsSignedIn, AuthenticationControllerPerformSignIn } from "../authentication/AuthenticationController.mjs";
13
14
  declare const controllerName = "UserStorageController";
14
15
  export type UserStorageControllerState = {
@@ -110,7 +111,7 @@ export type UserStorageControllerGetStorageKey = ActionsObj['getStorageKey'];
110
111
  export type AllowedActions = KeyringControllerGetStateAction | HandleSnapRequest | AuthenticationControllerGetBearerToken | AuthenticationControllerGetSessionProfile | AuthenticationControllerPerformSignIn | AuthenticationControllerIsSignedIn | AccountsControllerListAccountsAction | AccountsControllerUpdateAccountMetadataAction | AccountsControllerUpdateAccountsAction | KeyringControllerWithKeyringAction | NetworkControllerGetStateAction | NetworkControllerAddNetworkAction | NetworkControllerRemoveNetworkAction | NetworkControllerUpdateNetworkAction;
111
112
  export type UserStorageControllerStateChangeEvent = ControllerStateChangeEvent<typeof controllerName, UserStorageControllerState>;
112
113
  export type Events = UserStorageControllerStateChangeEvent;
113
- export type AllowedEvents = UserStorageControllerStateChangeEvent | KeyringControllerLockEvent | KeyringControllerUnlockEvent | AccountsControllerAccountRenamedEvent | NetworkControllerNetworkRemovedEvent;
114
+ export type AllowedEvents = UserStorageControllerStateChangeEvent | KeyringControllerLockEvent | KeyringControllerUnlockEvent | AccountsControllerAccountRenamedEvent | AccountsControllerAccountAddedEvent | NetworkControllerNetworkRemovedEvent;
114
115
  export type UserStorageControllerMessenger = RestrictedMessenger<typeof controllerName, Actions | AllowedActions, Events | AllowedEvents, AllowedActions['type'], AllowedEvents['type']>;
115
116
  /**
116
117
  * Reusable controller that allows any team to store synchronized data for a given user.
@@ -122,6 +123,7 @@ export type UserStorageControllerMessenger = RestrictedMessenger<typeof controll
122
123
  */
123
124
  export default class UserStorageController extends BaseController<typeof controllerName, UserStorageControllerState, UserStorageControllerMessenger> {
124
125
  #private;
126
+ eventQueue: EventQueue;
125
127
  constructor({ messenger, state, env, config, nativeScryptCrypto, }: {
126
128
  messenger: UserStorageControllerMessenger;
127
129
  state?: UserStorageControllerState;
@@ -1 +1 @@
1
- {"version":3,"file":"UserStorageController.d.mts","sourceRoot":"","sources":["../../../src/controllers/user-storage/UserStorageController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,oCAAoC,EACpC,6CAA6C,EAC7C,qCAAqC,EACrC,sCAAsC,EACvC,sCAAsC;AACvC,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAC1B,mBAAmB,EAEpB,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,EAEL,KAAK,+BAA+B,EACpC,KAAK,0BAA0B,EAC/B,KAAK,4BAA4B,EACjC,KAAK,kCAAkC,EACxC,qCAAqC;AACtC,OAAO,KAAK,EAAE,eAAe,EAAE,uCAAuC;AACtE,OAAO,KAAK,EACV,iCAAiC,EACjC,+BAA+B,EAC/B,oCAAoC,EACpC,oCAAoC,EACpC,oCAAoC,EACrC,qCAAqC;AACtC,OAAO,KAAK,EAAE,iBAAiB,EAAE,oCAAoC;AAOrE,OAAO,EAAE,sBAAsB,EAAE,wBAAoB;AAMrD,OAAO,KAAK,EAAE,sBAAsB,EAAE,wCAAoC;AAC1E,OAAO,EACL,KAAK,gCAAgC,EACrC,KAAK,8BAA8B,EACpC,wCAAoC;AACrC,OAAO,KAAK,EAAE,YAAY,EAAE,0CAAsC;AAElE,OAAO,KAAK,EACV,sCAAsC,EACtC,yCAAyC,EACzC,kCAAkC,EACl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C;IAMhB;;;;OAIG;IACG,mCAAmC,IAAI,OAAO,CAAC,IAAI,CAAC;IA2C1D;;;;OAIG;IACG,gCAAgC,CACpC,eAAe,EAAE,eAAe,GAC/B,OAAO,CAAC,IAAI,CAAC;IAOV,YAAY;CAuBnB"}
1
+ {"version":3,"file":"UserStorageController.d.mts","sourceRoot":"","sources":["../../../src/controllers/user-storage/UserStorageController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,oCAAoC,EACpC,6CAA6C,EAC7C,qCAAqC,EACrC,mCAAmC,EACnC,sCAAsC,EACvC,sCAAsC;AACvC,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAC1B,mBAAmB,EAEpB,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,EAEL,KAAK,+BAA+B,EACpC,KAAK,0BAA0B,EAC/B,KAAK,4BAA4B,EACjC,KAAK,kCAAkC,EACxC,qCAAqC;AACtC,OAAO,KAAK,EAAE,eAAe,EAAE,uCAAuC;AACtE,OAAO,KAAK,EACV,iCAAiC,EACjC,+BAA+B,EAC/B,oCAAoC,EACpC,oCAAoC,EACpC,oCAAoC,EACrC,qCAAqC;AACtC,OAAO,KAAK,EAAE,iBAAiB,EAAE,oCAAoC;AAOrE,OAAO,EAAE,sBAAsB,EAAE,wBAAoB;AAMrD,OAAO,KAAK,EAAE,sBAAsB,EAAE,wCAAoC;AAC1E,OAAO,EACL,KAAK,gCAAgC,EACrC,KAAK,8BAA8B,EACpC,wCAAoC;AACrC,OAAO,KAAK,EAAE,YAAY,EAAE,0CAAsC;AAClE,OAAO,EAAE,UAAU,EAAE,2CAAuC;AAE5D,OAAO,KAAK,EACV,sCAAsC,EACtC,yCAAyC,EACzC,kCAAkC,EAClC,qCAAqC,EACtC,uDAAmD;AAEpD,QAAA,MAAM,cAAc,0BAA0B,CAAC;AAG/C,MAAM,MAAM,0BAA0B,GAAG;IACvC;;OAEG;IACH,sBAAsB,EAAE,OAAO,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Ae,EAAE,eAAe,GAC/B,OAAO,CAAC,IAAI,CAAC;IAOV,YAAY;CAuBnB"}
@@ -17,6 +17,7 @@ import { setupAccountSyncingSubscriptions } from "./account-syncing/setup-subscr
17
17
  import { BACKUPANDSYNC_FEATURES } from "./constants.mjs";
18
18
  import { performMainNetworkSync, startNetworkSyncing } from "./network-syncing/controller-integration.mjs";
19
19
  import { Env, UserStorage } from "../../sdk/index.mjs";
20
+ import { EventQueue } from "../../shared/utils/event-queue.mjs";
20
21
  import { createSnapSignMessageRequest } from "../authentication/auth-snap-requests.mjs";
21
22
  const controllerName = 'UserStorageController';
22
23
  export const defaultState = {
@@ -108,6 +109,7 @@ class UserStorageController extends BaseController {
108
109
  },
109
110
  });
110
111
  _UserStorageController_nativeScryptCrypto.set(this, undefined);
112
+ this.eventQueue = new EventQueue();
111
113
  _UserStorageController__snapSignMessageCache.set(this, {});
112
114
  __classPrivateFieldGet(this, _UserStorageController_env, "f").isNetworkSyncingEnabled = Boolean(env?.isNetworkSyncingEnabled);
113
115
  __classPrivateFieldSet(this, _UserStorageController_config, config, "f");
@@ -1 +1 @@
1
- {"version":3,"file":"UserStorageController.mjs","sourceRoot":"","sources":["../../../src/controllers/user-storage/UserStorageController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAYA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,EACL,YAAY,EAKb,qCAAqC;AAWtC,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;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,IAAI,KAAK,CACb,0DAA0D,CAC3D,CAAC;KACH;IAED,MAAM,MAAM,GAAG,CAAC,MAAM,IAAI,CAAC,eAAe,CAAC,IAAI,CAC7C,8BAA8B,EAC9B,4BAA4B,CAAC,OAAO,EAAE,eAAe,CAAC,CACvD,CAAW,CAAC;IAEb,uBAAA,IAAI,oDAAuB,CAAC,OAAO,CAAC,GAAG,MAAM,CAAC;IAE9C,OAAO,MAAM,CAAC;AAChB,CAAC,2HAuCC,4BAAqC;IAErC,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,4BAA4B,GAAG,4BAA4B,CAAC;IACpE,CAAC,CAAC,CAAC;AACL,CAAC;eAhbkB,qBAAqB","sourcesContent":["import type {\n AccountsControllerListAccountsAction,\n AccountsControllerUpdateAccountMetadataAction,\n AccountsControllerAccountRenamedEvent,\n AccountsControllerUpdateAccountsAction,\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 KeyringTypes,\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 isBackupAndSyncEnabled: boolean;\n /**\n * Loading state for the backup and sync update\n */\n isBackupAndSyncUpdateLoading: 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 isBackupAndSyncEnabled: true,\n isBackupAndSyncUpdateLoading: false,\n isAccountSyncingEnabled: true,\n hasAccountSyncingSyncedAtLeastOnce: false,\n isAccountSyncingReadyToBeDispatched: false,\n isAccountSyncingInProgress: false,\n};\n\nconst metadata: StateMetadata<UserStorageControllerState> = {\n isBackupAndSyncEnabled: {\n persist: true,\n anonymous: true,\n },\n isBackupAndSyncUpdateLoading: {\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 | AccountsControllerUpdateAccountsAction\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 | 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 (entropySourceId?: string) => {\n const sessionProfile = await this.messagingSystem.call(\n 'AuthenticationController:getSessionProfile',\n entropySourceId,\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: (entropySourceId?: string) =>\n this.messagingSystem.call(\n 'AuthenticationController:getBearerToken',\n entropySourceId,\n ),\n getUserProfile: async (entropySourceId?: string) => {\n return await this.messagingSystem.call(\n 'AuthenticationController:getSessionProfile',\n entropySourceId,\n );\n },\n signMessage: (message: string, entropySourceId?: string) =>\n this.#snapSignMessage(\n message as `metamask:${string}`,\n entropySourceId,\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 * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns the decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorage(\n path: UserStoragePathWithFeatureAndKey,\n entropySourceId?: string,\n ): Promise<string | null> {\n return await this.#userStorage.getItem(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n entropySourceId,\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 * @param entropySourceId - The entropy source ID used to generate the encryption key.\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 entropySourceId?: string,\n ): Promise<string[] | null> {\n return await this.#userStorage.getAllFeatureItems(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n entropySourceId,\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 * @param entropySourceId - The entropy source ID used to generate the encryption key.\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 entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.setItem(path, value, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n entropySourceId,\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 * @param entropySourceId - The entropy source ID used to generate the encryption key.\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 entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.batchSetItems(path, values, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n entropySourceId,\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 * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to delete data.\n */\n public async performDeleteStorage(\n path: UserStoragePathWithFeatureAndKey,\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.deleteItem(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n entropySourceId,\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 * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to delete data.\n */\n public async performDeleteStorageAllFeatureEntries(\n path: UserStoragePathWithFeatureOnly,\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.deleteAllFeatureItems(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\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 * @param entropySourceId - The entropy source ID used to generate the encryption key.\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 entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.batchDeleteItems(path, values, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\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 /**\n * Lists all the available HD keyring metadata IDs.\n * These IDs can be used in a multi-SRP context to segregate data specific to different SRPs.\n *\n * @returns A promise that resolves to an array of HD keyring metadata IDs.\n */\n async listEntropySources() {\n if (!this.#isUnlocked) {\n throw new Error(\n 'listEntropySources - unable to list entropy sources, wallet is locked',\n );\n }\n\n const { keyrings } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n return keyrings\n .filter((keyring) => keyring.type === KeyringTypes.hd.toString())\n .map((keyring) => keyring.metadata.id);\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 * @param entropySourceId - The entropy source ID used to derive the key,\n * when multiple sources are available (Multi-SRP).\n * @returns A Signature created by the snap.\n */\n async #snapSignMessage(\n message: `metamask:${string}`,\n entropySourceId?: string,\n ): Promise<string> {\n // the message is SRP specific already, so there's no need to use the entropySourceId in the cache\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, entropySourceId),\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.#setIsBackupAndSyncUpdateLoading(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.isBackupAndSyncEnabled = 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.#setIsBackupAndSyncUpdateLoading(false);\n }\n }\n\n #setIsBackupAndSyncUpdateLoading(\n isBackupAndSyncUpdateLoading: boolean,\n ): void {\n this.update((state) => {\n state.isBackupAndSyncUpdateLoading = isBackupAndSyncUpdateLoading;\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 entropySourceIds = await this.listEntropySources();\n\n try {\n for (const entropySourceId of entropySourceIds) {\n const profileId = await this.#auth.getProfileId(entropySourceId);\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: (\n situationMessage,\n sentryContext,\n ) =>\n this.#config?.accountSyncing?.onAccountSyncErroneousSituation?.(\n profileId,\n situationMessage,\n sentryContext,\n ),\n },\n {\n getMessenger: () => this.messagingSystem,\n getUserStorageControllerInstance: () => this,\n },\n entropySourceId,\n );\n }\n\n // We do this here and not in the finally statement because we want to make sure that\n // the accounts are saved / updated / deleted at least once before we set this flag\n await this.setHasAccountSyncingSyncedAtLeastOnce(true);\n } catch (e) {\n // Silently fail for now\n // istanbul ignore next\n console.error(e);\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":";;;;;;;;;;;;AAaA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,EACL,YAAY,EAKb,qCAAqC;AAWtC,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,UAAU,EAAE,2CAAuC;AAC5D,OAAO,EAAE,4BAA4B,EAAE,iDAA6C;AAQpF,MAAM,cAAc,GAAG,uBAAuB,CAAC;AAoC/C,MAAM,CAAC,MAAM,YAAY,GAA+B;IACtD,sBAAsB,EAAE,IAAI;IAC5B,4BAA4B,EAAE,KAAK;IACnC,uBAAuB,EAAE,IAAI;IAC7B,kCAAkC,EAAE,KAAK;IACzC,mCAAmC,EAAE,KAAK;IAC1C,0BAA0B,EAAE,KAAK;CAClC,CAAC;AAEF,MAAM,QAAQ,GAA8C;IAC1D,sBAAsB,EAAE;QACtB,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,IAAI;KAChB;IACD,4BAA4B,EAAE;QAC5B,OAAO,EAAE,KAAK;QACd,SAAS,EAAE,KAAK;KACjB;IACD,uBAAuB,EAAE;QACvB,OAAO,EAAE,I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AAK,EAAE,EAAE;QACpB,KAAK,CAAC,4BAA4B,GAAG,4BAA4B,CAAC;IACpE,CAAC,CAAC,CAAC;AACL,CAAC;eAlbkB,qBAAqB","sourcesContent":["import type {\n AccountsControllerListAccountsAction,\n AccountsControllerUpdateAccountMetadataAction,\n AccountsControllerAccountRenamedEvent,\n AccountsControllerAccountAddedEvent,\n AccountsControllerUpdateAccountsAction,\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 KeyringTypes,\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 { EventQueue } from '../../shared/utils/event-queue';\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 isBackupAndSyncEnabled: boolean;\n /**\n * Loading state for the backup and sync update\n */\n isBackupAndSyncUpdateLoading: 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 isBackupAndSyncEnabled: true,\n isBackupAndSyncUpdateLoading: false,\n isAccountSyncingEnabled: true,\n hasAccountSyncingSyncedAtLeastOnce: false,\n isAccountSyncingReadyToBeDispatched: false,\n isAccountSyncingInProgress: false,\n};\n\nconst metadata: StateMetadata<UserStorageControllerState> = {\n isBackupAndSyncEnabled: {\n persist: true,\n anonymous: true,\n },\n isBackupAndSyncUpdateLoading: {\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 | AccountsControllerUpdateAccountsAction\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 | AccountsControllerAccountRenamedEvent\n | AccountsControllerAccountAddedEvent\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 (entropySourceId?: string) => {\n const sessionProfile = await this.messagingSystem.call(\n 'AuthenticationController:getSessionProfile',\n entropySourceId,\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 eventQueue = new EventQueue();\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: (entropySourceId?: string) =>\n this.messagingSystem.call(\n 'AuthenticationController:getBearerToken',\n entropySourceId,\n ),\n getUserProfile: async (entropySourceId?: string) => {\n return await this.messagingSystem.call(\n 'AuthenticationController:getSessionProfile',\n entropySourceId,\n );\n },\n signMessage: (message: string, entropySourceId?: string) =>\n this.#snapSignMessage(\n message as `metamask:${string}`,\n entropySourceId,\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 * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns the decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorage(\n path: UserStoragePathWithFeatureAndKey,\n entropySourceId?: string,\n ): Promise<string | null> {\n return await this.#userStorage.getItem(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n entropySourceId,\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 * @param entropySourceId - The entropy source ID used to generate the encryption key.\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 entropySourceId?: string,\n ): Promise<string[] | null> {\n return await this.#userStorage.getAllFeatureItems(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n entropySourceId,\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 * @param entropySourceId - The entropy source ID used to generate the encryption key.\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 entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.setItem(path, value, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n entropySourceId,\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 * @param entropySourceId - The entropy source ID used to generate the encryption key.\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 entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.batchSetItems(path, values, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n entropySourceId,\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 * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to delete data.\n */\n public async performDeleteStorage(\n path: UserStoragePathWithFeatureAndKey,\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.deleteItem(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n validateAgainstSchema: true,\n entropySourceId,\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 * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to delete data.\n */\n public async performDeleteStorageAllFeatureEntries(\n path: UserStoragePathWithFeatureOnly,\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.deleteAllFeatureItems(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\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 * @param entropySourceId - The entropy source ID used to generate the encryption key.\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 entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.batchDeleteItems(path, values, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\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 /**\n * Lists all the available HD keyring metadata IDs.\n * These IDs can be used in a multi-SRP context to segregate data specific to different SRPs.\n *\n * @returns A promise that resolves to an array of HD keyring metadata IDs.\n */\n async listEntropySources() {\n if (!this.#isUnlocked) {\n throw new Error(\n 'listEntropySources - unable to list entropy sources, wallet is locked',\n );\n }\n\n const { keyrings } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n return keyrings\n .filter((keyring) => keyring.type === KeyringTypes.hd.toString())\n .map((keyring) => keyring.metadata.id);\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 * @param entropySourceId - The entropy source ID used to derive the key,\n * when multiple sources are available (Multi-SRP).\n * @returns A Signature created by the snap.\n */\n async #snapSignMessage(\n message: `metamask:${string}`,\n entropySourceId?: string,\n ): Promise<string> {\n // the message is SRP specific already, so there's no need to use the entropySourceId in the cache\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, entropySourceId),\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.#setIsBackupAndSyncUpdateLoading(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.isBackupAndSyncEnabled = 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.#setIsBackupAndSyncUpdateLoading(false);\n }\n }\n\n #setIsBackupAndSyncUpdateLoading(\n isBackupAndSyncUpdateLoading: boolean,\n ): void {\n this.update((state) => {\n state.isBackupAndSyncUpdateLoading = isBackupAndSyncUpdateLoading;\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 entropySourceIds = await this.listEntropySources();\n\n try {\n for (const entropySourceId of entropySourceIds) {\n const profileId = await this.#auth.getProfileId(entropySourceId);\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: (\n situationMessage,\n sentryContext,\n ) =>\n this.#config?.accountSyncing?.onAccountSyncErroneousSituation?.(\n profileId,\n situationMessage,\n sentryContext,\n ),\n },\n {\n getMessenger: () => this.messagingSystem,\n getUserStorageControllerInstance: () => this,\n },\n entropySourceId,\n );\n }\n\n // We do this here and not in the finally statement because we want to make sure that\n // the accounts are saved / updated / deleted at least once before we set this flag\n await this.setHasAccountSyncingSyncedAtLeastOnce(true);\n } catch (e) {\n // Silently fail for now\n // istanbul ignore next\n console.error(e);\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"]}
@@ -10,15 +10,25 @@ const sync_utils_1 = require("./sync-utils.cjs");
10
10
  */
11
11
  function setupAccountSyncingSubscriptions(options) {
12
12
  const { getMessenger, getUserStorageControllerInstance } = options;
13
- // We don't listen to `AccountsController:accountAdded`
14
- // because it publishes `AccountsController:accountRenamed` in any case.
13
+ getMessenger().subscribe('AccountsController:accountAdded', async (account) => {
14
+ if (!(0, sync_utils_1.canPerformAccountSyncing)(options) ||
15
+ !getUserStorageControllerInstance().state
16
+ .hasAccountSyncingSyncedAtLeastOnce) {
17
+ return;
18
+ }
19
+ const { eventQueue } = getUserStorageControllerInstance();
20
+ eventQueue.push(async () => await (0, controller_integration_1.saveInternalAccountToUserStorage)(account, options));
21
+ await eventQueue.run();
22
+ });
15
23
  getMessenger().subscribe('AccountsController:accountRenamed', async (account) => {
16
24
  if (!(0, sync_utils_1.canPerformAccountSyncing)(options) ||
17
25
  !getUserStorageControllerInstance().state
18
26
  .hasAccountSyncingSyncedAtLeastOnce) {
19
27
  return;
20
28
  }
21
- await (0, controller_integration_1.saveInternalAccountToUserStorage)(account, options);
29
+ const { eventQueue } = getUserStorageControllerInstance();
30
+ eventQueue.push(async () => await (0, controller_integration_1.saveInternalAccountToUserStorage)(account, options));
31
+ await eventQueue.run();
22
32
  });
23
33
  }
24
34
  exports.setupAccountSyncingSubscriptions = setupAccountSyncingSubscriptions;
@@ -1 +1 @@
1
- {"version":3,"file":"setup-subscriptions.cjs","sourceRoot":"","sources":["../../../../src/controllers/user-storage/account-syncing/setup-subscriptions.ts"],"names":[],"mappings":";;;AAAA,yEAA4E;AAC5E,iDAAwD;AAGxD;;;;GAIG;AACH,SAAgB,gCAAgC,CAC9C,OAA8B;IAE9B,MAAM,EAAE,YAAY,EAAE,gCAAgC,EAAE,GAAG,OAAO,CAAC;IAEnE,uDAAuD;IACvD,wEAAwE;IACxE,YAAY,EAAE,CAAC,SAAS,CACtB,mCAAmC,EAEnC,KAAK,EAAE,OAAO,EAAE,EAAE;QAChB,IACE,CAAC,IAAA,qCAAwB,EAAC,OAAO,CAAC;YAClC,CAAC,gCAAgC,EAAE,CAAC,KAAK;iBACtC,kCAAkC,EACrC;YACA,OAAO;SACR;QAED,MAAM,IAAA,yDAAgC,EAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAC3D,CAAC,CACF,CAAC;AACJ,CAAC;AAtBD,4EAsBC","sourcesContent":["import { saveInternalAccountToUserStorage } from './controller-integration';\nimport { canPerformAccountSyncing } from './sync-utils';\nimport type { AccountSyncingOptions } from './types';\n\n/**\n * Initialize and setup events to listen to for account syncing\n *\n * @param options - parameters used for initializing and enabling account syncing\n */\nexport function setupAccountSyncingSubscriptions(\n options: AccountSyncingOptions,\n) {\n const { getMessenger, getUserStorageControllerInstance } = options;\n\n // We don't listen to `AccountsController:accountAdded`\n // because it publishes `AccountsController:accountRenamed` in any case.\n getMessenger().subscribe(\n 'AccountsController:accountRenamed',\n\n async (account) => {\n if (\n !canPerformAccountSyncing(options) ||\n !getUserStorageControllerInstance().state\n .hasAccountSyncingSyncedAtLeastOnce\n ) {\n return;\n }\n\n await saveInternalAccountToUserStorage(account, options);\n },\n );\n}\n"]}
1
+ {"version":3,"file":"setup-subscriptions.cjs","sourceRoot":"","sources":["../../../../src/controllers/user-storage/account-syncing/setup-subscriptions.ts"],"names":[],"mappings":";;;AAAA,yEAA4E;AAC5E,iDAAwD;AAGxD;;;;GAIG;AACH,SAAgB,gCAAgC,CAC9C,OAA8B;IAE9B,MAAM,EAAE,YAAY,EAAE,gCAAgC,EAAE,GAAG,OAAO,CAAC;IAEnE,YAAY,EAAE,CAAC,SAAS,CACtB,iCAAiC,EAEjC,KAAK,EAAE,OAAO,EAAE,EAAE;QAChB,IACE,CAAC,IAAA,qCAAwB,EAAC,OAAO,CAAC;YAClC,CAAC,gCAAgC,EAAE,CAAC,KAAK;iBACtC,kCAAkC,EACrC;YACA,OAAO;SACR;QAED,MAAM,EAAE,UAAU,EAAE,GAAG,gCAAgC,EAAE,CAAC;QAE1D,UAAU,CAAC,IAAI,CACb,KAAK,IAAI,EAAE,CAAC,MAAM,IAAA,yDAAgC,EAAC,OAAO,EAAE,OAAO,CAAC,CACrE,CAAC;QACF,MAAM,UAAU,CAAC,GAAG,EAAE,CAAC;IACzB,CAAC,CACF,CAAC;IAEF,YAAY,EAAE,CAAC,SAAS,CACtB,mCAAmC,EAEnC,KAAK,EAAE,OAAO,EAAE,EAAE;QAChB,IACE,CAAC,IAAA,qCAAwB,EAAC,OAAO,CAAC;YAClC,CAAC,gCAAgC,EAAE,CAAC,KAAK;iBACtC,kCAAkC,EACrC;YACA,OAAO;SACR;QAED,MAAM,EAAE,UAAU,EAAE,GAAG,gCAAgC,EAAE,CAAC;QAE1D,UAAU,CAAC,IAAI,CACb,KAAK,IAAI,EAAE,CAAC,MAAM,IAAA,yDAAgC,EAAC,OAAO,EAAE,OAAO,CAAC,CACrE,CAAC;QACF,MAAM,UAAU,CAAC,GAAG,EAAE,CAAC;IACzB,CAAC,CACF,CAAC;AACJ,CAAC;AA9CD,4EA8CC","sourcesContent":["import { saveInternalAccountToUserStorage } from './controller-integration';\nimport { canPerformAccountSyncing } from './sync-utils';\nimport type { AccountSyncingOptions } from './types';\n\n/**\n * Initialize and setup events to listen to for account syncing\n *\n * @param options - parameters used for initializing and enabling account syncing\n */\nexport function setupAccountSyncingSubscriptions(\n options: AccountSyncingOptions,\n) {\n const { getMessenger, getUserStorageControllerInstance } = options;\n\n getMessenger().subscribe(\n 'AccountsController:accountAdded',\n\n async (account) => {\n if (\n !canPerformAccountSyncing(options) ||\n !getUserStorageControllerInstance().state\n .hasAccountSyncingSyncedAtLeastOnce\n ) {\n return;\n }\n\n const { eventQueue } = getUserStorageControllerInstance();\n\n eventQueue.push(\n async () => await saveInternalAccountToUserStorage(account, options),\n );\n await eventQueue.run();\n },\n );\n\n getMessenger().subscribe(\n 'AccountsController:accountRenamed',\n\n async (account) => {\n if (\n !canPerformAccountSyncing(options) ||\n !getUserStorageControllerInstance().state\n .hasAccountSyncingSyncedAtLeastOnce\n ) {\n return;\n }\n\n const { eventQueue } = getUserStorageControllerInstance();\n\n eventQueue.push(\n async () => await saveInternalAccountToUserStorage(account, options),\n );\n await eventQueue.run();\n },\n );\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"setup-subscriptions.d.cts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/account-syncing/setup-subscriptions.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,qBAAqB,EAAE,oBAAgB;AAErD;;;;GAIG;AACH,wBAAgB,gCAAgC,CAC9C,OAAO,EAAE,qBAAqB,QAqB/B"}
1
+ {"version":3,"file":"setup-subscriptions.d.cts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/account-syncing/setup-subscriptions.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,qBAAqB,EAAE,oBAAgB;AAErD;;;;GAIG;AACH,wBAAgB,gCAAgC,CAC9C,OAAO,EAAE,qBAAqB,QA6C/B"}
@@ -1 +1 @@
1
- {"version":3,"file":"setup-subscriptions.d.mts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/account-syncing/setup-subscriptions.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,qBAAqB,EAAE,oBAAgB;AAErD;;;;GAIG;AACH,wBAAgB,gCAAgC,CAC9C,OAAO,EAAE,qBAAqB,QAqB/B"}
1
+ {"version":3,"file":"setup-subscriptions.d.mts","sourceRoot":"","sources":["../../../../src/controllers/user-storage/account-syncing/setup-subscriptions.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,qBAAqB,EAAE,oBAAgB;AAErD;;;;GAIG;AACH,wBAAgB,gCAAgC,CAC9C,OAAO,EAAE,qBAAqB,QA6C/B"}
@@ -7,15 +7,25 @@ import { canPerformAccountSyncing } from "./sync-utils.mjs";
7
7
  */
8
8
  export function setupAccountSyncingSubscriptions(options) {
9
9
  const { getMessenger, getUserStorageControllerInstance } = options;
10
- // We don't listen to `AccountsController:accountAdded`
11
- // because it publishes `AccountsController:accountRenamed` in any case.
10
+ getMessenger().subscribe('AccountsController:accountAdded', async (account) => {
11
+ if (!canPerformAccountSyncing(options) ||
12
+ !getUserStorageControllerInstance().state
13
+ .hasAccountSyncingSyncedAtLeastOnce) {
14
+ return;
15
+ }
16
+ const { eventQueue } = getUserStorageControllerInstance();
17
+ eventQueue.push(async () => await saveInternalAccountToUserStorage(account, options));
18
+ await eventQueue.run();
19
+ });
12
20
  getMessenger().subscribe('AccountsController:accountRenamed', async (account) => {
13
21
  if (!canPerformAccountSyncing(options) ||
14
22
  !getUserStorageControllerInstance().state
15
23
  .hasAccountSyncingSyncedAtLeastOnce) {
16
24
  return;
17
25
  }
18
- await saveInternalAccountToUserStorage(account, options);
26
+ const { eventQueue } = getUserStorageControllerInstance();
27
+ eventQueue.push(async () => await saveInternalAccountToUserStorage(account, options));
28
+ await eventQueue.run();
19
29
  });
20
30
  }
21
31
  //# sourceMappingURL=setup-subscriptions.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"setup-subscriptions.mjs","sourceRoot":"","sources":["../../../../src/controllers/user-storage/account-syncing/setup-subscriptions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gCAAgC,EAAE,qCAAiC;AAC5E,OAAO,EAAE,wBAAwB,EAAE,yBAAqB;AAGxD;;;;GAIG;AACH,MAAM,UAAU,gCAAgC,CAC9C,OAA8B;IAE9B,MAAM,EAAE,YAAY,EAAE,gCAAgC,EAAE,GAAG,OAAO,CAAC;IAEnE,uDAAuD;IACvD,wEAAwE;IACxE,YAAY,EAAE,CAAC,SAAS,CACtB,mCAAmC,EAEnC,KAAK,EAAE,OAAO,EAAE,EAAE;QAChB,IACE,CAAC,wBAAwB,CAAC,OAAO,CAAC;YAClC,CAAC,gCAAgC,EAAE,CAAC,KAAK;iBACtC,kCAAkC,EACrC;YACA,OAAO;SACR;QAED,MAAM,gCAAgC,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAC3D,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import { saveInternalAccountToUserStorage } from './controller-integration';\nimport { canPerformAccountSyncing } from './sync-utils';\nimport type { AccountSyncingOptions } from './types';\n\n/**\n * Initialize and setup events to listen to for account syncing\n *\n * @param options - parameters used for initializing and enabling account syncing\n */\nexport function setupAccountSyncingSubscriptions(\n options: AccountSyncingOptions,\n) {\n const { getMessenger, getUserStorageControllerInstance } = options;\n\n // We don't listen to `AccountsController:accountAdded`\n // because it publishes `AccountsController:accountRenamed` in any case.\n getMessenger().subscribe(\n 'AccountsController:accountRenamed',\n\n async (account) => {\n if (\n !canPerformAccountSyncing(options) ||\n !getUserStorageControllerInstance().state\n .hasAccountSyncingSyncedAtLeastOnce\n ) {\n return;\n }\n\n await saveInternalAccountToUserStorage(account, options);\n },\n );\n}\n"]}
1
+ {"version":3,"file":"setup-subscriptions.mjs","sourceRoot":"","sources":["../../../../src/controllers/user-storage/account-syncing/setup-subscriptions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gCAAgC,EAAE,qCAAiC;AAC5E,OAAO,EAAE,wBAAwB,EAAE,yBAAqB;AAGxD;;;;GAIG;AACH,MAAM,UAAU,gCAAgC,CAC9C,OAA8B;IAE9B,MAAM,EAAE,YAAY,EAAE,gCAAgC,EAAE,GAAG,OAAO,CAAC;IAEnE,YAAY,EAAE,CAAC,SAAS,CACtB,iCAAiC,EAEjC,KAAK,EAAE,OAAO,EAAE,EAAE;QAChB,IACE,CAAC,wBAAwB,CAAC,OAAO,CAAC;YAClC,CAAC,gCAAgC,EAAE,CAAC,KAAK;iBACtC,kCAAkC,EACrC;YACA,OAAO;SACR;QAED,MAAM,EAAE,UAAU,EAAE,GAAG,gCAAgC,EAAE,CAAC;QAE1D,UAAU,CAAC,IAAI,CACb,KAAK,IAAI,EAAE,CAAC,MAAM,gCAAgC,CAAC,OAAO,EAAE,OAAO,CAAC,CACrE,CAAC;QACF,MAAM,UAAU,CAAC,GAAG,EAAE,CAAC;IACzB,CAAC,CACF,CAAC;IAEF,YAAY,EAAE,CAAC,SAAS,CACtB,mCAAmC,EAEnC,KAAK,EAAE,OAAO,EAAE,EAAE;QAChB,IACE,CAAC,wBAAwB,CAAC,OAAO,CAAC;YAClC,CAAC,gCAAgC,EAAE,CAAC,KAAK;iBACtC,kCAAkC,EACrC;YACA,OAAO;SACR;QAED,MAAM,EAAE,UAAU,EAAE,GAAG,gCAAgC,EAAE,CAAC;QAE1D,UAAU,CAAC,IAAI,CACb,KAAK,IAAI,EAAE,CAAC,MAAM,gCAAgC,CAAC,OAAO,EAAE,OAAO,CAAC,CACrE,CAAC;QACF,MAAM,UAAU,CAAC,GAAG,EAAE,CAAC;IACzB,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import { saveInternalAccountToUserStorage } from './controller-integration';\nimport { canPerformAccountSyncing } from './sync-utils';\nimport type { AccountSyncingOptions } from './types';\n\n/**\n * Initialize and setup events to listen to for account syncing\n *\n * @param options - parameters used for initializing and enabling account syncing\n */\nexport function setupAccountSyncingSubscriptions(\n options: AccountSyncingOptions,\n) {\n const { getMessenger, getUserStorageControllerInstance } = options;\n\n getMessenger().subscribe(\n 'AccountsController:accountAdded',\n\n async (account) => {\n if (\n !canPerformAccountSyncing(options) ||\n !getUserStorageControllerInstance().state\n .hasAccountSyncingSyncedAtLeastOnce\n ) {\n return;\n }\n\n const { eventQueue } = getUserStorageControllerInstance();\n\n eventQueue.push(\n async () => await saveInternalAccountToUserStorage(account, options),\n );\n await eventQueue.run();\n },\n );\n\n getMessenger().subscribe(\n 'AccountsController:accountRenamed',\n\n async (account) => {\n if (\n !canPerformAccountSyncing(options) ||\n !getUserStorageControllerInstance().state\n .hasAccountSyncingSyncedAtLeastOnce\n ) {\n return;\n }\n\n const { eventQueue } = getUserStorageControllerInstance();\n\n eventQueue.push(\n async () => await saveInternalAccountToUserStorage(account, options),\n );\n await eventQueue.run();\n },\n );\n}\n"]}
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EventQueue = void 0;
4
+ class EventQueue {
5
+ constructor() {
6
+ this.queue = [];
7
+ }
8
+ push(callback) {
9
+ this.queue.push(callback);
10
+ }
11
+ async run() {
12
+ while (this.queue.length > 0) {
13
+ const event = this.queue[0];
14
+ try {
15
+ await event();
16
+ }
17
+ finally {
18
+ this.queue = this.queue.filter((e) => e !== event);
19
+ }
20
+ }
21
+ }
22
+ }
23
+ exports.EventQueue = EventQueue;
24
+ //# sourceMappingURL=event-queue.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-queue.cjs","sourceRoot":"","sources":["../../../src/shared/utils/event-queue.ts"],"names":[],"mappings":";;;AAAA,MAAa,UAAU;IAAvB;QACE,UAAK,GAA4B,EAAE,CAAC;IAiBtC,CAAC;IAfQ,IAAI,CAAC,QAA6B;QACvC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IAC5B,CAAC;IAEM,KAAK,CAAC,GAAG;QACd,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE;YAC5B,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YAE5B,IAAI;gBACF,MAAM,KAAK,EAAE,CAAC;aACf;oBAAS;gBACR,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,KAAK,CAAC,CAAC;aACpD;SACF;IACH,CAAC;CACF;AAlBD,gCAkBC","sourcesContent":["export class EventQueue {\n queue: (() => Promise<void>)[] = [];\n\n public push(callback: () => Promise<void>) {\n this.queue.push(callback);\n }\n\n public async run() {\n while (this.queue.length > 0) {\n const event = this.queue[0];\n\n try {\n await event();\n } finally {\n this.queue = this.queue.filter((e) => e !== event);\n }\n }\n }\n}\n"]}
@@ -0,0 +1,6 @@
1
+ export declare class EventQueue {
2
+ queue: (() => Promise<void>)[];
3
+ push(callback: () => Promise<void>): void;
4
+ run(): Promise<void>;
5
+ }
6
+ //# sourceMappingURL=event-queue.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-queue.d.cts","sourceRoot":"","sources":["../../../src/shared/utils/event-queue.ts"],"names":[],"mappings":"AAAA,qBAAa,UAAU;IACrB,KAAK,EAAE,CAAC,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,EAAE,CAAM;IAE7B,IAAI,CAAC,QAAQ,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC;IAI5B,GAAG;CAWjB"}
@@ -0,0 +1,6 @@
1
+ export declare class EventQueue {
2
+ queue: (() => Promise<void>)[];
3
+ push(callback: () => Promise<void>): void;
4
+ run(): Promise<void>;
5
+ }
6
+ //# sourceMappingURL=event-queue.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-queue.d.mts","sourceRoot":"","sources":["../../../src/shared/utils/event-queue.ts"],"names":[],"mappings":"AAAA,qBAAa,UAAU;IACrB,KAAK,EAAE,CAAC,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,EAAE,CAAM;IAE7B,IAAI,CAAC,QAAQ,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC;IAI5B,GAAG;CAWjB"}
@@ -0,0 +1,20 @@
1
+ export class EventQueue {
2
+ constructor() {
3
+ this.queue = [];
4
+ }
5
+ push(callback) {
6
+ this.queue.push(callback);
7
+ }
8
+ async run() {
9
+ while (this.queue.length > 0) {
10
+ const event = this.queue[0];
11
+ try {
12
+ await event();
13
+ }
14
+ finally {
15
+ this.queue = this.queue.filter((e) => e !== event);
16
+ }
17
+ }
18
+ }
19
+ }
20
+ //# sourceMappingURL=event-queue.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-queue.mjs","sourceRoot":"","sources":["../../../src/shared/utils/event-queue.ts"],"names":[],"mappings":"AAAA,MAAM,OAAO,UAAU;IAAvB;QACE,UAAK,GAA4B,EAAE,CAAC;IAiBtC,CAAC;IAfQ,IAAI,CAAC,QAA6B;QACvC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IAC5B,CAAC;IAEM,KAAK,CAAC,GAAG;QACd,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE;YAC5B,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YAE5B,IAAI;gBACF,MAAM,KAAK,EAAE,CAAC;aACf;oBAAS;gBACR,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,KAAK,CAAC,CAAC;aACpD;SACF;IACH,CAAC;CACF","sourcesContent":["export class EventQueue {\n queue: (() => Promise<void>)[] = [];\n\n public push(callback: () => Promise<void>) {\n this.queue.push(callback);\n }\n\n public async run() {\n while (this.queue.length > 0) {\n const event = this.queue[0];\n\n try {\n await event();\n } finally {\n this.queue = this.queue.filter((e) => e !== event);\n }\n }\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/profile-sync-controller",
3
- "version": "17.0.0-preview-e11fb169",
3
+ "version": "17.1.0-preview-7dcef379",
4
4
  "description": "The profile sync helps developers synchronize data across multiple clients and devices in a privacy-preserving way. All data saved in the user storage database is encrypted client-side to preserve privacy. The user storage provides a modular design, giving developers the flexibility to construct and manage their storage spaces in a way that best suits their needs",
5
5
  "keywords": [
6
6
  "MetaMask",