@metamask/profile-sync-controller 16.0.0 → 17.0.0

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 (118) hide show
  1. package/CHANGELOG.md +15 -1
  2. package/dist/controllers/authentication/AuthenticationController.cjs +60 -24
  3. package/dist/controllers/authentication/AuthenticationController.cjs.map +1 -1
  4. package/dist/controllers/authentication/AuthenticationController.d.cts +6 -4
  5. package/dist/controllers/authentication/AuthenticationController.d.cts.map +1 -1
  6. package/dist/controllers/authentication/AuthenticationController.d.mts +6 -4
  7. package/dist/controllers/authentication/AuthenticationController.d.mts.map +1 -1
  8. package/dist/controllers/authentication/AuthenticationController.mjs +61 -25
  9. package/dist/controllers/authentication/AuthenticationController.mjs.map +1 -1
  10. package/dist/controllers/authentication/auth-snap-requests.cjs +25 -4
  11. package/dist/controllers/authentication/auth-snap-requests.cjs.map +1 -1
  12. package/dist/controllers/authentication/auth-snap-requests.d.cts +12 -2
  13. package/dist/controllers/authentication/auth-snap-requests.d.cts.map +1 -1
  14. package/dist/controllers/authentication/auth-snap-requests.d.mts +12 -2
  15. package/dist/controllers/authentication/auth-snap-requests.d.mts.map +1 -1
  16. package/dist/controllers/authentication/auth-snap-requests.mjs +23 -3
  17. package/dist/controllers/authentication/auth-snap-requests.mjs.map +1 -1
  18. package/dist/controllers/authentication/mocks/mockResponses.cjs +36 -3
  19. package/dist/controllers/authentication/mocks/mockResponses.cjs.map +1 -1
  20. package/dist/controllers/authentication/mocks/mockResponses.d.cts +7 -5
  21. package/dist/controllers/authentication/mocks/mockResponses.d.cts.map +1 -1
  22. package/dist/controllers/authentication/mocks/mockResponses.d.mts +7 -5
  23. package/dist/controllers/authentication/mocks/mockResponses.d.mts.map +1 -1
  24. package/dist/controllers/authentication/mocks/mockResponses.mjs +36 -3
  25. package/dist/controllers/authentication/mocks/mockResponses.mjs.map +1 -1
  26. package/dist/controllers/user-storage/UserStorageController.cjs +77 -27
  27. package/dist/controllers/user-storage/UserStorageController.cjs.map +1 -1
  28. package/dist/controllers/user-storage/UserStorageController.d.cts +24 -10
  29. package/dist/controllers/user-storage/UserStorageController.d.cts.map +1 -1
  30. package/dist/controllers/user-storage/UserStorageController.d.mts +24 -10
  31. package/dist/controllers/user-storage/UserStorageController.d.mts.map +1 -1
  32. package/dist/controllers/user-storage/UserStorageController.mjs +77 -27
  33. package/dist/controllers/user-storage/UserStorageController.mjs.map +1 -1
  34. package/dist/controllers/user-storage/account-syncing/controller-integration.cjs +22 -26
  35. package/dist/controllers/user-storage/account-syncing/controller-integration.cjs.map +1 -1
  36. package/dist/controllers/user-storage/account-syncing/controller-integration.d.cts +5 -2
  37. package/dist/controllers/user-storage/account-syncing/controller-integration.d.cts.map +1 -1
  38. package/dist/controllers/user-storage/account-syncing/controller-integration.d.mts +5 -2
  39. package/dist/controllers/user-storage/account-syncing/controller-integration.d.mts.map +1 -1
  40. package/dist/controllers/user-storage/account-syncing/controller-integration.mjs +23 -27
  41. package/dist/controllers/user-storage/account-syncing/controller-integration.mjs.map +1 -1
  42. package/dist/controllers/user-storage/account-syncing/setup-subscriptions.cjs +3 -13
  43. package/dist/controllers/user-storage/account-syncing/setup-subscriptions.cjs.map +1 -1
  44. package/dist/controllers/user-storage/account-syncing/setup-subscriptions.d.cts.map +1 -1
  45. package/dist/controllers/user-storage/account-syncing/setup-subscriptions.d.mts.map +1 -1
  46. package/dist/controllers/user-storage/account-syncing/setup-subscriptions.mjs +3 -13
  47. package/dist/controllers/user-storage/account-syncing/setup-subscriptions.mjs.map +1 -1
  48. package/dist/controllers/user-storage/account-syncing/sync-utils.cjs +16 -7
  49. package/dist/controllers/user-storage/account-syncing/sync-utils.cjs.map +1 -1
  50. package/dist/controllers/user-storage/account-syncing/sync-utils.d.cts +6 -2
  51. package/dist/controllers/user-storage/account-syncing/sync-utils.d.cts.map +1 -1
  52. package/dist/controllers/user-storage/account-syncing/sync-utils.d.mts +6 -2
  53. package/dist/controllers/user-storage/account-syncing/sync-utils.d.mts.map +1 -1
  54. package/dist/controllers/user-storage/account-syncing/sync-utils.mjs +16 -7
  55. package/dist/controllers/user-storage/account-syncing/sync-utils.mjs.map +1 -1
  56. package/dist/controllers/user-storage/account-syncing/utils.cjs +1 -42
  57. package/dist/controllers/user-storage/account-syncing/utils.cjs.map +1 -1
  58. package/dist/controllers/user-storage/account-syncing/utils.d.cts +1 -18
  59. package/dist/controllers/user-storage/account-syncing/utils.d.cts.map +1 -1
  60. package/dist/controllers/user-storage/account-syncing/utils.d.mts +1 -18
  61. package/dist/controllers/user-storage/account-syncing/utils.d.mts.map +1 -1
  62. package/dist/controllers/user-storage/account-syncing/utils.mjs +0 -39
  63. package/dist/controllers/user-storage/account-syncing/utils.mjs.map +1 -1
  64. package/dist/sdk/authentication-jwt-bearer/flow-siwe.cjs.map +1 -1
  65. package/dist/sdk/authentication-jwt-bearer/flow-siwe.d.cts.map +1 -1
  66. package/dist/sdk/authentication-jwt-bearer/flow-siwe.d.mts.map +1 -1
  67. package/dist/sdk/authentication-jwt-bearer/flow-siwe.mjs.map +1 -1
  68. package/dist/sdk/authentication-jwt-bearer/flow-srp.cjs +22 -22
  69. package/dist/sdk/authentication-jwt-bearer/flow-srp.cjs.map +1 -1
  70. package/dist/sdk/authentication-jwt-bearer/flow-srp.d.cts +4 -4
  71. package/dist/sdk/authentication-jwt-bearer/flow-srp.d.cts.map +1 -1
  72. package/dist/sdk/authentication-jwt-bearer/flow-srp.d.mts +4 -4
  73. package/dist/sdk/authentication-jwt-bearer/flow-srp.d.mts.map +1 -1
  74. package/dist/sdk/authentication-jwt-bearer/flow-srp.mjs +22 -22
  75. package/dist/sdk/authentication-jwt-bearer/flow-srp.mjs.map +1 -1
  76. package/dist/sdk/authentication-jwt-bearer/services.cjs.map +1 -1
  77. package/dist/sdk/authentication-jwt-bearer/services.d.cts.map +1 -1
  78. package/dist/sdk/authentication-jwt-bearer/services.d.mts.map +1 -1
  79. package/dist/sdk/authentication-jwt-bearer/services.mjs.map +1 -1
  80. package/dist/sdk/authentication-jwt-bearer/types.cjs.map +1 -1
  81. package/dist/sdk/authentication-jwt-bearer/types.d.cts +8 -8
  82. package/dist/sdk/authentication-jwt-bearer/types.d.cts.map +1 -1
  83. package/dist/sdk/authentication-jwt-bearer/types.d.mts +8 -8
  84. package/dist/sdk/authentication-jwt-bearer/types.d.mts.map +1 -1
  85. package/dist/sdk/authentication-jwt-bearer/types.mjs.map +1 -1
  86. package/dist/sdk/authentication.cjs +8 -11
  87. package/dist/sdk/authentication.cjs.map +1 -1
  88. package/dist/sdk/authentication.d.cts +4 -4
  89. package/dist/sdk/authentication.d.cts.map +1 -1
  90. package/dist/sdk/authentication.d.mts +4 -4
  91. package/dist/sdk/authentication.d.mts.map +1 -1
  92. package/dist/sdk/authentication.mjs +8 -11
  93. package/dist/sdk/authentication.mjs.map +1 -1
  94. package/dist/sdk/user-storage.cjs +38 -32
  95. package/dist/sdk/user-storage.cjs.map +1 -1
  96. package/dist/sdk/user-storage.d.cts +4 -3
  97. package/dist/sdk/user-storage.d.cts.map +1 -1
  98. package/dist/sdk/user-storage.d.mts +4 -3
  99. package/dist/sdk/user-storage.d.mts.map +1 -1
  100. package/dist/sdk/user-storage.mjs +38 -32
  101. package/dist/sdk/user-storage.mjs.map +1 -1
  102. package/dist/sdk/utils/messaging-signing-snap-requests.cjs +16 -4
  103. package/dist/sdk/utils/messaging-signing-snap-requests.cjs.map +1 -1
  104. package/dist/sdk/utils/messaging-signing-snap-requests.d.cts +2 -2
  105. package/dist/sdk/utils/messaging-signing-snap-requests.d.cts.map +1 -1
  106. package/dist/sdk/utils/messaging-signing-snap-requests.d.mts +2 -2
  107. package/dist/sdk/utils/messaging-signing-snap-requests.d.mts.map +1 -1
  108. package/dist/sdk/utils/messaging-signing-snap-requests.mjs +16 -4
  109. package/dist/sdk/utils/messaging-signing-snap-requests.mjs.map +1 -1
  110. package/dist/shared/storage-schema.cjs +1 -6
  111. package/dist/shared/storage-schema.cjs.map +1 -1
  112. package/dist/shared/storage-schema.d.cts +0 -1
  113. package/dist/shared/storage-schema.d.cts.map +1 -1
  114. package/dist/shared/storage-schema.d.mts +0 -1
  115. package/dist/shared/storage-schema.d.mts.map +1 -1
  116. package/dist/shared/storage-schema.mjs +0 -4
  117. package/dist/shared/storage-schema.mjs.map +1 -1
  118. package/package.json +2 -2
package/CHANGELOG.md CHANGED
@@ -7,6 +7,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [17.0.0]
11
+
12
+ ### Added
13
+
14
+ - **BREAKING:** Add multi-SRP support for authentication and user storage ([#5753](https://github.com/MetaMask/core/pull/5753))
15
+ - Add `entropySource` based authentication support for multiple SRPs
16
+ - Add `entropySource` optional parameter for `UserStorageController` CRUD methods
17
+ - Rename `sessionData` in `AuthenticationControllerState` to `srpSessionData`
18
+ - Update `AuthenticationController.performSignIn` to return `string[]` rather than `string`
19
+ - Add `AccountsController:updateAccounts` as a required allowed action to the `UserStorageController` messenger
20
+ - Add `listEntropySources` to `UserStorageController`
21
+ - Render `UserStorageController.syncInternalAccountsWithUserStorage` compatible with multi-SRP
22
+
10
23
  ## [16.0.0]
11
24
 
12
25
  ### Changed
@@ -601,7 +614,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
601
614
 
602
615
  - Initial release
603
616
 
604
- [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@16.0.0...HEAD
617
+ [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@17.0.0...HEAD
618
+ [17.0.0]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@16.0.0...@metamask/profile-sync-controller@17.0.0
605
619
  [16.0.0]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@15.0.0...@metamask/profile-sync-controller@16.0.0
606
620
  [15.0.0]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@14.0.0...@metamask/profile-sync-controller@15.0.0
607
621
  [14.0.0]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@13.0.0...@metamask/profile-sync-controller@14.0.0
@@ -10,7 +10,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
10
10
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
11
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
12
  };
13
- var _AuthenticationController_instances, _AuthenticationController_metametrics, _AuthenticationController_auth, _AuthenticationController_isUnlocked, _AuthenticationController_keyringController, _AuthenticationController_registerMessageHandlers, _AuthenticationController_getLoginResponseFromState, _AuthenticationController_setLoginResponseToState, _AuthenticationController_assertIsUnlocked, _AuthenticationController_snapGetPublicKey, _AuthenticationController__snapSignMessageCache, _AuthenticationController_snapSignMessage;
13
+ var _AuthenticationController_instances, _AuthenticationController_metametrics, _AuthenticationController_auth, _AuthenticationController_isUnlocked, _AuthenticationController_keyringController, _AuthenticationController_registerMessageHandlers, _AuthenticationController_getLoginResponseFromState, _AuthenticationController_setLoginResponseToState, _AuthenticationController_assertIsUnlocked, _AuthenticationController_snapGetPublicKey, _AuthenticationController_snapGetAllPublicKeys, _AuthenticationController__snapSignMessageCache, _AuthenticationController_snapSignMessage;
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.defaultState = void 0;
16
16
  const base_controller_1 = require("@metamask/base-controller");
@@ -25,7 +25,7 @@ const metadata = {
25
25
  persist: true,
26
26
  anonymous: true,
27
27
  },
28
- sessionData: {
28
+ srpSessionData: {
29
29
  persist: true,
30
30
  anonymous: false,
31
31
  },
@@ -83,12 +83,20 @@ class AuthenticationController extends base_controller_1.BaseController {
83
83
  }
84
84
  async performSignIn() {
85
85
  __classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_assertIsUnlocked).call(this, 'performSignIn');
86
- return await __classPrivateFieldGet(this, _AuthenticationController_auth, "f").getAccessToken();
86
+ const allPublicKeys = await __classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_snapGetAllPublicKeys).call(this);
87
+ const accessTokens = [];
88
+ // We iterate sequentially in order to be sure that the first entry
89
+ // is the primary SRP LoginResponse.
90
+ for (const [entropySourceId] of allPublicKeys) {
91
+ const accessToken = await __classPrivateFieldGet(this, _AuthenticationController_auth, "f").getAccessToken(entropySourceId);
92
+ accessTokens.push(accessToken);
93
+ }
94
+ return accessTokens;
87
95
  }
88
96
  performSignOut() {
89
97
  this.update((state) => {
90
98
  state.isSignedIn = false;
91
- state.sessionData = undefined;
99
+ state.srpSessionData = undefined;
92
100
  });
93
101
  }
94
102
  /**
@@ -97,19 +105,21 @@ class AuthenticationController extends base_controller_1.BaseController {
97
105
  *
98
106
  * @returns profile for the session.
99
107
  */
100
- async getBearerToken() {
108
+ async getBearerToken(entropySourceId) {
101
109
  __classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_assertIsUnlocked).call(this, 'getBearerToken');
102
- return await __classPrivateFieldGet(this, _AuthenticationController_auth, "f").getAccessToken();
110
+ return await __classPrivateFieldGet(this, _AuthenticationController_auth, "f").getAccessToken(entropySourceId);
103
111
  }
104
112
  /**
105
113
  * Will return a session profile.
106
114
  * Logs a user in if a user is not logged in.
107
115
  *
116
+ * @param entropySourceId - The entropy source ID used to derive the key,
117
+ * when multiple sources are available (Multi-SRP).
108
118
  * @returns profile for the session.
109
119
  */
110
- async getSessionProfile() {
120
+ async getSessionProfile(entropySourceId) {
111
121
  __classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_assertIsUnlocked).call(this, 'getSessionProfile');
112
- return await __classPrivateFieldGet(this, _AuthenticationController_auth, "f").getUserProfile();
122
+ return await __classPrivateFieldGet(this, _AuthenticationController_auth, "f").getUserProfile(entropySourceId);
113
123
  }
114
124
  isSignedIn() {
115
125
  return this.state.isSignedIn;
@@ -121,22 +131,34 @@ _AuthenticationController_metametrics = new WeakMap(), _AuthenticationController
121
131
  this.messagingSystem.registerActionHandler('AuthenticationController:isSignedIn', this.isSignedIn.bind(this));
122
132
  this.messagingSystem.registerActionHandler('AuthenticationController:performSignIn', this.performSignIn.bind(this));
123
133
  this.messagingSystem.registerActionHandler('AuthenticationController:performSignOut', this.performSignOut.bind(this));
124
- }, _AuthenticationController_getLoginResponseFromState = async function _AuthenticationController_getLoginResponseFromState() {
125
- if (!this.state.sessionData) {
134
+ }, _AuthenticationController_getLoginResponseFromState = async function _AuthenticationController_getLoginResponseFromState(entropySourceId) {
135
+ if (entropySourceId) {
136
+ if (!this.state.srpSessionData?.[entropySourceId]) {
137
+ return null;
138
+ }
139
+ return this.state.srpSessionData[entropySourceId];
140
+ }
141
+ const primarySrpLoginResponse = Object.values(this.state.srpSessionData || {})?.[0];
142
+ if (!primarySrpLoginResponse) {
126
143
  return null;
127
144
  }
128
- return this.state.sessionData;
129
- }, _AuthenticationController_setLoginResponseToState = async function _AuthenticationController_setLoginResponseToState(loginResponse) {
145
+ return primarySrpLoginResponse;
146
+ }, _AuthenticationController_setLoginResponseToState = async function _AuthenticationController_setLoginResponseToState(loginResponse, entropySourceId) {
130
147
  const metaMetricsId = await __classPrivateFieldGet(this, _AuthenticationController_metametrics, "f").getMetaMetricsId();
131
148
  this.update((state) => {
132
- state.isSignedIn = true;
133
- state.sessionData = {
134
- ...loginResponse,
135
- profile: {
136
- ...loginResponse.profile,
137
- metaMetricsId,
138
- },
139
- };
149
+ if (entropySourceId) {
150
+ state.isSignedIn = true;
151
+ if (!state.srpSessionData) {
152
+ state.srpSessionData = {};
153
+ }
154
+ state.srpSessionData[entropySourceId] = {
155
+ ...loginResponse,
156
+ profile: {
157
+ ...loginResponse.profile,
158
+ metaMetricsId,
159
+ },
160
+ };
161
+ }
140
162
  });
141
163
  }, _AuthenticationController_assertIsUnlocked = function _AuthenticationController_assertIsUnlocked(methodName) {
142
164
  if (!__classPrivateFieldGet(this, _AuthenticationController_isUnlocked, "f")) {
@@ -146,26 +168,40 @@ _AuthenticationController_metametrics = new WeakMap(), _AuthenticationController
146
168
  /**
147
169
  * Returns the auth snap public key.
148
170
  *
171
+ * @param entropySourceId - The entropy source ID used to derive the key,
172
+ * when multiple sources are available (Multi-SRP).
149
173
  * @returns The snap public key.
150
174
  */
151
- async function _AuthenticationController_snapGetPublicKey() {
175
+ async function _AuthenticationController_snapGetPublicKey(entropySourceId) {
152
176
  __classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_assertIsUnlocked).call(this, '#snapGetPublicKey');
153
- const result = (await this.messagingSystem.call('SnapController:handleRequest', (0, auth_snap_requests_1.createSnapPublicKeyRequest)()));
177
+ const result = (await this.messagingSystem.call('SnapController:handleRequest', (0, auth_snap_requests_1.createSnapPublicKeyRequest)(entropySourceId)));
178
+ return result;
179
+ }, _AuthenticationController_snapGetAllPublicKeys =
180
+ /**
181
+ * Returns a mapping of entropy source IDs to auth snap public keys.
182
+ *
183
+ * @returns A mapping of entropy source IDs to public keys.
184
+ */
185
+ async function _AuthenticationController_snapGetAllPublicKeys() {
186
+ __classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_assertIsUnlocked).call(this, '#snapGetAllPublicKeys');
187
+ const result = (await this.messagingSystem.call('SnapController:handleRequest', (0, auth_snap_requests_1.createSnapAllPublicKeysRequest)()));
154
188
  return result;
155
189
  }, _AuthenticationController_snapSignMessage =
156
190
  /**
157
191
  * Signs a specific message using an underlying auth snap.
158
192
  *
159
193
  * @param message - A specific tagged message to sign.
194
+ * @param entropySourceId - The entropy source ID used to derive the key,
195
+ * when multiple sources are available (Multi-SRP).
160
196
  * @returns A Signature created by the snap.
161
197
  */
162
- async function _AuthenticationController_snapSignMessage(message) {
198
+ async function _AuthenticationController_snapSignMessage(message, entropySourceId) {
163
199
  (0, sdk_1.assertMessageStartsWithMetamask)(message);
164
200
  if (__classPrivateFieldGet(this, _AuthenticationController__snapSignMessageCache, "f")[message]) {
165
201
  return __classPrivateFieldGet(this, _AuthenticationController__snapSignMessageCache, "f")[message];
166
202
  }
167
203
  __classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_assertIsUnlocked).call(this, '#snapSignMessage');
168
- const result = (await this.messagingSystem.call('SnapController:handleRequest', (0, auth_snap_requests_1.createSnapSignMessageRequest)(message)));
204
+ const result = (await this.messagingSystem.call('SnapController:handleRequest', (0, auth_snap_requests_1.createSnapSignMessageRequest)(message, entropySourceId)));
169
205
  __classPrivateFieldGet(this, _AuthenticationController__snapSignMessageCache, "f")[message] = result;
170
206
  return result;
171
207
  };
@@ -1 +1 @@
1
- {"version":3,"file":"AuthenticationController.cjs","sourceRoot":"","sources":["../../../src/controllers/authentication/AuthenticationController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAMA,+DAA2D;AAQ3D,iEAG8B;AAE9B,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,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,IAAI;KAChB;IACD,WAAW,EAAE;QACX,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;KACjB;CACF,CAAC;AA0DF;;;GAGG;AACH,MAAqB,wBAAyB,SAAQ,gCAIrD;IAwBC,YAAY,EACV,SAAS,EACT,KAAK,EACL,WAAW,GASZ;QACC,KAAK,CAAC;YACJ,SAAS;YACT,QAAQ;YACR,IAAI,EAAE,cAAc;YACpB,KAAK,EAAE,EAAE,GAAG,oBAAY,EAAE,GAAG,KAAK,EAAE;SACrC,CAAC,CAAC;;QAzCI,wDAA8B;QAE9B,iDAAoB;QAE7B,+CAAc,KAAK,EAAC;QAEX,sDAAqB;YAC5B,6BAA6B,EAAE,GAAG,EAAE;gBAClC,MAAM,EAAE,UAAU,EAAE,GAAG,IAAI,CAAC,eAAe,CAAC,IAAI,CAC9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CAAC,EAAE;QACxC,OAAO,uBAAA,IAAI,uDAAuB,CAAC,OAAO,CAAC,CAAC;KAC7C;IAED,uBAAA,IAAI,uFAAkB,MAAtB,IAAI,EAAmB,kBAAkB,CAAC,CAAC;IAE3C,MAAM,MAAM,GAAG,CAAC,MAAM,IAAI,CAAC,eAAe,CAAC,IAAI,CAC7C,8BAA8B,EAC9B,IAAA,iDAA4B,EAAC,OAAO,CAAC,CACtC,CAAW,CAAC;IAEb,uBAAA,IAAI,uDAAuB,CAAC,OAAO,CAAC,GAAG,MAAM,CAAC;IAE9C,OAAO,MAAM,CAAC;AAChB,CAAC;kBAxNkB,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';\n\nimport {\n createSnapPublicKeyRequest,\n createSnapSignMessageRequest,\n} from './auth-snap-requests';\nimport type { LoginResponse, SRPInterface, UserProfile } 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 sessionData?: LoginResponse;\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 =\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 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 #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 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.#auth = new JwtBearerAuth(\n {\n env: Env.PRD,\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\n async #getLoginResponseFromState(): Promise<LoginResponse | null> {\n if (!this.state.sessionData) {\n return null;\n }\n\n return this.state.sessionData;\n }\n\n async #setLoginResponseToState(loginResponse: LoginResponse) {\n const metaMetricsId = await this.#metametrics.getMetaMetricsId();\n this.update((state) => {\n state.isSignedIn = true;\n state.sessionData = {\n ...loginResponse,\n profile: {\n ...loginResponse.profile,\n metaMetricsId,\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 return await this.#auth.getAccessToken();\n }\n\n public performSignOut(): void {\n this.update((state) => {\n state.isSignedIn = false;\n state.sessionData = 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(): Promise<string> {\n this.#assertIsUnlocked('getBearerToken');\n return await this.#auth.getAccessToken();\n }\n\n /**\n * Will return a session profile.\n * Logs a user in if a user is not logged in.\n *\n * @returns profile for the session.\n */\n public async getSessionProfile(): Promise<UserProfile> {\n this.#assertIsUnlocked('getSessionProfile');\n return await this.#auth.getUserProfile();\n }\n\n public isSignedIn(): boolean {\n return this.state.isSignedIn;\n }\n\n /**\n * Returns the auth snap public key.\n *\n * @returns The snap public key.\n */\n async #snapGetPublicKey(): Promise<string> {\n this.#assertIsUnlocked('#snapGetPublicKey');\n\n const result = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n createSnapPublicKeyRequest(),\n )) as 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 * @returns A Signature created by the snap.\n */\n async #snapSignMessage(message: string): 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),\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":";;;;;;;;;;;;;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FAAkB,MAAtB,IAAI,EAAmB,mBAAmB,CAAC,CAAC;IAE5C,MAAM,MAAM,GAAG,CAAC,MAAM,IAAI,CAAC,eAAe,CAAC,IAAI,CAC7C,8BAA8B,EAC9B,IAAA,+CAA0B,EAAC,eAAe,CAAC,CAC5C,CAAW,CAAC;IAEb,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;GAIG;AACH,KAAK;IACH,uBAAA,IAAI,uFAAkB,MAAtB,IAAI,EAAmB,uBAAuB,CAAC,CAAC;IAEhD,MAAM,MAAM,GAAG,CAAC,MAAM,IAAI,CAAC,eAAe,CAAC,IAAI,CAC7C,8BAA8B,EAC9B,IAAA,mDAA8B,GAAE,CACjC,CAAuB,CAAC;IAEzB,OAAO,MAAM,CAAC;AAChB,CAAC;AAID;;;;;;;GAOG;AACH,KAAK,oDACH,OAAe,EACf,eAAwB;IAExB,IAAA,qCAA+B,EAAC,OAAO,CAAC,CAAC;IAEzC,IAAI,uBAAA,IAAI,uDAAuB,CAAC,OAAO,CAAC,EAAE;QACxC,OAAO,uBAAA,IAAI,uDAAuB,CAAC,OAAO,CAAC,CAAC;KAC7C;IAED,uBAAA,IAAI,uFAAkB,MAAtB,IAAI,EAAmB,kBAAkB,CAAC,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;kBAnRkB,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';\n\nimport {\n createSnapPublicKeyRequest,\n createSnapAllPublicKeysRequest,\n createSnapSignMessageRequest,\n} from './auth-snap-requests';\nimport type { LoginResponse, SRPInterface, UserProfile } 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 persist: true,\n anonymous: true,\n },\n srpSessionData: {\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 =\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 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 #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 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.#auth = new JwtBearerAuth(\n {\n env: Env.PRD,\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\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 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"]}
@@ -7,7 +7,7 @@ import type { MetaMetricsAuth } from "../../shared/types/services.cjs";
7
7
  declare const controllerName = "AuthenticationController";
8
8
  export type AuthenticationControllerState = {
9
9
  isSignedIn: boolean;
10
- sessionData?: LoginResponse;
10
+ srpSessionData?: Record<string, LoginResponse>;
11
11
  };
12
12
  export declare const defaultState: AuthenticationControllerState;
13
13
  type CreateActionsObj<Controller extends keyof AuthenticationController> = {
@@ -44,7 +44,7 @@ export default class AuthenticationController extends BaseController<typeof cont
44
44
  */
45
45
  metametrics: MetaMetricsAuth;
46
46
  });
47
- performSignIn(): Promise<string>;
47
+ performSignIn(): Promise<string[]>;
48
48
  performSignOut(): void;
49
49
  /**
50
50
  * Will return a bearer token.
@@ -52,14 +52,16 @@ export default class AuthenticationController extends BaseController<typeof cont
52
52
  *
53
53
  * @returns profile for the session.
54
54
  */
55
- getBearerToken(): Promise<string>;
55
+ getBearerToken(entropySourceId?: string): Promise<string>;
56
56
  /**
57
57
  * Will return a session profile.
58
58
  * Logs a user in if a user is not logged in.
59
59
  *
60
+ * @param entropySourceId - The entropy source ID used to derive the key,
61
+ * when multiple sources are available (Multi-SRP).
60
62
  * @returns profile for the session.
61
63
  */
62
- getSessionProfile(): Promise<UserProfile>;
64
+ getSessionProfile(entropySourceId?: string): Promise<UserProfile>;
63
65
  isSignedIn(): boolean;
64
66
  }
65
67
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"AuthenticationController.d.cts","sourceRoot":"","sources":["../../../src/controllers/authentication/AuthenticationController.ts"],"names":[],"mappings":"AAAA,O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AAM,MAAM,yCAAyC,GACnD,UAAU,CAAC,mBAAmB,CAAC,CAAC;AAClC,MAAM,MAAM,kCAAkC,GAAG,UAAU,CAAC,YAAY,CAAC,CAAC;AAE1E,MAAM,MAAM,wCAAwC,GAClD,0BAA0B,CACxB,OAAO,cAAc,EACrB,6BAA6B,CAC9B,CAAC;AAEJ,MAAM,MAAM,MAAM,GAAG,wCAAwC,CAAC;AAG9D,MAAM,MAAM,cAAc,GACtB,iBAAiB,GACjB,+BAA+B,CAAC;AAEpC,MAAM,MAAM,aAAa,GACrB,0BAA0B,GAC1B,4BAA4B,CAAC;AAGjC,MAAM,MAAM,iCAAiC,GAAG,mBAAmB,CACjE,OAAO,cAAc,EACrB,OAAO,GAAG,cAAc,EACxB,MAAM,GAAG,aAAa,EACtB,cAAc,CAAC,MAAM,CAAC,EACtB,aAAa,CAAC,MAAM,CAAC,CACtB,CAAC;AAEF;;;GAGG;AACH,MAAM,CAAC,OAAO,OAAO,wBAAyB,SAAQ,cAAc,CAClE,OAAO,cAAc,EACrB,6BAA6B,EAC7B,iCAAiC,CAClC;;gBAwBa,EACV,SAAS,EACT,KAAK,EACL,WAAW,GACZ,EAAE;QACD,SAAS,EAAE,iCAAiC,CAAC;QAC7C,KAAK,CAAC,EAAE,6BAA6B,CAAC;QACtC;;;WAGG;QACH,WAAW,EAAE,eAAe,CAAC;KAC9B;IAgGY,aAAa,IAAI,OAAO,CAAC,MAAM,CAAC;IAKtC,cAAc,IAAI,IAAI;IAO7B;;;;;OAKG;IAEU,cAAc,IAAI,OAAO,CAAC,MAAM,CAAC;IAK9C;;;;;OAKG;IACU,iBAAiB,IAAI,OAAO,CAAC,WAAW,CAAC;IAK/C,UAAU,IAAI,OAAO;CA8C7B"}
1
+ {"version":3,"file":"AuthenticationController.d.cts","sourceRoot":"","sources":["../../../src/controllers/authentication/AuthenticationController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAC1B,mBAAmB,EA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AU,CAAC,mBAAmB,CAAC,CAAC;AAClC,MAAM,MAAM,kCAAkC,GAAG,UAAU,CAAC,YAAY,CAAC,CAAC;AAE1E,MAAM,MAAM,wCAAwC,GAClD,0BAA0B,CACxB,OAAO,cAAc,EACrB,6BAA6B,CAC9B,CAAC;AAEJ,MAAM,MAAM,MAAM,GAAG,wCAAwC,CAAC;AAG9D,MAAM,MAAM,cAAc,GACtB,iBAAiB,GACjB,+BAA+B,CAAC;AAEpC,MAAM,MAAM,aAAa,GACrB,0BAA0B,GAC1B,4BAA4B,CAAC;AAGjC,MAAM,MAAM,iCAAiC,GAAG,mBAAmB,CACjE,OAAO,cAAc,EACrB,OAAO,GAAG,cAAc,EACxB,MAAM,GAAG,aAAa,EACtB,cAAc,CAAC,MAAM,CAAC,EACtB,aAAa,CAAC,MAAM,CAAC,CACtB,CAAC;AAEF;;;GAGG;AACH,MAAM,CAAC,OAAO,OAAO,wBAAyB,SAAQ,cAAc,CAClE,OAAO,cAAc,EACrB,6BAA6B,EAC7B,iCAAiC,CAClC;;gBAwBa,EACV,SAAS,EACT,KAAK,EACL,WAAW,GACZ,EAAE;QACD,SAAS,EAAE,iCAAiC,CAAC;QAC7C,KAAK,CAAC,EAAE,6BAA6B,CAAC;QACtC;;;WAGG;QACH,WAAW,EAAE,eAAe,CAAC;KAC9B;IAqHY,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;IAKhB,UAAU,IAAI,OAAO;CAqE7B"}
@@ -7,7 +7,7 @@ import type { MetaMetricsAuth } from "../../shared/types/services.mjs";
7
7
  declare const controllerName = "AuthenticationController";
8
8
  export type AuthenticationControllerState = {
9
9
  isSignedIn: boolean;
10
- sessionData?: LoginResponse;
10
+ srpSessionData?: Record<string, LoginResponse>;
11
11
  };
12
12
  export declare const defaultState: AuthenticationControllerState;
13
13
  type CreateActionsObj<Controller extends keyof AuthenticationController> = {
@@ -44,7 +44,7 @@ export default class AuthenticationController extends BaseController<typeof cont
44
44
  */
45
45
  metametrics: MetaMetricsAuth;
46
46
  });
47
- performSignIn(): Promise<string>;
47
+ performSignIn(): Promise<string[]>;
48
48
  performSignOut(): void;
49
49
  /**
50
50
  * Will return a bearer token.
@@ -52,14 +52,16 @@ export default class AuthenticationController extends BaseController<typeof cont
52
52
  *
53
53
  * @returns profile for the session.
54
54
  */
55
- getBearerToken(): Promise<string>;
55
+ getBearerToken(entropySourceId?: string): Promise<string>;
56
56
  /**
57
57
  * Will return a session profile.
58
58
  * Logs a user in if a user is not logged in.
59
59
  *
60
+ * @param entropySourceId - The entropy source ID used to derive the key,
61
+ * when multiple sources are available (Multi-SRP).
60
62
  * @returns profile for the session.
61
63
  */
62
- getSessionProfile(): Promise<UserProfile>;
64
+ getSessionProfile(entropySourceId?: string): Promise<UserProfile>;
63
65
  isSignedIn(): boolean;
64
66
  }
65
67
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"AuthenticationController.d.mts","sourceRoot":"","sources":["../../../src/controllers/authentication/AuthenticationController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAC1B,mBAAmB,EAEpB,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,KAAK,EACV,+BAA+B,EAC/B,0BAA0B,EAC1B,4BAA4B,EAC7B,qCAAqC;AACtC,OAAO,KAAK,EAAE,iBAAiB,EAAE,oCAAoC;AAMrE,OAAO,KAAK,EAAE,aAAa,EAAgB,WAAW,EAAE,4BAAkB;AAO1E,OAAO,KAAK,EAAE,eAAe,EAAE,wCAAoC;AAEnE,QAAA,MAAM,cAAc,6BAA6B,CAAC;AAGl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AAM,MAAM,iCAAiC,GAAG,mBAAmB,CACjE,OAAO,cAAc,EACrB,OAAO,GAAG,cAAc,EACxB,MAAM,GAAG,aAAa,EACtB,cAAc,CAAC,MAAM,CAAC,EACtB,aAAa,CAAC,MAAM,CAAC,CACtB,CAAC;AAEF;;;GAGG;AACH,MAAM,CAAC,OAAO,OAAO,wBAAyB,SAAQ,cAAc,CAClE,OAAO,cAAc,EACrB,6BAA6B,EAC7B,iCAAiC,CAClC;;gBAwBa,EACV,SAAS,EACT,KAAK,EACL,WAAW,GACZ,EAAE;QACD,SAAS,EAAE,iCAAiC,CAAC;QAC7C,KAAK,CAAC,EAAE,6BAA6B,CAAC;QACtC;;;WAGG;QACH,WAAW,EAAE,eAAe,CAAC;KAC9B;IAgGY,aAAa,IAAI,OAAO,CAAC,MAAM,CAAC;IAKtC,cAAc,IAAI,IAAI;IAO7B;;;;;OAKG;IAEU,cAAc,IAAI,OAAO,CAAC,MAAM,CAAC;IAK9C;;;;;OAKG;IACU,iBAAiB,IAAI,OAAO,CAAC,WAAW,CAAC;IAK/C,UAAU,IAAI,OAAO;CA8C7B"}
1
+ {"version":3,"file":"AuthenticationController.d.mts","sourceRoot":"","sources":["../../../src/controllers/authentication/AuthenticationController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAC1B,mBAAmB,EAEpB,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,KAAK,EACV,+BAA+B,EAC/B,0BAA0B,EAC1B,4BAA4B,EAC7B,qCAAqC;AACtC,OAAO,KAAK,EAAE,iBAAiB,EAAE,oCAAoC;AAOrE,OAAO,KAAK,EAAE,aAAa,EAAgB,WAAW,EAAE,4BAAkB;AAO1E,OAAO,KAAK,EAAE,eAAe,EAAE,wCAAoC;AAEnE,QAAA,MAAM,cAAc,6BAA6B,CAAC;AAGlD,MAAM,MAAM,6BAA6B,GAAG;IAC1C,UAAU,EAAE,OAAO,CA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AAmB,CACjE,OAAO,cAAc,EACrB,OAAO,GAAG,cAAc,EACxB,MAAM,GAAG,aAAa,EACtB,cAAc,CAAC,MAAM,CAAC,EACtB,aAAa,CAAC,MAAM,CAAC,CACtB,CAAC;AAEF;;;GAGG;AACH,MAAM,CAAC,OAAO,OAAO,wBAAyB,SAAQ,cAAc,CAClE,OAAO,cAAc,EACrB,6BAA6B,EAC7B,iCAAiC,CAClC;;gBAwBa,EACV,SAAS,EACT,KAAK,EACL,WAAW,GACZ,EAAE;QACD,SAAS,EAAE,iCAAiC,CAAC;QAC7C,KAAK,CAAC,EAAE,6BAA6B,CAAC;QACtC;;;WAGG;QACH,WAAW,EAAE,eAAe,CAAC;KAC9B;IAqHY,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;IAKhB,UAAU,IAAI,OAAO;CAqE7B"}
@@ -9,9 +9,9 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _AuthenticationController_instances, _AuthenticationController_metametrics, _AuthenticationController_auth, _AuthenticationController_isUnlocked, _AuthenticationController_keyringController, _AuthenticationController_registerMessageHandlers, _AuthenticationController_getLoginResponseFromState, _AuthenticationController_setLoginResponseToState, _AuthenticationController_assertIsUnlocked, _AuthenticationController_snapGetPublicKey, _AuthenticationController__snapSignMessageCache, _AuthenticationController_snapSignMessage;
12
+ var _AuthenticationController_instances, _AuthenticationController_metametrics, _AuthenticationController_auth, _AuthenticationController_isUnlocked, _AuthenticationController_keyringController, _AuthenticationController_registerMessageHandlers, _AuthenticationController_getLoginResponseFromState, _AuthenticationController_setLoginResponseToState, _AuthenticationController_assertIsUnlocked, _AuthenticationController_snapGetPublicKey, _AuthenticationController_snapGetAllPublicKeys, _AuthenticationController__snapSignMessageCache, _AuthenticationController_snapSignMessage;
13
13
  import { BaseController } from "@metamask/base-controller";
14
- import { createSnapPublicKeyRequest, createSnapSignMessageRequest } from "./auth-snap-requests.mjs";
14
+ import { createSnapPublicKeyRequest, createSnapAllPublicKeysRequest, createSnapSignMessageRequest } from "./auth-snap-requests.mjs";
15
15
  import { assertMessageStartsWithMetamask, AuthType, Env, JwtBearerAuth } from "../../sdk/index.mjs";
16
16
  const controllerName = 'AuthenticationController';
17
17
  export const defaultState = {
@@ -22,7 +22,7 @@ const metadata = {
22
22
  persist: true,
23
23
  anonymous: true,
24
24
  },
25
- sessionData: {
25
+ srpSessionData: {
26
26
  persist: true,
27
27
  anonymous: false,
28
28
  },
@@ -80,12 +80,20 @@ class AuthenticationController extends BaseController {
80
80
  }
81
81
  async performSignIn() {
82
82
  __classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_assertIsUnlocked).call(this, 'performSignIn');
83
- return await __classPrivateFieldGet(this, _AuthenticationController_auth, "f").getAccessToken();
83
+ const allPublicKeys = await __classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_snapGetAllPublicKeys).call(this);
84
+ const accessTokens = [];
85
+ // We iterate sequentially in order to be sure that the first entry
86
+ // is the primary SRP LoginResponse.
87
+ for (const [entropySourceId] of allPublicKeys) {
88
+ const accessToken = await __classPrivateFieldGet(this, _AuthenticationController_auth, "f").getAccessToken(entropySourceId);
89
+ accessTokens.push(accessToken);
90
+ }
91
+ return accessTokens;
84
92
  }
85
93
  performSignOut() {
86
94
  this.update((state) => {
87
95
  state.isSignedIn = false;
88
- state.sessionData = undefined;
96
+ state.srpSessionData = undefined;
89
97
  });
90
98
  }
91
99
  /**
@@ -94,19 +102,21 @@ class AuthenticationController extends BaseController {
94
102
  *
95
103
  * @returns profile for the session.
96
104
  */
97
- async getBearerToken() {
105
+ async getBearerToken(entropySourceId) {
98
106
  __classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_assertIsUnlocked).call(this, 'getBearerToken');
99
- return await __classPrivateFieldGet(this, _AuthenticationController_auth, "f").getAccessToken();
107
+ return await __classPrivateFieldGet(this, _AuthenticationController_auth, "f").getAccessToken(entropySourceId);
100
108
  }
101
109
  /**
102
110
  * Will return a session profile.
103
111
  * Logs a user in if a user is not logged in.
104
112
  *
113
+ * @param entropySourceId - The entropy source ID used to derive the key,
114
+ * when multiple sources are available (Multi-SRP).
105
115
  * @returns profile for the session.
106
116
  */
107
- async getSessionProfile() {
117
+ async getSessionProfile(entropySourceId) {
108
118
  __classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_assertIsUnlocked).call(this, 'getSessionProfile');
109
- return await __classPrivateFieldGet(this, _AuthenticationController_auth, "f").getUserProfile();
119
+ return await __classPrivateFieldGet(this, _AuthenticationController_auth, "f").getUserProfile(entropySourceId);
110
120
  }
111
121
  isSignedIn() {
112
122
  return this.state.isSignedIn;
@@ -118,22 +128,34 @@ _AuthenticationController_metametrics = new WeakMap(), _AuthenticationController
118
128
  this.messagingSystem.registerActionHandler('AuthenticationController:isSignedIn', this.isSignedIn.bind(this));
119
129
  this.messagingSystem.registerActionHandler('AuthenticationController:performSignIn', this.performSignIn.bind(this));
120
130
  this.messagingSystem.registerActionHandler('AuthenticationController:performSignOut', this.performSignOut.bind(this));
121
- }, _AuthenticationController_getLoginResponseFromState = async function _AuthenticationController_getLoginResponseFromState() {
122
- if (!this.state.sessionData) {
131
+ }, _AuthenticationController_getLoginResponseFromState = async function _AuthenticationController_getLoginResponseFromState(entropySourceId) {
132
+ if (entropySourceId) {
133
+ if (!this.state.srpSessionData?.[entropySourceId]) {
134
+ return null;
135
+ }
136
+ return this.state.srpSessionData[entropySourceId];
137
+ }
138
+ const primarySrpLoginResponse = Object.values(this.state.srpSessionData || {})?.[0];
139
+ if (!primarySrpLoginResponse) {
123
140
  return null;
124
141
  }
125
- return this.state.sessionData;
126
- }, _AuthenticationController_setLoginResponseToState = async function _AuthenticationController_setLoginResponseToState(loginResponse) {
142
+ return primarySrpLoginResponse;
143
+ }, _AuthenticationController_setLoginResponseToState = async function _AuthenticationController_setLoginResponseToState(loginResponse, entropySourceId) {
127
144
  const metaMetricsId = await __classPrivateFieldGet(this, _AuthenticationController_metametrics, "f").getMetaMetricsId();
128
145
  this.update((state) => {
129
- state.isSignedIn = true;
130
- state.sessionData = {
131
- ...loginResponse,
132
- profile: {
133
- ...loginResponse.profile,
134
- metaMetricsId,
135
- },
136
- };
146
+ if (entropySourceId) {
147
+ state.isSignedIn = true;
148
+ if (!state.srpSessionData) {
149
+ state.srpSessionData = {};
150
+ }
151
+ state.srpSessionData[entropySourceId] = {
152
+ ...loginResponse,
153
+ profile: {
154
+ ...loginResponse.profile,
155
+ metaMetricsId,
156
+ },
157
+ };
158
+ }
137
159
  });
138
160
  }, _AuthenticationController_assertIsUnlocked = function _AuthenticationController_assertIsUnlocked(methodName) {
139
161
  if (!__classPrivateFieldGet(this, _AuthenticationController_isUnlocked, "f")) {
@@ -143,26 +165,40 @@ _AuthenticationController_metametrics = new WeakMap(), _AuthenticationController
143
165
  /**
144
166
  * Returns the auth snap public key.
145
167
  *
168
+ * @param entropySourceId - The entropy source ID used to derive the key,
169
+ * when multiple sources are available (Multi-SRP).
146
170
  * @returns The snap public key.
147
171
  */
148
- async function _AuthenticationController_snapGetPublicKey() {
172
+ async function _AuthenticationController_snapGetPublicKey(entropySourceId) {
149
173
  __classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_assertIsUnlocked).call(this, '#snapGetPublicKey');
150
- const result = (await this.messagingSystem.call('SnapController:handleRequest', createSnapPublicKeyRequest()));
174
+ const result = (await this.messagingSystem.call('SnapController:handleRequest', createSnapPublicKeyRequest(entropySourceId)));
175
+ return result;
176
+ }, _AuthenticationController_snapGetAllPublicKeys =
177
+ /**
178
+ * Returns a mapping of entropy source IDs to auth snap public keys.
179
+ *
180
+ * @returns A mapping of entropy source IDs to public keys.
181
+ */
182
+ async function _AuthenticationController_snapGetAllPublicKeys() {
183
+ __classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_assertIsUnlocked).call(this, '#snapGetAllPublicKeys');
184
+ const result = (await this.messagingSystem.call('SnapController:handleRequest', createSnapAllPublicKeysRequest()));
151
185
  return result;
152
186
  }, _AuthenticationController_snapSignMessage =
153
187
  /**
154
188
  * Signs a specific message using an underlying auth snap.
155
189
  *
156
190
  * @param message - A specific tagged message to sign.
191
+ * @param entropySourceId - The entropy source ID used to derive the key,
192
+ * when multiple sources are available (Multi-SRP).
157
193
  * @returns A Signature created by the snap.
158
194
  */
159
- async function _AuthenticationController_snapSignMessage(message) {
195
+ async function _AuthenticationController_snapSignMessage(message, entropySourceId) {
160
196
  assertMessageStartsWithMetamask(message);
161
197
  if (__classPrivateFieldGet(this, _AuthenticationController__snapSignMessageCache, "f")[message]) {
162
198
  return __classPrivateFieldGet(this, _AuthenticationController__snapSignMessageCache, "f")[message];
163
199
  }
164
200
  __classPrivateFieldGet(this, _AuthenticationController_instances, "m", _AuthenticationController_assertIsUnlocked).call(this, '#snapSignMessage');
165
- const result = (await this.messagingSystem.call('SnapController:handleRequest', createSnapSignMessageRequest(message)));
201
+ const result = (await this.messagingSystem.call('SnapController:handleRequest', createSnapSignMessageRequest(message, entropySourceId)));
166
202
  __classPrivateFieldGet(this, _AuthenticationController__snapSignMessageCache, "f")[message] = result;
167
203
  return result;
168
204
  };
@@ -1 +1 @@
1
- {"version":3,"file":"AuthenticationController.mjs","sourceRoot":"","sources":["../../../src/controllers/authentication/AuthenticationController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAMA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AA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cesContent":["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';\n\nimport {\n createSnapPublicKeyRequest,\n createSnapSignMessageRequest,\n} from './auth-snap-requests';\nimport type { LoginResponse, SRPInterface, UserProfile } 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 sessionData?: LoginResponse;\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 =\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 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 #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 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.#auth = new JwtBearerAuth(\n {\n env: Env.PRD,\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\n async #getLoginResponseFromState(): Promise<LoginResponse | null> {\n if (!this.state.sessionData) {\n return null;\n }\n\n return this.state.sessionData;\n }\n\n async #setLoginResponseToState(loginResponse: LoginResponse) {\n const metaMetricsId = await this.#metametrics.getMetaMetricsId();\n this.update((state) => {\n state.isSignedIn = true;\n state.sessionData = {\n ...loginResponse,\n profile: {\n ...loginResponse.profile,\n metaMetricsId,\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 return await this.#auth.getAccessToken();\n }\n\n public performSignOut(): void {\n this.update((state) => {\n state.isSignedIn = false;\n state.sessionData = 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(): Promise<string> {\n this.#assertIsUnlocked('getBearerToken');\n return await this.#auth.getAccessToken();\n }\n\n /**\n * Will return a session profile.\n * Logs a user in if a user is not logged in.\n *\n * @returns profile for the session.\n */\n public async getSessionProfile(): Promise<UserProfile> {\n this.#assertIsUnlocked('getSessionProfile');\n return await this.#auth.getUserProfile();\n }\n\n public isSignedIn(): boolean {\n return this.state.isSignedIn;\n }\n\n /**\n * Returns the auth snap public key.\n *\n * @returns The snap public key.\n */\n async #snapGetPublicKey(): Promise<string> {\n this.#assertIsUnlocked('#snapGetPublicKey');\n\n const result = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n createSnapPublicKeyRequest(),\n )) as 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 * @returns A Signature created by the snap.\n */\n async #snapSignMessage(message: string): 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),\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":";;;;;;;;;;;;AAMA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAQ3D,OAAO,EACL,0BAA0B,EAC1B,8BAA8B,EAC9B,4BAA4B,EAC7B,iCAA6B;AAE9B,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,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,IAAI;KAChB;IACD,cAA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AI,uFAAkB,MAAtB,IAAI,EAAmB,uBAAuB,CAAC,CAAC;IAEhD,MAAM,MAAM,GAAG,CAAC,MAAM,IAAI,CAAC,eAAe,CAAC,IAAI,CAC7C,8BAA8B,EAC9B,8BAA8B,EAAE,CACjC,CAAuB,CAAC;IAEzB,OAAO,MAAM,CAAC;AAChB,CAAC;AAID;;;;;;;GAOG;AACH,KAAK,oDACH,OAAe,EACf,eAAwB;IAExB,+BAA+B,CAAC,OAAO,CAAC,CAAC;IAEzC,IAAI,uBAAA,IAAI,uDAAuB,CAAC,OAAO,CAAC,EAAE;QACxC,OAAO,uBAAA,IAAI,uDAAuB,CAAC,OAAO,CAAC,CAAC;KAC7C;IAED,uBAAA,IAAI,uFAAkB,MAAtB,IAAI,EAAmB,kBAAkB,CAAC,CAAC;IAE3C,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,uDAAuB,CAAC,OAAO,CAAC,GAAG,MAAM,CAAC;IAE9C,OAAO,MAAM,CAAC;AAChB,CAAC;eAnRkB,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';\n\nimport {\n createSnapPublicKeyRequest,\n createSnapAllPublicKeysRequest,\n createSnapSignMessageRequest,\n} from './auth-snap-requests';\nimport type { LoginResponse, SRPInterface, UserProfile } 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 persist: true,\n anonymous: true,\n },\n srpSessionData: {\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 =\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 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 #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 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.#auth = new JwtBearerAuth(\n {\n env: Env.PRD,\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\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 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"]}