@metamask/profile-sync-controller 0.2.1 → 0.4.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 (189) hide show
  1. package/CHANGELOG.md +42 -1
  2. package/auth/mocks/package.json +9 -0
  3. package/auth/package.json +9 -0
  4. package/dist/{chunk-JENTMRXO.js → chunk-246Z6L5V.js} +245 -16
  5. package/dist/chunk-246Z6L5V.js.map +1 -0
  6. package/dist/chunk-2677XY6G.mjs +107 -0
  7. package/dist/chunk-2677XY6G.mjs.map +1 -0
  8. package/dist/{chunk-BDO3VJEU.mjs → chunk-2CWF7ZTL.mjs} +2 -2
  9. package/dist/{chunk-ILIZJQ6X.mjs → chunk-2VEMA6OE.mjs} +11 -4
  10. package/dist/chunk-2VEMA6OE.mjs.map +1 -0
  11. package/dist/chunk-4LMFZDL4.js +114 -0
  12. package/dist/chunk-4LMFZDL4.js.map +1 -0
  13. package/dist/{chunk-VD2IGTS3.js → chunk-4ZGRRVMI.js} +5 -5
  14. package/dist/{chunk-SLHAVOTE.js → chunk-5MQUI24U.js} +13 -6
  15. package/dist/chunk-5MQUI24U.js.map +1 -0
  16. package/dist/chunk-6DAK2U35.mjs +11 -0
  17. package/dist/chunk-6DAK2U35.mjs.map +1 -0
  18. package/dist/{chunk-FU7PSGFP.mjs → chunk-76NMME23.mjs} +51 -9
  19. package/dist/chunk-76NMME23.mjs.map +1 -0
  20. package/dist/{chunk-7KMONAQI.mjs → chunk-7MSQV43P.mjs} +7 -9
  21. package/dist/{chunk-7KMONAQI.mjs.map → chunk-7MSQV43P.mjs.map} +1 -1
  22. package/dist/{chunk-T3FNDVE3.js → chunk-BKQE7DB5.js} +30 -18
  23. package/dist/chunk-BKQE7DB5.js.map +1 -0
  24. package/dist/chunk-CHUZGCDV.js +107 -0
  25. package/dist/chunk-CHUZGCDV.js.map +1 -0
  26. package/dist/{chunk-K5UKU454.mjs → chunk-COBJUBZE.mjs} +31 -19
  27. package/dist/chunk-COBJUBZE.mjs.map +1 -0
  28. package/dist/{chunk-WWQ65CZY.mjs → chunk-D4SNJOID.mjs} +2 -2
  29. package/dist/chunk-D4SNJOID.mjs.map +1 -0
  30. package/dist/{chunk-SMKTWM6I.js → chunk-DF24ZX4H.js} +2 -3
  31. package/dist/chunk-DF24ZX4H.js.map +1 -0
  32. package/dist/chunk-EHZFPUJH.mjs +53 -0
  33. package/dist/chunk-EHZFPUJH.mjs.map +1 -0
  34. package/dist/{chunk-KW3X4TT5.js → chunk-F6BAOSH2.js} +6 -6
  35. package/dist/chunk-F6BAOSH2.js.map +1 -0
  36. package/dist/chunk-GQXYWBFK.js +28 -0
  37. package/dist/chunk-GQXYWBFK.js.map +1 -0
  38. package/dist/{chunk-DRD22DR5.mjs → chunk-J7NSK6BO.mjs} +2 -2
  39. package/dist/chunk-JAQ5TPSZ.js +53 -0
  40. package/dist/chunk-JAQ5TPSZ.js.map +1 -0
  41. package/dist/{chunk-5TOWF6UW.mjs → chunk-KHASG4H3.mjs} +2 -2
  42. package/dist/{chunk-G4NU4KP7.js → chunk-KIVBL6OM.js} +6 -6
  43. package/dist/{chunk-FQ5SDMRE.mjs → chunk-KTCSRECK.mjs} +2 -3
  44. package/dist/{chunk-FQ5SDMRE.mjs.map → chunk-KTCSRECK.mjs.map} +1 -1
  45. package/dist/{chunk-7SW3CC66.mjs → chunk-LGXQBALM.mjs} +2 -2
  46. package/dist/{chunk-5C53GKTU.js.map → chunk-LGXQBALM.mjs.map} +1 -1
  47. package/dist/{chunk-BOET676P.js → chunk-LLG4D2SC.js} +8 -8
  48. package/dist/{chunk-NPH5AHLH.mjs → chunk-MK7ABX2V.mjs} +54 -6
  49. package/dist/chunk-MK7ABX2V.mjs.map +1 -0
  50. package/dist/{chunk-AK7OTIWA.js → chunk-NIUQ34PY.js} +3 -3
  51. package/dist/{chunk-MNVUKRZC.js → chunk-PRYLTXW4.js} +15 -9
  52. package/dist/chunk-PRYLTXW4.js.map +1 -0
  53. package/dist/{chunk-XSSIP3PJ.js → chunk-Q5KTSMRE.js} +8 -8
  54. package/dist/{chunk-QE5X2BT3.mjs → chunk-SZ6WMC6C.mjs} +242 -13
  55. package/dist/chunk-SZ6WMC6C.mjs.map +1 -0
  56. package/dist/{chunk-PSR2V3R4.js → chunk-T2YURW25.js} +17 -19
  57. package/dist/chunk-T2YURW25.js.map +1 -0
  58. package/dist/{chunk-CJLDMVV3.mjs → chunk-UHP2Y32K.mjs} +9 -3
  59. package/dist/chunk-UHP2Y32K.mjs.map +1 -0
  60. package/dist/chunk-UHX7HJAI.js +11 -0
  61. package/dist/chunk-UHX7HJAI.js.map +1 -0
  62. package/dist/{chunk-FUPEFLXB.js → chunk-UIRAMHNM.js} +60 -12
  63. package/dist/chunk-UIRAMHNM.js.map +1 -0
  64. package/dist/{chunk-VYZPOR47.mjs → chunk-YKOMKXG4.mjs} +4 -4
  65. package/dist/{chunk-WB6MUIML.mjs → chunk-YLURF2PF.mjs} +2 -2
  66. package/dist/chunk-ZUPTMFEA.mjs +28 -0
  67. package/dist/chunk-ZUPTMFEA.mjs.map +1 -0
  68. package/dist/{chunk-5C53GKTU.js → chunk-ZX2KHPXG.js} +5 -5
  69. package/dist/chunk-ZX2KHPXG.js.map +1 -0
  70. package/dist/controllers/authentication/AuthenticationController.js +4 -21
  71. package/dist/controllers/authentication/AuthenticationController.mjs +3 -20
  72. package/dist/controllers/authentication/index.js +7 -22
  73. package/dist/controllers/authentication/index.mjs +6 -21
  74. package/dist/controllers/authentication/services.js +3 -20
  75. package/dist/controllers/authentication/services.mjs +2 -19
  76. package/dist/controllers/index.js +13 -23
  77. package/dist/controllers/index.mjs +12 -22
  78. package/dist/controllers/user-storage/UserStorageController.js +9 -19
  79. package/dist/controllers/user-storage/UserStorageController.mjs +8 -18
  80. package/dist/controllers/user-storage/accounts/constants.js +12 -0
  81. package/dist/controllers/user-storage/accounts/constants.js.map +1 -0
  82. package/dist/controllers/user-storage/accounts/constants.mjs +12 -0
  83. package/dist/controllers/user-storage/accounts/constants.mjs.map +1 -0
  84. package/dist/controllers/user-storage/accounts/user-storage.js +11 -0
  85. package/dist/controllers/user-storage/accounts/user-storage.js.map +1 -0
  86. package/dist/controllers/user-storage/accounts/user-storage.mjs +11 -0
  87. package/dist/controllers/user-storage/accounts/user-storage.mjs.map +1 -0
  88. package/dist/controllers/user-storage/encryption/encryption.js +2 -2
  89. package/dist/controllers/user-storage/encryption/encryption.mjs +1 -1
  90. package/dist/controllers/user-storage/encryption/index.js +3 -3
  91. package/dist/controllers/user-storage/encryption/index.mjs +2 -2
  92. package/dist/controllers/user-storage/index.js +15 -23
  93. package/dist/controllers/user-storage/index.mjs +12 -20
  94. package/dist/controllers/user-storage/schema.js +6 -4
  95. package/dist/controllers/user-storage/schema.mjs +7 -5
  96. package/dist/controllers/user-storage/services.js +8 -18
  97. package/dist/controllers/user-storage/services.mjs +7 -17
  98. package/dist/index.js +20 -18
  99. package/dist/index.mjs +19 -17
  100. package/dist/sdk/authentication-jwt-bearer/flow-siwe.js +4 -4
  101. package/dist/sdk/authentication-jwt-bearer/flow-siwe.mjs +3 -3
  102. package/dist/sdk/authentication-jwt-bearer/flow-srp.js +4 -4
  103. package/dist/sdk/authentication-jwt-bearer/flow-srp.mjs +3 -3
  104. package/dist/sdk/authentication-jwt-bearer/services.js +3 -3
  105. package/dist/sdk/authentication-jwt-bearer/services.mjs +2 -2
  106. package/dist/sdk/authentication.js +6 -6
  107. package/dist/sdk/authentication.mjs +5 -5
  108. package/dist/sdk/encryption.js +5 -3
  109. package/dist/sdk/encryption.mjs +6 -4
  110. package/dist/sdk/env.js +2 -2
  111. package/dist/sdk/env.mjs +1 -1
  112. package/dist/sdk/index.js +14 -16
  113. package/dist/sdk/index.mjs +13 -15
  114. package/dist/sdk/user-storage.js +7 -7
  115. package/dist/sdk/user-storage.mjs +6 -6
  116. package/dist/tsconfig.build.tsbuildinfo +1 -1
  117. package/dist/types/controllers/authentication/AuthenticationController.d.ts +6 -3
  118. package/dist/types/controllers/authentication/AuthenticationController.d.ts.map +1 -1
  119. package/dist/types/controllers/authentication/__fixtures__/mockResponses.d.ts +1 -1
  120. package/dist/types/controllers/authentication/__fixtures__/mockResponses.d.ts.map +1 -1
  121. package/dist/types/controllers/authentication/index.d.ts +2 -0
  122. package/dist/types/controllers/authentication/index.d.ts.map +1 -1
  123. package/dist/types/controllers/user-storage/UserStorageController.d.ts +52 -11
  124. package/dist/types/controllers/user-storage/UserStorageController.d.ts.map +1 -1
  125. package/dist/types/controllers/user-storage/__fixtures__/mockAccounts.d.ts +63 -0
  126. package/dist/types/controllers/user-storage/__fixtures__/mockAccounts.d.ts.map +1 -0
  127. package/dist/types/controllers/user-storage/__fixtures__/mockResponses.d.ts +11 -5
  128. package/dist/types/controllers/user-storage/__fixtures__/mockResponses.d.ts.map +1 -1
  129. package/dist/types/controllers/user-storage/__fixtures__/mockServices.d.ts +4 -2
  130. package/dist/types/controllers/user-storage/__fixtures__/mockServices.d.ts.map +1 -1
  131. package/dist/types/controllers/user-storage/__fixtures__/mockStorage.d.ts +1 -1
  132. package/dist/types/controllers/user-storage/__fixtures__/mockStorage.d.ts.map +1 -1
  133. package/dist/types/controllers/user-storage/accounts/constants.d.ts +4 -0
  134. package/dist/types/controllers/user-storage/accounts/constants.d.ts.map +1 -0
  135. package/dist/types/controllers/user-storage/accounts/user-storage.d.ts +32 -0
  136. package/dist/types/controllers/user-storage/accounts/user-storage.d.ts.map +1 -0
  137. package/dist/types/controllers/user-storage/encryption/encryption.d.ts +3 -2
  138. package/dist/types/controllers/user-storage/encryption/encryption.d.ts.map +1 -1
  139. package/dist/types/controllers/user-storage/index.d.ts +2 -0
  140. package/dist/types/controllers/user-storage/index.d.ts.map +1 -1
  141. package/dist/types/controllers/user-storage/schema.d.ts +13 -6
  142. package/dist/types/controllers/user-storage/schema.d.ts.map +1 -1
  143. package/dist/types/controllers/user-storage/services.d.ts +23 -4
  144. package/dist/types/controllers/user-storage/services.d.ts.map +1 -1
  145. package/dist/types/sdk/__fixtures__/mock-userstorage.d.ts +5 -4
  146. package/dist/types/sdk/__fixtures__/mock-userstorage.d.ts.map +1 -1
  147. package/dist/types/sdk/encryption.d.ts +3 -19
  148. package/dist/types/sdk/encryption.d.ts.map +1 -1
  149. package/dist/types/sdk/user-storage.d.ts +4 -3
  150. package/dist/types/sdk/user-storage.d.ts.map +1 -1
  151. package/package.json +37 -6
  152. package/user-storage/mocks/package.json +9 -0
  153. package/user-storage/package.json +9 -0
  154. package/dist/chunk-3TE6M5TV.js +0 -72
  155. package/dist/chunk-3TE6M5TV.js.map +0 -1
  156. package/dist/chunk-4DQF2YNS.js +0 -78
  157. package/dist/chunk-4DQF2YNS.js.map +0 -1
  158. package/dist/chunk-7SW3CC66.mjs.map +0 -1
  159. package/dist/chunk-B5DBQDB3.mjs +0 -140
  160. package/dist/chunk-B5DBQDB3.mjs.map +0 -1
  161. package/dist/chunk-CJLDMVV3.mjs.map +0 -1
  162. package/dist/chunk-FU7PSGFP.mjs.map +0 -1
  163. package/dist/chunk-FUPEFLXB.js.map +0 -1
  164. package/dist/chunk-ILIZJQ6X.mjs.map +0 -1
  165. package/dist/chunk-JENTMRXO.js.map +0 -1
  166. package/dist/chunk-K5UKU454.mjs.map +0 -1
  167. package/dist/chunk-KW3X4TT5.js.map +0 -1
  168. package/dist/chunk-MNVUKRZC.js.map +0 -1
  169. package/dist/chunk-NPH5AHLH.mjs.map +0 -1
  170. package/dist/chunk-P4DUDLMY.js +0 -140
  171. package/dist/chunk-P4DUDLMY.js.map +0 -1
  172. package/dist/chunk-PSR2V3R4.js.map +0 -1
  173. package/dist/chunk-QE5X2BT3.mjs.map +0 -1
  174. package/dist/chunk-SLHAVOTE.js.map +0 -1
  175. package/dist/chunk-SMKTWM6I.js.map +0 -1
  176. package/dist/chunk-T3FNDVE3.js.map +0 -1
  177. package/dist/chunk-WWQ65CZY.mjs.map +0 -1
  178. package/dist/chunk-XMYWJQNH.mjs +0 -78
  179. package/dist/chunk-XMYWJQNH.mjs.map +0 -1
  180. /package/dist/{chunk-BDO3VJEU.mjs.map → chunk-2CWF7ZTL.mjs.map} +0 -0
  181. /package/dist/{chunk-VD2IGTS3.js.map → chunk-4ZGRRVMI.js.map} +0 -0
  182. /package/dist/{chunk-DRD22DR5.mjs.map → chunk-J7NSK6BO.mjs.map} +0 -0
  183. /package/dist/{chunk-5TOWF6UW.mjs.map → chunk-KHASG4H3.mjs.map} +0 -0
  184. /package/dist/{chunk-G4NU4KP7.js.map → chunk-KIVBL6OM.js.map} +0 -0
  185. /package/dist/{chunk-BOET676P.js.map → chunk-LLG4D2SC.js.map} +0 -0
  186. /package/dist/{chunk-AK7OTIWA.js.map → chunk-NIUQ34PY.js.map} +0 -0
  187. /package/dist/{chunk-XSSIP3PJ.js.map → chunk-Q5KTSMRE.js.map} +0 -0
  188. /package/dist/{chunk-VYZPOR47.mjs.map → chunk-YKOMKXG4.mjs.map} +0 -0
  189. /package/dist/{chunk-WB6MUIML.mjs.map → chunk-YLURF2PF.mjs.map} +0 -0
@@ -1,13 +1,18 @@
1
+ import {
2
+ isNameDefaultAccountName,
3
+ mapInternalAccountToUserStorageAccount
4
+ } from "./chunk-ZUPTMFEA.mjs";
1
5
  import {
2
6
  createSnapSignMessageRequest
3
7
  } from "./chunk-NMIF3LSX.mjs";
4
8
  import {
5
9
  getUserStorage,
10
+ getUserStorageAllFeatureEntries,
6
11
  upsertUserStorage
7
- } from "./chunk-FU7PSGFP.mjs";
12
+ } from "./chunk-76NMME23.mjs";
8
13
  import {
9
14
  createSHA256Hash
10
- } from "./chunk-K5UKU454.mjs";
15
+ } from "./chunk-COBJUBZE.mjs";
11
16
  import {
12
17
  __privateAdd,
13
18
  __privateGet,
@@ -32,14 +37,20 @@ var metadata = {
32
37
  anonymous: false
33
38
  }
34
39
  };
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;
40
+ var _auth, _accounts, _notificationServices, _isUnlocked, _keyringController, _nativeScryptCrypto, _registerMessageHandlers, registerMessageHandlers_fn, _assertProfileSyncingEnabled, assertProfileSyncingEnabled_fn, _getStorageKeyAndBearerToken, getStorageKeyAndBearerToken_fn, _createStorageKey, createStorageKey_fn, __snapSignMessageCache, _snapSignMessage, snapSignMessage_fn, _setIsProfileSyncingUpdateLoading, setIsProfileSyncingUpdateLoading_fn;
36
41
  var UserStorageController = class extends BaseController {
37
- constructor(params) {
42
+ constructor({
43
+ messenger,
44
+ state,
45
+ env,
46
+ getMetaMetricsState,
47
+ nativeScryptCrypto
48
+ }) {
38
49
  super({
39
- messenger: params.messenger,
50
+ messenger,
40
51
  metadata,
41
52
  name: controllerName,
42
- state: { ...defaultState, ...params.state }
53
+ state: { ...defaultState, ...state }
43
54
  });
44
55
  /**
45
56
  * Constructor helper for registering this controller's messaging system
@@ -91,6 +102,60 @@ var UserStorageController = class extends BaseController {
91
102
  );
92
103
  }
93
104
  });
105
+ __privateAdd(this, _accounts, {
106
+ // This is replaced with the actual value in the constructor
107
+ // We will remove this once the feature will be released
108
+ isAccountSyncingEnabled: false,
109
+ // This is replaced with the actual value in the constructor
110
+ maxSyncInterval: 1e3 * 60,
111
+ lastSyncedAt: 0,
112
+ shouldSync: () => {
113
+ return Date.now() - __privateGet(this, _accounts).lastSyncedAt > __privateGet(this, _accounts).maxSyncInterval;
114
+ },
115
+ getInternalAccountByAddress: async (address) => {
116
+ return this.messagingSystem.call(
117
+ "AccountsController:getAccountByAddress",
118
+ address
119
+ );
120
+ },
121
+ getInternalAccountsList: async () => {
122
+ return this.messagingSystem.call("AccountsController:listAccounts");
123
+ },
124
+ getUserStorageAccountsList: async () => {
125
+ const rawAccountsListResponse = await this.performGetStorageAllFeatureEntries("accounts");
126
+ return rawAccountsListResponse?.map((rawAccount) => JSON.parse(rawAccount)) ?? null;
127
+ },
128
+ saveInternalAccountToUserStorage: async (address) => {
129
+ const internalAccount = await __privateGet(this, _accounts).getInternalAccountByAddress(
130
+ address
131
+ );
132
+ if (!internalAccount) {
133
+ return;
134
+ }
135
+ const mappedAccount = mapInternalAccountToUserStorageAccount(internalAccount);
136
+ await this.performSetStorage(
137
+ `accounts.${address}`,
138
+ JSON.stringify(mappedAccount)
139
+ );
140
+ },
141
+ saveInternalAccountsListToUserStorage: async () => {
142
+ const internalAccountsList = await __privateGet(this, _accounts).getInternalAccountsList();
143
+ if (!internalAccountsList) {
144
+ return;
145
+ }
146
+ const userStorageAccountsList = internalAccountsList.map(
147
+ mapInternalAccountToUserStorageAccount
148
+ );
149
+ await Promise.all(
150
+ userStorageAccountsList.map(async (userStorageAccount) => {
151
+ await this.performSetStorage(
152
+ `accounts.${userStorageAccount.a}`,
153
+ JSON.stringify(userStorageAccount)
154
+ );
155
+ })
156
+ );
157
+ }
158
+ });
94
159
  __privateAdd(this, _notificationServices, {
95
160
  disableNotificationServices: async () => {
96
161
  return await this.messagingSystem.call(
@@ -110,18 +175,29 @@ var UserStorageController = class extends BaseController {
110
175
  "KeyringController:getState"
111
176
  );
112
177
  __privateSet(this, _isUnlocked, isUnlocked);
113
- this.messagingSystem.subscribe("KeyringController:unlock", () => {
114
- __privateSet(this, _isUnlocked, true);
115
- });
178
+ this.messagingSystem.subscribe(
179
+ "KeyringController:unlock",
180
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
181
+ async () => {
182
+ __privateSet(this, _isUnlocked, true);
183
+ await this.syncInternalAccountsWithUserStorage();
184
+ }
185
+ );
116
186
  this.messagingSystem.subscribe("KeyringController:lock", () => {
117
187
  __privateSet(this, _isUnlocked, false);
118
188
  });
119
189
  }
120
190
  });
191
+ __privateAdd(this, _nativeScryptCrypto, void 0);
121
192
  __privateAdd(this, __snapSignMessageCache, {});
122
- this.getMetaMetricsState = params.getMetaMetricsState;
193
+ __privateGet(this, _accounts).isAccountSyncingEnabled = Boolean(
194
+ env?.isAccountSyncingEnabled
195
+ );
196
+ __privateGet(this, _accounts).maxSyncInterval = env?.accountSyncingMaxSyncInterval ?? __privateGet(this, _accounts).maxSyncInterval;
197
+ this.getMetaMetricsState = getMetaMetricsState;
123
198
  __privateGet(this, _keyringController).setupLockedStateSubscriptions();
124
199
  __privateMethod(this, _registerMessageHandlers, registerMessageHandlers_fn).call(this);
200
+ __privateSet(this, _nativeScryptCrypto, nativeScryptCrypto);
125
201
  }
126
202
  async enableProfileSyncing() {
127
203
  try {
@@ -187,7 +263,26 @@ var UserStorageController = class extends BaseController {
187
263
  const result = await getUserStorage({
188
264
  path,
189
265
  bearerToken,
190
- storageKey
266
+ storageKey,
267
+ nativeScryptCrypto: __privateGet(this, _nativeScryptCrypto)
268
+ });
269
+ return result;
270
+ }
271
+ /**
272
+ * Allows retrieval of all stored data for a specific feature. Data stored is formatted as an array of strings.
273
+ * Developers can extend the entry path through the `schema.ts` file.
274
+ *
275
+ * @param path - string in the form of `${feature}` that matches schema
276
+ * @returns the array of decrypted string contents found from user storage (or null if not found)
277
+ */
278
+ async performGetStorageAllFeatureEntries(path) {
279
+ __privateMethod(this, _assertProfileSyncingEnabled, assertProfileSyncingEnabled_fn).call(this);
280
+ const { bearerToken, storageKey } = await __privateMethod(this, _getStorageKeyAndBearerToken, getStorageKeyAndBearerToken_fn).call(this);
281
+ const result = await getUserStorageAllFeatureEntries({
282
+ path,
283
+ bearerToken,
284
+ storageKey,
285
+ nativeScryptCrypto: __privateGet(this, _nativeScryptCrypto)
191
286
  });
192
287
  return result;
193
288
  }
@@ -205,7 +300,8 @@ var UserStorageController = class extends BaseController {
205
300
  await upsertUserStorage(value, {
206
301
  path,
207
302
  bearerToken,
208
- storageKey
303
+ storageKey,
304
+ nativeScryptCrypto: __privateGet(this, _nativeScryptCrypto)
209
305
  });
210
306
  }
211
307
  /**
@@ -218,17 +314,142 @@ var UserStorageController = class extends BaseController {
218
314
  const storageKey = await __privateMethod(this, _createStorageKey, createStorageKey_fn).call(this);
219
315
  return storageKey;
220
316
  }
317
+ /**
318
+ * Syncs the internal accounts list with the user storage accounts list.
319
+ * This method is used to make sure that the internal accounts list is up-to-date with the user storage accounts list and vice-versa.
320
+ * It will add new accounts to the internal accounts list, update/merge conflicting names and re-upload the results in some cases to the user storage.
321
+ */
322
+ async syncInternalAccountsWithUserStorage() {
323
+ if (!__privateGet(this, _accounts).isAccountSyncingEnabled) {
324
+ return;
325
+ }
326
+ if (!__privateGet(this, _accounts).shouldSync()) {
327
+ return;
328
+ }
329
+ __privateGet(this, _accounts).lastSyncedAt = Date.now();
330
+ try {
331
+ __privateMethod(this, _assertProfileSyncingEnabled, assertProfileSyncingEnabled_fn).call(this);
332
+ const userStorageAccountsList = await __privateGet(this, _accounts).getUserStorageAccountsList();
333
+ if (!userStorageAccountsList || !userStorageAccountsList.length) {
334
+ await __privateGet(this, _accounts).saveInternalAccountsListToUserStorage();
335
+ return;
336
+ }
337
+ let internalAccountsList = await __privateGet(this, _accounts).getInternalAccountsList();
338
+ if (!internalAccountsList || !internalAccountsList.length) {
339
+ throw new Error(`Failed to get internal accounts list`);
340
+ }
341
+ const hasMoreInternalAccountsThanUserStorageAccounts = internalAccountsList.length > userStorageAccountsList.length;
342
+ if (!hasMoreInternalAccountsThanUserStorageAccounts) {
343
+ const numberOfAccountsToAdd = userStorageAccountsList.length - internalAccountsList.length;
344
+ const addNewAccountsPromises = Array.from({
345
+ length: numberOfAccountsToAdd
346
+ }).map(async () => {
347
+ await this.messagingSystem.call("KeyringController:addNewAccount");
348
+ });
349
+ await Promise.all(addNewAccountsPromises);
350
+ }
351
+ internalAccountsList = await __privateGet(this, _accounts).getInternalAccountsList();
352
+ for await (const internalAccount of internalAccountsList) {
353
+ const userStorageAccount = userStorageAccountsList.find(
354
+ (account) => account.a === internalAccount.address
355
+ );
356
+ if (!userStorageAccount) {
357
+ await __privateGet(this, _accounts).saveInternalAccountToUserStorage(
358
+ internalAccount.address
359
+ );
360
+ continue;
361
+ }
362
+ const isInternalAccountNameDefault = isNameDefaultAccountName(
363
+ internalAccount.metadata.name
364
+ );
365
+ const isUserStorageAccountNameDefault = isNameDefaultAccountName(
366
+ userStorageAccount.n
367
+ );
368
+ if (isInternalAccountNameDefault) {
369
+ if (!isUserStorageAccountNameDefault) {
370
+ this.messagingSystem.call(
371
+ "AccountsController:updateAccountMetadata",
372
+ internalAccount.id,
373
+ {
374
+ name: userStorageAccount.n
375
+ }
376
+ );
377
+ }
378
+ continue;
379
+ }
380
+ if (isUserStorageAccountNameDefault) {
381
+ await __privateGet(this, _accounts).saveInternalAccountToUserStorage(
382
+ internalAccount.address
383
+ );
384
+ continue;
385
+ }
386
+ if (userStorageAccount.nlu !== void 0) {
387
+ if (internalAccount.metadata.nameLastUpdatedAt !== void 0) {
388
+ const isInternalAccountNameNewer = internalAccount.metadata.nameLastUpdatedAt > userStorageAccount.nlu;
389
+ if (isInternalAccountNameNewer) {
390
+ await __privateGet(this, _accounts).saveInternalAccountToUserStorage(
391
+ internalAccount.address
392
+ );
393
+ continue;
394
+ }
395
+ }
396
+ this.messagingSystem.call(
397
+ "AccountsController:updateAccountMetadata",
398
+ internalAccount.id,
399
+ {
400
+ name: userStorageAccount.n,
401
+ nameLastUpdatedAt: userStorageAccount.nlu
402
+ }
403
+ );
404
+ continue;
405
+ } else if (internalAccount.metadata.nameLastUpdatedAt !== void 0) {
406
+ await __privateGet(this, _accounts).saveInternalAccountToUserStorage(
407
+ internalAccount.address
408
+ );
409
+ continue;
410
+ }
411
+ }
412
+ } catch (e) {
413
+ const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);
414
+ throw new Error(
415
+ `${controllerName} - failed to sync user storage accounts list - ${errorMessage}`
416
+ );
417
+ }
418
+ }
419
+ /**
420
+ * Saves an individual internal account to the user storage.
421
+ * @param address - The address of the internal account to save
422
+ */
423
+ async saveInternalAccountToUserStorage(address) {
424
+ if (!__privateGet(this, _accounts).isAccountSyncingEnabled) {
425
+ return;
426
+ }
427
+ try {
428
+ await __privateGet(this, _accounts).saveInternalAccountToUserStorage(address);
429
+ } catch (e) {
430
+ const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);
431
+ throw new Error(
432
+ `${controllerName} - failed to save account to user storage - ${errorMessage}`
433
+ );
434
+ }
435
+ }
221
436
  };
222
437
  _auth = new WeakMap();
438
+ _accounts = new WeakMap();
223
439
  _notificationServices = new WeakMap();
224
440
  _isUnlocked = new WeakMap();
225
441
  _keyringController = new WeakMap();
442
+ _nativeScryptCrypto = new WeakMap();
226
443
  _registerMessageHandlers = new WeakSet();
227
444
  registerMessageHandlers_fn = function() {
228
445
  this.messagingSystem.registerActionHandler(
229
446
  "UserStorageController:performGetStorage",
230
447
  this.performGetStorage.bind(this)
231
448
  );
449
+ this.messagingSystem.registerActionHandler(
450
+ "UserStorageController:performGetStorageAllFeatureEntries",
451
+ this.performGetStorageAllFeatureEntries.bind(this)
452
+ );
232
453
  this.messagingSystem.registerActionHandler(
233
454
  "UserStorageController:performSetStorage",
234
455
  this.performSetStorage.bind(this)
@@ -245,6 +466,14 @@ registerMessageHandlers_fn = function() {
245
466
  "UserStorageController:disableProfileSyncing",
246
467
  this.disableProfileSyncing.bind(this)
247
468
  );
469
+ this.messagingSystem.registerActionHandler(
470
+ "UserStorageController:syncInternalAccountsWithUserStorage",
471
+ this.syncInternalAccountsWithUserStorage.bind(this)
472
+ );
473
+ this.messagingSystem.registerActionHandler(
474
+ "UserStorageController:saveInternalAccountToUserStorage",
475
+ this.saveInternalAccountToUserStorage.bind(this)
476
+ );
248
477
  };
249
478
  _assertProfileSyncingEnabled = new WeakSet();
250
479
  assertProfileSyncingEnabled_fn = function() {
@@ -302,4 +531,4 @@ export {
302
531
  defaultState,
303
532
  UserStorageController
304
533
  };
305
- //# sourceMappingURL=chunk-QE5X2BT3.mjs.map
534
+ //# sourceMappingURL=chunk-SZ6WMC6C.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/controllers/user-storage/UserStorageController.ts"],"sourcesContent":["import type {\n AccountsControllerListAccountsAction,\n AccountsControllerUpdateAccountMetadataAction,\n AccountsControllerGetAccountByAddressAction,\n} from '@metamask/accounts-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedControllerMessenger,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { InternalAccount } from '@metamask/keyring-api';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n KeyringControllerAddNewAccountAction,\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 type { UserStorageAccount } from './accounts/user-storage';\nimport {\n isNameDefaultAccountName,\n mapInternalAccountToUserStorageAccount,\n} from './accounts/user-storage';\nimport { createSHA256Hash } from './encryption';\nimport type {\n UserStoragePathWithFeatureAndKey,\n UserStoragePathWithFeatureOnly,\n} from './schema';\nimport {\n getUserStorage,\n getUserStorageAllFeatureEntries,\n upsertUserStorage,\n} 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\nexport declare type NativeScrypt = (\n passwd: string,\n salt: Uint8Array,\n N: number,\n r: number,\n p: number,\n size: number,\n) => Promise<Uint8Array>;\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 | 'performGetStorageAllFeatureEntries'\n | 'performSetStorage'\n | 'getStorageKey'\n | 'enableProfileSyncing'\n | 'disableProfileSyncing'\n | 'syncInternalAccountsWithUserStorage'\n | 'saveInternalAccountToUserStorage'\n>;\nexport type UserStorageControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n UserStorageControllerState\n>;\nexport type Actions =\n | ActionsObj[keyof ActionsObj]\n | UserStorageControllerGetStateAction;\nexport type UserStorageControllerPerformGetStorage =\n ActionsObj['performGetStorage'];\nexport type UserStorageControllerPerformGetStorageAllFeatureEntries =\n ActionsObj['performGetStorageAllFeatureEntries'];\nexport type UserStorageControllerPerformSetStorage =\n ActionsObj['performSetStorage'];\nexport type UserStorageControllerGetStorageKey = ActionsObj['getStorageKey'];\nexport type UserStorageControllerEnableProfileSyncing =\n ActionsObj['enableProfileSyncing'];\nexport type UserStorageControllerDisableProfileSyncing =\n ActionsObj['disableProfileSyncing'];\nexport type UserStorageControllerSyncInternalAccountsWithUserStorage =\n ActionsObj['syncInternalAccountsWithUserStorage'];\nexport type UserStorageControllerSaveInternalAccountToUserStorage =\n ActionsObj['saveInternalAccountToUserStorage'];\n\nexport type UserStorageControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n UserStorageControllerState\n>;\nexport type Events = UserStorageControllerStateChangeEvent;\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 // Account syncing\n | AccountsControllerListAccountsAction\n | AccountsControllerGetAccountByAddressAction\n | AccountsControllerUpdateAccountMetadataAction\n | KeyringControllerAddNewAccountAction;\n\n// Messenger events\nexport type UserStorageControllerChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n UserStorageControllerState\n>;\nexport type UserStorageControllerAccountSyncingInProgress = {\n type: `${typeof controllerName}:accountSyncingInProgress`;\n payload: [boolean];\n};\nexport type UserStorageControllerAccountSyncingComplete = {\n type: `${typeof controllerName}:accountSyncingComplete`;\n payload: [boolean];\n};\n\nexport type AllowedEvents =\n | UserStorageControllerChangeEvent\n | UserStorageControllerAccountSyncingInProgress\n | UserStorageControllerAccountSyncingComplete\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent;\n\n// Messenger\nexport type UserStorageControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n Actions | AllowedActions,\n Events | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Reusable controller that allows any team to store synchronized data for a given user.\n * These can be settings shared cross MetaMask clients, or data we want to persist when uninstalling/reinstalling.\n *\n * NOTE:\n * - data stored on UserStorage is FULLY encrypted, with the only keys stored/managed on the client.\n * - No one can access this data unless they are have the SRP and are able to run the signing snap.\n */\nexport default class UserStorageController extends BaseController<\n typeof controllerName,\n UserStorageControllerState,\n UserStorageControllerMessenger\n> {\n #auth = {\n getBearerToken: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:getBearerToken',\n );\n },\n getProfileId: async () => {\n const sessionProfile = await this.messagingSystem.call(\n 'AuthenticationController:getSessionProfile',\n );\n return sessionProfile?.profileId;\n },\n isAuthEnabled: () => {\n return this.messagingSystem.call('AuthenticationController:isSignedIn');\n },\n signIn: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:performSignIn',\n );\n },\n signOut: async () => {\n return this.messagingSystem.call(\n 'AuthenticationController:performSignOut',\n );\n },\n };\n\n #accounts = {\n // This is replaced with the actual value in the constructor\n // We will remove this once the feature will be released\n isAccountSyncingEnabled: false,\n // This is replaced with the actual value in the constructor\n maxSyncInterval: 1000 * 60,\n lastSyncedAt: 0,\n shouldSync: () => {\n return (\n Date.now() - this.#accounts.lastSyncedAt >\n this.#accounts.maxSyncInterval\n );\n },\n getInternalAccountByAddress: async (address: string) => {\n return this.messagingSystem.call(\n 'AccountsController:getAccountByAddress',\n address,\n );\n },\n getInternalAccountsList: async (): Promise<InternalAccount[]> => {\n return this.messagingSystem.call('AccountsController:listAccounts');\n },\n getUserStorageAccountsList: async (): Promise<\n UserStorageAccount[] | null\n > => {\n const rawAccountsListResponse =\n await this.performGetStorageAllFeatureEntries('accounts');\n\n return (\n rawAccountsListResponse?.map((rawAccount) => JSON.parse(rawAccount)) ??\n null\n );\n },\n saveInternalAccountToUserStorage: async (address: string) => {\n const internalAccount = await this.#accounts.getInternalAccountByAddress(\n address,\n );\n\n if (!internalAccount) {\n return;\n }\n\n // Map the internal account to the user storage account schema\n const mappedAccount =\n mapInternalAccountToUserStorageAccount(internalAccount);\n\n await this.performSetStorage(\n `accounts.${address}`,\n JSON.stringify(mappedAccount),\n );\n },\n saveInternalAccountsListToUserStorage: async () => {\n const internalAccountsList =\n await this.#accounts.getInternalAccountsList();\n\n if (!internalAccountsList) {\n return;\n }\n\n const userStorageAccountsList = internalAccountsList.map(\n mapInternalAccountToUserStorageAccount,\n );\n\n await Promise.all(\n userStorageAccountsList.map(async (userStorageAccount) => {\n await this.performSetStorage(\n `accounts.${userStorageAccount.a}`,\n JSON.stringify(userStorageAccount),\n );\n }),\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(\n 'KeyringController:unlock',\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async () => {\n this.#isUnlocked = true;\n\n await this.syncInternalAccountsWithUserStorage();\n },\n );\n\n this.messagingSystem.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n },\n };\n\n #nativeScryptCrypto: NativeScrypt | undefined = undefined;\n\n getMetaMetricsState: () => boolean;\n\n constructor({\n messenger,\n state,\n env,\n getMetaMetricsState,\n nativeScryptCrypto,\n }: {\n messenger: UserStorageControllerMessenger;\n state?: UserStorageControllerState;\n env?: {\n isAccountSyncingEnabled?: boolean;\n accountSyncingMaxSyncInterval?: number;\n };\n getMetaMetricsState: () => boolean;\n nativeScryptCrypto?: NativeScrypt;\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n this.#accounts.isAccountSyncingEnabled = Boolean(\n env?.isAccountSyncingEnabled,\n );\n this.#accounts.maxSyncInterval =\n env?.accountSyncingMaxSyncInterval ?? this.#accounts.maxSyncInterval;\n\n this.getMetaMetricsState = getMetaMetricsState;\n this.#keyringController.setupLockedStateSubscriptions();\n this.#registerMessageHandlers();\n this.#nativeScryptCrypto = nativeScryptCrypto;\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performGetStorage',\n this.performGetStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performGetStorageAllFeatureEntries',\n this.performGetStorageAllFeatureEntries.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performSetStorage',\n this.performSetStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:getStorageKey',\n this.getStorageKey.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:enableProfileSyncing',\n this.enableProfileSyncing.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:disableProfileSyncing',\n this.disableProfileSyncing.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:syncInternalAccountsWithUserStorage',\n this.syncInternalAccountsWithUserStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:saveInternalAccountToUserStorage',\n this.saveInternalAccountToUserStorage.bind(this),\n );\n }\n\n public async enableProfileSyncing(): Promise<void> {\n try {\n this.#setIsProfileSyncingUpdateLoading(true);\n\n const authEnabled = this.#auth.isAuthEnabled();\n if (!authEnabled) {\n await this.#auth.signIn();\n }\n\n this.update((state) => {\n state.isProfileSyncingEnabled = true;\n });\n\n this.#setIsProfileSyncingUpdateLoading(false);\n } catch (e) {\n this.#setIsProfileSyncingUpdateLoading(false);\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to enable profile syncing - ${errorMessage}`,\n );\n }\n }\n\n public async setIsProfileSyncingEnabled(\n isProfileSyncingEnabled: boolean,\n ): Promise<void> {\n this.update((state) => {\n state.isProfileSyncingEnabled = isProfileSyncingEnabled;\n });\n }\n\n public async disableProfileSyncing(): Promise<void> {\n const isAlreadyDisabled = !this.state.isProfileSyncingEnabled;\n if (isAlreadyDisabled) {\n return;\n }\n\n try {\n this.#setIsProfileSyncingUpdateLoading(true);\n\n const isNotificationServicesEnabled =\n await this.#notificationServices.selectIsNotificationServicesEnabled();\n\n if (isNotificationServicesEnabled) {\n await this.#notificationServices.disableNotificationServices();\n }\n\n const isMetaMetricsParticipation = this.getMetaMetricsState();\n\n if (!isMetaMetricsParticipation) {\n await this.#auth.signOut();\n }\n\n this.#setIsProfileSyncingUpdateLoading(false);\n\n this.update((state) => {\n state.isProfileSyncingEnabled = false;\n });\n } catch (e) {\n this.#setIsProfileSyncingUpdateLoading(false);\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to disable profile syncing - ${errorMessage}`,\n );\n }\n }\n\n /**\n * Allows retrieval of stored data. Data stored is string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @returns the decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorage(\n path: UserStoragePathWithFeatureAndKey,\n ): Promise<string | null> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n const result = await getUserStorage({\n path,\n bearerToken,\n storageKey,\n nativeScryptCrypto: this.#nativeScryptCrypto,\n });\n\n return result;\n }\n\n /**\n * Allows retrieval of all stored data for a specific feature. Data stored is formatted as an array of strings.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @returns the array of decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorageAllFeatureEntries(\n path: UserStoragePathWithFeatureOnly,\n ): Promise<string[] | null> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n const result = await getUserStorageAllFeatureEntries({\n path,\n bearerToken,\n storageKey,\n nativeScryptCrypto: this.#nativeScryptCrypto,\n });\n\n return result;\n }\n\n /**\n * Allows storage of user data. Data stored must be string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param value - The string data you want to store.\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performSetStorage(\n path: UserStoragePathWithFeatureAndKey,\n value: string,\n ): Promise<void> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n await upsertUserStorage(value, {\n path,\n bearerToken,\n storageKey,\n nativeScryptCrypto: this.#nativeScryptCrypto,\n });\n }\n\n /**\n * Retrieves the storage key, for internal use only!\n *\n * @returns the storage key\n */\n public async getStorageKey(): Promise<string> {\n this.#assertProfileSyncingEnabled();\n const storageKey = await this.#createStorageKey();\n return storageKey;\n }\n\n #assertProfileSyncingEnabled(): void {\n if (!this.state.isProfileSyncingEnabled) {\n throw new Error(\n `${controllerName}: Unable to call method, user is not authenticated`,\n );\n }\n }\n\n /**\n * Utility to get the bearer token and storage key\n */\n async #getStorageKeyAndBearerToken(): Promise<{\n bearerToken: string;\n storageKey: string;\n }> {\n const bearerToken = await this.#auth.getBearerToken();\n if (!bearerToken) {\n throw new Error('UserStorageController - unable to get bearer token');\n }\n const storageKey = await this.#createStorageKey();\n\n return { bearerToken, storageKey };\n }\n\n /**\n * Rather than storing the storage key, we can compute the storage key when needed.\n *\n * @returns the storage key\n */\n async #createStorageKey(): Promise<string> {\n const id: string = await this.#auth.getProfileId();\n if (!id) {\n throw new Error('UserStorageController - unable to create storage key');\n }\n\n const storageKeySignature = await this.#snapSignMessage(`metamask:${id}`);\n const storageKey = createSHA256Hash(storageKeySignature);\n return storageKey;\n }\n\n #_snapSignMessageCache: Record<`metamask:${string}`, string> = {};\n\n /**\n * Signs a specific message using an underlying auth snap.\n *\n * @param message - A specific tagged message to sign.\n * @returns A Signature created by the snap.\n */\n async #snapSignMessage(message: `metamask:${string}`): Promise<string> {\n if (this.#_snapSignMessageCache[message]) {\n return this.#_snapSignMessageCache[message];\n }\n\n if (!this.#isUnlocked) {\n throw new Error(\n '#snapSignMessage - unable to call snap, wallet is locked',\n );\n }\n\n const result = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n createSnapSignMessageRequest(message),\n )) as string;\n\n this.#_snapSignMessageCache[message] = result;\n\n return result;\n }\n\n #setIsProfileSyncingUpdateLoading(\n isProfileSyncingUpdateLoading: boolean,\n ): void {\n this.update((state) => {\n state.isProfileSyncingUpdateLoading = isProfileSyncingUpdateLoading;\n });\n }\n\n /**\n * Syncs the internal accounts list with the user storage accounts list.\n * This method is used to make sure that the internal accounts list is up-to-date with the user storage accounts list and vice-versa.\n * It will add new accounts to the internal accounts list, update/merge conflicting names and re-upload the results in some cases to the user storage.\n */\n async syncInternalAccountsWithUserStorage(): Promise<void> {\n if (!this.#accounts.isAccountSyncingEnabled) {\n return;\n }\n\n if (!this.#accounts.shouldSync()) {\n return;\n }\n\n this.#accounts.lastSyncedAt = Date.now();\n\n try {\n this.#assertProfileSyncingEnabled();\n\n const userStorageAccountsList =\n await this.#accounts.getUserStorageAccountsList();\n\n if (!userStorageAccountsList || !userStorageAccountsList.length) {\n await this.#accounts.saveInternalAccountsListToUserStorage();\n return;\n }\n\n // Compare internal accounts list with user storage accounts list\n // First step: compare lengths\n let internalAccountsList = await this.#accounts.getInternalAccountsList();\n\n if (!internalAccountsList || !internalAccountsList.length) {\n throw new Error(`Failed to get internal accounts list`);\n }\n\n const hasMoreInternalAccountsThanUserStorageAccounts =\n internalAccountsList.length > userStorageAccountsList.length;\n\n // We don't want to remove existing accounts for a user\n // so we only add new accounts if the user has more accounts than the internal accounts list\n if (!hasMoreInternalAccountsThanUserStorageAccounts) {\n const numberOfAccountsToAdd =\n userStorageAccountsList.length - internalAccountsList.length;\n\n // Create new accounts to match the user storage accounts list\n const addNewAccountsPromises = Array.from({\n length: numberOfAccountsToAdd,\n }).map(async () => {\n await this.messagingSystem.call('KeyringController:addNewAccount');\n });\n\n await Promise.all(addNewAccountsPromises);\n }\n\n // Second step: compare account names\n // Get the internal accounts list again since new accounts might have been added in the previous step\n internalAccountsList = await this.#accounts.getInternalAccountsList();\n\n for await (const internalAccount of internalAccountsList) {\n const userStorageAccount = userStorageAccountsList.find(\n (account) => account.a === internalAccount.address,\n );\n\n if (!userStorageAccount) {\n await this.#accounts.saveInternalAccountToUserStorage(\n internalAccount.address,\n );\n continue;\n }\n\n // One or both accounts have default names\n const isInternalAccountNameDefault = isNameDefaultAccountName(\n internalAccount.metadata.name,\n );\n const isUserStorageAccountNameDefault = isNameDefaultAccountName(\n userStorageAccount.n,\n );\n\n // Internal account has default name\n if (isInternalAccountNameDefault) {\n if (!isUserStorageAccountNameDefault) {\n this.messagingSystem.call(\n 'AccountsController:updateAccountMetadata',\n internalAccount.id,\n {\n name: userStorageAccount.n,\n },\n );\n }\n continue;\n }\n\n // Internal account has custom name but user storage account has default name\n if (isUserStorageAccountNameDefault) {\n await this.#accounts.saveInternalAccountToUserStorage(\n internalAccount.address,\n );\n continue;\n }\n\n // Both accounts have custom names\n\n // User storage account has a nameLastUpdatedAt timestamp\n // Note: not storing the undefined checks in constants to act as a type guard\n if (userStorageAccount.nlu !== undefined) {\n if (internalAccount.metadata.nameLastUpdatedAt !== undefined) {\n const isInternalAccountNameNewer =\n internalAccount.metadata.nameLastUpdatedAt >\n userStorageAccount.nlu;\n\n if (isInternalAccountNameNewer) {\n await this.#accounts.saveInternalAccountToUserStorage(\n internalAccount.address,\n );\n continue;\n }\n }\n\n this.messagingSystem.call(\n 'AccountsController:updateAccountMetadata',\n internalAccount.id,\n {\n name: userStorageAccount.n,\n nameLastUpdatedAt: userStorageAccount.nlu,\n },\n );\n\n continue;\n } else if (internalAccount.metadata.nameLastUpdatedAt !== undefined) {\n await this.#accounts.saveInternalAccountToUserStorage(\n internalAccount.address,\n );\n continue;\n }\n }\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to sync user storage accounts list - ${errorMessage}`,\n );\n }\n }\n\n /**\n * Saves an individual internal account to the user storage.\n * @param address - The address of the internal account to save\n */\n async saveInternalAccountToUserStorage(address: string): Promise<void> {\n if (!this.#accounts.isAccountSyncingEnabled) {\n return;\n }\n\n try {\n await this.#accounts.saveInternalAccountToUserStorage(address);\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to save account to user storage - ${errorMessage}`,\n );\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAWA,SAAS,sBAAsB;AAwD/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;AA/FA;AA0MA,IAAqB,wBAArB,cAAmD,eAIjD;AAAA,EAgJA,YAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,GASG;AACD,UAAM;AAAA,MACJ;AAAA,MACA;AAAA,MACA,MAAM;AAAA,MACN,OAAO,EAAE,GAAG,cAAc,GAAG,MAAM;AAAA,IACrC,CAAC;AAkBH;AAAA;AAAA;AAAA;AAAA;AAmMA;AAWA;AAAA;AAAA;AAAA,uBAAM;AAkBN;AAAA;AAAA;AAAA;AAAA;AAAA,uBAAM;AAmBN;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,uBAAM;AAqBN;AA9bA,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,g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AuB,OAAO,IAAI;AAEvC,SAAO;AACT;AAEA;AAAA,sCAAiC,SAC/B,+BACM;AACN,OAAK,OAAO,CAAC,UAAU;AACrB,UAAM,gCAAgC;AAAA,EACxC,CAAC;AACH;","names":[]}
@@ -1,12 +1,12 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
2
 
3
- var _chunkXSSIP3PJjs = require('./chunk-XSSIP3PJ.js');
3
+ var _chunkQ5KTSMREjs = require('./chunk-Q5KTSMRE.js');
4
4
 
5
5
 
6
- var _chunkG4NU4KP7js = require('./chunk-G4NU4KP7.js');
6
+ var _chunkKIVBL6OMjs = require('./chunk-KIVBL6OM.js');
7
7
 
8
8
 
9
- var _chunkVD2IGTS3js = require('./chunk-VD2IGTS3.js');
9
+ var _chunk4ZGRRVMIjs = require('./chunk-4ZGRRVMI.js');
10
10
 
11
11
 
12
12
  var _chunkPBRUOBEQjs = require('./chunk-PBRUOBEQ.js');
@@ -20,17 +20,16 @@ var _chunkPQ5T4GHYjs = require('./chunk-PQ5T4GHY.js');
20
20
 
21
21
 
22
22
 
23
- var _chunkFUPEFLXBjs = require('./chunk-FUPEFLXB.js');
23
+ var _chunkUIRAMHNMjs = require('./chunk-UIRAMHNM.js');
24
24
 
25
25
 
26
+ var _chunkBKQE7DB5js = require('./chunk-BKQE7DB5.js');
26
27
 
27
- var _chunkP4DUDLMYjs = require('./chunk-P4DUDLMY.js');
28
28
 
29
29
 
30
30
 
31
31
 
32
-
33
- var _chunkSMKTWM6Ijs = require('./chunk-SMKTWM6I.js');
32
+ var _chunkDF24ZX4Hjs = require('./chunk-DF24ZX4H.js');
34
33
 
35
34
 
36
35
 
@@ -48,27 +47,26 @@ var _chunkIGY2S5BCjs = require('./chunk-IGY2S5BC.js');
48
47
  var sdk_exports = {};
49
48
  _chunkIGY2S5BCjs.__export.call(void 0, sdk_exports, {
50
49
  AuthType: () => _chunkPBRUOBEQjs.AuthType,
51
- Encryption: () => _chunkP4DUDLMYjs.Encryption,
52
- Env: () => _chunkSMKTWM6Ijs.Env,
53
- JwtBearerAuth: () => _chunkXSSIP3PJjs.JwtBearerAuth,
50
+ Env: () => _chunkDF24ZX4Hjs.Env,
51
+ JwtBearerAuth: () => _chunkQ5KTSMREjs.JwtBearerAuth,
54
52
  MESSAGE_SIGNING_SNAP: () => _chunkPQ5T4GHYjs.MESSAGE_SIGNING_SNAP,
55
53
  NonceRetrievalError: () => _chunkMBTBE4P5js.NonceRetrievalError,
56
54
  NotFoundError: () => _chunkMBTBE4P5js.NotFoundError,
57
55
  PairError: () => _chunkMBTBE4P5js.PairError,
58
- Platform: () => _chunkSMKTWM6Ijs.Platform,
59
- SIWEJwtBearerAuth: () => _chunkG4NU4KP7js.SIWEJwtBearerAuth,
56
+ Platform: () => _chunkDF24ZX4Hjs.Platform,
57
+ SIWEJwtBearerAuth: () => _chunkKIVBL6OMjs.SIWEJwtBearerAuth,
60
58
  SNAP_ORIGIN: () => _chunkPQ5T4GHYjs.SNAP_ORIGIN,
61
- SRPJwtBearerAuth: () => _chunkVD2IGTS3js.SRPJwtBearerAuth,
62
- STORAGE_URL: () => _chunkFUPEFLXBjs.STORAGE_URL,
59
+ SRPJwtBearerAuth: () => _chunk4ZGRRVMIjs.SRPJwtBearerAuth,
60
+ STORAGE_URL: () => _chunkUIRAMHNMjs.STORAGE_URL,
63
61
  SignInError: () => _chunkMBTBE4P5js.SignInError,
64
62
  UnsupportedAuthTypeError: () => _chunkMBTBE4P5js.UnsupportedAuthTypeError,
65
- UserStorage: () => _chunkFUPEFLXBjs.UserStorage,
63
+ UserStorage: () => _chunkUIRAMHNMjs.UserStorage,
66
64
  UserStorageError: () => _chunkMBTBE4P5js.UserStorageError,
67
65
  ValidationError: () => _chunkMBTBE4P5js.ValidationError,
68
66
  connectSnap: () => _chunkPQ5T4GHYjs.connectSnap,
69
- createSHA256Hash: () => _chunkP4DUDLMYjs.createSHA256Hash,
70
- getEnvUrls: () => _chunkSMKTWM6Ijs.getEnvUrls,
71
- getOidcClientId: () => _chunkSMKTWM6Ijs.getOidcClientId,
67
+ createSHA256Hash: () => _chunkBKQE7DB5js.createSHA256Hash,
68
+ getEnvUrls: () => _chunkDF24ZX4Hjs.getEnvUrls,
69
+ getOidcClientId: () => _chunkDF24ZX4Hjs.getOidcClientId,
72
70
  getSnap: () => _chunkPQ5T4GHYjs.getSnap,
73
71
  getSnaps: () => _chunkPQ5T4GHYjs.getSnaps
74
72
  });
@@ -76,4 +74,4 @@ _chunkIGY2S5BCjs.__export.call(void 0, sdk_exports, {
76
74
 
77
75
 
78
76
  exports.sdk_exports = sdk_exports;
79
- //# sourceMappingURL=chunk-PSR2V3R4.js.map
77
+ //# sourceMappingURL=chunk-T2YURW25.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sdk/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA","sourcesContent":["export * from './authentication';\nexport * from './user-storage';\nexport * from './env';\nexport * from './errors';\nexport * from './encryption';\nexport * from './utils/messaging-signing-snap-requests';\n"]}
@@ -1,12 +1,12 @@
1
1
  import {
2
2
  AuthenticationController,
3
3
  defaultState
4
- } from "./chunk-WWQ65CZY.mjs";
4
+ } from "./chunk-D4SNJOID.mjs";
5
5
  import {
6
6
  AUTH_LOGIN_ENDPOINT,
7
7
  AUTH_NONCE_ENDPOINT,
8
8
  OIDC_TOKENS_ENDPOINT
9
- } from "./chunk-7SW3CC66.mjs";
9
+ } from "./chunk-LGXQBALM.mjs";
10
10
  import {
11
11
  __export
12
12
  } from "./chunk-U5UIDVOO.mjs";
@@ -16,6 +16,7 @@ var authentication_exports = {};
16
16
  __export(authentication_exports, {
17
17
  Controller: () => AuthenticationController,
18
18
  Mocks: () => fixtures_exports,
19
+ default: () => authentication_default,
19
20
  defaultState: () => defaultState
20
21
  });
21
22
 
@@ -79,8 +80,13 @@ var getMockAuthAccessTokenResponse = () => {
79
80
  };
80
81
  };
81
82
 
83
+ // src/controllers/authentication/index.ts
84
+ var AuthenticationController2 = AuthenticationController;
85
+ var authentication_default = AuthenticationController2;
86
+
82
87
  export {
83
88
  fixtures_exports,
89
+ authentication_default,
84
90
  authentication_exports
85
91
  };
86
- //# sourceMappingURL=chunk-CJLDMVV3.mjs.map
92
+ //# sourceMappingURL=chunk-UHP2Y32K.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/controllers/authentication/index.ts","../src/controllers/authentication/__fixtures__/index.ts","../src/controllers/authentication/__fixtures__/mockResponses.ts"],"sourcesContent":["import Controller from './AuthenticationController';\n\nconst AuthenticationController = Controller;\nexport { Controller };\nexport default AuthenticationController;\nexport * from './AuthenticationController';\nexport * as Mocks from './__fixtures__';\n","export * from './mockResponses';\n","import type {\n LoginResponse,\n NonceResponse,\n OAuthTokenResponse,\n} from '../services';\nimport {\n AUTH_LOGIN_ENDPOINT,\n AUTH_NONCE_ENDPOINT,\n OIDC_TOKENS_ENDPOINT,\n} from '../services';\n\ntype MockResponse = {\n url: string;\n requestMethod: 'GET' | 'POST' | 'PUT';\n response: unknown;\n};\n\nexport const MOCK_NONCE = '4cbfqzoQpcNxVImGv';\nexport const MOCK_NONCE_RESPONSE: NonceResponse = {\n nonce: MOCK_NONCE,\n};\n\nexport const getMockAuthNonceResponse = () => {\n return {\n url: AUTH_NONCE_ENDPOINT,\n requestMethod: 'GET',\n response: MOCK_NONCE_RESPONSE,\n } satisfies MockResponse;\n};\n\nexport const MOCK_JWT =\n 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';\nexport const MOCK_LOGIN_RESPONSE: LoginResponse = {\n token: MOCK_JWT,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n expires_in: new Date().toString(),\n profile: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n identifier_id: 'MOCK_IDENTIFIER',\n // eslint-disable-next-line @typescript-eslint/naming-convention\n profile_id: 'MOCK_PROFILE_ID',\n },\n};\n\nexport const getMockAuthLoginResponse = () => {\n return {\n url: AUTH_LOGIN_ENDPOINT,\n requestMethod: 'POST',\n response: MOCK_LOGIN_RESPONSE,\n } satisfies MockResponse;\n};\n\nexport const MOCK_ACCESS_TOKEN = `MOCK_ACCESS_TOKEN-${MOCK_JWT}`;\nexport const MOCK_OATH_TOKEN_RESPONSE: OAuthTokenResponse = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n access_token: MOCK_ACCESS_TOKEN,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n expires_in: new Date().getTime(),\n};\n\nexport const getMockAuthAccessTokenResponse = () => {\n return {\n url: OIDC_TOKENS_ENDPOINT,\n requestMethod: 'POST',\n response: MOCK_OATH_TOKEN_RESPONSE,\n } satisfies MockResponse;\n};\n"],"mappings":";;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACiBO,IAAM,aAAa;AACnB,IAAM,sBAAqC;AAAA,EAChD,OAAO;AACT;AAEO,IAAM,2BAA2B,MAAM;AAC5C,SAAO;AAAA,IACL,KAAK;AAAA,IACL,eAAe;AAAA,IACf,UAAU;AAAA,EACZ;AACF;AAEO,IAAM,WACX;AACK,IAAM,sBAAqC;AAAA,EAChD,OAAO;AAAA;AAAA,EAEP,aAAY,oBAAI,KAAK,GAAE,SAAS;AAAA,EAChC,SAAS;AAAA;AAAA,IAEP,eAAe;AAAA;AAAA,IAEf,YAAY;AAAA,EACd;AACF;AAEO,IAAM,2BAA2B,MAAM;AAC5C,SAAO;AAAA,IACL,KAAK;AAAA,IACL,eAAe;AAAA,IACf,UAAU;AAAA,EACZ;AACF;AAEO,IAAM,oBAAoB,qBAAqB,QAAQ;AACvD,IAAM,2BAA+C;AAAA;AAAA,EAE1D,cAAc;AAAA;AAAA,EAEd,aAAY,oBAAI,KAAK,GAAE,QAAQ;AACjC;AAEO,IAAM,iCAAiC,MAAM;AAClD,SAAO;AAAA,IACL,KAAK;AAAA,IACL,eAAe;AAAA,IACf,UAAU;AAAA,EACZ;AACF;;;AFhEA,IAAMA,4BAA2B;AAEjC,IAAO,yBAAQC;","names":["AuthenticationController","AuthenticationController"]}
@@ -0,0 +1,11 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
+
3
+ var _chunkBKQE7DB5js = require('./chunk-BKQE7DB5.js');
4
+
5
+ // src/sdk/encryption.ts
6
+ var encryption_default2 = _chunkBKQE7DB5js.encryption_default;
7
+
8
+
9
+
10
+ exports.encryption_default = encryption_default2;
11
+ //# sourceMappingURL=chunk-UHX7HJAI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sdk/encryption.ts"],"names":["encryption_default"],"mappings":";;;;;AAGA,IAAOA,sBAAQ","sourcesContent":["import encryption from '../controllers/user-storage/encryption/encryption';\n\nexport * from '../controllers/user-storage/encryption/encryption';\nexport default encryption;\n"]}