@metamask/profile-sync-controller 0.3.0 → 0.5.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 (113) hide show
  1. package/CHANGELOG.md +25 -1
  2. package/dist/{chunk-NSSHFDIS.mjs → chunk-2VEMA6OE.mjs} +2 -2
  3. package/dist/{chunk-HMRRB4EX.js → chunk-4LMFZDL4.js} +22 -13
  4. package/dist/chunk-4LMFZDL4.js.map +1 -0
  5. package/dist/{chunk-JJ5BDCKD.js → chunk-4TMLEABQ.js} +18 -16
  6. package/dist/chunk-4TMLEABQ.js.map +1 -0
  7. package/dist/{chunk-EYZFHZR2.js → chunk-5MQUI24U.js} +3 -3
  8. package/dist/{chunk-QU4EXKJO.mjs → chunk-6DAK2U35.mjs} +2 -2
  9. package/dist/{chunk-LYDHYB6I.mjs → chunk-76NMME23.mjs} +20 -11
  10. package/dist/chunk-76NMME23.mjs.map +1 -0
  11. package/dist/{chunk-T3FNDVE3.js → chunk-BKQE7DB5.js} +30 -18
  12. package/dist/chunk-BKQE7DB5.js.map +1 -0
  13. package/dist/{chunk-K5UKU454.mjs → chunk-COBJUBZE.mjs} +31 -19
  14. package/dist/chunk-COBJUBZE.mjs.map +1 -0
  15. package/dist/{chunk-5TOWF6UW.mjs → chunk-KHASG4H3.mjs} +2 -2
  16. package/dist/{chunk-4WXZXVLI.mjs → chunk-M7AUA5W7.mjs} +10 -8
  17. package/dist/{chunk-4WXZXVLI.mjs.map → chunk-M7AUA5W7.mjs.map} +1 -1
  18. package/dist/{chunk-E7Z5TCQT.mjs → chunk-MK7ABX2V.mjs} +5 -5
  19. package/dist/{chunk-E7Z5TCQT.mjs.map → chunk-MK7ABX2V.mjs.map} +1 -1
  20. package/dist/{chunk-ZYYAQJ56.mjs → chunk-NEBLEB3X.mjs} +19 -15
  21. package/dist/chunk-NEBLEB3X.mjs.map +1 -0
  22. package/dist/{chunk-AK7OTIWA.js → chunk-NIUQ34PY.js} +3 -3
  23. package/dist/{chunk-M23ZCTKE.mjs → chunk-OLFO6R7Z.mjs} +55 -20
  24. package/dist/chunk-OLFO6R7Z.mjs.map +1 -0
  25. package/dist/{chunk-LNECIW4K.js → chunk-PQMPSEVJ.js} +59 -24
  26. package/dist/chunk-PQMPSEVJ.js.map +1 -0
  27. package/dist/{chunk-YKOMKXG4.mjs → chunk-PU7MAIST.mjs} +13 -4
  28. package/dist/chunk-PU7MAIST.mjs.map +1 -0
  29. package/dist/{chunk-PQ5T4GHY.js → chunk-QCQU4BQL.js} +15 -2
  30. package/dist/chunk-QCQU4BQL.js.map +1 -0
  31. package/dist/{chunk-J7NSK6BO.mjs → chunk-TP7SP3AG.mjs} +2 -2
  32. package/dist/{chunk-4ZGRRVMI.js → chunk-UEHMUVQQ.js} +4 -4
  33. package/dist/{chunk-5EBUFNAN.mjs → chunk-UEWCUBMX.mjs} +14 -1
  34. package/dist/chunk-UEWCUBMX.mjs.map +1 -0
  35. package/dist/chunk-UHX7HJAI.js +11 -0
  36. package/dist/{chunk-ZMQRPWJN.js → chunk-UIRAMHNM.js} +12 -12
  37. package/dist/chunk-UIRAMHNM.js.map +1 -0
  38. package/dist/{chunk-WAFY3R2F.js → chunk-VWDRFRJU.js} +27 -23
  39. package/dist/chunk-VWDRFRJU.js.map +1 -0
  40. package/dist/{chunk-Q5KTSMRE.js → chunk-Y45XUW33.js} +14 -5
  41. package/dist/chunk-Y45XUW33.js.map +1 -0
  42. package/dist/controllers/index.js +7 -7
  43. package/dist/controllers/index.mjs +6 -6
  44. package/dist/controllers/user-storage/UserStorageController.js +6 -6
  45. package/dist/controllers/user-storage/UserStorageController.mjs +5 -5
  46. package/dist/controllers/user-storage/encryption/encryption.js +2 -2
  47. package/dist/controllers/user-storage/encryption/encryption.mjs +1 -1
  48. package/dist/controllers/user-storage/encryption/index.js +3 -3
  49. package/dist/controllers/user-storage/encryption/index.mjs +2 -2
  50. package/dist/controllers/user-storage/index.js +7 -7
  51. package/dist/controllers/user-storage/index.mjs +6 -6
  52. package/dist/controllers/user-storage/schema.js +4 -4
  53. package/dist/controllers/user-storage/schema.mjs +3 -3
  54. package/dist/controllers/user-storage/services.js +5 -5
  55. package/dist/controllers/user-storage/services.mjs +4 -4
  56. package/dist/index.js +13 -13
  57. package/dist/index.mjs +12 -12
  58. package/dist/sdk/authentication-jwt-bearer/flow-srp.js +3 -3
  59. package/dist/sdk/authentication-jwt-bearer/flow-srp.mjs +2 -2
  60. package/dist/sdk/authentication.js +4 -4
  61. package/dist/sdk/authentication.mjs +3 -3
  62. package/dist/sdk/encryption.js +3 -3
  63. package/dist/sdk/encryption.mjs +2 -2
  64. package/dist/sdk/index.js +12 -10
  65. package/dist/sdk/index.mjs +13 -11
  66. package/dist/sdk/user-storage.js +6 -6
  67. package/dist/sdk/user-storage.mjs +5 -5
  68. package/dist/sdk/utils/messaging-signing-snap-requests.js +4 -2
  69. package/dist/sdk/utils/messaging-signing-snap-requests.mjs +5 -3
  70. package/dist/tsconfig.build.tsbuildinfo +1 -1
  71. package/dist/types/controllers/user-storage/UserStorageController.d.ts +5 -3
  72. package/dist/types/controllers/user-storage/UserStorageController.d.ts.map +1 -1
  73. package/dist/types/controllers/user-storage/__fixtures__/mockResponses.d.ts +4 -4
  74. package/dist/types/controllers/user-storage/__fixtures__/mockResponses.d.ts.map +1 -1
  75. package/dist/types/controllers/user-storage/__fixtures__/mockServices.d.ts +2 -2
  76. package/dist/types/controllers/user-storage/__fixtures__/mockServices.d.ts.map +1 -1
  77. package/dist/types/controllers/user-storage/__fixtures__/mockStorage.d.ts +1 -1
  78. package/dist/types/controllers/user-storage/__fixtures__/mockStorage.d.ts.map +1 -1
  79. package/dist/types/controllers/user-storage/encryption/encryption.d.ts +3 -2
  80. package/dist/types/controllers/user-storage/encryption/encryption.d.ts.map +1 -1
  81. package/dist/types/controllers/user-storage/services.d.ts +3 -0
  82. package/dist/types/controllers/user-storage/services.d.ts.map +1 -1
  83. package/dist/types/sdk/__fixtures__/mock-userstorage.d.ts +5 -5
  84. package/dist/types/sdk/__fixtures__/mock-userstorage.d.ts.map +1 -1
  85. package/dist/types/sdk/authentication.d.ts +1 -0
  86. package/dist/types/sdk/authentication.d.ts.map +1 -1
  87. package/dist/types/sdk/user-storage.d.ts.map +1 -1
  88. package/dist/types/sdk/utils/messaging-signing-snap-requests.d.ts +7 -0
  89. package/dist/types/sdk/utils/messaging-signing-snap-requests.d.ts.map +1 -1
  90. package/package.json +1 -1
  91. package/dist/chunk-5EBUFNAN.mjs.map +0 -1
  92. package/dist/chunk-HMRRB4EX.js.map +0 -1
  93. package/dist/chunk-JJ5BDCKD.js.map +0 -1
  94. package/dist/chunk-K5UKU454.mjs.map +0 -1
  95. package/dist/chunk-LDYHGAP4.js +0 -11
  96. package/dist/chunk-LNECIW4K.js.map +0 -1
  97. package/dist/chunk-LYDHYB6I.mjs.map +0 -1
  98. package/dist/chunk-M23ZCTKE.mjs.map +0 -1
  99. package/dist/chunk-PQ5T4GHY.js.map +0 -1
  100. package/dist/chunk-Q5KTSMRE.js.map +0 -1
  101. package/dist/chunk-T3FNDVE3.js.map +0 -1
  102. package/dist/chunk-WAFY3R2F.js.map +0 -1
  103. package/dist/chunk-YKOMKXG4.mjs.map +0 -1
  104. package/dist/chunk-ZMQRPWJN.js.map +0 -1
  105. package/dist/chunk-ZYYAQJ56.mjs.map +0 -1
  106. /package/dist/{chunk-NSSHFDIS.mjs.map → chunk-2VEMA6OE.mjs.map} +0 -0
  107. /package/dist/{chunk-EYZFHZR2.js.map → chunk-5MQUI24U.js.map} +0 -0
  108. /package/dist/{chunk-QU4EXKJO.mjs.map → chunk-6DAK2U35.mjs.map} +0 -0
  109. /package/dist/{chunk-5TOWF6UW.mjs.map → chunk-KHASG4H3.mjs.map} +0 -0
  110. /package/dist/{chunk-AK7OTIWA.js.map → chunk-NIUQ34PY.js.map} +0 -0
  111. /package/dist/{chunk-J7NSK6BO.mjs.map → chunk-TP7SP3AG.mjs.map} +0 -0
  112. /package/dist/{chunk-4ZGRRVMI.js.map → chunk-UEHMUVQQ.js.map} +0 -0
  113. /package/dist/{chunk-LDYHGAP4.js.map → chunk-UHX7HJAI.js.map} +0 -0
@@ -9,10 +9,10 @@ var _chunkYHGWG3EQjs = require('./chunk-YHGWG3EQ.js');
9
9
 
10
10
 
11
11
 
12
- var _chunkHMRRB4EXjs = require('./chunk-HMRRB4EX.js');
12
+ var _chunk4LMFZDL4js = require('./chunk-4LMFZDL4.js');
13
13
 
14
14
 
15
- var _chunkT3FNDVE3js = require('./chunk-T3FNDVE3.js');
15
+ var _chunkBKQE7DB5js = require('./chunk-BKQE7DB5.js');
16
16
 
17
17
 
18
18
 
@@ -37,14 +37,20 @@ var metadata = {
37
37
  anonymous: false
38
38
  }
39
39
  };
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;
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;
41
41
  var UserStorageController = class extends _basecontroller.BaseController {
42
- constructor(params) {
42
+ constructor({
43
+ messenger,
44
+ state,
45
+ env,
46
+ getMetaMetricsState,
47
+ nativeScryptCrypto
48
+ }) {
43
49
  super({
44
- messenger: params.messenger,
50
+ messenger,
45
51
  metadata,
46
52
  name: controllerName,
47
- state: { ...defaultState, ...params.state }
53
+ state: { ...defaultState, ...state }
48
54
  });
49
55
  /**
50
56
  * Constructor helper for registering this controller's messaging system
@@ -100,6 +106,29 @@ var UserStorageController = class extends _basecontroller.BaseController {
100
106
  // This is replaced with the actual value in the constructor
101
107
  // We will remove this once the feature will be released
102
108
  isAccountSyncingEnabled: false,
109
+ isAccountSyncingInProgress: false,
110
+ setupAccountSyncingSubscriptions: () => {
111
+ this.messagingSystem.subscribe(
112
+ "AccountsController:accountAdded",
113
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
114
+ async (account) => {
115
+ if (_chunkIGY2S5BCjs.__privateGet.call(void 0, this, _accounts).isAccountSyncingInProgress) {
116
+ return;
117
+ }
118
+ await this.saveInternalAccountToUserStorage(account.address);
119
+ }
120
+ );
121
+ this.messagingSystem.subscribe(
122
+ "AccountsController:accountRenamed",
123
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
124
+ async (account) => {
125
+ if (_chunkIGY2S5BCjs.__privateGet.call(void 0, this, _accounts).isAccountSyncingInProgress) {
126
+ return;
127
+ }
128
+ await this.saveInternalAccountToUserStorage(account.address);
129
+ }
130
+ );
131
+ },
103
132
  getInternalAccountByAddress: async (address) => {
104
133
  return this.messagingSystem.call(
105
134
  "AccountsController:getAccountByAddress",
@@ -163,26 +192,24 @@ var UserStorageController = class extends _basecontroller.BaseController {
163
192
  "KeyringController:getState"
164
193
  );
165
194
  _chunkIGY2S5BCjs.__privateSet.call(void 0, this, _isUnlocked, isUnlocked);
166
- this.messagingSystem.subscribe(
167
- "KeyringController:unlock",
168
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
169
- async () => {
170
- _chunkIGY2S5BCjs.__privateSet.call(void 0, this, _isUnlocked, true);
171
- await this.syncInternalAccountsWithUserStorage();
172
- }
173
- );
195
+ this.messagingSystem.subscribe("KeyringController:unlock", () => {
196
+ _chunkIGY2S5BCjs.__privateSet.call(void 0, this, _isUnlocked, true);
197
+ });
174
198
  this.messagingSystem.subscribe("KeyringController:lock", () => {
175
199
  _chunkIGY2S5BCjs.__privateSet.call(void 0, this, _isUnlocked, false);
176
200
  });
177
201
  }
178
202
  });
203
+ _chunkIGY2S5BCjs.__privateAdd.call(void 0, this, _nativeScryptCrypto, void 0);
179
204
  _chunkIGY2S5BCjs.__privateAdd.call(void 0, this, __snapSignMessageCache, {});
180
205
  _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _accounts).isAccountSyncingEnabled = Boolean(
181
- params.env?.isAccountSyncingEnabled
206
+ env?.isAccountSyncingEnabled
182
207
  );
183
- this.getMetaMetricsState = params.getMetaMetricsState;
208
+ this.getMetaMetricsState = getMetaMetricsState;
184
209
  _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _keyringController).setupLockedStateSubscriptions();
185
210
  _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _registerMessageHandlers, registerMessageHandlers_fn).call(this);
211
+ _chunkIGY2S5BCjs.__privateSet.call(void 0, this, _nativeScryptCrypto, nativeScryptCrypto);
212
+ _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _accounts).setupAccountSyncingSubscriptions();
186
213
  }
187
214
  async enableProfileSyncing() {
188
215
  try {
@@ -245,10 +272,11 @@ var UserStorageController = class extends _basecontroller.BaseController {
245
272
  async performGetStorage(path) {
246
273
  _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _assertProfileSyncingEnabled, assertProfileSyncingEnabled_fn).call(this);
247
274
  const { bearerToken, storageKey } = await _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _getStorageKeyAndBearerToken, getStorageKeyAndBearerToken_fn).call(this);
248
- const result = await _chunkHMRRB4EXjs.getUserStorage.call(void 0, {
275
+ const result = await _chunk4LMFZDL4js.getUserStorage.call(void 0, {
249
276
  path,
250
277
  bearerToken,
251
- storageKey
278
+ storageKey,
279
+ nativeScryptCrypto: _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _nativeScryptCrypto)
252
280
  });
253
281
  return result;
254
282
  }
@@ -262,10 +290,11 @@ var UserStorageController = class extends _basecontroller.BaseController {
262
290
  async performGetStorageAllFeatureEntries(path) {
263
291
  _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _assertProfileSyncingEnabled, assertProfileSyncingEnabled_fn).call(this);
264
292
  const { bearerToken, storageKey } = await _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _getStorageKeyAndBearerToken, getStorageKeyAndBearerToken_fn).call(this);
265
- const result = await _chunkHMRRB4EXjs.getUserStorageAllFeatureEntries.call(void 0, {
293
+ const result = await _chunk4LMFZDL4js.getUserStorageAllFeatureEntries.call(void 0, {
266
294
  path,
267
295
  bearerToken,
268
- storageKey
296
+ storageKey,
297
+ nativeScryptCrypto: _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _nativeScryptCrypto)
269
298
  });
270
299
  return result;
271
300
  }
@@ -280,10 +309,11 @@ var UserStorageController = class extends _basecontroller.BaseController {
280
309
  async performSetStorage(path, value) {
281
310
  _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _assertProfileSyncingEnabled, assertProfileSyncingEnabled_fn).call(this);
282
311
  const { bearerToken, storageKey } = await _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _getStorageKeyAndBearerToken, getStorageKeyAndBearerToken_fn).call(this);
283
- await _chunkHMRRB4EXjs.upsertUserStorage.call(void 0, value, {
312
+ await _chunk4LMFZDL4js.upsertUserStorage.call(void 0, value, {
284
313
  path,
285
314
  bearerToken,
286
- storageKey
315
+ storageKey,
316
+ nativeScryptCrypto: _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _nativeScryptCrypto)
287
317
  });
288
318
  }
289
319
  /**
@@ -307,6 +337,7 @@ var UserStorageController = class extends _basecontroller.BaseController {
307
337
  }
308
338
  try {
309
339
  _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _assertProfileSyncingEnabled, assertProfileSyncingEnabled_fn).call(this);
340
+ _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _accounts).isAccountSyncingInProgress = true;
310
341
  const userStorageAccountsList = await _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _accounts).getUserStorageAccountsList();
311
342
  if (!userStorageAccountsList || !userStorageAccountsList.length) {
312
343
  await _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _accounts).saveInternalAccountsListToUserStorage();
@@ -392,6 +423,8 @@ var UserStorageController = class extends _basecontroller.BaseController {
392
423
  throw new Error(
393
424
  `${controllerName} - failed to sync user storage accounts list - ${errorMessage}`
394
425
  );
426
+ } finally {
427
+ _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _accounts).isAccountSyncingInProgress = false;
395
428
  }
396
429
  }
397
430
  /**
@@ -403,6 +436,7 @@ var UserStorageController = class extends _basecontroller.BaseController {
403
436
  return;
404
437
  }
405
438
  try {
439
+ _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _assertProfileSyncingEnabled, assertProfileSyncingEnabled_fn).call(this);
406
440
  await _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _accounts).saveInternalAccountToUserStorage(address);
407
441
  } catch (e) {
408
442
  const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);
@@ -417,6 +451,7 @@ _accounts = new WeakMap();
417
451
  _notificationServices = new WeakMap();
418
452
  _isUnlocked = new WeakMap();
419
453
  _keyringController = new WeakMap();
454
+ _nativeScryptCrypto = new WeakMap();
420
455
  _registerMessageHandlers = new WeakSet();
421
456
  registerMessageHandlers_fn = function() {
422
457
  this.messagingSystem.registerActionHandler(
@@ -476,7 +511,7 @@ createStorageKey_fn = async function() {
476
511
  throw new Error("UserStorageController - unable to create storage key");
477
512
  }
478
513
  const storageKeySignature = await _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _snapSignMessage, snapSignMessage_fn).call(this, `metamask:${id}`);
479
- const storageKey = _chunkT3FNDVE3js.createSHA256Hash.call(void 0, storageKeySignature);
514
+ const storageKey = _chunkBKQE7DB5js.createSHA256Hash.call(void 0, storageKeySignature);
480
515
  return storageKey;
481
516
  };
482
517
  __snapSignMessageCache = new WeakMap();
@@ -508,4 +543,4 @@ setIsProfileSyncingUpdateLoading_fn = function(isProfileSyncingUpdateLoading) {
508
543
 
509
544
 
510
545
  exports.defaultState = defaultState; exports.UserStorageController = UserStorageController;
511
- //# sourceMappingURL=chunk-LNECIW4K.js.map
546
+ //# sourceMappingURL=chunk-PQMPSEVJ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/controllers/user-storage/UserStorageController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAaA,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;AAjGA;AA8MA,IAAqB,wBAArB,cAAmD,eAIjD;AAAA,EAyJA,YAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,GAQG;AACD,UAAM;AAAA,MACJ;AAAA,MACA;AAAA,MACA,MAAM;AAAA,MACN,OAAO,EAAE,GAAG,cAAc,GAAG,MAAM;AAAA,IACrC,CAAC;AAiBH;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;AArcA,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,MAA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AAuB,OAAO;AAAA,EAC5C;AAEA,MAAI,CAAC,mBAAK,cAAa;AACrB,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM,SAAU,MAAM,KAAK,gBAAgB;AAAA,IACzC;AAAA,IACA,6BAA6B,OAAO;AAAA,EACtC;AAEA,qBAAK,wBAAuB,OAAO,IAAI;AAEvC,SAAO;AACT;AAEA;AAAA,sCAAiC,SAC/B,+BACM;AACN,OAAK,OAAO,CAAC,UAAU;AACrB,UAAM,gCAAgC;AAAA,EACxC,CAAC;AACH","sourcesContent":["import type {\n AccountsControllerListAccountsAction,\n AccountsControllerUpdateAccountMetadataAction,\n AccountsControllerGetAccountByAddressAction,\n AccountsControllerAccountRenamedEvent,\n AccountsControllerAccountAddedEvent,\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 | AccountsControllerAccountAddedEvent\n | AccountsControllerAccountRenamedEvent;\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 isAccountSyncingInProgress: false,\n setupAccountSyncingSubscriptions: () => {\n this.messagingSystem.subscribe(\n 'AccountsController:accountAdded',\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async (account) => {\n if (this.#accounts.isAccountSyncingInProgress) {\n return;\n }\n await this.saveInternalAccountToUserStorage(account.address);\n },\n );\n\n this.messagingSystem.subscribe(\n 'AccountsController:accountRenamed',\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async (account) => {\n if (this.#accounts.isAccountSyncingInProgress) {\n return;\n }\n await this.saveInternalAccountToUserStorage(account.address);\n },\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('KeyringController:unlock', () => {\n this.#isUnlocked = true;\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 };\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\n this.getMetaMetricsState = getMetaMetricsState;\n this.#keyringController.setupLockedStateSubscriptions();\n this.#registerMessageHandlers();\n this.#nativeScryptCrypto = nativeScryptCrypto;\n this.#accounts.setupAccountSyncingSubscriptions();\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 try {\n this.#assertProfileSyncingEnabled();\n\n this.#accounts.isAccountSyncingInProgress = true;\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 } finally {\n this.#accounts.isAccountSyncingInProgress = false;\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 this.#assertProfileSyncingEnabled();\n\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"]}
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-2CWF7ZTL.mjs";
4
4
  import {
5
5
  SRPJwtBearerAuth
6
- } from "./chunk-J7NSK6BO.mjs";
6
+ } from "./chunk-TP7SP3AG.mjs";
7
7
  import {
8
8
  getNonce,
9
9
  pairIdentifiers
@@ -12,8 +12,9 @@ import {
12
12
  getMetaMaskProviderEIP6963
13
13
  } from "./chunk-5XSXZTED.mjs";
14
14
  import {
15
- connectSnap
16
- } from "./chunk-5EBUFNAN.mjs";
15
+ connectSnap,
16
+ isSnapConnected
17
+ } from "./chunk-UEWCUBMX.mjs";
17
18
  import {
18
19
  PairError,
19
20
  UnsupportedAuthTypeError
@@ -56,6 +57,14 @@ var JwtBearerAuth = class {
56
57
  const res = await connectSnap(provider);
57
58
  return res;
58
59
  }
60
+ async isSnapConnected() {
61
+ const provider = await getMetaMaskProviderEIP6963();
62
+ if (!provider) {
63
+ return false;
64
+ }
65
+ const isConnected = await isSnapConnected(provider);
66
+ return isConnected;
67
+ }
59
68
  async getUserProfile() {
60
69
  return await __privateGet(this, _sdk).getUserProfile();
61
70
  }
@@ -117,4 +126,4 @@ assertSIWE_fn = function(type, sdk) {
117
126
  export {
118
127
  JwtBearerAuth
119
128
  };
120
- //# sourceMappingURL=chunk-YKOMKXG4.mjs.map
129
+ //# sourceMappingURL=chunk-PU7MAIST.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sdk/authentication.ts"],"sourcesContent":["import { SIWEJwtBearerAuth } from './authentication-jwt-bearer/flow-siwe';\nimport { SRPJwtBearerAuth } from './authentication-jwt-bearer/flow-srp';\nimport {\n getNonce,\n pairIdentifiers,\n} from './authentication-jwt-bearer/services';\nimport type { UserProfile, Pair } from './authentication-jwt-bearer/types';\nimport { AuthType } from './authentication-jwt-bearer/types';\nimport type { Env } from './env';\nimport { PairError, UnsupportedAuthTypeError } from './errors';\nimport { getMetaMaskProviderEIP6963 } from './utils/eip-6963-metamask-provider';\nimport {\n connectSnap,\n isSnapConnected,\n} from './utils/messaging-signing-snap-requests';\n\n// Computing the Classes, so we only get back the public methods for the interface.\n// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/naming-convention\ntype Compute<T> = T extends infer U ? { [K in keyof U]: U[K] } : never;\ntype SIWEInterface = Compute<SIWEJwtBearerAuth>;\ntype SRPInterface = Compute<SRPJwtBearerAuth>;\n\ntype SiweParams = ConstructorParameters<typeof SIWEJwtBearerAuth>;\ntype SRPParams = ConstructorParameters<typeof SRPJwtBearerAuth>;\ntype JwtBearerAuthParams = SiweParams | SRPParams;\n\nexport class JwtBearerAuth implements SIWEInterface, SRPInterface {\n #type: AuthType;\n\n #env: Env;\n\n #sdk: SIWEJwtBearerAuth | SRPJwtBearerAuth;\n\n constructor(...args: JwtBearerAuthParams) {\n this.#type = args[0].type;\n this.#env = args[0].env;\n\n if (args[0].type === AuthType.SRP) {\n this.#sdk = new SRPJwtBearerAuth(args[0], args[1]);\n return;\n }\n\n if (args[0].type === AuthType.SiWE) {\n this.#sdk = new SIWEJwtBearerAuth(args[0], args[1]);\n return;\n }\n\n throw new UnsupportedAuthTypeError('unsupported auth type');\n }\n\n async getAccessToken(): Promise<string> {\n return await this.#sdk.getAccessToken();\n }\n\n async connectSnap(): Promise<string> {\n const provider = await getMetaMaskProviderEIP6963();\n if (!provider) {\n throw new Error('failed to get MetaMaskProviderEIP6963 provider');\n }\n const res = await connectSnap(provider);\n return res;\n }\n\n async isSnapConnected(): Promise<boolean> {\n const provider = await getMetaMaskProviderEIP6963();\n if (!provider) {\n return false;\n }\n\n const isConnected = await isSnapConnected(provider);\n return isConnected;\n }\n\n async getUserProfile(): Promise<UserProfile> {\n return await this.#sdk.getUserProfile();\n }\n\n async getIdentifier(): Promise<string> {\n return await this.#sdk.getIdentifier();\n }\n\n async signMessage(message: string): Promise<string> {\n return await this.#sdk.signMessage(message);\n }\n\n async pairIdentifiers(pairing: Pair[]): Promise<void> {\n const profile = await this.getUserProfile();\n const n = await getNonce(profile.profileId, this.#env);\n\n const logins = await Promise.all(\n pairing.map(async (p) => {\n try {\n const raw = `metamask:${n.nonce}:${p.identifier}`;\n const sig = await p.signMessage(raw);\n return {\n signature: sig,\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n raw_message: raw,\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n encrypted_storage_key: p.encryptedStorageKey,\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n identifier_type: p.identifierType,\n };\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n throw new PairError(\n `failed to sign pairing message: ${errorMessage}`,\n );\n }\n }),\n );\n\n const accessToken = await this.getAccessToken();\n await pairIdentifiers(n.nonce, logins, accessToken, this.#env);\n }\n\n prepare(signer: {\n address: string;\n chainId: number;\n signMessage: (message: string) => Promise<string>;\n domain: string;\n }): void {\n this.#assertSIWE(this.#type, this.#sdk);\n this.#sdk.prepare(signer);\n }\n\n #assertSIWE(\n type: AuthType,\n sdk: SIWEJwtBearerAuth | SRPJwtBearerAuth,\n ): asserts sdk is SIWEJwtBearerAuth {\n if (type === AuthType.SiWE) {\n return;\n }\n\n throw new UnsupportedAuthTypeError(\n 'This method is only available via SIWE auth type',\n );\n }\n}\n\nexport { SIWEJwtBearerAuth } from './authentication-jwt-bearer/flow-siwe';\nexport { SRPJwtBearerAuth } from './authentication-jwt-bearer/flow-srp';\nexport * from './authentication-jwt-bearer/types';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AA2BO,IAAM,gBAAN,MAA2D;AAAA,EAOhE,eAAe,MAA2B;AAkG1C;AAxGA;AAEA;AAEA;AAGE,uBAAK,OAAQ,KAAK,CAAC,EAAE;AACrB,uBAAK,MAAO,KAAK,CAAC,EAAE;AAEpB,QAAI,KAAK,CAAC,EAAE,0BAAuB;AACjC,yBAAK,MAAO,IAAI,iBAAiB,KAAK,CAAC,GAAG,KAAK,CAAC,CAAC;AACjD;AAAA,IACF;AAEA,QAAI,KAAK,CAAC,EAAE,4BAAwB;AAClC,yBAAK,MAAO,IAAI,kBAAkB,KAAK,CAAC,GAAG,KAAK,CAAC,CAAC;AAClD;AAAA,IACF;AAEA,UAAM,IAAI,yBAAyB,uBAAuB;AAAA,EAC5D;AAAA,EAEA,MAAM,iBAAkC;AACtC,WAAO,MAAM,mBAAK,MAAK,eAAe;AAAA,EACxC;AAAA,EAEA,MAAM,cAA+B;AACnC,UAAM,WAAW,MAAM,2BAA2B;AAClD,QAAI,CAAC,UAAU;AACb,YAAM,IAAI,MAAM,gDAAgD;A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AAAA,EAEA,QAAQ,QAKC;AACP,0BAAK,4BAAL,WAAiB,mBAAK,QAAO,mBAAK;AAClC,uBAAK,MAAK,QAAQ,MAAM;AAAA,EAC1B;AAcF;AApHE;AAEA;AAEA;AAoGA;AAAA,gBAAW,SACT,MACA,KACkC;AAClC,MAAI,4BAAwB;AAC1B;AAAA,EACF;AAEA,QAAM,IAAI;AAAA,IACR;AAAA,EACF;AACF;","names":[]}
@@ -16,6 +16,18 @@ async function getSnaps(provider) {
16
16
  });
17
17
  return result;
18
18
  }
19
+ async function isSnapConnected(provider) {
20
+ try {
21
+ const snaps = await getSnaps(provider);
22
+ if (!snaps) {
23
+ return false;
24
+ }
25
+ return Object.keys(snaps).includes(SNAP_ORIGIN);
26
+ } catch (e) {
27
+ console.error("Failed to determine if snap is connected", e);
28
+ return false;
29
+ }
30
+ }
19
31
  async function getSnap(provider) {
20
32
  try {
21
33
  const snaps = await getSnaps(provider);
@@ -51,5 +63,6 @@ var MESSAGE_SIGNING_SNAP = {
51
63
 
52
64
 
53
65
 
54
- exports.SNAP_ORIGIN = SNAP_ORIGIN; exports.connectSnap = connectSnap; exports.getSnaps = getSnaps; exports.getSnap = getSnap; exports.MESSAGE_SIGNING_SNAP = MESSAGE_SIGNING_SNAP;
55
- //# sourceMappingURL=chunk-PQ5T4GHY.js.map
66
+
67
+ exports.SNAP_ORIGIN = SNAP_ORIGIN; exports.connectSnap = connectSnap; exports.getSnaps = getSnaps; exports.isSnapConnected = isSnapConnected; exports.getSnap = getSnap; exports.MESSAGE_SIGNING_SNAP = MESSAGE_SIGNING_SNAP;
68
+ //# sourceMappingURL=chunk-QCQU4BQL.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sdk/utils/messaging-signing-snap-requests.ts"],"names":[],"mappings":";AAUO,IAAM,cAAc;AAE3B,IAAM,YAAY,CAAC,SAAe,KAAK,OAAO;AAQ9C,eAAsB,YAAY,UAA4C;AAC5E,QAAM,SAAiB,MAAM,SAAS,QAAQ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ider } from 'ethers';\n\nexport type Snap = {\n permissionName: string;\n id: string;\n version: string;\n initialPermissions: Record<string, unknown>;\n};\nexport type GetSnapsResponse = Record<string, Snap>;\n\nexport const SNAP_ORIGIN = 'npm:@metamask/message-signing-snap';\n\nconst foundSnap = (snap: Snap) => snap.id === SNAP_ORIGIN;\n\n/**\n * Requests Connection to the Message Signing Snap\n *\n * @param provider - MetaMask Wallet Provider\n * @returns snap connect result\n */\nexport async function connectSnap(provider: Eip1193Provider): Promise<string> {\n const result: string = await provider.request({\n method: 'wallet_requestSnaps',\n params: {\n [SNAP_ORIGIN]: {},\n },\n });\n\n return result;\n}\n\n/**\n * Gets Snaps from a MetaMask Wallet\n *\n * @param provider - MetaMask Wallet Provider\n * @returns All currently installed snaps.\n */\nexport async function getSnaps(\n provider: Eip1193Provider,\n): Promise<GetSnapsResponse> {\n const result: GetSnapsResponse = await provider.request({\n method: 'wallet_getSnaps',\n });\n\n return result;\n}\n\n/**\n * Check if snap is connected\n *\n * @param provider - MetaMask Wallet Provider\n * @returns if snap is connected\n */\nexport async function isSnapConnected(\n provider: Eip1193Provider,\n): Promise<boolean> {\n try {\n const snaps = await getSnaps(provider);\n if (!snaps) {\n return false;\n }\n return Object.keys(snaps).includes(SNAP_ORIGIN);\n } catch (e) {\n console.error('Failed to determine if snap is connected', e);\n return false;\n }\n}\n\n/**\n * Will return the message signing snap if installed\n * @param provider - MetaMask Wallet Provider\n */\nexport async function getSnap(\n provider: Eip1193Provider,\n): Promise<Snap | undefined> {\n try {\n const snaps = await getSnaps(provider);\n return Object.values(snaps ?? {}).find((snap) => foundSnap(snap));\n } catch (e) {\n console.error('Failed to obtain installed snap', e);\n return undefined;\n }\n}\n\nexport const MESSAGE_SIGNING_SNAP = {\n async getPublicKey(provider: Eip1193Provider) {\n const publicKey: string = await provider.request({\n method: 'wallet_invokeSnap',\n params: { snapId: SNAP_ORIGIN, request: { method: 'getPublicKey' } },\n });\n\n return publicKey;\n },\n\n async signMessage(provider: Eip1193Provider, message: `metamask:${string}`) {\n const signedMessage: string = await provider?.request({\n method: 'wallet_invokeSnap',\n params: {\n snapId: SNAP_ORIGIN,\n request: { method: 'signMessage', params: { message } },\n },\n });\n\n return signedMessage;\n },\n};\n"]}
@@ -8,7 +8,7 @@ import {
8
8
  } from "./chunk-5XSXZTED.mjs";
9
9
  import {
10
10
  MESSAGE_SIGNING_SNAP
11
- } from "./chunk-5EBUFNAN.mjs";
11
+ } from "./chunk-UEWCUBMX.mjs";
12
12
  import {
13
13
  validateLoginResponse
14
14
  } from "./chunk-QDGLIUUS.mjs";
@@ -130,4 +130,4 @@ createSrpLoginRawMessage_fn = function(nonce, publicKey) {
130
130
  export {
131
131
  SRPJwtBearerAuth
132
132
  };
133
- //# sourceMappingURL=chunk-J7NSK6BO.mjs.map
133
+ //# sourceMappingURL=chunk-TP7SP3AG.mjs.map
@@ -8,7 +8,7 @@ var _chunkLLG4D2SCjs = require('./chunk-LLG4D2SC.js');
8
8
  var _chunkRG4II6WHjs = require('./chunk-RG4II6WH.js');
9
9
 
10
10
 
11
- var _chunkPQ5T4GHYjs = require('./chunk-PQ5T4GHY.js');
11
+ var _chunkQCQU4BQLjs = require('./chunk-QCQU4BQL.js');
12
12
 
13
13
 
14
14
  var _chunkDRB2MN4Tjs = require('./chunk-DRB2MN4T.js');
@@ -29,7 +29,7 @@ var defaultEIP6963SigningOptions = {
29
29
  if (!provider) {
30
30
  throw new (0, _chunkMBTBE4P5js.ValidationError)("No MetaMask wallet connected");
31
31
  }
32
- return await _chunkPQ5T4GHYjs.MESSAGE_SIGNING_SNAP.getPublicKey(provider);
32
+ return await _chunkQCQU4BQLjs.MESSAGE_SIGNING_SNAP.getPublicKey(provider);
33
33
  },
34
34
  signMessage: async (message) => {
35
35
  const provider = await _chunkRG4II6WHjs.getMetaMaskProviderEIP6963.call(void 0, );
@@ -40,7 +40,7 @@ var defaultEIP6963SigningOptions = {
40
40
  throw new (0, _chunkMBTBE4P5js.ValidationError)('message must start with "metamask:"');
41
41
  }
42
42
  const formattedMessage = message;
43
- return await _chunkPQ5T4GHYjs.MESSAGE_SIGNING_SNAP.signMessage(provider, formattedMessage);
43
+ return await _chunkQCQU4BQLjs.MESSAGE_SIGNING_SNAP.signMessage(provider, formattedMessage);
44
44
  }
45
45
  };
46
46
  var _config, _options, _getAuthSession, getAuthSession_fn, _login, login_fn, _createSrpLoginRawMessage, createSrpLoginRawMessage_fn;
@@ -130,4 +130,4 @@ createSrpLoginRawMessage_fn = function(nonce, publicKey) {
130
130
 
131
131
 
132
132
  exports.SRPJwtBearerAuth = SRPJwtBearerAuth;
133
- //# sourceMappingURL=chunk-4ZGRRVMI.js.map
133
+ //# sourceMappingURL=chunk-UEHMUVQQ.js.map
@@ -16,6 +16,18 @@ async function getSnaps(provider) {
16
16
  });
17
17
  return result;
18
18
  }
19
+ async function isSnapConnected(provider) {
20
+ try {
21
+ const snaps = await getSnaps(provider);
22
+ if (!snaps) {
23
+ return false;
24
+ }
25
+ return Object.keys(snaps).includes(SNAP_ORIGIN);
26
+ } catch (e) {
27
+ console.error("Failed to determine if snap is connected", e);
28
+ return false;
29
+ }
30
+ }
19
31
  async function getSnap(provider) {
20
32
  try {
21
33
  const snaps = await getSnaps(provider);
@@ -49,7 +61,8 @@ export {
49
61
  SNAP_ORIGIN,
50
62
  connectSnap,
51
63
  getSnaps,
64
+ isSnapConnected,
52
65
  getSnap,
53
66
  MESSAGE_SIGNING_SNAP
54
67
  };
55
- //# sourceMappingURL=chunk-5EBUFNAN.mjs.map
68
+ //# sourceMappingURL=chunk-UEWCUBMX.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sdk/utils/messaging-signing-snap-requests.ts"],"sourcesContent":["import type { Eip1193Provider } from 'ethers';\n\nexport type Snap = {\n permissionName: string;\n id: string;\n version: string;\n initialPermissions: Record<string, unknown>;\n};\nexport type GetSnapsResponse = Record<string, Snap>;\n\nexport const SNAP_ORIGIN = 'npm:@metamask/message-signing-snap';\n\nconst foundSnap = (snap: Snap) => snap.id === SNAP_ORIGIN;\n\n/**\n * Requests Connection to the Message Signing Snap\n *\n * @param provider - MetaMask Wallet Provider\n * @returns snap connect result\n */\nexport async function connectSnap(provider: Eip1193Provider): Promise<string> {\n const result: string = await provider.request({\n method: 'wallet_requestSnaps',\n params: {\n [SNAP_ORIGIN]: {},\n },\n });\n\n return result;\n}\n\n/**\n * Gets Snaps from a MetaMask Wallet\n *\n * @param provider - MetaMask Wallet Provider\n * @returns All currently installed snaps.\n */\nexport async function getSnaps(\n provider: Eip1193Provider,\n): Promise<GetSnapsResponse> {\n const result: GetSnapsResponse = await provider.request({\n method: 'wallet_getSnaps',\n });\n\n return result;\n}\n\n/**\n * Check if snap is connected\n *\n * @param provider - MetaMask Wallet Provider\n * @returns if snap is connected\n */\nexport async function isSnapConnected(\n provider: Eip1193Provider,\n): Promise<boolean> {\n try {\n const snaps = await getSnaps(provider);\n if (!snaps) {\n return false;\n }\n return Object.keys(snaps).includes(SNAP_ORIGIN);\n } catch (e) {\n console.error('Failed to determine if snap is connected', e);\n return false;\n }\n}\n\n/**\n * Will return the message signing snap if installed\n * @param provider - MetaMask Wallet Provider\n */\nexport async function getSnap(\n provider: Eip1193Provider,\n): Promise<Snap | undefined> {\n try {\n const snaps = await getSnaps(provider);\n return Object.values(snaps ?? {}).find((snap) => foundSnap(snap));\n } catch (e) {\n console.error('Failed to obtain installed snap', e);\n return undefined;\n }\n}\n\nexport const MESSAGE_SIGNING_SNAP = {\n async getPublicKey(provider: Eip1193Provider) {\n const publicKey: string = await provider.request({\n method: 'wallet_invokeSnap',\n params: { snapId: SNAP_ORIGIN, request: { method: 'getPublicKey' } },\n });\n\n return publicKey;\n },\n\n async signMessage(provider: Eip1193Provider, message: `metamask:${string}`) {\n const signedMessage: string = await provider?.request({\n method: 'wallet_invokeSnap',\n params: {\n snapId: SNAP_ORIGIN,\n request: { method: 'signMessage', params: { message } },\n },\n });\n\n return signedMessage;\n },\n};\n"],"mappings":";AAUO,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AAE,QAAQ,eAAe,QAAQ,EAAE,QAAQ,EAAE;AAAA,MACxD;AAAA,IACF,CAAC;AAED,WAAO;AAAA,EACT;AACF;","names":[]}
@@ -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
@@ -1,12 +1,12 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
2
 
3
- var _chunkEYZFHZR2js = require('./chunk-EYZFHZR2.js');
3
+ var _chunk5MQUI24Ujs = require('./chunk-5MQUI24U.js');
4
4
 
5
5
 
6
- var _chunkLDYHGAP4js = require('./chunk-LDYHGAP4.js');
6
+ var _chunkUHX7HJAIjs = require('./chunk-UHX7HJAI.js');
7
7
 
8
8
 
9
- var _chunkT3FNDVE3js = require('./chunk-T3FNDVE3.js');
9
+ var _chunkBKQE7DB5js = require('./chunk-BKQE7DB5.js');
10
10
 
11
11
 
12
12
  var _chunkDF24ZX4Hjs = require('./chunk-DF24ZX4H.js');
@@ -53,7 +53,7 @@ var UserStorage = class {
53
53
  const storageKeySignature = await this.config.auth.signMessage(
54
54
  `metamask:${userProfile.profileId}`
55
55
  );
56
- const hashedStorageKeySignature = _chunkT3FNDVE3js.createSHA256Hash.call(void 0, storageKeySignature);
56
+ const hashedStorageKeySignature = _chunkBKQE7DB5js.createSHA256Hash.call(void 0, storageKeySignature);
57
57
  await this.options.storage?.setStorageKey(hashedStorageKeySignature);
58
58
  return hashedStorageKeySignature;
59
59
  }
@@ -63,8 +63,8 @@ upsertUserStorage_fn = async function(path, data) {
63
63
  try {
64
64
  const headers = await _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _getAuthorizationHeader, getAuthorizationHeader_fn).call(this);
65
65
  const storageKey = await this.getStorageKey();
66
- const encryptedData = _chunkLDYHGAP4js.encryption_default.encryptString(data, storageKey);
67
- const encryptedPath = _chunkEYZFHZR2js.createEntryPath.call(void 0, path, storageKey);
66
+ const encryptedData = _chunkUHX7HJAIjs.encryption_default.encryptString(data, storageKey);
67
+ const encryptedPath = _chunk5MQUI24Ujs.createEntryPath.call(void 0, path, storageKey);
68
68
  const url = new URL(STORAGE_URL(this.env, encryptedPath));
69
69
  const response = await fetch(url.toString(), {
70
70
  method: "PUT",
@@ -95,7 +95,7 @@ getUserStorage_fn = async function(path) {
95
95
  try {
96
96
  const headers = await _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _getAuthorizationHeader, getAuthorizationHeader_fn).call(this);
97
97
  const storageKey = await this.getStorageKey();
98
- const encryptedPath = _chunkEYZFHZR2js.createEntryPath.call(void 0, path, storageKey);
98
+ const encryptedPath = _chunk5MQUI24Ujs.createEntryPath.call(void 0, path, storageKey);
99
99
  const url = new URL(STORAGE_URL(this.env, encryptedPath));
100
100
  const response = await fetch(url.toString(), {
101
101
  headers: {
@@ -115,7 +115,7 @@ getUserStorage_fn = async function(path) {
115
115
  );
116
116
  }
117
117
  const { Data: encryptedData } = await response.json();
118
- return _chunkLDYHGAP4js.encryption_default.decryptString(encryptedData, storageKey);
118
+ return _chunkUHX7HJAIjs.encryption_default.decryptString(encryptedData, storageKey);
119
119
  } catch (e) {
120
120
  if (e instanceof _chunkMBTBE4P5js.NotFoundError) {
121
121
  throw e;
@@ -155,9 +155,9 @@ getUserStorageAllFeatureEntries_fn = async function(path) {
155
155
  if (!entry.Data) {
156
156
  return [];
157
157
  }
158
- return _chunkLDYHGAP4js.encryption_default.decryptString(entry.Data, storageKey);
158
+ return _chunkUHX7HJAIjs.encryption_default.decryptString(entry.Data, storageKey);
159
159
  });
160
- return decryptedData;
160
+ return (await Promise.allSettled(decryptedData)).map((d) => d.status === "fulfilled" ? d.value : void 0).filter((d) => d !== void 0);
161
161
  } catch (e) {
162
162
  if (e instanceof _chunkMBTBE4P5js.NotFoundError) {
163
163
  throw e;
@@ -170,7 +170,7 @@ getUserStorageAllFeatureEntries_fn = async function(path) {
170
170
  };
171
171
  _createEntryKey = new WeakSet();
172
172
  createEntryKey_fn = function(key, storageKey) {
173
- const hashedKey = _chunkT3FNDVE3js.createSHA256Hash.call(void 0, key + storageKey);
173
+ const hashedKey = _chunkBKQE7DB5js.createSHA256Hash.call(void 0, key + storageKey);
174
174
  return hashedKey;
175
175
  };
176
176
  _getAuthorizationHeader = new WeakSet();
@@ -183,4 +183,4 @@ getAuthorizationHeader_fn = async function() {
183
183
 
184
184
 
185
185
  exports.STORAGE_URL = STORAGE_URL; exports.UserStorage = UserStorage;
186
- //# sourceMappingURL=chunk-ZMQRPWJN.js.map
186
+ //# sourceMappingURL=chunk-UIRAMHNM.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sdk/user-storage.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAYO,IAAM,cAAc,CAAC,KAAU,kBACpC,GAAG,WAAW,GAAG,EAAE,iBAAiB,uBAAuB,aAAa;AAb1E;AAkCO,IAAM,cAAN,MAAkB;AAAA,EAOvB,YAAY,QAA2B,SAA6B;AAsCpE,uBAAM;AAwCN,uBAAM;AA+CN,uBAAM;AA4DN;AAOA;AAAA;AAAA,uBAAM;AA/LJ,SAAK,MAAM,OAAO;AAClB,SAAK,SAAS;AACd,SAAK,UAAU;AAAA,EACjB;AAAA,EAEA,MAAM,QACJ,MACA,OACe;AACf,UAAM,sBAAK,0CAAL,WAAwB,MAAM;AAAA,EACtC;AAAA,EAEA,MAAM,QAAQ,MAAyD;AACrE,WAAO,sBAAK,oCAAL,WAAqB;AAAA,EAC9B;AAAA,EAEA,MAAM,mBACJ,MAC0B;AAC1B,WAAO,sBAAK,sEAAL,WAAsC;AAAA,EAC/C;AAAA,EAEA,MAAM,gBAAiC;AACrC,UAAM,aAAa,MAAM,KAAK,QAAQ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IAAI,cAAc,+BAA+B,IAAI,IAAI;AAAA,IACjE;AAEA,QAAI,CAAC,SAAS,IAAI;AAChB,YAAM,eAAgB,MAAM,SAAS,KAAK;AAC1C,YAAM,IAAI;AAAA,QACR,uBAAuB,aAAa,OAAO,YAAY,aAAa,KAAK;AAAA,MAC3E;AAAA,IACF;AAEA,UAAM,cACJ,MAAM,SAAS,KAAK;AAEtB,QAAI,CAAC,MAAM,QAAQ,WAAW,GAAG;AAC/B,aAAO;AAAA,IACT;AAEA,UAAM,gBAAgB,YAAY,QAAQ,CAAC,UAAU;AACnD,UAAI,CAAC,MAAM,MAAM;AACf,eAAO,CAAC;AAAA,MACV;AAEA,aAAO,mBAAW,cAAc,MAAM,MAAM,UAAU;AAAA,IACxD,CAAC;AAED,YAAQ,MAAM,QAAQ,WAAW,aAAa,GAC3C,IAAI,CAAC,MAAO,EAAE,WAAW,cAAc,EAAE,QAAQ,MAAU,EAC3D,OAAO,CAAC,MAAmB,MAAM,MAAS;AAAA,EAC/C,SAAS,GAAG;AACV,QAAI,aAAa,eAAe;AAC9B,YAAM;AAAA,IACR;AAGA,UAAM,eACJ,aAAa,QAAQ,EAAE,UAAU,KAAK,UAAU,KAAK,EAAE;AAEzD,UAAM,IAAI;AAAA,MACR,wCAAwC,IAAI,MAAM,YAAY;AAAA,IAChE;AAAA,EACF;AACF;AAEA;AAAA,oBAAe,SAAC,KAAa,YAA4B;AACvD,QAAM,YAAY,iBAAiB,MAAM,UAAU;AACnD,SAAO;AACT;AAIM;AAAA,4BAAuB,iBAAuC;AAClE,QAAM,cAAc,MAAM,KAAK,OAAO,KAAK,eAAe;AAC1D,SAAO,EAAE,eAAe,UAAU,WAAW,GAAG;AAClD","sourcesContent":["import type {\n UserStoragePathWithFeatureAndKey,\n UserStoragePathWithFeatureOnly,\n} from '../controllers/user-storage/schema';\nimport { createEntryPath } from '../controllers/user-storage/schema';\nimport type { GetUserStorageAllFeatureEntriesResponse } from '../controllers/user-storage/services';\nimport type { IBaseAuth } from './authentication-jwt-bearer/types';\nimport encryption, { createSHA256Hash } from './encryption';\nimport type { Env } from './env';\nimport { getEnvUrls } from './env';\nimport { NotFoundError, UserStorageError } from './errors';\n\nexport const STORAGE_URL = (env: Env, encryptedPath: string) =>\n `${getEnvUrls(env).userStorageApiUrl}/api/v1/userstorage/${encryptedPath}`;\n\nexport type UserStorageConfig = {\n env: Env;\n auth: Pick<IBaseAuth, 'getAccessToken' | 'getUserProfile' | 'signMessage'>;\n};\n\nexport type StorageOptions = {\n getStorageKey: () => Promise<string | null>;\n setStorageKey: (val: string) => Promise<void>;\n};\n\nexport type UserStorageOptions = {\n storage?: StorageOptions;\n};\n\ntype ErrorMessage = {\n message: string;\n error: string;\n};\n\nexport class UserStorage {\n protected config: UserStorageConfig;\n\n protected options: UserStorageOptions;\n\n protected env: Env;\n\n constructor(config: UserStorageConfig, options: UserStorageOptions) {\n this.env = config.env;\n this.config = config;\n this.options = options;\n }\n\n async setItem(\n path: UserStoragePathWithFeatureAndKey,\n value: string,\n ): Promise<void> {\n await this.#upsertUserStorage(path, value);\n }\n\n async getItem(path: UserStoragePathWithFeatureAndKey): Promise<string> {\n return this.#getUserStorage(path);\n }\n\n async getAllFeatureItems(\n path: UserStoragePathWithFeatureOnly,\n ): Promise<string[] | null> {\n return this.#getUserStorageAllFeatureEntries(path);\n }\n\n async getStorageKey(): Promise<string> {\n const storageKey = await this.options.storage?.getStorageKey();\n if (storageKey) {\n return storageKey;\n }\n\n const userProfile = await this.config.auth.getUserProfile();\n const storageKeySignature = await this.config.auth.signMessage(\n `metamask:${userProfile.profileId}`,\n );\n const hashedStorageKeySignature = createSHA256Hash(storageKeySignature);\n await this.options.storage?.setStorageKey(hashedStorageKeySignature);\n return hashedStorageKeySignature;\n }\n\n async #upsertUserStorage(\n path: UserStoragePathWithFeatureAndKey,\n data: string,\n ): Promise<void> {\n try {\n const headers = await this.#getAuthorizationHeader();\n const storageKey = await this.getStorageKey();\n const encryptedData = encryption.encryptString(data, storageKey);\n const encryptedPath = createEntryPath(path, storageKey);\n\n const url = new URL(STORAGE_URL(this.env, encryptedPath));\n\n const response = await fetch(url.toString(), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: JSON.stringify({ data: encryptedData }),\n });\n\n if (!response.ok) {\n const responseBody: ErrorMessage = await response.json().catch(() => ({\n message: 'unknown',\n error: 'unknown',\n }));\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n throw new UserStorageError(\n `failed to upsert user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #getUserStorage(\n path: UserStoragePathWithFeatureAndKey,\n ): Promise<string> {\n try {\n const headers = await this.#getAuthorizationHeader();\n const storageKey = await this.getStorageKey();\n const encryptedPath = createEntryPath(path, storageKey);\n\n const url = new URL(STORAGE_URL(this.env, encryptedPath));\n\n const response = await fetch(url.toString(), {\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });\n\n if (response.status === 404) {\n throw new NotFoundError(\n `feature/key set not found for path '${path}'.`,\n );\n }\n\n if (!response.ok) {\n const responseBody = (await response.json()) as ErrorMessage;\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n\n const { Data: encryptedData } = await response.json();\n return encryption.decryptString(encryptedData, storageKey);\n } catch (e) {\n if (e instanceof NotFoundError) {\n throw e;\n }\n\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n\n throw new UserStorageError(\n `failed to get user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n async #getUserStorageAllFeatureEntries(\n path: UserStoragePathWithFeatureOnly,\n ): Promise<string[] | null> {\n try {\n const headers = await this.#getAuthorizationHeader();\n const storageKey = await this.getStorageKey();\n\n const url = new URL(STORAGE_URL(this.env, path));\n\n const response = await fetch(url.toString(), {\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n });\n\n if (response.status === 404) {\n throw new NotFoundError(`feature not found for path '${path}'.`);\n }\n\n if (!response.ok) {\n const responseBody = (await response.json()) as ErrorMessage;\n throw new Error(\n `HTTP error message: ${responseBody.message}, error: ${responseBody.error}`,\n );\n }\n\n const userStorage: GetUserStorageAllFeatureEntriesResponse | null =\n await response.json();\n\n if (!Array.isArray(userStorage)) {\n return null;\n }\n\n const decryptedData = userStorage.flatMap((entry) => {\n if (!entry.Data) {\n return [];\n }\n\n return encryption.decryptString(entry.Data, storageKey);\n });\n\n return (await Promise.allSettled(decryptedData))\n .map((d) => (d.status === 'fulfilled' ? d.value : undefined))\n .filter((d): d is string => d !== undefined);\n } catch (e) {\n if (e instanceof NotFoundError) {\n throw e;\n }\n\n /* istanbul ignore next */\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n\n throw new UserStorageError(\n `failed to get user storage for path '${path}'. ${errorMessage}`,\n );\n }\n }\n\n #createEntryKey(key: string, storageKey: string): string {\n const hashedKey = createSHA256Hash(key + storageKey);\n return hashedKey;\n }\n\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n async #getAuthorizationHeader(): Promise<{ Authorization: string }> {\n const accessToken = await this.config.auth.getAccessToken();\n return { Authorization: `Bearer ${accessToken}` };\n }\n}\n"]}