@metamask/profile-sync-controller 0.2.1 → 0.3.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 (168) hide show
  1. package/CHANGELOG.md +34 -1
  2. package/auth/mocks/package.json +9 -0
  3. package/auth/package.json +9 -0
  4. package/dist/{chunk-BDO3VJEU.mjs → chunk-2CWF7ZTL.mjs} +2 -2
  5. package/dist/{chunk-7KMONAQI.mjs → chunk-4WXZXVLI.mjs} +7 -9
  6. package/dist/{chunk-7KMONAQI.mjs.map → chunk-4WXZXVLI.mjs.map} +1 -1
  7. package/dist/{chunk-VD2IGTS3.js → chunk-4ZGRRVMI.js} +5 -5
  8. package/dist/{chunk-WWQ65CZY.mjs → chunk-D4SNJOID.mjs} +2 -2
  9. package/dist/chunk-D4SNJOID.mjs.map +1 -0
  10. package/dist/{chunk-SMKTWM6I.js → chunk-DF24ZX4H.js} +2 -3
  11. package/dist/chunk-DF24ZX4H.js.map +1 -0
  12. package/dist/{chunk-NPH5AHLH.mjs → chunk-E7Z5TCQT.mjs} +54 -6
  13. package/dist/chunk-E7Z5TCQT.mjs.map +1 -0
  14. package/dist/chunk-EHZFPUJH.mjs +53 -0
  15. package/dist/chunk-EHZFPUJH.mjs.map +1 -0
  16. package/dist/{chunk-SLHAVOTE.js → chunk-EYZFHZR2.js} +11 -4
  17. package/dist/chunk-EYZFHZR2.js.map +1 -0
  18. package/dist/{chunk-KW3X4TT5.js → chunk-F6BAOSH2.js} +6 -6
  19. package/dist/chunk-F6BAOSH2.js.map +1 -0
  20. package/dist/chunk-GQXYWBFK.js +28 -0
  21. package/dist/chunk-GQXYWBFK.js.map +1 -0
  22. package/dist/{chunk-3TE6M5TV.js → chunk-HMRRB4EX.js} +40 -7
  23. package/dist/chunk-HMRRB4EX.js.map +1 -0
  24. package/dist/{chunk-DRD22DR5.mjs → chunk-J7NSK6BO.mjs} +2 -2
  25. package/dist/chunk-JAQ5TPSZ.js +53 -0
  26. package/dist/chunk-JAQ5TPSZ.js.map +1 -0
  27. package/dist/{chunk-PSR2V3R4.js → chunk-JJ5BDCKD.js} +17 -19
  28. package/dist/chunk-JJ5BDCKD.js.map +1 -0
  29. package/dist/{chunk-G4NU4KP7.js → chunk-KIVBL6OM.js} +6 -6
  30. package/dist/{chunk-FQ5SDMRE.mjs → chunk-KTCSRECK.mjs} +2 -3
  31. package/dist/{chunk-FQ5SDMRE.mjs.map → chunk-KTCSRECK.mjs.map} +1 -1
  32. package/dist/chunk-LDYHGAP4.js +11 -0
  33. package/dist/chunk-LDYHGAP4.js.map +1 -0
  34. package/dist/{chunk-7SW3CC66.mjs → chunk-LGXQBALM.mjs} +2 -2
  35. package/dist/{chunk-5C53GKTU.js.map → chunk-LGXQBALM.mjs.map} +1 -1
  36. package/dist/{chunk-BOET676P.js → chunk-LLG4D2SC.js} +8 -8
  37. package/dist/{chunk-JENTMRXO.js → chunk-LNECIW4K.js} +214 -8
  38. package/dist/chunk-LNECIW4K.js.map +1 -0
  39. package/dist/{chunk-FU7PSGFP.mjs → chunk-LYDHYB6I.mjs} +36 -3
  40. package/dist/chunk-LYDHYB6I.mjs.map +1 -0
  41. package/dist/{chunk-QE5X2BT3.mjs → chunk-M23ZCTKE.mjs} +212 -6
  42. package/dist/chunk-M23ZCTKE.mjs.map +1 -0
  43. package/dist/{chunk-ILIZJQ6X.mjs → chunk-NSSHFDIS.mjs} +10 -3
  44. package/dist/chunk-NSSHFDIS.mjs.map +1 -0
  45. package/dist/{chunk-MNVUKRZC.js → chunk-PRYLTXW4.js} +15 -9
  46. package/dist/chunk-PRYLTXW4.js.map +1 -0
  47. package/dist/{chunk-XSSIP3PJ.js → chunk-Q5KTSMRE.js} +8 -8
  48. package/dist/chunk-QU4EXKJO.mjs +11 -0
  49. package/dist/chunk-QU4EXKJO.mjs.map +1 -0
  50. package/dist/{chunk-CJLDMVV3.mjs → chunk-UHP2Y32K.mjs} +9 -3
  51. package/dist/chunk-UHP2Y32K.mjs.map +1 -0
  52. package/dist/{chunk-4DQF2YNS.js → chunk-WAFY3R2F.js} +41 -16
  53. package/dist/chunk-WAFY3R2F.js.map +1 -0
  54. package/dist/{chunk-VYZPOR47.mjs → chunk-YKOMKXG4.mjs} +4 -4
  55. package/dist/{chunk-WB6MUIML.mjs → chunk-YLURF2PF.mjs} +2 -2
  56. package/dist/{chunk-FUPEFLXB.js → chunk-ZMQRPWJN.js} +60 -12
  57. package/dist/chunk-ZMQRPWJN.js.map +1 -0
  58. package/dist/chunk-ZUPTMFEA.mjs +28 -0
  59. package/dist/chunk-ZUPTMFEA.mjs.map +1 -0
  60. package/dist/{chunk-5C53GKTU.js → chunk-ZX2KHPXG.js} +5 -5
  61. package/dist/chunk-ZX2KHPXG.js.map +1 -0
  62. package/dist/{chunk-XMYWJQNH.mjs → chunk-ZYYAQJ56.mjs} +38 -13
  63. package/dist/chunk-ZYYAQJ56.mjs.map +1 -0
  64. package/dist/controllers/authentication/AuthenticationController.js +4 -21
  65. package/dist/controllers/authentication/AuthenticationController.mjs +3 -20
  66. package/dist/controllers/authentication/index.js +7 -22
  67. package/dist/controllers/authentication/index.mjs +6 -21
  68. package/dist/controllers/authentication/services.js +3 -20
  69. package/dist/controllers/authentication/services.mjs +2 -19
  70. package/dist/controllers/index.js +11 -21
  71. package/dist/controllers/index.mjs +10 -20
  72. package/dist/controllers/user-storage/UserStorageController.js +7 -17
  73. package/dist/controllers/user-storage/UserStorageController.mjs +6 -16
  74. package/dist/controllers/user-storage/accounts/constants.js +12 -0
  75. package/dist/controllers/user-storage/accounts/constants.js.map +1 -0
  76. package/dist/controllers/user-storage/accounts/constants.mjs +12 -0
  77. package/dist/controllers/user-storage/accounts/constants.mjs.map +1 -0
  78. package/dist/controllers/user-storage/accounts/user-storage.js +11 -0
  79. package/dist/controllers/user-storage/accounts/user-storage.js.map +1 -0
  80. package/dist/controllers/user-storage/accounts/user-storage.mjs +11 -0
  81. package/dist/controllers/user-storage/accounts/user-storage.mjs.map +1 -0
  82. package/dist/controllers/user-storage/index.js +10 -18
  83. package/dist/controllers/user-storage/index.mjs +10 -18
  84. package/dist/controllers/user-storage/schema.js +4 -2
  85. package/dist/controllers/user-storage/schema.mjs +5 -3
  86. package/dist/controllers/user-storage/services.js +6 -16
  87. package/dist/controllers/user-storage/services.mjs +5 -15
  88. package/dist/index.js +18 -16
  89. package/dist/index.mjs +17 -15
  90. package/dist/sdk/authentication-jwt-bearer/flow-siwe.js +4 -4
  91. package/dist/sdk/authentication-jwt-bearer/flow-siwe.mjs +3 -3
  92. package/dist/sdk/authentication-jwt-bearer/flow-srp.js +4 -4
  93. package/dist/sdk/authentication-jwt-bearer/flow-srp.mjs +3 -3
  94. package/dist/sdk/authentication-jwt-bearer/services.js +3 -3
  95. package/dist/sdk/authentication-jwt-bearer/services.mjs +2 -2
  96. package/dist/sdk/authentication.js +6 -6
  97. package/dist/sdk/authentication.mjs +5 -5
  98. package/dist/sdk/encryption.js +5 -3
  99. package/dist/sdk/encryption.mjs +6 -4
  100. package/dist/sdk/env.js +2 -2
  101. package/dist/sdk/env.mjs +1 -1
  102. package/dist/sdk/index.js +13 -15
  103. package/dist/sdk/index.mjs +12 -14
  104. package/dist/sdk/user-storage.js +5 -5
  105. package/dist/sdk/user-storage.mjs +4 -4
  106. package/dist/tsconfig.build.tsbuildinfo +1 -1
  107. package/dist/types/controllers/authentication/AuthenticationController.d.ts +6 -3
  108. package/dist/types/controllers/authentication/AuthenticationController.d.ts.map +1 -1
  109. package/dist/types/controllers/authentication/__fixtures__/mockResponses.d.ts +1 -1
  110. package/dist/types/controllers/authentication/__fixtures__/mockResponses.d.ts.map +1 -1
  111. package/dist/types/controllers/authentication/index.d.ts +2 -0
  112. package/dist/types/controllers/authentication/index.d.ts.map +1 -1
  113. package/dist/types/controllers/user-storage/UserStorageController.d.ts +48 -10
  114. package/dist/types/controllers/user-storage/UserStorageController.d.ts.map +1 -1
  115. package/dist/types/controllers/user-storage/__fixtures__/mockAccounts.d.ts +63 -0
  116. package/dist/types/controllers/user-storage/__fixtures__/mockAccounts.d.ts.map +1 -0
  117. package/dist/types/controllers/user-storage/__fixtures__/mockResponses.d.ts +10 -4
  118. package/dist/types/controllers/user-storage/__fixtures__/mockResponses.d.ts.map +1 -1
  119. package/dist/types/controllers/user-storage/__fixtures__/mockServices.d.ts +4 -2
  120. package/dist/types/controllers/user-storage/__fixtures__/mockServices.d.ts.map +1 -1
  121. package/dist/types/controllers/user-storage/accounts/constants.d.ts +4 -0
  122. package/dist/types/controllers/user-storage/accounts/constants.d.ts.map +1 -0
  123. package/dist/types/controllers/user-storage/accounts/user-storage.d.ts +32 -0
  124. package/dist/types/controllers/user-storage/accounts/user-storage.d.ts.map +1 -0
  125. package/dist/types/controllers/user-storage/index.d.ts +2 -0
  126. package/dist/types/controllers/user-storage/index.d.ts.map +1 -1
  127. package/dist/types/controllers/user-storage/schema.d.ts +13 -6
  128. package/dist/types/controllers/user-storage/schema.d.ts.map +1 -1
  129. package/dist/types/controllers/user-storage/services.d.ts +20 -4
  130. package/dist/types/controllers/user-storage/services.d.ts.map +1 -1
  131. package/dist/types/sdk/__fixtures__/mock-userstorage.d.ts +1 -0
  132. package/dist/types/sdk/__fixtures__/mock-userstorage.d.ts.map +1 -1
  133. package/dist/types/sdk/encryption.d.ts +3 -19
  134. package/dist/types/sdk/encryption.d.ts.map +1 -1
  135. package/dist/types/sdk/user-storage.d.ts +4 -3
  136. package/dist/types/sdk/user-storage.d.ts.map +1 -1
  137. package/package.json +37 -6
  138. package/user-storage/mocks/package.json +9 -0
  139. package/user-storage/package.json +9 -0
  140. package/dist/chunk-3TE6M5TV.js.map +0 -1
  141. package/dist/chunk-4DQF2YNS.js.map +0 -1
  142. package/dist/chunk-7SW3CC66.mjs.map +0 -1
  143. package/dist/chunk-B5DBQDB3.mjs +0 -140
  144. package/dist/chunk-B5DBQDB3.mjs.map +0 -1
  145. package/dist/chunk-CJLDMVV3.mjs.map +0 -1
  146. package/dist/chunk-FU7PSGFP.mjs.map +0 -1
  147. package/dist/chunk-FUPEFLXB.js.map +0 -1
  148. package/dist/chunk-ILIZJQ6X.mjs.map +0 -1
  149. package/dist/chunk-JENTMRXO.js.map +0 -1
  150. package/dist/chunk-KW3X4TT5.js.map +0 -1
  151. package/dist/chunk-MNVUKRZC.js.map +0 -1
  152. package/dist/chunk-NPH5AHLH.mjs.map +0 -1
  153. package/dist/chunk-P4DUDLMY.js +0 -140
  154. package/dist/chunk-P4DUDLMY.js.map +0 -1
  155. package/dist/chunk-PSR2V3R4.js.map +0 -1
  156. package/dist/chunk-QE5X2BT3.mjs.map +0 -1
  157. package/dist/chunk-SLHAVOTE.js.map +0 -1
  158. package/dist/chunk-SMKTWM6I.js.map +0 -1
  159. package/dist/chunk-WWQ65CZY.mjs.map +0 -1
  160. package/dist/chunk-XMYWJQNH.mjs.map +0 -1
  161. /package/dist/{chunk-BDO3VJEU.mjs.map → chunk-2CWF7ZTL.mjs.map} +0 -0
  162. /package/dist/{chunk-VD2IGTS3.js.map → chunk-4ZGRRVMI.js.map} +0 -0
  163. /package/dist/{chunk-DRD22DR5.mjs.map → chunk-J7NSK6BO.mjs.map} +0 -0
  164. /package/dist/{chunk-G4NU4KP7.js.map → chunk-KIVBL6OM.js.map} +0 -0
  165. /package/dist/{chunk-BOET676P.js.map → chunk-LLG4D2SC.js.map} +0 -0
  166. /package/dist/{chunk-XSSIP3PJ.js.map → chunk-Q5KTSMRE.js.map} +0 -0
  167. /package/dist/{chunk-VYZPOR47.mjs.map → chunk-YKOMKXG4.mjs.map} +0 -0
  168. /package/dist/{chunk-WB6MUIML.mjs.map → chunk-YLURF2PF.mjs.map} +0 -0
@@ -1,10 +1,15 @@
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-LYDHYB6I.mjs";
8
13
  import {
9
14
  createSHA256Hash
10
15
  } from "./chunk-K5UKU454.mjs";
@@ -32,7 +37,7 @@ 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, _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
42
  constructor(params) {
38
43
  super({
@@ -91,6 +96,54 @@ var UserStorageController = class extends BaseController {
91
96
  );
92
97
  }
93
98
  });
99
+ __privateAdd(this, _accounts, {
100
+ // This is replaced with the actual value in the constructor
101
+ // We will remove this once the feature will be released
102
+ isAccountSyncingEnabled: false,
103
+ getInternalAccountByAddress: async (address) => {
104
+ return this.messagingSystem.call(
105
+ "AccountsController:getAccountByAddress",
106
+ address
107
+ );
108
+ },
109
+ getInternalAccountsList: async () => {
110
+ return this.messagingSystem.call("AccountsController:listAccounts");
111
+ },
112
+ getUserStorageAccountsList: async () => {
113
+ const rawAccountsListResponse = await this.performGetStorageAllFeatureEntries("accounts");
114
+ return rawAccountsListResponse?.map((rawAccount) => JSON.parse(rawAccount)) ?? null;
115
+ },
116
+ saveInternalAccountToUserStorage: async (address) => {
117
+ const internalAccount = await __privateGet(this, _accounts).getInternalAccountByAddress(
118
+ address
119
+ );
120
+ if (!internalAccount) {
121
+ return;
122
+ }
123
+ const mappedAccount = mapInternalAccountToUserStorageAccount(internalAccount);
124
+ await this.performSetStorage(
125
+ `accounts.${address}`,
126
+ JSON.stringify(mappedAccount)
127
+ );
128
+ },
129
+ saveInternalAccountsListToUserStorage: async () => {
130
+ const internalAccountsList = await __privateGet(this, _accounts).getInternalAccountsList();
131
+ if (!internalAccountsList) {
132
+ return;
133
+ }
134
+ const userStorageAccountsList = internalAccountsList.map(
135
+ mapInternalAccountToUserStorageAccount
136
+ );
137
+ await Promise.all(
138
+ userStorageAccountsList.map(async (userStorageAccount) => {
139
+ await this.performSetStorage(
140
+ `accounts.${userStorageAccount.a}`,
141
+ JSON.stringify(userStorageAccount)
142
+ );
143
+ })
144
+ );
145
+ }
146
+ });
94
147
  __privateAdd(this, _notificationServices, {
95
148
  disableNotificationServices: async () => {
96
149
  return await this.messagingSystem.call(
@@ -110,15 +163,23 @@ var UserStorageController = class extends BaseController {
110
163
  "KeyringController:getState"
111
164
  );
112
165
  __privateSet(this, _isUnlocked, isUnlocked);
113
- this.messagingSystem.subscribe("KeyringController:unlock", () => {
114
- __privateSet(this, _isUnlocked, true);
115
- });
166
+ this.messagingSystem.subscribe(
167
+ "KeyringController:unlock",
168
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
169
+ async () => {
170
+ __privateSet(this, _isUnlocked, true);
171
+ await this.syncInternalAccountsWithUserStorage();
172
+ }
173
+ );
116
174
  this.messagingSystem.subscribe("KeyringController:lock", () => {
117
175
  __privateSet(this, _isUnlocked, false);
118
176
  });
119
177
  }
120
178
  });
121
179
  __privateAdd(this, __snapSignMessageCache, {});
180
+ __privateGet(this, _accounts).isAccountSyncingEnabled = Boolean(
181
+ params.env?.isAccountSyncingEnabled
182
+ );
122
183
  this.getMetaMetricsState = params.getMetaMetricsState;
123
184
  __privateGet(this, _keyringController).setupLockedStateSubscriptions();
124
185
  __privateMethod(this, _registerMessageHandlers, registerMessageHandlers_fn).call(this);
@@ -191,6 +252,23 @@ var UserStorageController = class extends BaseController {
191
252
  });
192
253
  return result;
193
254
  }
255
+ /**
256
+ * Allows retrieval of all stored data for a specific feature. Data stored is formatted as an array of strings.
257
+ * Developers can extend the entry path through the `schema.ts` file.
258
+ *
259
+ * @param path - string in the form of `${feature}` that matches schema
260
+ * @returns the array of decrypted string contents found from user storage (or null if not found)
261
+ */
262
+ async performGetStorageAllFeatureEntries(path) {
263
+ __privateMethod(this, _assertProfileSyncingEnabled, assertProfileSyncingEnabled_fn).call(this);
264
+ const { bearerToken, storageKey } = await __privateMethod(this, _getStorageKeyAndBearerToken, getStorageKeyAndBearerToken_fn).call(this);
265
+ const result = await getUserStorageAllFeatureEntries({
266
+ path,
267
+ bearerToken,
268
+ storageKey
269
+ });
270
+ return result;
271
+ }
194
272
  /**
195
273
  * Allows storage of user data. Data stored must be string formatted.
196
274
  * Developers can extend the entry path and entry name through the `schema.ts` file.
@@ -218,8 +296,124 @@ var UserStorageController = class extends BaseController {
218
296
  const storageKey = await __privateMethod(this, _createStorageKey, createStorageKey_fn).call(this);
219
297
  return storageKey;
220
298
  }
299
+ /**
300
+ * Syncs the internal accounts list with the user storage accounts list.
301
+ * 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.
302
+ * 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.
303
+ */
304
+ async syncInternalAccountsWithUserStorage() {
305
+ if (!__privateGet(this, _accounts).isAccountSyncingEnabled) {
306
+ return;
307
+ }
308
+ try {
309
+ __privateMethod(this, _assertProfileSyncingEnabled, assertProfileSyncingEnabled_fn).call(this);
310
+ const userStorageAccountsList = await __privateGet(this, _accounts).getUserStorageAccountsList();
311
+ if (!userStorageAccountsList || !userStorageAccountsList.length) {
312
+ await __privateGet(this, _accounts).saveInternalAccountsListToUserStorage();
313
+ return;
314
+ }
315
+ let internalAccountsList = await __privateGet(this, _accounts).getInternalAccountsList();
316
+ if (!internalAccountsList || !internalAccountsList.length) {
317
+ throw new Error(`Failed to get internal accounts list`);
318
+ }
319
+ const hasMoreInternalAccountsThanUserStorageAccounts = internalAccountsList.length > userStorageAccountsList.length;
320
+ if (!hasMoreInternalAccountsThanUserStorageAccounts) {
321
+ const numberOfAccountsToAdd = userStorageAccountsList.length - internalAccountsList.length;
322
+ const addNewAccountsPromises = Array.from({
323
+ length: numberOfAccountsToAdd
324
+ }).map(async () => {
325
+ await this.messagingSystem.call("KeyringController:addNewAccount");
326
+ });
327
+ await Promise.all(addNewAccountsPromises);
328
+ }
329
+ internalAccountsList = await __privateGet(this, _accounts).getInternalAccountsList();
330
+ for await (const internalAccount of internalAccountsList) {
331
+ const userStorageAccount = userStorageAccountsList.find(
332
+ (account) => account.a === internalAccount.address
333
+ );
334
+ if (!userStorageAccount) {
335
+ await __privateGet(this, _accounts).saveInternalAccountToUserStorage(
336
+ internalAccount.address
337
+ );
338
+ continue;
339
+ }
340
+ const isInternalAccountNameDefault = isNameDefaultAccountName(
341
+ internalAccount.metadata.name
342
+ );
343
+ const isUserStorageAccountNameDefault = isNameDefaultAccountName(
344
+ userStorageAccount.n
345
+ );
346
+ if (isInternalAccountNameDefault) {
347
+ if (!isUserStorageAccountNameDefault) {
348
+ this.messagingSystem.call(
349
+ "AccountsController:updateAccountMetadata",
350
+ internalAccount.id,
351
+ {
352
+ name: userStorageAccount.n
353
+ }
354
+ );
355
+ }
356
+ continue;
357
+ }
358
+ if (isUserStorageAccountNameDefault) {
359
+ await __privateGet(this, _accounts).saveInternalAccountToUserStorage(
360
+ internalAccount.address
361
+ );
362
+ continue;
363
+ }
364
+ if (userStorageAccount.nlu !== void 0) {
365
+ if (internalAccount.metadata.nameLastUpdatedAt !== void 0) {
366
+ const isInternalAccountNameNewer = internalAccount.metadata.nameLastUpdatedAt > userStorageAccount.nlu;
367
+ if (isInternalAccountNameNewer) {
368
+ await __privateGet(this, _accounts).saveInternalAccountToUserStorage(
369
+ internalAccount.address
370
+ );
371
+ continue;
372
+ }
373
+ }
374
+ this.messagingSystem.call(
375
+ "AccountsController:updateAccountMetadata",
376
+ internalAccount.id,
377
+ {
378
+ name: userStorageAccount.n,
379
+ nameLastUpdatedAt: userStorageAccount.nlu
380
+ }
381
+ );
382
+ continue;
383
+ } else if (internalAccount.metadata.nameLastUpdatedAt !== void 0) {
384
+ await __privateGet(this, _accounts).saveInternalAccountToUserStorage(
385
+ internalAccount.address
386
+ );
387
+ continue;
388
+ }
389
+ }
390
+ } catch (e) {
391
+ const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);
392
+ throw new Error(
393
+ `${controllerName} - failed to sync user storage accounts list - ${errorMessage}`
394
+ );
395
+ }
396
+ }
397
+ /**
398
+ * Saves an individual internal account to the user storage.
399
+ * @param address - The address of the internal account to save
400
+ */
401
+ async saveInternalAccountToUserStorage(address) {
402
+ if (!__privateGet(this, _accounts).isAccountSyncingEnabled) {
403
+ return;
404
+ }
405
+ try {
406
+ await __privateGet(this, _accounts).saveInternalAccountToUserStorage(address);
407
+ } catch (e) {
408
+ const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);
409
+ throw new Error(
410
+ `${controllerName} - failed to save account to user storage - ${errorMessage}`
411
+ );
412
+ }
413
+ }
221
414
  };
222
415
  _auth = new WeakMap();
416
+ _accounts = new WeakMap();
223
417
  _notificationServices = new WeakMap();
224
418
  _isUnlocked = new WeakMap();
225
419
  _keyringController = new WeakMap();
@@ -229,6 +423,10 @@ registerMessageHandlers_fn = function() {
229
423
  "UserStorageController:performGetStorage",
230
424
  this.performGetStorage.bind(this)
231
425
  );
426
+ this.messagingSystem.registerActionHandler(
427
+ "UserStorageController:performGetStorageAllFeatureEntries",
428
+ this.performGetStorageAllFeatureEntries.bind(this)
429
+ );
232
430
  this.messagingSystem.registerActionHandler(
233
431
  "UserStorageController:performSetStorage",
234
432
  this.performSetStorage.bind(this)
@@ -245,6 +443,14 @@ registerMessageHandlers_fn = function() {
245
443
  "UserStorageController:disableProfileSyncing",
246
444
  this.disableProfileSyncing.bind(this)
247
445
  );
446
+ this.messagingSystem.registerActionHandler(
447
+ "UserStorageController:syncInternalAccountsWithUserStorage",
448
+ this.syncInternalAccountsWithUserStorage.bind(this)
449
+ );
450
+ this.messagingSystem.registerActionHandler(
451
+ "UserStorageController:saveInternalAccountToUserStorage",
452
+ this.saveInternalAccountToUserStorage.bind(this)
453
+ );
248
454
  };
249
455
  _assertProfileSyncingEnabled = new WeakSet();
250
456
  assertProfileSyncingEnabled_fn = function() {
@@ -302,4 +508,4 @@ export {
302
508
  defaultState,
303
509
  UserStorageController
304
510
  };
305
- //# sourceMappingURL=chunk-QE5X2BT3.mjs.map
511
+ //# sourceMappingURL=chunk-M23ZCTKE.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\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 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 getMetaMetricsState: () => boolean;\n\n constructor(params: {\n messenger: UserStorageControllerMessenger;\n state?: UserStorageControllerState;\n env?: {\n isAccountSyncingEnabled?: boolean;\n };\n getMetaMetricsState: () => boolean;\n }) {\n super({\n messenger: params.messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...params.state },\n });\n\n this.#accounts.isAccountSyncingEnabled = Boolean(\n params.env?.isAccountSyncingEnabled,\n );\n\n this.getMetaMetricsState = params.getMetaMetricsState;\n this.#keyringController.setupLockedStateSubscriptions();\n this.#registerMessageHandlers();\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performGetStorage',\n this.performGetStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController: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 });\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 });\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 });\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 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;AA+C/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;AAtFA;AAiMA,IAAqB,wBAArB,cAAmD,eAIjD;AAAA,EAqIA,YAAY,QAOT;AACD,UAAM;AAAA,MACJ,WAAW,OAAO;AAAA,MAClB;AAAA,MACA,MAAM;AAAA,MACN,OAAO,EAAE,GAAG,cAAc,GAAG,OAAO,MAAM;AAAA,IAC5C,CAAC;AAeH;AAAA;AAAA;AAAA;AAAA;AAgMA;AAWA;AAAA;AAAA;AAAA,uBAAM;AAkBN;AAAA;AAAA;AAAA;AAAA;AAAA,uBAAM;AAmBN;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,uBAAM;AAqBN;AAraA,8BAAQ;AAAA,MACN,gBAAgB,YAAY;AAC1B,eAAO,MAAM,KAAK,gBAAgB;AAAA,UAChC;AAAA,QACF;AAAA,MACF;AAAA,MACA,cAAc,YAAY;AACxB,cAAM,iBAAiB,MAAM,KAAK,gBAAgB;AAAA,UAChD;AAAA,QACF;AACA,eAAO,gBAAgB;AAAA,MACzB;AAAA,MACA,eAAe,MAAM;AACnB,eAAO,KAAK,gBAAgB,KAAK,qCAAqC;AAAA,MACxE;AAAA,MACA,QAAQ,YAAY;AAClB,eAAO,MAAM,KAAK,gBAAgB;AAAA,UAChC;AAAA,QACF;AAAA,MACF;AAAA,MACA,SAAS,YAAY;AACnB,eAAO,KAAK,gB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E;AACA,QAAM,aAAa,MAAM,sBAAK,wCAAL;AAEzB,SAAO,EAAE,aAAa,WAAW;AACnC;AAOM;AAAA,sBAAiB,iBAAoB;AACzC,QAAM,KAAa,MAAM,mBAAK,OAAM,aAAa;AACjD,MAAI,CAAC,IAAI;AACP,UAAM,IAAI,MAAM,sDAAsD;AAAA,EACxE;AAEA,QAAM,sBAAsB,MAAM,sBAAK,sCAAL,WAAsB,YAAY,EAAE;AACtE,QAAM,aAAa,iBAAiB,mBAAmB;AACvD,SAAO;AACT;AAEA;AAQM;AAAA,qBAAgB,eAAC,SAAgD;AACrE,MAAI,mBAAK,wBAAuB,OAAO,GAAG;AACxC,WAAO,mBAAK,wBAAuB,OAAO;AAAA,EAC5C;AAEA,MAAI,CAAC,mBAAK,cAAa;AACrB,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM,SAAU,MAAM,KAAK,gBAAgB;AAAA,IACzC;AAAA,IACA,6BAA6B,OAAO;AAAA,EACtC;AAEA,qBAAK,wBAAuB,OAAO,IAAI;AAEvC,SAAO;AACT;AAEA;AAAA,sCAAiC,SAC/B,+BACM;AACN,OAAK,OAAO,CAAC,UAAU;AACrB,UAAM,gCAAgC;AAAA,EACxC,CAAC;AACH;","names":[]}
@@ -3,8 +3,10 @@ import {
3
3
  } from "./chunk-K5UKU454.mjs";
4
4
 
5
5
  // src/controllers/user-storage/schema.ts
6
+ var ALLOW_ARBITRARY_KEYS = "ALLOW_ARBITRARY_KEYS";
6
7
  var USER_STORAGE_SCHEMA = {
7
- notifications: ["notificationSettings"]
8
+ notifications: ["notificationSettings"],
9
+ accounts: [ALLOW_ARBITRARY_KEYS]
8
10
  };
9
11
  var getFeatureAndKeyFromPath = (path) => {
10
12
  const pathRegex = /^\w+\.\w+$/u;
@@ -18,7 +20,7 @@ var getFeatureAndKeyFromPath = (path) => {
18
20
  throw new Error(`user-storage - invalid feature provided: ${feature}`);
19
21
  }
20
22
  const validFeature = USER_STORAGE_SCHEMA[feature];
21
- if (!validFeature.includes(key)) {
23
+ if (!validFeature.includes(key) && !validFeature.includes(ALLOW_ARBITRARY_KEYS)) {
22
24
  const validKeys = USER_STORAGE_SCHEMA[feature].join(", ");
23
25
  throw new Error(
24
26
  `user-storage - invalid key provided for this feature: ${key}. Valid keys: ${validKeys}`
@@ -26,6 +28,10 @@ var getFeatureAndKeyFromPath = (path) => {
26
28
  }
27
29
  return { feature, key };
28
30
  };
31
+ var isPathWithFeatureAndKey = (path) => {
32
+ const pathRegex = /^\w+\.\w+$/u;
33
+ return pathRegex.test(path);
34
+ };
29
35
  function createEntryPath(path, storageKey) {
30
36
  const { feature, key } = getFeatureAndKeyFromPath(path);
31
37
  const hashedKey = createSHA256Hash(key + storageKey);
@@ -35,6 +41,7 @@ function createEntryPath(path, storageKey) {
35
41
  export {
36
42
  USER_STORAGE_SCHEMA,
37
43
  getFeatureAndKeyFromPath,
44
+ isPathWithFeatureAndKey,
38
45
  createEntryPath
39
46
  };
40
- //# sourceMappingURL=chunk-ILIZJQ6X.mjs.map
47
+ //# sourceMappingURL=chunk-NSSHFDIS.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/controllers/user-storage/schema.ts"],"sourcesContent":["import { createSHA256Hash } from './encryption';\n\n/**\n * The User Storage Endpoint requires a feature name and a namespace key.\n * Developers can provide additional features and keys by extending these types below.\n *\n * Adding ALLOW_ARBITRARY_KEYS as the first key in the array allows for any key to be used for this feature.\n * This can be useful for features where keys are not deterministic (eg. accounts addresses).\n */\nconst ALLOW_ARBITRARY_KEYS = 'ALLOW_ARBITRARY_KEYS' as const;\n\nexport const USER_STORAGE_SCHEMA = {\n notifications: ['notificationSettings'],\n accounts: [ALLOW_ARBITRARY_KEYS],\n} as const;\n\ntype UserStorageSchema = typeof USER_STORAGE_SCHEMA;\n\ntype UserStorageFeatures = keyof UserStorageSchema;\ntype UserStorageFeatureKeys<Feature extends UserStorageFeatures> =\n UserStorageSchema[Feature][0] extends typeof ALLOW_ARBITRARY_KEYS\n ? string\n : UserStorageSchema[Feature][number];\n\ntype UserStorageFeatureAndKey = {\n feature: UserStorageFeatures;\n key: UserStorageFeatureKeys<UserStorageFeatures>;\n};\n\nexport type UserStoragePathWithFeatureOnly = keyof UserStorageSchema;\nexport type UserStoragePathWithFeatureAndKey = {\n [K in UserStorageFeatures]: `${K}.${UserStorageFeatureKeys<K>}`;\n}[UserStoragePathWithFeatureOnly];\n\nexport const getFeatureAndKeyFromPath = (\n path: UserStoragePathWithFeatureAndKey,\n): UserStorageFeatureAndKey => {\n const pathRegex = /^\\w+\\.\\w+$/u;\n\n if (!pathRegex.test(path)) {\n throw new Error(\n `user-storage - path is not in the correct format. Correct format: 'feature.key'`,\n );\n }\n\n const [feature, key] = path.split('.') as [\n UserStorageFeatures,\n UserStorageFeatureKeys<UserStorageFeatures>,\n ];\n\n if (!(feature in USER_STORAGE_SCHEMA)) {\n throw new Error(`user-storage - invalid feature provided: ${feature}`);\n }\n\n const validFeature = USER_STORAGE_SCHEMA[feature] as readonly string[];\n\n if (\n !validFeature.includes(key) &&\n !validFeature.includes(ALLOW_ARBITRARY_KEYS)\n ) {\n const validKeys = USER_STORAGE_SCHEMA[feature].join(', ');\n\n throw new Error(\n `user-storage - invalid key provided for this feature: ${key}. Valid keys: ${validKeys}`,\n );\n }\n\n return { feature, key };\n};\n\nexport const isPathWithFeatureAndKey = (\n path: string,\n): path is UserStoragePathWithFeatureAndKey => {\n const pathRegex = /^\\w+\\.\\w+$/u;\n\n return pathRegex.test(path);\n};\n\n/**\n * Constructs a unique entry path for a user.\n * This can be done due to the uniqueness of the storage key (no users will share the same storage key).\n * The users entry is a unique hash that cannot be reversed.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param storageKey - users storage key\n * @returns path to store entry\n */\nexport function createEntryPath(\n path: UserStoragePathWithFeatureAndKey,\n storageKey: string,\n): string {\n const { feature, key } = getFeatureAndKeyFromPath(path);\n const hashedKey = createSHA256Hash(key + storageKey);\n\n return `/${feature}/${hashedKey}`;\n}\n"],"mappings":";;;;;AASA,IAAM,uBAAuB;AAEtB,IAAM,sBAAsB;AAAA,EACjC,eAAe,CAAC,sBAAsB;AAAA,EACtC,UAAU,CAAC,oBAAoB;AACjC;AAoBO,IAAM,2BAA2B,CACtC,SAC6B;AAC7B,QAAM,YAAY;AAElB,MAAI,CAAC,UAAU,KAAK,IAAI,GAAG;AACzB,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM,CAAC,SAAS,GAAG,IAAI,KAAK,MAAM,GAAG;AAKrC,MAAI,EAAE,WAAW,sBAAsB;AACrC,UAAM,IAAI,MAAM,4CAA4C,OAAO,EAAE;AAAA,EACvE;AAEA,QAAM,eAAe,oBAAoB,OAAO;AAEhD,MACE,CAAC,aAAa,SAAS,GAAG,KAC1B,CAAC,aAAa,SAAS,oBAAoB,GAC3C;AACA,UAAM,YAAY,oBAAoB,OAAO,EAAE,KAAK,IAAI;AAExD,UAAM,IAAI;AAAA,MACR,yDAAyD,GAAG,iBAAiB,SAAS;AAAA,IACxF;AAAA,EACF;AAEA,SAAO,EAAE,SAAS,IAAI;AACxB;AAEO,IAAM,0BAA0B,CACrC,SAC6C;AAC7C,QAAM,YAAY;AAElB,SAAO,UAAU,KAAK,IAAI;AAC5B;AAWO,SAAS,gBACd,MACA,YACQ;AACR,QAAM,EAAE,SAAS,IAAI,IAAI,yBAAyB,IAAI;AACtD,QAAM,YAAY,iBAAiB,MAAM,UAAU;AAEnD,SAAO,IAAI,OAAO,IAAI,SAAS;AACjC;","names":[]}
@@ -1,12 +1,12 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
2
 
3
3
 
4
- var _chunkKW3X4TT5js = require('./chunk-KW3X4TT5.js');
4
+ var _chunkF6BAOSH2js = require('./chunk-F6BAOSH2.js');
5
5
 
6
6
 
7
7
 
8
8
 
9
- var _chunk5C53GKTUjs = require('./chunk-5C53GKTU.js');
9
+ var _chunkZX2KHPXGjs = require('./chunk-ZX2KHPXG.js');
10
10
 
11
11
 
12
12
  var _chunkIGY2S5BCjs = require('./chunk-IGY2S5BC.js');
@@ -14,9 +14,10 @@ var _chunkIGY2S5BCjs = require('./chunk-IGY2S5BC.js');
14
14
  // src/controllers/authentication/index.ts
15
15
  var authentication_exports = {};
16
16
  _chunkIGY2S5BCjs.__export.call(void 0, authentication_exports, {
17
- Controller: () => _chunkKW3X4TT5js.AuthenticationController,
17
+ Controller: () => _chunkF6BAOSH2js.AuthenticationController,
18
18
  Mocks: () => fixtures_exports,
19
- defaultState: () => _chunkKW3X4TT5js.defaultState
19
+ default: () => authentication_default,
20
+ defaultState: () => _chunkF6BAOSH2js.defaultState
20
21
  });
21
22
 
22
23
  // src/controllers/authentication/__fixtures__/index.ts
@@ -40,7 +41,7 @@ var MOCK_NONCE_RESPONSE = {
40
41
  };
41
42
  var getMockAuthNonceResponse = () => {
42
43
  return {
43
- url: _chunk5C53GKTUjs.AUTH_NONCE_ENDPOINT,
44
+ url: _chunkZX2KHPXGjs.AUTH_NONCE_ENDPOINT,
44
45
  requestMethod: "GET",
45
46
  response: MOCK_NONCE_RESPONSE
46
47
  };
@@ -59,7 +60,7 @@ var MOCK_LOGIN_RESPONSE = {
59
60
  };
60
61
  var getMockAuthLoginResponse = () => {
61
62
  return {
62
- url: _chunk5C53GKTUjs.AUTH_LOGIN_ENDPOINT,
63
+ url: _chunkZX2KHPXGjs.AUTH_LOGIN_ENDPOINT,
63
64
  requestMethod: "POST",
64
65
  response: MOCK_LOGIN_RESPONSE
65
66
  };
@@ -73,14 +74,19 @@ var MOCK_OATH_TOKEN_RESPONSE = {
73
74
  };
74
75
  var getMockAuthAccessTokenResponse = () => {
75
76
  return {
76
- url: _chunk5C53GKTUjs.OIDC_TOKENS_ENDPOINT,
77
+ url: _chunkZX2KHPXGjs.OIDC_TOKENS_ENDPOINT,
77
78
  requestMethod: "POST",
78
79
  response: MOCK_OATH_TOKEN_RESPONSE
79
80
  };
80
81
  };
81
82
 
83
+ // src/controllers/authentication/index.ts
84
+ var AuthenticationController2 = _chunkF6BAOSH2js.AuthenticationController;
85
+ var authentication_default = AuthenticationController2;
86
+
87
+
82
88
 
83
89
 
84
90
 
85
- exports.fixtures_exports = fixtures_exports; exports.authentication_exports = authentication_exports;
86
- //# sourceMappingURL=chunk-MNVUKRZC.js.map
91
+ exports.fixtures_exports = fixtures_exports; exports.authentication_default = authentication_default; exports.authentication_exports = authentication_exports;
92
+ //# sourceMappingURL=chunk-PRYLTXW4.js.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"],"names":["AuthenticationController"],"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,yBAAQA","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"]}
@@ -1,13 +1,13 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
2
 
3
- var _chunkG4NU4KP7js = require('./chunk-G4NU4KP7.js');
3
+ var _chunkKIVBL6OMjs = require('./chunk-KIVBL6OM.js');
4
4
 
5
5
 
6
- var _chunkVD2IGTS3js = require('./chunk-VD2IGTS3.js');
6
+ var _chunk4ZGRRVMIjs = require('./chunk-4ZGRRVMI.js');
7
7
 
8
8
 
9
9
 
10
- var _chunkBOET676Pjs = require('./chunk-BOET676P.js');
10
+ var _chunkLLG4D2SCjs = require('./chunk-LLG4D2SC.js');
11
11
 
12
12
 
13
13
  var _chunkRG4II6WHjs = require('./chunk-RG4II6WH.js');
@@ -36,11 +36,11 @@ var JwtBearerAuth = class {
36
36
  _chunkIGY2S5BCjs.__privateSet.call(void 0, this, _type, args[0].type);
37
37
  _chunkIGY2S5BCjs.__privateSet.call(void 0, this, _env, args[0].env);
38
38
  if (args[0].type === "SRP" /* SRP */) {
39
- _chunkIGY2S5BCjs.__privateSet.call(void 0, this, _sdk, new (0, _chunkVD2IGTS3js.SRPJwtBearerAuth)(args[0], args[1]));
39
+ _chunkIGY2S5BCjs.__privateSet.call(void 0, this, _sdk, new (0, _chunk4ZGRRVMIjs.SRPJwtBearerAuth)(args[0], args[1]));
40
40
  return;
41
41
  }
42
42
  if (args[0].type === "SiWE" /* SiWE */) {
43
- _chunkIGY2S5BCjs.__privateSet.call(void 0, this, _sdk, new (0, _chunkG4NU4KP7js.SIWEJwtBearerAuth)(args[0], args[1]));
43
+ _chunkIGY2S5BCjs.__privateSet.call(void 0, this, _sdk, new (0, _chunkKIVBL6OMjs.SIWEJwtBearerAuth)(args[0], args[1]));
44
44
  return;
45
45
  }
46
46
  throw new (0, _chunkMBTBE4P5js.UnsupportedAuthTypeError)("unsupported auth type");
@@ -67,7 +67,7 @@ var JwtBearerAuth = class {
67
67
  }
68
68
  async pairIdentifiers(pairing) {
69
69
  const profile = await this.getUserProfile();
70
- const n = await _chunkBOET676Pjs.getNonce.call(void 0, profile.profileId, _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _env));
70
+ const n = await _chunkLLG4D2SCjs.getNonce.call(void 0, profile.profileId, _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _env));
71
71
  const logins = await Promise.all(
72
72
  pairing.map(async (p) => {
73
73
  try {
@@ -94,7 +94,7 @@ var JwtBearerAuth = class {
94
94
  })
95
95
  );
96
96
  const accessToken = await this.getAccessToken();
97
- await _chunkBOET676Pjs.pairIdentifiers.call(void 0, n.nonce, logins, accessToken, _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _env));
97
+ await _chunkLLG4D2SCjs.pairIdentifiers.call(void 0, n.nonce, logins, accessToken, _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _env));
98
98
  }
99
99
  prepare(signer) {
100
100
  _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _assertSIWE, assertSIWE_fn).call(this, _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _type), _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _sdk));
@@ -117,4 +117,4 @@ assertSIWE_fn = function(type, sdk) {
117
117
 
118
118
 
119
119
  exports.JwtBearerAuth = JwtBearerAuth;
120
- //# sourceMappingURL=chunk-XSSIP3PJ.js.map
120
+ //# sourceMappingURL=chunk-Q5KTSMRE.js.map
@@ -0,0 +1,11 @@
1
+ import {
2
+ encryption_default
3
+ } from "./chunk-K5UKU454.mjs";
4
+
5
+ // src/sdk/encryption.ts
6
+ var encryption_default2 = encryption_default;
7
+
8
+ export {
9
+ encryption_default2 as encryption_default
10
+ };
11
+ //# sourceMappingURL=chunk-QU4EXKJO.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sdk/encryption.ts"],"sourcesContent":["import encryption from '../controllers/user-storage/encryption/encryption';\n\nexport * from '../controllers/user-storage/encryption/encryption';\nexport default encryption;\n"],"mappings":";;;;;AAGA,IAAOA,sBAAQ;","names":["encryption_default"]}
@@ -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"]}