@metamask/profile-sync-controller 0.9.7 → 0.9.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -1
- package/dist/controllers/user-storage/UserStorageController.cjs +16 -8
- package/dist/controllers/user-storage/UserStorageController.cjs.map +1 -1
- package/dist/controllers/user-storage/UserStorageController.d.cts +1 -0
- package/dist/controllers/user-storage/UserStorageController.d.cts.map +1 -1
- package/dist/controllers/user-storage/UserStorageController.d.mts +1 -0
- package/dist/controllers/user-storage/UserStorageController.d.mts.map +1 -1
- package/dist/controllers/user-storage/UserStorageController.mjs +16 -8
- package/dist/controllers/user-storage/UserStorageController.mjs.map +1 -1
- package/package.json +6 -5
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.9.8]
|
|
11
|
+
|
|
12
|
+
### Changed
|
|
13
|
+
|
|
14
|
+
- **BREAKING:** Bump `@metamask/network-controller` peer dependency to `^22.0.0` ([#4841](https://github.com/MetaMask/core/pull/4841))
|
|
15
|
+
|
|
16
|
+
### Fixed
|
|
17
|
+
|
|
18
|
+
- prevent multiple parallel account syncs by checking the value of `isAccountSyncingInProgress` before dispatching account syncing ([#4901](https://github.com/MetaMask/core/pull/4901))
|
|
19
|
+
|
|
10
20
|
## [0.9.7]
|
|
11
21
|
|
|
12
22
|
### Added
|
|
@@ -278,7 +288,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
278
288
|
|
|
279
289
|
- Initial release
|
|
280
290
|
|
|
281
|
-
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@0.9.
|
|
291
|
+
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@0.9.8...HEAD
|
|
292
|
+
[0.9.8]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@0.9.7...@metamask/profile-sync-controller@0.9.8
|
|
282
293
|
[0.9.7]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@0.9.6...@metamask/profile-sync-controller@0.9.7
|
|
283
294
|
[0.9.6]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@0.9.5...@metamask/profile-sync-controller@0.9.6
|
|
284
295
|
[0.9.5]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@0.9.4...@metamask/profile-sync-controller@0.9.5
|
|
@@ -73,14 +73,22 @@ class UserStorageController extends base_controller_1.BaseController {
|
|
|
73
73
|
});
|
|
74
74
|
_UserStorageController_accounts.set(this, {
|
|
75
75
|
// This is replaced with the actual value in the constructor
|
|
76
|
-
// We will remove this once the feature will be released
|
|
77
76
|
isAccountSyncingEnabled: false,
|
|
78
77
|
isAccountSyncingInProgress: false,
|
|
79
|
-
|
|
78
|
+
maxNumberOfAccountsToAdd: 0,
|
|
80
79
|
canSync: () => {
|
|
81
80
|
try {
|
|
82
81
|
__classPrivateFieldGet(this, _UserStorageController_instances, "m", _UserStorageController_assertProfileSyncingEnabled).call(this);
|
|
83
|
-
|
|
82
|
+
if (__classPrivateFieldGet(this, _UserStorageController_accounts, "f").isAccountSyncingInProgress) {
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
if (!__classPrivateFieldGet(this, _UserStorageController_accounts, "f").isAccountSyncingEnabled) {
|
|
86
|
+
return false;
|
|
87
|
+
}
|
|
88
|
+
if (!__classPrivateFieldGet(this, _UserStorageController_auth, "f").isAuthEnabled()) {
|
|
89
|
+
return false;
|
|
90
|
+
}
|
|
91
|
+
return true;
|
|
84
92
|
}
|
|
85
93
|
catch {
|
|
86
94
|
return false;
|
|
@@ -90,8 +98,7 @@ class UserStorageController extends base_controller_1.BaseController {
|
|
|
90
98
|
this.messagingSystem.subscribe('AccountsController:accountAdded',
|
|
91
99
|
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
|
92
100
|
async (account) => {
|
|
93
|
-
if (__classPrivateFieldGet(this, _UserStorageController_accounts, "f").
|
|
94
|
-
__classPrivateFieldGet(this, _UserStorageController_accounts, "f").addedAccountsCount += 1;
|
|
101
|
+
if (!__classPrivateFieldGet(this, _UserStorageController_accounts, "f").canSync()) {
|
|
95
102
|
return;
|
|
96
103
|
}
|
|
97
104
|
await this.saveInternalAccountToUserStorage(account);
|
|
@@ -99,7 +106,7 @@ class UserStorageController extends base_controller_1.BaseController {
|
|
|
99
106
|
this.messagingSystem.subscribe('AccountsController:accountRenamed',
|
|
100
107
|
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
|
101
108
|
async (account) => {
|
|
102
|
-
if (__classPrivateFieldGet(this, _UserStorageController_accounts, "f").
|
|
109
|
+
if (!__classPrivateFieldGet(this, _UserStorageController_accounts, "f").canSync()) {
|
|
103
110
|
return;
|
|
104
111
|
}
|
|
105
112
|
await this.saveInternalAccountToUserStorage(account);
|
|
@@ -161,6 +168,8 @@ class UserStorageController extends base_controller_1.BaseController {
|
|
|
161
168
|
_UserStorageController__snapSignMessageCache.set(this, {});
|
|
162
169
|
__classPrivateFieldSet(this, _UserStorageController_config, config, "f");
|
|
163
170
|
__classPrivateFieldGet(this, _UserStorageController_accounts, "f").isAccountSyncingEnabled = Boolean(env?.isAccountSyncingEnabled);
|
|
171
|
+
__classPrivateFieldGet(this, _UserStorageController_accounts, "f").maxNumberOfAccountsToAdd =
|
|
172
|
+
config?.accountSyncing?.maxNumberOfAccountsToAdd ?? 100;
|
|
164
173
|
this.getMetaMetricsState = getMetaMetricsState;
|
|
165
174
|
__classPrivateFieldGet(this, _UserStorageController_keyringController, "f").setupLockedStateSubscriptions();
|
|
166
175
|
__classPrivateFieldGet(this, _UserStorageController_instances, "m", _UserStorageController_registerMessageHandlers).call(this);
|
|
@@ -354,7 +363,6 @@ class UserStorageController extends base_controller_1.BaseController {
|
|
|
354
363
|
}
|
|
355
364
|
try {
|
|
356
365
|
__classPrivateFieldGet(this, _UserStorageController_accounts, "f").isAccountSyncingInProgress = true;
|
|
357
|
-
__classPrivateFieldGet(this, _UserStorageController_accounts, "f").addedAccountsCount = 0;
|
|
358
366
|
const profileId = await __classPrivateFieldGet(this, _UserStorageController_auth, "f").getProfileId();
|
|
359
367
|
const userStorageAccountsList = await __classPrivateFieldGet(this, _UserStorageController_accounts, "f").getUserStorageAccountsList();
|
|
360
368
|
if (!userStorageAccountsList || !userStorageAccountsList.length) {
|
|
@@ -373,7 +381,7 @@ class UserStorageController extends base_controller_1.BaseController {
|
|
|
373
381
|
// We don't want to remove existing accounts for a user
|
|
374
382
|
// so we only add new accounts if the user has more accounts than the internal accounts list
|
|
375
383
|
if (!hasMoreInternalAccountsThanUserStorageAccounts) {
|
|
376
|
-
const numberOfAccountsToAdd = userStorageAccountsList.length - internalAccountsList.length;
|
|
384
|
+
const numberOfAccountsToAdd = Math.min(userStorageAccountsList.length, __classPrivateFieldGet(this, _UserStorageController_accounts, "f").maxNumberOfAccountsToAdd) - internalAccountsList.length;
|
|
377
385
|
// Create new accounts to match the user storage accounts list
|
|
378
386
|
for (let i = 0; i < numberOfAccountsToAdd; i++) {
|
|
379
387
|
await this.messagingSystem.call('KeyringController:addNewAccount');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"UserStorageController.cjs","sourceRoot":"","sources":["../../../src/controllers/user-storage/UserStorageController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAYA,+DAA2D;AAC3D,uDAA+E;AAC/E,qEAMsC;AAItC,kEAA2D;AAO3D,iFAAoF;AASpF,8DAGiC;AACjC,yFAA+E;AAC/E,6CAOoB;AAoCpB,MAAM,cAAc,GAAG,uBAAuB,CAAC;AAclC,QAAA,YAAY,GAA+B;IACtD,uBAAuB,EAAE,IAAI;IAC7B,6BAA6B,EAAE,KAAK;CACrC,CAAC;AAEF,MAAM,QAAQ,GAA8C;IAC1D,uBAAuB,EAAE;QACvB,OAAO,EAAE,IAAI;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AC;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,CAAC,CACtC,CAAW,CAAC;IAEb,uBAAA,IAAI,oDAAuB,CAAC,OAAO,CAAC,GAAG,MAAM,CAAC;IAE9C,OAAO,MAAM,CAAC;AAChB,CAAC,6HAGC,6BAAsC;IAEtC,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,6BAA6B,GAAG,6BAA6B,CAAC;IACtE,CAAC,CAAC,CAAC;AACL,CAAC;kBArjBkB,qBAAqB","sourcesContent":["import type {\n AccountsControllerListAccountsAction,\n AccountsControllerUpdateAccountMetadataAction,\n AccountsControllerAccountRenamedEvent,\n AccountsControllerAccountAddedEvent,\n} from '@metamask/accounts-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedControllerMessenger,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport { type InternalAccount, isEvmAccountType } from '@metamask/keyring-api';\nimport {\n type KeyringControllerGetStateAction,\n type KeyringControllerLockEvent,\n type KeyringControllerUnlockEvent,\n type KeyringControllerAddNewAccountAction,\n KeyringTypes,\n} from '@metamask/keyring-controller';\nimport type { NetworkConfiguration } from '@metamask/network-controller';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\n\nimport { createSHA256Hash } from '../../shared/encryption';\nimport type {\n UserStoragePathWithFeatureAndKey,\n UserStoragePathWithFeatureOnly,\n UserStoragePathWithKeyOnly,\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 AuthenticationControllerPerformSignOut,\n} from '../authentication/AuthenticationController';\nimport type { UserStorageAccount } from './accounts/user-storage';\nimport {\n isNameDefaultAccountName,\n mapInternalAccountToUserStorageAccount,\n} from './accounts/user-storage';\nimport { startNetworkSyncing } from './network-syncing/controller-integration';\nimport {\n batchUpsertUserStorage,\n deleteUserStorage,\n deleteUserStorageAllFeatureEntries,\n getUserStorage,\n getUserStorageAllFeatureEntries,\n upsertUserStorage,\n} from './services';\n\n// TODO: add external NetworkController event\n// Need to listen for when a network gets added\ntype NetworkControllerNetworkAddedEvent = {\n type: 'NetworkController:networkAdded';\n payload: [networkConfiguration: NetworkConfiguration];\n};\n\n// TODO: add external NetworkController event\n// Need to listen for when a network is updated, or the default rpc/block explorer changes\ntype NetworkControllerNetworkChangedEvent = {\n type: 'NetworkController:networkChanged';\n payload: [networkConfiguration: NetworkConfiguration];\n};\n\n// TODO: add external NetworkController event\n// Need to listen for when a network gets deleted\ntype NetworkControllerNetworkDeletedEvent = {\n type: 'NetworkController:networkDeleted';\n payload: [networkConfiguration: NetworkConfiguration];\n};\n\n// TODO: fix external dependencies\nexport declare type NotificationServicesControllerDisableNotificationServices =\n {\n type: `NotificationServicesController:disableNotificationServices`;\n handler: () => Promise<void>;\n };\n\nexport declare type NotificationServicesControllerSelectIsNotificationServicesEnabled =\n {\n type: `NotificationServicesController:selectIsNotificationServicesEnabled`;\n handler: () => boolean;\n };\n\nconst controllerName = 'UserStorageController';\n\n// State\nexport type UserStorageControllerState = {\n /**\n * Condition used by UI and to determine if we can use some of the User Storage methods.\n */\n isProfileSyncingEnabled: boolean | null;\n /**\n * Loading state for the profile syncing update\n */\n isProfileSyncingUpdateLoading: boolean;\n};\n\nexport const defaultState: UserStorageControllerState = {\n isProfileSyncingEnabled: true,\n isProfileSyncingUpdateLoading: false,\n};\n\nconst metadata: StateMetadata<UserStorageControllerState> = {\n isProfileSyncingEnabled: {\n persist: true,\n anonymous: true,\n },\n isProfileSyncingUpdateLoading: {\n persist: false,\n anonymous: false,\n },\n};\n\ntype ControllerConfig = {\n accountSyncing?: {\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\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 | 'getStorageKey'\n | 'enableProfileSyncing'\n | 'disableProfileSyncing'\n | 'syncInternalAccountsWithUserStorage'\n | 'saveInternalAccountToUserStorage'\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 UserStorageControllerGetStorageKey = ActionsObj['getStorageKey'];\nexport type UserStorageControllerEnableProfileSyncing =\n ActionsObj['enableProfileSyncing'];\nexport type UserStorageControllerDisableProfileSyncing =\n ActionsObj['disableProfileSyncing'];\nexport type UserStorageControllerSyncInternalAccountsWithUserStorage =\n ActionsObj['syncInternalAccountsWithUserStorage'];\nexport type UserStorageControllerSaveInternalAccountToUserStorage =\n ActionsObj['saveInternalAccountToUserStorage'];\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 | AuthenticationControllerPerformSignOut\n // Metamask Notifications\n | NotificationServicesControllerDisableNotificationServices\n | NotificationServicesControllerSelectIsNotificationServicesEnabled\n // Account syncing\n | AccountsControllerListAccountsAction\n | AccountsControllerUpdateAccountMetadataAction\n | KeyringControllerAddNewAccountAction;\n\n// Messenger events\nexport type UserStorageControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n UserStorageControllerState\n>;\nexport type UserStorageControllerAccountSyncingInProgress = {\n type: `${typeof controllerName}:accountSyncingInProgress`;\n payload: [boolean];\n};\nexport type UserStorageControllerAccountSyncingComplete = {\n type: `${typeof controllerName}:accountSyncingComplete`;\n payload: [boolean];\n};\nexport type Events =\n | UserStorageControllerStateChangeEvent\n | UserStorageControllerAccountSyncingInProgress\n | UserStorageControllerAccountSyncingComplete;\n\nexport type AllowedEvents =\n | UserStorageControllerStateChangeEvent\n | UserStorageControllerAccountSyncingInProgress\n | UserStorageControllerAccountSyncingComplete\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent\n // Account Syncing Events\n | AccountsControllerAccountAddedEvent\n | AccountsControllerAccountRenamedEvent\n // Network Syncing Events\n | NetworkControllerNetworkAddedEvent\n | NetworkControllerNetworkChangedEvent\n | NetworkControllerNetworkDeletedEvent;\n\n// Messenger\nexport type UserStorageControllerMessenger = RestrictedControllerMessenger<\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 #auth = {\n getBearerToken: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:getBearerToken',\n );\n },\n getProfileId: async () => {\n const sessionProfile = await this.messagingSystem.call(\n 'AuthenticationController:getSessionProfile',\n );\n return sessionProfile?.profileId;\n },\n isAuthEnabled: () => {\n return this.messagingSystem.call('AuthenticationController:isSignedIn');\n },\n signIn: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:performSignIn',\n );\n },\n signOut: async () => {\n return this.messagingSystem.call(\n 'AuthenticationController:performSignOut',\n );\n },\n };\n\n #accounts = {\n // This is replaced with the actual value in the constructor\n // We will remove this once the feature will be released\n isAccountSyncingEnabled: false,\n isAccountSyncingInProgress: false,\n addedAccountsCount: 0,\n canSync: () => {\n try {\n this.#assertProfileSyncingEnabled();\n\n return (\n this.#accounts.isAccountSyncingEnabled && this.#auth.isAuthEnabled()\n );\n } catch {\n return false;\n }\n },\n setupAccountSyncingSubscriptions: () => {\n this.messagingSystem.subscribe(\n 'AccountsController:accountAdded',\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async (account) => {\n if (this.#accounts.isAccountSyncingInProgress) {\n this.#accounts.addedAccountsCount += 1;\n return;\n }\n\n await this.saveInternalAccountToUserStorage(account);\n },\n );\n\n this.messagingSystem.subscribe(\n 'AccountsController:accountRenamed',\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async (account) => {\n if (this.#accounts.isAccountSyncingInProgress) {\n return;\n }\n await this.saveInternalAccountToUserStorage(account);\n },\n );\n },\n doesInternalAccountHaveCorrectKeyringType: (account: InternalAccount) => {\n return account.metadata.keyring.type === KeyringTypes.hd;\n },\n getInternalAccountsList: async (): Promise<InternalAccount[]> => {\n // eslint-disable-next-line @typescript-eslint/await-thenable\n const internalAccountsList = await this.messagingSystem.call(\n 'AccountsController:listAccounts',\n );\n\n return internalAccountsList?.filter(\n this.#accounts.doesInternalAccountHaveCorrectKeyringType,\n );\n },\n getUserStorageAccountsList: async (): Promise<\n UserStorageAccount[] | null\n > => {\n const rawAccountsListResponse =\n await this.performGetStorageAllFeatureEntries('accounts');\n\n return (\n rawAccountsListResponse?.map((rawAccount) => JSON.parse(rawAccount)) ??\n null\n );\n },\n saveInternalAccountToUserStorage: async (\n internalAccount: InternalAccount,\n ) => {\n // Map the internal account to the user storage account schema\n const mappedAccount =\n mapInternalAccountToUserStorageAccount(internalAccount);\n\n await this.performSetStorage(\n `accounts.${internalAccount.address}`,\n JSON.stringify(mappedAccount),\n );\n },\n saveInternalAccountsListToUserStorage: async () => {\n const internalAccountsList =\n await this.#accounts.getInternalAccountsList();\n\n if (!internalAccountsList) {\n return;\n }\n\n const internalAccountsListFormattedForUserStorage =\n internalAccountsList.map(mapInternalAccountToUserStorageAccount);\n\n await this.performBatchSetStorage(\n 'accounts',\n internalAccountsListFormattedForUserStorage.map((account) => [\n account.a,\n JSON.stringify(account),\n ]),\n );\n },\n };\n\n #config?: ControllerConfig;\n\n #notificationServices = {\n disableNotificationServices: async () => {\n return await this.messagingSystem.call(\n 'NotificationServicesController:disableNotificationServices',\n );\n },\n selectIsNotificationServicesEnabled: async () => {\n return this.messagingSystem.call(\n 'NotificationServicesController:selectIsNotificationServicesEnabled',\n );\n },\n };\n\n #isUnlocked = false;\n\n #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 #nativeScryptCrypto: NativeScrypt | undefined = undefined;\n\n getMetaMetricsState: () => boolean;\n\n constructor({\n messenger,\n state,\n env,\n config,\n getMetaMetricsState,\n nativeScryptCrypto,\n }: {\n messenger: UserStorageControllerMessenger;\n state?: UserStorageControllerState;\n config?: ControllerConfig;\n env?: {\n isAccountSyncingEnabled?: boolean;\n isNetworkSyncingEnabled?: boolean;\n };\n getMetaMetricsState: () => boolean;\n nativeScryptCrypto?: NativeScrypt;\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n this.#config = config;\n\n this.#accounts.isAccountSyncingEnabled = Boolean(\n env?.isAccountSyncingEnabled,\n );\n\n this.getMetaMetricsState = getMetaMetricsState;\n this.#keyringController.setupLockedStateSubscriptions();\n this.#registerMessageHandlers();\n this.#nativeScryptCrypto = nativeScryptCrypto;\n this.#accounts.setupAccountSyncingSubscriptions();\n\n // Network Syncing\n if (env?.isNetworkSyncingEnabled) {\n startNetworkSyncing({\n messenger,\n getStorageConfig: async () => {\n const { storageKey, bearerToken } =\n await this.#getStorageKeyAndBearerToken();\n return {\n storageKey,\n bearerToken,\n nativeScryptCrypto: this.#nativeScryptCrypto,\n };\n },\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:getStorageKey',\n this.getStorageKey.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:enableProfileSyncing',\n this.enableProfileSyncing.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:disableProfileSyncing',\n this.disableProfileSyncing.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:syncInternalAccountsWithUserStorage',\n this.syncInternalAccountsWithUserStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:saveInternalAccountToUserStorage',\n this.saveInternalAccountToUserStorage.bind(this),\n );\n }\n\n public async enableProfileSyncing(): Promise<void> {\n try {\n this.#setIsProfileSyncingUpdateLoading(true);\n\n const authEnabled = this.#auth.isAuthEnabled();\n if (!authEnabled) {\n await this.#auth.signIn();\n }\n\n this.update((state) => {\n state.isProfileSyncingEnabled = true;\n });\n\n this.#setIsProfileSyncingUpdateLoading(false);\n } catch (e) {\n this.#setIsProfileSyncingUpdateLoading(false);\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to enable profile syncing - ${errorMessage}`,\n );\n }\n }\n\n public async setIsProfileSyncingEnabled(\n isProfileSyncingEnabled: boolean,\n ): Promise<void> {\n this.update((state) => {\n state.isProfileSyncingEnabled = isProfileSyncingEnabled;\n });\n }\n\n public async disableProfileSyncing(): Promise<void> {\n const isAlreadyDisabled = !this.state.isProfileSyncingEnabled;\n if (isAlreadyDisabled) {\n return;\n }\n\n try {\n this.#setIsProfileSyncingUpdateLoading(true);\n\n const isNotificationServicesEnabled =\n await this.#notificationServices.selectIsNotificationServicesEnabled();\n\n if (isNotificationServicesEnabled) {\n await this.#notificationServices.disableNotificationServices();\n }\n\n const isMetaMetricsParticipation = this.getMetaMetricsState();\n\n if (!isMetaMetricsParticipation) {\n await this.#auth.signOut();\n }\n\n this.#setIsProfileSyncingUpdateLoading(false);\n\n this.update((state) => {\n state.isProfileSyncingEnabled = false;\n });\n } catch (e) {\n this.#setIsProfileSyncingUpdateLoading(false);\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to disable profile syncing - ${errorMessage}`,\n );\n }\n }\n\n /**\n * Allows retrieval of stored data. Data stored is string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @returns the decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorage(\n path: UserStoragePathWithFeatureAndKey,\n ): Promise<string | null> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n const result = await getUserStorage({\n path,\n bearerToken,\n storageKey,\n nativeScryptCrypto: this.#nativeScryptCrypto,\n });\n\n return result;\n }\n\n /**\n * Allows retrieval of all stored data for a specific feature. Data stored is formatted as an array of strings.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @returns the array of decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorageAllFeatureEntries(\n path: UserStoragePathWithFeatureOnly,\n ): Promise<string[] | null> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n const result = await getUserStorageAllFeatureEntries({\n path,\n bearerToken,\n storageKey,\n nativeScryptCrypto: this.#nativeScryptCrypto,\n });\n\n return result;\n }\n\n /**\n * Allows storage of user data. Data stored must be string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param value - The string data you want to store.\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performSetStorage(\n path: UserStoragePathWithFeatureAndKey,\n value: string,\n ): Promise<void> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n await upsertUserStorage(value, {\n path,\n bearerToken,\n storageKey,\n nativeScryptCrypto: this.#nativeScryptCrypto,\n });\n }\n\n /**\n * Allows storage of multiple user data entries for one specific feature. Data stored must be string formatted.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @param values - data to store, in the form of an array of `[entryKey, entryValue]` pairs\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performBatchSetStorage(\n path: UserStoragePathWithFeatureOnly,\n values: [UserStoragePathWithKeyOnly, string][],\n ): Promise<void> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n await batchUpsertUserStorage(values, {\n path,\n bearerToken,\n storageKey,\n nativeScryptCrypto: this.#nativeScryptCrypto,\n });\n }\n\n /**\n * Allows deletion of user data. Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @returns nothing. NOTE that an error is thrown if fails to delete data.\n */\n public async performDeleteStorage(\n path: UserStoragePathWithFeatureAndKey,\n ): Promise<void> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n await deleteUserStorage({\n path,\n bearerToken,\n storageKey,\n });\n }\n\n /**\n * Allows deletion of all user data entries for a specific feature.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @returns nothing. NOTE that an error is thrown if fails to delete data.\n */\n public async performDeleteStorageAllFeatureEntries(\n path: UserStoragePathWithFeatureOnly,\n ): Promise<void> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n await deleteUserStorageAllFeatureEntries({\n path,\n bearerToken,\n storageKey,\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 this.#assertProfileSyncingEnabled();\n const storageKey = await this.#createStorageKey();\n return storageKey;\n }\n\n #assertProfileSyncingEnabled(): void {\n if (!this.state.isProfileSyncingEnabled) {\n throw new Error(\n `${controllerName}: Unable to call method, user is not authenticated`,\n );\n }\n }\n\n /**\n * Utility to get the bearer token and storage key\n */\n async #getStorageKeyAndBearerToken(): Promise<{\n bearerToken: string;\n storageKey: string;\n }> {\n const bearerToken = await this.#auth.getBearerToken();\n if (!bearerToken) {\n throw new Error('UserStorageController - unable to get bearer token');\n }\n const storageKey = await this.#createStorageKey();\n\n return { bearerToken, storageKey };\n }\n\n /**\n * Rather than storing the storage key, we can compute the storage key when needed.\n *\n * @returns the storage key\n */\n async #createStorageKey(): Promise<string> {\n const id: string = await this.#auth.getProfileId();\n if (!id) {\n throw new Error('UserStorageController - unable to create storage key');\n }\n\n const storageKeySignature = await this.#snapSignMessage(`metamask:${id}`);\n const storageKey = createSHA256Hash(storageKeySignature);\n return storageKey;\n }\n\n #_snapSignMessageCache: Record<`metamask:${string}`, string> = {};\n\n /**\n * Signs a specific message using an underlying auth snap.\n *\n * @param message - A specific tagged message to sign.\n * @returns A Signature created by the snap.\n */\n async #snapSignMessage(message: `metamask:${string}`): Promise<string> {\n if (this.#_snapSignMessageCache[message]) {\n return this.#_snapSignMessageCache[message];\n }\n\n if (!this.#isUnlocked) {\n throw new Error(\n '#snapSignMessage - unable to call snap, wallet is locked',\n );\n }\n\n const result = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n createSnapSignMessageRequest(message),\n )) as string;\n\n this.#_snapSignMessageCache[message] = result;\n\n return result;\n }\n\n #setIsProfileSyncingUpdateLoading(\n isProfileSyncingUpdateLoading: boolean,\n ): void {\n this.update((state) => {\n state.isProfileSyncingUpdateLoading = isProfileSyncingUpdateLoading;\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 if (!this.#accounts.canSync()) {\n return;\n }\n\n try {\n this.#accounts.isAccountSyncingInProgress = true;\n this.#accounts.addedAccountsCount = 0;\n\n const profileId = await this.#auth.getProfileId();\n\n const userStorageAccountsList =\n await this.#accounts.getUserStorageAccountsList();\n\n if (!userStorageAccountsList || !userStorageAccountsList.length) {\n await this.#accounts.saveInternalAccountsListToUserStorage();\n return;\n }\n\n // Prepare an array of internal accounts to be saved to the user storage\n const internalAccountsToBeSavedToUserStorage: InternalAccount[] = [];\n\n // Compare internal accounts list with user storage accounts list\n // First step: compare lengths\n let internalAccountsList = await this.#accounts.getInternalAccountsList();\n\n if (!internalAccountsList || !internalAccountsList.length) {\n throw new Error(`Failed to get internal accounts list`);\n }\n\n const hasMoreInternalAccountsThanUserStorageAccounts =\n internalAccountsList.length > userStorageAccountsList.length;\n\n // We don't want to remove existing accounts for a user\n // so we only add new accounts if the user has more accounts than the internal accounts list\n if (!hasMoreInternalAccountsThanUserStorageAccounts) {\n const numberOfAccountsToAdd =\n userStorageAccountsList.length - internalAccountsList.length;\n\n // Create new accounts to match the user storage accounts list\n\n for (let i = 0; i < numberOfAccountsToAdd; i++) {\n await this.messagingSystem.call('KeyringController:addNewAccount');\n\n this.#config?.accountSyncing?.onAccountAdded?.(profileId);\n }\n }\n\n // Second step: compare account names\n // Get the internal accounts list again since new accounts might have been added in the previous step\n internalAccountsList = await this.#accounts.getInternalAccountsList();\n\n for (const internalAccount of internalAccountsList) {\n const userStorageAccount = userStorageAccountsList.find(\n (account) => account.a === internalAccount.address,\n );\n\n if (!userStorageAccount) {\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n\n // One or both accounts have default names\n const isInternalAccountNameDefault = isNameDefaultAccountName(\n internalAccount.metadata.name,\n );\n const isUserStorageAccountNameDefault = isNameDefaultAccountName(\n userStorageAccount.n,\n );\n\n // Internal account has default name\n if (isInternalAccountNameDefault) {\n if (!isUserStorageAccountNameDefault) {\n this.messagingSystem.call(\n 'AccountsController:updateAccountMetadata',\n internalAccount.id,\n {\n name: userStorageAccount.n,\n },\n );\n\n this.#config?.accountSyncing?.onAccountNameUpdated?.(profileId);\n }\n continue;\n }\n\n // Internal account has custom name but user storage account has default name\n if (isUserStorageAccountNameDefault) {\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n\n // Both accounts have custom names\n\n // User storage account has a nameLastUpdatedAt timestamp\n // Note: not storing the undefined checks in constants to act as a type guard\n if (userStorageAccount.nlu !== undefined) {\n if (internalAccount.metadata.nameLastUpdatedAt !== undefined) {\n const isInternalAccountNameNewer =\n internalAccount.metadata.nameLastUpdatedAt >\n userStorageAccount.nlu;\n\n if (isInternalAccountNameNewer) {\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n }\n\n this.messagingSystem.call(\n 'AccountsController:updateAccountMetadata',\n internalAccount.id,\n {\n name: userStorageAccount.n,\n nameLastUpdatedAt: userStorageAccount.nlu,\n },\n );\n\n const areInternalAndUserStorageAccountNamesEqual =\n internalAccount.metadata.name === userStorageAccount.n;\n\n if (!areInternalAndUserStorageAccountNamesEqual) {\n this.#config?.accountSyncing?.onAccountNameUpdated?.(profileId);\n }\n\n continue;\n } else if (internalAccount.metadata.nameLastUpdatedAt !== undefined) {\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n }\n\n // Save the internal accounts list to the user storage\n await this.performBatchSetStorage(\n 'accounts',\n internalAccountsToBeSavedToUserStorage.map((account) => [\n account.address,\n JSON.stringify(mapInternalAccountToUserStorageAccount(account)),\n ]),\n );\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to sync user storage accounts list - ${errorMessage}`,\n );\n } finally {\n this.#accounts.isAccountSyncingInProgress = false;\n }\n }\n\n /**\n * Saves an individual internal account to the user storage.\n * @param internalAccount - The internal account to save\n */\n async saveInternalAccountToUserStorage(\n internalAccount: InternalAccount,\n ): Promise<void> {\n if (\n !this.#accounts.canSync() ||\n !isEvmAccountType(internalAccount.type) ||\n !this.#accounts.doesInternalAccountHaveCorrectKeyringType(internalAccount)\n ) {\n return;\n }\n\n try {\n await this.#accounts.saveInternalAccountToUserStorage(internalAccount);\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to save account to user storage - ${errorMessage}`,\n );\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"UserStorageController.cjs","sourceRoot":"","sources":["../../../src/controllers/user-storage/UserStorageController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAYA,+DAA2D;AAC3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CAAC;AAED;;;;GAIG;AACH,KAAK;IACH,MAAM,EAAE,GAAW,MAAM,uBAAA,IAAI,mCAAM,CAAC,YAAY,EAAE,CAAC;IACnD,IAAI,CAAC,EAAE,EAAE;QACP,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;KACzE;IAED,MAAM,mBAAmB,GAAG,MAAM,uBAAA,IAAI,gFAAiB,MAArB,IAAI,EAAkB,YAAY,EAAE,EAAE,CAAC,CAAC;IAC1E,MAAM,UAAU,GAAG,IAAA,6BAAgB,EAAC,mBAAmB,CAAC,CAAC;IACzD,OAAO,UAAU,CAAC;AACpB,CAAC;AAID;;;;;GAKG;AACH,KAAK,iDAAkB,OAA6B;IAClD,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,CAAC,CACtC,CAAW,CAAC;IAEb,uBAAA,IAAI,oDAAuB,CAAC,OAAO,CAAC,GAAG,MAAM,CAAC;IAE9C,OAAO,MAAM,CAAC;AAChB,CAAC,6HAGC,6BAAsC;IAEtC,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,6BAA6B,GAAG,6BAA6B,CAAC;IACtE,CAAC,CAAC,CAAC;AACL,CAAC;kBAhkBkB,qBAAqB","sourcesContent":["import type {\n AccountsControllerListAccountsAction,\n AccountsControllerUpdateAccountMetadataAction,\n AccountsControllerAccountRenamedEvent,\n AccountsControllerAccountAddedEvent,\n} from '@metamask/accounts-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedControllerMessenger,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport { type InternalAccount, isEvmAccountType } from '@metamask/keyring-api';\nimport {\n type KeyringControllerGetStateAction,\n type KeyringControllerLockEvent,\n type KeyringControllerUnlockEvent,\n type KeyringControllerAddNewAccountAction,\n KeyringTypes,\n} from '@metamask/keyring-controller';\nimport type { NetworkConfiguration } from '@metamask/network-controller';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\n\nimport { createSHA256Hash } from '../../shared/encryption';\nimport type {\n UserStoragePathWithFeatureAndKey,\n UserStoragePathWithFeatureOnly,\n UserStoragePathWithKeyOnly,\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 AuthenticationControllerPerformSignOut,\n} from '../authentication/AuthenticationController';\nimport type { UserStorageAccount } from './accounts/user-storage';\nimport {\n isNameDefaultAccountName,\n mapInternalAccountToUserStorageAccount,\n} from './accounts/user-storage';\nimport { startNetworkSyncing } from './network-syncing/controller-integration';\nimport {\n batchUpsertUserStorage,\n deleteUserStorage,\n deleteUserStorageAllFeatureEntries,\n getUserStorage,\n getUserStorageAllFeatureEntries,\n upsertUserStorage,\n} from './services';\n\n// TODO: add external NetworkController event\n// Need to listen for when a network gets added\ntype NetworkControllerNetworkAddedEvent = {\n type: 'NetworkController:networkAdded';\n payload: [networkConfiguration: NetworkConfiguration];\n};\n\n// TODO: add external NetworkController event\n// Need to listen for when a network is updated, or the default rpc/block explorer changes\ntype NetworkControllerNetworkChangedEvent = {\n type: 'NetworkController:networkChanged';\n payload: [networkConfiguration: NetworkConfiguration];\n};\n\n// TODO: add external NetworkController event\n// Need to listen for when a network gets deleted\ntype NetworkControllerNetworkDeletedEvent = {\n type: 'NetworkController:networkDeleted';\n payload: [networkConfiguration: NetworkConfiguration];\n};\n\n// TODO: fix external dependencies\nexport declare type NotificationServicesControllerDisableNotificationServices =\n {\n type: `NotificationServicesController:disableNotificationServices`;\n handler: () => Promise<void>;\n };\n\nexport declare type NotificationServicesControllerSelectIsNotificationServicesEnabled =\n {\n type: `NotificationServicesController:selectIsNotificationServicesEnabled`;\n handler: () => boolean;\n };\n\nconst controllerName = 'UserStorageController';\n\n// State\nexport type UserStorageControllerState = {\n /**\n * Condition used by UI and to determine if we can use some of the User Storage methods.\n */\n isProfileSyncingEnabled: boolean | null;\n /**\n * Loading state for the profile syncing update\n */\n isProfileSyncingUpdateLoading: boolean;\n};\n\nexport const defaultState: UserStorageControllerState = {\n isProfileSyncingEnabled: true,\n isProfileSyncingUpdateLoading: false,\n};\n\nconst metadata: StateMetadata<UserStorageControllerState> = {\n isProfileSyncingEnabled: {\n persist: true,\n anonymous: true,\n },\n isProfileSyncingUpdateLoading: {\n persist: false,\n anonymous: false,\n },\n};\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\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 | 'getStorageKey'\n | 'enableProfileSyncing'\n | 'disableProfileSyncing'\n | 'syncInternalAccountsWithUserStorage'\n | 'saveInternalAccountToUserStorage'\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 UserStorageControllerGetStorageKey = ActionsObj['getStorageKey'];\nexport type UserStorageControllerEnableProfileSyncing =\n ActionsObj['enableProfileSyncing'];\nexport type UserStorageControllerDisableProfileSyncing =\n ActionsObj['disableProfileSyncing'];\nexport type UserStorageControllerSyncInternalAccountsWithUserStorage =\n ActionsObj['syncInternalAccountsWithUserStorage'];\nexport type UserStorageControllerSaveInternalAccountToUserStorage =\n ActionsObj['saveInternalAccountToUserStorage'];\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 | AuthenticationControllerPerformSignOut\n // Metamask Notifications\n | NotificationServicesControllerDisableNotificationServices\n | NotificationServicesControllerSelectIsNotificationServicesEnabled\n // Account syncing\n | AccountsControllerListAccountsAction\n | AccountsControllerUpdateAccountMetadataAction\n | KeyringControllerAddNewAccountAction;\n\n// Messenger events\nexport type UserStorageControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n UserStorageControllerState\n>;\nexport type UserStorageControllerAccountSyncingInProgress = {\n type: `${typeof controllerName}:accountSyncingInProgress`;\n payload: [boolean];\n};\nexport type UserStorageControllerAccountSyncingComplete = {\n type: `${typeof controllerName}:accountSyncingComplete`;\n payload: [boolean];\n};\nexport type Events =\n | UserStorageControllerStateChangeEvent\n | UserStorageControllerAccountSyncingInProgress\n | UserStorageControllerAccountSyncingComplete;\n\nexport type AllowedEvents =\n | UserStorageControllerStateChangeEvent\n | UserStorageControllerAccountSyncingInProgress\n | UserStorageControllerAccountSyncingComplete\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent\n // Account Syncing Events\n | AccountsControllerAccountAddedEvent\n | AccountsControllerAccountRenamedEvent\n // Network Syncing Events\n | NetworkControllerNetworkAddedEvent\n | NetworkControllerNetworkChangedEvent\n | NetworkControllerNetworkDeletedEvent;\n\n// Messenger\nexport type UserStorageControllerMessenger = RestrictedControllerMessenger<\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 #auth = {\n getBearerToken: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:getBearerToken',\n );\n },\n getProfileId: async () => {\n const sessionProfile = await this.messagingSystem.call(\n 'AuthenticationController:getSessionProfile',\n );\n return sessionProfile?.profileId;\n },\n isAuthEnabled: () => {\n return this.messagingSystem.call('AuthenticationController:isSignedIn');\n },\n signIn: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:performSignIn',\n );\n },\n signOut: async () => {\n return this.messagingSystem.call(\n 'AuthenticationController:performSignOut',\n );\n },\n };\n\n #accounts = {\n // This is replaced with the actual value in the constructor\n isAccountSyncingEnabled: false,\n isAccountSyncingInProgress: false,\n maxNumberOfAccountsToAdd: 0,\n canSync: () => {\n try {\n this.#assertProfileSyncingEnabled();\n\n if (this.#accounts.isAccountSyncingInProgress) {\n return false;\n }\n\n if (!this.#accounts.isAccountSyncingEnabled) {\n return false;\n }\n\n if (!this.#auth.isAuthEnabled()) {\n return false;\n }\n\n return true;\n } catch {\n return false;\n }\n },\n setupAccountSyncingSubscriptions: () => {\n this.messagingSystem.subscribe(\n 'AccountsController:accountAdded',\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async (account) => {\n if (!this.#accounts.canSync()) {\n return;\n }\n\n await this.saveInternalAccountToUserStorage(account);\n },\n );\n\n this.messagingSystem.subscribe(\n 'AccountsController:accountRenamed',\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async (account) => {\n if (!this.#accounts.canSync()) {\n return;\n }\n await this.saveInternalAccountToUserStorage(account);\n },\n );\n },\n doesInternalAccountHaveCorrectKeyringType: (account: InternalAccount) => {\n return account.metadata.keyring.type === KeyringTypes.hd;\n },\n getInternalAccountsList: async (): Promise<InternalAccount[]> => {\n // eslint-disable-next-line @typescript-eslint/await-thenable\n const internalAccountsList = await this.messagingSystem.call(\n 'AccountsController:listAccounts',\n );\n\n return internalAccountsList?.filter(\n this.#accounts.doesInternalAccountHaveCorrectKeyringType,\n );\n },\n getUserStorageAccountsList: async (): Promise<\n UserStorageAccount[] | null\n > => {\n const rawAccountsListResponse =\n await this.performGetStorageAllFeatureEntries('accounts');\n\n return (\n rawAccountsListResponse?.map((rawAccount) => JSON.parse(rawAccount)) ??\n null\n );\n },\n saveInternalAccountToUserStorage: async (\n internalAccount: InternalAccount,\n ) => {\n // Map the internal account to the user storage account schema\n const mappedAccount =\n mapInternalAccountToUserStorageAccount(internalAccount);\n\n await this.performSetStorage(\n `accounts.${internalAccount.address}`,\n JSON.stringify(mappedAccount),\n );\n },\n saveInternalAccountsListToUserStorage: async () => {\n const internalAccountsList =\n await this.#accounts.getInternalAccountsList();\n\n if (!internalAccountsList) {\n return;\n }\n\n const internalAccountsListFormattedForUserStorage =\n internalAccountsList.map(mapInternalAccountToUserStorageAccount);\n\n await this.performBatchSetStorage(\n 'accounts',\n internalAccountsListFormattedForUserStorage.map((account) => [\n account.a,\n JSON.stringify(account),\n ]),\n );\n },\n };\n\n #config?: ControllerConfig;\n\n #notificationServices = {\n disableNotificationServices: async () => {\n return await this.messagingSystem.call(\n 'NotificationServicesController:disableNotificationServices',\n );\n },\n selectIsNotificationServicesEnabled: async () => {\n return this.messagingSystem.call(\n 'NotificationServicesController:selectIsNotificationServicesEnabled',\n );\n },\n };\n\n #isUnlocked = false;\n\n #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 #nativeScryptCrypto: NativeScrypt | undefined = undefined;\n\n getMetaMetricsState: () => boolean;\n\n constructor({\n messenger,\n state,\n env,\n config,\n getMetaMetricsState,\n nativeScryptCrypto,\n }: {\n messenger: UserStorageControllerMessenger;\n state?: UserStorageControllerState;\n config?: ControllerConfig;\n env?: {\n isAccountSyncingEnabled?: boolean;\n isNetworkSyncingEnabled?: boolean;\n };\n getMetaMetricsState: () => boolean;\n nativeScryptCrypto?: NativeScrypt;\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n this.#config = config;\n\n this.#accounts.isAccountSyncingEnabled = Boolean(\n env?.isAccountSyncingEnabled,\n );\n\n this.#accounts.maxNumberOfAccountsToAdd =\n config?.accountSyncing?.maxNumberOfAccountsToAdd ?? 100;\n\n this.getMetaMetricsState = getMetaMetricsState;\n this.#keyringController.setupLockedStateSubscriptions();\n this.#registerMessageHandlers();\n this.#nativeScryptCrypto = nativeScryptCrypto;\n this.#accounts.setupAccountSyncingSubscriptions();\n\n // Network Syncing\n if (env?.isNetworkSyncingEnabled) {\n startNetworkSyncing({\n messenger,\n getStorageConfig: async () => {\n const { storageKey, bearerToken } =\n await this.#getStorageKeyAndBearerToken();\n return {\n storageKey,\n bearerToken,\n nativeScryptCrypto: this.#nativeScryptCrypto,\n };\n },\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:getStorageKey',\n this.getStorageKey.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:enableProfileSyncing',\n this.enableProfileSyncing.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:disableProfileSyncing',\n this.disableProfileSyncing.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:syncInternalAccountsWithUserStorage',\n this.syncInternalAccountsWithUserStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:saveInternalAccountToUserStorage',\n this.saveInternalAccountToUserStorage.bind(this),\n );\n }\n\n public async enableProfileSyncing(): Promise<void> {\n try {\n this.#setIsProfileSyncingUpdateLoading(true);\n\n const authEnabled = this.#auth.isAuthEnabled();\n if (!authEnabled) {\n await this.#auth.signIn();\n }\n\n this.update((state) => {\n state.isProfileSyncingEnabled = true;\n });\n\n this.#setIsProfileSyncingUpdateLoading(false);\n } catch (e) {\n this.#setIsProfileSyncingUpdateLoading(false);\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to enable profile syncing - ${errorMessage}`,\n );\n }\n }\n\n public async setIsProfileSyncingEnabled(\n isProfileSyncingEnabled: boolean,\n ): Promise<void> {\n this.update((state) => {\n state.isProfileSyncingEnabled = isProfileSyncingEnabled;\n });\n }\n\n public async disableProfileSyncing(): Promise<void> {\n const isAlreadyDisabled = !this.state.isProfileSyncingEnabled;\n if (isAlreadyDisabled) {\n return;\n }\n\n try {\n this.#setIsProfileSyncingUpdateLoading(true);\n\n const isNotificationServicesEnabled =\n await this.#notificationServices.selectIsNotificationServicesEnabled();\n\n if (isNotificationServicesEnabled) {\n await this.#notificationServices.disableNotificationServices();\n }\n\n const isMetaMetricsParticipation = this.getMetaMetricsState();\n\n if (!isMetaMetricsParticipation) {\n await this.#auth.signOut();\n }\n\n this.#setIsProfileSyncingUpdateLoading(false);\n\n this.update((state) => {\n state.isProfileSyncingEnabled = false;\n });\n } catch (e) {\n this.#setIsProfileSyncingUpdateLoading(false);\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to disable profile syncing - ${errorMessage}`,\n );\n }\n }\n\n /**\n * Allows retrieval of stored data. Data stored is string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @returns the decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorage(\n path: UserStoragePathWithFeatureAndKey,\n ): Promise<string | null> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n const result = await getUserStorage({\n path,\n bearerToken,\n storageKey,\n nativeScryptCrypto: this.#nativeScryptCrypto,\n });\n\n return result;\n }\n\n /**\n * Allows retrieval of all stored data for a specific feature. Data stored is formatted as an array of strings.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @returns the array of decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorageAllFeatureEntries(\n path: UserStoragePathWithFeatureOnly,\n ): Promise<string[] | null> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n const result = await getUserStorageAllFeatureEntries({\n path,\n bearerToken,\n storageKey,\n nativeScryptCrypto: this.#nativeScryptCrypto,\n });\n\n return result;\n }\n\n /**\n * Allows storage of user data. Data stored must be string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param value - The string data you want to store.\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performSetStorage(\n path: UserStoragePathWithFeatureAndKey,\n value: string,\n ): Promise<void> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n await upsertUserStorage(value, {\n path,\n bearerToken,\n storageKey,\n nativeScryptCrypto: this.#nativeScryptCrypto,\n });\n }\n\n /**\n * Allows storage of multiple user data entries for one specific feature. Data stored must be string formatted.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @param values - data to store, in the form of an array of `[entryKey, entryValue]` pairs\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performBatchSetStorage(\n path: UserStoragePathWithFeatureOnly,\n values: [UserStoragePathWithKeyOnly, string][],\n ): Promise<void> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n await batchUpsertUserStorage(values, {\n path,\n bearerToken,\n storageKey,\n nativeScryptCrypto: this.#nativeScryptCrypto,\n });\n }\n\n /**\n * Allows deletion of user data. Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @returns nothing. NOTE that an error is thrown if fails to delete data.\n */\n public async performDeleteStorage(\n path: UserStoragePathWithFeatureAndKey,\n ): Promise<void> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n await deleteUserStorage({\n path,\n bearerToken,\n storageKey,\n });\n }\n\n /**\n * Allows deletion of all user data entries for a specific feature.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @returns nothing. NOTE that an error is thrown if fails to delete data.\n */\n public async performDeleteStorageAllFeatureEntries(\n path: UserStoragePathWithFeatureOnly,\n ): Promise<void> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n await deleteUserStorageAllFeatureEntries({\n path,\n bearerToken,\n storageKey,\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 this.#assertProfileSyncingEnabled();\n const storageKey = await this.#createStorageKey();\n return storageKey;\n }\n\n #assertProfileSyncingEnabled(): void {\n if (!this.state.isProfileSyncingEnabled) {\n throw new Error(\n `${controllerName}: Unable to call method, user is not authenticated`,\n );\n }\n }\n\n /**\n * Utility to get the bearer token and storage key\n */\n async #getStorageKeyAndBearerToken(): Promise<{\n bearerToken: string;\n storageKey: string;\n }> {\n const bearerToken = await this.#auth.getBearerToken();\n if (!bearerToken) {\n throw new Error('UserStorageController - unable to get bearer token');\n }\n const storageKey = await this.#createStorageKey();\n\n return { bearerToken, storageKey };\n }\n\n /**\n * Rather than storing the storage key, we can compute the storage key when needed.\n *\n * @returns the storage key\n */\n async #createStorageKey(): Promise<string> {\n const id: string = await this.#auth.getProfileId();\n if (!id) {\n throw new Error('UserStorageController - unable to create storage key');\n }\n\n const storageKeySignature = await this.#snapSignMessage(`metamask:${id}`);\n const storageKey = createSHA256Hash(storageKeySignature);\n return storageKey;\n }\n\n #_snapSignMessageCache: Record<`metamask:${string}`, string> = {};\n\n /**\n * Signs a specific message using an underlying auth snap.\n *\n * @param message - A specific tagged message to sign.\n * @returns A Signature created by the snap.\n */\n async #snapSignMessage(message: `metamask:${string}`): Promise<string> {\n if (this.#_snapSignMessageCache[message]) {\n return this.#_snapSignMessageCache[message];\n }\n\n if (!this.#isUnlocked) {\n throw new Error(\n '#snapSignMessage - unable to call snap, wallet is locked',\n );\n }\n\n const result = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n createSnapSignMessageRequest(message),\n )) as string;\n\n this.#_snapSignMessageCache[message] = result;\n\n return result;\n }\n\n #setIsProfileSyncingUpdateLoading(\n isProfileSyncingUpdateLoading: boolean,\n ): void {\n this.update((state) => {\n state.isProfileSyncingUpdateLoading = isProfileSyncingUpdateLoading;\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 if (!this.#accounts.canSync()) {\n return;\n }\n\n try {\n this.#accounts.isAccountSyncingInProgress = true;\n\n const profileId = await this.#auth.getProfileId();\n\n const userStorageAccountsList =\n await this.#accounts.getUserStorageAccountsList();\n\n if (!userStorageAccountsList || !userStorageAccountsList.length) {\n await this.#accounts.saveInternalAccountsListToUserStorage();\n return;\n }\n\n // Prepare an array of internal accounts to be saved to the user storage\n const internalAccountsToBeSavedToUserStorage: InternalAccount[] = [];\n\n // Compare internal accounts list with user storage accounts list\n // First step: compare lengths\n let internalAccountsList = await this.#accounts.getInternalAccountsList();\n\n if (!internalAccountsList || !internalAccountsList.length) {\n throw new Error(`Failed to get internal accounts list`);\n }\n\n const hasMoreInternalAccountsThanUserStorageAccounts =\n internalAccountsList.length > userStorageAccountsList.length;\n\n // We don't want to remove existing accounts for a user\n // so we only add new accounts if the user has more accounts than the internal accounts list\n if (!hasMoreInternalAccountsThanUserStorageAccounts) {\n const numberOfAccountsToAdd =\n Math.min(\n userStorageAccountsList.length,\n this.#accounts.maxNumberOfAccountsToAdd,\n ) - internalAccountsList.length;\n\n // Create new accounts to match the user storage accounts list\n\n for (let i = 0; i < numberOfAccountsToAdd; i++) {\n await this.messagingSystem.call('KeyringController:addNewAccount');\n\n this.#config?.accountSyncing?.onAccountAdded?.(profileId);\n }\n }\n\n // Second step: compare account names\n // Get the internal accounts list again since new accounts might have been added in the previous step\n internalAccountsList = await this.#accounts.getInternalAccountsList();\n\n for (const internalAccount of internalAccountsList) {\n const userStorageAccount = userStorageAccountsList.find(\n (account) => account.a === internalAccount.address,\n );\n\n if (!userStorageAccount) {\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n\n // One or both accounts have default names\n const isInternalAccountNameDefault = isNameDefaultAccountName(\n internalAccount.metadata.name,\n );\n const isUserStorageAccountNameDefault = isNameDefaultAccountName(\n userStorageAccount.n,\n );\n\n // Internal account has default name\n if (isInternalAccountNameDefault) {\n if (!isUserStorageAccountNameDefault) {\n this.messagingSystem.call(\n 'AccountsController:updateAccountMetadata',\n internalAccount.id,\n {\n name: userStorageAccount.n,\n },\n );\n\n this.#config?.accountSyncing?.onAccountNameUpdated?.(profileId);\n }\n continue;\n }\n\n // Internal account has custom name but user storage account has default name\n if (isUserStorageAccountNameDefault) {\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n\n // Both accounts have custom names\n\n // User storage account has a nameLastUpdatedAt timestamp\n // Note: not storing the undefined checks in constants to act as a type guard\n if (userStorageAccount.nlu !== undefined) {\n if (internalAccount.metadata.nameLastUpdatedAt !== undefined) {\n const isInternalAccountNameNewer =\n internalAccount.metadata.nameLastUpdatedAt >\n userStorageAccount.nlu;\n\n if (isInternalAccountNameNewer) {\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n }\n\n this.messagingSystem.call(\n 'AccountsController:updateAccountMetadata',\n internalAccount.id,\n {\n name: userStorageAccount.n,\n nameLastUpdatedAt: userStorageAccount.nlu,\n },\n );\n\n const areInternalAndUserStorageAccountNamesEqual =\n internalAccount.metadata.name === userStorageAccount.n;\n\n if (!areInternalAndUserStorageAccountNamesEqual) {\n this.#config?.accountSyncing?.onAccountNameUpdated?.(profileId);\n }\n\n continue;\n } else if (internalAccount.metadata.nameLastUpdatedAt !== undefined) {\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n }\n\n // Save the internal accounts list to the user storage\n await this.performBatchSetStorage(\n 'accounts',\n internalAccountsToBeSavedToUserStorage.map((account) => [\n account.address,\n JSON.stringify(mapInternalAccountToUserStorageAccount(account)),\n ]),\n );\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to sync user storage accounts list - ${errorMessage}`,\n );\n } finally {\n this.#accounts.isAccountSyncingInProgress = false;\n }\n }\n\n /**\n * Saves an individual internal account to the user storage.\n * @param internalAccount - The internal account to save\n */\n async saveInternalAccountToUserStorage(\n internalAccount: InternalAccount,\n ): Promise<void> {\n if (\n !this.#accounts.canSync() ||\n !isEvmAccountType(internalAccount.type) ||\n !this.#accounts.doesInternalAccountHaveCorrectKeyringType(internalAccount)\n ) {\n return;\n }\n\n try {\n await this.#accounts.saveInternalAccountToUserStorage(internalAccount);\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to save account to user storage - ${errorMessage}`,\n );\n }\n }\n}\n"]}
|
|
@@ -42,6 +42,7 @@ export type UserStorageControllerState = {
|
|
|
42
42
|
export declare const defaultState: UserStorageControllerState;
|
|
43
43
|
type ControllerConfig = {
|
|
44
44
|
accountSyncing?: {
|
|
45
|
+
maxNumberOfAccountsToAdd?: number;
|
|
45
46
|
/**
|
|
46
47
|
* Callback that fires when account sync adds an account.
|
|
47
48
|
* This is used for analytics.
|
|
@@ -1 +1 @@
|
|
|
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,EACpC,sCAAsC;AACvC,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAC1B,6BAA6B,EAE9B,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,EAAE,KAAK,eAAe,EAAoB,8BAA8B;AAC/E,OAAO,EACL,KAAK,+BAA+B,EACpC,KAAK,0BAA0B,EAC/B,KA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|
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,EACpC,sCAAsC;AACvC,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAC1B,6BAA6B,EAE9B,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,EAAE,KAAK,eAAe,EAAoB,8BAA8B;AAC/E,OAAO,EACL,KAAK,+BAA+B,EACpC,KAAK,0BAA0B,EAC/B,KAAK,4BAA4B,EACjC,KAAK,oCAAoC,EAE1C,qCAAqC;AACtC,OAAO,KAAK,EAAE,oBAAoB,EAAE,qCAAqC;AACzE,OAAO,KAAK,EAAE,iBAAiB,EAAE,oCAAoC;AAGrE,OAAO,KAAK,EACV,gCAAgC,EAChC,8BAA8B,EAC9B,0BAA0B,EAC3B,wCAAoC;AACrC,OAAO,KAAK,EAAE,YAAY,EAAE,0CAAsC;AAElE,OAAO,KAAK,EACV,sCAAsC,EACtC,yCAAyC,EACzC,kCAAkC,EAClC,qCAAqC,EACrC,sCAAsC,EACvC,uDAAmD;AAkBpD,KAAK,kCAAkC,GAAG;IACxC,IAAI,EAAE,gCAAgC,CAAC;IACvC,OAAO,EAAE,CAAC,oBAAoB,EAAE,oBAAoB,CAAC,CAAC;CACvD,CAAC;AAIF,KAAK,oCAAoC,GAAG;IAC1C,IAAI,EAAE,kCAAkC,CAAC;IACzC,OAAO,EAAE,CAAC,oBAAoB,EAAE,oBAAoB,CAAC,CAAC;CACvD,CAAC;AAIF,KAAK,oCAAoC,GAAG;IAC1C,IAAI,EAAE,kCAAkC,CAAC;IACzC,OAAO,EAAE,CAAC,oBAAoB,EAAE,oBAAoB,CAAC,CAAC;CACvD,CAAC;AAGF,MAAM,CAAC,OAAO,MAAM,yDAAyD,GAC3E;IACE,IAAI,EA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AM,EAAE,GAAG,IAAI,CAAC;IAgB3B;;;;;;;OAOG;IACU,iBAAiB,CAC5B,IAAI,EAAE,gCAAgC,EACtC,KAAK,EAAE,MAAM,GACZ,OAAO,CAAC,IAAI,CAAC;IAchB;;;;;;;OAOG;IACU,sBAAsB,CACjC,IAAI,EAAE,8BAA8B,EACpC,MAAM,EAAE,CAAC,0BAA0B,EAAE,MAAM,CAAC,EAAE,GAC7C,OAAO,CAAC,IAAI,CAAC;IAchB;;;;;OAKG;IACU,oBAAoB,CAC/B,IAAI,EAAE,gCAAgC,GACrC,OAAO,CAAC,IAAI,CAAC;IAahB;;;;;;OAMG;IACU,qCAAqC,CAChD,IAAI,EAAE,8BAA8B,GACnC,OAAO,CAAC,IAAI,CAAC;IAahB;;;;OAIG;IACU,aAAa,IAAI,OAAO,CAAC,MAAM,CAAC;IAmF7C;;;;OAIG;IACG,mCAAmC,IAAI,OAAO,CAAC,IAAI,CAAC;IAuJ1D;;;OAGG;IACG,gCAAgC,CACpC,eAAe,EAAE,eAAe,GAC/B,OAAO,CAAC,IAAI,CAAC;CAkBjB"}
|
|
@@ -42,6 +42,7 @@ export type UserStorageControllerState = {
|
|
|
42
42
|
export declare const defaultState: UserStorageControllerState;
|
|
43
43
|
type ControllerConfig = {
|
|
44
44
|
accountSyncing?: {
|
|
45
|
+
maxNumberOfAccountsToAdd?: number;
|
|
45
46
|
/**
|
|
46
47
|
* Callback that fires when account sync adds an account.
|
|
47
48
|
* This is used for analytics.
|
|
@@ -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,mCAAmC,EACpC,sCAAsC;AACvC,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAC1B,6BAA6B,EAE9B,kCAAkC;AACnC,OAAO,EAAE,cAAc,EA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;;;GAOG;AACH,MAAM,CAAC,OAAO,OAAO,qBAAsB,SAAQ,cAAc,CAC/D,OAAO,cAAc,EACrB,0BAA0B,EAC1B,8BAA8B,CAC/B;;
|
|
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,EACpC,sCAAsC;AACvC,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAC1B,6BAA6B,EAE9B,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,EAAE,KAAK,eAAe,EAAoB,8BAA8B;AAC/E,OAAO,EACL,KAAK,+BAA+B,EACpC,KAAK,0BAA0B,EAC/B,KAAK,4BAA4B,EACjC,KAAK,oCAAoC,EAE1C,qCAAqC;AACtC,OAAO,KAAK,EAAE,oBAAoB,EAAE,qCAAqC;AACzE,OAAO,KAAK,EAAE,iBAAiB,EAAE,oCAAoC;AAGrE,OAAO,KAAK,EACV,gCAAgC,EAChC,8BAA8B,EAC9B,0BAA0B,EAC3B,wCAAoC;AACrC,OAAO,KAAK,EAAE,YAAY,EAAE,0CAAsC;AAElE,OAAO,KAAK,EACV,sCAAsC,EACtC,yCAAyC,EACzC,kCAAkC,EAClC,qCAAqC,EACrC,sCAAsC,EACvC,uDAAmD;AAkBpD,KAAK,kCAAkC,GAAG;IACxC,IAAI,EAAE,gCAAgC,CAAC;IACvC,OAAO,EAAE,CAAC,oBAAoB,EAAE,oBAAoB,CAAC,CAAC;CACvD,CAAC;AAIF,KAAK,oCAAoC,GAAG;IAC1C,IAAI,EAAE,kCAAkC,CAAC;IACzC,OAAO,EAAE,CAAC,oBAAoB,EAAE,oBAAoB,CAAC,CAAC;CACvD,CAAC;AAIF,KAAK,oCAAoC,GAAG;IAC1C,IAAI,EAAE,kCAAkC,CAAC;IACzC,OA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rC,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IAgBzB;;;;;;OAMG;IACU,kCAAkC,CAC7C,IAAI,EAAE,8BAA8B,GACnC,OAAO,CAAC,MAAM,EAAE,GAAG,IAAI,CAAC;IAgB3B;;;;;;;OAOG;IACU,iBAAiB,CAC5B,IAAI,EAAE,gCAAgC,EACtC,KAAK,EAAE,MAAM,GACZ,OAAO,CAAC,IAAI,CAAC;IAchB;;;;;;;OAOG;IACU,sBAAsB,CACjC,IAAI,EAAE,8BAA8B,EACpC,MAAM,EAAE,CAAC,0BAA0B,EAAE,MAAM,CAAC,EAAE,GAC7C,OAAO,CAAC,IAAI,CAAC;IAchB;;;;;OAKG;IACU,oBAAoB,CAC/B,IAAI,EAAE,gCAAgC,GACrC,OAAO,CAAC,IAAI,CAAC;IAahB;;;;;;OAMG;IACU,qCAAqC,CAChD,IAAI,EAAE,8BAA8B,GACnC,OAAO,CAAC,IAAI,CAAC;IAahB;;;;OAIG;IACU,aAAa,IAAI,OAAO,CAAC,MAAM,CAAC;IAmF7C;;;;OAIG;IACG,mCAAmC,IAAI,OAAO,CAAC,IAAI,CAAC;IAuJ1D;;;OAGG;IACG,gCAAgC,CACpC,eAAe,EAAE,eAAe,GAC/B,OAAO,CAAC,IAAI,CAAC;CAkBjB"}
|
|
@@ -71,14 +71,22 @@ class UserStorageController extends BaseController {
|
|
|
71
71
|
});
|
|
72
72
|
_UserStorageController_accounts.set(this, {
|
|
73
73
|
// This is replaced with the actual value in the constructor
|
|
74
|
-
// We will remove this once the feature will be released
|
|
75
74
|
isAccountSyncingEnabled: false,
|
|
76
75
|
isAccountSyncingInProgress: false,
|
|
77
|
-
|
|
76
|
+
maxNumberOfAccountsToAdd: 0,
|
|
78
77
|
canSync: () => {
|
|
79
78
|
try {
|
|
80
79
|
__classPrivateFieldGet(this, _UserStorageController_instances, "m", _UserStorageController_assertProfileSyncingEnabled).call(this);
|
|
81
|
-
|
|
80
|
+
if (__classPrivateFieldGet(this, _UserStorageController_accounts, "f").isAccountSyncingInProgress) {
|
|
81
|
+
return false;
|
|
82
|
+
}
|
|
83
|
+
if (!__classPrivateFieldGet(this, _UserStorageController_accounts, "f").isAccountSyncingEnabled) {
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
if (!__classPrivateFieldGet(this, _UserStorageController_auth, "f").isAuthEnabled()) {
|
|
87
|
+
return false;
|
|
88
|
+
}
|
|
89
|
+
return true;
|
|
82
90
|
}
|
|
83
91
|
catch {
|
|
84
92
|
return false;
|
|
@@ -88,8 +96,7 @@ class UserStorageController extends BaseController {
|
|
|
88
96
|
this.messagingSystem.subscribe('AccountsController:accountAdded',
|
|
89
97
|
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
|
90
98
|
async (account) => {
|
|
91
|
-
if (__classPrivateFieldGet(this, _UserStorageController_accounts, "f").
|
|
92
|
-
__classPrivateFieldGet(this, _UserStorageController_accounts, "f").addedAccountsCount += 1;
|
|
99
|
+
if (!__classPrivateFieldGet(this, _UserStorageController_accounts, "f").canSync()) {
|
|
93
100
|
return;
|
|
94
101
|
}
|
|
95
102
|
await this.saveInternalAccountToUserStorage(account);
|
|
@@ -97,7 +104,7 @@ class UserStorageController extends BaseController {
|
|
|
97
104
|
this.messagingSystem.subscribe('AccountsController:accountRenamed',
|
|
98
105
|
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
|
99
106
|
async (account) => {
|
|
100
|
-
if (__classPrivateFieldGet(this, _UserStorageController_accounts, "f").
|
|
107
|
+
if (!__classPrivateFieldGet(this, _UserStorageController_accounts, "f").canSync()) {
|
|
101
108
|
return;
|
|
102
109
|
}
|
|
103
110
|
await this.saveInternalAccountToUserStorage(account);
|
|
@@ -159,6 +166,8 @@ class UserStorageController extends BaseController {
|
|
|
159
166
|
_UserStorageController__snapSignMessageCache.set(this, {});
|
|
160
167
|
__classPrivateFieldSet(this, _UserStorageController_config, config, "f");
|
|
161
168
|
__classPrivateFieldGet(this, _UserStorageController_accounts, "f").isAccountSyncingEnabled = Boolean(env?.isAccountSyncingEnabled);
|
|
169
|
+
__classPrivateFieldGet(this, _UserStorageController_accounts, "f").maxNumberOfAccountsToAdd =
|
|
170
|
+
config?.accountSyncing?.maxNumberOfAccountsToAdd ?? 100;
|
|
162
171
|
this.getMetaMetricsState = getMetaMetricsState;
|
|
163
172
|
__classPrivateFieldGet(this, _UserStorageController_keyringController, "f").setupLockedStateSubscriptions();
|
|
164
173
|
__classPrivateFieldGet(this, _UserStorageController_instances, "m", _UserStorageController_registerMessageHandlers).call(this);
|
|
@@ -352,7 +361,6 @@ class UserStorageController extends BaseController {
|
|
|
352
361
|
}
|
|
353
362
|
try {
|
|
354
363
|
__classPrivateFieldGet(this, _UserStorageController_accounts, "f").isAccountSyncingInProgress = true;
|
|
355
|
-
__classPrivateFieldGet(this, _UserStorageController_accounts, "f").addedAccountsCount = 0;
|
|
356
364
|
const profileId = await __classPrivateFieldGet(this, _UserStorageController_auth, "f").getProfileId();
|
|
357
365
|
const userStorageAccountsList = await __classPrivateFieldGet(this, _UserStorageController_accounts, "f").getUserStorageAccountsList();
|
|
358
366
|
if (!userStorageAccountsList || !userStorageAccountsList.length) {
|
|
@@ -371,7 +379,7 @@ class UserStorageController extends BaseController {
|
|
|
371
379
|
// We don't want to remove existing accounts for a user
|
|
372
380
|
// so we only add new accounts if the user has more accounts than the internal accounts list
|
|
373
381
|
if (!hasMoreInternalAccountsThanUserStorageAccounts) {
|
|
374
|
-
const numberOfAccountsToAdd = userStorageAccountsList.length - internalAccountsList.length;
|
|
382
|
+
const numberOfAccountsToAdd = Math.min(userStorageAccountsList.length, __classPrivateFieldGet(this, _UserStorageController_accounts, "f").maxNumberOfAccountsToAdd) - internalAccountsList.length;
|
|
375
383
|
// Create new accounts to match the user storage accounts list
|
|
376
384
|
for (let i = 0; i < numberOfAccountsToAdd; i++) {
|
|
377
385
|
await this.messagingSystem.call('KeyringController:addNewAccount');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"UserStorageController.mjs","sourceRoot":"","sources":["../../../src/controllers/user-storage/UserStorageController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAYA,OAAO,EAAE,cAAc,EAAE,kCAAkC;;;AAE3D,OAAO,EAKL,YAAY,EACb,qCAAqC;AAItC,OAAO,EAAE,gBAAgB,EAAE,0CAAgC;AAO3D,OAAO,EAAE,4BAA4B,EAAE,iDAA6C;AASpF,OAAO,EACL,wBAAwB,EACxB,sCAAsC,EACvC,oCAAgC;AACjC,OAAO,EAAE,mBAAmB,EAAE,qDAAiD;AAC/E,OAAO,EACL,sBAAsB,EACtB,iBAAiB,EACjB,kCAAkC,EAClC,cAAc,EACd,+BAA+B,EAC/B,iBAAiB,EAClB,uBAAmB;AAoCpB,MAAM,cAAc,GAAG,uBAAuB,CAAC;AAc/C,MAAM,CAAC,MAAM,YAAY,GAA+B;IACtD,uBAAuB,EAAE,IAAI;IAC7B,6BAA6B,EAAE,KAAK;CACrC,CAAC;AAEF,MAAM,QAAQ,GAA8C;IAC1D,uBAAuB,EAAE;QACvB,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,IAAI;KAChB;IACD,6BAA6B,EAAE;QAC7B,OAAO,EAAE,KAAK;QACd,SAAS,EAAE,KAAK;KACjB;CACF,CAAC;AAsHF;;;;;;;GAOG;AACH,MAAqB,qBAAsB,SAAQ,cAIlD;IAqKC,YAAY,EACV,SAAS,EACT,KAAK,EACL,GAAG,EACH,MAAM,EACN,mBAAmB,EACnB,kBAAkB,GAWnB;QACC,KAAK,CAAC;YACJ,SAAS;YACT,QAAQ;YACR,IAAI,EAAE,cAAc;YACpB,KAAK,EAAE,EAAE,GAAG,YAAY,EAAE,GAAG,KAAK,EAAE;SACrC,CAAC,CAAC;;QA3LL,sCAAQ;YACN,cAAc,EAAE,KAAK,IAAI,EAAE;gBACzB,OAAO,MAAM,IAAI,CAAC,eAAe,CAAC,IAAI,CACpC,yCAAyC,CAC1C,CAAC;YACJ,CAAC;YACD,YAAY,E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ElD,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,CAAC;AACrC,CAAC;AAED;;;;GAIG;AACH,KAAK;IACH,MAAM,EAAE,GAAW,MAAM,uBAAA,IAAI,mCAAM,CAAC,YAAY,EAAE,CAAC;IACnD,IAAI,CAAC,EAAE,EAAE;QACP,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;KACzE;IAED,MAAM,mBAAmB,GAAG,MAAM,uBAAA,IAAI,gFAAiB,MAArB,IAAI,EAAkB,YAAY,EAAE,EAAE,CAAC,CAAC;IAC1E,MAAM,UAAU,GAAG,gBAAgB,CAAC,mBAAmB,CAAC,CAAC;IACzD,OAAO,UAAU,CAAC;AACpB,CAAC;AAID;;;;;GAKG;AACH,KAAK,iDAAkB,OAA6B;IAClD,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,4BAA4B,CAAC,OAAO,CAAC,CACtC,CAAW,CAAC;IAEb,uBAAA,IAAI,oDAAuB,CAAC,OAAO,CAAC,GAAG,MAAM,CAAC;IAE9C,OAAO,MAAM,CAAC;AAChB,CAAC,6HAGC,6BAAsC;IAEtC,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,6BAA6B,GAAG,6BAA6B,CAAC;IACtE,CAAC,CAAC,CAAC;AACL,CAAC;eArjBkB,qBAAqB","sourcesContent":["import type {\n AccountsControllerListAccountsAction,\n AccountsControllerUpdateAccountMetadataAction,\n AccountsControllerAccountRenamedEvent,\n AccountsControllerAccountAddedEvent,\n} from '@metamask/accounts-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedControllerMessenger,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport { type InternalAccount, isEvmAccountType } from '@metamask/keyring-api';\nimport {\n type KeyringControllerGetStateAction,\n type KeyringControllerLockEvent,\n type KeyringControllerUnlockEvent,\n type KeyringControllerAddNewAccountAction,\n KeyringTypes,\n} from '@metamask/keyring-controller';\nimport type { NetworkConfiguration } from '@metamask/network-controller';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\n\nimport { createSHA256Hash } from '../../shared/encryption';\nimport type {\n UserStoragePathWithFeatureAndKey,\n UserStoragePathWithFeatureOnly,\n UserStoragePathWithKeyOnly,\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 AuthenticationControllerPerformSignOut,\n} from '../authentication/AuthenticationController';\nimport type { UserStorageAccount } from './accounts/user-storage';\nimport {\n isNameDefaultAccountName,\n mapInternalAccountToUserStorageAccount,\n} from './accounts/user-storage';\nimport { startNetworkSyncing } from './network-syncing/controller-integration';\nimport {\n batchUpsertUserStorage,\n deleteUserStorage,\n deleteUserStorageAllFeatureEntries,\n getUserStorage,\n getUserStorageAllFeatureEntries,\n upsertUserStorage,\n} from './services';\n\n// TODO: add external NetworkController event\n// Need to listen for when a network gets added\ntype NetworkControllerNetworkAddedEvent = {\n type: 'NetworkController:networkAdded';\n payload: [networkConfiguration: NetworkConfiguration];\n};\n\n// TODO: add external NetworkController event\n// Need to listen for when a network is updated, or the default rpc/block explorer changes\ntype NetworkControllerNetworkChangedEvent = {\n type: 'NetworkController:networkChanged';\n payload: [networkConfiguration: NetworkConfiguration];\n};\n\n// TODO: add external NetworkController event\n// Need to listen for when a network gets deleted\ntype NetworkControllerNetworkDeletedEvent = {\n type: 'NetworkController:networkDeleted';\n payload: [networkConfiguration: NetworkConfiguration];\n};\n\n// TODO: fix external dependencies\nexport declare type NotificationServicesControllerDisableNotificationServices =\n {\n type: `NotificationServicesController:disableNotificationServices`;\n handler: () => Promise<void>;\n };\n\nexport declare type NotificationServicesControllerSelectIsNotificationServicesEnabled =\n {\n type: `NotificationServicesController:selectIsNotificationServicesEnabled`;\n handler: () => boolean;\n };\n\nconst controllerName = 'UserStorageController';\n\n// State\nexport type UserStorageControllerState = {\n /**\n * Condition used by UI and to determine if we can use some of the User Storage methods.\n */\n isProfileSyncingEnabled: boolean | null;\n /**\n * Loading state for the profile syncing update\n */\n isProfileSyncingUpdateLoading: boolean;\n};\n\nexport const defaultState: UserStorageControllerState = {\n isProfileSyncingEnabled: true,\n isProfileSyncingUpdateLoading: false,\n};\n\nconst metadata: StateMetadata<UserStorageControllerState> = {\n isProfileSyncingEnabled: {\n persist: true,\n anonymous: true,\n },\n isProfileSyncingUpdateLoading: {\n persist: false,\n anonymous: false,\n },\n};\n\ntype ControllerConfig = {\n accountSyncing?: {\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\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 | 'getStorageKey'\n | 'enableProfileSyncing'\n | 'disableProfileSyncing'\n | 'syncInternalAccountsWithUserStorage'\n | 'saveInternalAccountToUserStorage'\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 UserStorageControllerGetStorageKey = ActionsObj['getStorageKey'];\nexport type UserStorageControllerEnableProfileSyncing =\n ActionsObj['enableProfileSyncing'];\nexport type UserStorageControllerDisableProfileSyncing =\n ActionsObj['disableProfileSyncing'];\nexport type UserStorageControllerSyncInternalAccountsWithUserStorage =\n ActionsObj['syncInternalAccountsWithUserStorage'];\nexport type UserStorageControllerSaveInternalAccountToUserStorage =\n ActionsObj['saveInternalAccountToUserStorage'];\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 | AuthenticationControllerPerformSignOut\n // Metamask Notifications\n | NotificationServicesControllerDisableNotificationServices\n | NotificationServicesControllerSelectIsNotificationServicesEnabled\n // Account syncing\n | AccountsControllerListAccountsAction\n | AccountsControllerUpdateAccountMetadataAction\n | KeyringControllerAddNewAccountAction;\n\n// Messenger events\nexport type UserStorageControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n UserStorageControllerState\n>;\nexport type UserStorageControllerAccountSyncingInProgress = {\n type: `${typeof controllerName}:accountSyncingInProgress`;\n payload: [boolean];\n};\nexport type UserStorageControllerAccountSyncingComplete = {\n type: `${typeof controllerName}:accountSyncingComplete`;\n payload: [boolean];\n};\nexport type Events =\n | UserStorageControllerStateChangeEvent\n | UserStorageControllerAccountSyncingInProgress\n | UserStorageControllerAccountSyncingComplete;\n\nexport type AllowedEvents =\n | UserStorageControllerStateChangeEvent\n | UserStorageControllerAccountSyncingInProgress\n | UserStorageControllerAccountSyncingComplete\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent\n // Account Syncing Events\n | AccountsControllerAccountAddedEvent\n | AccountsControllerAccountRenamedEvent\n // Network Syncing Events\n | NetworkControllerNetworkAddedEvent\n | NetworkControllerNetworkChangedEvent\n | NetworkControllerNetworkDeletedEvent;\n\n// Messenger\nexport type UserStorageControllerMessenger = RestrictedControllerMessenger<\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 #auth = {\n getBearerToken: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:getBearerToken',\n );\n },\n getProfileId: async () => {\n const sessionProfile = await this.messagingSystem.call(\n 'AuthenticationController:getSessionProfile',\n );\n return sessionProfile?.profileId;\n },\n isAuthEnabled: () => {\n return this.messagingSystem.call('AuthenticationController:isSignedIn');\n },\n signIn: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:performSignIn',\n );\n },\n signOut: async () => {\n return this.messagingSystem.call(\n 'AuthenticationController:performSignOut',\n );\n },\n };\n\n #accounts = {\n // This is replaced with the actual value in the constructor\n // We will remove this once the feature will be released\n isAccountSyncingEnabled: false,\n isAccountSyncingInProgress: false,\n addedAccountsCount: 0,\n canSync: () => {\n try {\n this.#assertProfileSyncingEnabled();\n\n return (\n this.#accounts.isAccountSyncingEnabled && this.#auth.isAuthEnabled()\n );\n } catch {\n return false;\n }\n },\n setupAccountSyncingSubscriptions: () => {\n this.messagingSystem.subscribe(\n 'AccountsController:accountAdded',\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async (account) => {\n if (this.#accounts.isAccountSyncingInProgress) {\n this.#accounts.addedAccountsCount += 1;\n return;\n }\n\n await this.saveInternalAccountToUserStorage(account);\n },\n );\n\n this.messagingSystem.subscribe(\n 'AccountsController:accountRenamed',\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async (account) => {\n if (this.#accounts.isAccountSyncingInProgress) {\n return;\n }\n await this.saveInternalAccountToUserStorage(account);\n },\n );\n },\n doesInternalAccountHaveCorrectKeyringType: (account: InternalAccount) => {\n return account.metadata.keyring.type === KeyringTypes.hd;\n },\n getInternalAccountsList: async (): Promise<InternalAccount[]> => {\n // eslint-disable-next-line @typescript-eslint/await-thenable\n const internalAccountsList = await this.messagingSystem.call(\n 'AccountsController:listAccounts',\n );\n\n return internalAccountsList?.filter(\n this.#accounts.doesInternalAccountHaveCorrectKeyringType,\n );\n },\n getUserStorageAccountsList: async (): Promise<\n UserStorageAccount[] | null\n > => {\n const rawAccountsListResponse =\n await this.performGetStorageAllFeatureEntries('accounts');\n\n return (\n rawAccountsListResponse?.map((rawAccount) => JSON.parse(rawAccount)) ??\n null\n );\n },\n saveInternalAccountToUserStorage: async (\n internalAccount: InternalAccount,\n ) => {\n // Map the internal account to the user storage account schema\n const mappedAccount =\n mapInternalAccountToUserStorageAccount(internalAccount);\n\n await this.performSetStorage(\n `accounts.${internalAccount.address}`,\n JSON.stringify(mappedAccount),\n );\n },\n saveInternalAccountsListToUserStorage: async () => {\n const internalAccountsList =\n await this.#accounts.getInternalAccountsList();\n\n if (!internalAccountsList) {\n return;\n }\n\n const internalAccountsListFormattedForUserStorage =\n internalAccountsList.map(mapInternalAccountToUserStorageAccount);\n\n await this.performBatchSetStorage(\n 'accounts',\n internalAccountsListFormattedForUserStorage.map((account) => [\n account.a,\n JSON.stringify(account),\n ]),\n );\n },\n };\n\n #config?: ControllerConfig;\n\n #notificationServices = {\n disableNotificationServices: async () => {\n return await this.messagingSystem.call(\n 'NotificationServicesController:disableNotificationServices',\n );\n },\n selectIsNotificationServicesEnabled: async () => {\n return this.messagingSystem.call(\n 'NotificationServicesController:selectIsNotificationServicesEnabled',\n );\n },\n };\n\n #isUnlocked = false;\n\n #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 #nativeScryptCrypto: NativeScrypt | undefined = undefined;\n\n getMetaMetricsState: () => boolean;\n\n constructor({\n messenger,\n state,\n env,\n config,\n getMetaMetricsState,\n nativeScryptCrypto,\n }: {\n messenger: UserStorageControllerMessenger;\n state?: UserStorageControllerState;\n config?: ControllerConfig;\n env?: {\n isAccountSyncingEnabled?: boolean;\n isNetworkSyncingEnabled?: boolean;\n };\n getMetaMetricsState: () => boolean;\n nativeScryptCrypto?: NativeScrypt;\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n this.#config = config;\n\n this.#accounts.isAccountSyncingEnabled = Boolean(\n env?.isAccountSyncingEnabled,\n );\n\n this.getMetaMetricsState = getMetaMetricsState;\n this.#keyringController.setupLockedStateSubscriptions();\n this.#registerMessageHandlers();\n this.#nativeScryptCrypto = nativeScryptCrypto;\n this.#accounts.setupAccountSyncingSubscriptions();\n\n // Network Syncing\n if (env?.isNetworkSyncingEnabled) {\n startNetworkSyncing({\n messenger,\n getStorageConfig: async () => {\n const { storageKey, bearerToken } =\n await this.#getStorageKeyAndBearerToken();\n return {\n storageKey,\n bearerToken,\n nativeScryptCrypto: this.#nativeScryptCrypto,\n };\n },\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:getStorageKey',\n this.getStorageKey.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:enableProfileSyncing',\n this.enableProfileSyncing.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:disableProfileSyncing',\n this.disableProfileSyncing.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:syncInternalAccountsWithUserStorage',\n this.syncInternalAccountsWithUserStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:saveInternalAccountToUserStorage',\n this.saveInternalAccountToUserStorage.bind(this),\n );\n }\n\n public async enableProfileSyncing(): Promise<void> {\n try {\n this.#setIsProfileSyncingUpdateLoading(true);\n\n const authEnabled = this.#auth.isAuthEnabled();\n if (!authEnabled) {\n await this.#auth.signIn();\n }\n\n this.update((state) => {\n state.isProfileSyncingEnabled = true;\n });\n\n this.#setIsProfileSyncingUpdateLoading(false);\n } catch (e) {\n this.#setIsProfileSyncingUpdateLoading(false);\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to enable profile syncing - ${errorMessage}`,\n );\n }\n }\n\n public async setIsProfileSyncingEnabled(\n isProfileSyncingEnabled: boolean,\n ): Promise<void> {\n this.update((state) => {\n state.isProfileSyncingEnabled = isProfileSyncingEnabled;\n });\n }\n\n public async disableProfileSyncing(): Promise<void> {\n const isAlreadyDisabled = !this.state.isProfileSyncingEnabled;\n if (isAlreadyDisabled) {\n return;\n }\n\n try {\n this.#setIsProfileSyncingUpdateLoading(true);\n\n const isNotificationServicesEnabled =\n await this.#notificationServices.selectIsNotificationServicesEnabled();\n\n if (isNotificationServicesEnabled) {\n await this.#notificationServices.disableNotificationServices();\n }\n\n const isMetaMetricsParticipation = this.getMetaMetricsState();\n\n if (!isMetaMetricsParticipation) {\n await this.#auth.signOut();\n }\n\n this.#setIsProfileSyncingUpdateLoading(false);\n\n this.update((state) => {\n state.isProfileSyncingEnabled = false;\n });\n } catch (e) {\n this.#setIsProfileSyncingUpdateLoading(false);\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to disable profile syncing - ${errorMessage}`,\n );\n }\n }\n\n /**\n * Allows retrieval of stored data. Data stored is string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @returns the decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorage(\n path: UserStoragePathWithFeatureAndKey,\n ): Promise<string | null> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n const result = await getUserStorage({\n path,\n bearerToken,\n storageKey,\n nativeScryptCrypto: this.#nativeScryptCrypto,\n });\n\n return result;\n }\n\n /**\n * Allows retrieval of all stored data for a specific feature. Data stored is formatted as an array of strings.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @returns the array of decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorageAllFeatureEntries(\n path: UserStoragePathWithFeatureOnly,\n ): Promise<string[] | null> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n const result = await getUserStorageAllFeatureEntries({\n path,\n bearerToken,\n storageKey,\n nativeScryptCrypto: this.#nativeScryptCrypto,\n });\n\n return result;\n }\n\n /**\n * Allows storage of user data. Data stored must be string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param value - The string data you want to store.\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performSetStorage(\n path: UserStoragePathWithFeatureAndKey,\n value: string,\n ): Promise<void> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n await upsertUserStorage(value, {\n path,\n bearerToken,\n storageKey,\n nativeScryptCrypto: this.#nativeScryptCrypto,\n });\n }\n\n /**\n * Allows storage of multiple user data entries for one specific feature. Data stored must be string formatted.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @param values - data to store, in the form of an array of `[entryKey, entryValue]` pairs\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performBatchSetStorage(\n path: UserStoragePathWithFeatureOnly,\n values: [UserStoragePathWithKeyOnly, string][],\n ): Promise<void> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n await batchUpsertUserStorage(values, {\n path,\n bearerToken,\n storageKey,\n nativeScryptCrypto: this.#nativeScryptCrypto,\n });\n }\n\n /**\n * Allows deletion of user data. Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @returns nothing. NOTE that an error is thrown if fails to delete data.\n */\n public async performDeleteStorage(\n path: UserStoragePathWithFeatureAndKey,\n ): Promise<void> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n await deleteUserStorage({\n path,\n bearerToken,\n storageKey,\n });\n }\n\n /**\n * Allows deletion of all user data entries for a specific feature.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @returns nothing. NOTE that an error is thrown if fails to delete data.\n */\n public async performDeleteStorageAllFeatureEntries(\n path: UserStoragePathWithFeatureOnly,\n ): Promise<void> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n await deleteUserStorageAllFeatureEntries({\n path,\n bearerToken,\n storageKey,\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 this.#assertProfileSyncingEnabled();\n const storageKey = await this.#createStorageKey();\n return storageKey;\n }\n\n #assertProfileSyncingEnabled(): void {\n if (!this.state.isProfileSyncingEnabled) {\n throw new Error(\n `${controllerName}: Unable to call method, user is not authenticated`,\n );\n }\n }\n\n /**\n * Utility to get the bearer token and storage key\n */\n async #getStorageKeyAndBearerToken(): Promise<{\n bearerToken: string;\n storageKey: string;\n }> {\n const bearerToken = await this.#auth.getBearerToken();\n if (!bearerToken) {\n throw new Error('UserStorageController - unable to get bearer token');\n }\n const storageKey = await this.#createStorageKey();\n\n return { bearerToken, storageKey };\n }\n\n /**\n * Rather than storing the storage key, we can compute the storage key when needed.\n *\n * @returns the storage key\n */\n async #createStorageKey(): Promise<string> {\n const id: string = await this.#auth.getProfileId();\n if (!id) {\n throw new Error('UserStorageController - unable to create storage key');\n }\n\n const storageKeySignature = await this.#snapSignMessage(`metamask:${id}`);\n const storageKey = createSHA256Hash(storageKeySignature);\n return storageKey;\n }\n\n #_snapSignMessageCache: Record<`metamask:${string}`, string> = {};\n\n /**\n * Signs a specific message using an underlying auth snap.\n *\n * @param message - A specific tagged message to sign.\n * @returns A Signature created by the snap.\n */\n async #snapSignMessage(message: `metamask:${string}`): Promise<string> {\n if (this.#_snapSignMessageCache[message]) {\n return this.#_snapSignMessageCache[message];\n }\n\n if (!this.#isUnlocked) {\n throw new Error(\n '#snapSignMessage - unable to call snap, wallet is locked',\n );\n }\n\n const result = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n createSnapSignMessageRequest(message),\n )) as string;\n\n this.#_snapSignMessageCache[message] = result;\n\n return result;\n }\n\n #setIsProfileSyncingUpdateLoading(\n isProfileSyncingUpdateLoading: boolean,\n ): void {\n this.update((state) => {\n state.isProfileSyncingUpdateLoading = isProfileSyncingUpdateLoading;\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 if (!this.#accounts.canSync()) {\n return;\n }\n\n try {\n this.#accounts.isAccountSyncingInProgress = true;\n this.#accounts.addedAccountsCount = 0;\n\n const profileId = await this.#auth.getProfileId();\n\n const userStorageAccountsList =\n await this.#accounts.getUserStorageAccountsList();\n\n if (!userStorageAccountsList || !userStorageAccountsList.length) {\n await this.#accounts.saveInternalAccountsListToUserStorage();\n return;\n }\n\n // Prepare an array of internal accounts to be saved to the user storage\n const internalAccountsToBeSavedToUserStorage: InternalAccount[] = [];\n\n // Compare internal accounts list with user storage accounts list\n // First step: compare lengths\n let internalAccountsList = await this.#accounts.getInternalAccountsList();\n\n if (!internalAccountsList || !internalAccountsList.length) {\n throw new Error(`Failed to get internal accounts list`);\n }\n\n const hasMoreInternalAccountsThanUserStorageAccounts =\n internalAccountsList.length > userStorageAccountsList.length;\n\n // We don't want to remove existing accounts for a user\n // so we only add new accounts if the user has more accounts than the internal accounts list\n if (!hasMoreInternalAccountsThanUserStorageAccounts) {\n const numberOfAccountsToAdd =\n userStorageAccountsList.length - internalAccountsList.length;\n\n // Create new accounts to match the user storage accounts list\n\n for (let i = 0; i < numberOfAccountsToAdd; i++) {\n await this.messagingSystem.call('KeyringController:addNewAccount');\n\n this.#config?.accountSyncing?.onAccountAdded?.(profileId);\n }\n }\n\n // Second step: compare account names\n // Get the internal accounts list again since new accounts might have been added in the previous step\n internalAccountsList = await this.#accounts.getInternalAccountsList();\n\n for (const internalAccount of internalAccountsList) {\n const userStorageAccount = userStorageAccountsList.find(\n (account) => account.a === internalAccount.address,\n );\n\n if (!userStorageAccount) {\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n\n // One or both accounts have default names\n const isInternalAccountNameDefault = isNameDefaultAccountName(\n internalAccount.metadata.name,\n );\n const isUserStorageAccountNameDefault = isNameDefaultAccountName(\n userStorageAccount.n,\n );\n\n // Internal account has default name\n if (isInternalAccountNameDefault) {\n if (!isUserStorageAccountNameDefault) {\n this.messagingSystem.call(\n 'AccountsController:updateAccountMetadata',\n internalAccount.id,\n {\n name: userStorageAccount.n,\n },\n );\n\n this.#config?.accountSyncing?.onAccountNameUpdated?.(profileId);\n }\n continue;\n }\n\n // Internal account has custom name but user storage account has default name\n if (isUserStorageAccountNameDefault) {\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n\n // Both accounts have custom names\n\n // User storage account has a nameLastUpdatedAt timestamp\n // Note: not storing the undefined checks in constants to act as a type guard\n if (userStorageAccount.nlu !== undefined) {\n if (internalAccount.metadata.nameLastUpdatedAt !== undefined) {\n const isInternalAccountNameNewer =\n internalAccount.metadata.nameLastUpdatedAt >\n userStorageAccount.nlu;\n\n if (isInternalAccountNameNewer) {\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n }\n\n this.messagingSystem.call(\n 'AccountsController:updateAccountMetadata',\n internalAccount.id,\n {\n name: userStorageAccount.n,\n nameLastUpdatedAt: userStorageAccount.nlu,\n },\n );\n\n const areInternalAndUserStorageAccountNamesEqual =\n internalAccount.metadata.name === userStorageAccount.n;\n\n if (!areInternalAndUserStorageAccountNamesEqual) {\n this.#config?.accountSyncing?.onAccountNameUpdated?.(profileId);\n }\n\n continue;\n } else if (internalAccount.metadata.nameLastUpdatedAt !== undefined) {\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n }\n\n // Save the internal accounts list to the user storage\n await this.performBatchSetStorage(\n 'accounts',\n internalAccountsToBeSavedToUserStorage.map((account) => [\n account.address,\n JSON.stringify(mapInternalAccountToUserStorageAccount(account)),\n ]),\n );\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to sync user storage accounts list - ${errorMessage}`,\n );\n } finally {\n this.#accounts.isAccountSyncingInProgress = false;\n }\n }\n\n /**\n * Saves an individual internal account to the user storage.\n * @param internalAccount - The internal account to save\n */\n async saveInternalAccountToUserStorage(\n internalAccount: InternalAccount,\n ): Promise<void> {\n if (\n !this.#accounts.canSync() ||\n !isEvmAccountType(internalAccount.type) ||\n !this.#accounts.doesInternalAccountHaveCorrectKeyringType(internalAccount)\n ) {\n return;\n }\n\n try {\n await this.#accounts.saveInternalAccountToUserStorage(internalAccount);\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to save account to user storage - ${errorMessage}`,\n );\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"UserStorageController.mjs","sourceRoot":"","sources":["../../../src/controllers/user-storage/UserStorageController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAYA,OAAO,EAAE,cAAc,EAAE,kCAAkC;;;AAE3D,OAAO,EAKL,YAAY,EACb,qCAAqC;AAItC,OAAO,EAAE,gBAAgB,EAAE,0CAAgC;AAO3D,OAAO,EAAE,4BAA4B,EAAE,iDAA6C;AASpF,OAAO,EACL,wBAAwB,EACxB,sCAAsC,EACvC,oCAAgC;AACjC,OAAO,EAAE,mBAAmB,EAAE,qDAAiD;AAC/E,OAAO,EACL,sBAAsB,EACtB,iBAAiB,EACjB,kCAAkC,EAClC,cAAc,EACd,+BAA+B,EAC/B,iBAAiB,EAClB,uBAAmB;AAoCpB,MAAM,cAAc,GAAG,uBAAuB,CAAC;AAc/C,MAAM,CAAC,MAAM,YAAY,GAA+B;IACtD,uBAAuB,EAAE,IAAI;IAC7B,6BAA6B,EAAE,KAAK;CACrC,CAAC;AAEF,MAAM,QAAQ,GAA8C;IAC1D,uBAAuB,EAAE;QACvB,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,IAAI;KAChB;IACD,6BAA6B,EAAE;QAC7B,OAAO,EAAE,KAAK;QACd,SAA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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,4BAA4B,CAAC,OAAO,CAAC,CACtC,CAAW,CAAC;IAEb,uBAAA,IAAI,oDAAuB,CAAC,OAAO,CAAC,GAAG,MAAM,CAAC;IAE9C,OAAO,MAAM,CAAC;AAChB,CAAC,6HAGC,6BAAsC;IAEtC,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,6BAA6B,GAAG,6BAA6B,CAAC;IACtE,CAAC,CAAC,CAAC;AACL,CAAC;eAhkBkB,qBAAqB","sourcesContent":["import type {\n AccountsControllerListAccountsAction,\n AccountsControllerUpdateAccountMetadataAction,\n AccountsControllerAccountRenamedEvent,\n AccountsControllerAccountAddedEvent,\n} from '@metamask/accounts-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedControllerMessenger,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport { type InternalAccount, isEvmAccountType } from '@metamask/keyring-api';\nimport {\n type KeyringControllerGetStateAction,\n type KeyringControllerLockEvent,\n type KeyringControllerUnlockEvent,\n type KeyringControllerAddNewAccountAction,\n KeyringTypes,\n} from '@metamask/keyring-controller';\nimport type { NetworkConfiguration } from '@metamask/network-controller';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\n\nimport { createSHA256Hash } from '../../shared/encryption';\nimport type {\n UserStoragePathWithFeatureAndKey,\n UserStoragePathWithFeatureOnly,\n UserStoragePathWithKeyOnly,\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 AuthenticationControllerPerformSignOut,\n} from '../authentication/AuthenticationController';\nimport type { UserStorageAccount } from './accounts/user-storage';\nimport {\n isNameDefaultAccountName,\n mapInternalAccountToUserStorageAccount,\n} from './accounts/user-storage';\nimport { startNetworkSyncing } from './network-syncing/controller-integration';\nimport {\n batchUpsertUserStorage,\n deleteUserStorage,\n deleteUserStorageAllFeatureEntries,\n getUserStorage,\n getUserStorageAllFeatureEntries,\n upsertUserStorage,\n} from './services';\n\n// TODO: add external NetworkController event\n// Need to listen for when a network gets added\ntype NetworkControllerNetworkAddedEvent = {\n type: 'NetworkController:networkAdded';\n payload: [networkConfiguration: NetworkConfiguration];\n};\n\n// TODO: add external NetworkController event\n// Need to listen for when a network is updated, or the default rpc/block explorer changes\ntype NetworkControllerNetworkChangedEvent = {\n type: 'NetworkController:networkChanged';\n payload: [networkConfiguration: NetworkConfiguration];\n};\n\n// TODO: add external NetworkController event\n// Need to listen for when a network gets deleted\ntype NetworkControllerNetworkDeletedEvent = {\n type: 'NetworkController:networkDeleted';\n payload: [networkConfiguration: NetworkConfiguration];\n};\n\n// TODO: fix external dependencies\nexport declare type NotificationServicesControllerDisableNotificationServices =\n {\n type: `NotificationServicesController:disableNotificationServices`;\n handler: () => Promise<void>;\n };\n\nexport declare type NotificationServicesControllerSelectIsNotificationServicesEnabled =\n {\n type: `NotificationServicesController:selectIsNotificationServicesEnabled`;\n handler: () => boolean;\n };\n\nconst controllerName = 'UserStorageController';\n\n// State\nexport type UserStorageControllerState = {\n /**\n * Condition used by UI and to determine if we can use some of the User Storage methods.\n */\n isProfileSyncingEnabled: boolean | null;\n /**\n * Loading state for the profile syncing update\n */\n isProfileSyncingUpdateLoading: boolean;\n};\n\nexport const defaultState: UserStorageControllerState = {\n isProfileSyncingEnabled: true,\n isProfileSyncingUpdateLoading: false,\n};\n\nconst metadata: StateMetadata<UserStorageControllerState> = {\n isProfileSyncingEnabled: {\n persist: true,\n anonymous: true,\n },\n isProfileSyncingUpdateLoading: {\n persist: false,\n anonymous: false,\n },\n};\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\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 | 'getStorageKey'\n | 'enableProfileSyncing'\n | 'disableProfileSyncing'\n | 'syncInternalAccountsWithUserStorage'\n | 'saveInternalAccountToUserStorage'\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 UserStorageControllerGetStorageKey = ActionsObj['getStorageKey'];\nexport type UserStorageControllerEnableProfileSyncing =\n ActionsObj['enableProfileSyncing'];\nexport type UserStorageControllerDisableProfileSyncing =\n ActionsObj['disableProfileSyncing'];\nexport type UserStorageControllerSyncInternalAccountsWithUserStorage =\n ActionsObj['syncInternalAccountsWithUserStorage'];\nexport type UserStorageControllerSaveInternalAccountToUserStorage =\n ActionsObj['saveInternalAccountToUserStorage'];\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 | AuthenticationControllerPerformSignOut\n // Metamask Notifications\n | NotificationServicesControllerDisableNotificationServices\n | NotificationServicesControllerSelectIsNotificationServicesEnabled\n // Account syncing\n | AccountsControllerListAccountsAction\n | AccountsControllerUpdateAccountMetadataAction\n | KeyringControllerAddNewAccountAction;\n\n// Messenger events\nexport type UserStorageControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n UserStorageControllerState\n>;\nexport type UserStorageControllerAccountSyncingInProgress = {\n type: `${typeof controllerName}:accountSyncingInProgress`;\n payload: [boolean];\n};\nexport type UserStorageControllerAccountSyncingComplete = {\n type: `${typeof controllerName}:accountSyncingComplete`;\n payload: [boolean];\n};\nexport type Events =\n | UserStorageControllerStateChangeEvent\n | UserStorageControllerAccountSyncingInProgress\n | UserStorageControllerAccountSyncingComplete;\n\nexport type AllowedEvents =\n | UserStorageControllerStateChangeEvent\n | UserStorageControllerAccountSyncingInProgress\n | UserStorageControllerAccountSyncingComplete\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent\n // Account Syncing Events\n | AccountsControllerAccountAddedEvent\n | AccountsControllerAccountRenamedEvent\n // Network Syncing Events\n | NetworkControllerNetworkAddedEvent\n | NetworkControllerNetworkChangedEvent\n | NetworkControllerNetworkDeletedEvent;\n\n// Messenger\nexport type UserStorageControllerMessenger = RestrictedControllerMessenger<\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 #auth = {\n getBearerToken: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:getBearerToken',\n );\n },\n getProfileId: async () => {\n const sessionProfile = await this.messagingSystem.call(\n 'AuthenticationController:getSessionProfile',\n );\n return sessionProfile?.profileId;\n },\n isAuthEnabled: () => {\n return this.messagingSystem.call('AuthenticationController:isSignedIn');\n },\n signIn: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:performSignIn',\n );\n },\n signOut: async () => {\n return this.messagingSystem.call(\n 'AuthenticationController:performSignOut',\n );\n },\n };\n\n #accounts = {\n // This is replaced with the actual value in the constructor\n isAccountSyncingEnabled: false,\n isAccountSyncingInProgress: false,\n maxNumberOfAccountsToAdd: 0,\n canSync: () => {\n try {\n this.#assertProfileSyncingEnabled();\n\n if (this.#accounts.isAccountSyncingInProgress) {\n return false;\n }\n\n if (!this.#accounts.isAccountSyncingEnabled) {\n return false;\n }\n\n if (!this.#auth.isAuthEnabled()) {\n return false;\n }\n\n return true;\n } catch {\n return false;\n }\n },\n setupAccountSyncingSubscriptions: () => {\n this.messagingSystem.subscribe(\n 'AccountsController:accountAdded',\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async (account) => {\n if (!this.#accounts.canSync()) {\n return;\n }\n\n await this.saveInternalAccountToUserStorage(account);\n },\n );\n\n this.messagingSystem.subscribe(\n 'AccountsController:accountRenamed',\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async (account) => {\n if (!this.#accounts.canSync()) {\n return;\n }\n await this.saveInternalAccountToUserStorage(account);\n },\n );\n },\n doesInternalAccountHaveCorrectKeyringType: (account: InternalAccount) => {\n return account.metadata.keyring.type === KeyringTypes.hd;\n },\n getInternalAccountsList: async (): Promise<InternalAccount[]> => {\n // eslint-disable-next-line @typescript-eslint/await-thenable\n const internalAccountsList = await this.messagingSystem.call(\n 'AccountsController:listAccounts',\n );\n\n return internalAccountsList?.filter(\n this.#accounts.doesInternalAccountHaveCorrectKeyringType,\n );\n },\n getUserStorageAccountsList: async (): Promise<\n UserStorageAccount[] | null\n > => {\n const rawAccountsListResponse =\n await this.performGetStorageAllFeatureEntries('accounts');\n\n return (\n rawAccountsListResponse?.map((rawAccount) => JSON.parse(rawAccount)) ??\n null\n );\n },\n saveInternalAccountToUserStorage: async (\n internalAccount: InternalAccount,\n ) => {\n // Map the internal account to the user storage account schema\n const mappedAccount =\n mapInternalAccountToUserStorageAccount(internalAccount);\n\n await this.performSetStorage(\n `accounts.${internalAccount.address}`,\n JSON.stringify(mappedAccount),\n );\n },\n saveInternalAccountsListToUserStorage: async () => {\n const internalAccountsList =\n await this.#accounts.getInternalAccountsList();\n\n if (!internalAccountsList) {\n return;\n }\n\n const internalAccountsListFormattedForUserStorage =\n internalAccountsList.map(mapInternalAccountToUserStorageAccount);\n\n await this.performBatchSetStorage(\n 'accounts',\n internalAccountsListFormattedForUserStorage.map((account) => [\n account.a,\n JSON.stringify(account),\n ]),\n );\n },\n };\n\n #config?: ControllerConfig;\n\n #notificationServices = {\n disableNotificationServices: async () => {\n return await this.messagingSystem.call(\n 'NotificationServicesController:disableNotificationServices',\n );\n },\n selectIsNotificationServicesEnabled: async () => {\n return this.messagingSystem.call(\n 'NotificationServicesController:selectIsNotificationServicesEnabled',\n );\n },\n };\n\n #isUnlocked = false;\n\n #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 #nativeScryptCrypto: NativeScrypt | undefined = undefined;\n\n getMetaMetricsState: () => boolean;\n\n constructor({\n messenger,\n state,\n env,\n config,\n getMetaMetricsState,\n nativeScryptCrypto,\n }: {\n messenger: UserStorageControllerMessenger;\n state?: UserStorageControllerState;\n config?: ControllerConfig;\n env?: {\n isAccountSyncingEnabled?: boolean;\n isNetworkSyncingEnabled?: boolean;\n };\n getMetaMetricsState: () => boolean;\n nativeScryptCrypto?: NativeScrypt;\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n this.#config = config;\n\n this.#accounts.isAccountSyncingEnabled = Boolean(\n env?.isAccountSyncingEnabled,\n );\n\n this.#accounts.maxNumberOfAccountsToAdd =\n config?.accountSyncing?.maxNumberOfAccountsToAdd ?? 100;\n\n this.getMetaMetricsState = getMetaMetricsState;\n this.#keyringController.setupLockedStateSubscriptions();\n this.#registerMessageHandlers();\n this.#nativeScryptCrypto = nativeScryptCrypto;\n this.#accounts.setupAccountSyncingSubscriptions();\n\n // Network Syncing\n if (env?.isNetworkSyncingEnabled) {\n startNetworkSyncing({\n messenger,\n getStorageConfig: async () => {\n const { storageKey, bearerToken } =\n await this.#getStorageKeyAndBearerToken();\n return {\n storageKey,\n bearerToken,\n nativeScryptCrypto: this.#nativeScryptCrypto,\n };\n },\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:getStorageKey',\n this.getStorageKey.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:enableProfileSyncing',\n this.enableProfileSyncing.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:disableProfileSyncing',\n this.disableProfileSyncing.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:syncInternalAccountsWithUserStorage',\n this.syncInternalAccountsWithUserStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:saveInternalAccountToUserStorage',\n this.saveInternalAccountToUserStorage.bind(this),\n );\n }\n\n public async enableProfileSyncing(): Promise<void> {\n try {\n this.#setIsProfileSyncingUpdateLoading(true);\n\n const authEnabled = this.#auth.isAuthEnabled();\n if (!authEnabled) {\n await this.#auth.signIn();\n }\n\n this.update((state) => {\n state.isProfileSyncingEnabled = true;\n });\n\n this.#setIsProfileSyncingUpdateLoading(false);\n } catch (e) {\n this.#setIsProfileSyncingUpdateLoading(false);\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to enable profile syncing - ${errorMessage}`,\n );\n }\n }\n\n public async setIsProfileSyncingEnabled(\n isProfileSyncingEnabled: boolean,\n ): Promise<void> {\n this.update((state) => {\n state.isProfileSyncingEnabled = isProfileSyncingEnabled;\n });\n }\n\n public async disableProfileSyncing(): Promise<void> {\n const isAlreadyDisabled = !this.state.isProfileSyncingEnabled;\n if (isAlreadyDisabled) {\n return;\n }\n\n try {\n this.#setIsProfileSyncingUpdateLoading(true);\n\n const isNotificationServicesEnabled =\n await this.#notificationServices.selectIsNotificationServicesEnabled();\n\n if (isNotificationServicesEnabled) {\n await this.#notificationServices.disableNotificationServices();\n }\n\n const isMetaMetricsParticipation = this.getMetaMetricsState();\n\n if (!isMetaMetricsParticipation) {\n await this.#auth.signOut();\n }\n\n this.#setIsProfileSyncingUpdateLoading(false);\n\n this.update((state) => {\n state.isProfileSyncingEnabled = false;\n });\n } catch (e) {\n this.#setIsProfileSyncingUpdateLoading(false);\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to disable profile syncing - ${errorMessage}`,\n );\n }\n }\n\n /**\n * Allows retrieval of stored data. Data stored is string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @returns the decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorage(\n path: UserStoragePathWithFeatureAndKey,\n ): Promise<string | null> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n const result = await getUserStorage({\n path,\n bearerToken,\n storageKey,\n nativeScryptCrypto: this.#nativeScryptCrypto,\n });\n\n return result;\n }\n\n /**\n * Allows retrieval of all stored data for a specific feature. Data stored is formatted as an array of strings.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @returns the array of decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorageAllFeatureEntries(\n path: UserStoragePathWithFeatureOnly,\n ): Promise<string[] | null> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n const result = await getUserStorageAllFeatureEntries({\n path,\n bearerToken,\n storageKey,\n nativeScryptCrypto: this.#nativeScryptCrypto,\n });\n\n return result;\n }\n\n /**\n * Allows storage of user data. Data stored must be string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param value - The string data you want to store.\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performSetStorage(\n path: UserStoragePathWithFeatureAndKey,\n value: string,\n ): Promise<void> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n await upsertUserStorage(value, {\n path,\n bearerToken,\n storageKey,\n nativeScryptCrypto: this.#nativeScryptCrypto,\n });\n }\n\n /**\n * Allows storage of multiple user data entries for one specific feature. Data stored must be string formatted.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @param values - data to store, in the form of an array of `[entryKey, entryValue]` pairs\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performBatchSetStorage(\n path: UserStoragePathWithFeatureOnly,\n values: [UserStoragePathWithKeyOnly, string][],\n ): Promise<void> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n await batchUpsertUserStorage(values, {\n path,\n bearerToken,\n storageKey,\n nativeScryptCrypto: this.#nativeScryptCrypto,\n });\n }\n\n /**\n * Allows deletion of user data. Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @returns nothing. NOTE that an error is thrown if fails to delete data.\n */\n public async performDeleteStorage(\n path: UserStoragePathWithFeatureAndKey,\n ): Promise<void> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n await deleteUserStorage({\n path,\n bearerToken,\n storageKey,\n });\n }\n\n /**\n * Allows deletion of all user data entries for a specific feature.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @returns nothing. NOTE that an error is thrown if fails to delete data.\n */\n public async performDeleteStorageAllFeatureEntries(\n path: UserStoragePathWithFeatureOnly,\n ): Promise<void> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n await deleteUserStorageAllFeatureEntries({\n path,\n bearerToken,\n storageKey,\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 this.#assertProfileSyncingEnabled();\n const storageKey = await this.#createStorageKey();\n return storageKey;\n }\n\n #assertProfileSyncingEnabled(): void {\n if (!this.state.isProfileSyncingEnabled) {\n throw new Error(\n `${controllerName}: Unable to call method, user is not authenticated`,\n );\n }\n }\n\n /**\n * Utility to get the bearer token and storage key\n */\n async #getStorageKeyAndBearerToken(): Promise<{\n bearerToken: string;\n storageKey: string;\n }> {\n const bearerToken = await this.#auth.getBearerToken();\n if (!bearerToken) {\n throw new Error('UserStorageController - unable to get bearer token');\n }\n const storageKey = await this.#createStorageKey();\n\n return { bearerToken, storageKey };\n }\n\n /**\n * Rather than storing the storage key, we can compute the storage key when needed.\n *\n * @returns the storage key\n */\n async #createStorageKey(): Promise<string> {\n const id: string = await this.#auth.getProfileId();\n if (!id) {\n throw new Error('UserStorageController - unable to create storage key');\n }\n\n const storageKeySignature = await this.#snapSignMessage(`metamask:${id}`);\n const storageKey = createSHA256Hash(storageKeySignature);\n return storageKey;\n }\n\n #_snapSignMessageCache: Record<`metamask:${string}`, string> = {};\n\n /**\n * Signs a specific message using an underlying auth snap.\n *\n * @param message - A specific tagged message to sign.\n * @returns A Signature created by the snap.\n */\n async #snapSignMessage(message: `metamask:${string}`): Promise<string> {\n if (this.#_snapSignMessageCache[message]) {\n return this.#_snapSignMessageCache[message];\n }\n\n if (!this.#isUnlocked) {\n throw new Error(\n '#snapSignMessage - unable to call snap, wallet is locked',\n );\n }\n\n const result = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n createSnapSignMessageRequest(message),\n )) as string;\n\n this.#_snapSignMessageCache[message] = result;\n\n return result;\n }\n\n #setIsProfileSyncingUpdateLoading(\n isProfileSyncingUpdateLoading: boolean,\n ): void {\n this.update((state) => {\n state.isProfileSyncingUpdateLoading = isProfileSyncingUpdateLoading;\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 if (!this.#accounts.canSync()) {\n return;\n }\n\n try {\n this.#accounts.isAccountSyncingInProgress = true;\n\n const profileId = await this.#auth.getProfileId();\n\n const userStorageAccountsList =\n await this.#accounts.getUserStorageAccountsList();\n\n if (!userStorageAccountsList || !userStorageAccountsList.length) {\n await this.#accounts.saveInternalAccountsListToUserStorage();\n return;\n }\n\n // Prepare an array of internal accounts to be saved to the user storage\n const internalAccountsToBeSavedToUserStorage: InternalAccount[] = [];\n\n // Compare internal accounts list with user storage accounts list\n // First step: compare lengths\n let internalAccountsList = await this.#accounts.getInternalAccountsList();\n\n if (!internalAccountsList || !internalAccountsList.length) {\n throw new Error(`Failed to get internal accounts list`);\n }\n\n const hasMoreInternalAccountsThanUserStorageAccounts =\n internalAccountsList.length > userStorageAccountsList.length;\n\n // We don't want to remove existing accounts for a user\n // so we only add new accounts if the user has more accounts than the internal accounts list\n if (!hasMoreInternalAccountsThanUserStorageAccounts) {\n const numberOfAccountsToAdd =\n Math.min(\n userStorageAccountsList.length,\n this.#accounts.maxNumberOfAccountsToAdd,\n ) - internalAccountsList.length;\n\n // Create new accounts to match the user storage accounts list\n\n for (let i = 0; i < numberOfAccountsToAdd; i++) {\n await this.messagingSystem.call('KeyringController:addNewAccount');\n\n this.#config?.accountSyncing?.onAccountAdded?.(profileId);\n }\n }\n\n // Second step: compare account names\n // Get the internal accounts list again since new accounts might have been added in the previous step\n internalAccountsList = await this.#accounts.getInternalAccountsList();\n\n for (const internalAccount of internalAccountsList) {\n const userStorageAccount = userStorageAccountsList.find(\n (account) => account.a === internalAccount.address,\n );\n\n if (!userStorageAccount) {\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n\n // One or both accounts have default names\n const isInternalAccountNameDefault = isNameDefaultAccountName(\n internalAccount.metadata.name,\n );\n const isUserStorageAccountNameDefault = isNameDefaultAccountName(\n userStorageAccount.n,\n );\n\n // Internal account has default name\n if (isInternalAccountNameDefault) {\n if (!isUserStorageAccountNameDefault) {\n this.messagingSystem.call(\n 'AccountsController:updateAccountMetadata',\n internalAccount.id,\n {\n name: userStorageAccount.n,\n },\n );\n\n this.#config?.accountSyncing?.onAccountNameUpdated?.(profileId);\n }\n continue;\n }\n\n // Internal account has custom name but user storage account has default name\n if (isUserStorageAccountNameDefault) {\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n\n // Both accounts have custom names\n\n // User storage account has a nameLastUpdatedAt timestamp\n // Note: not storing the undefined checks in constants to act as a type guard\n if (userStorageAccount.nlu !== undefined) {\n if (internalAccount.metadata.nameLastUpdatedAt !== undefined) {\n const isInternalAccountNameNewer =\n internalAccount.metadata.nameLastUpdatedAt >\n userStorageAccount.nlu;\n\n if (isInternalAccountNameNewer) {\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n }\n\n this.messagingSystem.call(\n 'AccountsController:updateAccountMetadata',\n internalAccount.id,\n {\n name: userStorageAccount.n,\n nameLastUpdatedAt: userStorageAccount.nlu,\n },\n );\n\n const areInternalAndUserStorageAccountNamesEqual =\n internalAccount.metadata.name === userStorageAccount.n;\n\n if (!areInternalAndUserStorageAccountNamesEqual) {\n this.#config?.accountSyncing?.onAccountNameUpdated?.(profileId);\n }\n\n continue;\n } else if (internalAccount.metadata.nameLastUpdatedAt !== undefined) {\n internalAccountsToBeSavedToUserStorage.push(internalAccount);\n continue;\n }\n }\n\n // Save the internal accounts list to the user storage\n await this.performBatchSetStorage(\n 'accounts',\n internalAccountsToBeSavedToUserStorage.map((account) => [\n account.address,\n JSON.stringify(mapInternalAccountToUserStorageAccount(account)),\n ]),\n );\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to sync user storage accounts list - ${errorMessage}`,\n );\n } finally {\n this.#accounts.isAccountSyncingInProgress = false;\n }\n }\n\n /**\n * Saves an individual internal account to the user storage.\n * @param internalAccount - The internal account to save\n */\n async saveInternalAccountToUserStorage(\n internalAccount: InternalAccount,\n ): Promise<void> {\n if (\n !this.#accounts.canSync() ||\n !isEvmAccountType(internalAccount.type) ||\n !this.#accounts.doesInternalAccountHaveCorrectKeyringType(internalAccount)\n ) {\n return;\n }\n\n try {\n await this.#accounts.saveInternalAccountToUserStorage(internalAccount);\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to save account to user storage - ${errorMessage}`,\n );\n }\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask/profile-sync-controller",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.8",
|
|
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",
|
|
@@ -100,9 +100,10 @@
|
|
|
100
100
|
"test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch"
|
|
101
101
|
},
|
|
102
102
|
"dependencies": {
|
|
103
|
-
"@metamask/base-controller": "^7.0.
|
|
103
|
+
"@metamask/base-controller": "^7.0.2",
|
|
104
104
|
"@metamask/keyring-api": "^8.1.3",
|
|
105
|
-
"@metamask/keyring-controller": "^17.
|
|
105
|
+
"@metamask/keyring-controller": "^17.3.1",
|
|
106
|
+
"@metamask/network-controller": "^22.0.1",
|
|
106
107
|
"@metamask/snaps-sdk": "^6.5.0",
|
|
107
108
|
"@metamask/snaps-utils": "^8.1.1",
|
|
108
109
|
"@noble/ciphers": "^0.5.2",
|
|
@@ -113,9 +114,8 @@
|
|
|
113
114
|
},
|
|
114
115
|
"devDependencies": {
|
|
115
116
|
"@lavamoat/allow-scripts": "^3.0.4",
|
|
116
|
-
"@metamask/accounts-controller": "^18.2.
|
|
117
|
+
"@metamask/accounts-controller": "^18.2.3",
|
|
117
118
|
"@metamask/auto-changelog": "^3.4.4",
|
|
118
|
-
"@metamask/network-controller": "^21.0.1",
|
|
119
119
|
"@metamask/snaps-controllers": "^9.7.0",
|
|
120
120
|
"@types/jest": "^27.4.1",
|
|
121
121
|
"deepmerge": "^4.2.2",
|
|
@@ -131,6 +131,7 @@
|
|
|
131
131
|
"peerDependencies": {
|
|
132
132
|
"@metamask/accounts-controller": "^18.1.1",
|
|
133
133
|
"@metamask/keyring-controller": "^17.2.0",
|
|
134
|
+
"@metamask/network-controller": "^22.0.0",
|
|
134
135
|
"@metamask/snaps-controllers": "^9.7.0"
|
|
135
136
|
},
|
|
136
137
|
"engines": {
|