@metamask/profile-sync-controller 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -1
- package/dist/{chunk-LNECIW4K.js → chunk-246Z6L5V.js} +39 -16
- package/dist/chunk-246Z6L5V.js.map +1 -0
- package/dist/{chunk-ZYYAQJ56.mjs → chunk-2677XY6G.mjs} +19 -15
- package/dist/chunk-2677XY6G.mjs.map +1 -0
- package/dist/{chunk-NSSHFDIS.mjs → chunk-2VEMA6OE.mjs} +2 -2
- package/dist/{chunk-HMRRB4EX.js → chunk-4LMFZDL4.js} +22 -13
- package/dist/chunk-4LMFZDL4.js.map +1 -0
- package/dist/{chunk-EYZFHZR2.js → chunk-5MQUI24U.js} +3 -3
- package/dist/{chunk-QU4EXKJO.mjs → chunk-6DAK2U35.mjs} +2 -2
- package/dist/{chunk-LYDHYB6I.mjs → chunk-76NMME23.mjs} +20 -11
- package/dist/chunk-76NMME23.mjs.map +1 -0
- package/dist/{chunk-4WXZXVLI.mjs → chunk-7MSQV43P.mjs} +3 -3
- package/dist/{chunk-T3FNDVE3.js → chunk-BKQE7DB5.js} +30 -18
- package/dist/chunk-BKQE7DB5.js.map +1 -0
- package/dist/{chunk-WAFY3R2F.js → chunk-CHUZGCDV.js} +27 -23
- package/dist/chunk-CHUZGCDV.js.map +1 -0
- package/dist/{chunk-K5UKU454.mjs → chunk-COBJUBZE.mjs} +31 -19
- package/dist/chunk-COBJUBZE.mjs.map +1 -0
- package/dist/{chunk-5TOWF6UW.mjs → chunk-KHASG4H3.mjs} +2 -2
- package/dist/{chunk-E7Z5TCQT.mjs → chunk-MK7ABX2V.mjs} +5 -5
- package/dist/{chunk-E7Z5TCQT.mjs.map → chunk-MK7ABX2V.mjs.map} +1 -1
- package/dist/{chunk-AK7OTIWA.js → chunk-NIUQ34PY.js} +3 -3
- package/dist/{chunk-M23ZCTKE.mjs → chunk-SZ6WMC6C.mjs} +35 -12
- package/dist/chunk-SZ6WMC6C.mjs.map +1 -0
- package/dist/{chunk-JJ5BDCKD.js → chunk-T2YURW25.js} +6 -6
- package/dist/chunk-UHX7HJAI.js +11 -0
- package/dist/{chunk-ZMQRPWJN.js → chunk-UIRAMHNM.js} +12 -12
- package/dist/chunk-UIRAMHNM.js.map +1 -0
- package/dist/controllers/index.js +7 -7
- package/dist/controllers/index.mjs +6 -6
- package/dist/controllers/user-storage/UserStorageController.js +6 -6
- package/dist/controllers/user-storage/UserStorageController.mjs +5 -5
- package/dist/controllers/user-storage/encryption/encryption.js +2 -2
- package/dist/controllers/user-storage/encryption/encryption.mjs +1 -1
- package/dist/controllers/user-storage/encryption/index.js +3 -3
- package/dist/controllers/user-storage/encryption/index.mjs +2 -2
- package/dist/controllers/user-storage/index.js +7 -7
- package/dist/controllers/user-storage/index.mjs +6 -6
- package/dist/controllers/user-storage/schema.js +4 -4
- package/dist/controllers/user-storage/schema.mjs +3 -3
- package/dist/controllers/user-storage/services.js +5 -5
- package/dist/controllers/user-storage/services.mjs +4 -4
- package/dist/index.js +10 -10
- package/dist/index.mjs +9 -9
- package/dist/sdk/encryption.js +3 -3
- package/dist/sdk/encryption.mjs +2 -2
- package/dist/sdk/index.js +7 -7
- package/dist/sdk/index.mjs +6 -6
- package/dist/sdk/user-storage.js +6 -6
- package/dist/sdk/user-storage.mjs +5 -5
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/dist/types/controllers/user-storage/UserStorageController.d.ts +4 -1
- package/dist/types/controllers/user-storage/UserStorageController.d.ts.map +1 -1
- package/dist/types/controllers/user-storage/__fixtures__/mockResponses.d.ts +4 -4
- package/dist/types/controllers/user-storage/__fixtures__/mockResponses.d.ts.map +1 -1
- package/dist/types/controllers/user-storage/__fixtures__/mockServices.d.ts +2 -2
- package/dist/types/controllers/user-storage/__fixtures__/mockServices.d.ts.map +1 -1
- package/dist/types/controllers/user-storage/__fixtures__/mockStorage.d.ts +1 -1
- package/dist/types/controllers/user-storage/__fixtures__/mockStorage.d.ts.map +1 -1
- package/dist/types/controllers/user-storage/encryption/encryption.d.ts +3 -2
- package/dist/types/controllers/user-storage/encryption/encryption.d.ts.map +1 -1
- package/dist/types/controllers/user-storage/services.d.ts +3 -0
- package/dist/types/controllers/user-storage/services.d.ts.map +1 -1
- package/dist/types/sdk/__fixtures__/mock-userstorage.d.ts +5 -5
- package/dist/types/sdk/__fixtures__/mock-userstorage.d.ts.map +1 -1
- package/dist/types/sdk/user-storage.d.ts.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-HMRRB4EX.js.map +0 -1
- package/dist/chunk-K5UKU454.mjs.map +0 -1
- package/dist/chunk-LDYHGAP4.js +0 -11
- package/dist/chunk-LNECIW4K.js.map +0 -1
- package/dist/chunk-LYDHYB6I.mjs.map +0 -1
- package/dist/chunk-M23ZCTKE.mjs.map +0 -1
- package/dist/chunk-T3FNDVE3.js.map +0 -1
- package/dist/chunk-WAFY3R2F.js.map +0 -1
- package/dist/chunk-ZMQRPWJN.js.map +0 -1
- package/dist/chunk-ZYYAQJ56.mjs.map +0 -1
- /package/dist/{chunk-NSSHFDIS.mjs.map → chunk-2VEMA6OE.mjs.map} +0 -0
- /package/dist/{chunk-EYZFHZR2.js.map → chunk-5MQUI24U.js.map} +0 -0
- /package/dist/{chunk-QU4EXKJO.mjs.map → chunk-6DAK2U35.mjs.map} +0 -0
- /package/dist/{chunk-4WXZXVLI.mjs.map → chunk-7MSQV43P.mjs.map} +0 -0
- /package/dist/{chunk-5TOWF6UW.mjs.map → chunk-KHASG4H3.mjs.map} +0 -0
- /package/dist/{chunk-AK7OTIWA.js.map → chunk-NIUQ34PY.js.map} +0 -0
- /package/dist/{chunk-JJ5BDCKD.js.map → chunk-T2YURW25.js.map} +0 -0
- /package/dist/{chunk-LDYHGAP4.js.map → chunk-UHX7HJAI.js.map} +0 -0
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.4.0]
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- add `maxSyncInterval` for account syncing to `UserStorageController` prevent multiple sync requests ([#4659](https://github.com/MetaMask/core/pull/4659))
|
|
15
|
+
- add optional `NativeScrypt` property to `UserStorageController` to allow the scrypt implementation to be swapped out for a native version. Improving mobile performance ([#4656](https://github.com/MetaMask/core/pull/4656))
|
|
16
|
+
|
|
10
17
|
## [0.3.0]
|
|
11
18
|
|
|
12
19
|
### Added
|
|
@@ -127,7 +134,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
127
134
|
|
|
128
135
|
- Initial release
|
|
129
136
|
|
|
130
|
-
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@0.
|
|
137
|
+
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@0.4.0...HEAD
|
|
138
|
+
[0.4.0]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@0.3.0...@metamask/profile-sync-controller@0.4.0
|
|
131
139
|
[0.3.0]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@0.2.1...@metamask/profile-sync-controller@0.3.0
|
|
132
140
|
[0.2.1]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@0.2.0...@metamask/profile-sync-controller@0.2.1
|
|
133
141
|
[0.2.0]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@0.1.4...@metamask/profile-sync-controller@0.2.0
|
|
@@ -9,10 +9,10 @@ var _chunkYHGWG3EQjs = require('./chunk-YHGWG3EQ.js');
|
|
|
9
9
|
|
|
10
10
|
|
|
11
11
|
|
|
12
|
-
var
|
|
12
|
+
var _chunk4LMFZDL4js = require('./chunk-4LMFZDL4.js');
|
|
13
13
|
|
|
14
14
|
|
|
15
|
-
var
|
|
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(
|
|
42
|
+
constructor({
|
|
43
|
+
messenger,
|
|
44
|
+
state,
|
|
45
|
+
env,
|
|
46
|
+
getMetaMetricsState,
|
|
47
|
+
nativeScryptCrypto
|
|
48
|
+
}) {
|
|
43
49
|
super({
|
|
44
|
-
messenger
|
|
50
|
+
messenger,
|
|
45
51
|
metadata,
|
|
46
52
|
name: controllerName,
|
|
47
|
-
state: { ...defaultState, ...
|
|
53
|
+
state: { ...defaultState, ...state }
|
|
48
54
|
});
|
|
49
55
|
/**
|
|
50
56
|
* Constructor helper for registering this controller's messaging system
|
|
@@ -100,6 +106,12 @@ 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
|
+
// This is replaced with the actual value in the constructor
|
|
110
|
+
maxSyncInterval: 1e3 * 60,
|
|
111
|
+
lastSyncedAt: 0,
|
|
112
|
+
shouldSync: () => {
|
|
113
|
+
return Date.now() - _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _accounts).lastSyncedAt > _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _accounts).maxSyncInterval;
|
|
114
|
+
},
|
|
103
115
|
getInternalAccountByAddress: async (address) => {
|
|
104
116
|
return this.messagingSystem.call(
|
|
105
117
|
"AccountsController:getAccountByAddress",
|
|
@@ -176,13 +188,16 @@ var UserStorageController = class extends _basecontroller.BaseController {
|
|
|
176
188
|
});
|
|
177
189
|
}
|
|
178
190
|
});
|
|
191
|
+
_chunkIGY2S5BCjs.__privateAdd.call(void 0, this, _nativeScryptCrypto, void 0);
|
|
179
192
|
_chunkIGY2S5BCjs.__privateAdd.call(void 0, this, __snapSignMessageCache, {});
|
|
180
193
|
_chunkIGY2S5BCjs.__privateGet.call(void 0, this, _accounts).isAccountSyncingEnabled = Boolean(
|
|
181
|
-
|
|
194
|
+
env?.isAccountSyncingEnabled
|
|
182
195
|
);
|
|
183
|
-
this.
|
|
196
|
+
_chunkIGY2S5BCjs.__privateGet.call(void 0, this, _accounts).maxSyncInterval = env?.accountSyncingMaxSyncInterval ?? _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _accounts).maxSyncInterval;
|
|
197
|
+
this.getMetaMetricsState = getMetaMetricsState;
|
|
184
198
|
_chunkIGY2S5BCjs.__privateGet.call(void 0, this, _keyringController).setupLockedStateSubscriptions();
|
|
185
199
|
_chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _registerMessageHandlers, registerMessageHandlers_fn).call(this);
|
|
200
|
+
_chunkIGY2S5BCjs.__privateSet.call(void 0, this, _nativeScryptCrypto, nativeScryptCrypto);
|
|
186
201
|
}
|
|
187
202
|
async enableProfileSyncing() {
|
|
188
203
|
try {
|
|
@@ -245,10 +260,11 @@ var UserStorageController = class extends _basecontroller.BaseController {
|
|
|
245
260
|
async performGetStorage(path) {
|
|
246
261
|
_chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _assertProfileSyncingEnabled, assertProfileSyncingEnabled_fn).call(this);
|
|
247
262
|
const { bearerToken, storageKey } = await _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _getStorageKeyAndBearerToken, getStorageKeyAndBearerToken_fn).call(this);
|
|
248
|
-
const result = await
|
|
263
|
+
const result = await _chunk4LMFZDL4js.getUserStorage.call(void 0, {
|
|
249
264
|
path,
|
|
250
265
|
bearerToken,
|
|
251
|
-
storageKey
|
|
266
|
+
storageKey,
|
|
267
|
+
nativeScryptCrypto: _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _nativeScryptCrypto)
|
|
252
268
|
});
|
|
253
269
|
return result;
|
|
254
270
|
}
|
|
@@ -262,10 +278,11 @@ var UserStorageController = class extends _basecontroller.BaseController {
|
|
|
262
278
|
async performGetStorageAllFeatureEntries(path) {
|
|
263
279
|
_chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _assertProfileSyncingEnabled, assertProfileSyncingEnabled_fn).call(this);
|
|
264
280
|
const { bearerToken, storageKey } = await _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _getStorageKeyAndBearerToken, getStorageKeyAndBearerToken_fn).call(this);
|
|
265
|
-
const result = await
|
|
281
|
+
const result = await _chunk4LMFZDL4js.getUserStorageAllFeatureEntries.call(void 0, {
|
|
266
282
|
path,
|
|
267
283
|
bearerToken,
|
|
268
|
-
storageKey
|
|
284
|
+
storageKey,
|
|
285
|
+
nativeScryptCrypto: _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _nativeScryptCrypto)
|
|
269
286
|
});
|
|
270
287
|
return result;
|
|
271
288
|
}
|
|
@@ -280,10 +297,11 @@ var UserStorageController = class extends _basecontroller.BaseController {
|
|
|
280
297
|
async performSetStorage(path, value) {
|
|
281
298
|
_chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _assertProfileSyncingEnabled, assertProfileSyncingEnabled_fn).call(this);
|
|
282
299
|
const { bearerToken, storageKey } = await _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _getStorageKeyAndBearerToken, getStorageKeyAndBearerToken_fn).call(this);
|
|
283
|
-
await
|
|
300
|
+
await _chunk4LMFZDL4js.upsertUserStorage.call(void 0, value, {
|
|
284
301
|
path,
|
|
285
302
|
bearerToken,
|
|
286
|
-
storageKey
|
|
303
|
+
storageKey,
|
|
304
|
+
nativeScryptCrypto: _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _nativeScryptCrypto)
|
|
287
305
|
});
|
|
288
306
|
}
|
|
289
307
|
/**
|
|
@@ -305,6 +323,10 @@ var UserStorageController = class extends _basecontroller.BaseController {
|
|
|
305
323
|
if (!_chunkIGY2S5BCjs.__privateGet.call(void 0, this, _accounts).isAccountSyncingEnabled) {
|
|
306
324
|
return;
|
|
307
325
|
}
|
|
326
|
+
if (!_chunkIGY2S5BCjs.__privateGet.call(void 0, this, _accounts).shouldSync()) {
|
|
327
|
+
return;
|
|
328
|
+
}
|
|
329
|
+
_chunkIGY2S5BCjs.__privateGet.call(void 0, this, _accounts).lastSyncedAt = Date.now();
|
|
308
330
|
try {
|
|
309
331
|
_chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _assertProfileSyncingEnabled, assertProfileSyncingEnabled_fn).call(this);
|
|
310
332
|
const userStorageAccountsList = await _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _accounts).getUserStorageAccountsList();
|
|
@@ -417,6 +439,7 @@ _accounts = new WeakMap();
|
|
|
417
439
|
_notificationServices = new WeakMap();
|
|
418
440
|
_isUnlocked = new WeakMap();
|
|
419
441
|
_keyringController = new WeakMap();
|
|
442
|
+
_nativeScryptCrypto = new WeakMap();
|
|
420
443
|
_registerMessageHandlers = new WeakSet();
|
|
421
444
|
registerMessageHandlers_fn = function() {
|
|
422
445
|
this.messagingSystem.registerActionHandler(
|
|
@@ -476,7 +499,7 @@ createStorageKey_fn = async function() {
|
|
|
476
499
|
throw new Error("UserStorageController - unable to create storage key");
|
|
477
500
|
}
|
|
478
501
|
const storageKeySignature = await _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _snapSignMessage, snapSignMessage_fn).call(this, `metamask:${id}`);
|
|
479
|
-
const storageKey =
|
|
502
|
+
const storageKey = _chunkBKQE7DB5js.createSHA256Hash.call(void 0, storageKeySignature);
|
|
480
503
|
return storageKey;
|
|
481
504
|
};
|
|
482
505
|
__snapSignMessageCache = new WeakMap();
|
|
@@ -508,4 +531,4 @@ setIsProfileSyncingUpdateLoading_fn = function(isProfileSyncingUpdateLoading) {
|
|
|
508
531
|
|
|
509
532
|
|
|
510
533
|
exports.defaultState = defaultState; exports.UserStorageController = UserStorageController;
|
|
511
|
-
//# sourceMappingURL=chunk-
|
|
534
|
+
//# sourceMappingURL=chunk-246Z6L5V.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/controllers/user-storage/UserStorageController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAWA,SAAS,sBAAsB;AAwD/B,IAAM,iBAAiB;AAchB,IAAM,eAA2C;AAAA,EACtD,yBAAyB;AAAA,EACzB,+BAA+B;AACjC;AAEA,IAAM,WAAsD;AAAA,EAC1D,yBAAyB;AAAA,IACvB,SAAS;AAAA,IACT,WAAW;AAAA,EACb;AAAA,EACA,+BAA+B;AAAA,IAC7B,SAAS;AAAA,IACT,WAAW;AAAA,EACb;AACF;AA/FA;AA0MA,IAAqB,wBAArB,cAAmD,eAIjD;AAAA,EAgJA,YAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,GASG;AACD,UAAM;AAAA,MACJ;AAAA,MACA;AAAA,MACA,MAAM;AAAA,MACN,OAAO,EAAE,GAAG,cAAc,GAAG,MAAM;AAAA,IACrC,CAAC;AAkBH;AAAA;AAAA;AAAA;AAAA;AAmM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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","sourcesContent":["import type {\n AccountsControllerListAccountsAction,\n AccountsControllerUpdateAccountMetadataAction,\n AccountsControllerGetAccountByAddressAction,\n} from '@metamask/accounts-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedControllerMessenger,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { InternalAccount } from '@metamask/keyring-api';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n KeyringControllerAddNewAccountAction,\n} from '@metamask/keyring-controller';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\n\nimport { createSnapSignMessageRequest } from '../authentication/auth-snap-requests';\nimport type {\n AuthenticationControllerGetBearerToken,\n AuthenticationControllerGetSessionProfile,\n AuthenticationControllerIsSignedIn,\n AuthenticationControllerPerformSignIn,\n AuthenticationControllerPerformSignOut,\n} from '../authentication/AuthenticationController';\nimport type { UserStorageAccount } from './accounts/user-storage';\nimport {\n isNameDefaultAccountName,\n mapInternalAccountToUserStorageAccount,\n} from './accounts/user-storage';\nimport { createSHA256Hash } from './encryption';\nimport type {\n UserStoragePathWithFeatureAndKey,\n UserStoragePathWithFeatureOnly,\n} from './schema';\nimport {\n getUserStorage,\n getUserStorageAllFeatureEntries,\n upsertUserStorage,\n} from './services';\n\n// TODO: fix external dependencies\nexport declare type NotificationServicesControllerDisableNotificationServices =\n {\n type: `NotificationServicesController:disableNotificationServices`;\n handler: () => Promise<void>;\n };\n\nexport declare type NotificationServicesControllerSelectIsNotificationServicesEnabled =\n {\n type: `NotificationServicesController:selectIsNotificationServicesEnabled`;\n handler: () => boolean;\n };\n\nexport declare type NativeScrypt = (\n passwd: string,\n salt: Uint8Array,\n N: number,\n r: number,\n p: number,\n size: number,\n) => Promise<Uint8Array>;\n\nconst controllerName = 'UserStorageController';\n\n// State\nexport type UserStorageControllerState = {\n /**\n * Condition used by UI and to determine if we can use some of the User Storage methods.\n */\n isProfileSyncingEnabled: boolean | null;\n /**\n * Loading state for the profile syncing update\n */\n isProfileSyncingUpdateLoading: boolean;\n};\n\nexport const defaultState: UserStorageControllerState = {\n isProfileSyncingEnabled: true,\n isProfileSyncingUpdateLoading: false,\n};\n\nconst metadata: StateMetadata<UserStorageControllerState> = {\n isProfileSyncingEnabled: {\n persist: true,\n anonymous: true,\n },\n isProfileSyncingUpdateLoading: {\n persist: false,\n anonymous: false,\n },\n};\n\n// Messenger Actions\ntype CreateActionsObj<Controller extends keyof UserStorageController> = {\n [K in Controller]: {\n type: `${typeof controllerName}:${K}`;\n handler: UserStorageController[K];\n };\n};\ntype ActionsObj = CreateActionsObj<\n | 'performGetStorage'\n | 'performGetStorageAllFeatureEntries'\n | 'performSetStorage'\n | 'getStorageKey'\n | 'enableProfileSyncing'\n | 'disableProfileSyncing'\n | 'syncInternalAccountsWithUserStorage'\n | 'saveInternalAccountToUserStorage'\n>;\nexport type UserStorageControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n UserStorageControllerState\n>;\nexport type Actions =\n | ActionsObj[keyof ActionsObj]\n | UserStorageControllerGetStateAction;\nexport type UserStorageControllerPerformGetStorage =\n ActionsObj['performGetStorage'];\nexport type UserStorageControllerPerformGetStorageAllFeatureEntries =\n ActionsObj['performGetStorageAllFeatureEntries'];\nexport type UserStorageControllerPerformSetStorage =\n ActionsObj['performSetStorage'];\nexport type UserStorageControllerGetStorageKey = ActionsObj['getStorageKey'];\nexport type UserStorageControllerEnableProfileSyncing =\n ActionsObj['enableProfileSyncing'];\nexport type UserStorageControllerDisableProfileSyncing =\n ActionsObj['disableProfileSyncing'];\nexport type UserStorageControllerSyncInternalAccountsWithUserStorage =\n ActionsObj['syncInternalAccountsWithUserStorage'];\nexport type UserStorageControllerSaveInternalAccountToUserStorage =\n ActionsObj['saveInternalAccountToUserStorage'];\n\nexport type UserStorageControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n UserStorageControllerState\n>;\nexport type Events = UserStorageControllerStateChangeEvent;\n\n// Allowed Actions\nexport type AllowedActions =\n // Keyring Requests\n | KeyringControllerGetStateAction\n // Snap Requests\n | HandleSnapRequest\n // Auth Requests\n | AuthenticationControllerGetBearerToken\n | AuthenticationControllerGetSessionProfile\n | AuthenticationControllerPerformSignIn\n | AuthenticationControllerIsSignedIn\n | AuthenticationControllerPerformSignOut\n // Metamask Notifications\n | NotificationServicesControllerDisableNotificationServices\n | NotificationServicesControllerSelectIsNotificationServicesEnabled\n // Account syncing\n | AccountsControllerListAccountsAction\n | AccountsControllerGetAccountByAddressAction\n | AccountsControllerUpdateAccountMetadataAction\n | KeyringControllerAddNewAccountAction;\n\n// Messenger events\nexport type UserStorageControllerChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n UserStorageControllerState\n>;\nexport type UserStorageControllerAccountSyncingInProgress = {\n type: `${typeof controllerName}:accountSyncingInProgress`;\n payload: [boolean];\n};\nexport type UserStorageControllerAccountSyncingComplete = {\n type: `${typeof controllerName}:accountSyncingComplete`;\n payload: [boolean];\n};\n\nexport type AllowedEvents =\n | UserStorageControllerChangeEvent\n | UserStorageControllerAccountSyncingInProgress\n | UserStorageControllerAccountSyncingComplete\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent;\n\n// Messenger\nexport type UserStorageControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n Actions | AllowedActions,\n Events | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Reusable controller that allows any team to store synchronized data for a given user.\n * These can be settings shared cross MetaMask clients, or data we want to persist when uninstalling/reinstalling.\n *\n * NOTE:\n * - data stored on UserStorage is FULLY encrypted, with the only keys stored/managed on the client.\n * - No one can access this data unless they are have the SRP and are able to run the signing snap.\n */\nexport default class UserStorageController extends BaseController<\n typeof controllerName,\n UserStorageControllerState,\n UserStorageControllerMessenger\n> {\n #auth = {\n getBearerToken: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:getBearerToken',\n );\n },\n getProfileId: async () => {\n const sessionProfile = await this.messagingSystem.call(\n 'AuthenticationController:getSessionProfile',\n );\n return sessionProfile?.profileId;\n },\n isAuthEnabled: () => {\n return this.messagingSystem.call('AuthenticationController:isSignedIn');\n },\n signIn: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:performSignIn',\n );\n },\n signOut: async () => {\n return this.messagingSystem.call(\n 'AuthenticationController:performSignOut',\n );\n },\n };\n\n #accounts = {\n // This is replaced with the actual value in the constructor\n // We will remove this once the feature will be released\n isAccountSyncingEnabled: false,\n // This is replaced with the actual value in the constructor\n maxSyncInterval: 1000 * 60,\n lastSyncedAt: 0,\n shouldSync: () => {\n return (\n Date.now() - this.#accounts.lastSyncedAt >\n this.#accounts.maxSyncInterval\n );\n },\n getInternalAccountByAddress: async (address: string) => {\n return this.messagingSystem.call(\n 'AccountsController:getAccountByAddress',\n address,\n );\n },\n getInternalAccountsList: async (): Promise<InternalAccount[]> => {\n return this.messagingSystem.call('AccountsController:listAccounts');\n },\n getUserStorageAccountsList: async (): Promise<\n UserStorageAccount[] | null\n > => {\n const rawAccountsListResponse =\n await this.performGetStorageAllFeatureEntries('accounts');\n\n return (\n rawAccountsListResponse?.map((rawAccount) => JSON.parse(rawAccount)) ??\n null\n );\n },\n saveInternalAccountToUserStorage: async (address: string) => {\n const internalAccount = await this.#accounts.getInternalAccountByAddress(\n address,\n );\n\n if (!internalAccount) {\n return;\n }\n\n // Map the internal account to the user storage account schema\n const mappedAccount =\n mapInternalAccountToUserStorageAccount(internalAccount);\n\n await this.performSetStorage(\n `accounts.${address}`,\n JSON.stringify(mappedAccount),\n );\n },\n saveInternalAccountsListToUserStorage: async () => {\n const internalAccountsList =\n await this.#accounts.getInternalAccountsList();\n\n if (!internalAccountsList) {\n return;\n }\n\n const userStorageAccountsList = internalAccountsList.map(\n mapInternalAccountToUserStorageAccount,\n );\n\n await Promise.all(\n userStorageAccountsList.map(async (userStorageAccount) => {\n await this.performSetStorage(\n `accounts.${userStorageAccount.a}`,\n JSON.stringify(userStorageAccount),\n );\n }),\n );\n },\n };\n\n #notificationServices = {\n disableNotificationServices: async () => {\n return await this.messagingSystem.call(\n 'NotificationServicesController:disableNotificationServices',\n );\n },\n selectIsNotificationServicesEnabled: async () => {\n return this.messagingSystem.call(\n 'NotificationServicesController:selectIsNotificationServicesEnabled',\n );\n },\n };\n\n #isUnlocked = false;\n\n #keyringController = {\n setupLockedStateSubscriptions: () => {\n const { isUnlocked } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n this.#isUnlocked = isUnlocked;\n\n this.messagingSystem.subscribe(\n 'KeyringController:unlock',\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async () => {\n this.#isUnlocked = true;\n\n await this.syncInternalAccountsWithUserStorage();\n },\n );\n\n this.messagingSystem.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n },\n };\n\n #nativeScryptCrypto: NativeScrypt | undefined = undefined;\n\n getMetaMetricsState: () => boolean;\n\n constructor({\n messenger,\n state,\n env,\n getMetaMetricsState,\n nativeScryptCrypto,\n }: {\n messenger: UserStorageControllerMessenger;\n state?: UserStorageControllerState;\n env?: {\n isAccountSyncingEnabled?: boolean;\n accountSyncingMaxSyncInterval?: number;\n };\n getMetaMetricsState: () => boolean;\n nativeScryptCrypto?: NativeScrypt;\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n this.#accounts.isAccountSyncingEnabled = Boolean(\n env?.isAccountSyncingEnabled,\n );\n this.#accounts.maxSyncInterval =\n env?.accountSyncingMaxSyncInterval ?? this.#accounts.maxSyncInterval;\n\n this.getMetaMetricsState = getMetaMetricsState;\n this.#keyringController.setupLockedStateSubscriptions();\n this.#registerMessageHandlers();\n this.#nativeScryptCrypto = nativeScryptCrypto;\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performGetStorage',\n this.performGetStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performGetStorageAllFeatureEntries',\n this.performGetStorageAllFeatureEntries.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performSetStorage',\n this.performSetStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:getStorageKey',\n this.getStorageKey.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:enableProfileSyncing',\n this.enableProfileSyncing.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:disableProfileSyncing',\n this.disableProfileSyncing.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:syncInternalAccountsWithUserStorage',\n this.syncInternalAccountsWithUserStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:saveInternalAccountToUserStorage',\n this.saveInternalAccountToUserStorage.bind(this),\n );\n }\n\n public async enableProfileSyncing(): Promise<void> {\n try {\n this.#setIsProfileSyncingUpdateLoading(true);\n\n const authEnabled = this.#auth.isAuthEnabled();\n if (!authEnabled) {\n await this.#auth.signIn();\n }\n\n this.update((state) => {\n state.isProfileSyncingEnabled = true;\n });\n\n this.#setIsProfileSyncingUpdateLoading(false);\n } catch (e) {\n this.#setIsProfileSyncingUpdateLoading(false);\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to enable profile syncing - ${errorMessage}`,\n );\n }\n }\n\n public async setIsProfileSyncingEnabled(\n isProfileSyncingEnabled: boolean,\n ): Promise<void> {\n this.update((state) => {\n state.isProfileSyncingEnabled = isProfileSyncingEnabled;\n });\n }\n\n public async disableProfileSyncing(): Promise<void> {\n const isAlreadyDisabled = !this.state.isProfileSyncingEnabled;\n if (isAlreadyDisabled) {\n return;\n }\n\n try {\n this.#setIsProfileSyncingUpdateLoading(true);\n\n const isNotificationServicesEnabled =\n await this.#notificationServices.selectIsNotificationServicesEnabled();\n\n if (isNotificationServicesEnabled) {\n await this.#notificationServices.disableNotificationServices();\n }\n\n const isMetaMetricsParticipation = this.getMetaMetricsState();\n\n if (!isMetaMetricsParticipation) {\n await this.#auth.signOut();\n }\n\n this.#setIsProfileSyncingUpdateLoading(false);\n\n this.update((state) => {\n state.isProfileSyncingEnabled = false;\n });\n } catch (e) {\n this.#setIsProfileSyncingUpdateLoading(false);\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to disable profile syncing - ${errorMessage}`,\n );\n }\n }\n\n /**\n * Allows retrieval of stored data. Data stored is string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @returns the decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorage(\n path: UserStoragePathWithFeatureAndKey,\n ): Promise<string | null> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n const result = await getUserStorage({\n path,\n bearerToken,\n storageKey,\n nativeScryptCrypto: this.#nativeScryptCrypto,\n });\n\n return result;\n }\n\n /**\n * Allows retrieval of all stored data for a specific feature. Data stored is formatted as an array of strings.\n * Developers can extend the entry path through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}` that matches schema\n * @returns the array of decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorageAllFeatureEntries(\n path: UserStoragePathWithFeatureOnly,\n ): Promise<string[] | null> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n const result = await getUserStorageAllFeatureEntries({\n path,\n bearerToken,\n storageKey,\n nativeScryptCrypto: this.#nativeScryptCrypto,\n });\n\n return result;\n }\n\n /**\n * Allows storage of user data. Data stored must be string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param value - The string data you want to store.\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performSetStorage(\n path: UserStoragePathWithFeatureAndKey,\n value: string,\n ): Promise<void> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n await upsertUserStorage(value, {\n path,\n bearerToken,\n storageKey,\n nativeScryptCrypto: this.#nativeScryptCrypto,\n });\n }\n\n /**\n * Retrieves the storage key, for internal use only!\n *\n * @returns the storage key\n */\n public async getStorageKey(): Promise<string> {\n this.#assertProfileSyncingEnabled();\n const storageKey = await this.#createStorageKey();\n return storageKey;\n }\n\n #assertProfileSyncingEnabled(): void {\n if (!this.state.isProfileSyncingEnabled) {\n throw new Error(\n `${controllerName}: Unable to call method, user is not authenticated`,\n );\n }\n }\n\n /**\n * Utility to get the bearer token and storage key\n */\n async #getStorageKeyAndBearerToken(): Promise<{\n bearerToken: string;\n storageKey: string;\n }> {\n const bearerToken = await this.#auth.getBearerToken();\n if (!bearerToken) {\n throw new Error('UserStorageController - unable to get bearer token');\n }\n const storageKey = await this.#createStorageKey();\n\n return { bearerToken, storageKey };\n }\n\n /**\n * Rather than storing the storage key, we can compute the storage key when needed.\n *\n * @returns the storage key\n */\n async #createStorageKey(): Promise<string> {\n const id: string = await this.#auth.getProfileId();\n if (!id) {\n throw new Error('UserStorageController - unable to create storage key');\n }\n\n const storageKeySignature = await this.#snapSignMessage(`metamask:${id}`);\n const storageKey = createSHA256Hash(storageKeySignature);\n return storageKey;\n }\n\n #_snapSignMessageCache: Record<`metamask:${string}`, string> = {};\n\n /**\n * Signs a specific message using an underlying auth snap.\n *\n * @param message - A specific tagged message to sign.\n * @returns A Signature created by the snap.\n */\n async #snapSignMessage(message: `metamask:${string}`): Promise<string> {\n if (this.#_snapSignMessageCache[message]) {\n return this.#_snapSignMessageCache[message];\n }\n\n if (!this.#isUnlocked) {\n throw new Error(\n '#snapSignMessage - unable to call snap, wallet is locked',\n );\n }\n\n const result = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n createSnapSignMessageRequest(message),\n )) as string;\n\n this.#_snapSignMessageCache[message] = result;\n\n return result;\n }\n\n #setIsProfileSyncingUpdateLoading(\n isProfileSyncingUpdateLoading: boolean,\n ): void {\n this.update((state) => {\n state.isProfileSyncingUpdateLoading = isProfileSyncingUpdateLoading;\n });\n }\n\n /**\n * Syncs the internal accounts list with the user storage accounts list.\n * This method is used to make sure that the internal accounts list is up-to-date with the user storage accounts list and vice-versa.\n * It will add new accounts to the internal accounts list, update/merge conflicting names and re-upload the results in some cases to the user storage.\n */\n async syncInternalAccountsWithUserStorage(): Promise<void> {\n if (!this.#accounts.isAccountSyncingEnabled) {\n return;\n }\n\n if (!this.#accounts.shouldSync()) {\n return;\n }\n\n this.#accounts.lastSyncedAt = Date.now();\n\n try {\n this.#assertProfileSyncingEnabled();\n\n const userStorageAccountsList =\n await this.#accounts.getUserStorageAccountsList();\n\n if (!userStorageAccountsList || !userStorageAccountsList.length) {\n await this.#accounts.saveInternalAccountsListToUserStorage();\n return;\n }\n\n // Compare internal accounts list with user storage accounts list\n // First step: compare lengths\n let internalAccountsList = await this.#accounts.getInternalAccountsList();\n\n if (!internalAccountsList || !internalAccountsList.length) {\n throw new Error(`Failed to get internal accounts list`);\n }\n\n const hasMoreInternalAccountsThanUserStorageAccounts =\n internalAccountsList.length > userStorageAccountsList.length;\n\n // We don't want to remove existing accounts for a user\n // so we only add new accounts if the user has more accounts than the internal accounts list\n if (!hasMoreInternalAccountsThanUserStorageAccounts) {\n const numberOfAccountsToAdd =\n userStorageAccountsList.length - internalAccountsList.length;\n\n // Create new accounts to match the user storage accounts list\n const addNewAccountsPromises = Array.from({\n length: numberOfAccountsToAdd,\n }).map(async () => {\n await this.messagingSystem.call('KeyringController:addNewAccount');\n });\n\n await Promise.all(addNewAccountsPromises);\n }\n\n // Second step: compare account names\n // Get the internal accounts list again since new accounts might have been added in the previous step\n internalAccountsList = await this.#accounts.getInternalAccountsList();\n\n for await (const internalAccount of internalAccountsList) {\n const userStorageAccount = userStorageAccountsList.find(\n (account) => account.a === internalAccount.address,\n );\n\n if (!userStorageAccount) {\n await this.#accounts.saveInternalAccountToUserStorage(\n internalAccount.address,\n );\n continue;\n }\n\n // One or both accounts have default names\n const isInternalAccountNameDefault = isNameDefaultAccountName(\n internalAccount.metadata.name,\n );\n const isUserStorageAccountNameDefault = isNameDefaultAccountName(\n userStorageAccount.n,\n );\n\n // Internal account has default name\n if (isInternalAccountNameDefault) {\n if (!isUserStorageAccountNameDefault) {\n this.messagingSystem.call(\n 'AccountsController:updateAccountMetadata',\n internalAccount.id,\n {\n name: userStorageAccount.n,\n },\n );\n }\n continue;\n }\n\n // Internal account has custom name but user storage account has default name\n if (isUserStorageAccountNameDefault) {\n await this.#accounts.saveInternalAccountToUserStorage(\n internalAccount.address,\n );\n continue;\n }\n\n // Both accounts have custom names\n\n // User storage account has a nameLastUpdatedAt timestamp\n // Note: not storing the undefined checks in constants to act as a type guard\n if (userStorageAccount.nlu !== undefined) {\n if (internalAccount.metadata.nameLastUpdatedAt !== undefined) {\n const isInternalAccountNameNewer =\n internalAccount.metadata.nameLastUpdatedAt >\n userStorageAccount.nlu;\n\n if (isInternalAccountNameNewer) {\n await this.#accounts.saveInternalAccountToUserStorage(\n internalAccount.address,\n );\n continue;\n }\n }\n\n this.messagingSystem.call(\n 'AccountsController:updateAccountMetadata',\n internalAccount.id,\n {\n name: userStorageAccount.n,\n nameLastUpdatedAt: userStorageAccount.nlu,\n },\n );\n\n continue;\n } else if (internalAccount.metadata.nameLastUpdatedAt !== undefined) {\n await this.#accounts.saveInternalAccountToUserStorage(\n internalAccount.address,\n );\n continue;\n }\n }\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to sync user storage accounts list - ${errorMessage}`,\n );\n }\n }\n\n /**\n * Saves an individual internal account to the user storage.\n * @param address - The address of the internal account to save\n */\n async saveInternalAccountToUserStorage(address: string): Promise<void> {\n if (!this.#accounts.isAccountSyncingEnabled) {\n return;\n }\n\n try {\n await this.#accounts.saveInternalAccountToUserStorage(address);\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to save account to user storage - ${errorMessage}`,\n );\n }\n }\n}\n"]}
|
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
import {
|
|
2
2
|
UserStorageController,
|
|
3
3
|
defaultState
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-SZ6WMC6C.mjs";
|
|
5
5
|
import {
|
|
6
6
|
USER_STORAGE_ENDPOINT
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-76NMME23.mjs";
|
|
8
8
|
import {
|
|
9
9
|
createEntryPath
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-2VEMA6OE.mjs";
|
|
11
11
|
import {
|
|
12
12
|
encryption_default as encryption_default2
|
|
13
|
-
} from "./chunk-
|
|
13
|
+
} from "./chunk-KHASG4H3.mjs";
|
|
14
14
|
import {
|
|
15
15
|
createSHA256Hash,
|
|
16
16
|
encryption_default
|
|
17
|
-
} from "./chunk-
|
|
17
|
+
} from "./chunk-COBJUBZE.mjs";
|
|
18
18
|
import {
|
|
19
19
|
__export
|
|
20
20
|
} from "./chunk-U5UIDVOO.mjs";
|
|
@@ -47,7 +47,11 @@ __export(fixtures_exports, {
|
|
|
47
47
|
var MOCK_STORAGE_KEY_SIGNATURE = "mockStorageKey";
|
|
48
48
|
var MOCK_STORAGE_KEY = createSHA256Hash(MOCK_STORAGE_KEY_SIGNATURE);
|
|
49
49
|
var MOCK_STORAGE_DATA = JSON.stringify({ hello: "world" });
|
|
50
|
-
var
|
|
50
|
+
var cachedMockEncryptedData;
|
|
51
|
+
var MOCK_ENCRYPTED_STORAGE_DATA = async () => cachedMockEncryptedData ?? (cachedMockEncryptedData = await encryption_default2.encryptString(
|
|
52
|
+
MOCK_STORAGE_DATA,
|
|
53
|
+
MOCK_STORAGE_KEY
|
|
54
|
+
));
|
|
51
55
|
|
|
52
56
|
// src/controllers/user-storage/__fixtures__/mockResponses.ts
|
|
53
57
|
var getMockUserStorageEndpoint = (path) => {
|
|
@@ -59,28 +63,28 @@ var getMockUserStorageEndpoint = (path) => {
|
|
|
59
63
|
MOCK_STORAGE_KEY
|
|
60
64
|
)}`;
|
|
61
65
|
};
|
|
62
|
-
var MOCK_GET_USER_STORAGE_RESPONSE = () => ({
|
|
66
|
+
var MOCK_GET_USER_STORAGE_RESPONSE = async () => ({
|
|
63
67
|
HashedKey: "HASHED_KEY",
|
|
64
|
-
Data: MOCK_ENCRYPTED_STORAGE_DATA()
|
|
68
|
+
Data: await MOCK_ENCRYPTED_STORAGE_DATA()
|
|
65
69
|
});
|
|
66
|
-
var MOCK_GET_USER_STORAGE_ALL_FEATURE_ENTRIES_RESPONSE = () => [
|
|
70
|
+
var MOCK_GET_USER_STORAGE_ALL_FEATURE_ENTRIES_RESPONSE = async () => [
|
|
67
71
|
{
|
|
68
72
|
HashedKey: "HASHED_KEY",
|
|
69
|
-
Data: MOCK_ENCRYPTED_STORAGE_DATA()
|
|
73
|
+
Data: await MOCK_ENCRYPTED_STORAGE_DATA()
|
|
70
74
|
}
|
|
71
75
|
];
|
|
72
|
-
var getMockUserStorageGetResponse = (path = "notifications.notificationSettings") => {
|
|
76
|
+
var getMockUserStorageGetResponse = async (path = "notifications.notificationSettings") => {
|
|
73
77
|
return {
|
|
74
78
|
url: getMockUserStorageEndpoint(path),
|
|
75
79
|
requestMethod: "GET",
|
|
76
|
-
response: MOCK_GET_USER_STORAGE_RESPONSE()
|
|
80
|
+
response: await MOCK_GET_USER_STORAGE_RESPONSE()
|
|
77
81
|
};
|
|
78
82
|
};
|
|
79
|
-
var getMockUserStorageAllFeatureEntriesResponse = (path = "notifications") => {
|
|
83
|
+
var getMockUserStorageAllFeatureEntriesResponse = async (path = "notifications") => {
|
|
80
84
|
return {
|
|
81
85
|
url: getMockUserStorageEndpoint(path),
|
|
82
86
|
requestMethod: "GET",
|
|
83
|
-
response: MOCK_GET_USER_STORAGE_ALL_FEATURE_ENTRIES_RESPONSE()
|
|
87
|
+
response: await MOCK_GET_USER_STORAGE_ALL_FEATURE_ENTRIES_RESPONSE()
|
|
84
88
|
};
|
|
85
89
|
};
|
|
86
90
|
var getMockUserStoragePutResponse = (path = "notifications.notificationSettings") => {
|
|
@@ -100,4 +104,4 @@ export {
|
|
|
100
104
|
user_storage_default,
|
|
101
105
|
user_storage_exports
|
|
102
106
|
};
|
|
103
|
-
//# sourceMappingURL=chunk-
|
|
107
|
+
//# sourceMappingURL=chunk-2677XY6G.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/controllers/user-storage/index.ts","../src/controllers/user-storage/__fixtures__/index.ts","../src/controllers/user-storage/__fixtures__/mockStorage.ts","../src/controllers/user-storage/__fixtures__/mockResponses.ts"],"sourcesContent":["import Controller from './UserStorageController';\n\nconst UserStorageController = Controller;\nexport { Controller };\nexport default UserStorageController;\nexport * from './UserStorageController';\nexport * from './encryption';\nexport * as Mocks from './__fixtures__';\n","export * from './mockResponses';\nexport * from './mockStorage';\n","import encryption, { createSHA256Hash } from '../encryption';\n\nexport const MOCK_STORAGE_KEY_SIGNATURE = 'mockStorageKey';\nexport const MOCK_STORAGE_KEY = createSHA256Hash(MOCK_STORAGE_KEY_SIGNATURE);\nexport const MOCK_STORAGE_DATA = JSON.stringify({ hello: 'world' });\n\n// NOTE - using encryption.encryptString directly in fixtures causes issues on mobile.\n// This is because this fixture is getting added in at run time. Will be improved once we support multiple exports\nlet cachedMockEncryptedData: string;\nexport const MOCK_ENCRYPTED_STORAGE_DATA = async () =>\n (cachedMockEncryptedData ??= await encryption.encryptString(\n MOCK_STORAGE_DATA,\n MOCK_STORAGE_KEY,\n ));\n","import type {\n UserStoragePathWithFeatureAndKey,\n UserStoragePathWithFeatureOnly,\n} from '../schema';\nimport { createEntryPath } from '../schema';\nimport type {\n GetUserStorageAllFeatureEntriesResponse,\n GetUserStorageResponse,\n} from '../services';\nimport { USER_STORAGE_ENDPOINT } from '../services';\nimport { MOCK_ENCRYPTED_STORAGE_DATA, MOCK_STORAGE_KEY } from './mockStorage';\n\ntype MockResponse = {\n url: string;\n requestMethod: 'GET' | 'POST' | 'PUT';\n response: unknown;\n};\n\nexport const getMockUserStorageEndpoint = (\n path: UserStoragePathWithFeatureAndKey | UserStoragePathWithFeatureOnly,\n) => {\n if (path.split('.').length === 1) {\n return `${USER_STORAGE_ENDPOINT}/${path}`;\n }\n\n return `${USER_STORAGE_ENDPOINT}${createEntryPath(\n path as UserStoragePathWithFeatureAndKey,\n MOCK_STORAGE_KEY,\n )}`;\n};\n\nconst MOCK_GET_USER_STORAGE_RESPONSE =\n async (): Promise<GetUserStorageResponse> => ({\n HashedKey: 'HASHED_KEY',\n Data: await MOCK_ENCRYPTED_STORAGE_DATA(),\n });\n\nconst MOCK_GET_USER_STORAGE_ALL_FEATURE_ENTRIES_RESPONSE =\n async (): Promise<GetUserStorageAllFeatureEntriesResponse> => [\n {\n HashedKey: 'HASHED_KEY',\n Data: await MOCK_ENCRYPTED_STORAGE_DATA(),\n },\n ];\n\nexport const getMockUserStorageGetResponse = async (\n path: UserStoragePathWithFeatureAndKey = 'notifications.notificationSettings',\n) => {\n return {\n url: getMockUserStorageEndpoint(path),\n requestMethod: 'GET',\n response: await MOCK_GET_USER_STORAGE_RESPONSE(),\n } satisfies MockResponse;\n};\n\nexport const getMockUserStorageAllFeatureEntriesResponse = async (\n path: UserStoragePathWithFeatureOnly = 'notifications',\n) => {\n return {\n url: getMockUserStorageEndpoint(path),\n requestMethod: 'GET',\n response: await MOCK_GET_USER_STORAGE_ALL_FEATURE_ENTRIES_RESPONSE(),\n } satisfies MockResponse;\n};\n\nexport const getMockUserStoragePutResponse = (\n path: UserStoragePathWithFeatureAndKey = 'notifications.notificationSettings',\n) => {\n return {\n url: getMockUserStorageEndpoint(path),\n requestMethod: 'PUT',\n response: null,\n } satisfies MockResponse;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEO,IAAM,6BAA6B;AACnC,IAAM,mBAAmB,iBAAiB,0BAA0B;AACpE,IAAM,oBAAoB,KAAK,UAAU,EAAE,OAAO,QAAQ,CAAC;AAIlE,IAAI;AACG,IAAM,8BAA8B,YACxC,sDAA4B,MAAMA,oBAAW;AAAA,EAC5C;AAAA,EACA;AACF;;;ACKK,IAAM,6BAA6B,CACxC,SACG;AACH,MAAI,KAAK,MAAM,GAAG,EAAE,WAAW,GAAG;AAChC,WAAO,GAAG,qBAAqB,IAAI,IAAI;AAAA,EACzC;AAEA,SAAO,GAAG,qBAAqB,GAAG;AAAA,IAChC;AAAA,IACA;AAAA,EACF,CAAC;AACH;AAEA,IAAM,iCACJ,aAA8C;AAAA,EAC5C,WAAW;AAAA,EACX,MAAM,MAAM,4BAA4B;AAC1C;AAEF,IAAM,qDACJ,YAA8D;AAAA,EAC5D;AAAA,IACE,WAAW;AAAA,IACX,MAAM,MAAM,4BAA4B;AAAA,EAC1C;AACF;AAEK,IAAM,gCAAgC,OAC3C,OAAyC,yCACtC;AACH,SAAO;AAAA,IACL,KAAK,2BAA2B,IAAI;AAAA,IACpC,eAAe;AAAA,IACf,UAAU,MAAM,+BAA+B;AAAA,EACjD;AACF;AAEO,IAAM,8CAA8C,OACzD,OAAuC,oBACpC;AACH,SAAO;AAAA,IACL,KAAK,2BAA2B,IAAI;AAAA,IACpC,eAAe;AAAA,IACf,UAAU,MAAM,mDAAmD;AAAA,EACrE;AACF;AAEO,IAAM,gCAAgC,CAC3C,OAAyC,yCACtC;AACH,SAAO;AAAA,IACL,KAAK,2BAA2B,IAAI;AAAA,IACpC,eAAe;AAAA,IACf,UAAU;AAAA,EACZ;AACF;;;AHvEA,IAAMC,yBAAwB;AAE9B,IAAO,uBAAQC;","names":["encryption_default","UserStorageController","UserStorageController"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
createSHA256Hash
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-COBJUBZE.mjs";
|
|
4
4
|
|
|
5
5
|
// src/controllers/user-storage/schema.ts
|
|
6
6
|
var ALLOW_ARBITRARY_KEYS = "ALLOW_ARBITRARY_KEYS";
|
|
@@ -44,4 +44,4 @@ export {
|
|
|
44
44
|
isPathWithFeatureAndKey,
|
|
45
45
|
createEntryPath
|
|
46
46
|
};
|
|
47
|
-
//# sourceMappingURL=chunk-
|
|
47
|
+
//# sourceMappingURL=chunk-2VEMA6OE.mjs.map
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var _chunk5MQUI24Ujs = require('./chunk-5MQUI24U.js');
|
|
4
4
|
|
|
5
5
|
|
|
6
|
-
var
|
|
6
|
+
var _chunkNIUQ34PYjs = require('./chunk-NIUQ34PY.js');
|
|
7
7
|
|
|
8
8
|
|
|
9
9
|
var _chunkDF24ZX4Hjs = require('./chunk-DF24ZX4H.js');
|
|
@@ -15,8 +15,8 @@ var USER_STORAGE_API = ENV_URLS.userStorageApiUrl;
|
|
|
15
15
|
var USER_STORAGE_ENDPOINT = `${USER_STORAGE_API}/api/v1/userstorage`;
|
|
16
16
|
async function getUserStorage(opts) {
|
|
17
17
|
try {
|
|
18
|
-
const { bearerToken, path, storageKey } = opts;
|
|
19
|
-
const encryptedPath =
|
|
18
|
+
const { bearerToken, path, storageKey, nativeScryptCrypto } = opts;
|
|
19
|
+
const encryptedPath = _chunk5MQUI24Ujs.createEntryPath.call(void 0, path, storageKey);
|
|
20
20
|
const url = new URL(`${USER_STORAGE_ENDPOINT}${encryptedPath}`);
|
|
21
21
|
const userStorageResponse = await fetch(url.toString(), {
|
|
22
22
|
headers: {
|
|
@@ -35,9 +35,10 @@ async function getUserStorage(opts) {
|
|
|
35
35
|
if (!encryptedData) {
|
|
36
36
|
return null;
|
|
37
37
|
}
|
|
38
|
-
const decryptedData =
|
|
38
|
+
const decryptedData = await _chunkNIUQ34PYjs.encryption_default.decryptString(
|
|
39
39
|
encryptedData,
|
|
40
|
-
opts.storageKey
|
|
40
|
+
opts.storageKey,
|
|
41
|
+
nativeScryptCrypto
|
|
41
42
|
);
|
|
42
43
|
return decryptedData;
|
|
43
44
|
} catch (e) {
|
|
@@ -47,7 +48,7 @@ async function getUserStorage(opts) {
|
|
|
47
48
|
}
|
|
48
49
|
async function getUserStorageAllFeatureEntries(opts) {
|
|
49
50
|
try {
|
|
50
|
-
const { bearerToken, path } = opts;
|
|
51
|
+
const { bearerToken, path, nativeScryptCrypto } = opts;
|
|
51
52
|
const url = new URL(`${USER_STORAGE_ENDPOINT}/${path}`);
|
|
52
53
|
const userStorageResponse = await fetch(url.toString(), {
|
|
53
54
|
headers: {
|
|
@@ -69,18 +70,26 @@ async function getUserStorageAllFeatureEntries(opts) {
|
|
|
69
70
|
if (!entry.Data) {
|
|
70
71
|
return [];
|
|
71
72
|
}
|
|
72
|
-
return
|
|
73
|
+
return _chunkNIUQ34PYjs.encryption_default.decryptString(
|
|
74
|
+
entry.Data,
|
|
75
|
+
opts.storageKey,
|
|
76
|
+
nativeScryptCrypto
|
|
77
|
+
);
|
|
73
78
|
});
|
|
74
|
-
return decryptedData;
|
|
79
|
+
return (await Promise.allSettled(decryptedData)).map((d) => d.status === "fulfilled" ? d.value : void 0).filter((d) => d !== void 0);
|
|
75
80
|
} catch (e) {
|
|
76
81
|
_loglevel2.default.error("Failed to get user storage", e);
|
|
77
82
|
return null;
|
|
78
83
|
}
|
|
79
84
|
}
|
|
80
85
|
async function upsertUserStorage(data, opts) {
|
|
81
|
-
const { bearerToken, path, storageKey } = opts;
|
|
82
|
-
const encryptedData =
|
|
83
|
-
|
|
86
|
+
const { bearerToken, path, storageKey, nativeScryptCrypto } = opts;
|
|
87
|
+
const encryptedData = await _chunkNIUQ34PYjs.encryption_default.encryptString(
|
|
88
|
+
data,
|
|
89
|
+
opts.storageKey,
|
|
90
|
+
nativeScryptCrypto
|
|
91
|
+
);
|
|
92
|
+
const encryptedPath = _chunk5MQUI24Ujs.createEntryPath.call(void 0, path, storageKey);
|
|
84
93
|
const url = new URL(`${USER_STORAGE_ENDPOINT}${encryptedPath}`);
|
|
85
94
|
const res = await fetch(url.toString(), {
|
|
86
95
|
method: "PUT",
|
|
@@ -102,4 +111,4 @@ async function upsertUserStorage(data, opts) {
|
|
|
102
111
|
|
|
103
112
|
|
|
104
113
|
exports.USER_STORAGE_API = USER_STORAGE_API; exports.USER_STORAGE_ENDPOINT = USER_STORAGE_ENDPOINT; exports.getUserStorage = getUserStorage; exports.getUserStorageAllFeatureEntries = getUserStorageAllFeatureEntries; exports.upsertUserStorage = upsertUserStorage;
|
|
105
|
-
//# sourceMappingURL=chunk-
|
|
114
|
+
//# sourceMapp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AI,IAAI;AACX,UAAM,IAAI,MAAM,sCAAsC;AAAA,EACxD;AACF","sourcesContent":["import log from 'loglevel';\n\nimport { Env, getEnvUrls } from '../../sdk/env';\nimport encryption from './encryption';\nimport type {\n UserStoragePathWithFeatureAndKey,\n UserStoragePathWithFeatureOnly,\n} from './schema';\nimport { createEntryPath } from './schema';\nimport type { NativeScrypt } from './UserStorageController';\n\nconst ENV_URLS = getEnvUrls(Env.PRD);\n\nexport const USER_STORAGE_API: string = ENV_URLS.userStorageApiUrl;\nexport const USER_STORAGE_ENDPOINT = `${USER_STORAGE_API}/api/v1/userstorage`;\n\n/**\n * This is the Server Response shape for a feature entry.\n */\nexport type GetUserStorageResponse = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n HashedKey: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n Data: string;\n};\n\nexport type GetUserStorageAllFeatureEntriesResponse = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n HashedKey: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n Data: string;\n}[];\n\nexport type UserStorageBaseOptions = {\n bearerToken: string;\n storageKey: string;\n};\n\nexport type UserStorageOptions = UserStorageBaseOptions & {\n path: UserStoragePathWithFeatureAndKey;\n nativeScryptCrypto?: NativeScrypt;\n};\n\nexport type UserStorageAllFeatureEntriesOptions = UserStorageBaseOptions & {\n path: UserStoragePathWithFeatureOnly;\n nativeScryptCrypto?: NativeScrypt;\n};\n\n/**\n * User Storage Service - Get Storage Entry.\n *\n * @param opts - User Storage Options\n * @returns The storage entry, or null if fails to find entry\n */\nexport async function getUserStorage(\n opts: UserStorageOptions,\n): Promise<string | null> {\n try {\n const { bearerToken, path, storageKey, nativeScryptCrypto } = opts;\n\n const encryptedPath = createEntryPath(path, storageKey);\n const url = new URL(`${USER_STORAGE_ENDPOINT}${encryptedPath}`);\n\n const userStorageResponse = await fetch(url.toString(), {\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${bearerToken}`,\n },\n });\n\n // Acceptable error - since indicates entry does not exist.\n if (userStorageResponse.status === 404) {\n return null;\n }\n\n if (userStorageResponse.status !== 200) {\n throw new Error('Unable to get User Storage');\n }\n\n const userStorage: GetUserStorageResponse | null =\n await userStorageResponse.json();\n const encryptedData = userStorage?.Data ?? null;\n\n if (!encryptedData) {\n return null;\n }\n\n const decryptedData = await encryption.decryptString(\n encryptedData,\n opts.storageKey,\n nativeScryptCrypto,\n );\n\n return decryptedData;\n } catch (e) {\n log.error('Failed to get user storage', e);\n return null;\n }\n}\n\n/**\n * User Storage Service - Get all storage entries for a specific feature.\n *\n * @param opts - User Storage Options\n * @returns The storage entry, or null if fails to find entry\n */\nexport async function getUserStorageAllFeatureEntries(\n opts: UserStorageAllFeatureEntriesOptions,\n): Promise<string[] | null> {\n try {\n const { bearerToken, path, nativeScryptCrypto } = opts;\n const url = new URL(`${USER_STORAGE_ENDPOINT}/${path}`);\n\n const userStorageResponse = await fetch(url.toString(), {\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${bearerToken}`,\n },\n });\n\n // Acceptable error - since indicates feature does not exist.\n if (userStorageResponse.status === 404) {\n return null;\n }\n\n if (userStorageResponse.status !== 200) {\n throw new Error('Unable to get User Storage');\n }\n\n const userStorage: GetUserStorageAllFeatureEntriesResponse | null =\n await userStorageResponse.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(\n entry.Data,\n opts.storageKey,\n nativeScryptCrypto,\n );\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 log.error('Failed to get user storage', e);\n return null;\n }\n}\n\n/**\n * User Storage Service - Set Storage Entry.\n *\n * @param data - data to store\n * @param opts - storage options\n */\nexport async function upsertUserStorage(\n data: string,\n opts: UserStorageOptions,\n): Promise<void> {\n const { bearerToken, path, storageKey, nativeScryptCrypto } = opts;\n\n const encryptedData = await encryption.encryptString(\n data,\n opts.storageKey,\n nativeScryptCrypto,\n );\n const encryptedPath = createEntryPath(path, storageKey);\n const url = new URL(`${USER_STORAGE_ENDPOINT}${encryptedPath}`);\n\n const res = await fetch(url.toString(), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${bearerToken}`,\n },\n body: JSON.stringify({ data: encryptedData }),\n });\n\n if (!res.ok) {\n throw new Error('user-storage - unable to upsert data');\n }\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var _chunkBKQE7DB5js = require('./chunk-BKQE7DB5.js');
|
|
4
4
|
|
|
5
5
|
// src/controllers/user-storage/schema.ts
|
|
6
6
|
var ALLOW_ARBITRARY_KEYS = "ALLOW_ARBITRARY_KEYS";
|
|
@@ -34,7 +34,7 @@ var isPathWithFeatureAndKey = (path) => {
|
|
|
34
34
|
};
|
|
35
35
|
function createEntryPath(path, storageKey) {
|
|
36
36
|
const { feature, key } = getFeatureAndKeyFromPath(path);
|
|
37
|
-
const hashedKey =
|
|
37
|
+
const hashedKey = _chunkBKQE7DB5js.createSHA256Hash.call(void 0, key + storageKey);
|
|
38
38
|
return `/${feature}/${hashedKey}`;
|
|
39
39
|
}
|
|
40
40
|
|
|
@@ -44,4 +44,4 @@ function createEntryPath(path, storageKey) {
|
|
|
44
44
|
|
|
45
45
|
|
|
46
46
|
exports.USER_STORAGE_SCHEMA = USER_STORAGE_SCHEMA; exports.getFeatureAndKeyFromPath = getFeatureAndKeyFromPath; exports.isPathWithFeatureAndKey = isPathWithFeatureAndKey; exports.createEntryPath = createEntryPath;
|
|
47
|
-
//# sourceMappingURL=chunk-
|
|
47
|
+
//# sourceMappingURL=chunk-5MQUI24U.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
encryption_default
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-COBJUBZE.mjs";
|
|
4
4
|
|
|
5
5
|
// src/sdk/encryption.ts
|
|
6
6
|
var encryption_default2 = encryption_default;
|
|
@@ -8,4 +8,4 @@ var encryption_default2 = encryption_default;
|
|
|
8
8
|
export {
|
|
9
9
|
encryption_default2 as encryption_default
|
|
10
10
|
};
|
|
11
|
-
//# sourceMappingURL=chunk-
|
|
11
|
+
//# sourceMappingURL=chunk-6DAK2U35.mjs.map
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
2
|
createEntryPath
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-2VEMA6OE.mjs";
|
|
4
4
|
import {
|
|
5
5
|
encryption_default
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-KHASG4H3.mjs";
|
|
7
7
|
import {
|
|
8
8
|
getEnvUrls
|
|
9
9
|
} from "./chunk-KTCSRECK.mjs";
|
|
@@ -15,7 +15,7 @@ var USER_STORAGE_API = ENV_URLS.userStorageApiUrl;
|
|
|
15
15
|
var USER_STORAGE_ENDPOINT = `${USER_STORAGE_API}/api/v1/userstorage`;
|
|
16
16
|
async function getUserStorage(opts) {
|
|
17
17
|
try {
|
|
18
|
-
const { bearerToken, path, storageKey } = opts;
|
|
18
|
+
const { bearerToken, path, storageKey, nativeScryptCrypto } = opts;
|
|
19
19
|
const encryptedPath = createEntryPath(path, storageKey);
|
|
20
20
|
const url = new URL(`${USER_STORAGE_ENDPOINT}${encryptedPath}`);
|
|
21
21
|
const userStorageResponse = await fetch(url.toString(), {
|
|
@@ -35,9 +35,10 @@ async function getUserStorage(opts) {
|
|
|
35
35
|
if (!encryptedData) {
|
|
36
36
|
return null;
|
|
37
37
|
}
|
|
38
|
-
const decryptedData = encryption_default.decryptString(
|
|
38
|
+
const decryptedData = await encryption_default.decryptString(
|
|
39
39
|
encryptedData,
|
|
40
|
-
opts.storageKey
|
|
40
|
+
opts.storageKey,
|
|
41
|
+
nativeScryptCrypto
|
|
41
42
|
);
|
|
42
43
|
return decryptedData;
|
|
43
44
|
} catch (e) {
|
|
@@ -47,7 +48,7 @@ async function getUserStorage(opts) {
|
|
|
47
48
|
}
|
|
48
49
|
async function getUserStorageAllFeatureEntries(opts) {
|
|
49
50
|
try {
|
|
50
|
-
const { bearerToken, path } = opts;
|
|
51
|
+
const { bearerToken, path, nativeScryptCrypto } = opts;
|
|
51
52
|
const url = new URL(`${USER_STORAGE_ENDPOINT}/${path}`);
|
|
52
53
|
const userStorageResponse = await fetch(url.toString(), {
|
|
53
54
|
headers: {
|
|
@@ -69,17 +70,25 @@ async function getUserStorageAllFeatureEntries(opts) {
|
|
|
69
70
|
if (!entry.Data) {
|
|
70
71
|
return [];
|
|
71
72
|
}
|
|
72
|
-
return encryption_default.decryptString(
|
|
73
|
+
return encryption_default.decryptString(
|
|
74
|
+
entry.Data,
|
|
75
|
+
opts.storageKey,
|
|
76
|
+
nativeScryptCrypto
|
|
77
|
+
);
|
|
73
78
|
});
|
|
74
|
-
return decryptedData;
|
|
79
|
+
return (await Promise.allSettled(decryptedData)).map((d) => d.status === "fulfilled" ? d.value : void 0).filter((d) => d !== void 0);
|
|
75
80
|
} catch (e) {
|
|
76
81
|
log.error("Failed to get user storage", e);
|
|
77
82
|
return null;
|
|
78
83
|
}
|
|
79
84
|
}
|
|
80
85
|
async function upsertUserStorage(data, opts) {
|
|
81
|
-
const { bearerToken, path, storageKey } = opts;
|
|
82
|
-
const encryptedData = encryption_default.encryptString(
|
|
86
|
+
const { bearerToken, path, storageKey, nativeScryptCrypto } = opts;
|
|
87
|
+
const encryptedData = await encryption_default.encryptString(
|
|
88
|
+
data,
|
|
89
|
+
opts.storageKey,
|
|
90
|
+
nativeScryptCrypto
|
|
91
|
+
);
|
|
83
92
|
const encryptedPath = createEntryPath(path, storageKey);
|
|
84
93
|
const url = new URL(`${USER_STORAGE_ENDPOINT}${encryptedPath}`);
|
|
85
94
|
const res = await fetch(url.toString(), {
|
|
@@ -102,4 +111,4 @@ export {
|
|
|
102
111
|
getUserStorageAllFeatureEntries,
|
|
103
112
|
upsertUserStorage
|
|
104
113
|
};
|
|
105
|
-
//# sourceMappingURL=chunk-
|
|
114
|
+
//# sourceMappingURL=chunk-76NMME23.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/controllers/user-storage/services.ts"],"sourcesContent":["import log from 'loglevel';\n\nimport { Env, getEnvUrls } from '../../sdk/env';\nimport encryption from './encryption';\nimport type {\n UserStoragePathWithFeatureAndKey,\n UserStoragePathWithFeatureOnly,\n} from './schema';\nimport { createEntryPath } from './schema';\nimport type { NativeScrypt } from './UserStorageController';\n\nconst ENV_URLS = getEnvUrls(Env.PRD);\n\nexport const USER_STORAGE_API: string = ENV_URLS.userStorageApiUrl;\nexport const USER_STORAGE_ENDPOINT = `${USER_STORAGE_API}/api/v1/userstorage`;\n\n/**\n * This is the Server Response shape for a feature entry.\n */\nexport type GetUserStorageResponse = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n HashedKey: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n Data: string;\n};\n\nexport type GetUserStorageAllFeatureEntriesResponse = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n HashedKey: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n Data: string;\n}[];\n\nexport type UserStorageBaseOptions = {\n bearerToken: string;\n storageKey: string;\n};\n\nexport type UserStorageOptions = UserStorageBaseOptions & {\n path: UserStoragePathWithFeatureAndKey;\n nativeScryptCrypto?: NativeScrypt;\n};\n\nexport type UserStorageAllFeatureEntriesOptions = UserStorageBaseOptions & {\n path: UserStoragePathWithFeatureOnly;\n nativeScryptCrypto?: NativeScrypt;\n};\n\n/**\n * User Storage Service - Get Storage Entry.\n *\n * @param opts - User Storage Options\n * @returns The storage entry, or null if fails to find entry\n */\nexport async function getUserStorage(\n opts: UserStorageOptions,\n): Promise<string | null> {\n try {\n const { bearerToken, path, storageKey, nativeScryptCrypto } = opts;\n\n const encryptedPath = createEntryPath(path, storageKey);\n const url = new URL(`${USER_STORAGE_ENDPOINT}${encryptedPath}`);\n\n const userStorageResponse = await fetch(url.toString(), {\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${bearerToken}`,\n },\n });\n\n // Acceptable error - since indicates entry does not exist.\n if (userStorageResponse.status === 404) {\n return null;\n }\n\n if (userStorageResponse.status !== 200) {\n throw new Error('Unable to get User Storage');\n }\n\n const userStorage: GetUserStorageResponse | null =\n await userStorageResponse.json();\n const encryptedData = userStorage?.Data ?? null;\n\n if (!encryptedData) {\n return null;\n }\n\n const decryptedData = await encryption.decryptString(\n encryptedData,\n opts.storageKey,\n nativeScryptCrypto,\n );\n\n return decryptedData;\n } catch (e) {\n log.error('Failed to get user storage', e);\n return null;\n }\n}\n\n/**\n * User Storage Service - Get all storage entries for a specific feature.\n *\n * @param opts - User Storage Options\n * @returns The storage entry, or null if fails to find entry\n */\nexport async function getUserStorageAllFeatureEntries(\n opts: UserStorageAllFeatureEntriesOptions,\n): Promise<string[] | null> {\n try {\n const { bearerToken, path, nativeScryptCrypto } = opts;\n const url = new URL(`${USER_STORAGE_ENDPOINT}/${path}`);\n\n const userStorageResponse = await fetch(url.toString(), {\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${bearerToken}`,\n },\n });\n\n // Acceptable error - since indicates feature does not exist.\n if (userStorageResponse.status === 404) {\n return null;\n }\n\n if (userStorageResponse.status !== 200) {\n throw new Error('Unable to get User Storage');\n }\n\n const userStorage: GetUserStorageAllFeatureEntriesResponse | null =\n await userStorageResponse.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(\n entry.Data,\n opts.storageKey,\n nativeScryptCrypto,\n );\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 log.error('Failed to get user storage', e);\n return null;\n }\n}\n\n/**\n * User Storage Service - Set Storage Entry.\n *\n * @param data - data to store\n * @param opts - storage options\n */\nexport async function upsertUserStorage(\n data: string,\n opts: UserStorageOptions,\n): Promise<void> {\n const { bearerToken, path, storageKey, nativeScryptCrypto } = opts;\n\n const encryptedData = await encryption.encryptString(\n data,\n opts.storageKey,\n nativeScryptCrypto,\n );\n const encryptedPath = createEntryPath(path, storageKey);\n const url = new URL(`${USER_STORAGE_ENDPOINT}${encryptedPath}`);\n\n const res = await fetch(url.toString(), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${bearerToken}`,\n },\n body: JSON.stringify({ data: encryptedData }),\n });\n\n if (!res.ok) {\n throw new Error('user-storage - unable to upsert data');\n }\n}\n"],"mappings":";;;;;;;;;;;AAAA,OAAO,SAAS;AAWhB,IAAM,WAAW,0BAAkB;AAE5B,IAAM,mBAA2B,SAAS;AAC1C,IAAM,wBAAwB,GAAG,gBAAgB;AAwCxD,eAAsB,eACpB,MACwB;AACxB,MAAI;AACF,UAAM,EAAE,aAAa,MAAM,YAAY,mBAAmB,IAAI;AAE9D,UAAM,gBAAgB,gBAAgB,MAAM,UAAU;AACtD,UAAM,MAAM,IAAI,IAAI,GAAG,qBAAqB,GAAG,aAAa,EAAE;AAE9D,UAAM,sBAAsB,MAAM,MAAM,IAAI,SAAS,GAAG;AAAA,MACtD,SAAS;AAAA,QACP,gBAAgB;AAAA,QAChB,eAAe,UAAU,WAAW;AAAA,MACtC;AAAA,IACF,CAAC;AAGD,QAAI,oBAAoB,WAAW,KAAK;AACtC,aAAO;AAAA,IACT;AAEA,QAAI,oBAAoB,WAAW,KAAK;AACtC,YAAM,IAAI,MAAM,4BAA4B;AAAA,IAC9C;AAEA,UAAM,cACJ,MAAM,oBAAoB,KAAK;AACjC,UAAM,gBAAgB,aAAa,QAAQ;AA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AAM,YAAY,mBAAmB,IAAI;AAE9D,QAAM,gBAAgB,MAAM,mBAAW;AAAA,IACrC;AAAA,IACA,KAAK;AAAA,IACL;AAAA,EACF;AACA,QAAM,gBAAgB,gBAAgB,MAAM,UAAU;AACtD,QAAM,MAAM,IAAI,IAAI,GAAG,qBAAqB,GAAG,aAAa,EAAE;AAE9D,QAAM,MAAM,MAAM,MAAM,IAAI,SAAS,GAAG;AAAA,IACtC,QAAQ;AAAA,IACR,SAAS;AAAA,MACP,gBAAgB;AAAA,MAChB,eAAe,UAAU,WAAW;AAAA,IACtC;AAAA,IACA,MAAM,KAAK,UAAU,EAAE,MAAM,cAAc,CAAC;AAAA,EAC9C,CAAC;AAED,MAAI,CAAC,IAAI,IAAI;AACX,UAAM,IAAI,MAAM,sCAAsC;AAAA,EACxD;AACF;","names":[]}
|
|
@@ -20,10 +20,10 @@ import {
|
|
|
20
20
|
import {
|
|
21
21
|
STORAGE_URL,
|
|
22
22
|
UserStorage
|
|
23
|
-
} from "./chunk-
|
|
23
|
+
} from "./chunk-MK7ABX2V.mjs";
|
|
24
24
|
import {
|
|
25
25
|
createSHA256Hash
|
|
26
|
-
} from "./chunk-
|
|
26
|
+
} from "./chunk-COBJUBZE.mjs";
|
|
27
27
|
import {
|
|
28
28
|
Env,
|
|
29
29
|
Platform,
|
|
@@ -74,4 +74,4 @@ __export(sdk_exports, {
|
|
|
74
74
|
export {
|
|
75
75
|
sdk_exports
|
|
76
76
|
};
|
|
77
|
-
//# sourceMappingURL=chunk-
|
|
77
|
+
//# sourceMappingURL=chunk-7MSQV43P.mjs.map
|