@metamask-previews/profile-sync-controller 25.1.2-preview-9fa15fd0 → 26.0.0-preview-46d2c977
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 +13 -1
- package/dist/controllers/authentication/AuthenticationController.cjs +14 -14
- package/dist/controllers/authentication/AuthenticationController.cjs.map +1 -1
- package/dist/controllers/authentication/AuthenticationController.d.cts +5 -5
- package/dist/controllers/authentication/AuthenticationController.d.cts.map +1 -1
- package/dist/controllers/authentication/AuthenticationController.d.mts +5 -5
- package/dist/controllers/authentication/AuthenticationController.d.mts.map +1 -1
- package/dist/controllers/authentication/AuthenticationController.mjs +14 -14
- package/dist/controllers/authentication/AuthenticationController.mjs.map +1 -1
- package/dist/controllers/user-storage/UserStorageController.cjs +24 -24
- package/dist/controllers/user-storage/UserStorageController.cjs.map +1 -1
- package/dist/controllers/user-storage/UserStorageController.d.cts +3 -3
- package/dist/controllers/user-storage/UserStorageController.d.cts.map +1 -1
- package/dist/controllers/user-storage/UserStorageController.d.mts +3 -3
- package/dist/controllers/user-storage/UserStorageController.d.mts.map +1 -1
- package/dist/controllers/user-storage/UserStorageController.mjs +24 -24
- package/dist/controllers/user-storage/UserStorageController.mjs.map +1 -1
- package/package.json +7 -6
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [26.0.0]
|
|
11
|
+
|
|
12
|
+
### Changed
|
|
13
|
+
|
|
14
|
+
- **BREAKING:** Use new `Messenger` from `@metamask/messenger` ([#6533](https://github.com/MetaMask/core/pull/6533))
|
|
15
|
+
- Previously, `AuthenticationController` and `UserStorageController` accepted a `RestrictedMessenger` instance from `@metamask/base-controller`.
|
|
16
|
+
- **BREAKING:** Metadata property `anonymous` renamed to `includeInDebugSnapshot` ([#6533](https://github.com/MetaMask/core/pull/6533))
|
|
17
|
+
- **BREAKING:** Bump `@metamask/address-book-controller` from `^6.1.1` to `^7.0.0` ([#6962](https://github.com/MetaMask/core/pull/6962))
|
|
18
|
+
- **BREAKING:** Bump `@metamask/keyring-controller` from `^23.0.0` to `^24.0.0` ([#6962](https://github.com/MetaMask/core/pull/6962))
|
|
19
|
+
- Bump `@metamask/base-controller` from `^8.4.2` to `^9.0.0` ([#6962](https://github.com/MetaMask/core/pull/6962))
|
|
20
|
+
|
|
10
21
|
## [25.1.2]
|
|
11
22
|
|
|
12
23
|
### Changed
|
|
@@ -751,7 +762,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
751
762
|
|
|
752
763
|
- Initial release
|
|
753
764
|
|
|
754
|
-
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@
|
|
765
|
+
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@26.0.0...HEAD
|
|
766
|
+
[26.0.0]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@25.1.2...@metamask/profile-sync-controller@26.0.0
|
|
755
767
|
[25.1.2]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@25.1.1...@metamask/profile-sync-controller@25.1.2
|
|
756
768
|
[25.1.1]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@25.1.0...@metamask/profile-sync-controller@25.1.1
|
|
757
769
|
[25.1.0]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@25.0.0...@metamask/profile-sync-controller@25.1.0
|
|
@@ -24,7 +24,7 @@ const metadata = {
|
|
|
24
24
|
isSignedIn: {
|
|
25
25
|
includeInStateLogs: true,
|
|
26
26
|
persist: true,
|
|
27
|
-
|
|
27
|
+
includeInDebugSnapshot: true,
|
|
28
28
|
usedInUi: true,
|
|
29
29
|
},
|
|
30
30
|
srpSessionData: {
|
|
@@ -48,7 +48,7 @@ const metadata = {
|
|
|
48
48
|
}, {});
|
|
49
49
|
},
|
|
50
50
|
persist: true,
|
|
51
|
-
|
|
51
|
+
includeInDebugSnapshot: false,
|
|
52
52
|
usedInUi: true,
|
|
53
53
|
},
|
|
54
54
|
};
|
|
@@ -73,12 +73,12 @@ class AuthenticationController extends base_controller_1.BaseController {
|
|
|
73
73
|
_AuthenticationController_isUnlocked.set(this, false);
|
|
74
74
|
_AuthenticationController_keyringController.set(this, {
|
|
75
75
|
setupLockedStateSubscriptions: () => {
|
|
76
|
-
const { isUnlocked } = this.
|
|
76
|
+
const { isUnlocked } = this.messenger.call('KeyringController:getState');
|
|
77
77
|
__classPrivateFieldSet(this, _AuthenticationController_isUnlocked, isUnlocked, "f");
|
|
78
|
-
this.
|
|
78
|
+
this.messenger.subscribe('KeyringController:unlock', () => {
|
|
79
79
|
__classPrivateFieldSet(this, _AuthenticationController_isUnlocked, true, "f");
|
|
80
80
|
});
|
|
81
|
-
this.
|
|
81
|
+
this.messenger.subscribe('KeyringController:lock', () => {
|
|
82
82
|
__classPrivateFieldSet(this, _AuthenticationController_isUnlocked, false, "f");
|
|
83
83
|
});
|
|
84
84
|
},
|
|
@@ -159,12 +159,12 @@ class AuthenticationController extends base_controller_1.BaseController {
|
|
|
159
159
|
}
|
|
160
160
|
}
|
|
161
161
|
_AuthenticationController_metametrics = new WeakMap(), _AuthenticationController_auth = new WeakMap(), _AuthenticationController_config = new WeakMap(), _AuthenticationController_isUnlocked = new WeakMap(), _AuthenticationController_keyringController = new WeakMap(), _AuthenticationController__snapSignMessageCache = new WeakMap(), _AuthenticationController_instances = new WeakSet(), _AuthenticationController_registerMessageHandlers = function _AuthenticationController_registerMessageHandlers() {
|
|
162
|
-
this.
|
|
163
|
-
this.
|
|
164
|
-
this.
|
|
165
|
-
this.
|
|
166
|
-
this.
|
|
167
|
-
this.
|
|
162
|
+
this.messenger.registerActionHandler('AuthenticationController:getBearerToken', this.getBearerToken.bind(this));
|
|
163
|
+
this.messenger.registerActionHandler('AuthenticationController:getSessionProfile', this.getSessionProfile.bind(this));
|
|
164
|
+
this.messenger.registerActionHandler('AuthenticationController:isSignedIn', this.isSignedIn.bind(this));
|
|
165
|
+
this.messenger.registerActionHandler('AuthenticationController:performSignIn', this.performSignIn.bind(this));
|
|
166
|
+
this.messenger.registerActionHandler('AuthenticationController:performSignOut', this.performSignOut.bind(this));
|
|
167
|
+
this.messenger.registerActionHandler('AuthenticationController:getUserProfileLineage', this.getUserProfileLineage.bind(this));
|
|
168
168
|
}, _AuthenticationController_getLoginResponseFromState = async function _AuthenticationController_getLoginResponseFromState(entropySourceId) {
|
|
169
169
|
if (entropySourceId) {
|
|
170
170
|
if (!this.state.srpSessionData?.[entropySourceId]) {
|
|
@@ -208,7 +208,7 @@ _AuthenticationController_metametrics = new WeakMap(), _AuthenticationController
|
|
|
208
208
|
*/
|
|
209
209
|
async function _AuthenticationController_snapGetPublicKey(entropySourceId) {
|
|
210
210
|
__classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_assertIsUnlocked).call(this, '#snapGetPublicKey');
|
|
211
|
-
const result = (await this.
|
|
211
|
+
const result = (await this.messenger.call('SnapController:handleRequest', (0, auth_snap_requests_1.createSnapPublicKeyRequest)(entropySourceId)));
|
|
212
212
|
return result;
|
|
213
213
|
}, _AuthenticationController_snapGetAllPublicKeys =
|
|
214
214
|
/**
|
|
@@ -218,7 +218,7 @@ async function _AuthenticationController_snapGetPublicKey(entropySourceId) {
|
|
|
218
218
|
*/
|
|
219
219
|
async function _AuthenticationController_snapGetAllPublicKeys() {
|
|
220
220
|
__classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_assertIsUnlocked).call(this, '#snapGetAllPublicKeys');
|
|
221
|
-
const result = (await this.
|
|
221
|
+
const result = (await this.messenger.call('SnapController:handleRequest', (0, auth_snap_requests_1.createSnapAllPublicKeysRequest)()));
|
|
222
222
|
return result;
|
|
223
223
|
}, _AuthenticationController_snapSignMessage =
|
|
224
224
|
/**
|
|
@@ -235,7 +235,7 @@ async function _AuthenticationController_snapSignMessage(message, entropySourceI
|
|
|
235
235
|
return __classPrivateFieldGet(this, _AuthenticationController__snapSignMessageCache, "f")[message];
|
|
236
236
|
}
|
|
237
237
|
__classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_assertIsUnlocked).call(this, '#snapSignMessage');
|
|
238
|
-
const result = (await this.
|
|
238
|
+
const result = (await this.messenger.call('SnapController:handleRequest', (0, auth_snap_requests_1.createSnapSignMessageRequest)(message, entropySourceId)));
|
|
239
239
|
__classPrivateFieldGet(this, _AuthenticationController__snapSignMessageCache, "f")[message] = result;
|
|
240
240
|
return result;
|
|
241
241
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AuthenticationController.cjs","sourceRoot":"","sources":["../../../src/controllers/authentication/AuthenticationController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAMA,+DAA2D;AAS3D,iEAI8B;AAO9B,6CAKmB;AAGnB,MAAM,cAAc,GAAG,0BAA0B,CAAC;AAOrC,QAAA,YAAY,GAAkC;IACzD,UAAU,EAAE,KAAK;CAClB,CAAC;AACF,MAAM,QAAQ,GAAiD;IAC7D,UAAU,EAAE;QACV,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,IAAI;QACf,QAAQ,EAAE,IAAI;KACf;IACD,cAAc,EAAE;QACd,sCAAsC;QACtC,kBAAkB,EAAE,CAAC,cAAc,EAAE,EAAE;YACrC,4FAA4F;YAC5F,2FAA2F;YAC3F,mEAAmE;YACnE,kEAAkE;YAClE,oDAAoD;YACpD,IAAI,cAAc,KAAK,IAAI,IAAI,cAAc,KAAK,SAAS,EAAE;gBAC3D,OAAO,IAAI,CAAC;aACb;YACD,OAAO,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC,MAAM,CAC1C,CAAC,uBAAuB,EAAE,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE;gBACxC,MAAM,EAAE,WAAW,EAAE,OAA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C,CAAC;IAE3C,MAAM,MAAM,GAAG,CAAC,MAAM,IAAI,CAAC,eAAe,CAAC,IAAI,CAC7C,8BAA8B,EAC9B,IAAA,iDAA4B,EAAC,OAAO,EAAE,eAAe,CAAC,CACvD,CAAW,CAAC;IAEb,uBAAA,IAAI,uDAAuB,CAAC,OAAO,CAAC,GAAG,MAAM,CAAC;IAE9C,OAAO,MAAM,CAAC;AAChB,CAAC;kBAxSkB,wBAAwB","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedMessenger,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n} from '@metamask/keyring-controller';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\nimport type { Json } from '@metamask/utils';\n\nimport {\n createSnapPublicKeyRequest,\n createSnapAllPublicKeysRequest,\n createSnapSignMessageRequest,\n} from './auth-snap-requests';\nimport type {\n LoginResponse,\n SRPInterface,\n UserProfile,\n UserProfileLineage,\n} from '../../sdk';\nimport {\n assertMessageStartsWithMetamask,\n AuthType,\n Env,\n JwtBearerAuth,\n} from '../../sdk';\nimport type { MetaMetricsAuth } from '../../shared/types/services';\n\nconst controllerName = 'AuthenticationController';\n\n// State\nexport type AuthenticationControllerState = {\n isSignedIn: boolean;\n srpSessionData?: Record<string, LoginResponse>;\n};\nexport const defaultState: AuthenticationControllerState = {\n isSignedIn: false,\n};\nconst metadata: StateMetadata<AuthenticationControllerState> = {\n isSignedIn: {\n includeInStateLogs: true,\n persist: true,\n anonymous: true,\n usedInUi: true,\n },\n srpSessionData: {\n // Remove access token from state logs\n includeInStateLogs: (srpSessionData) => {\n // Unreachable branch, included just to fix a type error for the case where this property is\n // unset. The type gets collapsed to include `| undefined` even though `undefined` is never\n // set here, because we don't yet use `exactOptionalPropertyTypes`.\n // TODO: Remove branch after enabling `exactOptionalPropertyTypes`\n // ref: https://github.com/MetaMask/core/issues/6565\n if (srpSessionData === null || srpSessionData === undefined) {\n return null;\n }\n return Object.entries(srpSessionData).reduce<Record<string, Json>>(\n (sanitizedSrpSessionData, [key, value]) => {\n const { accessToken: _unused, ...tokenWithoutAccessToken } =\n value.token;\n sanitizedSrpSessionData[key] = {\n ...value,\n token: tokenWithoutAccessToken,\n };\n return sanitizedSrpSessionData;\n },\n {},\n );\n },\n persist: true,\n anonymous: false,\n usedInUi: true,\n },\n};\n\ntype ControllerConfig = {\n env: Env;\n};\n\n// Messenger Actions\ntype CreateActionsObj<Controller extends keyof AuthenticationController> = {\n [K in Controller]: {\n type: `${typeof controllerName}:${K}`;\n handler: AuthenticationController[K];\n };\n};\ntype ActionsObj = CreateActionsObj<\n | 'performSignIn'\n | 'performSignOut'\n | 'getBearerToken'\n | 'getSessionProfile'\n | 'getUserProfileLineage'\n | 'isSignedIn'\n>;\nexport type Actions =\n | ActionsObj[keyof ActionsObj]\n | AuthenticationControllerGetStateAction;\nexport type AuthenticationControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n AuthenticationControllerState\n>;\nexport type AuthenticationControllerPerformSignIn = ActionsObj['performSignIn'];\nexport type AuthenticationControllerPerformSignOut =\n ActionsObj['performSignOut'];\nexport type AuthenticationControllerGetBearerToken =\n ActionsObj['getBearerToken'];\nexport type AuthenticationControllerGetSessionProfile =\n ActionsObj['getSessionProfile'];\nexport type AuthenticationControllerGetUserProfileLineage =\n ActionsObj['getUserProfileLineage'];\nexport type AuthenticationControllerIsSignedIn = ActionsObj['isSignedIn'];\n\nexport type AuthenticationControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n AuthenticationControllerState\n >;\n\nexport type Events = AuthenticationControllerStateChangeEvent;\n\n// Allowed Actions\nexport type AllowedActions =\n | HandleSnapRequest\n | KeyringControllerGetStateAction;\n\nexport type AllowedEvents =\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent;\n\n// Messenger\nexport type AuthenticationControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n Actions | AllowedActions,\n Events | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Controller that enables authentication for restricted endpoints.\n * Used for Backup & Sync, Notifications, and other services.\n */\nexport default class AuthenticationController extends BaseController<\n typeof controllerName,\n AuthenticationControllerState,\n AuthenticationControllerMessenger\n> {\n readonly #metametrics: MetaMetricsAuth;\n\n readonly #auth: SRPInterface;\n\n readonly #config: ControllerConfig = {\n env: Env.PRD,\n };\n\n #isUnlocked = false;\n\n readonly #keyringController = {\n setupLockedStateSubscriptions: () => {\n const { isUnlocked } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n this.#isUnlocked = isUnlocked;\n\n this.messagingSystem.subscribe('KeyringController:unlock', () => {\n this.#isUnlocked = true;\n });\n\n this.messagingSystem.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n },\n };\n\n constructor({\n messenger,\n state,\n config,\n metametrics,\n }: {\n messenger: AuthenticationControllerMessenger;\n state?: AuthenticationControllerState;\n config?: Partial<ControllerConfig>;\n /**\n * Not using the Messaging System as we\n * do not want to tie this strictly to extension\n */\n metametrics: MetaMetricsAuth;\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n if (!metametrics) {\n throw new Error('`metametrics` field is required');\n }\n\n this.#config = {\n ...this.#config,\n ...config,\n };\n\n this.#metametrics = metametrics;\n\n this.#auth = new JwtBearerAuth(\n {\n env: this.#config.env,\n platform: metametrics.agent,\n type: AuthType.SRP,\n },\n {\n storage: {\n getLoginResponse: this.#getLoginResponseFromState.bind(this),\n setLoginResponse: this.#setLoginResponseToState.bind(this),\n },\n signing: {\n getIdentifier: this.#snapGetPublicKey.bind(this),\n signMessage: this.#snapSignMessage.bind(this),\n },\n metametrics: this.#metametrics,\n },\n );\n\n this.#keyringController.setupLockedStateSubscriptions();\n this.#registerMessageHandlers();\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n 'AuthenticationController:getBearerToken',\n this.getBearerToken.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'AuthenticationController:getSessionProfile',\n this.getSessionProfile.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'AuthenticationController:isSignedIn',\n this.isSignedIn.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'AuthenticationController:performSignIn',\n this.performSignIn.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'AuthenticationController:performSignOut',\n this.performSignOut.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'AuthenticationController:getUserProfileLineage',\n this.getUserProfileLineage.bind(this),\n );\n }\n\n async #getLoginResponseFromState(\n entropySourceId?: string,\n ): Promise<LoginResponse | null> {\n if (entropySourceId) {\n if (!this.state.srpSessionData?.[entropySourceId]) {\n return null;\n }\n return this.state.srpSessionData[entropySourceId];\n }\n\n const primarySrpLoginResponse = Object.values(\n this.state.srpSessionData || {},\n )?.[0];\n\n if (!primarySrpLoginResponse) {\n return null;\n }\n\n return primarySrpLoginResponse;\n }\n\n async #setLoginResponseToState(\n loginResponse: LoginResponse,\n entropySourceId?: string,\n ) {\n const metaMetricsId = await this.#metametrics.getMetaMetricsId();\n this.update((state) => {\n if (entropySourceId) {\n state.isSignedIn = true;\n if (!state.srpSessionData) {\n state.srpSessionData = {};\n }\n state.srpSessionData[entropySourceId] = {\n ...loginResponse,\n profile: {\n ...loginResponse.profile,\n metaMetricsId,\n },\n };\n }\n });\n }\n\n #assertIsUnlocked(methodName: string): void {\n if (!this.#isUnlocked) {\n throw new Error(`${methodName} - unable to proceed, wallet is locked`);\n }\n }\n\n public async performSignIn(): Promise<string[]> {\n this.#assertIsUnlocked('performSignIn');\n\n const allPublicKeys = await this.#snapGetAllPublicKeys();\n const accessTokens = [];\n\n // We iterate sequentially in order to be sure that the first entry\n // is the primary SRP LoginResponse.\n for (const [entropySourceId] of allPublicKeys) {\n const accessToken = await this.#auth.getAccessToken(entropySourceId);\n accessTokens.push(accessToken);\n }\n\n return accessTokens;\n }\n\n public performSignOut(): void {\n this.update((state) => {\n state.isSignedIn = false;\n state.srpSessionData = undefined;\n });\n }\n\n /**\n * Will return a bearer token.\n * Logs a user in if a user is not logged in.\n *\n * @returns profile for the session.\n */\n\n public async getBearerToken(entropySourceId?: string): Promise<string> {\n this.#assertIsUnlocked('getBearerToken');\n return await this.#auth.getAccessToken(entropySourceId);\n }\n\n /**\n * Will return a session profile.\n * Logs a user in if a user is not logged in.\n *\n * @param entropySourceId - The entropy source ID used to derive the key,\n * when multiple sources are available (Multi-SRP).\n * @returns profile for the session.\n */\n public async getSessionProfile(\n entropySourceId?: string,\n ): Promise<UserProfile> {\n this.#assertIsUnlocked('getSessionProfile');\n return await this.#auth.getUserProfile(entropySourceId);\n }\n\n public async getUserProfileLineage(): Promise<UserProfileLineage> {\n this.#assertIsUnlocked('getUserProfileLineage');\n return await this.#auth.getUserProfileLineage();\n }\n\n public isSignedIn(): boolean {\n return this.state.isSignedIn;\n }\n\n /**\n * Returns the auth snap public key.\n *\n * @param entropySourceId - The entropy source ID used to derive the key,\n * when multiple sources are available (Multi-SRP).\n * @returns The snap public key.\n */\n async #snapGetPublicKey(entropySourceId?: string): Promise<string> {\n this.#assertIsUnlocked('#snapGetPublicKey');\n\n const result = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n createSnapPublicKeyRequest(entropySourceId),\n )) as string;\n\n return result;\n }\n\n /**\n * Returns a mapping of entropy source IDs to auth snap public keys.\n *\n * @returns A mapping of entropy source IDs to public keys.\n */\n async #snapGetAllPublicKeys(): Promise<[string, string][]> {\n this.#assertIsUnlocked('#snapGetAllPublicKeys');\n\n const result = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n createSnapAllPublicKeysRequest(),\n )) as [string, string][];\n\n return result;\n }\n\n #_snapSignMessageCache: Record<`metamask:${string}`, string> = {};\n\n /**\n * Signs a specific message using an underlying auth snap.\n *\n * @param message - A specific tagged message to sign.\n * @param entropySourceId - The entropy source ID used to derive the key,\n * when multiple sources are available (Multi-SRP).\n * @returns A Signature created by the snap.\n */\n async #snapSignMessage(\n message: string,\n entropySourceId?: string,\n ): Promise<string> {\n assertMessageStartsWithMetamask(message);\n\n if (this.#_snapSignMessageCache[message]) {\n return this.#_snapSignMessageCache[message];\n }\n\n this.#assertIsUnlocked('#snapSignMessage');\n\n const result = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n createSnapSignMessageRequest(message, entropySourceId),\n )) as string;\n\n this.#_snapSignMessageCache[message] = result;\n\n return result;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"AuthenticationController.cjs","sourceRoot":"","sources":["../../../src/controllers/authentication/AuthenticationController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,+DAKmC;AAUnC,iEAI8B;AAO9B,6CAKmB;AAGnB,MAAM,cAAc,GAAG,0BAA0B,CAAC;AAOrC,QAAA,YAAY,GAAkC;IACzD,UAAU,EAAE,KAAK;CAClB,CAAC;AACF,MAAM,QAAQ,GAAiD;IAC7D,UAAU,EAAE;QACV,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,IAAI;KACf;IACD,cAAc,EAAE;QACd,sCAAsC;QACtC,kBAAkB,EAAE,CAAC,cAAc,EAAE,EAAE;YACrC,4FAA4F;YAC5F,2FAA2F;YAC3F,mEAAmE;YACnE,kEAAkE;YAClE,oDAAoD;YACpD,IAAI,cAAc,KAAK,IAAI,IAAI,cAAc,KAAK,SAAS,EAAE;gBAC3D,OAAO,IAAI,CAAC;aACb;YACD,OAAO,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC,MAAM,CAC1C,CAAC,uBAAuB,EAAE,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE;gBACxC,MAAM,EAAE,WAAW,EAAE,OAAO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AAC;IAE3C,MAAM,MAAM,GAAG,CAAC,MAAM,IAAI,CAAC,SAAS,CAAC,IAAI,CACvC,8BAA8B,EAC9B,IAAA,iDAA4B,EAAC,OAAO,EAAE,eAAe,CAAC,CACvD,CAAW,CAAC;IAEb,uBAAA,IAAI,uDAAuB,CAAC,OAAO,CAAC,GAAG,MAAM,CAAC;IAE9C,OAAO,MAAM,CAAC;AAChB,CAAC;kBAtSkB,wBAAwB","sourcesContent":["import {\n BaseController,\n type ControllerGetStateAction,\n type ControllerStateChangeEvent,\n type StateMetadata,\n} from '@metamask/base-controller';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n} from '@metamask/keyring-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\nimport type { Json } from '@metamask/utils';\n\nimport {\n createSnapPublicKeyRequest,\n createSnapAllPublicKeysRequest,\n createSnapSignMessageRequest,\n} from './auth-snap-requests';\nimport type {\n LoginResponse,\n SRPInterface,\n UserProfile,\n UserProfileLineage,\n} from '../../sdk';\nimport {\n assertMessageStartsWithMetamask,\n AuthType,\n Env,\n JwtBearerAuth,\n} from '../../sdk';\nimport type { MetaMetricsAuth } from '../../shared/types/services';\n\nconst controllerName = 'AuthenticationController';\n\n// State\nexport type AuthenticationControllerState = {\n isSignedIn: boolean;\n srpSessionData?: Record<string, LoginResponse>;\n};\nexport const defaultState: AuthenticationControllerState = {\n isSignedIn: false,\n};\nconst metadata: StateMetadata<AuthenticationControllerState> = {\n isSignedIn: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n srpSessionData: {\n // Remove access token from state logs\n includeInStateLogs: (srpSessionData) => {\n // Unreachable branch, included just to fix a type error for the case where this property is\n // unset. The type gets collapsed to include `| undefined` even though `undefined` is never\n // set here, because we don't yet use `exactOptionalPropertyTypes`.\n // TODO: Remove branch after enabling `exactOptionalPropertyTypes`\n // ref: https://github.com/MetaMask/core/issues/6565\n if (srpSessionData === null || srpSessionData === undefined) {\n return null;\n }\n return Object.entries(srpSessionData).reduce<Record<string, Json>>(\n (sanitizedSrpSessionData, [key, value]) => {\n const { accessToken: _unused, ...tokenWithoutAccessToken } =\n value.token;\n sanitizedSrpSessionData[key] = {\n ...value,\n token: tokenWithoutAccessToken,\n };\n return sanitizedSrpSessionData;\n },\n {},\n );\n },\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n};\n\ntype ControllerConfig = {\n env: Env;\n};\n\n// Messenger Actions\ntype CreateActionsObj<Controller extends keyof AuthenticationController> = {\n [K in Controller]: {\n type: `${typeof controllerName}:${K}`;\n handler: AuthenticationController[K];\n };\n};\ntype ActionsObj = CreateActionsObj<\n | 'performSignIn'\n | 'performSignOut'\n | 'getBearerToken'\n | 'getSessionProfile'\n | 'getUserProfileLineage'\n | 'isSignedIn'\n>;\nexport type Actions =\n | ActionsObj[keyof ActionsObj]\n | AuthenticationControllerGetStateAction;\nexport type AuthenticationControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n AuthenticationControllerState\n>;\nexport type AuthenticationControllerPerformSignIn = ActionsObj['performSignIn'];\nexport type AuthenticationControllerPerformSignOut =\n ActionsObj['performSignOut'];\nexport type AuthenticationControllerGetBearerToken =\n ActionsObj['getBearerToken'];\nexport type AuthenticationControllerGetSessionProfile =\n ActionsObj['getSessionProfile'];\nexport type AuthenticationControllerGetUserProfileLineage =\n ActionsObj['getUserProfileLineage'];\nexport type AuthenticationControllerIsSignedIn = ActionsObj['isSignedIn'];\n\nexport type AuthenticationControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n AuthenticationControllerState\n >;\n\nexport type Events = AuthenticationControllerStateChangeEvent;\n\n// Allowed Actions\ntype AllowedActions = HandleSnapRequest | KeyringControllerGetStateAction;\n\ntype AllowedEvents = KeyringControllerLockEvent | KeyringControllerUnlockEvent;\n\n// Messenger\nexport type AuthenticationControllerMessenger = Messenger<\n typeof controllerName,\n Actions | AllowedActions,\n Events | AllowedEvents\n>;\n\n/**\n * Controller that enables authentication for restricted endpoints.\n * Used for Backup & Sync, Notifications, and other services.\n */\nexport default class AuthenticationController extends BaseController<\n typeof controllerName,\n AuthenticationControllerState,\n AuthenticationControllerMessenger\n> {\n readonly #metametrics: MetaMetricsAuth;\n\n readonly #auth: SRPInterface;\n\n readonly #config: ControllerConfig = {\n env: Env.PRD,\n };\n\n #isUnlocked = false;\n\n readonly #keyringController = {\n setupLockedStateSubscriptions: () => {\n const { isUnlocked } = this.messenger.call('KeyringController:getState');\n this.#isUnlocked = isUnlocked;\n\n this.messenger.subscribe('KeyringController:unlock', () => {\n this.#isUnlocked = true;\n });\n\n this.messenger.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n },\n };\n\n constructor({\n messenger,\n state,\n config,\n metametrics,\n }: {\n messenger: AuthenticationControllerMessenger;\n state?: AuthenticationControllerState;\n config?: Partial<ControllerConfig>;\n /**\n * Not using the Messaging System as we\n * do not want to tie this strictly to extension\n */\n metametrics: MetaMetricsAuth;\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n if (!metametrics) {\n throw new Error('`metametrics` field is required');\n }\n\n this.#config = {\n ...this.#config,\n ...config,\n };\n\n this.#metametrics = metametrics;\n\n this.#auth = new JwtBearerAuth(\n {\n env: this.#config.env,\n platform: metametrics.agent,\n type: AuthType.SRP,\n },\n {\n storage: {\n getLoginResponse: this.#getLoginResponseFromState.bind(this),\n setLoginResponse: this.#setLoginResponseToState.bind(this),\n },\n signing: {\n getIdentifier: this.#snapGetPublicKey.bind(this),\n signMessage: this.#snapSignMessage.bind(this),\n },\n metametrics: this.#metametrics,\n },\n );\n\n this.#keyringController.setupLockedStateSubscriptions();\n this.#registerMessageHandlers();\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers(): void {\n this.messenger.registerActionHandler(\n 'AuthenticationController:getBearerToken',\n this.getBearerToken.bind(this),\n );\n\n this.messenger.registerActionHandler(\n 'AuthenticationController:getSessionProfile',\n this.getSessionProfile.bind(this),\n );\n\n this.messenger.registerActionHandler(\n 'AuthenticationController:isSignedIn',\n this.isSignedIn.bind(this),\n );\n\n this.messenger.registerActionHandler(\n 'AuthenticationController:performSignIn',\n this.performSignIn.bind(this),\n );\n\n this.messenger.registerActionHandler(\n 'AuthenticationController:performSignOut',\n this.performSignOut.bind(this),\n );\n\n this.messenger.registerActionHandler(\n 'AuthenticationController:getUserProfileLineage',\n this.getUserProfileLineage.bind(this),\n );\n }\n\n async #getLoginResponseFromState(\n entropySourceId?: string,\n ): Promise<LoginResponse | null> {\n if (entropySourceId) {\n if (!this.state.srpSessionData?.[entropySourceId]) {\n return null;\n }\n return this.state.srpSessionData[entropySourceId];\n }\n\n const primarySrpLoginResponse = Object.values(\n this.state.srpSessionData || {},\n )?.[0];\n\n if (!primarySrpLoginResponse) {\n return null;\n }\n\n return primarySrpLoginResponse;\n }\n\n async #setLoginResponseToState(\n loginResponse: LoginResponse,\n entropySourceId?: string,\n ) {\n const metaMetricsId = await this.#metametrics.getMetaMetricsId();\n this.update((state) => {\n if (entropySourceId) {\n state.isSignedIn = true;\n if (!state.srpSessionData) {\n state.srpSessionData = {};\n }\n state.srpSessionData[entropySourceId] = {\n ...loginResponse,\n profile: {\n ...loginResponse.profile,\n metaMetricsId,\n },\n };\n }\n });\n }\n\n #assertIsUnlocked(methodName: string): void {\n if (!this.#isUnlocked) {\n throw new Error(`${methodName} - unable to proceed, wallet is locked`);\n }\n }\n\n public async performSignIn(): Promise<string[]> {\n this.#assertIsUnlocked('performSignIn');\n\n const allPublicKeys = await this.#snapGetAllPublicKeys();\n const accessTokens = [];\n\n // We iterate sequentially in order to be sure that the first entry\n // is the primary SRP LoginResponse.\n for (const [entropySourceId] of allPublicKeys) {\n const accessToken = await this.#auth.getAccessToken(entropySourceId);\n accessTokens.push(accessToken);\n }\n\n return accessTokens;\n }\n\n public performSignOut(): void {\n this.update((state) => {\n state.isSignedIn = false;\n state.srpSessionData = undefined;\n });\n }\n\n /**\n * Will return a bearer token.\n * Logs a user in if a user is not logged in.\n *\n * @returns profile for the session.\n */\n\n public async getBearerToken(entropySourceId?: string): Promise<string> {\n this.#assertIsUnlocked('getBearerToken');\n return await this.#auth.getAccessToken(entropySourceId);\n }\n\n /**\n * Will return a session profile.\n * Logs a user in if a user is not logged in.\n *\n * @param entropySourceId - The entropy source ID used to derive the key,\n * when multiple sources are available (Multi-SRP).\n * @returns profile for the session.\n */\n public async getSessionProfile(\n entropySourceId?: string,\n ): Promise<UserProfile> {\n this.#assertIsUnlocked('getSessionProfile');\n return await this.#auth.getUserProfile(entropySourceId);\n }\n\n public async getUserProfileLineage(): Promise<UserProfileLineage> {\n this.#assertIsUnlocked('getUserProfileLineage');\n return await this.#auth.getUserProfileLineage();\n }\n\n public isSignedIn(): boolean {\n return this.state.isSignedIn;\n }\n\n /**\n * Returns the auth snap public key.\n *\n * @param entropySourceId - The entropy source ID used to derive the key,\n * when multiple sources are available (Multi-SRP).\n * @returns The snap public key.\n */\n async #snapGetPublicKey(entropySourceId?: string): Promise<string> {\n this.#assertIsUnlocked('#snapGetPublicKey');\n\n const result = (await this.messenger.call(\n 'SnapController:handleRequest',\n createSnapPublicKeyRequest(entropySourceId),\n )) as string;\n\n return result;\n }\n\n /**\n * Returns a mapping of entropy source IDs to auth snap public keys.\n *\n * @returns A mapping of entropy source IDs to public keys.\n */\n async #snapGetAllPublicKeys(): Promise<[string, string][]> {\n this.#assertIsUnlocked('#snapGetAllPublicKeys');\n\n const result = (await this.messenger.call(\n 'SnapController:handleRequest',\n createSnapAllPublicKeysRequest(),\n )) as [string, string][];\n\n return result;\n }\n\n #_snapSignMessageCache: Record<`metamask:${string}`, string> = {};\n\n /**\n * Signs a specific message using an underlying auth snap.\n *\n * @param message - A specific tagged message to sign.\n * @param entropySourceId - The entropy source ID used to derive the key,\n * when multiple sources are available (Multi-SRP).\n * @returns A Signature created by the snap.\n */\n async #snapSignMessage(\n message: string,\n entropySourceId?: string,\n ): Promise<string> {\n assertMessageStartsWithMetamask(message);\n\n if (this.#_snapSignMessageCache[message]) {\n return this.#_snapSignMessageCache[message];\n }\n\n this.#assertIsUnlocked('#snapSignMessage');\n\n const result = (await this.messenger.call(\n 'SnapController:handleRequest',\n createSnapSignMessageRequest(message, entropySourceId),\n )) as string;\n\n this.#_snapSignMessageCache[message] = result;\n\n return result;\n }\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import type
|
|
2
|
-
import { BaseController } from "@metamask/base-controller";
|
|
1
|
+
import { BaseController, type ControllerGetStateAction, type ControllerStateChangeEvent } from "@metamask/base-controller";
|
|
3
2
|
import type { KeyringControllerGetStateAction, KeyringControllerLockEvent, KeyringControllerUnlockEvent } from "@metamask/keyring-controller";
|
|
3
|
+
import type { Messenger } from "@metamask/messenger";
|
|
4
4
|
import type { HandleSnapRequest } from "@metamask/snaps-controllers";
|
|
5
5
|
import type { LoginResponse, UserProfile, UserProfileLineage } from "../../sdk/index.cjs";
|
|
6
6
|
import { Env } from "../../sdk/index.cjs";
|
|
@@ -31,9 +31,9 @@ export type AuthenticationControllerGetUserProfileLineage = ActionsObj['getUserP
|
|
|
31
31
|
export type AuthenticationControllerIsSignedIn = ActionsObj['isSignedIn'];
|
|
32
32
|
export type AuthenticationControllerStateChangeEvent = ControllerStateChangeEvent<typeof controllerName, AuthenticationControllerState>;
|
|
33
33
|
export type Events = AuthenticationControllerStateChangeEvent;
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
export type AuthenticationControllerMessenger =
|
|
34
|
+
type AllowedActions = HandleSnapRequest | KeyringControllerGetStateAction;
|
|
35
|
+
type AllowedEvents = KeyringControllerLockEvent | KeyringControllerUnlockEvent;
|
|
36
|
+
export type AuthenticationControllerMessenger = Messenger<typeof controllerName, Actions | AllowedActions, Events | AllowedEvents>;
|
|
37
37
|
/**
|
|
38
38
|
* Controller that enables authentication for restricted endpoints.
|
|
39
39
|
* Used for Backup & Sync, Notifications, and other services.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AuthenticationController.d.cts","sourceRoot":"","sources":["../../../src/controllers/authentication/AuthenticationController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"AuthenticationController.d.cts","sourceRoot":"","sources":["../../../src/controllers/authentication/AuthenticationController.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,KAAK,wBAAwB,EAC7B,KAAK,0BAA0B,EAEhC,kCAAkC;AACnC,OAAO,KAAK,EACV,+BAA+B,EAC/B,0BAA0B,EAC1B,4BAA4B,EAC7B,qCAAqC;AACtC,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AACrD,OAAO,KAAK,EAAE,iBAAiB,EAAE,oCAAoC;AAQrE,OAAO,KAAK,EACV,aAAa,EAEb,WAAW,EACX,kBAAkB,EACnB,4BAAkB;AACnB,OAAO,EAGL,GAAG,EAEJ,4BAAkB;AACnB,OAAO,KAAK,EAAE,eAAe,EAAE,wCAAoC;AAEnE,QAAA,MAAM,cAAc,6BAA6B,CAAC;AAGlD,MAAM,MAAM,6BAA6B,GAAG;IAC1C,UAAU,EAAE,OAAO,CAAC;IACpB,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;CAChD,CAAC;AACF,eAAO,MAAM,YAAY,EAAE,6BAE1B,CAAC;AAsCF,KAAK,gBAAgB,GAAG;IACtB,GAAG,EAAE,GAAG,CAAC;CACV,CAAC;AAGF,KAAK,gBAAgB,CAAC,UAAU,SAAS,MAAM,wBAAwB,IAAI;KACxE,CAAC,IAAI,UAAU,GAAG;QACjB,IAAI,EAAE,GAAG,OAAO,cAAc,IAAI,CAAC,EAAE,CAAC;QACtC,OAAO,EAAE,wBAAwB,CAAC,CAAC,CAAC,CAAC;KACtC;CACF,CAAC;AACF,KAAK,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AAiC,CAAC;QAC7C,KAAK,CAAC,EAAE,6BAA6B,CAAC;QACtC,MAAM,CAAC,EAAE,OAAO,CAAC,gBAAgB,CAAC,CAAC;QACnC;;;WAGG;QACH,WAAW,EAAE,eAAe,CAAC;KAC9B;IA+HY,aAAa,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;IAgBxC,cAAc,IAAI,IAAI;IAO7B;;;;;OAKG;IAEU,cAAc,CAAC,eAAe,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAKtE;;;;;;;OAOG;IACU,iBAAiB,CAC5B,eAAe,CAAC,EAAE,MAAM,GACvB,OAAO,CAAC,WAAW,CAAC;IAKV,qBAAqB,IAAI,OAAO,CAAC,kBAAkB,CAAC;IAK1D,UAAU,IAAI,OAAO;CAqE7B"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import type
|
|
2
|
-
import { BaseController } from "@metamask/base-controller";
|
|
1
|
+
import { BaseController, type ControllerGetStateAction, type ControllerStateChangeEvent } from "@metamask/base-controller";
|
|
3
2
|
import type { KeyringControllerGetStateAction, KeyringControllerLockEvent, KeyringControllerUnlockEvent } from "@metamask/keyring-controller";
|
|
3
|
+
import type { Messenger } from "@metamask/messenger";
|
|
4
4
|
import type { HandleSnapRequest } from "@metamask/snaps-controllers";
|
|
5
5
|
import type { LoginResponse, UserProfile, UserProfileLineage } from "../../sdk/index.mjs";
|
|
6
6
|
import { Env } from "../../sdk/index.mjs";
|
|
@@ -31,9 +31,9 @@ export type AuthenticationControllerGetUserProfileLineage = ActionsObj['getUserP
|
|
|
31
31
|
export type AuthenticationControllerIsSignedIn = ActionsObj['isSignedIn'];
|
|
32
32
|
export type AuthenticationControllerStateChangeEvent = ControllerStateChangeEvent<typeof controllerName, AuthenticationControllerState>;
|
|
33
33
|
export type Events = AuthenticationControllerStateChangeEvent;
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
export type AuthenticationControllerMessenger =
|
|
34
|
+
type AllowedActions = HandleSnapRequest | KeyringControllerGetStateAction;
|
|
35
|
+
type AllowedEvents = KeyringControllerLockEvent | KeyringControllerUnlockEvent;
|
|
36
|
+
export type AuthenticationControllerMessenger = Messenger<typeof controllerName, Actions | AllowedActions, Events | AllowedEvents>;
|
|
37
37
|
/**
|
|
38
38
|
* Controller that enables authentication for restricted endpoints.
|
|
39
39
|
* Used for Backup & Sync, Notifications, and other services.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AuthenticationController.d.mts","sourceRoot":"","sources":["../../../src/controllers/authentication/AuthenticationController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"AuthenticationController.d.mts","sourceRoot":"","sources":["../../../src/controllers/authentication/AuthenticationController.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,KAAK,wBAAwB,EAC7B,KAAK,0BAA0B,EAEhC,kCAAkC;AACnC,OAAO,KAAK,EACV,+BAA+B,EAC/B,0BAA0B,EAC1B,4BAA4B,EAC7B,qCAAqC;AACtC,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AACrD,OAAO,KAAK,EAAE,iBAAiB,EAAE,oCAAoC;AAQrE,OAAO,KAAK,EACV,aAAa,EAEb,WAAW,EACX,kBAAkB,EACnB,4BAAkB;AACnB,OAAO,EAGL,GAAG,EAEJ,4BAAkB;AACnB,OAAO,KAAK,EAAE,eAAe,EAAE,wCAAoC;AAEnE,QAAA,MAAM,cAAc,6BAA6B,CAAC;AAGlD,MAAM,MAAM,6BAA6B,GAAG;IAC1C,UAAU,EAAE,OAAO,CAAC;IACpB,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;CAChD,CAAC;AACF,eAAO,MAAM,YAAY,EAAE,6BAE1B,CAAC;AAsCF,KAAK,gBAAgB,GAAG;IACtB,GAAG,EAAE,GAAG,CAAC;CACV,CAAC;AAGF,KAAK,gBAAgB,CAAC,UAAU,SAAS,MAAM,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AM,CAAC,OAAO,OAAO,wBAAyB,SAAQ,cAAc,CAClE,OAAO,cAAc,EACrB,6BAA6B,EAC7B,iCAAiC,CAClC;;gBA0Ba,EACV,SAAS,EACT,KAAK,EACL,MAAM,EACN,WAAW,GACZ,EAAE;QACD,SAAS,EAAE,iCAAiC,CAAC;QAC7C,KAAK,CAAC,EAAE,6BAA6B,CAAC;QACtC,MAAM,CAAC,EAAE,OAAO,CAAC,gBAAgB,CAAC,CAAC;QACnC;;;WAGG;QACH,WAAW,EAAE,eAAe,CAAC;KAC9B;IA+HY,aAAa,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;IAgBxC,cAAc,IAAI,IAAI;IAO7B;;;;;OAKG;IAEU,cAAc,CAAC,eAAe,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAKtE;;;;;;;OAOG;IACU,iBAAiB,CAC5B,eAAe,CAAC,EAAE,MAAM,GACvB,OAAO,CAAC,WAAW,CAAC;IAKV,qBAAqB,IAAI,OAAO,CAAC,kBAAkB,CAAC;IAK1D,UAAU,IAAI,OAAO;CAqE7B"}
|
|
@@ -21,7 +21,7 @@ const metadata = {
|
|
|
21
21
|
isSignedIn: {
|
|
22
22
|
includeInStateLogs: true,
|
|
23
23
|
persist: true,
|
|
24
|
-
|
|
24
|
+
includeInDebugSnapshot: true,
|
|
25
25
|
usedInUi: true,
|
|
26
26
|
},
|
|
27
27
|
srpSessionData: {
|
|
@@ -45,7 +45,7 @@ const metadata = {
|
|
|
45
45
|
}, {});
|
|
46
46
|
},
|
|
47
47
|
persist: true,
|
|
48
|
-
|
|
48
|
+
includeInDebugSnapshot: false,
|
|
49
49
|
usedInUi: true,
|
|
50
50
|
},
|
|
51
51
|
};
|
|
@@ -70,12 +70,12 @@ class AuthenticationController extends BaseController {
|
|
|
70
70
|
_AuthenticationController_isUnlocked.set(this, false);
|
|
71
71
|
_AuthenticationController_keyringController.set(this, {
|
|
72
72
|
setupLockedStateSubscriptions: () => {
|
|
73
|
-
const { isUnlocked } = this.
|
|
73
|
+
const { isUnlocked } = this.messenger.call('KeyringController:getState');
|
|
74
74
|
__classPrivateFieldSet(this, _AuthenticationController_isUnlocked, isUnlocked, "f");
|
|
75
|
-
this.
|
|
75
|
+
this.messenger.subscribe('KeyringController:unlock', () => {
|
|
76
76
|
__classPrivateFieldSet(this, _AuthenticationController_isUnlocked, true, "f");
|
|
77
77
|
});
|
|
78
|
-
this.
|
|
78
|
+
this.messenger.subscribe('KeyringController:lock', () => {
|
|
79
79
|
__classPrivateFieldSet(this, _AuthenticationController_isUnlocked, false, "f");
|
|
80
80
|
});
|
|
81
81
|
},
|
|
@@ -156,12 +156,12 @@ class AuthenticationController extends BaseController {
|
|
|
156
156
|
}
|
|
157
157
|
}
|
|
158
158
|
_AuthenticationController_metametrics = new WeakMap(), _AuthenticationController_auth = new WeakMap(), _AuthenticationController_config = new WeakMap(), _AuthenticationController_isUnlocked = new WeakMap(), _AuthenticationController_keyringController = new WeakMap(), _AuthenticationController__snapSignMessageCache = new WeakMap(), _AuthenticationController_instances = new WeakSet(), _AuthenticationController_registerMessageHandlers = function _AuthenticationController_registerMessageHandlers() {
|
|
159
|
-
this.
|
|
160
|
-
this.
|
|
161
|
-
this.
|
|
162
|
-
this.
|
|
163
|
-
this.
|
|
164
|
-
this.
|
|
159
|
+
this.messenger.registerActionHandler('AuthenticationController:getBearerToken', this.getBearerToken.bind(this));
|
|
160
|
+
this.messenger.registerActionHandler('AuthenticationController:getSessionProfile', this.getSessionProfile.bind(this));
|
|
161
|
+
this.messenger.registerActionHandler('AuthenticationController:isSignedIn', this.isSignedIn.bind(this));
|
|
162
|
+
this.messenger.registerActionHandler('AuthenticationController:performSignIn', this.performSignIn.bind(this));
|
|
163
|
+
this.messenger.registerActionHandler('AuthenticationController:performSignOut', this.performSignOut.bind(this));
|
|
164
|
+
this.messenger.registerActionHandler('AuthenticationController:getUserProfileLineage', this.getUserProfileLineage.bind(this));
|
|
165
165
|
}, _AuthenticationController_getLoginResponseFromState = async function _AuthenticationController_getLoginResponseFromState(entropySourceId) {
|
|
166
166
|
if (entropySourceId) {
|
|
167
167
|
if (!this.state.srpSessionData?.[entropySourceId]) {
|
|
@@ -205,7 +205,7 @@ _AuthenticationController_metametrics = new WeakMap(), _AuthenticationController
|
|
|
205
205
|
*/
|
|
206
206
|
async function _AuthenticationController_snapGetPublicKey(entropySourceId) {
|
|
207
207
|
__classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_assertIsUnlocked).call(this, '#snapGetPublicKey');
|
|
208
|
-
const result = (await this.
|
|
208
|
+
const result = (await this.messenger.call('SnapController:handleRequest', createSnapPublicKeyRequest(entropySourceId)));
|
|
209
209
|
return result;
|
|
210
210
|
}, _AuthenticationController_snapGetAllPublicKeys =
|
|
211
211
|
/**
|
|
@@ -215,7 +215,7 @@ async function _AuthenticationController_snapGetPublicKey(entropySourceId) {
|
|
|
215
215
|
*/
|
|
216
216
|
async function _AuthenticationController_snapGetAllPublicKeys() {
|
|
217
217
|
__classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_assertIsUnlocked).call(this, '#snapGetAllPublicKeys');
|
|
218
|
-
const result = (await this.
|
|
218
|
+
const result = (await this.messenger.call('SnapController:handleRequest', createSnapAllPublicKeysRequest()));
|
|
219
219
|
return result;
|
|
220
220
|
}, _AuthenticationController_snapSignMessage =
|
|
221
221
|
/**
|
|
@@ -232,7 +232,7 @@ async function _AuthenticationController_snapSignMessage(message, entropySourceI
|
|
|
232
232
|
return __classPrivateFieldGet(this, _AuthenticationController__snapSignMessageCache, "f")[message];
|
|
233
233
|
}
|
|
234
234
|
__classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_assertIsUnlocked).call(this, '#snapSignMessage');
|
|
235
|
-
const result = (await this.
|
|
235
|
+
const result = (await this.messenger.call('SnapController:handleRequest', createSnapSignMessageRequest(message, entropySourceId)));
|
|
236
236
|
__classPrivateFieldGet(this, _AuthenticationController__snapSignMessageCache, "f")[message] = result;
|
|
237
237
|
return result;
|
|
238
238
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AuthenticationController.mjs","sourceRoot":"","sources":["../../../src/controllers/authentication/AuthenticationController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAMA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAS3D,OAAO,EACL,0BAA0B,EAC1B,8BAA8B,EAC9B,4BAA4B,EAC7B,iCAA6B;AAO9B,OAAO,EACL,+BAA+B,EAC/B,QAAQ,EACR,GAAG,EACH,aAAa,EACd,4BAAkB;AAGnB,MAAM,cAAc,GAAG,0BAA0B,CAAC;AAOlD,MAAM,CAAC,MAAM,YAAY,GAAkC;IACzD,UAAU,EAAE,KAAK;CAClB,CAAC;AACF,MAAM,QAAQ,GAAiD;IAC7D,UAAU,EAAE;QACV,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,IAAI;QACf,QAAQ,EAAE,IAAI;KACf;IACD,cAAc,EAAE;QACd,sCAAsC;QACtC,kBAAkB,EAAE,CAAC,cAAc,EAAE,EAAE;YACrC,4FAA4F;YAC5F,2FAA2F;YAC3F,mEAAmE;YACnE,kEAAkE;YAClE,oDAAoD;YACpD,IAAI,cAAc,KAAK,IAAI,IAAI,cAAc,KAAK,SAAS,EAAE;gBAC3D,OAAO,IAAI,CAAC;aACb;YACD,OAAO,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC,MAAM,CAC1C,CAAC,uBAAuB,EAAE,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE;gBACxC,MAAM,EAAE,WAAW,EAAE,OAAO,EAAE,GAAG,uBAAuB,EAAE,GACxD,KAAK,CAAC,KAAK,CAAC;gBACd,uBAAuB,CAAC,GAAG,CAAC,GAAG;oBAC7B,GAAG,KAAK;oBACR,KAAK,EAAE,uBAAuB;iBAC/B,CAAC;gBACF,OAAO,uBAAuB,CAAC;YACjC,CAAC,E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AE9C,OAAO,MAAM,CAAC;AAChB,CAAC;eAxSkB,wBAAwB","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedMessenger,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n} from '@metamask/keyring-controller';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\nimport type { Json } from '@metamask/utils';\n\nimport {\n createSnapPublicKeyRequest,\n createSnapAllPublicKeysRequest,\n createSnapSignMessageRequest,\n} from './auth-snap-requests';\nimport type {\n LoginResponse,\n SRPInterface,\n UserProfile,\n UserProfileLineage,\n} from '../../sdk';\nimport {\n assertMessageStartsWithMetamask,\n AuthType,\n Env,\n JwtBearerAuth,\n} from '../../sdk';\nimport type { MetaMetricsAuth } from '../../shared/types/services';\n\nconst controllerName = 'AuthenticationController';\n\n// State\nexport type AuthenticationControllerState = {\n isSignedIn: boolean;\n srpSessionData?: Record<string, LoginResponse>;\n};\nexport const defaultState: AuthenticationControllerState = {\n isSignedIn: false,\n};\nconst metadata: StateMetadata<AuthenticationControllerState> = {\n isSignedIn: {\n includeInStateLogs: true,\n persist: true,\n anonymous: true,\n usedInUi: true,\n },\n srpSessionData: {\n // Remove access token from state logs\n includeInStateLogs: (srpSessionData) => {\n // Unreachable branch, included just to fix a type error for the case where this property is\n // unset. The type gets collapsed to include `| undefined` even though `undefined` is never\n // set here, because we don't yet use `exactOptionalPropertyTypes`.\n // TODO: Remove branch after enabling `exactOptionalPropertyTypes`\n // ref: https://github.com/MetaMask/core/issues/6565\n if (srpSessionData === null || srpSessionData === undefined) {\n return null;\n }\n return Object.entries(srpSessionData).reduce<Record<string, Json>>(\n (sanitizedSrpSessionData, [key, value]) => {\n const { accessToken: _unused, ...tokenWithoutAccessToken } =\n value.token;\n sanitizedSrpSessionData[key] = {\n ...value,\n token: tokenWithoutAccessToken,\n };\n return sanitizedSrpSessionData;\n },\n {},\n );\n },\n persist: true,\n anonymous: false,\n usedInUi: true,\n },\n};\n\ntype ControllerConfig = {\n env: Env;\n};\n\n// Messenger Actions\ntype CreateActionsObj<Controller extends keyof AuthenticationController> = {\n [K in Controller]: {\n type: `${typeof controllerName}:${K}`;\n handler: AuthenticationController[K];\n };\n};\ntype ActionsObj = CreateActionsObj<\n | 'performSignIn'\n | 'performSignOut'\n | 'getBearerToken'\n | 'getSessionProfile'\n | 'getUserProfileLineage'\n | 'isSignedIn'\n>;\nexport type Actions =\n | ActionsObj[keyof ActionsObj]\n | AuthenticationControllerGetStateAction;\nexport type AuthenticationControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n AuthenticationControllerState\n>;\nexport type AuthenticationControllerPerformSignIn = ActionsObj['performSignIn'];\nexport type AuthenticationControllerPerformSignOut =\n ActionsObj['performSignOut'];\nexport type AuthenticationControllerGetBearerToken =\n ActionsObj['getBearerToken'];\nexport type AuthenticationControllerGetSessionProfile =\n ActionsObj['getSessionProfile'];\nexport type AuthenticationControllerGetUserProfileLineage =\n ActionsObj['getUserProfileLineage'];\nexport type AuthenticationControllerIsSignedIn = ActionsObj['isSignedIn'];\n\nexport type AuthenticationControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n AuthenticationControllerState\n >;\n\nexport type Events = AuthenticationControllerStateChangeEvent;\n\n// Allowed Actions\nexport type AllowedActions =\n | HandleSnapRequest\n | KeyringControllerGetStateAction;\n\nexport type AllowedEvents =\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent;\n\n// Messenger\nexport type AuthenticationControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n Actions | AllowedActions,\n Events | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Controller that enables authentication for restricted endpoints.\n * Used for Backup & Sync, Notifications, and other services.\n */\nexport default class AuthenticationController extends BaseController<\n typeof controllerName,\n AuthenticationControllerState,\n AuthenticationControllerMessenger\n> {\n readonly #metametrics: MetaMetricsAuth;\n\n readonly #auth: SRPInterface;\n\n readonly #config: ControllerConfig = {\n env: Env.PRD,\n };\n\n #isUnlocked = false;\n\n readonly #keyringController = {\n setupLockedStateSubscriptions: () => {\n const { isUnlocked } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n this.#isUnlocked = isUnlocked;\n\n this.messagingSystem.subscribe('KeyringController:unlock', () => {\n this.#isUnlocked = true;\n });\n\n this.messagingSystem.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n },\n };\n\n constructor({\n messenger,\n state,\n config,\n metametrics,\n }: {\n messenger: AuthenticationControllerMessenger;\n state?: AuthenticationControllerState;\n config?: Partial<ControllerConfig>;\n /**\n * Not using the Messaging System as we\n * do not want to tie this strictly to extension\n */\n metametrics: MetaMetricsAuth;\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n if (!metametrics) {\n throw new Error('`metametrics` field is required');\n }\n\n this.#config = {\n ...this.#config,\n ...config,\n };\n\n this.#metametrics = metametrics;\n\n this.#auth = new JwtBearerAuth(\n {\n env: this.#config.env,\n platform: metametrics.agent,\n type: AuthType.SRP,\n },\n {\n storage: {\n getLoginResponse: this.#getLoginResponseFromState.bind(this),\n setLoginResponse: this.#setLoginResponseToState.bind(this),\n },\n signing: {\n getIdentifier: this.#snapGetPublicKey.bind(this),\n signMessage: this.#snapSignMessage.bind(this),\n },\n metametrics: this.#metametrics,\n },\n );\n\n this.#keyringController.setupLockedStateSubscriptions();\n this.#registerMessageHandlers();\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n 'AuthenticationController:getBearerToken',\n this.getBearerToken.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'AuthenticationController:getSessionProfile',\n this.getSessionProfile.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'AuthenticationController:isSignedIn',\n this.isSignedIn.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'AuthenticationController:performSignIn',\n this.performSignIn.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'AuthenticationController:performSignOut',\n this.performSignOut.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'AuthenticationController:getUserProfileLineage',\n this.getUserProfileLineage.bind(this),\n );\n }\n\n async #getLoginResponseFromState(\n entropySourceId?: string,\n ): Promise<LoginResponse | null> {\n if (entropySourceId) {\n if (!this.state.srpSessionData?.[entropySourceId]) {\n return null;\n }\n return this.state.srpSessionData[entropySourceId];\n }\n\n const primarySrpLoginResponse = Object.values(\n this.state.srpSessionData || {},\n )?.[0];\n\n if (!primarySrpLoginResponse) {\n return null;\n }\n\n return primarySrpLoginResponse;\n }\n\n async #setLoginResponseToState(\n loginResponse: LoginResponse,\n entropySourceId?: string,\n ) {\n const metaMetricsId = await this.#metametrics.getMetaMetricsId();\n this.update((state) => {\n if (entropySourceId) {\n state.isSignedIn = true;\n if (!state.srpSessionData) {\n state.srpSessionData = {};\n }\n state.srpSessionData[entropySourceId] = {\n ...loginResponse,\n profile: {\n ...loginResponse.profile,\n metaMetricsId,\n },\n };\n }\n });\n }\n\n #assertIsUnlocked(methodName: string): void {\n if (!this.#isUnlocked) {\n throw new Error(`${methodName} - unable to proceed, wallet is locked`);\n }\n }\n\n public async performSignIn(): Promise<string[]> {\n this.#assertIsUnlocked('performSignIn');\n\n const allPublicKeys = await this.#snapGetAllPublicKeys();\n const accessTokens = [];\n\n // We iterate sequentially in order to be sure that the first entry\n // is the primary SRP LoginResponse.\n for (const [entropySourceId] of allPublicKeys) {\n const accessToken = await this.#auth.getAccessToken(entropySourceId);\n accessTokens.push(accessToken);\n }\n\n return accessTokens;\n }\n\n public performSignOut(): void {\n this.update((state) => {\n state.isSignedIn = false;\n state.srpSessionData = undefined;\n });\n }\n\n /**\n * Will return a bearer token.\n * Logs a user in if a user is not logged in.\n *\n * @returns profile for the session.\n */\n\n public async getBearerToken(entropySourceId?: string): Promise<string> {\n this.#assertIsUnlocked('getBearerToken');\n return await this.#auth.getAccessToken(entropySourceId);\n }\n\n /**\n * Will return a session profile.\n * Logs a user in if a user is not logged in.\n *\n * @param entropySourceId - The entropy source ID used to derive the key,\n * when multiple sources are available (Multi-SRP).\n * @returns profile for the session.\n */\n public async getSessionProfile(\n entropySourceId?: string,\n ): Promise<UserProfile> {\n this.#assertIsUnlocked('getSessionProfile');\n return await this.#auth.getUserProfile(entropySourceId);\n }\n\n public async getUserProfileLineage(): Promise<UserProfileLineage> {\n this.#assertIsUnlocked('getUserProfileLineage');\n return await this.#auth.getUserProfileLineage();\n }\n\n public isSignedIn(): boolean {\n return this.state.isSignedIn;\n }\n\n /**\n * Returns the auth snap public key.\n *\n * @param entropySourceId - The entropy source ID used to derive the key,\n * when multiple sources are available (Multi-SRP).\n * @returns The snap public key.\n */\n async #snapGetPublicKey(entropySourceId?: string): Promise<string> {\n this.#assertIsUnlocked('#snapGetPublicKey');\n\n const result = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n createSnapPublicKeyRequest(entropySourceId),\n )) as string;\n\n return result;\n }\n\n /**\n * Returns a mapping of entropy source IDs to auth snap public keys.\n *\n * @returns A mapping of entropy source IDs to public keys.\n */\n async #snapGetAllPublicKeys(): Promise<[string, string][]> {\n this.#assertIsUnlocked('#snapGetAllPublicKeys');\n\n const result = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n createSnapAllPublicKeysRequest(),\n )) as [string, string][];\n\n return result;\n }\n\n #_snapSignMessageCache: Record<`metamask:${string}`, string> = {};\n\n /**\n * Signs a specific message using an underlying auth snap.\n *\n * @param message - A specific tagged message to sign.\n * @param entropySourceId - The entropy source ID used to derive the key,\n * when multiple sources are available (Multi-SRP).\n * @returns A Signature created by the snap.\n */\n async #snapSignMessage(\n message: string,\n entropySourceId?: string,\n ): Promise<string> {\n assertMessageStartsWithMetamask(message);\n\n if (this.#_snapSignMessageCache[message]) {\n return this.#_snapSignMessageCache[message];\n }\n\n this.#assertIsUnlocked('#snapSignMessage');\n\n const result = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n createSnapSignMessageRequest(message, entropySourceId),\n )) as string;\n\n this.#_snapSignMessageCache[message] = result;\n\n return result;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"AuthenticationController.mjs","sourceRoot":"","sources":["../../../src/controllers/authentication/AuthenticationController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EACL,cAAc,EAIf,kCAAkC;AAUnC,OAAO,EACL,0BAA0B,EAC1B,8BAA8B,EAC9B,4BAA4B,EAC7B,iCAA6B;AAO9B,OAAO,EACL,+BAA+B,EAC/B,QAAQ,EACR,GAAG,EACH,aAAa,EACd,4BAAkB;AAGnB,MAAM,cAAc,GAAG,0BAA0B,CAAC;AAOlD,MAAM,CAAC,MAAM,YAAY,GAAkC;IACzD,UAAU,EAAE,KAAK;CAClB,CAAC;AACF,MAAM,QAAQ,GAAiD;IAC7D,UAAU,EAAE;QACV,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,IAAI;KACf;IACD,cAAc,EAAE;QACd,sCAAsC;QACtC,kBAAkB,EAAE,CAAC,cAAc,EAAE,EAAE;YACrC,4FAA4F;YAC5F,2FAA2F;YAC3F,mEAAmE;YACnE,kEAAkE;YAClE,oDAAoD;YACpD,IAAI,cAAc,KAAK,IAAI,IAAI,cAAc,KAAK,SAAS,EAAE;gBAC3D,OAAO,IAAI,CAAC;aACb;YACD,OAAO,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC,MAAM,CAC1C,CAAC,uBAAuB,EAAE,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE;gBACxC,MAAM,EAAE,WAAW,EAAE,OAAO,EAAE,GAAG,uBAAuB,EAAE,GACxD,KAAK,CAAC,KAAK,CAAC;gBACd,uBAAuB,CAAC,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B,CAAC,OAAO,EAAE,eAAe,CAAC,CACvD,CAAW,CAAC;IAEb,uBAAA,IAAI,uDAAuB,CAAC,OAAO,CAAC,GAAG,MAAM,CAAC;IAE9C,OAAO,MAAM,CAAC;AAChB,CAAC;eAtSkB,wBAAwB","sourcesContent":["import {\n BaseController,\n type ControllerGetStateAction,\n type ControllerStateChangeEvent,\n type StateMetadata,\n} from '@metamask/base-controller';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n} from '@metamask/keyring-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\nimport type { Json } from '@metamask/utils';\n\nimport {\n createSnapPublicKeyRequest,\n createSnapAllPublicKeysRequest,\n createSnapSignMessageRequest,\n} from './auth-snap-requests';\nimport type {\n LoginResponse,\n SRPInterface,\n UserProfile,\n UserProfileLineage,\n} from '../../sdk';\nimport {\n assertMessageStartsWithMetamask,\n AuthType,\n Env,\n JwtBearerAuth,\n} from '../../sdk';\nimport type { MetaMetricsAuth } from '../../shared/types/services';\n\nconst controllerName = 'AuthenticationController';\n\n// State\nexport type AuthenticationControllerState = {\n isSignedIn: boolean;\n srpSessionData?: Record<string, LoginResponse>;\n};\nexport const defaultState: AuthenticationControllerState = {\n isSignedIn: false,\n};\nconst metadata: StateMetadata<AuthenticationControllerState> = {\n isSignedIn: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n srpSessionData: {\n // Remove access token from state logs\n includeInStateLogs: (srpSessionData) => {\n // Unreachable branch, included just to fix a type error for the case where this property is\n // unset. The type gets collapsed to include `| undefined` even though `undefined` is never\n // set here, because we don't yet use `exactOptionalPropertyTypes`.\n // TODO: Remove branch after enabling `exactOptionalPropertyTypes`\n // ref: https://github.com/MetaMask/core/issues/6565\n if (srpSessionData === null || srpSessionData === undefined) {\n return null;\n }\n return Object.entries(srpSessionData).reduce<Record<string, Json>>(\n (sanitizedSrpSessionData, [key, value]) => {\n const { accessToken: _unused, ...tokenWithoutAccessToken } =\n value.token;\n sanitizedSrpSessionData[key] = {\n ...value,\n token: tokenWithoutAccessToken,\n };\n return sanitizedSrpSessionData;\n },\n {},\n );\n },\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n};\n\ntype ControllerConfig = {\n env: Env;\n};\n\n// Messenger Actions\ntype CreateActionsObj<Controller extends keyof AuthenticationController> = {\n [K in Controller]: {\n type: `${typeof controllerName}:${K}`;\n handler: AuthenticationController[K];\n };\n};\ntype ActionsObj = CreateActionsObj<\n | 'performSignIn'\n | 'performSignOut'\n | 'getBearerToken'\n | 'getSessionProfile'\n | 'getUserProfileLineage'\n | 'isSignedIn'\n>;\nexport type Actions =\n | ActionsObj[keyof ActionsObj]\n | AuthenticationControllerGetStateAction;\nexport type AuthenticationControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n AuthenticationControllerState\n>;\nexport type AuthenticationControllerPerformSignIn = ActionsObj['performSignIn'];\nexport type AuthenticationControllerPerformSignOut =\n ActionsObj['performSignOut'];\nexport type AuthenticationControllerGetBearerToken =\n ActionsObj['getBearerToken'];\nexport type AuthenticationControllerGetSessionProfile =\n ActionsObj['getSessionProfile'];\nexport type AuthenticationControllerGetUserProfileLineage =\n ActionsObj['getUserProfileLineage'];\nexport type AuthenticationControllerIsSignedIn = ActionsObj['isSignedIn'];\n\nexport type AuthenticationControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n AuthenticationControllerState\n >;\n\nexport type Events = AuthenticationControllerStateChangeEvent;\n\n// Allowed Actions\ntype AllowedActions = HandleSnapRequest | KeyringControllerGetStateAction;\n\ntype AllowedEvents = KeyringControllerLockEvent | KeyringControllerUnlockEvent;\n\n// Messenger\nexport type AuthenticationControllerMessenger = Messenger<\n typeof controllerName,\n Actions | AllowedActions,\n Events | AllowedEvents\n>;\n\n/**\n * Controller that enables authentication for restricted endpoints.\n * Used for Backup & Sync, Notifications, and other services.\n */\nexport default class AuthenticationController extends BaseController<\n typeof controllerName,\n AuthenticationControllerState,\n AuthenticationControllerMessenger\n> {\n readonly #metametrics: MetaMetricsAuth;\n\n readonly #auth: SRPInterface;\n\n readonly #config: ControllerConfig = {\n env: Env.PRD,\n };\n\n #isUnlocked = false;\n\n readonly #keyringController = {\n setupLockedStateSubscriptions: () => {\n const { isUnlocked } = this.messenger.call('KeyringController:getState');\n this.#isUnlocked = isUnlocked;\n\n this.messenger.subscribe('KeyringController:unlock', () => {\n this.#isUnlocked = true;\n });\n\n this.messenger.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n },\n };\n\n constructor({\n messenger,\n state,\n config,\n metametrics,\n }: {\n messenger: AuthenticationControllerMessenger;\n state?: AuthenticationControllerState;\n config?: Partial<ControllerConfig>;\n /**\n * Not using the Messaging System as we\n * do not want to tie this strictly to extension\n */\n metametrics: MetaMetricsAuth;\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n if (!metametrics) {\n throw new Error('`metametrics` field is required');\n }\n\n this.#config = {\n ...this.#config,\n ...config,\n };\n\n this.#metametrics = metametrics;\n\n this.#auth = new JwtBearerAuth(\n {\n env: this.#config.env,\n platform: metametrics.agent,\n type: AuthType.SRP,\n },\n {\n storage: {\n getLoginResponse: this.#getLoginResponseFromState.bind(this),\n setLoginResponse: this.#setLoginResponseToState.bind(this),\n },\n signing: {\n getIdentifier: this.#snapGetPublicKey.bind(this),\n signMessage: this.#snapSignMessage.bind(this),\n },\n metametrics: this.#metametrics,\n },\n );\n\n this.#keyringController.setupLockedStateSubscriptions();\n this.#registerMessageHandlers();\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers(): void {\n this.messenger.registerActionHandler(\n 'AuthenticationController:getBearerToken',\n this.getBearerToken.bind(this),\n );\n\n this.messenger.registerActionHandler(\n 'AuthenticationController:getSessionProfile',\n this.getSessionProfile.bind(this),\n );\n\n this.messenger.registerActionHandler(\n 'AuthenticationController:isSignedIn',\n this.isSignedIn.bind(this),\n );\n\n this.messenger.registerActionHandler(\n 'AuthenticationController:performSignIn',\n this.performSignIn.bind(this),\n );\n\n this.messenger.registerActionHandler(\n 'AuthenticationController:performSignOut',\n this.performSignOut.bind(this),\n );\n\n this.messenger.registerActionHandler(\n 'AuthenticationController:getUserProfileLineage',\n this.getUserProfileLineage.bind(this),\n );\n }\n\n async #getLoginResponseFromState(\n entropySourceId?: string,\n ): Promise<LoginResponse | null> {\n if (entropySourceId) {\n if (!this.state.srpSessionData?.[entropySourceId]) {\n return null;\n }\n return this.state.srpSessionData[entropySourceId];\n }\n\n const primarySrpLoginResponse = Object.values(\n this.state.srpSessionData || {},\n )?.[0];\n\n if (!primarySrpLoginResponse) {\n return null;\n }\n\n return primarySrpLoginResponse;\n }\n\n async #setLoginResponseToState(\n loginResponse: LoginResponse,\n entropySourceId?: string,\n ) {\n const metaMetricsId = await this.#metametrics.getMetaMetricsId();\n this.update((state) => {\n if (entropySourceId) {\n state.isSignedIn = true;\n if (!state.srpSessionData) {\n state.srpSessionData = {};\n }\n state.srpSessionData[entropySourceId] = {\n ...loginResponse,\n profile: {\n ...loginResponse.profile,\n metaMetricsId,\n },\n };\n }\n });\n }\n\n #assertIsUnlocked(methodName: string): void {\n if (!this.#isUnlocked) {\n throw new Error(`${methodName} - unable to proceed, wallet is locked`);\n }\n }\n\n public async performSignIn(): Promise<string[]> {\n this.#assertIsUnlocked('performSignIn');\n\n const allPublicKeys = await this.#snapGetAllPublicKeys();\n const accessTokens = [];\n\n // We iterate sequentially in order to be sure that the first entry\n // is the primary SRP LoginResponse.\n for (const [entropySourceId] of allPublicKeys) {\n const accessToken = await this.#auth.getAccessToken(entropySourceId);\n accessTokens.push(accessToken);\n }\n\n return accessTokens;\n }\n\n public performSignOut(): void {\n this.update((state) => {\n state.isSignedIn = false;\n state.srpSessionData = undefined;\n });\n }\n\n /**\n * Will return a bearer token.\n * Logs a user in if a user is not logged in.\n *\n * @returns profile for the session.\n */\n\n public async getBearerToken(entropySourceId?: string): Promise<string> {\n this.#assertIsUnlocked('getBearerToken');\n return await this.#auth.getAccessToken(entropySourceId);\n }\n\n /**\n * Will return a session profile.\n * Logs a user in if a user is not logged in.\n *\n * @param entropySourceId - The entropy source ID used to derive the key,\n * when multiple sources are available (Multi-SRP).\n * @returns profile for the session.\n */\n public async getSessionProfile(\n entropySourceId?: string,\n ): Promise<UserProfile> {\n this.#assertIsUnlocked('getSessionProfile');\n return await this.#auth.getUserProfile(entropySourceId);\n }\n\n public async getUserProfileLineage(): Promise<UserProfileLineage> {\n this.#assertIsUnlocked('getUserProfileLineage');\n return await this.#auth.getUserProfileLineage();\n }\n\n public isSignedIn(): boolean {\n return this.state.isSignedIn;\n }\n\n /**\n * Returns the auth snap public key.\n *\n * @param entropySourceId - The entropy source ID used to derive the key,\n * when multiple sources are available (Multi-SRP).\n * @returns The snap public key.\n */\n async #snapGetPublicKey(entropySourceId?: string): Promise<string> {\n this.#assertIsUnlocked('#snapGetPublicKey');\n\n const result = (await this.messenger.call(\n 'SnapController:handleRequest',\n createSnapPublicKeyRequest(entropySourceId),\n )) as string;\n\n return result;\n }\n\n /**\n * Returns a mapping of entropy source IDs to auth snap public keys.\n *\n * @returns A mapping of entropy source IDs to public keys.\n */\n async #snapGetAllPublicKeys(): Promise<[string, string][]> {\n this.#assertIsUnlocked('#snapGetAllPublicKeys');\n\n const result = (await this.messenger.call(\n 'SnapController:handleRequest',\n createSnapAllPublicKeysRequest(),\n )) as [string, string][];\n\n return result;\n }\n\n #_snapSignMessageCache: Record<`metamask:${string}`, string> = {};\n\n /**\n * Signs a specific message using an underlying auth snap.\n *\n * @param message - A specific tagged message to sign.\n * @param entropySourceId - The entropy source ID used to derive the key,\n * when multiple sources are available (Multi-SRP).\n * @returns A Signature created by the snap.\n */\n async #snapSignMessage(\n message: string,\n entropySourceId?: string,\n ): Promise<string> {\n assertMessageStartsWithMetamask(message);\n\n if (this.#_snapSignMessageCache[message]) {\n return this.#_snapSignMessageCache[message];\n }\n\n this.#assertIsUnlocked('#snapSignMessage');\n\n const result = (await this.messenger.call(\n 'SnapController:handleRequest',\n createSnapSignMessageRequest(message, entropySourceId),\n )) as string;\n\n this.#_snapSignMessageCache[message] = result;\n\n return result;\n }\n}\n"]}
|
|
@@ -33,31 +33,31 @@ const metadata = {
|
|
|
33
33
|
isBackupAndSyncEnabled: {
|
|
34
34
|
includeInStateLogs: true,
|
|
35
35
|
persist: true,
|
|
36
|
-
|
|
36
|
+
includeInDebugSnapshot: true,
|
|
37
37
|
usedInUi: true,
|
|
38
38
|
},
|
|
39
39
|
isBackupAndSyncUpdateLoading: {
|
|
40
40
|
includeInStateLogs: false,
|
|
41
41
|
persist: false,
|
|
42
|
-
|
|
42
|
+
includeInDebugSnapshot: false,
|
|
43
43
|
usedInUi: true,
|
|
44
44
|
},
|
|
45
45
|
isAccountSyncingEnabled: {
|
|
46
46
|
includeInStateLogs: true,
|
|
47
47
|
persist: true,
|
|
48
|
-
|
|
48
|
+
includeInDebugSnapshot: true,
|
|
49
49
|
usedInUi: true,
|
|
50
50
|
},
|
|
51
51
|
isContactSyncingEnabled: {
|
|
52
52
|
includeInStateLogs: true,
|
|
53
53
|
persist: true,
|
|
54
|
-
|
|
54
|
+
includeInDebugSnapshot: true,
|
|
55
55
|
usedInUi: true,
|
|
56
56
|
},
|
|
57
57
|
isContactSyncingInProgress: {
|
|
58
58
|
includeInStateLogs: false,
|
|
59
59
|
persist: false,
|
|
60
|
-
|
|
60
|
+
includeInDebugSnapshot: false,
|
|
61
61
|
usedInUi: true,
|
|
62
62
|
},
|
|
63
63
|
};
|
|
@@ -81,14 +81,14 @@ class UserStorageController extends base_controller_1.BaseController {
|
|
|
81
81
|
_UserStorageController_userStorage.set(this, void 0);
|
|
82
82
|
_UserStorageController_auth.set(this, {
|
|
83
83
|
getProfileId: async (entropySourceId) => {
|
|
84
|
-
const sessionProfile = await this.
|
|
84
|
+
const sessionProfile = await this.messenger.call('AuthenticationController:getSessionProfile', entropySourceId);
|
|
85
85
|
return sessionProfile?.profileId;
|
|
86
86
|
},
|
|
87
87
|
isSignedIn: () => {
|
|
88
|
-
return this.
|
|
88
|
+
return this.messenger.call('AuthenticationController:isSignedIn');
|
|
89
89
|
},
|
|
90
90
|
signIn: async () => {
|
|
91
|
-
return await this.
|
|
91
|
+
return await this.messenger.call('AuthenticationController:performSignIn');
|
|
92
92
|
},
|
|
93
93
|
});
|
|
94
94
|
_UserStorageController_config.set(this, {
|
|
@@ -99,12 +99,12 @@ class UserStorageController extends base_controller_1.BaseController {
|
|
|
99
99
|
_UserStorageController_storageKeyCache.set(this, {});
|
|
100
100
|
_UserStorageController_keyringController.set(this, {
|
|
101
101
|
setupLockedStateSubscriptions: () => {
|
|
102
|
-
const { isUnlocked } = this.
|
|
102
|
+
const { isUnlocked } = this.messenger.call('KeyringController:getState');
|
|
103
103
|
__classPrivateFieldSet(this, _UserStorageController_isUnlocked, isUnlocked, "f");
|
|
104
|
-
this.
|
|
104
|
+
this.messenger.subscribe('KeyringController:unlock', () => {
|
|
105
105
|
__classPrivateFieldSet(this, _UserStorageController_isUnlocked, true, "f");
|
|
106
106
|
});
|
|
107
|
-
this.
|
|
107
|
+
this.messenger.subscribe('KeyringController:lock', () => {
|
|
108
108
|
__classPrivateFieldSet(this, _UserStorageController_isUnlocked, false, "f");
|
|
109
109
|
});
|
|
110
110
|
},
|
|
@@ -126,9 +126,9 @@ class UserStorageController extends base_controller_1.BaseController {
|
|
|
126
126
|
__classPrivateFieldSet(this, _UserStorageController_userStorage, new sdk_1.UserStorage({
|
|
127
127
|
env: __classPrivateFieldGet(this, _UserStorageController_config, "f").env,
|
|
128
128
|
auth: {
|
|
129
|
-
getAccessToken: (entropySourceId) => this.
|
|
129
|
+
getAccessToken: (entropySourceId) => this.messenger.call('AuthenticationController:getBearerToken', entropySourceId),
|
|
130
130
|
getUserProfile: async (entropySourceId) => {
|
|
131
|
-
return await this.
|
|
131
|
+
return await this.messenger.call('AuthenticationController:getSessionProfile', entropySourceId);
|
|
132
132
|
},
|
|
133
133
|
signMessage: (message, entropySourceId) => __classPrivateFieldGet(this, _UserStorageController_instances, "m", _UserStorageController_snapSignMessage).call(this, message, entropySourceId),
|
|
134
134
|
},
|
|
@@ -146,7 +146,7 @@ class UserStorageController extends base_controller_1.BaseController {
|
|
|
146
146
|
// Contact Syncing
|
|
147
147
|
(0, setup_subscriptions_1.setupContactSyncingSubscriptions)({
|
|
148
148
|
getUserStorageControllerInstance: () => this,
|
|
149
|
-
getMessenger: () => this.
|
|
149
|
+
getMessenger: () => this.messenger,
|
|
150
150
|
trace: __classPrivateFieldGet(this, _UserStorageController_trace, "f"),
|
|
151
151
|
});
|
|
152
152
|
}
|
|
@@ -276,7 +276,7 @@ class UserStorageController extends base_controller_1.BaseController {
|
|
|
276
276
|
if (!__classPrivateFieldGet(this, _UserStorageController_isUnlocked, "f")) {
|
|
277
277
|
throw new Error('listEntropySources - unable to list entropy sources, wallet is locked');
|
|
278
278
|
}
|
|
279
|
-
const { keyrings } = this.
|
|
279
|
+
const { keyrings } = this.messenger.call('KeyringController:getState');
|
|
280
280
|
return keyrings
|
|
281
281
|
.filter((keyring) => keyring.type === keyring_controller_1.KeyringTypes.hd.toString())
|
|
282
282
|
.map((keyring) => keyring.metadata.id);
|
|
@@ -342,20 +342,20 @@ class UserStorageController extends base_controller_1.BaseController {
|
|
|
342
342
|
},
|
|
343
343
|
};
|
|
344
344
|
await (0, controller_integration_1.syncContactsWithUserStorage)(config, {
|
|
345
|
-
getMessenger: () => this.
|
|
345
|
+
getMessenger: () => this.messenger,
|
|
346
346
|
getUserStorageControllerInstance: () => this,
|
|
347
347
|
trace: __classPrivateFieldGet(this, _UserStorageController_trace, "f"),
|
|
348
348
|
});
|
|
349
349
|
}
|
|
350
350
|
}
|
|
351
351
|
_UserStorageController_userStorage = new WeakMap(), _UserStorageController_auth = new WeakMap(), _UserStorageController_config = new WeakMap(), _UserStorageController_trace = new WeakMap(), _UserStorageController_isUnlocked = new WeakMap(), _UserStorageController_storageKeyCache = new WeakMap(), _UserStorageController_keyringController = new WeakMap(), _UserStorageController_nativeScryptCrypto = new WeakMap(), _UserStorageController__snapSignMessageCache = new WeakMap(), _UserStorageController_instances = new WeakSet(), _UserStorageController_registerMessageHandlers = function _UserStorageController_registerMessageHandlers() {
|
|
352
|
-
this.
|
|
353
|
-
this.
|
|
354
|
-
this.
|
|
355
|
-
this.
|
|
356
|
-
this.
|
|
357
|
-
this.
|
|
358
|
-
this.
|
|
352
|
+
this.messenger.registerActionHandler('UserStorageController:performGetStorage', this.performGetStorage.bind(this));
|
|
353
|
+
this.messenger.registerActionHandler('UserStorageController:performGetStorageAllFeatureEntries', this.performGetStorageAllFeatureEntries.bind(this));
|
|
354
|
+
this.messenger.registerActionHandler('UserStorageController:performSetStorage', this.performSetStorage.bind(this));
|
|
355
|
+
this.messenger.registerActionHandler('UserStorageController:performBatchSetStorage', this.performBatchSetStorage.bind(this));
|
|
356
|
+
this.messenger.registerActionHandler('UserStorageController:performDeleteStorage', this.performDeleteStorage.bind(this));
|
|
357
|
+
this.messenger.registerActionHandler('UserStorageController:performBatchDeleteStorage', this.performBatchDeleteStorage.bind(this));
|
|
358
|
+
this.messenger.registerActionHandler('UserStorageController:getStorageKey', this.getStorageKey.bind(this));
|
|
359
359
|
}, _UserStorageController_snapSignMessage =
|
|
360
360
|
/**
|
|
361
361
|
* Signs a specific message using an underlying auth snap.
|
|
@@ -373,7 +373,7 @@ async function _UserStorageController_snapSignMessage(message, entropySourceId)
|
|
|
373
373
|
if (!__classPrivateFieldGet(this, _UserStorageController_isUnlocked, "f")) {
|
|
374
374
|
throw new Error('#snapSignMessage - unable to call snap, wallet is locked');
|
|
375
375
|
}
|
|
376
|
-
const result = (await this.
|
|
376
|
+
const result = (await this.messenger.call('SnapController:handleRequest', (0, auth_snap_requests_1.createSnapSignMessageRequest)(message, entropySourceId)));
|
|
377
377
|
__classPrivateFieldGet(this, _UserStorageController__snapSignMessageCache, "f")[message] = result;
|
|
378
378
|
return result;
|
|
379
379
|
}, _UserStorageController_setIsBackupAndSyncUpdateLoading = function _UserStorageController_setIsBackupAndSyncUpdateLoading(isBackupAndSyncUpdateLoading) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"UserStorageController.cjs","sourceRoot":"","sources":["../../../src/controllers/user-storage/UserStorageController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAcA,+DAA2D;AAM3D,qEAKsC;AAGtC,+CAAqD;AACrD,yFAAuF;AACvF,mFAAyF;AAMzF,6CAA6C;AAE7C,oEAA4D;AAC5D,iFAAoF;AAQpF,MAAM,cAAc,GAAG,uBAAuB,CAAC;AA0BlC,QAAA,YAAY,GAA+B;IACtD,sBAAsB,EAAE,IAAI;IAC5B,4BAA4B,EAAE,KAAK;IACnC,uBAAuB,EAAE,IAAI;IAC7B,uBAAuB,EAAE,IAAI;IAC7B,0BAA0B,EAAE,KAAK;CAClC,CAAC;AAEF,MAAM,QAAQ,GAA8C;IAC1D,sBAAsB,EAAE;QACtB,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,IAAI;QACf,QAAQ,EAAE,IAAI;KACf;IACD,4BAA4B,EAAE;QAC5B,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,KAAK;QACd,SAAS,EAAE,KAAK;QAChB,QAAQ,EAAE,IAAI;KACf;IACD,uBAAuB,EAAE;QACvB,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,IAAI;QACf,QAAQ,EAAE,IAAI;KACf;IACD,uBAAuB,EAAE;QACvB,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,IAAI;QACf,QAAQ,EAAE,IAAI;KACf;IACD,0BAA0B,EAAE;QAC1B,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,KAAK;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KAC7C;IAED,IAAI,CAAC,uBAAA,IAAI,yCAAY,EAAE;QACrB,MAAM,IAAI,KAAK,CACb,0DAA0D,CAC3D,CAAC;KACH;IAED,MAAM,MAAM,GAAG,CAAC,MAAM,IAAI,CAAC,eAAe,CAAC,IAAI,CAC7C,8BAA8B,EAC9B,IAAA,iDAA4B,EAAC,OAAO,EAAE,eAAe,CAAC,CACvD,CAAW,CAAC;IAEb,uBAAA,IAAI,oDAAuB,CAAC,OAAO,CAAC,GAAG,MAAM,CAAC;IAE9C,OAAO,MAAM,CAAC;AAChB,CAAC,2HA2CC,4BAAqC;IAErC,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,4BAA4B,GAAG,4BAA4B,CAAC;IACpE,CAAC,CAAC,CAAC;AACL,CAAC;kBA7akB,qBAAqB","sourcesContent":["import type {\n AddressBookControllerContactUpdatedEvent,\n AddressBookControllerContactDeletedEvent,\n AddressBookControllerActions,\n AddressBookControllerListAction,\n AddressBookControllerSetAction,\n AddressBookControllerDeleteAction,\n} from '@metamask/address-book-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedMessenger,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type {\n TraceCallback,\n TraceContext,\n TraceRequest,\n} from '@metamask/controller-utils';\nimport {\n KeyringTypes,\n type KeyringControllerGetStateAction,\n type KeyringControllerLockEvent,\n type KeyringControllerUnlockEvent,\n} from '@metamask/keyring-controller';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\n\nimport { BACKUPANDSYNC_FEATURES } from './constants';\nimport { syncContactsWithUserStorage } from './contact-syncing/controller-integration';\nimport { setupContactSyncingSubscriptions } from './contact-syncing/setup-subscriptions';\nimport type {\n UserStorageGenericFeatureKey,\n UserStorageGenericPathWithFeatureAndKey,\n UserStorageGenericPathWithFeatureOnly,\n} from '../../sdk';\nimport { Env, UserStorage } from '../../sdk';\nimport type { NativeScrypt } from '../../shared/types/encryption';\nimport { EventQueue } from '../../shared/utils/event-queue';\nimport { createSnapSignMessageRequest } from '../authentication/auth-snap-requests';\nimport type {\n AuthenticationControllerGetBearerToken,\n AuthenticationControllerGetSessionProfile,\n AuthenticationControllerIsSignedIn,\n AuthenticationControllerPerformSignIn,\n} from '../authentication/AuthenticationController';\n\nconst controllerName = 'UserStorageController';\n\n// State\nexport type UserStorageControllerState = {\n /**\n * Condition used by UI and to determine if we can use some of the User Storage methods.\n */\n isBackupAndSyncEnabled: boolean;\n /**\n * Loading state for the backup and sync update\n */\n isBackupAndSyncUpdateLoading: boolean;\n /**\n * Condition used by UI to determine if account syncing is enabled.\n */\n isAccountSyncingEnabled: boolean;\n /**\n * Condition used by UI to determine if contact syncing is enabled.\n */\n isContactSyncingEnabled: boolean;\n /**\n * Condition used by UI to determine if contact syncing is in progress.\n */\n isContactSyncingInProgress: boolean;\n};\n\nexport const defaultState: UserStorageControllerState = {\n isBackupAndSyncEnabled: true,\n isBackupAndSyncUpdateLoading: false,\n isAccountSyncingEnabled: true,\n isContactSyncingEnabled: true,\n isContactSyncingInProgress: false,\n};\n\nconst metadata: StateMetadata<UserStorageControllerState> = {\n isBackupAndSyncEnabled: {\n includeInStateLogs: true,\n persist: true,\n anonymous: true,\n usedInUi: true,\n },\n isBackupAndSyncUpdateLoading: {\n includeInStateLogs: false,\n persist: false,\n anonymous: false,\n usedInUi: true,\n },\n isAccountSyncingEnabled: {\n includeInStateLogs: true,\n persist: true,\n anonymous: true,\n usedInUi: true,\n },\n isContactSyncingEnabled: {\n includeInStateLogs: true,\n persist: true,\n anonymous: true,\n usedInUi: true,\n },\n isContactSyncingInProgress: {\n includeInStateLogs: false,\n persist: false,\n anonymous: false,\n usedInUi: true,\n },\n};\n\ntype ControllerConfig = {\n env: Env;\n contactSyncing?: {\n /**\n * Callback that fires when contact sync updates a contact.\n * This is used for analytics.\n */\n onContactUpdated?: (profileId: string) => void;\n\n /**\n * Callback that fires when contact sync deletes a contact.\n * This is used for analytics.\n */\n onContactDeleted?: (profileId: string) => void;\n\n /**\n * Callback that fires when an erroneous situation happens during contact sync.\n * This is used for analytics.\n */\n onContactSyncErroneousSituation?: (\n profileId: string,\n situationMessage: string,\n sentryContext?: Record<string, unknown>,\n ) => void;\n };\n};\n\n// Messenger Actions\ntype CreateActionsObj<Controller extends keyof UserStorageController> = {\n [K in Controller]: {\n type: `${typeof controllerName}:${K}`;\n handler: UserStorageController[K];\n };\n};\ntype ActionsObj = CreateActionsObj<\n | 'performGetStorage'\n | 'performGetStorageAllFeatureEntries'\n | 'performSetStorage'\n | 'performBatchSetStorage'\n | 'performDeleteStorage'\n | 'performBatchDeleteStorage'\n | 'getStorageKey'\n>;\nexport type UserStorageControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n UserStorageControllerState\n>;\nexport type Actions =\n | ActionsObj[keyof ActionsObj]\n | UserStorageControllerGetStateAction;\nexport type UserStorageControllerPerformGetStorage =\n ActionsObj['performGetStorage'];\nexport type UserStorageControllerPerformGetStorageAllFeatureEntries =\n ActionsObj['performGetStorageAllFeatureEntries'];\nexport type UserStorageControllerPerformSetStorage =\n ActionsObj['performSetStorage'];\nexport type UserStorageControllerPerformBatchSetStorage =\n ActionsObj['performBatchSetStorage'];\nexport type UserStorageControllerPerformDeleteStorage =\n ActionsObj['performDeleteStorage'];\nexport type UserStorageControllerPerformBatchDeleteStorage =\n ActionsObj['performBatchDeleteStorage'];\nexport type UserStorageControllerGetStorageKey = ActionsObj['getStorageKey'];\n\nexport type AllowedActions =\n // Keyring Requests\n | KeyringControllerGetStateAction\n // Snap Requests\n | HandleSnapRequest\n // Auth Requests\n | AuthenticationControllerGetBearerToken\n | AuthenticationControllerGetSessionProfile\n | AuthenticationControllerPerformSignIn\n | AuthenticationControllerIsSignedIn\n // Contact Syncing\n | AddressBookControllerListAction\n | AddressBookControllerSetAction\n | AddressBookControllerDeleteAction\n | AddressBookControllerActions;\n\n// Messenger events\nexport type UserStorageControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n UserStorageControllerState\n>;\n\nexport type Events = UserStorageControllerStateChangeEvent;\n\nexport type AllowedEvents =\n | UserStorageControllerStateChangeEvent\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent\n // Address Book Events\n | AddressBookControllerContactUpdatedEvent\n | AddressBookControllerContactDeletedEvent;\n\n// Messenger\nexport type UserStorageControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n Actions | AllowedActions,\n Events | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Reusable controller that allows any team to store synchronized data for a given user.\n * These can be settings shared cross MetaMask clients, or data we want to persist when uninstalling/reinstalling.\n *\n * NOTE:\n * - data stored on UserStorage is FULLY encrypted, with the only keys stored/managed on the client.\n * - No one can access this data unless they are have the SRP and are able to run the signing snap.\n */\nexport default class UserStorageController extends BaseController<\n typeof controllerName,\n UserStorageControllerState,\n UserStorageControllerMessenger\n> {\n readonly #userStorage: UserStorage;\n\n readonly #auth = {\n getProfileId: async (entropySourceId?: string) => {\n const sessionProfile = await this.messagingSystem.call(\n 'AuthenticationController:getSessionProfile',\n entropySourceId,\n );\n return sessionProfile?.profileId;\n },\n isSignedIn: () => {\n return this.messagingSystem.call('AuthenticationController:isSignedIn');\n },\n signIn: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:performSignIn',\n );\n },\n };\n\n readonly #config: ControllerConfig = {\n env: Env.PRD,\n };\n\n readonly #trace: TraceCallback;\n\n #isUnlocked = false;\n\n #storageKeyCache: Record<`metamask:${string}`, string> = {};\n\n readonly #keyringController = {\n setupLockedStateSubscriptions: () => {\n const { isUnlocked } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n this.#isUnlocked = isUnlocked;\n\n this.messagingSystem.subscribe('KeyringController:unlock', () => {\n this.#isUnlocked = true;\n });\n\n this.messagingSystem.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n },\n };\n\n readonly #nativeScryptCrypto: NativeScrypt | undefined = undefined;\n\n eventQueue = new EventQueue();\n\n constructor({\n messenger,\n state,\n config,\n nativeScryptCrypto,\n trace,\n }: {\n messenger: UserStorageControllerMessenger;\n state?: UserStorageControllerState;\n config?: Partial<ControllerConfig>;\n nativeScryptCrypto?: NativeScrypt;\n trace?: TraceCallback;\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n this.#config = {\n ...this.#config,\n ...config,\n };\n this.#trace =\n trace ??\n (async <ReturnType>(\n _request: TraceRequest,\n fn?: (context?: TraceContext) => ReturnType,\n ): Promise<ReturnType> => {\n if (!fn) {\n return undefined as ReturnType;\n }\n return await Promise.resolve(fn());\n });\n\n this.#userStorage = new UserStorage(\n {\n env: this.#config.env,\n auth: {\n getAccessToken: (entropySourceId?: string) =>\n this.messagingSystem.call(\n 'AuthenticationController:getBearerToken',\n entropySourceId,\n ),\n getUserProfile: async (entropySourceId?: string) => {\n return await this.messagingSystem.call(\n 'AuthenticationController:getSessionProfile',\n entropySourceId,\n );\n },\n signMessage: (message: string, entropySourceId?: string) =>\n this.#snapSignMessage(\n message as `metamask:${string}`,\n entropySourceId,\n ),\n },\n },\n {\n storage: {\n getStorageKey: async (message) =>\n this.#storageKeyCache[message] ?? null,\n setStorageKey: async (message, key) => {\n this.#storageKeyCache[message] = key;\n },\n },\n },\n );\n\n this.#keyringController.setupLockedStateSubscriptions();\n this.#registerMessageHandlers();\n this.#nativeScryptCrypto = nativeScryptCrypto;\n\n // Contact Syncing\n setupContactSyncingSubscriptions({\n getUserStorageControllerInstance: () => this,\n getMessenger: () => this.messagingSystem,\n trace: this.#trace,\n });\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performGetStorage',\n this.performGetStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performGetStorageAllFeatureEntries',\n this.performGetStorageAllFeatureEntries.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performSetStorage',\n this.performSetStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performBatchSetStorage',\n this.performBatchSetStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performDeleteStorage',\n this.performDeleteStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performBatchDeleteStorage',\n this.performBatchDeleteStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:getStorageKey',\n this.getStorageKey.bind(this),\n );\n }\n\n /**\n * Allows retrieval of stored data. Data stored is string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns the decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorage(\n path: UserStorageGenericPathWithFeatureAndKey,\n entropySourceId?: string,\n ): Promise<string | null> {\n return await this.#userStorage.getItem(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Allows retrieval of all stored data for a specific feature. Data stored is formatted as an array of strings.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns the array of decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorageAllFeatureEntries(\n path: UserStorageGenericPathWithFeatureOnly,\n entropySourceId?: string,\n ): Promise<string[] | null> {\n return await this.#userStorage.getAllFeatureItems(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Allows storage of user data. Data stored must be string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param value - The string data you want to store.\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performSetStorage(\n path: UserStorageGenericPathWithFeatureAndKey,\n value: string,\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.setItem(path, value, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Allows storage of multiple user data entries for one specific feature. Data stored must be string formatted.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @param values - data to store, in the form of an array of `[entryKey, entryValue]` pairs\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performBatchSetStorage(\n path: UserStorageGenericPathWithFeatureOnly,\n values: [UserStorageGenericFeatureKey, string][],\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.batchSetItems(path, values, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Allows deletion of user data. Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to delete data.\n */\n public async performDeleteStorage(\n path: UserStorageGenericPathWithFeatureAndKey,\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.deleteItem(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Allows deletion of all user data entries for a specific feature.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to delete data.\n */\n public async performDeleteStorageAllFeatureEntries(\n path: UserStorageGenericPathWithFeatureOnly,\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.deleteAllFeatureItems(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Allows delete of multiple user data entries for one specific feature. Data deleted must be string formatted.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @param values - data to store, in the form of an array of entryKey[]\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performBatchDeleteStorage(\n path: UserStorageGenericPathWithFeatureOnly,\n values: UserStorageGenericFeatureKey[],\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.batchDeleteItems(path, values, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Retrieves the storage key, for internal use only!\n *\n * @returns the storage key\n */\n public async getStorageKey(): Promise<string> {\n return await this.#userStorage.getStorageKey();\n }\n\n /**\n * Flushes the storage key cache.\n * CAUTION: This is only public for testing purposes.\n * It should not be used in production code.\n */\n public flushStorageKeyCache(): void {\n this.#storageKeyCache = {};\n }\n\n /**\n * Lists all the available HD keyring metadata IDs.\n * These IDs can be used in a multi-SRP context to segregate data specific to different SRPs.\n *\n * @returns A promise that resolves to an array of HD keyring metadata IDs.\n */\n async listEntropySources() {\n if (!this.#isUnlocked) {\n throw new Error(\n 'listEntropySources - unable to list entropy sources, wallet is locked',\n );\n }\n\n const { keyrings } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n return keyrings\n .filter((keyring) => keyring.type === KeyringTypes.hd.toString())\n .map((keyring) => keyring.metadata.id);\n }\n\n #_snapSignMessageCache: Record<`metamask:${string}`, string> = {};\n\n /**\n * Signs a specific message using an underlying auth snap.\n *\n * @param message - A specific tagged message to sign.\n * @param entropySourceId - The entropy source ID used to derive the key,\n * when multiple sources are available (Multi-SRP).\n * @returns A Signature created by the snap.\n */\n async #snapSignMessage(\n message: `metamask:${string}`,\n entropySourceId?: string,\n ): Promise<string> {\n // the message is SRP specific already, so there's no need to use the entropySourceId in the cache\n if (this.#_snapSignMessageCache[message]) {\n return this.#_snapSignMessageCache[message];\n }\n\n if (!this.#isUnlocked) {\n throw new Error(\n '#snapSignMessage - unable to call snap, wallet is locked',\n );\n }\n\n const result = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n createSnapSignMessageRequest(message, entropySourceId),\n )) as string;\n\n this.#_snapSignMessageCache[message] = result;\n\n return result;\n }\n\n public async setIsBackupAndSyncFeatureEnabled(\n feature: keyof typeof BACKUPANDSYNC_FEATURES,\n enabled: boolean,\n ): Promise<void> {\n try {\n this.#setIsBackupAndSyncUpdateLoading(true);\n\n if (enabled) {\n // If any of the features are enabled, we need to ensure the user is signed in\n const isSignedIn = this.#auth.isSignedIn();\n if (!isSignedIn) {\n await this.#auth.signIn();\n }\n }\n\n this.update((state) => {\n if (feature === BACKUPANDSYNC_FEATURES.main) {\n state.isBackupAndSyncEnabled = enabled;\n }\n\n if (feature === BACKUPANDSYNC_FEATURES.accountSyncing) {\n state.isAccountSyncingEnabled = enabled;\n }\n\n if (feature === BACKUPANDSYNC_FEATURES.contactSyncing) {\n state.isContactSyncingEnabled = enabled;\n }\n });\n } catch (e) {\n // istanbul ignore next\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n // istanbul ignore next\n throw new Error(\n `${controllerName} - failed to ${enabled ? 'enable' : 'disable'} ${feature} - ${errorMessage}`,\n );\n } finally {\n this.#setIsBackupAndSyncUpdateLoading(false);\n }\n }\n\n #setIsBackupAndSyncUpdateLoading(\n isBackupAndSyncUpdateLoading: boolean,\n ): void {\n this.update((state) => {\n state.isBackupAndSyncUpdateLoading = isBackupAndSyncUpdateLoading;\n });\n }\n\n /**\n * Sets the isContactSyncingInProgress flag to prevent infinite loops during contact synchronization\n *\n * @param isContactSyncingInProgress - Whether contact syncing is in progress\n */\n async setIsContactSyncingInProgress(\n isContactSyncingInProgress: boolean,\n ): Promise<void> {\n this.update((state) => {\n state.isContactSyncingInProgress = isContactSyncingInProgress;\n });\n }\n\n /**\n * Syncs the address book list with the user storage address book list.\n * This method is used to make sure that the address book list is up-to-date with the user storage address book list and vice-versa.\n * It will add new contacts to the address book list, update/merge conflicting contacts and re-upload the results in some cases to the user storage.\n */\n async syncContactsWithUserStorage(): Promise<void> {\n const profileId = await this.#auth.getProfileId();\n\n const config = {\n onContactUpdated: () => {\n this.#config?.contactSyncing?.onContactUpdated?.(profileId);\n },\n onContactDeleted: () => {\n this.#config?.contactSyncing?.onContactDeleted?.(profileId);\n },\n onContactSyncErroneousSituation: (\n errorMessage: string,\n sentryContext?: Record<string, unknown>,\n ) => {\n this.#config?.contactSyncing?.onContactSyncErroneousSituation?.(\n profileId,\n errorMessage,\n sentryContext,\n );\n },\n };\n\n await syncContactsWithUserStorage(config, {\n getMessenger: () => this.messagingSystem,\n getUserStorageControllerInstance: () => this,\n trace: this.#trace,\n });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"UserStorageController.cjs","sourceRoot":"","sources":["../../../src/controllers/user-storage/UserStorageController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAQA,+DAKmC;AAMnC,qEAKsC;AAItC,+CAAqD;AACrD,yFAAuF;AACvF,mFAAyF;AAMzF,6CAA6C;AAE7C,oEAA4D;AAC5D,iFAAoF;AAQpF,MAAM,cAAc,GAAG,uBAAuB,CAAC;AA0BlC,QAAA,YAAY,GAA+B;IACtD,sBAAsB,EAAE,IAAI;IAC5B,4BAA4B,EAAE,KAAK;IACnC,uBAAuB,EAAE,IAAI;IAC7B,uBAAuB,EAAE,IAAI;IAC7B,0BAA0B,EAAE,KAAK;CAClC,CAAC;AAEF,MAAM,QAAQ,GAA8C;IAC1D,sBAAsB,EAAE;QACtB,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,IAAI;KACf;IACD,4BAA4B,EAAE;QAC5B,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,KAAK;QACd,sBAAsB,EAAE,KAAK;QAC7B,QAAQ,EAAE,IAA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AC1C,CAAC;IAEF,IAAI,CAAC,SAAS,CAAC,qBAAqB,CAClC,qCAAqC,EACrC,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,CAC9B,CAAC;AACJ,CAAC;AA4KD;;;;;;;GAOG;AACH,KAAK,iDACH,OAA6B,EAC7B,eAAwB;IAExB,kGAAkG;IAClG,IAAI,uBAAA,IAAI,oDAAuB,CAAC,OAAO,CAAC,EAAE;QACxC,OAAO,uBAAA,IAAI,oDAAuB,CAAC,OAAO,CAAC,CAAC;KAC7C;IAED,IAAI,CAAC,uBAAA,IAAI,yCAAY,EAAE;QACrB,MAAM,IAAI,KAAK,CACb,0DAA0D,CAC3D,CAAC;KACH;IAED,MAAM,MAAM,GAAG,CAAC,MAAM,IAAI,CAAC,SAAS,CAAC,IAAI,CACvC,8BAA8B,EAC9B,IAAA,iDAA4B,EAAC,OAAO,EAAE,eAAe,CAAC,CACvD,CAAW,CAAC;IAEb,uBAAA,IAAI,oDAAuB,CAAC,OAAO,CAAC,GAAG,MAAM,CAAC;IAE9C,OAAO,MAAM,CAAC;AAChB,CAAC,2HA2CC,4BAAqC;IAErC,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,4BAA4B,GAAG,4BAA4B,CAAC;IACpE,CAAC,CAAC,CAAC;AACL,CAAC;kBAzakB,qBAAqB","sourcesContent":["import type {\n AddressBookControllerContactUpdatedEvent,\n AddressBookControllerContactDeletedEvent,\n AddressBookControllerActions,\n AddressBookControllerListAction,\n AddressBookControllerSetAction,\n AddressBookControllerDeleteAction,\n} from '@metamask/address-book-controller';\nimport {\n BaseController,\n type ControllerGetStateAction,\n type ControllerStateChangeEvent,\n type StateMetadata,\n} from '@metamask/base-controller';\nimport type {\n TraceCallback,\n TraceContext,\n TraceRequest,\n} from '@metamask/controller-utils';\nimport {\n KeyringTypes,\n type KeyringControllerGetStateAction,\n type KeyringControllerLockEvent,\n type KeyringControllerUnlockEvent,\n} from '@metamask/keyring-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\n\nimport { BACKUPANDSYNC_FEATURES } from './constants';\nimport { syncContactsWithUserStorage } from './contact-syncing/controller-integration';\nimport { setupContactSyncingSubscriptions } from './contact-syncing/setup-subscriptions';\nimport type {\n UserStorageGenericFeatureKey,\n UserStorageGenericPathWithFeatureAndKey,\n UserStorageGenericPathWithFeatureOnly,\n} from '../../sdk';\nimport { Env, UserStorage } from '../../sdk';\nimport type { NativeScrypt } from '../../shared/types/encryption';\nimport { EventQueue } from '../../shared/utils/event-queue';\nimport { createSnapSignMessageRequest } from '../authentication/auth-snap-requests';\nimport type {\n AuthenticationControllerGetBearerToken,\n AuthenticationControllerGetSessionProfile,\n AuthenticationControllerIsSignedIn,\n AuthenticationControllerPerformSignIn,\n} from '../authentication/AuthenticationController';\n\nconst controllerName = 'UserStorageController';\n\n// State\nexport type UserStorageControllerState = {\n /**\n * Condition used by UI and to determine if we can use some of the User Storage methods.\n */\n isBackupAndSyncEnabled: boolean;\n /**\n * Loading state for the backup and sync update\n */\n isBackupAndSyncUpdateLoading: boolean;\n /**\n * Condition used by UI to determine if account syncing is enabled.\n */\n isAccountSyncingEnabled: boolean;\n /**\n * Condition used by UI to determine if contact syncing is enabled.\n */\n isContactSyncingEnabled: boolean;\n /**\n * Condition used by UI to determine if contact syncing is in progress.\n */\n isContactSyncingInProgress: boolean;\n};\n\nexport const defaultState: UserStorageControllerState = {\n isBackupAndSyncEnabled: true,\n isBackupAndSyncUpdateLoading: false,\n isAccountSyncingEnabled: true,\n isContactSyncingEnabled: true,\n isContactSyncingInProgress: false,\n};\n\nconst metadata: StateMetadata<UserStorageControllerState> = {\n isBackupAndSyncEnabled: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n isBackupAndSyncUpdateLoading: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n isAccountSyncingEnabled: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n isContactSyncingEnabled: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n isContactSyncingInProgress: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n};\n\ntype ControllerConfig = {\n env: Env;\n contactSyncing?: {\n /**\n * Callback that fires when contact sync updates a contact.\n * This is used for analytics.\n */\n onContactUpdated?: (profileId: string) => void;\n\n /**\n * Callback that fires when contact sync deletes a contact.\n * This is used for analytics.\n */\n onContactDeleted?: (profileId: string) => void;\n\n /**\n * Callback that fires when an erroneous situation happens during contact sync.\n * This is used for analytics.\n */\n onContactSyncErroneousSituation?: (\n profileId: string,\n situationMessage: string,\n sentryContext?: Record<string, unknown>,\n ) => void;\n };\n};\n\n// Messenger Actions\ntype CreateActionsObj<Controller extends keyof UserStorageController> = {\n [K in Controller]: {\n type: `${typeof controllerName}:${K}`;\n handler: UserStorageController[K];\n };\n};\ntype ActionsObj = CreateActionsObj<\n | 'performGetStorage'\n | 'performGetStorageAllFeatureEntries'\n | 'performSetStorage'\n | 'performBatchSetStorage'\n | 'performDeleteStorage'\n | 'performBatchDeleteStorage'\n | 'getStorageKey'\n>;\nexport type UserStorageControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n UserStorageControllerState\n>;\nexport type Actions =\n | ActionsObj[keyof ActionsObj]\n | UserStorageControllerGetStateAction;\nexport type UserStorageControllerPerformGetStorage =\n ActionsObj['performGetStorage'];\nexport type UserStorageControllerPerformGetStorageAllFeatureEntries =\n ActionsObj['performGetStorageAllFeatureEntries'];\nexport type UserStorageControllerPerformSetStorage =\n ActionsObj['performSetStorage'];\nexport type UserStorageControllerPerformBatchSetStorage =\n ActionsObj['performBatchSetStorage'];\nexport type UserStorageControllerPerformDeleteStorage =\n ActionsObj['performDeleteStorage'];\nexport type UserStorageControllerPerformBatchDeleteStorage =\n ActionsObj['performBatchDeleteStorage'];\nexport type UserStorageControllerGetStorageKey = ActionsObj['getStorageKey'];\n\nexport type AllowedActions =\n // Keyring Requests\n | KeyringControllerGetStateAction\n // Snap Requests\n | HandleSnapRequest\n // Auth Requests\n | AuthenticationControllerGetBearerToken\n | AuthenticationControllerGetSessionProfile\n | AuthenticationControllerPerformSignIn\n | AuthenticationControllerIsSignedIn\n // Contact Syncing\n | AddressBookControllerListAction\n | AddressBookControllerSetAction\n | AddressBookControllerDeleteAction\n | AddressBookControllerActions;\n\n// Messenger events\nexport type UserStorageControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n UserStorageControllerState\n>;\n\nexport type Events = UserStorageControllerStateChangeEvent;\n\nexport type AllowedEvents =\n | UserStorageControllerStateChangeEvent\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent\n // Address Book Events\n | AddressBookControllerContactUpdatedEvent\n | AddressBookControllerContactDeletedEvent;\n\n// Messenger\nexport type UserStorageControllerMessenger = Messenger<\n typeof controllerName,\n Actions | AllowedActions,\n Events | AllowedEvents\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 readonly #userStorage: UserStorage;\n\n readonly #auth = {\n getProfileId: async (entropySourceId?: string) => {\n const sessionProfile = await this.messenger.call(\n 'AuthenticationController:getSessionProfile',\n entropySourceId,\n );\n return sessionProfile?.profileId;\n },\n isSignedIn: () => {\n return this.messenger.call('AuthenticationController:isSignedIn');\n },\n signIn: async () => {\n return await this.messenger.call(\n 'AuthenticationController:performSignIn',\n );\n },\n };\n\n readonly #config: ControllerConfig = {\n env: Env.PRD,\n };\n\n readonly #trace: TraceCallback;\n\n #isUnlocked = false;\n\n #storageKeyCache: Record<`metamask:${string}`, string> = {};\n\n readonly #keyringController = {\n setupLockedStateSubscriptions: () => {\n const { isUnlocked } = this.messenger.call('KeyringController:getState');\n this.#isUnlocked = isUnlocked;\n\n this.messenger.subscribe('KeyringController:unlock', () => {\n this.#isUnlocked = true;\n });\n\n this.messenger.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n },\n };\n\n readonly #nativeScryptCrypto: NativeScrypt | undefined = undefined;\n\n eventQueue = new EventQueue();\n\n constructor({\n messenger,\n state,\n config,\n nativeScryptCrypto,\n trace,\n }: {\n messenger: UserStorageControllerMessenger;\n state?: UserStorageControllerState;\n config?: Partial<ControllerConfig>;\n nativeScryptCrypto?: NativeScrypt;\n trace?: TraceCallback;\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n this.#config = {\n ...this.#config,\n ...config,\n };\n this.#trace =\n trace ??\n (async <ReturnType>(\n _request: TraceRequest,\n fn?: (context?: TraceContext) => ReturnType,\n ): Promise<ReturnType> => {\n if (!fn) {\n return undefined as ReturnType;\n }\n return await Promise.resolve(fn());\n });\n\n this.#userStorage = new UserStorage(\n {\n env: this.#config.env,\n auth: {\n getAccessToken: (entropySourceId?: string) =>\n this.messenger.call(\n 'AuthenticationController:getBearerToken',\n entropySourceId,\n ),\n getUserProfile: async (entropySourceId?: string) => {\n return await this.messenger.call(\n 'AuthenticationController:getSessionProfile',\n entropySourceId,\n );\n },\n signMessage: (message: string, entropySourceId?: string) =>\n this.#snapSignMessage(\n message as `metamask:${string}`,\n entropySourceId,\n ),\n },\n },\n {\n storage: {\n getStorageKey: async (message) =>\n this.#storageKeyCache[message] ?? null,\n setStorageKey: async (message, key) => {\n this.#storageKeyCache[message] = key;\n },\n },\n },\n );\n\n this.#keyringController.setupLockedStateSubscriptions();\n this.#registerMessageHandlers();\n this.#nativeScryptCrypto = nativeScryptCrypto;\n\n // Contact Syncing\n setupContactSyncingSubscriptions({\n getUserStorageControllerInstance: () => this,\n getMessenger: () => this.messenger,\n trace: this.#trace,\n });\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers(): void {\n this.messenger.registerActionHandler(\n 'UserStorageController:performGetStorage',\n this.performGetStorage.bind(this),\n );\n\n this.messenger.registerActionHandler(\n 'UserStorageController:performGetStorageAllFeatureEntries',\n this.performGetStorageAllFeatureEntries.bind(this),\n );\n\n this.messenger.registerActionHandler(\n 'UserStorageController:performSetStorage',\n this.performSetStorage.bind(this),\n );\n\n this.messenger.registerActionHandler(\n 'UserStorageController:performBatchSetStorage',\n this.performBatchSetStorage.bind(this),\n );\n\n this.messenger.registerActionHandler(\n 'UserStorageController:performDeleteStorage',\n this.performDeleteStorage.bind(this),\n );\n\n this.messenger.registerActionHandler(\n 'UserStorageController:performBatchDeleteStorage',\n this.performBatchDeleteStorage.bind(this),\n );\n\n this.messenger.registerActionHandler(\n 'UserStorageController:getStorageKey',\n this.getStorageKey.bind(this),\n );\n }\n\n /**\n * Allows retrieval of stored data. Data stored is string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns the decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorage(\n path: UserStorageGenericPathWithFeatureAndKey,\n entropySourceId?: string,\n ): Promise<string | null> {\n return await this.#userStorage.getItem(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Allows retrieval of all stored data for a specific feature. Data stored is formatted as an array of strings.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns the array of decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorageAllFeatureEntries(\n path: UserStorageGenericPathWithFeatureOnly,\n entropySourceId?: string,\n ): Promise<string[] | null> {\n return await this.#userStorage.getAllFeatureItems(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Allows storage of user data. Data stored must be string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param value - The string data you want to store.\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performSetStorage(\n path: UserStorageGenericPathWithFeatureAndKey,\n value: string,\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.setItem(path, value, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Allows storage of multiple user data entries for one specific feature. Data stored must be string formatted.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @param values - data to store, in the form of an array of `[entryKey, entryValue]` pairs\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performBatchSetStorage(\n path: UserStorageGenericPathWithFeatureOnly,\n values: [UserStorageGenericFeatureKey, string][],\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.batchSetItems(path, values, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Allows deletion of user data. Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to delete data.\n */\n public async performDeleteStorage(\n path: UserStorageGenericPathWithFeatureAndKey,\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.deleteItem(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Allows deletion of all user data entries for a specific feature.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to delete data.\n */\n public async performDeleteStorageAllFeatureEntries(\n path: UserStorageGenericPathWithFeatureOnly,\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.deleteAllFeatureItems(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Allows delete of multiple user data entries for one specific feature. Data deleted must be string formatted.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @param values - data to store, in the form of an array of entryKey[]\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performBatchDeleteStorage(\n path: UserStorageGenericPathWithFeatureOnly,\n values: UserStorageGenericFeatureKey[],\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.batchDeleteItems(path, values, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Retrieves the storage key, for internal use only!\n *\n * @returns the storage key\n */\n public async getStorageKey(): Promise<string> {\n return await this.#userStorage.getStorageKey();\n }\n\n /**\n * Flushes the storage key cache.\n * CAUTION: This is only public for testing purposes.\n * It should not be used in production code.\n */\n public flushStorageKeyCache(): void {\n this.#storageKeyCache = {};\n }\n\n /**\n * Lists all the available HD keyring metadata IDs.\n * These IDs can be used in a multi-SRP context to segregate data specific to different SRPs.\n *\n * @returns A promise that resolves to an array of HD keyring metadata IDs.\n */\n async listEntropySources() {\n if (!this.#isUnlocked) {\n throw new Error(\n 'listEntropySources - unable to list entropy sources, wallet is locked',\n );\n }\n\n const { keyrings } = this.messenger.call('KeyringController:getState');\n return keyrings\n .filter((keyring) => keyring.type === KeyringTypes.hd.toString())\n .map((keyring) => keyring.metadata.id);\n }\n\n #_snapSignMessageCache: Record<`metamask:${string}`, string> = {};\n\n /**\n * Signs a specific message using an underlying auth snap.\n *\n * @param message - A specific tagged message to sign.\n * @param entropySourceId - The entropy source ID used to derive the key,\n * when multiple sources are available (Multi-SRP).\n * @returns A Signature created by the snap.\n */\n async #snapSignMessage(\n message: `metamask:${string}`,\n entropySourceId?: string,\n ): Promise<string> {\n // the message is SRP specific already, so there's no need to use the entropySourceId in the cache\n if (this.#_snapSignMessageCache[message]) {\n return this.#_snapSignMessageCache[message];\n }\n\n if (!this.#isUnlocked) {\n throw new Error(\n '#snapSignMessage - unable to call snap, wallet is locked',\n );\n }\n\n const result = (await this.messenger.call(\n 'SnapController:handleRequest',\n createSnapSignMessageRequest(message, entropySourceId),\n )) as string;\n\n this.#_snapSignMessageCache[message] = result;\n\n return result;\n }\n\n public async setIsBackupAndSyncFeatureEnabled(\n feature: keyof typeof BACKUPANDSYNC_FEATURES,\n enabled: boolean,\n ): Promise<void> {\n try {\n this.#setIsBackupAndSyncUpdateLoading(true);\n\n if (enabled) {\n // If any of the features are enabled, we need to ensure the user is signed in\n const isSignedIn = this.#auth.isSignedIn();\n if (!isSignedIn) {\n await this.#auth.signIn();\n }\n }\n\n this.update((state) => {\n if (feature === BACKUPANDSYNC_FEATURES.main) {\n state.isBackupAndSyncEnabled = enabled;\n }\n\n if (feature === BACKUPANDSYNC_FEATURES.accountSyncing) {\n state.isAccountSyncingEnabled = enabled;\n }\n\n if (feature === BACKUPANDSYNC_FEATURES.contactSyncing) {\n state.isContactSyncingEnabled = enabled;\n }\n });\n } catch (e) {\n // istanbul ignore next\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n // istanbul ignore next\n throw new Error(\n `${controllerName} - failed to ${enabled ? 'enable' : 'disable'} ${feature} - ${errorMessage}`,\n );\n } finally {\n this.#setIsBackupAndSyncUpdateLoading(false);\n }\n }\n\n #setIsBackupAndSyncUpdateLoading(\n isBackupAndSyncUpdateLoading: boolean,\n ): void {\n this.update((state) => {\n state.isBackupAndSyncUpdateLoading = isBackupAndSyncUpdateLoading;\n });\n }\n\n /**\n * Sets the isContactSyncingInProgress flag to prevent infinite loops during contact synchronization\n *\n * @param isContactSyncingInProgress - Whether contact syncing is in progress\n */\n async setIsContactSyncingInProgress(\n isContactSyncingInProgress: boolean,\n ): Promise<void> {\n this.update((state) => {\n state.isContactSyncingInProgress = isContactSyncingInProgress;\n });\n }\n\n /**\n * Syncs the address book list with the user storage address book list.\n * This method is used to make sure that the address book list is up-to-date with the user storage address book list and vice-versa.\n * It will add new contacts to the address book list, update/merge conflicting contacts and re-upload the results in some cases to the user storage.\n */\n async syncContactsWithUserStorage(): Promise<void> {\n const profileId = await this.#auth.getProfileId();\n\n const config = {\n onContactUpdated: () => {\n this.#config?.contactSyncing?.onContactUpdated?.(profileId);\n },\n onContactDeleted: () => {\n this.#config?.contactSyncing?.onContactDeleted?.(profileId);\n },\n onContactSyncErroneousSituation: (\n errorMessage: string,\n sentryContext?: Record<string, unknown>,\n ) => {\n this.#config?.contactSyncing?.onContactSyncErroneousSituation?.(\n profileId,\n errorMessage,\n sentryContext,\n );\n },\n };\n\n await syncContactsWithUserStorage(config, {\n getMessenger: () => this.messenger,\n getUserStorageControllerInstance: () => this,\n trace: this.#trace,\n });\n }\n}\n"]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import type { AddressBookControllerContactUpdatedEvent, AddressBookControllerContactDeletedEvent, AddressBookControllerActions, AddressBookControllerListAction, AddressBookControllerSetAction, AddressBookControllerDeleteAction } from "@metamask/address-book-controller";
|
|
2
|
-
import type
|
|
3
|
-
import { BaseController } from "@metamask/base-controller";
|
|
2
|
+
import { BaseController, type ControllerGetStateAction, type ControllerStateChangeEvent } from "@metamask/base-controller";
|
|
4
3
|
import type { TraceCallback } from "@metamask/controller-utils";
|
|
5
4
|
import { type KeyringControllerGetStateAction, type KeyringControllerLockEvent, type KeyringControllerUnlockEvent } from "@metamask/keyring-controller";
|
|
5
|
+
import type { Messenger } from "@metamask/messenger";
|
|
6
6
|
import type { HandleSnapRequest } from "@metamask/snaps-controllers";
|
|
7
7
|
import { BACKUPANDSYNC_FEATURES } from "./constants.cjs";
|
|
8
8
|
import type { UserStorageGenericFeatureKey, UserStorageGenericPathWithFeatureAndKey, UserStorageGenericPathWithFeatureOnly } from "../../sdk/index.cjs";
|
|
@@ -74,7 +74,7 @@ export type AllowedActions = KeyringControllerGetStateAction | HandleSnapRequest
|
|
|
74
74
|
export type UserStorageControllerStateChangeEvent = ControllerStateChangeEvent<typeof controllerName, UserStorageControllerState>;
|
|
75
75
|
export type Events = UserStorageControllerStateChangeEvent;
|
|
76
76
|
export type AllowedEvents = UserStorageControllerStateChangeEvent | KeyringControllerLockEvent | KeyringControllerUnlockEvent | AddressBookControllerContactUpdatedEvent | AddressBookControllerContactDeletedEvent;
|
|
77
|
-
export type UserStorageControllerMessenger =
|
|
77
|
+
export type UserStorageControllerMessenger = Messenger<typeof controllerName, Actions | AllowedActions, Events | AllowedEvents>;
|
|
78
78
|
/**
|
|
79
79
|
* Reusable controller that allows any team to store synchronized data for a given user.
|
|
80
80
|
* These can be settings shared cross MetaMask clients, or data we want to persist when uninstalling/reinstalling.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"UserStorageController.d.cts","sourceRoot":"","sources":["../../../src/controllers/user-storage/UserStorageController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,wCAAwC,EACxC,wCAAwC,EACxC,4BAA4B,EAC5B,+BAA+B,EAC/B,8BAA8B,EAC9B,iCAAiC,EAClC,0CAA0C;AAC3C,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"UserStorageController.d.cts","sourceRoot":"","sources":["../../../src/controllers/user-storage/UserStorageController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,wCAAwC,EACxC,wCAAwC,EACxC,4BAA4B,EAC5B,+BAA+B,EAC/B,8BAA8B,EAC9B,iCAAiC,EAClC,0CAA0C;AAC3C,OAAO,EACL,cAAc,EACd,KAAK,wBAAwB,EAC7B,KAA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AC,EAAE,MAAM,GACvB,OAAO,CAAC,IAAI,CAAC;IAOhB;;;;;;;;OAQG;IACU,sBAAsB,CACjC,IAAI,EAAE,qCAAqC,EAC3C,MAAM,EAAE,CAAC,4BAA4B,EAAE,MAAM,CAAC,EAAE,EAChD,eAAe,CAAC,EAAE,MAAM,GACvB,OAAO,CAAC,IAAI,CAAC;IAOhB;;;;;;OAMG;IACU,oBAAoB,CAC/B,IAAI,EAAE,uCAAuC,EAC7C,eAAe,CAAC,EAAE,MAAM,GACvB,OAAO,CAAC,IAAI,CAAC;IAOhB;;;;;;;OAOG;IACU,qCAAqC,CAChD,IAAI,EAAE,qCAAqC,EAC3C,eAAe,CAAC,EAAE,MAAM,GACvB,OAAO,CAAC,IAAI,CAAC;IAOhB;;;;;;;;OAQG;IACU,yBAAyB,CACpC,IAAI,EAAE,qCAAqC,EAC3C,MAAM,EAAE,4BAA4B,EAAE,EACtC,eAAe,CAAC,EAAE,MAAM,GACvB,OAAO,CAAC,IAAI,CAAC;IAOhB;;;;OAIG;IACU,aAAa,IAAI,OAAO,CAAC,MAAM,CAAC;IAI7C;;;;OAIG;IACI,oBAAoB,IAAI,IAAI;IAInC;;;;;OAKG;IACG,kBAAkB;IAgDX,gCAAgC,CAC3C,OAAO,EAAE,MAAM,OAAO,sBAAsB,EAC5C,OAAO,EAAE,OAAO,GACf,OAAO,CAAC,IAAI,CAAC;IA6ChB;;;;OAIG;IACG,6BAA6B,CACjC,0BAA0B,EAAE,OAAO,GAClC,OAAO,CAAC,IAAI,CAAC;IAMhB;;;;OAIG;IACG,2BAA2B,IAAI,OAAO,CAAC,IAAI,CAAC;CA4BnD"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import type { AddressBookControllerContactUpdatedEvent, AddressBookControllerContactDeletedEvent, AddressBookControllerActions, AddressBookControllerListAction, AddressBookControllerSetAction, AddressBookControllerDeleteAction } from "@metamask/address-book-controller";
|
|
2
|
-
import type
|
|
3
|
-
import { BaseController } from "@metamask/base-controller";
|
|
2
|
+
import { BaseController, type ControllerGetStateAction, type ControllerStateChangeEvent } from "@metamask/base-controller";
|
|
4
3
|
import type { TraceCallback } from "@metamask/controller-utils";
|
|
5
4
|
import { type KeyringControllerGetStateAction, type KeyringControllerLockEvent, type KeyringControllerUnlockEvent } from "@metamask/keyring-controller";
|
|
5
|
+
import type { Messenger } from "@metamask/messenger";
|
|
6
6
|
import type { HandleSnapRequest } from "@metamask/snaps-controllers";
|
|
7
7
|
import { BACKUPANDSYNC_FEATURES } from "./constants.mjs";
|
|
8
8
|
import type { UserStorageGenericFeatureKey, UserStorageGenericPathWithFeatureAndKey, UserStorageGenericPathWithFeatureOnly } from "../../sdk/index.mjs";
|
|
@@ -74,7 +74,7 @@ export type AllowedActions = KeyringControllerGetStateAction | HandleSnapRequest
|
|
|
74
74
|
export type UserStorageControllerStateChangeEvent = ControllerStateChangeEvent<typeof controllerName, UserStorageControllerState>;
|
|
75
75
|
export type Events = UserStorageControllerStateChangeEvent;
|
|
76
76
|
export type AllowedEvents = UserStorageControllerStateChangeEvent | KeyringControllerLockEvent | KeyringControllerUnlockEvent | AddressBookControllerContactUpdatedEvent | AddressBookControllerContactDeletedEvent;
|
|
77
|
-
export type UserStorageControllerMessenger =
|
|
77
|
+
export type UserStorageControllerMessenger = Messenger<typeof controllerName, Actions | AllowedActions, Events | AllowedEvents>;
|
|
78
78
|
/**
|
|
79
79
|
* Reusable controller that allows any team to store synchronized data for a given user.
|
|
80
80
|
* These can be settings shared cross MetaMask clients, or data we want to persist when uninstalling/reinstalling.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"UserStorageController.d.mts","sourceRoot":"","sources":["../../../src/controllers/user-storage/UserStorageController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,wCAAwC,EACxC,wCAAwC,EACxC,4BAA4B,EAC5B,+BAA+B,EAC/B,8BAA8B,EAC9B,iCAAiC,EAClC,0CAA0C;AAC3C,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"UserStorageController.d.mts","sourceRoot":"","sources":["../../../src/controllers/user-storage/UserStorageController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,wCAAwC,EACxC,wCAAwC,EACxC,4BAA4B,EAC5B,+BAA+B,EAC/B,8BAA8B,EAC9B,iCAAiC,EAClC,0CAA0C;AAC3C,OAAO,EACL,cAAc,EACd,KAAK,wBAAwB,EAC7B,KAAK,0BAA0B,EAEhC,kCAAkC;AACnC,OAAO,KAAK,EACV,aAAa,EAGd,mCAAmC;AACpC,OAAO,EAEL,KAAK,+BAA+B,EACpC,KAAK,0BAA0B,EAC/B,KAAK,4BAA4B,EAClC,qCAAqC;AACtC,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AACrD,OAAO,KAAK,EAAE,iBAAiB,EAAE,oCAAoC;AAErE,OAAO,EAAE,sBAAsB,EAAE,wBAAoB;AAGrD,OAAO,KAAK,EACV,4BAA4B,EAC5B,uCAAuC,EACvC,qCAAqC,EACtC,4BAAkB;AACnB,OAAO,EAAE,GAAG,EAAe,4BAAkB;AAC7C,OAAO,KAAK,EAAE,YAAY,EAAE,0CAAsC;AAClE,OAAO,EAAE,UAAU,EAAE,2CAAuC;AAE5D,OAAO,KAAK,EACV,sCAAsC,EACtC,yCAAyC,EACzC,kCAAkC,EAClC,qCAAqC,EACtC,uDAAmD;AAEpD,QAAA,MAAM,cAAc,0BAA0B,CAAC;AAG/C,MAAM,MAAM,0BAA0B,GAAG;IACvC;;OAEG;IACH,sBAAsB,EAAE,OAAO,CAAC;IAChC;;OAEG;IACH,4BAA4B,EAAE,OAAO,CAAC;IACtC;;OAEG;IACH,uBAAuB,EAAE,OAAO,CAAC;IACjC;;OAEG;IACH,uBAAuB,EAAE,OAAO,CAAC;IACjC;;OAEG;IACH,0BAA0B,EAAE,OAAO,CAAC;CACrC,CAAC;AAEF,eAAO,MAAM,YAAY,EAAE,0BAM1B,CAAC;AAmCF,KAAK,gBAAgB,GAAG;IACtB,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IACG,2BAA2B,IAAI,OAAO,CAAC,IAAI,CAAC;CA4BnD"}
|
|
@@ -30,31 +30,31 @@ const metadata = {
|
|
|
30
30
|
isBackupAndSyncEnabled: {
|
|
31
31
|
includeInStateLogs: true,
|
|
32
32
|
persist: true,
|
|
33
|
-
|
|
33
|
+
includeInDebugSnapshot: true,
|
|
34
34
|
usedInUi: true,
|
|
35
35
|
},
|
|
36
36
|
isBackupAndSyncUpdateLoading: {
|
|
37
37
|
includeInStateLogs: false,
|
|
38
38
|
persist: false,
|
|
39
|
-
|
|
39
|
+
includeInDebugSnapshot: false,
|
|
40
40
|
usedInUi: true,
|
|
41
41
|
},
|
|
42
42
|
isAccountSyncingEnabled: {
|
|
43
43
|
includeInStateLogs: true,
|
|
44
44
|
persist: true,
|
|
45
|
-
|
|
45
|
+
includeInDebugSnapshot: true,
|
|
46
46
|
usedInUi: true,
|
|
47
47
|
},
|
|
48
48
|
isContactSyncingEnabled: {
|
|
49
49
|
includeInStateLogs: true,
|
|
50
50
|
persist: true,
|
|
51
|
-
|
|
51
|
+
includeInDebugSnapshot: true,
|
|
52
52
|
usedInUi: true,
|
|
53
53
|
},
|
|
54
54
|
isContactSyncingInProgress: {
|
|
55
55
|
includeInStateLogs: false,
|
|
56
56
|
persist: false,
|
|
57
|
-
|
|
57
|
+
includeInDebugSnapshot: false,
|
|
58
58
|
usedInUi: true,
|
|
59
59
|
},
|
|
60
60
|
};
|
|
@@ -78,14 +78,14 @@ class UserStorageController extends BaseController {
|
|
|
78
78
|
_UserStorageController_userStorage.set(this, void 0);
|
|
79
79
|
_UserStorageController_auth.set(this, {
|
|
80
80
|
getProfileId: async (entropySourceId) => {
|
|
81
|
-
const sessionProfile = await this.
|
|
81
|
+
const sessionProfile = await this.messenger.call('AuthenticationController:getSessionProfile', entropySourceId);
|
|
82
82
|
return sessionProfile?.profileId;
|
|
83
83
|
},
|
|
84
84
|
isSignedIn: () => {
|
|
85
|
-
return this.
|
|
85
|
+
return this.messenger.call('AuthenticationController:isSignedIn');
|
|
86
86
|
},
|
|
87
87
|
signIn: async () => {
|
|
88
|
-
return await this.
|
|
88
|
+
return await this.messenger.call('AuthenticationController:performSignIn');
|
|
89
89
|
},
|
|
90
90
|
});
|
|
91
91
|
_UserStorageController_config.set(this, {
|
|
@@ -96,12 +96,12 @@ class UserStorageController extends BaseController {
|
|
|
96
96
|
_UserStorageController_storageKeyCache.set(this, {});
|
|
97
97
|
_UserStorageController_keyringController.set(this, {
|
|
98
98
|
setupLockedStateSubscriptions: () => {
|
|
99
|
-
const { isUnlocked } = this.
|
|
99
|
+
const { isUnlocked } = this.messenger.call('KeyringController:getState');
|
|
100
100
|
__classPrivateFieldSet(this, _UserStorageController_isUnlocked, isUnlocked, "f");
|
|
101
|
-
this.
|
|
101
|
+
this.messenger.subscribe('KeyringController:unlock', () => {
|
|
102
102
|
__classPrivateFieldSet(this, _UserStorageController_isUnlocked, true, "f");
|
|
103
103
|
});
|
|
104
|
-
this.
|
|
104
|
+
this.messenger.subscribe('KeyringController:lock', () => {
|
|
105
105
|
__classPrivateFieldSet(this, _UserStorageController_isUnlocked, false, "f");
|
|
106
106
|
});
|
|
107
107
|
},
|
|
@@ -123,9 +123,9 @@ class UserStorageController extends BaseController {
|
|
|
123
123
|
__classPrivateFieldSet(this, _UserStorageController_userStorage, new UserStorage({
|
|
124
124
|
env: __classPrivateFieldGet(this, _UserStorageController_config, "f").env,
|
|
125
125
|
auth: {
|
|
126
|
-
getAccessToken: (entropySourceId) => this.
|
|
126
|
+
getAccessToken: (entropySourceId) => this.messenger.call('AuthenticationController:getBearerToken', entropySourceId),
|
|
127
127
|
getUserProfile: async (entropySourceId) => {
|
|
128
|
-
return await this.
|
|
128
|
+
return await this.messenger.call('AuthenticationController:getSessionProfile', entropySourceId);
|
|
129
129
|
},
|
|
130
130
|
signMessage: (message, entropySourceId) => __classPrivateFieldGet(this, _UserStorageController_instances, "m", _UserStorageController_snapSignMessage).call(this, message, entropySourceId),
|
|
131
131
|
},
|
|
@@ -143,7 +143,7 @@ class UserStorageController extends BaseController {
|
|
|
143
143
|
// Contact Syncing
|
|
144
144
|
setupContactSyncingSubscriptions({
|
|
145
145
|
getUserStorageControllerInstance: () => this,
|
|
146
|
-
getMessenger: () => this.
|
|
146
|
+
getMessenger: () => this.messenger,
|
|
147
147
|
trace: __classPrivateFieldGet(this, _UserStorageController_trace, "f"),
|
|
148
148
|
});
|
|
149
149
|
}
|
|
@@ -273,7 +273,7 @@ class UserStorageController extends BaseController {
|
|
|
273
273
|
if (!__classPrivateFieldGet(this, _UserStorageController_isUnlocked, "f")) {
|
|
274
274
|
throw new Error('listEntropySources - unable to list entropy sources, wallet is locked');
|
|
275
275
|
}
|
|
276
|
-
const { keyrings } = this.
|
|
276
|
+
const { keyrings } = this.messenger.call('KeyringController:getState');
|
|
277
277
|
return keyrings
|
|
278
278
|
.filter((keyring) => keyring.type === KeyringTypes.hd.toString())
|
|
279
279
|
.map((keyring) => keyring.metadata.id);
|
|
@@ -339,20 +339,20 @@ class UserStorageController extends BaseController {
|
|
|
339
339
|
},
|
|
340
340
|
};
|
|
341
341
|
await syncContactsWithUserStorage(config, {
|
|
342
|
-
getMessenger: () => this.
|
|
342
|
+
getMessenger: () => this.messenger,
|
|
343
343
|
getUserStorageControllerInstance: () => this,
|
|
344
344
|
trace: __classPrivateFieldGet(this, _UserStorageController_trace, "f"),
|
|
345
345
|
});
|
|
346
346
|
}
|
|
347
347
|
}
|
|
348
348
|
_UserStorageController_userStorage = new WeakMap(), _UserStorageController_auth = new WeakMap(), _UserStorageController_config = new WeakMap(), _UserStorageController_trace = new WeakMap(), _UserStorageController_isUnlocked = new WeakMap(), _UserStorageController_storageKeyCache = new WeakMap(), _UserStorageController_keyringController = new WeakMap(), _UserStorageController_nativeScryptCrypto = new WeakMap(), _UserStorageController__snapSignMessageCache = new WeakMap(), _UserStorageController_instances = new WeakSet(), _UserStorageController_registerMessageHandlers = function _UserStorageController_registerMessageHandlers() {
|
|
349
|
-
this.
|
|
350
|
-
this.
|
|
351
|
-
this.
|
|
352
|
-
this.
|
|
353
|
-
this.
|
|
354
|
-
this.
|
|
355
|
-
this.
|
|
349
|
+
this.messenger.registerActionHandler('UserStorageController:performGetStorage', this.performGetStorage.bind(this));
|
|
350
|
+
this.messenger.registerActionHandler('UserStorageController:performGetStorageAllFeatureEntries', this.performGetStorageAllFeatureEntries.bind(this));
|
|
351
|
+
this.messenger.registerActionHandler('UserStorageController:performSetStorage', this.performSetStorage.bind(this));
|
|
352
|
+
this.messenger.registerActionHandler('UserStorageController:performBatchSetStorage', this.performBatchSetStorage.bind(this));
|
|
353
|
+
this.messenger.registerActionHandler('UserStorageController:performDeleteStorage', this.performDeleteStorage.bind(this));
|
|
354
|
+
this.messenger.registerActionHandler('UserStorageController:performBatchDeleteStorage', this.performBatchDeleteStorage.bind(this));
|
|
355
|
+
this.messenger.registerActionHandler('UserStorageController:getStorageKey', this.getStorageKey.bind(this));
|
|
356
356
|
}, _UserStorageController_snapSignMessage =
|
|
357
357
|
/**
|
|
358
358
|
* Signs a specific message using an underlying auth snap.
|
|
@@ -370,7 +370,7 @@ async function _UserStorageController_snapSignMessage(message, entropySourceId)
|
|
|
370
370
|
if (!__classPrivateFieldGet(this, _UserStorageController_isUnlocked, "f")) {
|
|
371
371
|
throw new Error('#snapSignMessage - unable to call snap, wallet is locked');
|
|
372
372
|
}
|
|
373
|
-
const result = (await this.
|
|
373
|
+
const result = (await this.messenger.call('SnapController:handleRequest', createSnapSignMessageRequest(message, entropySourceId)));
|
|
374
374
|
__classPrivateFieldGet(this, _UserStorageController__snapSignMessageCache, "f")[message] = result;
|
|
375
375
|
return result;
|
|
376
376
|
}, _UserStorageController_setIsBackupAndSyncUpdateLoading = function _UserStorageController_setIsBackupAndSyncUpdateLoading(isBackupAndSyncUpdateLoading) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"UserStorageController.mjs","sourceRoot":"","sources":["../../../src/controllers/user-storage/UserStorageController.ts"],"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CACb,0DAA0D,CAC3D,CAAC;KACH;IAED,MAAM,MAAM,GAAG,CAAC,MAAM,IAAI,CAAC,eAAe,CAAC,IAAI,CAC7C,8BAA8B,EAC9B,4BAA4B,CAAC,OAAO,EAAE,eAAe,CAAC,CACvD,CAAW,CAAC;IAEb,uBAAA,IAAI,oDAAuB,CAAC,OAAO,CAAC,GAAG,MAAM,CAAC;IAE9C,OAAO,MAAM,CAAC;AAChB,CAAC,2HA2CC,4BAAqC;IAErC,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,4BAA4B,GAAG,4BAA4B,CAAC;IACpE,CAAC,CAAC,CAAC;AACL,CAAC;eA7akB,qBAAqB","sourcesContent":["import type {\n AddressBookControllerContactUpdatedEvent,\n AddressBookControllerContactDeletedEvent,\n AddressBookControllerActions,\n AddressBookControllerListAction,\n AddressBookControllerSetAction,\n AddressBookControllerDeleteAction,\n} from '@metamask/address-book-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedMessenger,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type {\n TraceCallback,\n TraceContext,\n TraceRequest,\n} from '@metamask/controller-utils';\nimport {\n KeyringTypes,\n type KeyringControllerGetStateAction,\n type KeyringControllerLockEvent,\n type KeyringControllerUnlockEvent,\n} from '@metamask/keyring-controller';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\n\nimport { BACKUPANDSYNC_FEATURES } from './constants';\nimport { syncContactsWithUserStorage } from './contact-syncing/controller-integration';\nimport { setupContactSyncingSubscriptions } from './contact-syncing/setup-subscriptions';\nimport type {\n UserStorageGenericFeatureKey,\n UserStorageGenericPathWithFeatureAndKey,\n UserStorageGenericPathWithFeatureOnly,\n} from '../../sdk';\nimport { Env, UserStorage } from '../../sdk';\nimport type { NativeScrypt } from '../../shared/types/encryption';\nimport { EventQueue } from '../../shared/utils/event-queue';\nimport { createSnapSignMessageRequest } from '../authentication/auth-snap-requests';\nimport type {\n AuthenticationControllerGetBearerToken,\n AuthenticationControllerGetSessionProfile,\n AuthenticationControllerIsSignedIn,\n AuthenticationControllerPerformSignIn,\n} from '../authentication/AuthenticationController';\n\nconst controllerName = 'UserStorageController';\n\n// State\nexport type UserStorageControllerState = {\n /**\n * Condition used by UI and to determine if we can use some of the User Storage methods.\n */\n isBackupAndSyncEnabled: boolean;\n /**\n * Loading state for the backup and sync update\n */\n isBackupAndSyncUpdateLoading: boolean;\n /**\n * Condition used by UI to determine if account syncing is enabled.\n */\n isAccountSyncingEnabled: boolean;\n /**\n * Condition used by UI to determine if contact syncing is enabled.\n */\n isContactSyncingEnabled: boolean;\n /**\n * Condition used by UI to determine if contact syncing is in progress.\n */\n isContactSyncingInProgress: boolean;\n};\n\nexport const defaultState: UserStorageControllerState = {\n isBackupAndSyncEnabled: true,\n isBackupAndSyncUpdateLoading: false,\n isAccountSyncingEnabled: true,\n isContactSyncingEnabled: true,\n isContactSyncingInProgress: false,\n};\n\nconst metadata: StateMetadata<UserStorageControllerState> = {\n isBackupAndSyncEnabled: {\n includeInStateLogs: true,\n persist: true,\n anonymous: true,\n usedInUi: true,\n },\n isBackupAndSyncUpdateLoading: {\n includeInStateLogs: false,\n persist: false,\n anonymous: false,\n usedInUi: true,\n },\n isAccountSyncingEnabled: {\n includeInStateLogs: true,\n persist: true,\n anonymous: true,\n usedInUi: true,\n },\n isContactSyncingEnabled: {\n includeInStateLogs: true,\n persist: true,\n anonymous: true,\n usedInUi: true,\n },\n isContactSyncingInProgress: {\n includeInStateLogs: false,\n persist: false,\n anonymous: false,\n usedInUi: true,\n },\n};\n\ntype ControllerConfig = {\n env: Env;\n contactSyncing?: {\n /**\n * Callback that fires when contact sync updates a contact.\n * This is used for analytics.\n */\n onContactUpdated?: (profileId: string) => void;\n\n /**\n * Callback that fires when contact sync deletes a contact.\n * This is used for analytics.\n */\n onContactDeleted?: (profileId: string) => void;\n\n /**\n * Callback that fires when an erroneous situation happens during contact sync.\n * This is used for analytics.\n */\n onContactSyncErroneousSituation?: (\n profileId: string,\n situationMessage: string,\n sentryContext?: Record<string, unknown>,\n ) => void;\n };\n};\n\n// Messenger Actions\ntype CreateActionsObj<Controller extends keyof UserStorageController> = {\n [K in Controller]: {\n type: `${typeof controllerName}:${K}`;\n handler: UserStorageController[K];\n };\n};\ntype ActionsObj = CreateActionsObj<\n | 'performGetStorage'\n | 'performGetStorageAllFeatureEntries'\n | 'performSetStorage'\n | 'performBatchSetStorage'\n | 'performDeleteStorage'\n | 'performBatchDeleteStorage'\n | 'getStorageKey'\n>;\nexport type UserStorageControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n UserStorageControllerState\n>;\nexport type Actions =\n | ActionsObj[keyof ActionsObj]\n | UserStorageControllerGetStateAction;\nexport type UserStorageControllerPerformGetStorage =\n ActionsObj['performGetStorage'];\nexport type UserStorageControllerPerformGetStorageAllFeatureEntries =\n ActionsObj['performGetStorageAllFeatureEntries'];\nexport type UserStorageControllerPerformSetStorage =\n ActionsObj['performSetStorage'];\nexport type UserStorageControllerPerformBatchSetStorage =\n ActionsObj['performBatchSetStorage'];\nexport type UserStorageControllerPerformDeleteStorage =\n ActionsObj['performDeleteStorage'];\nexport type UserStorageControllerPerformBatchDeleteStorage =\n ActionsObj['performBatchDeleteStorage'];\nexport type UserStorageControllerGetStorageKey = ActionsObj['getStorageKey'];\n\nexport type AllowedActions =\n // Keyring Requests\n | KeyringControllerGetStateAction\n // Snap Requests\n | HandleSnapRequest\n // Auth Requests\n | AuthenticationControllerGetBearerToken\n | AuthenticationControllerGetSessionProfile\n | AuthenticationControllerPerformSignIn\n | AuthenticationControllerIsSignedIn\n // Contact Syncing\n | AddressBookControllerListAction\n | AddressBookControllerSetAction\n | AddressBookControllerDeleteAction\n | AddressBookControllerActions;\n\n// Messenger events\nexport type UserStorageControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n UserStorageControllerState\n>;\n\nexport type Events = UserStorageControllerStateChangeEvent;\n\nexport type AllowedEvents =\n | UserStorageControllerStateChangeEvent\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent\n // Address Book Events\n | AddressBookControllerContactUpdatedEvent\n | AddressBookControllerContactDeletedEvent;\n\n// Messenger\nexport type UserStorageControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n Actions | AllowedActions,\n Events | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Reusable controller that allows any team to store synchronized data for a given user.\n * These can be settings shared cross MetaMask clients, or data we want to persist when uninstalling/reinstalling.\n *\n * NOTE:\n * - data stored on UserStorage is FULLY encrypted, with the only keys stored/managed on the client.\n * - No one can access this data unless they are have the SRP and are able to run the signing snap.\n */\nexport default class UserStorageController extends BaseController<\n typeof controllerName,\n UserStorageControllerState,\n UserStorageControllerMessenger\n> {\n readonly #userStorage: UserStorage;\n\n readonly #auth = {\n getProfileId: async (entropySourceId?: string) => {\n const sessionProfile = await this.messagingSystem.call(\n 'AuthenticationController:getSessionProfile',\n entropySourceId,\n );\n return sessionProfile?.profileId;\n },\n isSignedIn: () => {\n return this.messagingSystem.call('AuthenticationController:isSignedIn');\n },\n signIn: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:performSignIn',\n );\n },\n };\n\n readonly #config: ControllerConfig = {\n env: Env.PRD,\n };\n\n readonly #trace: TraceCallback;\n\n #isUnlocked = false;\n\n #storageKeyCache: Record<`metamask:${string}`, string> = {};\n\n readonly #keyringController = {\n setupLockedStateSubscriptions: () => {\n const { isUnlocked } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n this.#isUnlocked = isUnlocked;\n\n this.messagingSystem.subscribe('KeyringController:unlock', () => {\n this.#isUnlocked = true;\n });\n\n this.messagingSystem.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n },\n };\n\n readonly #nativeScryptCrypto: NativeScrypt | undefined = undefined;\n\n eventQueue = new EventQueue();\n\n constructor({\n messenger,\n state,\n config,\n nativeScryptCrypto,\n trace,\n }: {\n messenger: UserStorageControllerMessenger;\n state?: UserStorageControllerState;\n config?: Partial<ControllerConfig>;\n nativeScryptCrypto?: NativeScrypt;\n trace?: TraceCallback;\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n this.#config = {\n ...this.#config,\n ...config,\n };\n this.#trace =\n trace ??\n (async <ReturnType>(\n _request: TraceRequest,\n fn?: (context?: TraceContext) => ReturnType,\n ): Promise<ReturnType> => {\n if (!fn) {\n return undefined as ReturnType;\n }\n return await Promise.resolve(fn());\n });\n\n this.#userStorage = new UserStorage(\n {\n env: this.#config.env,\n auth: {\n getAccessToken: (entropySourceId?: string) =>\n this.messagingSystem.call(\n 'AuthenticationController:getBearerToken',\n entropySourceId,\n ),\n getUserProfile: async (entropySourceId?: string) => {\n return await this.messagingSystem.call(\n 'AuthenticationController:getSessionProfile',\n entropySourceId,\n );\n },\n signMessage: (message: string, entropySourceId?: string) =>\n this.#snapSignMessage(\n message as `metamask:${string}`,\n entropySourceId,\n ),\n },\n },\n {\n storage: {\n getStorageKey: async (message) =>\n this.#storageKeyCache[message] ?? null,\n setStorageKey: async (message, key) => {\n this.#storageKeyCache[message] = key;\n },\n },\n },\n );\n\n this.#keyringController.setupLockedStateSubscriptions();\n this.#registerMessageHandlers();\n this.#nativeScryptCrypto = nativeScryptCrypto;\n\n // Contact Syncing\n setupContactSyncingSubscriptions({\n getUserStorageControllerInstance: () => this,\n getMessenger: () => this.messagingSystem,\n trace: this.#trace,\n });\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performGetStorage',\n this.performGetStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performGetStorageAllFeatureEntries',\n this.performGetStorageAllFeatureEntries.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performSetStorage',\n this.performSetStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performBatchSetStorage',\n this.performBatchSetStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performDeleteStorage',\n this.performDeleteStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performBatchDeleteStorage',\n this.performBatchDeleteStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:getStorageKey',\n this.getStorageKey.bind(this),\n );\n }\n\n /**\n * Allows retrieval of stored data. Data stored is string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns the decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorage(\n path: UserStorageGenericPathWithFeatureAndKey,\n entropySourceId?: string,\n ): Promise<string | null> {\n return await this.#userStorage.getItem(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Allows retrieval of all stored data for a specific feature. Data stored is formatted as an array of strings.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns the array of decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorageAllFeatureEntries(\n path: UserStorageGenericPathWithFeatureOnly,\n entropySourceId?: string,\n ): Promise<string[] | null> {\n return await this.#userStorage.getAllFeatureItems(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Allows storage of user data. Data stored must be string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param value - The string data you want to store.\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performSetStorage(\n path: UserStorageGenericPathWithFeatureAndKey,\n value: string,\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.setItem(path, value, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Allows storage of multiple user data entries for one specific feature. Data stored must be string formatted.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @param values - data to store, in the form of an array of `[entryKey, entryValue]` pairs\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performBatchSetStorage(\n path: UserStorageGenericPathWithFeatureOnly,\n values: [UserStorageGenericFeatureKey, string][],\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.batchSetItems(path, values, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Allows deletion of user data. Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to delete data.\n */\n public async performDeleteStorage(\n path: UserStorageGenericPathWithFeatureAndKey,\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.deleteItem(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Allows deletion of all user data entries for a specific feature.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to delete data.\n */\n public async performDeleteStorageAllFeatureEntries(\n path: UserStorageGenericPathWithFeatureOnly,\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.deleteAllFeatureItems(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Allows delete of multiple user data entries for one specific feature. Data deleted must be string formatted.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @param values - data to store, in the form of an array of entryKey[]\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performBatchDeleteStorage(\n path: UserStorageGenericPathWithFeatureOnly,\n values: UserStorageGenericFeatureKey[],\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.batchDeleteItems(path, values, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Retrieves the storage key, for internal use only!\n *\n * @returns the storage key\n */\n public async getStorageKey(): Promise<string> {\n return await this.#userStorage.getStorageKey();\n }\n\n /**\n * Flushes the storage key cache.\n * CAUTION: This is only public for testing purposes.\n * It should not be used in production code.\n */\n public flushStorageKeyCache(): void {\n this.#storageKeyCache = {};\n }\n\n /**\n * Lists all the available HD keyring metadata IDs.\n * These IDs can be used in a multi-SRP context to segregate data specific to different SRPs.\n *\n * @returns A promise that resolves to an array of HD keyring metadata IDs.\n */\n async listEntropySources() {\n if (!this.#isUnlocked) {\n throw new Error(\n 'listEntropySources - unable to list entropy sources, wallet is locked',\n );\n }\n\n const { keyrings } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n return keyrings\n .filter((keyring) => keyring.type === KeyringTypes.hd.toString())\n .map((keyring) => keyring.metadata.id);\n }\n\n #_snapSignMessageCache: Record<`metamask:${string}`, string> = {};\n\n /**\n * Signs a specific message using an underlying auth snap.\n *\n * @param message - A specific tagged message to sign.\n * @param entropySourceId - The entropy source ID used to derive the key,\n * when multiple sources are available (Multi-SRP).\n * @returns A Signature created by the snap.\n */\n async #snapSignMessage(\n message: `metamask:${string}`,\n entropySourceId?: string,\n ): Promise<string> {\n // the message is SRP specific already, so there's no need to use the entropySourceId in the cache\n if (this.#_snapSignMessageCache[message]) {\n return this.#_snapSignMessageCache[message];\n }\n\n if (!this.#isUnlocked) {\n throw new Error(\n '#snapSignMessage - unable to call snap, wallet is locked',\n );\n }\n\n const result = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n createSnapSignMessageRequest(message, entropySourceId),\n )) as string;\n\n this.#_snapSignMessageCache[message] = result;\n\n return result;\n }\n\n public async setIsBackupAndSyncFeatureEnabled(\n feature: keyof typeof BACKUPANDSYNC_FEATURES,\n enabled: boolean,\n ): Promise<void> {\n try {\n this.#setIsBackupAndSyncUpdateLoading(true);\n\n if (enabled) {\n // If any of the features are enabled, we need to ensure the user is signed in\n const isSignedIn = this.#auth.isSignedIn();\n if (!isSignedIn) {\n await this.#auth.signIn();\n }\n }\n\n this.update((state) => {\n if (feature === BACKUPANDSYNC_FEATURES.main) {\n state.isBackupAndSyncEnabled = enabled;\n }\n\n if (feature === BACKUPANDSYNC_FEATURES.accountSyncing) {\n state.isAccountSyncingEnabled = enabled;\n }\n\n if (feature === BACKUPANDSYNC_FEATURES.contactSyncing) {\n state.isContactSyncingEnabled = enabled;\n }\n });\n } catch (e) {\n // istanbul ignore next\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n // istanbul ignore next\n throw new Error(\n `${controllerName} - failed to ${enabled ? 'enable' : 'disable'} ${feature} - ${errorMessage}`,\n );\n } finally {\n this.#setIsBackupAndSyncUpdateLoading(false);\n }\n }\n\n #setIsBackupAndSyncUpdateLoading(\n isBackupAndSyncUpdateLoading: boolean,\n ): void {\n this.update((state) => {\n state.isBackupAndSyncUpdateLoading = isBackupAndSyncUpdateLoading;\n });\n }\n\n /**\n * Sets the isContactSyncingInProgress flag to prevent infinite loops during contact synchronization\n *\n * @param isContactSyncingInProgress - Whether contact syncing is in progress\n */\n async setIsContactSyncingInProgress(\n isContactSyncingInProgress: boolean,\n ): Promise<void> {\n this.update((state) => {\n state.isContactSyncingInProgress = isContactSyncingInProgress;\n });\n }\n\n /**\n * Syncs the address book list with the user storage address book list.\n * This method is used to make sure that the address book list is up-to-date with the user storage address book list and vice-versa.\n * It will add new contacts to the address book list, update/merge conflicting contacts and re-upload the results in some cases to the user storage.\n */\n async syncContactsWithUserStorage(): Promise<void> {\n const profileId = await this.#auth.getProfileId();\n\n const config = {\n onContactUpdated: () => {\n this.#config?.contactSyncing?.onContactUpdated?.(profileId);\n },\n onContactDeleted: () => {\n this.#config?.contactSyncing?.onContactDeleted?.(profileId);\n },\n onContactSyncErroneousSituation: (\n errorMessage: string,\n sentryContext?: Record<string, unknown>,\n ) => {\n this.#config?.contactSyncing?.onContactSyncErroneousSituation?.(\n profileId,\n errorMessage,\n sentryContext,\n );\n },\n };\n\n await syncContactsWithUserStorage(config, {\n getMessenger: () => this.messagingSystem,\n getUserStorageControllerInstance: () => this,\n trace: this.#trace,\n });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"UserStorageController.mjs","sourceRoot":"","sources":["../../../src/controllers/user-storage/UserStorageController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAQA,OAAO,EACL,cAAc,EAIf,kCAAkC;AAMnC,OAAO,EACL,YAAY,EAIb,qCAAqC;AAItC,OAAO,EAAE,sBAAsB,EAAE,wBAAoB;AACrD,OAAO,EAAE,2BAA2B,EAAE,qDAAiD;AACvF,OAAO,EAAE,gCAAgC,EAAE,kDAA8C;AAMzF,OAAO,EAAE,GAAG,EAAE,WAAW,EAAE,4BAAkB;AAE7C,OAAO,EAAE,UAAU,EAAE,2CAAuC;AAC5D,OAAO,EAAE,4BAA4B,EAAE,iDAA6C;AAQpF,MAAM,cAAc,GAAG,uBAAuB,CAAC;AA0B/C,MAAM,CAAC,MAAM,YAAY,GAA+B;IACtD,sBAAsB,EAAE,IAAI;IAC5B,4BAA4B,EAAE,KAAK;IACnC,uBAAuB,EAAE,IAAI;IAC7B,uBAAuB,EAAE,IAAI;IAC7B,0BAA0B,EAAE,KAAK;CAClC,CAAC;AAEF,MAAM,QAAQ,GAA8C;IAC1D,sBAAsB,EAAE;QACtB,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,QAAQ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rC,CAAC;IAEF,IAAI,CAAC,SAAS,CAAC,qBAAqB,CAClC,iDAAiD,EACjD,IAAI,CAAC,yBAAyB,CAAC,IAAI,CAAC,IAAI,CAAC,CAC1C,CAAC;IAEF,IAAI,CAAC,SAAS,CAAC,qBAAqB,CAClC,qCAAqC,EACrC,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,CAC9B,CAAC;AACJ,CAAC;AA4KD;;;;;;;GAOG;AACH,KAAK,iDACH,OAA6B,EAC7B,eAAwB;IAExB,kGAAkG;IAClG,IAAI,uBAAA,IAAI,oDAAuB,CAAC,OAAO,CAAC,EAAE;QACxC,OAAO,uBAAA,IAAI,oDAAuB,CAAC,OAAO,CAAC,CAAC;KAC7C;IAED,IAAI,CAAC,uBAAA,IAAI,yCAAY,EAAE;QACrB,MAAM,IAAI,KAAK,CACb,0DAA0D,CAC3D,CAAC;KACH;IAED,MAAM,MAAM,GAAG,CAAC,MAAM,IAAI,CAAC,SAAS,CAAC,IAAI,CACvC,8BAA8B,EAC9B,4BAA4B,CAAC,OAAO,EAAE,eAAe,CAAC,CACvD,CAAW,CAAC;IAEb,uBAAA,IAAI,oDAAuB,CAAC,OAAO,CAAC,GAAG,MAAM,CAAC;IAE9C,OAAO,MAAM,CAAC;AAChB,CAAC,2HA2CC,4BAAqC;IAErC,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,4BAA4B,GAAG,4BAA4B,CAAC;IACpE,CAAC,CAAC,CAAC;AACL,CAAC;eAzakB,qBAAqB","sourcesContent":["import type {\n AddressBookControllerContactUpdatedEvent,\n AddressBookControllerContactDeletedEvent,\n AddressBookControllerActions,\n AddressBookControllerListAction,\n AddressBookControllerSetAction,\n AddressBookControllerDeleteAction,\n} from '@metamask/address-book-controller';\nimport {\n BaseController,\n type ControllerGetStateAction,\n type ControllerStateChangeEvent,\n type StateMetadata,\n} from '@metamask/base-controller';\nimport type {\n TraceCallback,\n TraceContext,\n TraceRequest,\n} from '@metamask/controller-utils';\nimport {\n KeyringTypes,\n type KeyringControllerGetStateAction,\n type KeyringControllerLockEvent,\n type KeyringControllerUnlockEvent,\n} from '@metamask/keyring-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\n\nimport { BACKUPANDSYNC_FEATURES } from './constants';\nimport { syncContactsWithUserStorage } from './contact-syncing/controller-integration';\nimport { setupContactSyncingSubscriptions } from './contact-syncing/setup-subscriptions';\nimport type {\n UserStorageGenericFeatureKey,\n UserStorageGenericPathWithFeatureAndKey,\n UserStorageGenericPathWithFeatureOnly,\n} from '../../sdk';\nimport { Env, UserStorage } from '../../sdk';\nimport type { NativeScrypt } from '../../shared/types/encryption';\nimport { EventQueue } from '../../shared/utils/event-queue';\nimport { createSnapSignMessageRequest } from '../authentication/auth-snap-requests';\nimport type {\n AuthenticationControllerGetBearerToken,\n AuthenticationControllerGetSessionProfile,\n AuthenticationControllerIsSignedIn,\n AuthenticationControllerPerformSignIn,\n} from '../authentication/AuthenticationController';\n\nconst controllerName = 'UserStorageController';\n\n// State\nexport type UserStorageControllerState = {\n /**\n * Condition used by UI and to determine if we can use some of the User Storage methods.\n */\n isBackupAndSyncEnabled: boolean;\n /**\n * Loading state for the backup and sync update\n */\n isBackupAndSyncUpdateLoading: boolean;\n /**\n * Condition used by UI to determine if account syncing is enabled.\n */\n isAccountSyncingEnabled: boolean;\n /**\n * Condition used by UI to determine if contact syncing is enabled.\n */\n isContactSyncingEnabled: boolean;\n /**\n * Condition used by UI to determine if contact syncing is in progress.\n */\n isContactSyncingInProgress: boolean;\n};\n\nexport const defaultState: UserStorageControllerState = {\n isBackupAndSyncEnabled: true,\n isBackupAndSyncUpdateLoading: false,\n isAccountSyncingEnabled: true,\n isContactSyncingEnabled: true,\n isContactSyncingInProgress: false,\n};\n\nconst metadata: StateMetadata<UserStorageControllerState> = {\n isBackupAndSyncEnabled: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n isBackupAndSyncUpdateLoading: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n isAccountSyncingEnabled: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n isContactSyncingEnabled: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n isContactSyncingInProgress: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n};\n\ntype ControllerConfig = {\n env: Env;\n contactSyncing?: {\n /**\n * Callback that fires when contact sync updates a contact.\n * This is used for analytics.\n */\n onContactUpdated?: (profileId: string) => void;\n\n /**\n * Callback that fires when contact sync deletes a contact.\n * This is used for analytics.\n */\n onContactDeleted?: (profileId: string) => void;\n\n /**\n * Callback that fires when an erroneous situation happens during contact sync.\n * This is used for analytics.\n */\n onContactSyncErroneousSituation?: (\n profileId: string,\n situationMessage: string,\n sentryContext?: Record<string, unknown>,\n ) => void;\n };\n};\n\n// Messenger Actions\ntype CreateActionsObj<Controller extends keyof UserStorageController> = {\n [K in Controller]: {\n type: `${typeof controllerName}:${K}`;\n handler: UserStorageController[K];\n };\n};\ntype ActionsObj = CreateActionsObj<\n | 'performGetStorage'\n | 'performGetStorageAllFeatureEntries'\n | 'performSetStorage'\n | 'performBatchSetStorage'\n | 'performDeleteStorage'\n | 'performBatchDeleteStorage'\n | 'getStorageKey'\n>;\nexport type UserStorageControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n UserStorageControllerState\n>;\nexport type Actions =\n | ActionsObj[keyof ActionsObj]\n | UserStorageControllerGetStateAction;\nexport type UserStorageControllerPerformGetStorage =\n ActionsObj['performGetStorage'];\nexport type UserStorageControllerPerformGetStorageAllFeatureEntries =\n ActionsObj['performGetStorageAllFeatureEntries'];\nexport type UserStorageControllerPerformSetStorage =\n ActionsObj['performSetStorage'];\nexport type UserStorageControllerPerformBatchSetStorage =\n ActionsObj['performBatchSetStorage'];\nexport type UserStorageControllerPerformDeleteStorage =\n ActionsObj['performDeleteStorage'];\nexport type UserStorageControllerPerformBatchDeleteStorage =\n ActionsObj['performBatchDeleteStorage'];\nexport type UserStorageControllerGetStorageKey = ActionsObj['getStorageKey'];\n\nexport type AllowedActions =\n // Keyring Requests\n | KeyringControllerGetStateAction\n // Snap Requests\n | HandleSnapRequest\n // Auth Requests\n | AuthenticationControllerGetBearerToken\n | AuthenticationControllerGetSessionProfile\n | AuthenticationControllerPerformSignIn\n | AuthenticationControllerIsSignedIn\n // Contact Syncing\n | AddressBookControllerListAction\n | AddressBookControllerSetAction\n | AddressBookControllerDeleteAction\n | AddressBookControllerActions;\n\n// Messenger events\nexport type UserStorageControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n UserStorageControllerState\n>;\n\nexport type Events = UserStorageControllerStateChangeEvent;\n\nexport type AllowedEvents =\n | UserStorageControllerStateChangeEvent\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent\n // Address Book Events\n | AddressBookControllerContactUpdatedEvent\n | AddressBookControllerContactDeletedEvent;\n\n// Messenger\nexport type UserStorageControllerMessenger = Messenger<\n typeof controllerName,\n Actions | AllowedActions,\n Events | AllowedEvents\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 readonly #userStorage: UserStorage;\n\n readonly #auth = {\n getProfileId: async (entropySourceId?: string) => {\n const sessionProfile = await this.messenger.call(\n 'AuthenticationController:getSessionProfile',\n entropySourceId,\n );\n return sessionProfile?.profileId;\n },\n isSignedIn: () => {\n return this.messenger.call('AuthenticationController:isSignedIn');\n },\n signIn: async () => {\n return await this.messenger.call(\n 'AuthenticationController:performSignIn',\n );\n },\n };\n\n readonly #config: ControllerConfig = {\n env: Env.PRD,\n };\n\n readonly #trace: TraceCallback;\n\n #isUnlocked = false;\n\n #storageKeyCache: Record<`metamask:${string}`, string> = {};\n\n readonly #keyringController = {\n setupLockedStateSubscriptions: () => {\n const { isUnlocked } = this.messenger.call('KeyringController:getState');\n this.#isUnlocked = isUnlocked;\n\n this.messenger.subscribe('KeyringController:unlock', () => {\n this.#isUnlocked = true;\n });\n\n this.messenger.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n },\n };\n\n readonly #nativeScryptCrypto: NativeScrypt | undefined = undefined;\n\n eventQueue = new EventQueue();\n\n constructor({\n messenger,\n state,\n config,\n nativeScryptCrypto,\n trace,\n }: {\n messenger: UserStorageControllerMessenger;\n state?: UserStorageControllerState;\n config?: Partial<ControllerConfig>;\n nativeScryptCrypto?: NativeScrypt;\n trace?: TraceCallback;\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n this.#config = {\n ...this.#config,\n ...config,\n };\n this.#trace =\n trace ??\n (async <ReturnType>(\n _request: TraceRequest,\n fn?: (context?: TraceContext) => ReturnType,\n ): Promise<ReturnType> => {\n if (!fn) {\n return undefined as ReturnType;\n }\n return await Promise.resolve(fn());\n });\n\n this.#userStorage = new UserStorage(\n {\n env: this.#config.env,\n auth: {\n getAccessToken: (entropySourceId?: string) =>\n this.messenger.call(\n 'AuthenticationController:getBearerToken',\n entropySourceId,\n ),\n getUserProfile: async (entropySourceId?: string) => {\n return await this.messenger.call(\n 'AuthenticationController:getSessionProfile',\n entropySourceId,\n );\n },\n signMessage: (message: string, entropySourceId?: string) =>\n this.#snapSignMessage(\n message as `metamask:${string}`,\n entropySourceId,\n ),\n },\n },\n {\n storage: {\n getStorageKey: async (message) =>\n this.#storageKeyCache[message] ?? null,\n setStorageKey: async (message, key) => {\n this.#storageKeyCache[message] = key;\n },\n },\n },\n );\n\n this.#keyringController.setupLockedStateSubscriptions();\n this.#registerMessageHandlers();\n this.#nativeScryptCrypto = nativeScryptCrypto;\n\n // Contact Syncing\n setupContactSyncingSubscriptions({\n getUserStorageControllerInstance: () => this,\n getMessenger: () => this.messenger,\n trace: this.#trace,\n });\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers(): void {\n this.messenger.registerActionHandler(\n 'UserStorageController:performGetStorage',\n this.performGetStorage.bind(this),\n );\n\n this.messenger.registerActionHandler(\n 'UserStorageController:performGetStorageAllFeatureEntries',\n this.performGetStorageAllFeatureEntries.bind(this),\n );\n\n this.messenger.registerActionHandler(\n 'UserStorageController:performSetStorage',\n this.performSetStorage.bind(this),\n );\n\n this.messenger.registerActionHandler(\n 'UserStorageController:performBatchSetStorage',\n this.performBatchSetStorage.bind(this),\n );\n\n this.messenger.registerActionHandler(\n 'UserStorageController:performDeleteStorage',\n this.performDeleteStorage.bind(this),\n );\n\n this.messenger.registerActionHandler(\n 'UserStorageController:performBatchDeleteStorage',\n this.performBatchDeleteStorage.bind(this),\n );\n\n this.messenger.registerActionHandler(\n 'UserStorageController:getStorageKey',\n this.getStorageKey.bind(this),\n );\n }\n\n /**\n * Allows retrieval of stored data. Data stored is string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns the decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorage(\n path: UserStorageGenericPathWithFeatureAndKey,\n entropySourceId?: string,\n ): Promise<string | null> {\n return await this.#userStorage.getItem(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Allows retrieval of all stored data for a specific feature. Data stored is formatted as an array of strings.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns the array of decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorageAllFeatureEntries(\n path: UserStorageGenericPathWithFeatureOnly,\n entropySourceId?: string,\n ): Promise<string[] | null> {\n return await this.#userStorage.getAllFeatureItems(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Allows storage of user data. Data stored must be string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param value - The string data you want to store.\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performSetStorage(\n path: UserStorageGenericPathWithFeatureAndKey,\n value: string,\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.setItem(path, value, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Allows storage of multiple user data entries for one specific feature. Data stored must be string formatted.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @param values - data to store, in the form of an array of `[entryKey, entryValue]` pairs\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performBatchSetStorage(\n path: UserStorageGenericPathWithFeatureOnly,\n values: [UserStorageGenericFeatureKey, string][],\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.batchSetItems(path, values, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Allows deletion of user data. Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to delete data.\n */\n public async performDeleteStorage(\n path: UserStorageGenericPathWithFeatureAndKey,\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.deleteItem(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Allows deletion of all user data entries for a specific feature.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to delete data.\n */\n public async performDeleteStorageAllFeatureEntries(\n path: UserStorageGenericPathWithFeatureOnly,\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.deleteAllFeatureItems(path, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Allows delete of multiple user data entries for one specific feature. Data deleted must be string formatted.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @param values - data to store, in the form of an array of entryKey[]\n * @param entropySourceId - The entropy source ID used to generate the encryption key.\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performBatchDeleteStorage(\n path: UserStorageGenericPathWithFeatureOnly,\n values: UserStorageGenericFeatureKey[],\n entropySourceId?: string,\n ): Promise<void> {\n return await this.#userStorage.batchDeleteItems(path, values, {\n nativeScryptCrypto: this.#nativeScryptCrypto,\n entropySourceId,\n });\n }\n\n /**\n * Retrieves the storage key, for internal use only!\n *\n * @returns the storage key\n */\n public async getStorageKey(): Promise<string> {\n return await this.#userStorage.getStorageKey();\n }\n\n /**\n * Flushes the storage key cache.\n * CAUTION: This is only public for testing purposes.\n * It should not be used in production code.\n */\n public flushStorageKeyCache(): void {\n this.#storageKeyCache = {};\n }\n\n /**\n * Lists all the available HD keyring metadata IDs.\n * These IDs can be used in a multi-SRP context to segregate data specific to different SRPs.\n *\n * @returns A promise that resolves to an array of HD keyring metadata IDs.\n */\n async listEntropySources() {\n if (!this.#isUnlocked) {\n throw new Error(\n 'listEntropySources - unable to list entropy sources, wallet is locked',\n );\n }\n\n const { keyrings } = this.messenger.call('KeyringController:getState');\n return keyrings\n .filter((keyring) => keyring.type === KeyringTypes.hd.toString())\n .map((keyring) => keyring.metadata.id);\n }\n\n #_snapSignMessageCache: Record<`metamask:${string}`, string> = {};\n\n /**\n * Signs a specific message using an underlying auth snap.\n *\n * @param message - A specific tagged message to sign.\n * @param entropySourceId - The entropy source ID used to derive the key,\n * when multiple sources are available (Multi-SRP).\n * @returns A Signature created by the snap.\n */\n async #snapSignMessage(\n message: `metamask:${string}`,\n entropySourceId?: string,\n ): Promise<string> {\n // the message is SRP specific already, so there's no need to use the entropySourceId in the cache\n if (this.#_snapSignMessageCache[message]) {\n return this.#_snapSignMessageCache[message];\n }\n\n if (!this.#isUnlocked) {\n throw new Error(\n '#snapSignMessage - unable to call snap, wallet is locked',\n );\n }\n\n const result = (await this.messenger.call(\n 'SnapController:handleRequest',\n createSnapSignMessageRequest(message, entropySourceId),\n )) as string;\n\n this.#_snapSignMessageCache[message] = result;\n\n return result;\n }\n\n public async setIsBackupAndSyncFeatureEnabled(\n feature: keyof typeof BACKUPANDSYNC_FEATURES,\n enabled: boolean,\n ): Promise<void> {\n try {\n this.#setIsBackupAndSyncUpdateLoading(true);\n\n if (enabled) {\n // If any of the features are enabled, we need to ensure the user is signed in\n const isSignedIn = this.#auth.isSignedIn();\n if (!isSignedIn) {\n await this.#auth.signIn();\n }\n }\n\n this.update((state) => {\n if (feature === BACKUPANDSYNC_FEATURES.main) {\n state.isBackupAndSyncEnabled = enabled;\n }\n\n if (feature === BACKUPANDSYNC_FEATURES.accountSyncing) {\n state.isAccountSyncingEnabled = enabled;\n }\n\n if (feature === BACKUPANDSYNC_FEATURES.contactSyncing) {\n state.isContactSyncingEnabled = enabled;\n }\n });\n } catch (e) {\n // istanbul ignore next\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n // istanbul ignore next\n throw new Error(\n `${controllerName} - failed to ${enabled ? 'enable' : 'disable'} ${feature} - ${errorMessage}`,\n );\n } finally {\n this.#setIsBackupAndSyncUpdateLoading(false);\n }\n }\n\n #setIsBackupAndSyncUpdateLoading(\n isBackupAndSyncUpdateLoading: boolean,\n ): void {\n this.update((state) => {\n state.isBackupAndSyncUpdateLoading = isBackupAndSyncUpdateLoading;\n });\n }\n\n /**\n * Sets the isContactSyncingInProgress flag to prevent infinite loops during contact synchronization\n *\n * @param isContactSyncingInProgress - Whether contact syncing is in progress\n */\n async setIsContactSyncingInProgress(\n isContactSyncingInProgress: boolean,\n ): Promise<void> {\n this.update((state) => {\n state.isContactSyncingInProgress = isContactSyncingInProgress;\n });\n }\n\n /**\n * Syncs the address book list with the user storage address book list.\n * This method is used to make sure that the address book list is up-to-date with the user storage address book list and vice-versa.\n * It will add new contacts to the address book list, update/merge conflicting contacts and re-upload the results in some cases to the user storage.\n */\n async syncContactsWithUserStorage(): Promise<void> {\n const profileId = await this.#auth.getProfileId();\n\n const config = {\n onContactUpdated: () => {\n this.#config?.contactSyncing?.onContactUpdated?.(profileId);\n },\n onContactDeleted: () => {\n this.#config?.contactSyncing?.onContactDeleted?.(profileId);\n },\n onContactSyncErroneousSituation: (\n errorMessage: string,\n sentryContext?: Record<string, unknown>,\n ) => {\n this.#config?.contactSyncing?.onContactSyncErroneousSituation?.(\n profileId,\n errorMessage,\n sentryContext,\n );\n },\n };\n\n await syncContactsWithUserStorage(config, {\n getMessenger: () => this.messenger,\n getUserStorageControllerInstance: () => this,\n trace: this.#trace,\n });\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask-previews/profile-sync-controller",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "26.0.0-preview-46d2c977",
|
|
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,7 +100,8 @@
|
|
|
100
100
|
"test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch"
|
|
101
101
|
},
|
|
102
102
|
"dependencies": {
|
|
103
|
-
"@metamask/base-controller": "^
|
|
103
|
+
"@metamask/base-controller": "^9.0.0",
|
|
104
|
+
"@metamask/messenger": "^0.3.0",
|
|
104
105
|
"@metamask/snaps-sdk": "^9.0.0",
|
|
105
106
|
"@metamask/snaps-utils": "^11.0.0",
|
|
106
107
|
"@metamask/utils": "^11.8.1",
|
|
@@ -113,10 +114,10 @@
|
|
|
113
114
|
"devDependencies": {
|
|
114
115
|
"@lavamoat/allow-scripts": "^3.0.4",
|
|
115
116
|
"@lavamoat/preinstall-always-fail": "^2.1.0",
|
|
116
|
-
"@metamask/address-book-controller": "^
|
|
117
|
+
"@metamask/address-book-controller": "^7.0.0",
|
|
117
118
|
"@metamask/auto-changelog": "^3.4.4",
|
|
118
119
|
"@metamask/keyring-api": "^21.0.0",
|
|
119
|
-
"@metamask/keyring-controller": "^
|
|
120
|
+
"@metamask/keyring-controller": "^24.0.0",
|
|
120
121
|
"@metamask/keyring-internal-api": "^9.0.0",
|
|
121
122
|
"@metamask/providers": "^22.1.0",
|
|
122
123
|
"@metamask/snaps-controllers": "^14.0.1",
|
|
@@ -133,8 +134,8 @@
|
|
|
133
134
|
"webextension-polyfill": "^0.12.0"
|
|
134
135
|
},
|
|
135
136
|
"peerDependencies": {
|
|
136
|
-
"@metamask/address-book-controller": "^
|
|
137
|
-
"@metamask/keyring-controller": "^
|
|
137
|
+
"@metamask/address-book-controller": "^7.0.0",
|
|
138
|
+
"@metamask/keyring-controller": "^24.0.0",
|
|
138
139
|
"@metamask/providers": "^22.0.0",
|
|
139
140
|
"@metamask/snaps-controllers": "^14.0.0",
|
|
140
141
|
"webextension-polyfill": "^0.10.0 || ^0.11.0 || ^0.12.0"
|