@metamask/profile-sync-controller 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/CHANGELOG.md +13 -1
  2. package/dist/{chunk-77LSWSGB.js → chunk-4DQF2YNS.js} +9 -12
  3. package/dist/chunk-4DQF2YNS.js.map +1 -0
  4. package/dist/{chunk-LDEIUP6J.mjs → chunk-CJLDMVV3.mjs} +2 -2
  5. package/dist/{chunk-R2S3HIDN.js → chunk-JENTMRXO.js} +27 -3
  6. package/dist/chunk-JENTMRXO.js.map +1 -0
  7. package/dist/{chunk-DHKZ2NEF.js → chunk-KW3X4TT5.js} +30 -2
  8. package/dist/chunk-KW3X4TT5.js.map +1 -0
  9. package/dist/{chunk-BXPL7ZFX.js → chunk-MNVUKRZC.js} +4 -4
  10. package/dist/{chunk-LNSB4L7K.mjs → chunk-QE5X2BT3.mjs} +28 -4
  11. package/dist/chunk-QE5X2BT3.mjs.map +1 -0
  12. package/dist/{chunk-Y7P3UH26.mjs → chunk-WWQ65CZY.mjs} +30 -2
  13. package/dist/chunk-WWQ65CZY.mjs.map +1 -0
  14. package/dist/{chunk-IQECLCH4.mjs → chunk-XMYWJQNH.mjs} +7 -10
  15. package/dist/chunk-XMYWJQNH.mjs.map +1 -0
  16. package/dist/controllers/authentication/AuthenticationController.js +2 -2
  17. package/dist/controllers/authentication/AuthenticationController.mjs +1 -1
  18. package/dist/controllers/authentication/index.js +3 -3
  19. package/dist/controllers/authentication/index.mjs +2 -2
  20. package/dist/controllers/index.js +5 -5
  21. package/dist/controllers/index.mjs +4 -4
  22. package/dist/controllers/user-storage/UserStorageController.js +2 -2
  23. package/dist/controllers/user-storage/UserStorageController.mjs +1 -1
  24. package/dist/controllers/user-storage/index.js +3 -3
  25. package/dist/controllers/user-storage/index.mjs +2 -2
  26. package/dist/index.js +5 -5
  27. package/dist/index.mjs +4 -4
  28. package/dist/tsconfig.build.tsbuildinfo +1 -1
  29. package/dist/types/controllers/authentication/AuthenticationController.d.ts +4 -2
  30. package/dist/types/controllers/authentication/AuthenticationController.d.ts.map +1 -1
  31. package/dist/types/controllers/user-storage/UserStorageController.d.ts +4 -2
  32. package/dist/types/controllers/user-storage/UserStorageController.d.ts.map +1 -1
  33. package/dist/types/controllers/user-storage/__fixtures__/mockStorage.d.ts +1 -1
  34. package/dist/types/controllers/user-storage/__fixtures__/mockStorage.d.ts.map +1 -1
  35. package/package.json +4 -2
  36. package/dist/chunk-77LSWSGB.js.map +0 -1
  37. package/dist/chunk-DHKZ2NEF.js.map +0 -1
  38. package/dist/chunk-IQECLCH4.mjs.map +0 -1
  39. package/dist/chunk-LNSB4L7K.mjs.map +0 -1
  40. package/dist/chunk-R2S3HIDN.js.map +0 -1
  41. package/dist/chunk-Y7P3UH26.mjs.map +0 -1
  42. /package/dist/{chunk-LDEIUP6J.mjs.map → chunk-CJLDMVV3.mjs.map} +0 -0
  43. /package/dist/{chunk-BXPL7ZFX.js.map → chunk-MNVUKRZC.js.map} +0 -0
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
+ ## [0.2.1]
11
+
12
+ ### Added
13
+
14
+ - unlock checks for when controller methods are called ([#4569](https://github.com/MetaMask/core/pull/4569))
15
+
16
+ ### Changed
17
+
18
+ - **BREAKING** made `MOCK_ENCRYPTED_STORAGE_DATA` fixture a function to be lazily evaluated ([#4592](https://github.com/MetaMask/core/pull/4592))
19
+ - Bump `typescript` from `~5.0.4` to `~5.1.6` ([#4576](https://github.com/MetaMask/core/pull/4576))
20
+
10
21
  ## [0.2.0]
11
22
 
12
23
  ### Added
@@ -84,7 +95,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
84
95
 
85
96
  - Initial release
86
97
 
87
- [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@0.2.0...HEAD
98
+ [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@0.2.1...HEAD
99
+ [0.2.1]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@0.2.0...@metamask/profile-sync-controller@0.2.1
88
100
  [0.2.0]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@0.1.4...@metamask/profile-sync-controller@0.2.0
89
101
  [0.1.4]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@0.1.3...@metamask/profile-sync-controller@0.1.4
90
102
  [0.1.3]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@0.1.2...@metamask/profile-sync-controller@0.1.3
@@ -1,7 +1,7 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
2
 
3
3
 
4
- var _chunkR2S3HIDNjs = require('./chunk-R2S3HIDN.js');
4
+ var _chunkJENTMRXOjs = require('./chunk-JENTMRXO.js');
5
5
 
6
6
 
7
7
  var _chunk3TE6M5TVjs = require('./chunk-3TE6M5TV.js');
@@ -22,11 +22,11 @@ var _chunkIGY2S5BCjs = require('./chunk-IGY2S5BC.js');
22
22
  // src/controllers/user-storage/index.ts
23
23
  var user_storage_exports = {};
24
24
  _chunkIGY2S5BCjs.__export.call(void 0, user_storage_exports, {
25
- Controller: () => _chunkR2S3HIDNjs.UserStorageController,
25
+ Controller: () => _chunkJENTMRXOjs.UserStorageController,
26
26
  Encryption: () => _chunkT3FNDVE3js.encryption_default,
27
27
  Mocks: () => fixtures_exports,
28
28
  createSHA256Hash: () => _chunkT3FNDVE3js.createSHA256Hash,
29
- defaultState: () => _chunkR2S3HIDNjs.defaultState
29
+ defaultState: () => _chunkJENTMRXOjs.defaultState
30
30
  });
31
31
 
32
32
  // src/controllers/user-storage/__fixtures__/index.ts
@@ -45,25 +45,22 @@ _chunkIGY2S5BCjs.__export.call(void 0, fixtures_exports, {
45
45
  var MOCK_STORAGE_KEY_SIGNATURE = "mockStorageKey";
46
46
  var MOCK_STORAGE_KEY = _chunkT3FNDVE3js.createSHA256Hash.call(void 0, MOCK_STORAGE_KEY_SIGNATURE);
47
47
  var MOCK_STORAGE_DATA = JSON.stringify({ hello: "world" });
48
- var MOCK_ENCRYPTED_STORAGE_DATA = _chunkAK7OTIWAjs.encryption_default.encryptString(
49
- MOCK_STORAGE_DATA,
50
- MOCK_STORAGE_KEY
51
- );
48
+ var MOCK_ENCRYPTED_STORAGE_DATA = () => _chunkAK7OTIWAjs.encryption_default.encryptString(MOCK_STORAGE_DATA, MOCK_STORAGE_KEY);
52
49
 
53
50
  // src/controllers/user-storage/__fixtures__/mockResponses.ts
54
51
  var MOCK_USER_STORAGE_NOTIFICATIONS_ENDPOINT = `${_chunk3TE6M5TVjs.USER_STORAGE_ENDPOINT}${_chunkSLHAVOTEjs.createEntryPath.call(void 0,
55
52
  "notifications.notificationSettings",
56
53
  MOCK_STORAGE_KEY
57
54
  )}`;
58
- var MOCK_GET_USER_STORAGE_RESPONSE = {
55
+ var MOCK_GET_USER_STORAGE_RESPONSE = () => ({
59
56
  HashedKey: "HASHED_KEY",
60
- Data: MOCK_ENCRYPTED_STORAGE_DATA
61
- };
57
+ Data: MOCK_ENCRYPTED_STORAGE_DATA()
58
+ });
62
59
  var getMockUserStorageGetResponse = () => {
63
60
  return {
64
61
  url: MOCK_USER_STORAGE_NOTIFICATIONS_ENDPOINT,
65
62
  requestMethod: "GET",
66
- response: MOCK_GET_USER_STORAGE_RESPONSE
63
+ response: MOCK_GET_USER_STORAGE_RESPONSE()
67
64
  };
68
65
  };
69
66
  var getMockUserStoragePutResponse = () => {
@@ -78,4 +75,4 @@ var getMockUserStoragePutResponse = () => {
78
75
 
79
76
 
80
77
  exports.fixtures_exports = fixtures_exports; exports.user_storage_exports = user_storage_exports;
81
- //# sourceMappingURL=chunk-77LSWSGB.js.map
78
+ //# sourceMappingURL=chunk-4DQF2YNS.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/controllers/user-storage/index.ts","../src/controllers/user-storage/__fixtures__/index.ts","../src/controllers/user-storage/__fixtures__/mockStorage.ts","../src/controllers/user-storage/__fixtures__/mockResponses.ts"],"names":["encryption_default"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEO,IAAM,6BAA6B;AACnC,IAAM,mBAAmB,iBAAiB,0BAA0B;AACpE,IAAM,oBAAoB,KAAK,UAAU,EAAE,OAAO,QAAQ,CAAC;AAI3D,IAAM,8BAA8B,MACzCA,oBAAW,cAAc,mBAAmB,gBAAgB;;;ACEvD,IAAM,2CAA2C,GAAG,qBAAqB,GAAG;AAAA,EACjF;AAAA,EACA;AACF,CAAC;AAED,IAAM,iCAAiC,OAA+B;AAAA,EACpE,WAAW;AAAA,EACX,MAAM,4BAA4B;AACpC;AAEO,IAAM,gCAAgC,MAAM;AACjD,SAAO;AAAA,IACL,KAAK;AAAA,IACL,eAAe;AAAA,IACf,UAAU,+BAA+B;AAAA,EAC3C;AACF;AAEO,IAAM,gCAAgC,MAAM;AACjD,SAAO;AAAA,IACL,KAAK;AAAA,IACL,eAAe;AAAA,IACf,UAAU;AAAA,EACZ;AACF","sourcesContent":["import Controller from './UserStorageController';\n\nexport { Controller };\nexport * from './UserStorageController';\nexport * from './encryption';\nexport * as Mocks from './__fixtures__';\n","export * from './mockResponses';\nexport * from './mockStorage';\n","import encryption, { createSHA256Hash } from '../encryption';\n\nexport const MOCK_STORAGE_KEY_SIGNATURE = 'mockStorageKey';\nexport const MOCK_STORAGE_KEY = createSHA256Hash(MOCK_STORAGE_KEY_SIGNATURE);\nexport const MOCK_STORAGE_DATA = JSON.stringify({ hello: 'world' });\n\n// NOTE - using encryption.encryptString directly in fixtures causes issues on mobile.\n// This is because this fixture is getting added in at run time. Will be improved once we support multiple exports\nexport const MOCK_ENCRYPTED_STORAGE_DATA = () =>\n encryption.encryptString(MOCK_STORAGE_DATA, MOCK_STORAGE_KEY);\n","import { createEntryPath } from '../schema';\nimport type { GetUserStorageResponse } from '../services';\nimport { USER_STORAGE_ENDPOINT } from '../services';\nimport { MOCK_ENCRYPTED_STORAGE_DATA, MOCK_STORAGE_KEY } from './mockStorage';\n\ntype MockResponse = {\n url: string;\n requestMethod: 'GET' | 'POST' | 'PUT';\n response: unknown;\n};\n\nexport const MOCK_USER_STORAGE_NOTIFICATIONS_ENDPOINT = `${USER_STORAGE_ENDPOINT}${createEntryPath(\n 'notifications.notificationSettings',\n MOCK_STORAGE_KEY,\n)}`;\n\nconst MOCK_GET_USER_STORAGE_RESPONSE = (): GetUserStorageResponse => ({\n HashedKey: 'HASHED_KEY',\n Data: MOCK_ENCRYPTED_STORAGE_DATA(),\n});\n\nexport const getMockUserStorageGetResponse = () => {\n return {\n url: MOCK_USER_STORAGE_NOTIFICATIONS_ENDPOINT,\n requestMethod: 'GET',\n response: MOCK_GET_USER_STORAGE_RESPONSE(),\n } satisfies MockResponse;\n};\n\nexport const getMockUserStoragePutResponse = () => {\n return {\n url: MOCK_USER_STORAGE_NOTIFICATIONS_ENDPOINT,\n requestMethod: 'PUT',\n response: null,\n } satisfies MockResponse;\n};\n"]}
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  AuthenticationController,
3
3
  defaultState
4
- } from "./chunk-Y7P3UH26.mjs";
4
+ } from "./chunk-WWQ65CZY.mjs";
5
5
  import {
6
6
  AUTH_LOGIN_ENDPOINT,
7
7
  AUTH_NONCE_ENDPOINT,
@@ -83,4 +83,4 @@ export {
83
83
  fixtures_exports,
84
84
  authentication_exports
85
85
  };
86
- //# sourceMappingURL=chunk-LDEIUP6J.mjs.map
86
+ //# sourceMappingURL=chunk-CJLDMVV3.mjs.map
@@ -12,6 +12,7 @@ var _chunkT3FNDVE3js = require('./chunk-T3FNDVE3.js');
12
12
 
13
13
 
14
14
 
15
+
15
16
  var _chunkIGY2S5BCjs = require('./chunk-IGY2S5BC.js');
16
17
 
17
18
  // src/controllers/user-storage/UserStorageController.ts
@@ -31,7 +32,7 @@ var metadata = {
31
32
  anonymous: false
32
33
  }
33
34
  };
34
- var _auth, _notificationServices, _registerMessageHandlers, registerMessageHandlers_fn, _assertProfileSyncingEnabled, assertProfileSyncingEnabled_fn, _getStorageKeyAndBearerToken, getStorageKeyAndBearerToken_fn, _createStorageKey, createStorageKey_fn, __snapSignMessageCache, _snapSignMessage, snapSignMessage_fn, _setIsProfileSyncingUpdateLoading, setIsProfileSyncingUpdateLoading_fn;
35
+ var _auth, _notificationServices, _isUnlocked, _keyringController, _registerMessageHandlers, registerMessageHandlers_fn, _assertProfileSyncingEnabled, assertProfileSyncingEnabled_fn, _getStorageKeyAndBearerToken, getStorageKeyAndBearerToken_fn, _createStorageKey, createStorageKey_fn, __snapSignMessageCache, _snapSignMessage, snapSignMessage_fn, _setIsProfileSyncingUpdateLoading, setIsProfileSyncingUpdateLoading_fn;
35
36
  var UserStorageController = class extends _basecontroller.BaseController {
36
37
  constructor(params) {
37
38
  super({
@@ -102,8 +103,24 @@ var UserStorageController = class extends _basecontroller.BaseController {
102
103
  );
103
104
  }
104
105
  });
106
+ _chunkIGY2S5BCjs.__privateAdd.call(void 0, this, _isUnlocked, false);
107
+ _chunkIGY2S5BCjs.__privateAdd.call(void 0, this, _keyringController, {
108
+ setupLockedStateSubscriptions: () => {
109
+ const { isUnlocked } = this.messagingSystem.call(
110
+ "KeyringController:getState"
111
+ );
112
+ _chunkIGY2S5BCjs.__privateSet.call(void 0, this, _isUnlocked, isUnlocked);
113
+ this.messagingSystem.subscribe("KeyringController:unlock", () => {
114
+ _chunkIGY2S5BCjs.__privateSet.call(void 0, this, _isUnlocked, true);
115
+ });
116
+ this.messagingSystem.subscribe("KeyringController:lock", () => {
117
+ _chunkIGY2S5BCjs.__privateSet.call(void 0, this, _isUnlocked, false);
118
+ });
119
+ }
120
+ });
105
121
  _chunkIGY2S5BCjs.__privateAdd.call(void 0, this, __snapSignMessageCache, {});
106
122
  this.getMetaMetricsState = params.getMetaMetricsState;
123
+ _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _keyringController).setupLockedStateSubscriptions();
107
124
  _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _registerMessageHandlers, registerMessageHandlers_fn).call(this);
108
125
  }
109
126
  async enableProfileSyncing() {
@@ -143,7 +160,7 @@ var UserStorageController = class extends _basecontroller.BaseController {
143
160
  }
144
161
  const isMetaMetricsParticipation = this.getMetaMetricsState();
145
162
  if (!isMetaMetricsParticipation) {
146
- this.messagingSystem.call("AuthenticationController:performSignOut");
163
+ await _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _auth).signOut();
147
164
  }
148
165
  _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _setIsProfileSyncingUpdateLoading, setIsProfileSyncingUpdateLoading_fn).call(this, false);
149
166
  this.update((state) => {
@@ -204,6 +221,8 @@ var UserStorageController = class extends _basecontroller.BaseController {
204
221
  };
205
222
  _auth = new WeakMap();
206
223
  _notificationServices = new WeakMap();
224
+ _isUnlocked = new WeakMap();
225
+ _keyringController = new WeakMap();
207
226
  _registerMessageHandlers = new WeakSet();
208
227
  registerMessageHandlers_fn = function() {
209
228
  this.messagingSystem.registerActionHandler(
@@ -260,6 +279,11 @@ snapSignMessage_fn = async function(message) {
260
279
  if (_chunkIGY2S5BCjs.__privateGet.call(void 0, this, __snapSignMessageCache)[message]) {
261
280
  return _chunkIGY2S5BCjs.__privateGet.call(void 0, this, __snapSignMessageCache)[message];
262
281
  }
282
+ if (!_chunkIGY2S5BCjs.__privateGet.call(void 0, this, _isUnlocked)) {
283
+ throw new Error(
284
+ "#snapSignMessage - unable to call snap, wallet is locked"
285
+ );
286
+ }
263
287
  const result = await this.messagingSystem.call(
264
288
  "SnapController:handleRequest",
265
289
  _chunkYHGWG3EQjs.createSnapSignMessageRequest.call(void 0, message)
@@ -278,4 +302,4 @@ setIsProfileSyncingUpdateLoading_fn = function(isProfileSyncingUpdateLoading) {
278
302
 
279
303
 
280
304
  exports.defaultState = defaultState; exports.UserStorageController = UserStorageController;
281
- //# sourceMappingURL=chunk-R2S3HIDN.js.map
305
+ //# sourceMappingURL=chunk-JENTMRXO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/controllers/user-storage/UserStorageController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAIA,SAAS,sBAAsB;AAiC/B,IAAM,iBAAiB;AAchB,IAAM,eAA2C;AAAA,EACtD,yBAAyB;AAAA,EACzB,+BAA+B;AACjC;AAEA,IAAM,WAAsD;AAAA,EAC1D,yBAAyB;AAAA,IACvB,SAAS;AAAA,IACT,WAAW;AAAA,EACb;AAAA,EACA,+BAA+B;AAAA,IAC7B,SAAS;AAAA,IACT,WAAW;AAAA,EACb;AACF;AAjEA;AAiIA,IAAqB,wBAArB,cAAmD,eAIjD;AAAA,EA8DA,YAAY,QAIT;AACD,UAAM;AAAA,MACJ,WAAW,OAAO;AAAA,MAClB;AAAA,MACA,MAAM;AAAA,MACN,OAAO,EAAE,GAAG,cAAc,GAAG,OAAO,MAAM;AAAA,IAC5C,CAAC;AAWH;AAAA;AAAA;AAAA;AAAA;AAyJA;AAWA;AAAA;AAAA;AAAA,uBAAM;AAkBN;AAAA;AAAA;AAAA;AAAA;AAAA,uBAAM;AAmBN;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,uBAAM;AAqBN;AAhTA,8BAAQ;AAAA,MACN,gBAAgB,YAAY;AAC1B,eAAO,MAAM,KAAK,gBAAgB;AAAA,UAChC;AAAA,QACF;AAAA,MACF;AAAA,MACA,cAAc,YAAY;AACxB,cAAM,iBAAiB,MAAM,KAAK,gBAAgB;AAAA,UAChD;AAAA,QACF;AACA,eAAO,gBAAgB;AAAA,MACzB;AAAA,MACA,eAAe,MAAM;AACnB,eAAO,KAAK,gBAAgB,KAAK,qCAAqC;AAAA,MACxE;AAAA,MACA,QAAQ,YAAY;AAClB,eAAO,MAAM,KAAK,gBAA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iBAAiB,mBAAmB;AACvD,SAAO;AACT;AAEA;AAQM;AAAA,qBAAgB,eAAC,SAAgD;AACrE,MAAI,mBAAK,wBAAuB,OAAO,GAAG;AACxC,WAAO,mBAAK,wBAAuB,OAAO;AAAA,EAC5C;AAEA,MAAI,CAAC,mBAAK,cAAa;AACrB,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM,SAAU,MAAM,KAAK,gBAAgB;AAAA,IACzC;AAAA,IACA,6BAA6B,OAAO;AAAA,EACtC;AAEA,qBAAK,wBAAuB,OAAO,IAAI;AAEvC,SAAO;AACT;AAEA;AAAA,sCAAiC,SAC/B,+BACM;AACN,OAAK,OAAO,CAAC,UAAU;AACrB,UAAM,gCAAgC;AAAA,EACxC,CAAC;AACH","sourcesContent":["import type {\n RestrictedControllerMessenger,\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';\n\nimport { createSnapSignMessageRequest } from '../authentication/auth-snap-requests';\nimport type {\n AuthenticationControllerGetBearerToken,\n AuthenticationControllerGetSessionProfile,\n AuthenticationControllerIsSignedIn,\n AuthenticationControllerPerformSignIn,\n AuthenticationControllerPerformSignOut,\n} from '../authentication/AuthenticationController';\nimport { createSHA256Hash } from './encryption';\nimport type { UserStoragePath } from './schema';\nimport { getUserStorage, upsertUserStorage } from './services';\n\n// TODO: fix external dependencies\nexport declare type NotificationServicesControllerDisableNotificationServices =\n {\n type: `NotificationServicesController:disableNotificationServices`;\n handler: () => Promise<void>;\n };\n\nexport declare type NotificationServicesControllerSelectIsNotificationServicesEnabled =\n {\n type: `NotificationServicesController:selectIsNotificationServicesEnabled`;\n handler: () => boolean;\n };\n\nconst controllerName = 'UserStorageController';\n\n// State\nexport type UserStorageControllerState = {\n /**\n * Condition used by UI and to determine if we can use some of the User Storage methods.\n */\n isProfileSyncingEnabled: boolean | null;\n /**\n * Loading state for the profile syncing update\n */\n isProfileSyncingUpdateLoading: boolean;\n};\n\nexport const defaultState: UserStorageControllerState = {\n isProfileSyncingEnabled: true,\n isProfileSyncingUpdateLoading: false,\n};\n\nconst metadata: StateMetadata<UserStorageControllerState> = {\n isProfileSyncingEnabled: {\n persist: true,\n anonymous: true,\n },\n isProfileSyncingUpdateLoading: {\n persist: false,\n anonymous: false,\n },\n};\n\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 | 'performSetStorage'\n | 'getStorageKey'\n | 'enableProfileSyncing'\n | 'disableProfileSyncing'\n>;\nexport type Actions = ActionsObj[keyof ActionsObj];\nexport type UserStorageControllerPerformGetStorage =\n ActionsObj['performGetStorage'];\nexport type UserStorageControllerPerformSetStorage =\n ActionsObj['performSetStorage'];\nexport type UserStorageControllerGetStorageKey = ActionsObj['getStorageKey'];\nexport type UserStorageControllerEnableProfileSyncing =\n ActionsObj['enableProfileSyncing'];\nexport type UserStorageControllerDisableProfileSyncing =\n ActionsObj['disableProfileSyncing'];\n\n// Allowed Actions\nexport type AllowedActions =\n // Keyring Requests\n | KeyringControllerGetStateAction\n // Snap Requests\n | HandleSnapRequest\n // Auth Requests\n | AuthenticationControllerGetBearerToken\n | AuthenticationControllerGetSessionProfile\n | AuthenticationControllerPerformSignIn\n | AuthenticationControllerIsSignedIn\n | AuthenticationControllerPerformSignOut\n // Metamask Notifications\n | NotificationServicesControllerDisableNotificationServices\n | NotificationServicesControllerSelectIsNotificationServicesEnabled;\n\nexport type AllowedEvents =\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent;\n\n// Messenger\nexport type UserStorageControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n Actions | AllowedActions,\n AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Reusable controller that allows any team to store synchronized data for a given user.\n * These can be settings shared cross MetaMask clients, or data we want to persist when uninstalling/reinstalling.\n *\n * NOTE:\n * - data stored on UserStorage is FULLY encrypted, with the only keys stored/managed on the client.\n * - No one can access this data unless they are have the SRP and are able to run the signing snap.\n */\nexport default class UserStorageController extends BaseController<\n typeof controllerName,\n UserStorageControllerState,\n UserStorageControllerMessenger\n> {\n #auth = {\n getBearerToken: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:getBearerToken',\n );\n },\n getProfileId: async () => {\n const sessionProfile = await this.messagingSystem.call(\n 'AuthenticationController:getSessionProfile',\n );\n return sessionProfile?.profileId;\n },\n isAuthEnabled: () => {\n return this.messagingSystem.call('AuthenticationController:isSignedIn');\n },\n signIn: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:performSignIn',\n );\n },\n signOut: async () => {\n return this.messagingSystem.call(\n 'AuthenticationController:performSignOut',\n );\n },\n };\n\n #notificationServices = {\n disableNotificationServices: async () => {\n return await this.messagingSystem.call(\n 'NotificationServicesController:disableNotificationServices',\n );\n },\n selectIsNotificationServicesEnabled: async () => {\n return this.messagingSystem.call(\n 'NotificationServicesController:selectIsNotificationServicesEnabled',\n );\n },\n };\n\n #isUnlocked = false;\n\n #keyringController = {\n setupLockedStateSubscriptions: () => {\n const { isUnlocked } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n this.#isUnlocked = isUnlocked;\n\n this.messagingSystem.subscribe('KeyringController:unlock', () => {\n this.#isUnlocked = true;\n });\n\n this.messagingSystem.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n },\n };\n\n getMetaMetricsState: () => boolean;\n\n constructor(params: {\n messenger: UserStorageControllerMessenger;\n state?: UserStorageControllerState;\n getMetaMetricsState: () => boolean;\n }) {\n super({\n messenger: params.messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...params.state },\n });\n\n this.getMetaMetricsState = params.getMetaMetricsState;\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 'UserStorageController:performGetStorage',\n this.performGetStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performSetStorage',\n this.performSetStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:getStorageKey',\n this.getStorageKey.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:enableProfileSyncing',\n this.enableProfileSyncing.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:disableProfileSyncing',\n this.disableProfileSyncing.bind(this),\n );\n }\n\n public async enableProfileSyncing(): Promise<void> {\n try {\n this.#setIsProfileSyncingUpdateLoading(true);\n\n const authEnabled = this.#auth.isAuthEnabled();\n if (!authEnabled) {\n await this.#auth.signIn();\n }\n\n this.update((state) => {\n state.isProfileSyncingEnabled = true;\n });\n\n this.#setIsProfileSyncingUpdateLoading(false);\n } catch (e) {\n this.#setIsProfileSyncingUpdateLoading(false);\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to enable profile syncing - ${errorMessage}`,\n );\n }\n }\n\n public async setIsProfileSyncingEnabled(\n isProfileSyncingEnabled: boolean,\n ): Promise<void> {\n this.update((state) => {\n state.isProfileSyncingEnabled = isProfileSyncingEnabled;\n });\n }\n\n public async disableProfileSyncing(): Promise<void> {\n const isAlreadyDisabled = !this.state.isProfileSyncingEnabled;\n if (isAlreadyDisabled) {\n return;\n }\n\n try {\n this.#setIsProfileSyncingUpdateLoading(true);\n\n const isNotificationServicesEnabled =\n await this.#notificationServices.selectIsNotificationServicesEnabled();\n\n if (isNotificationServicesEnabled) {\n await this.#notificationServices.disableNotificationServices();\n }\n\n const isMetaMetricsParticipation = this.getMetaMetricsState();\n\n if (!isMetaMetricsParticipation) {\n await this.#auth.signOut();\n }\n\n this.#setIsProfileSyncingUpdateLoading(false);\n\n this.update((state) => {\n state.isProfileSyncingEnabled = false;\n });\n } catch (e) {\n this.#setIsProfileSyncingUpdateLoading(false);\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to disable profile syncing - ${errorMessage}`,\n );\n }\n }\n\n /**\n * Allows retrieval of stored data. Data stored is string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @returns the decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorage(\n path: UserStoragePath,\n ): Promise<string | null> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n const result = await getUserStorage({\n path,\n bearerToken,\n storageKey,\n });\n\n return result;\n }\n\n /**\n * Allows storage of user data. Data stored must be string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param value - The string data you want to store.\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performSetStorage(\n path: UserStoragePath,\n value: string,\n ): Promise<void> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n await upsertUserStorage(value, {\n path,\n bearerToken,\n storageKey,\n });\n }\n\n /**\n * Retrieves the storage key, for internal use only!\n *\n * @returns the storage key\n */\n public async getStorageKey(): Promise<string> {\n this.#assertProfileSyncingEnabled();\n const storageKey = await this.#createStorageKey();\n return storageKey;\n }\n\n #assertProfileSyncingEnabled(): void {\n if (!this.state.isProfileSyncingEnabled) {\n throw new Error(\n `${controllerName}: Unable to call method, user is not authenticated`,\n );\n }\n }\n\n /**\n * Utility to get the bearer token and storage key\n */\n async #getStorageKeyAndBearerToken(): Promise<{\n bearerToken: string;\n storageKey: string;\n }> {\n const bearerToken = await this.#auth.getBearerToken();\n if (!bearerToken) {\n throw new Error('UserStorageController - unable to get bearer token');\n }\n const storageKey = await this.#createStorageKey();\n\n return { bearerToken, storageKey };\n }\n\n /**\n * Rather than storing the storage key, we can compute the storage key when needed.\n *\n * @returns the storage key\n */\n async #createStorageKey(): Promise<string> {\n const id: string = await this.#auth.getProfileId();\n if (!id) {\n throw new Error('UserStorageController - unable to create storage key');\n }\n\n const storageKeySignature = await this.#snapSignMessage(`metamask:${id}`);\n const storageKey = createSHA256Hash(storageKeySignature);\n return storageKey;\n }\n\n #_snapSignMessageCache: Record<`metamask:${string}`, string> = {};\n\n /**\n * Signs a specific message using an underlying auth snap.\n *\n * @param message - A specific tagged message to sign.\n * @returns A Signature created by the snap.\n */\n async #snapSignMessage(message: `metamask:${string}`): Promise<string> {\n if (this.#_snapSignMessageCache[message]) {\n return this.#_snapSignMessageCache[message];\n }\n\n if (!this.#isUnlocked) {\n throw new Error(\n '#snapSignMessage - unable to call snap, wallet is locked',\n );\n }\n\n const result = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n createSnapSignMessageRequest(message),\n )) as string;\n\n this.#_snapSignMessageCache[message] = result;\n\n return result;\n }\n\n #setIsProfileSyncingUpdateLoading(\n isProfileSyncingUpdateLoading: boolean,\n ): void {\n this.update((state) => {\n state.isProfileSyncingUpdateLoading = isProfileSyncingUpdateLoading;\n });\n }\n}\n"]}
@@ -32,7 +32,7 @@ var metadata = {
32
32
  anonymous: false
33
33
  }
34
34
  };
35
- var _metametrics, _registerMessageHandlers, registerMessageHandlers_fn, _assertLoggedIn, assertLoggedIn_fn, _performAuthenticationFlow, performAuthenticationFlow_fn, _hasValidSession, hasValidSession_fn, __snapPublicKeyCache, _snapGetPublicKey, snapGetPublicKey_fn, __snapSignMessageCache, _snapSignMessage, snapSignMessage_fn;
35
+ var _metametrics, _isUnlocked, _keyringController, _registerMessageHandlers, registerMessageHandlers_fn, _assertLoggedIn, assertLoggedIn_fn, _performAuthenticationFlow, performAuthenticationFlow_fn, _hasValidSession, hasValidSession_fn, __snapPublicKeyCache, _snapGetPublicKey, snapGetPublicKey_fn, __snapSignMessageCache, _snapSignMessage, snapSignMessage_fn;
36
36
  var AuthenticationController = class extends _basecontroller.BaseController {
37
37
  constructor({
38
38
  messenger,
@@ -67,12 +67,28 @@ var AuthenticationController = class extends _basecontroller.BaseController {
67
67
  */
68
68
  _chunkIGY2S5BCjs.__privateAdd.call(void 0, this, _snapSignMessage);
69
69
  _chunkIGY2S5BCjs.__privateAdd.call(void 0, this, _metametrics, void 0);
70
+ _chunkIGY2S5BCjs.__privateAdd.call(void 0, this, _isUnlocked, false);
71
+ _chunkIGY2S5BCjs.__privateAdd.call(void 0, this, _keyringController, {
72
+ setupLockedStateSubscriptions: () => {
73
+ const { isUnlocked } = this.messagingSystem.call(
74
+ "KeyringController:getState"
75
+ );
76
+ _chunkIGY2S5BCjs.__privateSet.call(void 0, this, _isUnlocked, isUnlocked);
77
+ this.messagingSystem.subscribe("KeyringController:unlock", () => {
78
+ _chunkIGY2S5BCjs.__privateSet.call(void 0, this, _isUnlocked, true);
79
+ });
80
+ this.messagingSystem.subscribe("KeyringController:lock", () => {
81
+ _chunkIGY2S5BCjs.__privateSet.call(void 0, this, _isUnlocked, false);
82
+ });
83
+ }
84
+ });
70
85
  _chunkIGY2S5BCjs.__privateAdd.call(void 0, this, __snapPublicKeyCache, void 0);
71
86
  _chunkIGY2S5BCjs.__privateAdd.call(void 0, this, __snapSignMessageCache, {});
72
87
  if (!metametrics) {
73
88
  throw new Error("`metametrics` field is required");
74
89
  }
75
90
  _chunkIGY2S5BCjs.__privateSet.call(void 0, this, _metametrics, metametrics);
91
+ _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _keyringController).setupLockedStateSubscriptions();
76
92
  _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _registerMessageHandlers, registerMessageHandlers_fn).call(this);
77
93
  }
78
94
  async performSignIn() {
@@ -113,6 +129,8 @@ var AuthenticationController = class extends _basecontroller.BaseController {
113
129
  }
114
130
  };
115
131
  _metametrics = new WeakMap();
132
+ _isUnlocked = new WeakMap();
133
+ _keyringController = new WeakMap();
116
134
  _registerMessageHandlers = new WeakSet();
117
135
  registerMessageHandlers_fn = function() {
118
136
  this.messagingSystem.registerActionHandler(
@@ -213,6 +231,11 @@ snapGetPublicKey_fn = async function() {
213
231
  if (_chunkIGY2S5BCjs.__privateGet.call(void 0, this, __snapPublicKeyCache)) {
214
232
  return _chunkIGY2S5BCjs.__privateGet.call(void 0, this, __snapPublicKeyCache);
215
233
  }
234
+ if (!_chunkIGY2S5BCjs.__privateGet.call(void 0, this, _isUnlocked)) {
235
+ throw new Error(
236
+ "#snapGetPublicKey - unable to call snap, wallet is locked"
237
+ );
238
+ }
216
239
  const result = await this.messagingSystem.call(
217
240
  "SnapController:handleRequest",
218
241
  _chunkYHGWG3EQjs.createSnapPublicKeyRequest.call(void 0, )
@@ -226,6 +249,11 @@ snapSignMessage_fn = async function(message) {
226
249
  if (_chunkIGY2S5BCjs.__privateGet.call(void 0, this, __snapSignMessageCache)[message]) {
227
250
  return _chunkIGY2S5BCjs.__privateGet.call(void 0, this, __snapSignMessageCache)[message];
228
251
  }
252
+ if (!_chunkIGY2S5BCjs.__privateGet.call(void 0, this, _isUnlocked)) {
253
+ throw new Error(
254
+ "#snapSignMessage - unable to call snap, wallet is locked"
255
+ );
256
+ }
229
257
  const result = await this.messagingSystem.call(
230
258
  "SnapController:handleRequest",
231
259
  _chunkYHGWG3EQjs.createSnapSignMessageRequest.call(void 0, message)
@@ -238,4 +266,4 @@ snapSignMessage_fn = async function(message) {
238
266
 
239
267
 
240
268
  exports.defaultState = defaultState; exports.AuthenticationController = AuthenticationController;
241
- //# sourceMappingURL=chunk-DHKZ2NEF.js.map
269
+ //# sourceMappingURL=chunk-KW3X4TT5.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/controllers/authentication/AuthenticationController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;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;AAAA,IAC7D;AAAA,EACF;AACF;AAEA;AAAA,qBAAgB,SACd,aAC4B;AAC5B,MAAI,CAAC,aAAa;AAChB,WAAO;AAAA,EACT;AAEA,QAAM,WAAW,KAAK,MAAM,YAAY,SAAS;AACjD,MAAI,MAAM,QAAQ,GAAG;AACnB,WAAO;AAAA,EACT;AAEA,QAAM,cAAc,oBAAI,KAAK;AAC7B,QAAM,SAAS,KAAK,IAAI,YAAY,QAAQ,IAAI,QAAQ;AAExD,SAAO,gBAAgB;AACzB;AAEA;AAOM;AAAA,sBAAiB,iBAAoB;AACzC,MAAI,mBAAK,uBAAsB;AAC7B,WAAO,mBAAK;AAAA,EACd;AAEA,MAAI,CAAC,mBAAK,cAAa;AACrB,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM,SAAU,MAAM,KAAK,gBAAgB;AAAA,IACzC;AAAA,IACA,2BAA2B;AAAA,EAC7B;AAEA,qBAAK,sBAAuB;AAE5B,SAAO;AACT;AAEA;AAQM;AAAA,qBAAgB,eAAC,SAAgD;AACrE,MAAI,mBAAK,wBAAuB,OAAO,GAAG;AACxC,WAAO,mBAAK,wBAAuB,OAAO;AAAA,EAC5C;AAEA,MAAI,CAAC,mBAAK,cAAa;AACrB,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM,SAAU,MAAM,KAAK,gBAAgB;AAAA,IACzC;AAAA,IACA,6BAA6B,OAAO;AAAA,EACtC;AAEA,qBAAK,wBAAuB,OAAO,IAAI;AAEvC,SAAO;AACT","sourcesContent":["import type {\n RestrictedControllerMessenger,\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';\n\nimport {\n createSnapPublicKeyRequest,\n createSnapSignMessageRequest,\n} from './auth-snap-requests';\nimport {\n createLoginRawMessage,\n getAccessToken,\n getNonce,\n login,\n} from './services';\n\nconst THIRTY_MIN_MS = 1000 * 60 * 30;\n\nconst controllerName = 'AuthenticationController';\n\n// State\ntype SessionProfile = {\n identifierId: string;\n profileId: string;\n};\n\ntype SessionData = {\n /** profile - anonymous profile data for the given logged in user */\n profile: SessionProfile;\n /** accessToken - used to make requests authorized endpoints */\n accessToken: string;\n /** expiresIn - string date to determine if new access token is required */\n expiresIn: string;\n};\n\ntype MetaMetricsAuth = {\n getMetaMetricsId: () => string | Promise<string>;\n agent: 'extension' | 'mobile';\n};\n\nexport type AuthenticationControllerState = {\n /**\n * Global isSignedIn state.\n * Can be used to determine if \"Profile Syncing\" is enabled.\n */\n isSignedIn: boolean;\n sessionData?: SessionData;\n};\nexport const defaultState: AuthenticationControllerState = {\n isSignedIn: false,\n};\nconst metadata: StateMetadata<AuthenticationControllerState> = {\n isSignedIn: {\n persist: true,\n anonymous: true,\n },\n sessionData: {\n persist: true,\n anonymous: false,\n },\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 | 'isSignedIn'\n>;\nexport type Actions = ActionsObj[keyof ActionsObj];\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 AuthenticationControllerIsSignedIn = ActionsObj['isSignedIn'];\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 = RestrictedControllerMessenger<\n typeof controllerName,\n Actions | AllowedActions,\n AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Controller that enables authentication for restricted endpoints.\n * Used for Global Profile Syncing and Notifications\n */\nexport default class AuthenticationController extends BaseController<\n typeof controllerName,\n AuthenticationControllerState,\n AuthenticationControllerMessenger\n> {\n #metametrics: MetaMetricsAuth;\n\n #isUnlocked = false;\n\n #keyringController = {\n setupLockedStateSubscriptions: () => {\n const { isUnlocked } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n this.#isUnlocked = isUnlocked;\n\n this.messagingSystem.subscribe('KeyringController:unlock', () => {\n this.#isUnlocked = true;\n });\n\n this.messagingSystem.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n },\n };\n\n constructor({\n messenger,\n state,\n metametrics,\n }: {\n messenger: AuthenticationControllerMessenger;\n state?: AuthenticationControllerState;\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.#metametrics = metametrics;\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\n public async performSignIn(): Promise<string> {\n const { accessToken } = await this.#performAuthenticationFlow();\n return accessToken;\n }\n\n public performSignOut(): void {\n this.#assertLoggedIn();\n\n this.update((state) => {\n state.isSignedIn = false;\n state.sessionData = undefined;\n });\n }\n\n public async getBearerToken(): Promise<string> {\n this.#assertLoggedIn();\n\n if (this.#hasValidSession(this.state.sessionData)) {\n return this.state.sessionData.accessToken;\n }\n\n const { accessToken } = await this.#performAuthenticationFlow();\n return accessToken;\n }\n\n /**\n * Will return a session profile.\n * Throws if a user is not logged in.\n *\n * @returns profile for the session.\n */\n public async getSessionProfile(): Promise<SessionProfile> {\n this.#assertLoggedIn();\n\n if (this.#hasValidSession(this.state.sessionData)) {\n return this.state.sessionData.profile;\n }\n\n const { profile } = await this.#performAuthenticationFlow();\n return profile;\n }\n\n public isSignedIn(): boolean {\n return this.state.isSignedIn;\n }\n\n #assertLoggedIn(): void {\n if (!this.state.isSignedIn) {\n throw new Error(\n `${controllerName}: Unable to call method, user is not authenticated`,\n );\n }\n }\n\n async #performAuthenticationFlow(): Promise<{\n profile: SessionProfile;\n accessToken: string;\n }> {\n try {\n // 1. Nonce\n const publicKey = await this.#snapGetPublicKey();\n const nonce = await getNonce(publicKey);\n if (!nonce) {\n throw new Error(`Unable to get nonce`);\n }\n\n // 2. Login\n const rawMessage = createLoginRawMessage(nonce, publicKey);\n const signature = await this.#snapSignMessage(rawMessage);\n const loginResponse = await login(rawMessage, signature, {\n metametricsId: await this.#metametrics.getMetaMetricsId(),\n agent: this.#metametrics.agent,\n });\n if (!loginResponse?.token) {\n throw new Error(`Unable to login`);\n }\n\n const profile: SessionProfile = {\n identifierId: loginResponse.profile.identifier_id,\n profileId: loginResponse.profile.profile_id,\n };\n\n // 3. Trade for Access Token\n const accessToken = await getAccessToken(\n loginResponse.token,\n this.#metametrics.agent,\n );\n if (!accessToken) {\n throw new Error(`Unable to get Access Token`);\n }\n\n // Update Internal State\n this.update((state) => {\n state.isSignedIn = true;\n const expiresIn = new Date();\n expiresIn.setTime(expiresIn.getTime() + THIRTY_MIN_MS);\n state.sessionData = {\n profile,\n accessToken,\n expiresIn: expiresIn.toString(),\n };\n });\n\n return {\n profile,\n accessToken,\n };\n } catch (e) {\n console.error('Failed to authenticate', e);\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n throw new Error(\n `${controllerName}: Failed to authenticate - ${errorMessage}`,\n );\n }\n }\n\n #hasValidSession(\n sessionData: SessionData | undefined,\n ): sessionData is SessionData {\n if (!sessionData) {\n return false;\n }\n\n const prevDate = Date.parse(sessionData.expiresIn);\n if (isNaN(prevDate)) {\n return false;\n }\n\n const currentDate = new Date();\n const diffMs = Math.abs(currentDate.getTime() - prevDate);\n\n return THIRTY_MIN_MS > diffMs;\n }\n\n #_snapPublicKeyCache: string | undefined;\n\n /**\n * Returns the auth snap public key.\n *\n * @returns The snap public key.\n */\n async #snapGetPublicKey(): Promise<string> {\n if (this.#_snapPublicKeyCache) {\n return this.#_snapPublicKeyCache;\n }\n\n if (!this.#isUnlocked) {\n throw new Error(\n '#snapGetPublicKey - unable to call snap, wallet is locked',\n );\n }\n\n const result = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n createSnapPublicKeyRequest(),\n )) as string;\n\n this.#_snapPublicKeyCache = result;\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 * @returns A Signature created by the snap.\n */\n async #snapSignMessage(message: `metamask:${string}`): Promise<string> {\n if (this.#_snapSignMessageCache[message]) {\n return this.#_snapSignMessageCache[message];\n }\n\n if (!this.#isUnlocked) {\n throw new Error(\n '#snapSignMessage - unable to call snap, wallet is locked',\n );\n }\n\n const result = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n createSnapSignMessageRequest(message),\n )) as string;\n\n this.#_snapSignMessageCache[message] = result;\n\n return result;\n }\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
2
 
3
3
 
4
- var _chunkDHKZ2NEFjs = require('./chunk-DHKZ2NEF.js');
4
+ var _chunkKW3X4TT5js = require('./chunk-KW3X4TT5.js');
5
5
 
6
6
 
7
7
 
@@ -14,9 +14,9 @@ var _chunkIGY2S5BCjs = require('./chunk-IGY2S5BC.js');
14
14
  // src/controllers/authentication/index.ts
15
15
  var authentication_exports = {};
16
16
  _chunkIGY2S5BCjs.__export.call(void 0, authentication_exports, {
17
- Controller: () => _chunkDHKZ2NEFjs.AuthenticationController,
17
+ Controller: () => _chunkKW3X4TT5js.AuthenticationController,
18
18
  Mocks: () => fixtures_exports,
19
- defaultState: () => _chunkDHKZ2NEFjs.defaultState
19
+ defaultState: () => _chunkKW3X4TT5js.defaultState
20
20
  });
21
21
 
22
22
  // src/controllers/authentication/__fixtures__/index.ts
@@ -83,4 +83,4 @@ var getMockAuthAccessTokenResponse = () => {
83
83
 
84
84
 
85
85
  exports.fixtures_exports = fixtures_exports; exports.authentication_exports = authentication_exports;
86
- //# sourceMappingURL=chunk-BXPL7ZFX.js.map
86
+ //# sourceMappingURL=chunk-MNVUKRZC.js.map
@@ -11,7 +11,8 @@ import {
11
11
  import {
12
12
  __privateAdd,
13
13
  __privateGet,
14
- __privateMethod
14
+ __privateMethod,
15
+ __privateSet
15
16
  } from "./chunk-U5UIDVOO.mjs";
16
17
 
17
18
  // src/controllers/user-storage/UserStorageController.ts
@@ -31,7 +32,7 @@ var metadata = {
31
32
  anonymous: false
32
33
  }
33
34
  };
34
- var _auth, _notificationServices, _registerMessageHandlers, registerMessageHandlers_fn, _assertProfileSyncingEnabled, assertProfileSyncingEnabled_fn, _getStorageKeyAndBearerToken, getStorageKeyAndBearerToken_fn, _createStorageKey, createStorageKey_fn, __snapSignMessageCache, _snapSignMessage, snapSignMessage_fn, _setIsProfileSyncingUpdateLoading, setIsProfileSyncingUpdateLoading_fn;
35
+ var _auth, _notificationServices, _isUnlocked, _keyringController, _registerMessageHandlers, registerMessageHandlers_fn, _assertProfileSyncingEnabled, assertProfileSyncingEnabled_fn, _getStorageKeyAndBearerToken, getStorageKeyAndBearerToken_fn, _createStorageKey, createStorageKey_fn, __snapSignMessageCache, _snapSignMessage, snapSignMessage_fn, _setIsProfileSyncingUpdateLoading, setIsProfileSyncingUpdateLoading_fn;
35
36
  var UserStorageController = class extends BaseController {
36
37
  constructor(params) {
37
38
  super({
@@ -102,8 +103,24 @@ var UserStorageController = class extends BaseController {
102
103
  );
103
104
  }
104
105
  });
106
+ __privateAdd(this, _isUnlocked, false);
107
+ __privateAdd(this, _keyringController, {
108
+ setupLockedStateSubscriptions: () => {
109
+ const { isUnlocked } = this.messagingSystem.call(
110
+ "KeyringController:getState"
111
+ );
112
+ __privateSet(this, _isUnlocked, isUnlocked);
113
+ this.messagingSystem.subscribe("KeyringController:unlock", () => {
114
+ __privateSet(this, _isUnlocked, true);
115
+ });
116
+ this.messagingSystem.subscribe("KeyringController:lock", () => {
117
+ __privateSet(this, _isUnlocked, false);
118
+ });
119
+ }
120
+ });
105
121
  __privateAdd(this, __snapSignMessageCache, {});
106
122
  this.getMetaMetricsState = params.getMetaMetricsState;
123
+ __privateGet(this, _keyringController).setupLockedStateSubscriptions();
107
124
  __privateMethod(this, _registerMessageHandlers, registerMessageHandlers_fn).call(this);
108
125
  }
109
126
  async enableProfileSyncing() {
@@ -143,7 +160,7 @@ var UserStorageController = class extends BaseController {
143
160
  }
144
161
  const isMetaMetricsParticipation = this.getMetaMetricsState();
145
162
  if (!isMetaMetricsParticipation) {
146
- this.messagingSystem.call("AuthenticationController:performSignOut");
163
+ await __privateGet(this, _auth).signOut();
147
164
  }
148
165
  __privateMethod(this, _setIsProfileSyncingUpdateLoading, setIsProfileSyncingUpdateLoading_fn).call(this, false);
149
166
  this.update((state) => {
@@ -204,6 +221,8 @@ var UserStorageController = class extends BaseController {
204
221
  };
205
222
  _auth = new WeakMap();
206
223
  _notificationServices = new WeakMap();
224
+ _isUnlocked = new WeakMap();
225
+ _keyringController = new WeakMap();
207
226
  _registerMessageHandlers = new WeakSet();
208
227
  registerMessageHandlers_fn = function() {
209
228
  this.messagingSystem.registerActionHandler(
@@ -260,6 +279,11 @@ snapSignMessage_fn = async function(message) {
260
279
  if (__privateGet(this, __snapSignMessageCache)[message]) {
261
280
  return __privateGet(this, __snapSignMessageCache)[message];
262
281
  }
282
+ if (!__privateGet(this, _isUnlocked)) {
283
+ throw new Error(
284
+ "#snapSignMessage - unable to call snap, wallet is locked"
285
+ );
286
+ }
263
287
  const result = await this.messagingSystem.call(
264
288
  "SnapController:handleRequest",
265
289
  createSnapSignMessageRequest(message)
@@ -278,4 +302,4 @@ export {
278
302
  defaultState,
279
303
  UserStorageController
280
304
  };
281
- //# sourceMappingURL=chunk-LNSB4L7K.mjs.map
305
+ //# sourceMappingURL=chunk-QE5X2BT3.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/controllers/user-storage/UserStorageController.ts"],"sourcesContent":["import type {\n RestrictedControllerMessenger,\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';\n\nimport { createSnapSignMessageRequest } from '../authentication/auth-snap-requests';\nimport type {\n AuthenticationControllerGetBearerToken,\n AuthenticationControllerGetSessionProfile,\n AuthenticationControllerIsSignedIn,\n AuthenticationControllerPerformSignIn,\n AuthenticationControllerPerformSignOut,\n} from '../authentication/AuthenticationController';\nimport { createSHA256Hash } from './encryption';\nimport type { UserStoragePath } from './schema';\nimport { getUserStorage, upsertUserStorage } from './services';\n\n// TODO: fix external dependencies\nexport declare type NotificationServicesControllerDisableNotificationServices =\n {\n type: `NotificationServicesController:disableNotificationServices`;\n handler: () => Promise<void>;\n };\n\nexport declare type NotificationServicesControllerSelectIsNotificationServicesEnabled =\n {\n type: `NotificationServicesController:selectIsNotificationServicesEnabled`;\n handler: () => boolean;\n };\n\nconst controllerName = 'UserStorageController';\n\n// State\nexport type UserStorageControllerState = {\n /**\n * Condition used by UI and to determine if we can use some of the User Storage methods.\n */\n isProfileSyncingEnabled: boolean | null;\n /**\n * Loading state for the profile syncing update\n */\n isProfileSyncingUpdateLoading: boolean;\n};\n\nexport const defaultState: UserStorageControllerState = {\n isProfileSyncingEnabled: true,\n isProfileSyncingUpdateLoading: false,\n};\n\nconst metadata: StateMetadata<UserStorageControllerState> = {\n isProfileSyncingEnabled: {\n persist: true,\n anonymous: true,\n },\n isProfileSyncingUpdateLoading: {\n persist: false,\n anonymous: false,\n },\n};\n\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 | 'performSetStorage'\n | 'getStorageKey'\n | 'enableProfileSyncing'\n | 'disableProfileSyncing'\n>;\nexport type Actions = ActionsObj[keyof ActionsObj];\nexport type UserStorageControllerPerformGetStorage =\n ActionsObj['performGetStorage'];\nexport type UserStorageControllerPerformSetStorage =\n ActionsObj['performSetStorage'];\nexport type UserStorageControllerGetStorageKey = ActionsObj['getStorageKey'];\nexport type UserStorageControllerEnableProfileSyncing =\n ActionsObj['enableProfileSyncing'];\nexport type UserStorageControllerDisableProfileSyncing =\n ActionsObj['disableProfileSyncing'];\n\n// Allowed Actions\nexport type AllowedActions =\n // Keyring Requests\n | KeyringControllerGetStateAction\n // Snap Requests\n | HandleSnapRequest\n // Auth Requests\n | AuthenticationControllerGetBearerToken\n | AuthenticationControllerGetSessionProfile\n | AuthenticationControllerPerformSignIn\n | AuthenticationControllerIsSignedIn\n | AuthenticationControllerPerformSignOut\n // Metamask Notifications\n | NotificationServicesControllerDisableNotificationServices\n | NotificationServicesControllerSelectIsNotificationServicesEnabled;\n\nexport type AllowedEvents =\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent;\n\n// Messenger\nexport type UserStorageControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n Actions | AllowedActions,\n AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Reusable controller that allows any team to store synchronized data for a given user.\n * These can be settings shared cross MetaMask clients, or data we want to persist when uninstalling/reinstalling.\n *\n * NOTE:\n * - data stored on UserStorage is FULLY encrypted, with the only keys stored/managed on the client.\n * - No one can access this data unless they are have the SRP and are able to run the signing snap.\n */\nexport default class UserStorageController extends BaseController<\n typeof controllerName,\n UserStorageControllerState,\n UserStorageControllerMessenger\n> {\n #auth = {\n getBearerToken: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:getBearerToken',\n );\n },\n getProfileId: async () => {\n const sessionProfile = await this.messagingSystem.call(\n 'AuthenticationController:getSessionProfile',\n );\n return sessionProfile?.profileId;\n },\n isAuthEnabled: () => {\n return this.messagingSystem.call('AuthenticationController:isSignedIn');\n },\n signIn: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:performSignIn',\n );\n },\n signOut: async () => {\n return this.messagingSystem.call(\n 'AuthenticationController:performSignOut',\n );\n },\n };\n\n #notificationServices = {\n disableNotificationServices: async () => {\n return await this.messagingSystem.call(\n 'NotificationServicesController:disableNotificationServices',\n );\n },\n selectIsNotificationServicesEnabled: async () => {\n return this.messagingSystem.call(\n 'NotificationServicesController:selectIsNotificationServicesEnabled',\n );\n },\n };\n\n #isUnlocked = false;\n\n #keyringController = {\n setupLockedStateSubscriptions: () => {\n const { isUnlocked } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n this.#isUnlocked = isUnlocked;\n\n this.messagingSystem.subscribe('KeyringController:unlock', () => {\n this.#isUnlocked = true;\n });\n\n this.messagingSystem.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n },\n };\n\n getMetaMetricsState: () => boolean;\n\n constructor(params: {\n messenger: UserStorageControllerMessenger;\n state?: UserStorageControllerState;\n getMetaMetricsState: () => boolean;\n }) {\n super({\n messenger: params.messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...params.state },\n });\n\n this.getMetaMetricsState = params.getMetaMetricsState;\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 'UserStorageController:performGetStorage',\n this.performGetStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performSetStorage',\n this.performSetStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:getStorageKey',\n this.getStorageKey.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:enableProfileSyncing',\n this.enableProfileSyncing.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:disableProfileSyncing',\n this.disableProfileSyncing.bind(this),\n );\n }\n\n public async enableProfileSyncing(): Promise<void> {\n try {\n this.#setIsProfileSyncingUpdateLoading(true);\n\n const authEnabled = this.#auth.isAuthEnabled();\n if (!authEnabled) {\n await this.#auth.signIn();\n }\n\n this.update((state) => {\n state.isProfileSyncingEnabled = true;\n });\n\n this.#setIsProfileSyncingUpdateLoading(false);\n } catch (e) {\n this.#setIsProfileSyncingUpdateLoading(false);\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to enable profile syncing - ${errorMessage}`,\n );\n }\n }\n\n public async setIsProfileSyncingEnabled(\n isProfileSyncingEnabled: boolean,\n ): Promise<void> {\n this.update((state) => {\n state.isProfileSyncingEnabled = isProfileSyncingEnabled;\n });\n }\n\n public async disableProfileSyncing(): Promise<void> {\n const isAlreadyDisabled = !this.state.isProfileSyncingEnabled;\n if (isAlreadyDisabled) {\n return;\n }\n\n try {\n this.#setIsProfileSyncingUpdateLoading(true);\n\n const isNotificationServicesEnabled =\n await this.#notificationServices.selectIsNotificationServicesEnabled();\n\n if (isNotificationServicesEnabled) {\n await this.#notificationServices.disableNotificationServices();\n }\n\n const isMetaMetricsParticipation = this.getMetaMetricsState();\n\n if (!isMetaMetricsParticipation) {\n await this.#auth.signOut();\n }\n\n this.#setIsProfileSyncingUpdateLoading(false);\n\n this.update((state) => {\n state.isProfileSyncingEnabled = false;\n });\n } catch (e) {\n this.#setIsProfileSyncingUpdateLoading(false);\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to disable profile syncing - ${errorMessage}`,\n );\n }\n }\n\n /**\n * Allows retrieval of stored data. Data stored is string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @returns the decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorage(\n path: UserStoragePath,\n ): Promise<string | null> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n const result = await getUserStorage({\n path,\n bearerToken,\n storageKey,\n });\n\n return result;\n }\n\n /**\n * Allows storage of user data. Data stored must be string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param value - The string data you want to store.\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performSetStorage(\n path: UserStoragePath,\n value: string,\n ): Promise<void> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n await upsertUserStorage(value, {\n path,\n bearerToken,\n storageKey,\n });\n }\n\n /**\n * Retrieves the storage key, for internal use only!\n *\n * @returns the storage key\n */\n public async getStorageKey(): Promise<string> {\n this.#assertProfileSyncingEnabled();\n const storageKey = await this.#createStorageKey();\n return storageKey;\n }\n\n #assertProfileSyncingEnabled(): void {\n if (!this.state.isProfileSyncingEnabled) {\n throw new Error(\n `${controllerName}: Unable to call method, user is not authenticated`,\n );\n }\n }\n\n /**\n * Utility to get the bearer token and storage key\n */\n async #getStorageKeyAndBearerToken(): Promise<{\n bearerToken: string;\n storageKey: string;\n }> {\n const bearerToken = await this.#auth.getBearerToken();\n if (!bearerToken) {\n throw new Error('UserStorageController - unable to get bearer token');\n }\n const storageKey = await this.#createStorageKey();\n\n return { bearerToken, storageKey };\n }\n\n /**\n * Rather than storing the storage key, we can compute the storage key when needed.\n *\n * @returns the storage key\n */\n async #createStorageKey(): Promise<string> {\n const id: string = await this.#auth.getProfileId();\n if (!id) {\n throw new Error('UserStorageController - unable to create storage key');\n }\n\n const storageKeySignature = await this.#snapSignMessage(`metamask:${id}`);\n const storageKey = createSHA256Hash(storageKeySignature);\n return storageKey;\n }\n\n #_snapSignMessageCache: Record<`metamask:${string}`, string> = {};\n\n /**\n * Signs a specific message using an underlying auth snap.\n *\n * @param message - A specific tagged message to sign.\n * @returns A Signature created by the snap.\n */\n async #snapSignMessage(message: `metamask:${string}`): Promise<string> {\n if (this.#_snapSignMessageCache[message]) {\n return this.#_snapSignMessageCache[message];\n }\n\n if (!this.#isUnlocked) {\n throw new Error(\n '#snapSignMessage - unable to call snap, wallet is locked',\n );\n }\n\n const result = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n createSnapSignMessageRequest(message),\n )) as string;\n\n this.#_snapSignMessageCache[message] = result;\n\n return result;\n }\n\n #setIsProfileSyncingUpdateLoading(\n isProfileSyncingUpdateLoading: boolean,\n ): void {\n this.update((state) => {\n state.isProfileSyncingUpdateLoading = isProfileSyncingUpdateLoading;\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAIA,SAAS,sBAAsB;AAiC/B,IAAM,iBAAiB;AAchB,IAAM,eAA2C;AAAA,EACtD,yBAAyB;AAAA,EACzB,+BAA+B;AACjC;AAEA,IAAM,WAAsD;AAAA,EAC1D,yBAAyB;AAAA,IACvB,SAAS;AAAA,IACT,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;AACN,OAAK,OAAO,CAAC,UAAU;AACrB,UAAM,gCAAgC;AAAA,EACxC,CAAC;AACH;","names":[]}
@@ -32,7 +32,7 @@ var metadata = {
32
32
  anonymous: false
33
33
  }
34
34
  };
35
- var _metametrics, _registerMessageHandlers, registerMessageHandlers_fn, _assertLoggedIn, assertLoggedIn_fn, _performAuthenticationFlow, performAuthenticationFlow_fn, _hasValidSession, hasValidSession_fn, __snapPublicKeyCache, _snapGetPublicKey, snapGetPublicKey_fn, __snapSignMessageCache, _snapSignMessage, snapSignMessage_fn;
35
+ var _metametrics, _isUnlocked, _keyringController, _registerMessageHandlers, registerMessageHandlers_fn, _assertLoggedIn, assertLoggedIn_fn, _performAuthenticationFlow, performAuthenticationFlow_fn, _hasValidSession, hasValidSession_fn, __snapPublicKeyCache, _snapGetPublicKey, snapGetPublicKey_fn, __snapSignMessageCache, _snapSignMessage, snapSignMessage_fn;
36
36
  var AuthenticationController = class extends BaseController {
37
37
  constructor({
38
38
  messenger,
@@ -67,12 +67,28 @@ var AuthenticationController = class extends BaseController {
67
67
  */
68
68
  __privateAdd(this, _snapSignMessage);
69
69
  __privateAdd(this, _metametrics, void 0);
70
+ __privateAdd(this, _isUnlocked, false);
71
+ __privateAdd(this, _keyringController, {
72
+ setupLockedStateSubscriptions: () => {
73
+ const { isUnlocked } = this.messagingSystem.call(
74
+ "KeyringController:getState"
75
+ );
76
+ __privateSet(this, _isUnlocked, isUnlocked);
77
+ this.messagingSystem.subscribe("KeyringController:unlock", () => {
78
+ __privateSet(this, _isUnlocked, true);
79
+ });
80
+ this.messagingSystem.subscribe("KeyringController:lock", () => {
81
+ __privateSet(this, _isUnlocked, false);
82
+ });
83
+ }
84
+ });
70
85
  __privateAdd(this, __snapPublicKeyCache, void 0);
71
86
  __privateAdd(this, __snapSignMessageCache, {});
72
87
  if (!metametrics) {
73
88
  throw new Error("`metametrics` field is required");
74
89
  }
75
90
  __privateSet(this, _metametrics, metametrics);
91
+ __privateGet(this, _keyringController).setupLockedStateSubscriptions();
76
92
  __privateMethod(this, _registerMessageHandlers, registerMessageHandlers_fn).call(this);
77
93
  }
78
94
  async performSignIn() {
@@ -113,6 +129,8 @@ var AuthenticationController = class extends BaseController {
113
129
  }
114
130
  };
115
131
  _metametrics = new WeakMap();
132
+ _isUnlocked = new WeakMap();
133
+ _keyringController = new WeakMap();
116
134
  _registerMessageHandlers = new WeakSet();
117
135
  registerMessageHandlers_fn = function() {
118
136
  this.messagingSystem.registerActionHandler(
@@ -213,6 +231,11 @@ snapGetPublicKey_fn = async function() {
213
231
  if (__privateGet(this, __snapPublicKeyCache)) {
214
232
  return __privateGet(this, __snapPublicKeyCache);
215
233
  }
234
+ if (!__privateGet(this, _isUnlocked)) {
235
+ throw new Error(
236
+ "#snapGetPublicKey - unable to call snap, wallet is locked"
237
+ );
238
+ }
216
239
  const result = await this.messagingSystem.call(
217
240
  "SnapController:handleRequest",
218
241
  createSnapPublicKeyRequest()
@@ -226,6 +249,11 @@ snapSignMessage_fn = async function(message) {
226
249
  if (__privateGet(this, __snapSignMessageCache)[message]) {
227
250
  return __privateGet(this, __snapSignMessageCache)[message];
228
251
  }
252
+ if (!__privateGet(this, _isUnlocked)) {
253
+ throw new Error(
254
+ "#snapSignMessage - unable to call snap, wallet is locked"
255
+ );
256
+ }
229
257
  const result = await this.messagingSystem.call(
230
258
  "SnapController:handleRequest",
231
259
  createSnapSignMessageRequest(message)
@@ -238,4 +266,4 @@ export {
238
266
  defaultState,
239
267
  AuthenticationController
240
268
  };
241
- //# sourceMappingURL=chunk-Y7P3UH26.mjs.map
269
+ //# sourceMappingURL=chunk-WWQ65CZY.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/controllers/authentication/AuthenticationController.ts"],"sourcesContent":["import type {\n RestrictedControllerMessenger,\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';\n\nimport {\n createSnapPublicKeyRequest,\n createSnapSignMessageRequest,\n} from './auth-snap-requests';\nimport {\n createLoginRawMessage,\n getAccessToken,\n getNonce,\n login,\n} from './services';\n\nconst THIRTY_MIN_MS = 1000 * 60 * 30;\n\nconst controllerName = 'AuthenticationController';\n\n// State\ntype SessionProfile = {\n identifierId: string;\n profileId: string;\n};\n\ntype SessionData = {\n /** profile - anonymous profile data for the given logged in user */\n profile: SessionProfile;\n /** accessToken - used to make requests authorized endpoints */\n accessToken: string;\n /** expiresIn - string date to determine if new access token is required */\n expiresIn: string;\n};\n\ntype MetaMetricsAuth = {\n getMetaMetricsId: () => string | Promise<string>;\n agent: 'extension' | 'mobile';\n};\n\nexport type AuthenticationControllerState = {\n /**\n * Global isSignedIn state.\n * Can be used to determine if \"Profile Syncing\" is enabled.\n */\n isSignedIn: boolean;\n sessionData?: SessionData;\n};\nexport const defaultState: AuthenticationControllerState = {\n isSignedIn: false,\n};\nconst metadata: StateMetadata<AuthenticationControllerState> = {\n isSignedIn: {\n persist: true,\n anonymous: true,\n },\n sessionData: {\n persist: true,\n anonymous: false,\n },\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 | 'isSignedIn'\n>;\nexport type Actions = ActionsObj[keyof ActionsObj];\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 AuthenticationControllerIsSignedIn = ActionsObj['isSignedIn'];\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 = RestrictedControllerMessenger<\n typeof controllerName,\n Actions | AllowedActions,\n AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Controller that enables authentication for restricted endpoints.\n * Used for Global Profile Syncing and Notifications\n */\nexport default class AuthenticationController extends BaseController<\n typeof controllerName,\n AuthenticationControllerState,\n AuthenticationControllerMessenger\n> {\n #metametrics: MetaMetricsAuth;\n\n #isUnlocked = false;\n\n #keyringController = {\n setupLockedStateSubscriptions: () => {\n const { isUnlocked } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n this.#isUnlocked = isUnlocked;\n\n this.messagingSystem.subscribe('KeyringController:unlock', () => {\n this.#isUnlocked = true;\n });\n\n this.messagingSystem.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n },\n };\n\n constructor({\n messenger,\n state,\n metametrics,\n }: {\n messenger: AuthenticationControllerMessenger;\n state?: AuthenticationControllerState;\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.#metametrics = metametrics;\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\n public async performSignIn(): Promise<string> {\n const { accessToken } = await this.#performAuthenticationFlow();\n return accessToken;\n }\n\n public performSignOut(): void {\n this.#assertLoggedIn();\n\n this.update((state) => {\n state.isSignedIn = false;\n state.sessionData = undefined;\n });\n }\n\n public async getBearerToken(): Promise<string> {\n this.#assertLoggedIn();\n\n if (this.#hasValidSession(this.state.sessionData)) {\n return this.state.sessionData.accessToken;\n }\n\n const { accessToken } = await this.#performAuthenticationFlow();\n return accessToken;\n }\n\n /**\n * Will return a session profile.\n * Throws if a user is not logged in.\n *\n * @returns profile for the session.\n */\n public async getSessionProfile(): Promise<SessionProfile> {\n this.#assertLoggedIn();\n\n if (this.#hasValidSession(this.state.sessionData)) {\n return this.state.sessionData.profile;\n }\n\n const { profile } = await this.#performAuthenticationFlow();\n return profile;\n }\n\n public isSignedIn(): boolean {\n return this.state.isSignedIn;\n }\n\n #assertLoggedIn(): void {\n if (!this.state.isSignedIn) {\n throw new Error(\n `${controllerName}: Unable to call method, user is not authenticated`,\n );\n }\n }\n\n async #performAuthenticationFlow(): Promise<{\n profile: SessionProfile;\n accessToken: string;\n }> {\n try {\n // 1. Nonce\n const publicKey = await this.#snapGetPublicKey();\n const nonce = await getNonce(publicKey);\n if (!nonce) {\n throw new Error(`Unable to get nonce`);\n }\n\n // 2. Login\n const rawMessage = createLoginRawMessage(nonce, publicKey);\n const signature = await this.#snapSignMessage(rawMessage);\n const loginResponse = await login(rawMessage, signature, {\n metametricsId: await this.#metametrics.getMetaMetricsId(),\n agent: this.#metametrics.agent,\n });\n if (!loginResponse?.token) {\n throw new Error(`Unable to login`);\n }\n\n const profile: SessionProfile = {\n identifierId: loginResponse.profile.identifier_id,\n profileId: loginResponse.profile.profile_id,\n };\n\n // 3. Trade for Access Token\n const accessToken = await getAccessToken(\n loginResponse.token,\n this.#metametrics.agent,\n );\n if (!accessToken) {\n throw new Error(`Unable to get Access Token`);\n }\n\n // Update Internal State\n this.update((state) => {\n state.isSignedIn = true;\n const expiresIn = new Date();\n expiresIn.setTime(expiresIn.getTime() + THIRTY_MIN_MS);\n state.sessionData = {\n profile,\n accessToken,\n expiresIn: expiresIn.toString(),\n };\n });\n\n return {\n profile,\n accessToken,\n };\n } catch (e) {\n console.error('Failed to authenticate', e);\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n throw new Error(\n `${controllerName}: Failed to authenticate - ${errorMessage}`,\n );\n }\n }\n\n #hasValidSession(\n sessionData: SessionData | undefined,\n ): sessionData is SessionData {\n if (!sessionData) {\n return false;\n }\n\n const prevDate = Date.parse(sessionData.expiresIn);\n if (isNaN(prevDate)) {\n return false;\n }\n\n const currentDate = new Date();\n const diffMs = Math.abs(currentDate.getTime() - prevDate);\n\n return THIRTY_MIN_MS > diffMs;\n }\n\n #_snapPublicKeyCache: string | undefined;\n\n /**\n * Returns the auth snap public key.\n *\n * @returns The snap public key.\n */\n async #snapGetPublicKey(): Promise<string> {\n if (this.#_snapPublicKeyCache) {\n return this.#_snapPublicKeyCache;\n }\n\n if (!this.#isUnlocked) {\n throw new Error(\n '#snapGetPublicKey - unable to call snap, wallet is locked',\n );\n }\n\n const result = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n createSnapPublicKeyRequest(),\n )) as string;\n\n this.#_snapPublicKeyCache = result;\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 * @returns A Signature created by the snap.\n */\n async #snapSignMessage(message: `metamask:${string}`): Promise<string> {\n if (this.#_snapSignMessageCache[message]) {\n return this.#_snapSignMessageCache[message];\n }\n\n if (!this.#isUnlocked) {\n throw new Error(\n '#snapSignMessage - unable to call snap, wallet is locked',\n );\n }\n\n const result = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n createSnapSignMessageRequest(message),\n )) as string;\n\n this.#_snapSignMessageCache[message] = result;\n\n return result;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAIA,SAAS,sBAAsB;AAmB/B,IAAM,gBAAgB,MAAO,KAAK;AAElC,IAAM,iBAAiB;AA8BhB,IAAM,eAA8C;AAAA,EACzD,YAAY;AACd;AACA,IAAM,WAAyD;AAAA,EAC7D,YAAY;AAAA,IACV,SAAS;AAAA,IACT,WAAW;AAAA,EACb;AAAA,EACA,aAAa;AAAA,IACX,SAAS;AAAA,IACT,WAAW;AAAA,EACb;AACF;AAnEA;AAmHA,IAAqB,2BAArB,cAAsD,eAIpD;AAAA,EAsBA,YAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,EACF,GAQG;AACD,UAAM;AAAA,MACJ;AAAA,MACA;AAAA,MACA,MAAM;AAAA,MACN,OAAO,EAAE,GAAG,cAAc,GAAG,MAAM;AAAA,IACrC,CAAC;AAgBH;AAAA;AAAA;AAAA;AAAA;AAyEA;AAQA,uBAAM;AA+DN;AAyBA;AAAA;AAAA;AAAA;AAAA;AAAA,uBAAM;AA6BN;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,uBAAM;AA7PN;AAEA,oCAAc;AAEd,2CAAqB;AAAA,MACnB,+BAA+B,MAAM;AACnC,cAAM,EAAE,WAAW,IAAI,KAAK,gBAAgB;AAAA,UAC1C;AAAA,QACF;AACA,2BAAK,aAAc;AAEnB,aAAK,gBAAgB,UAAU,4BAA4B,MAAM;AAC/D,6BAAK,aAAc;AAAA,QACrB,CAAC;AAED,aAAK,gBAAgB,UAAU,0BAA0B,MAAM;AAC7D,6BAAK,aAAc;AAAA,QACrB,CAAC;AAAA,MACH;AAAA,IACF;AAsMA;AA4BA,+CAA+D,CAAC;AA5M9D,QAAI,CAAC,aAAa;AAChB,YAAM,IAAI,MAAM,iCAAiC;AAAA,IACnD;AAEA,uB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