@metamask/profile-sync-controller 0.1.4 → 0.2.1

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 (94) hide show
  1. package/CHANGELOG.md +41 -1
  2. package/dist/{chunk-5SXXO4MV.js → chunk-3TE6M5TV.js} +10 -8
  3. package/dist/chunk-3TE6M5TV.js.map +1 -0
  4. package/dist/{chunk-CSFHMILK.js → chunk-4DQF2YNS.js} +13 -16
  5. package/dist/chunk-4DQF2YNS.js.map +1 -0
  6. package/dist/{chunk-RT2GRG4S.mjs → chunk-7KMONAQI.mjs} +3 -3
  7. package/dist/{chunk-LDEIUP6J.mjs → chunk-CJLDMVV3.mjs} +2 -2
  8. package/dist/{chunk-2XGRQBXI.mjs → chunk-FU7PSGFP.mjs} +10 -8
  9. package/dist/chunk-FU7PSGFP.mjs.map +1 -0
  10. package/dist/{chunk-P52TG263.js → chunk-FUPEFLXB.js} +18 -24
  11. package/dist/chunk-FUPEFLXB.js.map +1 -0
  12. package/dist/chunk-ILIZJQ6X.mjs +40 -0
  13. package/dist/chunk-ILIZJQ6X.mjs.map +1 -0
  14. package/dist/{chunk-DDOYG42A.js → chunk-JENTMRXO.js} +36 -12
  15. package/dist/chunk-JENTMRXO.js.map +1 -0
  16. package/dist/{chunk-DHKZ2NEF.js → chunk-KW3X4TT5.js} +30 -2
  17. package/dist/chunk-KW3X4TT5.js.map +1 -0
  18. package/dist/{chunk-BXPL7ZFX.js → chunk-MNVUKRZC.js} +4 -4
  19. package/dist/{chunk-AXWK4Y23.mjs → chunk-NPH5AHLH.mjs} +19 -25
  20. package/dist/chunk-NPH5AHLH.mjs.map +1 -0
  21. package/dist/{chunk-3DMUUTKC.js → chunk-PSR2V3R4.js} +6 -6
  22. package/dist/{chunk-TUMNNWY6.mjs → chunk-QE5X2BT3.mjs} +35 -11
  23. package/dist/chunk-QE5X2BT3.mjs.map +1 -0
  24. package/dist/chunk-SLHAVOTE.js +40 -0
  25. package/dist/chunk-SLHAVOTE.js.map +1 -0
  26. package/dist/{chunk-JFVONPMM.mjs → chunk-VYZPOR47.mjs} +15 -1
  27. package/dist/chunk-VYZPOR47.mjs.map +1 -0
  28. package/dist/{chunk-Y7P3UH26.mjs → chunk-WWQ65CZY.mjs} +30 -2
  29. package/dist/chunk-WWQ65CZY.mjs.map +1 -0
  30. package/dist/{chunk-3SNLHEYU.mjs → chunk-XMYWJQNH.mjs} +10 -13
  31. package/dist/chunk-XMYWJQNH.mjs.map +1 -0
  32. package/dist/{chunk-KUTU3NNS.js → chunk-XSSIP3PJ.js} +15 -1
  33. package/dist/chunk-XSSIP3PJ.js.map +1 -0
  34. package/dist/controllers/authentication/AuthenticationController.js +10 -5
  35. package/dist/controllers/authentication/AuthenticationController.mjs +9 -4
  36. package/dist/controllers/authentication/index.js +11 -6
  37. package/dist/controllers/authentication/index.mjs +10 -5
  38. package/dist/controllers/authentication/services.js +8 -3
  39. package/dist/controllers/authentication/services.mjs +8 -3
  40. package/dist/controllers/index.js +14 -14
  41. package/dist/controllers/index.mjs +13 -13
  42. package/dist/controllers/user-storage/UserStorageController.js +11 -11
  43. package/dist/controllers/user-storage/UserStorageController.mjs +10 -10
  44. package/dist/controllers/user-storage/index.js +15 -15
  45. package/dist/controllers/user-storage/index.mjs +14 -14
  46. package/dist/controllers/user-storage/schema.js +4 -2
  47. package/dist/controllers/user-storage/schema.mjs +7 -5
  48. package/dist/controllers/user-storage/services.js +10 -10
  49. package/dist/controllers/user-storage/services.mjs +9 -9
  50. package/dist/index.js +14 -14
  51. package/dist/index.mjs +13 -13
  52. package/dist/sdk/authentication.js +2 -2
  53. package/dist/sdk/authentication.mjs +1 -1
  54. package/dist/sdk/index.js +9 -4
  55. package/dist/sdk/index.mjs +8 -3
  56. package/dist/sdk/user-storage.js +7 -2
  57. package/dist/sdk/user-storage.mjs +6 -1
  58. package/dist/tsconfig.build.tsbuildinfo +1 -1
  59. package/dist/types/controllers/authentication/AuthenticationController.d.ts +4 -2
  60. package/dist/types/controllers/authentication/AuthenticationController.d.ts.map +1 -1
  61. package/dist/types/controllers/user-storage/UserStorageController.d.ts +10 -8
  62. package/dist/types/controllers/user-storage/UserStorageController.d.ts.map +1 -1
  63. package/dist/types/controllers/user-storage/__fixtures__/mockStorage.d.ts +1 -1
  64. package/dist/types/controllers/user-storage/__fixtures__/mockStorage.d.ts.map +1 -1
  65. package/dist/types/controllers/user-storage/schema.d.ts +18 -10
  66. package/dist/types/controllers/user-storage/schema.d.ts.map +1 -1
  67. package/dist/types/controllers/user-storage/services.d.ts +2 -2
  68. package/dist/types/controllers/user-storage/services.d.ts.map +1 -1
  69. package/dist/types/sdk/__fixtures__/mock-userstorage.d.ts.map +1 -1
  70. package/dist/types/sdk/authentication.d.ts +1 -0
  71. package/dist/types/sdk/authentication.d.ts.map +1 -1
  72. package/dist/types/sdk/user-storage.d.ts +4 -3
  73. package/dist/types/sdk/user-storage.d.ts.map +1 -1
  74. package/package.json +13 -10
  75. package/dist/chunk-2XGRQBXI.mjs.map +0 -1
  76. package/dist/chunk-3SNLHEYU.mjs.map +0 -1
  77. package/dist/chunk-5SXXO4MV.js.map +0 -1
  78. package/dist/chunk-AUFUOKJW.mjs +0 -25
  79. package/dist/chunk-AUFUOKJW.mjs.map +0 -1
  80. package/dist/chunk-AXWK4Y23.mjs.map +0 -1
  81. package/dist/chunk-B6CSNLGE.js +0 -25
  82. package/dist/chunk-B6CSNLGE.js.map +0 -1
  83. package/dist/chunk-CSFHMILK.js.map +0 -1
  84. package/dist/chunk-DDOYG42A.js.map +0 -1
  85. package/dist/chunk-DHKZ2NEF.js.map +0 -1
  86. package/dist/chunk-JFVONPMM.mjs.map +0 -1
  87. package/dist/chunk-KUTU3NNS.js.map +0 -1
  88. package/dist/chunk-P52TG263.js.map +0 -1
  89. package/dist/chunk-TUMNNWY6.mjs.map +0 -1
  90. package/dist/chunk-Y7P3UH26.mjs.map +0 -1
  91. /package/dist/{chunk-RT2GRG4S.mjs.map → chunk-7KMONAQI.mjs.map} +0 -0
  92. /package/dist/{chunk-LDEIUP6J.mjs.map → chunk-CJLDMVV3.mjs.map} +0 -0
  93. /package/dist/{chunk-BXPL7ZFX.js.map → chunk-MNVUKRZC.js.map} +0 -0
  94. /package/dist/{chunk-3DMUUTKC.js.map → chunk-PSR2V3R4.js.map} +0 -0
package/CHANGELOG.md CHANGED
@@ -7,6 +7,44 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.2.1]
11
+
12
+ ### Added
13
+
14
+ - unlock checks for when controller methods are called ([#4569](https://github.com/MetaMask/core/pull/4569))
15
+
16
+ ### Changed
17
+
18
+ - **BREAKING** made `MOCK_ENCRYPTED_STORAGE_DATA` fixture a function to be lazily evaluated ([#4592](https://github.com/MetaMask/core/pull/4592))
19
+ - Bump `typescript` from `~5.0.4` to `~5.1.6` ([#4576](https://github.com/MetaMask/core/pull/4576))
20
+
21
+ ## [0.2.0]
22
+
23
+ ### Added
24
+
25
+ - Add and export object `USER_STORAGE_SCHEMA`, function `getFeatureAndKeyFromPath`, and type `UserStoragePath` ([#4543](https://github.com/MetaMask/core/pull/4543))
26
+ - Add `connectSnap` method to the `JwtBearerAuth` class for connecting to snap after initializing the Profile Sync SDK ([#4560](https://github.com/MetaMask/core/pull/4560))
27
+
28
+ ### Changed
29
+
30
+ - **BREAKING:** Enforce `UserStorageSchema` usage in all functions that get or set user storage ([#4543](https://github.com/MetaMask/core/pull/4543))
31
+ - Keeps user storage entries consistent, and improves DX for consumers of user storage.
32
+ - **BREAKING:** Remove `entryKey` function parameter from `performGetStorage` and `performSetStorage` methods of `UserStorageController`, and replace with `path` parameter of type `UserStoragePath`.
33
+ - **BREAKING:** Remove `entryKey` function parameter from `createEntryPath`, and replace with `path` parameter of type `UserStoragePath`.
34
+ - **BREAKING:** Remove `entryKey` property from type `UserStorageOptions`, and replace with `path` property of type `UserStoragePath`.
35
+ - **BREAKING:** Bump peerDependency `@metamask/snaps-controllers` from `^8.1.1` to `^9.3.0` ([#3645](https://github.com/MetaMask/core/pull/3645))
36
+ - Remove `@metamask/snaps-controllers` dependency [#4556](https://github.com/MetaMask/core/pull/4556)
37
+ - This was listed under `peerDependencies` already, so it was redundant as a dependency.
38
+ - Widen `isProfileSyncingEnabled` property of the `UserStorageControllerState` type from `boolean` to `boolean | null` ([#4551](https://github.com/MetaMask/core/pull/4551))
39
+ - Upgrade TypeScript version to `~5.0.4` and set `moduleResolution` option to `Node16` ([#3645](https://github.com/MetaMask/core/pull/3645))
40
+ - Bump `@metamask/base-controller` from `^6.0.1` to `^6.0.2` ([#4544](https://github.com/MetaMask/core/pull/4544))
41
+ - Bump `@metamask/snaps-sdk` from `^4.2.0` to `^6.1.1` ([#3645](https://github.com/MetaMask/core/pull/3645), [#4547](https://github.com/MetaMask/core/pull/4547))
42
+ - Add new dependency `@metamask/snaps-utils` ([#3645](https://github.com/MetaMask/core/pull/3645), [#4547](https://github.com/MetaMask/core/pull/4547))
43
+
44
+ ### Removed
45
+
46
+ - Remove object `USER_STORAGE_ENTRIES` and type `UserStorageEntryKeys` ([#4543](https://github.com/MetaMask/core/pull/4543))
47
+
10
48
  ## [0.1.4]
11
49
 
12
50
  ### Added
@@ -57,7 +95,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
57
95
 
58
96
  - Initial release
59
97
 
60
- [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@0.1.4...HEAD
98
+ [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@0.2.1...HEAD
99
+ [0.2.1]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@0.2.0...@metamask/profile-sync-controller@0.2.1
100
+ [0.2.0]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@0.1.4...@metamask/profile-sync-controller@0.2.0
61
101
  [0.1.4]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@0.1.3...@metamask/profile-sync-controller@0.1.4
62
102
  [0.1.3]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@0.1.2...@metamask/profile-sync-controller@0.1.3
63
103
  [0.1.2]: https://github.com/MetaMask/core/compare/@metamask/profile-sync-controller@0.1.1...@metamask/profile-sync-controller@0.1.2
@@ -1,6 +1,6 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2
2
 
3
- var _chunkB6CSNLGEjs = require('./chunk-B6CSNLGE.js');
3
+ var _chunkSLHAVOTEjs = require('./chunk-SLHAVOTE.js');
4
4
 
5
5
 
6
6
  var _chunkAK7OTIWAjs = require('./chunk-AK7OTIWA.js');
@@ -15,12 +15,13 @@ 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 path = _chunkB6CSNLGEjs.createEntryPath.call(void 0, opts.entryKey, opts.storageKey);
19
- const url = new URL(`${USER_STORAGE_ENDPOINT}${path}`);
18
+ const { bearerToken, path, storageKey } = opts;
19
+ const encryptedPath = _chunkSLHAVOTEjs.createEntryPath.call(void 0, path, storageKey);
20
+ const url = new URL(`${USER_STORAGE_ENDPOINT}${encryptedPath}`);
20
21
  const userStorageResponse = await fetch(url.toString(), {
21
22
  headers: {
22
23
  "Content-Type": "application/json",
23
- Authorization: `Bearer ${opts.bearerToken}`
24
+ Authorization: `Bearer ${bearerToken}`
24
25
  }
25
26
  });
26
27
  if (userStorageResponse.status === 404) {
@@ -45,14 +46,15 @@ async function getUserStorage(opts) {
45
46
  }
46
47
  }
47
48
  async function upsertUserStorage(data, opts) {
49
+ const { bearerToken, path, storageKey } = opts;
48
50
  const encryptedData = _chunkAK7OTIWAjs.encryption_default.encryptString(data, opts.storageKey);
49
- const path = _chunkB6CSNLGEjs.createEntryPath.call(void 0, opts.entryKey, opts.storageKey);
50
- const url = new URL(`${USER_STORAGE_ENDPOINT}${path}`);
51
+ const encryptedPath = _chunkSLHAVOTEjs.createEntryPath.call(void 0, path, storageKey);
52
+ const url = new URL(`${USER_STORAGE_ENDPOINT}${encryptedPath}`);
51
53
  const res = await fetch(url.toString(), {
52
54
  method: "PUT",
53
55
  headers: {
54
56
  "Content-Type": "application/json",
55
- Authorization: `Bearer ${opts.bearerToken}`
57
+ Authorization: `Bearer ${bearerToken}`
56
58
  },
57
59
  body: JSON.stringify({ data: encryptedData })
58
60
  });
@@ -67,4 +69,4 @@ async function upsertUserStorage(data, opts) {
67
69
 
68
70
 
69
71
  exports.USER_STORAGE_API = USER_STORAGE_API; exports.USER_STORAGE_ENDPOINT = USER_STORAGE_ENDPOINT; exports.getUserStorage = getUserStorage; exports.upsertUserStorage = upsertUserStorage;
70
- //# sourceMappingURL=chunk-5SXXO4MV.js.map
72
+ //# sourceMappingURL=chunk-3TE6M5TV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/controllers/user-storage/services.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,OAAO,SAAS;AAOhB,IAAM,WAAW,0BAAkB;AAE5B,IAAM,mBAA2B,SAAS;AAC1C,IAAM,wBAAwB,GAAG,gBAAgB;AAwBxD,eAAsB,eACpB,MACwB;AACxB,MAAI;AACF,UAAM,EAAE,aAAa,MAAM,WAAW,IAAI;AAE1C,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;AAE3C,QAAI,CAAC,eAAe;AAClB,aAAO;AAAA,IACT;AAEA,UAAM,gBAAgB,mBAAW;AAAA,MAC/B;AAAA,MACA,KAAK;AAAA,IACP;AAEA,WAAO;AAAA,EACT,SAAS,GAAG;AACV,QAAI,MAAM,8BAA8B,CAAC;AACzC,WAAO;AAAA,EACT;AACF;AAQA,eAAsB,kBACpB,MACA,MACe;AACf,QAAM,EAAE,aAAa,MAAM,WAAW,IAAI;AAE1C,QAAM,gBAAgB,mBAAW,cAAc,MAAM,KAAK,UAAU;AACpE,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","sourcesContent":["import log from 'loglevel';\n\nimport { Env, getEnvUrls } from '../../sdk';\nimport encryption from './encryption';\nimport type { UserStoragePath } from './schema';\nimport { createEntryPath } from './schema';\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\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 UserStorageOptions = {\n path: UserStoragePath;\n bearerToken: string;\n storageKey: string;\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 } = 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 = encryption.decryptString(\n encryptedData,\n opts.storageKey,\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 - 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 } = opts;\n\n const encryptedData = encryption.encryptString(data, opts.storageKey);\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,13 +1,13 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
2
 
3
3
 
4
- var _chunkDDOYG42Ajs = require('./chunk-DDOYG42A.js');
4
+ var _chunkJENTMRXOjs = require('./chunk-JENTMRXO.js');
5
5
 
6
6
 
7
- var _chunk5SXXO4MVjs = require('./chunk-5SXXO4MV.js');
7
+ var _chunk3TE6M5TVjs = require('./chunk-3TE6M5TV.js');
8
8
 
9
9
 
10
- var _chunkB6CSNLGEjs = require('./chunk-B6CSNLGE.js');
10
+ var _chunkSLHAVOTEjs = require('./chunk-SLHAVOTE.js');
11
11
 
12
12
 
13
13
  var _chunkAK7OTIWAjs = require('./chunk-AK7OTIWA.js');
@@ -22,11 +22,11 @@ var _chunkIGY2S5BCjs = require('./chunk-IGY2S5BC.js');
22
22
  // src/controllers/user-storage/index.ts
23
23
  var user_storage_exports = {};
24
24
  _chunkIGY2S5BCjs.__export.call(void 0, user_storage_exports, {
25
- Controller: () => _chunkDDOYG42Ajs.UserStorageController,
25
+ Controller: () => _chunkJENTMRXOjs.UserStorageController,
26
26
  Encryption: () => _chunkT3FNDVE3js.encryption_default,
27
27
  Mocks: () => fixtures_exports,
28
28
  createSHA256Hash: () => _chunkT3FNDVE3js.createSHA256Hash,
29
- defaultState: () => _chunkDDOYG42Ajs.defaultState
29
+ defaultState: () => _chunkJENTMRXOjs.defaultState
30
30
  });
31
31
 
32
32
  // src/controllers/user-storage/__fixtures__/index.ts
@@ -45,25 +45,22 @@ _chunkIGY2S5BCjs.__export.call(void 0, fixtures_exports, {
45
45
  var MOCK_STORAGE_KEY_SIGNATURE = "mockStorageKey";
46
46
  var MOCK_STORAGE_KEY = _chunkT3FNDVE3js.createSHA256Hash.call(void 0, MOCK_STORAGE_KEY_SIGNATURE);
47
47
  var MOCK_STORAGE_DATA = JSON.stringify({ hello: "world" });
48
- var MOCK_ENCRYPTED_STORAGE_DATA = _chunkAK7OTIWAjs.encryption_default.encryptString(
49
- MOCK_STORAGE_DATA,
50
- MOCK_STORAGE_KEY
51
- );
48
+ var MOCK_ENCRYPTED_STORAGE_DATA = () => _chunkAK7OTIWAjs.encryption_default.encryptString(MOCK_STORAGE_DATA, MOCK_STORAGE_KEY);
52
49
 
53
50
  // src/controllers/user-storage/__fixtures__/mockResponses.ts
54
- var MOCK_USER_STORAGE_NOTIFICATIONS_ENDPOINT = `${_chunk5SXXO4MVjs.USER_STORAGE_ENDPOINT}${_chunkB6CSNLGEjs.createEntryPath.call(void 0,
55
- "notificationSettings",
51
+ var MOCK_USER_STORAGE_NOTIFICATIONS_ENDPOINT = `${_chunk3TE6M5TVjs.USER_STORAGE_ENDPOINT}${_chunkSLHAVOTEjs.createEntryPath.call(void 0,
52
+ "notifications.notificationSettings",
56
53
  MOCK_STORAGE_KEY
57
54
  )}`;
58
- var MOCK_GET_USER_STORAGE_RESPONSE = {
55
+ var MOCK_GET_USER_STORAGE_RESPONSE = () => ({
59
56
  HashedKey: "HASHED_KEY",
60
- Data: MOCK_ENCRYPTED_STORAGE_DATA
61
- };
57
+ Data: MOCK_ENCRYPTED_STORAGE_DATA()
58
+ });
62
59
  var getMockUserStorageGetResponse = () => {
63
60
  return {
64
61
  url: MOCK_USER_STORAGE_NOTIFICATIONS_ENDPOINT,
65
62
  requestMethod: "GET",
66
- response: MOCK_GET_USER_STORAGE_RESPONSE
63
+ response: MOCK_GET_USER_STORAGE_RESPONSE()
67
64
  };
68
65
  };
69
66
  var getMockUserStoragePutResponse = () => {
@@ -78,4 +75,4 @@ var getMockUserStoragePutResponse = () => {
78
75
 
79
76
 
80
77
  exports.fixtures_exports = fixtures_exports; exports.user_storage_exports = user_storage_exports;
81
- //# sourceMappingURL=chunk-CSFHMILK.js.map
78
+ //# sourceMappingURL=chunk-4DQF2YNS.js.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"],"names":["encryption_default"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;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;AAI3D,IAAM,8BAA8B,MACzCA,oBAAW,cAAc,mBAAmB,gBAAgB;;;ACEvD,IAAM,2CAA2C,GAAG,qBAAqB,GAAG;AAAA,EACjF;AAAA,EACA;AACF,CAAC;AAED,IAAM,iCAAiC,OAA+B;AAAA,EACpE,WAAW;AAAA,EACX,MAAM,4BAA4B;AACpC;AAEO,IAAM,gCAAgC,MAAM;AACjD,SAAO;AAAA,IACL,KAAK;AAAA,IACL,eAAe;AAAA,IACf,UAAU,+BAA+B;AAAA,EAC3C;AACF;AAEO,IAAM,gCAAgC,MAAM;AACjD,SAAO;AAAA,IACL,KAAK;AAAA,IACL,eAAe;AAAA,IACf,UAAU;AAAA,EACZ;AACF","sourcesContent":["import Controller from './UserStorageController';\n\nexport { Controller };\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\nexport const MOCK_ENCRYPTED_STORAGE_DATA = () =>\n encryption.encryptString(MOCK_STORAGE_DATA, MOCK_STORAGE_KEY);\n","import { createEntryPath } from '../schema';\nimport type { GetUserStorageResponse } 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 MOCK_USER_STORAGE_NOTIFICATIONS_ENDPOINT = `${USER_STORAGE_ENDPOINT}${createEntryPath(\n 'notifications.notificationSettings',\n MOCK_STORAGE_KEY,\n)}`;\n\nconst MOCK_GET_USER_STORAGE_RESPONSE = (): GetUserStorageResponse => ({\n HashedKey: 'HASHED_KEY',\n Data: MOCK_ENCRYPTED_STORAGE_DATA(),\n});\n\nexport const getMockUserStorageGetResponse = () => {\n return {\n url: MOCK_USER_STORAGE_NOTIFICATIONS_ENDPOINT,\n requestMethod: 'GET',\n response: MOCK_GET_USER_STORAGE_RESPONSE(),\n } satisfies MockResponse;\n};\n\nexport const getMockUserStoragePutResponse = () => {\n return {\n url: MOCK_USER_STORAGE_NOTIFICATIONS_ENDPOINT,\n requestMethod: 'PUT',\n response: null,\n } satisfies MockResponse;\n};\n"]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  JwtBearerAuth
3
- } from "./chunk-JFVONPMM.mjs";
3
+ } from "./chunk-VYZPOR47.mjs";
4
4
  import {
5
5
  SIWEJwtBearerAuth
6
6
  } from "./chunk-BDO3VJEU.mjs";
@@ -20,7 +20,7 @@ import {
20
20
  import {
21
21
  STORAGE_URL,
22
22
  UserStorage
23
- } from "./chunk-AXWK4Y23.mjs";
23
+ } from "./chunk-NPH5AHLH.mjs";
24
24
  import {
25
25
  Encryption,
26
26
  createSHA256Hash
@@ -76,4 +76,4 @@ __export(sdk_exports, {
76
76
  export {
77
77
  sdk_exports
78
78
  };
79
- //# sourceMappingURL=chunk-RT2GRG4S.mjs.map
79
+ //# sourceMappingURL=chunk-7KMONAQI.mjs.map
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  AuthenticationController,
3
3
  defaultState
4
- } from "./chunk-Y7P3UH26.mjs";
4
+ } from "./chunk-WWQ65CZY.mjs";
5
5
  import {
6
6
  AUTH_LOGIN_ENDPOINT,
7
7
  AUTH_NONCE_ENDPOINT,
@@ -83,4 +83,4 @@ export {
83
83
  fixtures_exports,
84
84
  authentication_exports
85
85
  };
86
- //# sourceMappingURL=chunk-LDEIUP6J.mjs.map
86
+ //# sourceMappingURL=chunk-CJLDMVV3.mjs.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  createEntryPath
3
- } from "./chunk-AUFUOKJW.mjs";
3
+ } from "./chunk-ILIZJQ6X.mjs";
4
4
  import {
5
5
  encryption_default
6
6
  } from "./chunk-5TOWF6UW.mjs";
@@ -15,12 +15,13 @@ 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 path = createEntryPath(opts.entryKey, opts.storageKey);
19
- const url = new URL(`${USER_STORAGE_ENDPOINT}${path}`);
18
+ const { bearerToken, path, storageKey } = opts;
19
+ const encryptedPath = createEntryPath(path, storageKey);
20
+ const url = new URL(`${USER_STORAGE_ENDPOINT}${encryptedPath}`);
20
21
  const userStorageResponse = await fetch(url.toString(), {
21
22
  headers: {
22
23
  "Content-Type": "application/json",
23
- Authorization: `Bearer ${opts.bearerToken}`
24
+ Authorization: `Bearer ${bearerToken}`
24
25
  }
25
26
  });
26
27
  if (userStorageResponse.status === 404) {
@@ -45,14 +46,15 @@ async function getUserStorage(opts) {
45
46
  }
46
47
  }
47
48
  async function upsertUserStorage(data, opts) {
49
+ const { bearerToken, path, storageKey } = opts;
48
50
  const encryptedData = encryption_default.encryptString(data, opts.storageKey);
49
- const path = createEntryPath(opts.entryKey, opts.storageKey);
50
- const url = new URL(`${USER_STORAGE_ENDPOINT}${path}`);
51
+ const encryptedPath = createEntryPath(path, storageKey);
52
+ const url = new URL(`${USER_STORAGE_ENDPOINT}${encryptedPath}`);
51
53
  const res = await fetch(url.toString(), {
52
54
  method: "PUT",
53
55
  headers: {
54
56
  "Content-Type": "application/json",
55
- Authorization: `Bearer ${opts.bearerToken}`
57
+ Authorization: `Bearer ${bearerToken}`
56
58
  },
57
59
  body: JSON.stringify({ data: encryptedData })
58
60
  });
@@ -67,4 +69,4 @@ export {
67
69
  getUserStorage,
68
70
  upsertUserStorage
69
71
  };
70
- //# sourceMappingURL=chunk-2XGRQBXI.mjs.map
72
+ //# sourceMappingURL=chunk-FU7PSGFP.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';\nimport encryption from './encryption';\nimport type { UserStoragePath } from './schema';\nimport { createEntryPath } from './schema';\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\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 UserStorageOptions = {\n path: UserStoragePath;\n bearerToken: string;\n storageKey: string;\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 } = 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 = encryption.decryptString(\n encryptedData,\n opts.storageKey,\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 - 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 } = opts;\n\n const encryptedData = encryption.encryptString(data, opts.storageKey);\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;AAOhB,IAAM,WAAW,0BAAkB;AAE5B,IAAM,mBAA2B,SAAS;AAC1C,IAAM,wBAAwB,GAAG,gBAAgB;AAwBxD,eAAsB,eACpB,MACwB;AACxB,MAAI;AACF,UAAM,EAAE,aAAa,MAAM,WAAW,IAAI;AAE1C,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;AAE3C,QAAI,CAAC,eAAe;AAClB,aAAO;AAAA,IACT;AAEA,UAAM,gBAAgB,mBAAW;AAAA,MAC/B;AAAA,MACA,KAAK;AAAA,IACP;AAEA,WAAO;AAAA,EACT,SAAS,GAAG;AACV,QAAI,MAAM,8BAA8B,CAAC;AACzC,WAAO;AAAA,EACT;AACF;AAQA,eAAsB,kBACpB,MACA,MACe;AACf,QAAM,EAAE,aAAa,MAAM,WAAW,IAAI;AAE1C,QAAM,gBAAgB,mBAAW,cAAc,MAAM,KAAK,UAAU;AACpE,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":[]}
@@ -1,5 +1,8 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
2
 
3
+ var _chunkSLHAVOTEjs = require('./chunk-SLHAVOTE.js');
4
+
5
+
3
6
 
4
7
  var _chunkP4DUDLMYjs = require('./chunk-P4DUDLMY.js');
5
8
 
@@ -8,7 +11,6 @@ var _chunkSMKTWM6Ijs = require('./chunk-SMKTWM6I.js');
8
11
 
9
12
 
10
13
 
11
-
12
14
  var _chunkMBTBE4P5js = require('./chunk-MBTBE4P5.js');
13
15
 
14
16
 
@@ -16,7 +18,7 @@ var _chunkMBTBE4P5js = require('./chunk-MBTBE4P5.js');
16
18
  var _chunkIGY2S5BCjs = require('./chunk-IGY2S5BC.js');
17
19
 
18
20
  // src/sdk/user-storage.ts
19
- var STORAGE_URL = (env, feature, entry) => `${_chunkSMKTWM6Ijs.getEnvUrls.call(void 0, env).userStorageApiUrl}/api/v1/userstorage/${feature}/${entry}`;
21
+ var STORAGE_URL = (env, encryptedPath) => `${_chunkSMKTWM6Ijs.getEnvUrls.call(void 0, env).userStorageApiUrl}/api/v1/userstorage/${encryptedPath}`;
20
22
  var _upsertUserStorage, upsertUserStorage_fn, _getUserStorage, getUserStorage_fn, _createEntryKey, createEntryKey_fn, _getAuthorizationHeader, getAuthorizationHeader_fn;
21
23
  var UserStorage = class {
22
24
  constructor(config, options) {
@@ -30,17 +32,11 @@ var UserStorage = class {
30
32
  this.config = config;
31
33
  this.options = options;
32
34
  }
33
- async setItem(feature, key, value) {
34
- if (!feature.trim() || !key.trim()) {
35
- throw new (0, _chunkMBTBE4P5js.ValidationError)("feature or key cannot be empty strings");
36
- }
37
- await _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _upsertUserStorage, upsertUserStorage_fn).call(this, feature, key, value);
35
+ async setItem(path, value) {
36
+ await _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _upsertUserStorage, upsertUserStorage_fn).call(this, path, value);
38
37
  }
39
- async getItem(feature, key) {
40
- if (!feature.trim() || !key.trim()) {
41
- throw new (0, _chunkMBTBE4P5js.ValidationError)("feature or key cannot be empty strings");
42
- }
43
- return _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _getUserStorage, getUserStorage_fn).call(this, feature, key);
38
+ async getItem(path) {
39
+ return _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _getUserStorage, getUserStorage_fn).call(this, path);
44
40
  }
45
41
  async getStorageKey() {
46
42
  const storageKey = await this.options.storage?.getStorageKey();
@@ -57,14 +53,13 @@ var UserStorage = class {
57
53
  }
58
54
  };
59
55
  _upsertUserStorage = new WeakSet();
60
- upsertUserStorage_fn = async function(feature, key, data) {
56
+ upsertUserStorage_fn = async function(path, data) {
61
57
  try {
62
58
  const headers = await _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _getAuthorizationHeader, getAuthorizationHeader_fn).call(this);
63
59
  const storageKey = await this.getStorageKey();
64
60
  const encryptedData = _chunkP4DUDLMYjs.encryption_default.encryptString(data, storageKey);
65
- const url = new URL(
66
- STORAGE_URL(this.env, feature, _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _createEntryKey, createEntryKey_fn).call(this, key, storageKey))
67
- );
61
+ const encryptedPath = _chunkSLHAVOTEjs.createEntryPath.call(void 0, path, storageKey);
62
+ const url = new URL(STORAGE_URL(this.env, encryptedPath));
68
63
  const response = await fetch(url.toString(), {
69
64
  method: "PUT",
70
65
  headers: {
@@ -85,18 +80,17 @@ upsertUserStorage_fn = async function(feature, key, data) {
85
80
  } catch (e) {
86
81
  const errorMessage = e instanceof Error ? e.message : JSON.stringify(e ?? "");
87
82
  throw new (0, _chunkMBTBE4P5js.UserStorageError)(
88
- `failed to upsert user storage for feature '${feature}' and key '${key}'. ${errorMessage}`
83
+ `failed to upsert user storage for path '${path}'. ${errorMessage}`
89
84
  );
90
85
  }
91
86
  };
92
87
  _getUserStorage = new WeakSet();
93
- getUserStorage_fn = async function(feature, key) {
88
+ getUserStorage_fn = async function(path) {
94
89
  try {
95
90
  const headers = await _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _getAuthorizationHeader, getAuthorizationHeader_fn).call(this);
96
91
  const storageKey = await this.getStorageKey();
97
- const url = new URL(
98
- STORAGE_URL(this.env, feature, _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _createEntryKey, createEntryKey_fn).call(this, key, storageKey))
99
- );
92
+ const encryptedPath = _chunkSLHAVOTEjs.createEntryPath.call(void 0, path, storageKey);
93
+ const url = new URL(STORAGE_URL(this.env, encryptedPath));
100
94
  const response = await fetch(url.toString(), {
101
95
  headers: {
102
96
  "Content-Type": "application/json",
@@ -105,7 +99,7 @@ getUserStorage_fn = async function(feature, key) {
105
99
  });
106
100
  if (response.status === 404) {
107
101
  throw new (0, _chunkMBTBE4P5js.NotFoundError)(
108
- `feature/key set not found for feature '${feature}' and key '${key}'.`
102
+ `feature/key set not found for path '${path}'.`
109
103
  );
110
104
  }
111
105
  if (!response.ok) {
@@ -122,7 +116,7 @@ getUserStorage_fn = async function(feature, key) {
122
116
  }
123
117
  const errorMessage = e instanceof Error ? e.message : JSON.stringify(e ?? "");
124
118
  throw new (0, _chunkMBTBE4P5js.UserStorageError)(
125
- `failed to get user storage for feature '${feature}' and key '${key}'. ${errorMessage}`
119
+ `failed to get user storage for path '${path}'. ${errorMessage}`
126
120
  );
127
121
  }
128
122
  };
@@ -141,4 +135,4 @@ getAuthorizationHeader_fn = async function() {
141
135
 
142
136
 
143
137
  exports.STORAGE_URL = STORAGE_URL; exports.UserStorage = UserStorage;
144
- //# sourceMappingURL=chunk-P52TG263.js.map
138
+ //# sourceMappingURL=chunk-FUPEFLXB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sdk/user-storage.ts"],"names":[],"mappings":"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","sourcesContent":["import type { UserStoragePath } from '../controllers/user-storage/schema';\nimport { createEntryPath } from '../controllers/user-storage/schema';\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(path: UserStoragePath, value: string): Promise<void> {\n await this.#upsertUserStorage(path, value);\n }\n\n async getItem(path: UserStoragePath): Promise<string> {\n return this.#getUserStorage(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(path: UserStoragePath, data: string): 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(path: UserStoragePath): 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 #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"]}
@@ -0,0 +1,40 @@
1
+ import {
2
+ createSHA256Hash
3
+ } from "./chunk-K5UKU454.mjs";
4
+
5
+ // src/controllers/user-storage/schema.ts
6
+ var USER_STORAGE_SCHEMA = {
7
+ notifications: ["notificationSettings"]
8
+ };
9
+ var getFeatureAndKeyFromPath = (path) => {
10
+ const pathRegex = /^\w+\.\w+$/u;
11
+ if (!pathRegex.test(path)) {
12
+ throw new Error(
13
+ `user-storage - path is not in the correct format. Correct format: 'feature.key'`
14
+ );
15
+ }
16
+ const [feature, key] = path.split(".");
17
+ if (!(feature in USER_STORAGE_SCHEMA)) {
18
+ throw new Error(`user-storage - invalid feature provided: ${feature}`);
19
+ }
20
+ const validFeature = USER_STORAGE_SCHEMA[feature];
21
+ if (!validFeature.includes(key)) {
22
+ const validKeys = USER_STORAGE_SCHEMA[feature].join(", ");
23
+ throw new Error(
24
+ `user-storage - invalid key provided for this feature: ${key}. Valid keys: ${validKeys}`
25
+ );
26
+ }
27
+ return { feature, key };
28
+ };
29
+ function createEntryPath(path, storageKey) {
30
+ const { feature, key } = getFeatureAndKeyFromPath(path);
31
+ const hashedKey = createSHA256Hash(key + storageKey);
32
+ return `/${feature}/${hashedKey}`;
33
+ }
34
+
35
+ export {
36
+ USER_STORAGE_SCHEMA,
37
+ getFeatureAndKeyFromPath,
38
+ createEntryPath
39
+ };
40
+ //# sourceMappingURL=chunk-ILIZJQ6X.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/controllers/user-storage/schema.ts"],"sourcesContent":["import { createSHA256Hash } from './encryption';\n\n/**\n * The User Storage Endpoint requires a feature name and a namespace key.\n * Developers can provide additional features and keys by extending these types below.\n */\n\nexport const USER_STORAGE_SCHEMA = {\n notifications: ['notificationSettings'],\n} as const;\n\ntype UserStorageSchema = typeof USER_STORAGE_SCHEMA;\ntype UserStorageFeatures = keyof UserStorageSchema;\ntype UserStorageFeatureKeys<Feature extends UserStorageFeatures> =\n UserStorageSchema[Feature][number];\n\ntype UserStorageFeatureAndKey = {\n feature: UserStorageFeatures;\n key: UserStorageFeatureKeys<UserStorageFeatures>;\n};\n\nexport type UserStoragePath = {\n [K in keyof UserStorageSchema]: `${K}.${UserStorageSchema[K][number]}`;\n}[keyof UserStorageSchema];\n\nexport const getFeatureAndKeyFromPath = (\n path: UserStoragePath,\n): UserStorageFeatureAndKey => {\n const pathRegex = /^\\w+\\.\\w+$/u;\n\n if (!pathRegex.test(path)) {\n throw new Error(\n `user-storage - path is not in the correct format. Correct format: 'feature.key'`,\n );\n }\n\n const [feature, key] = path.split('.') as [\n UserStorageFeatures,\n UserStorageFeatureKeys<UserStorageFeatures>,\n ];\n\n if (!(feature in USER_STORAGE_SCHEMA)) {\n throw new Error(`user-storage - invalid feature provided: ${feature}`);\n }\n\n const validFeature = USER_STORAGE_SCHEMA[feature] as readonly string[];\n\n if (!validFeature.includes(key)) {\n const validKeys = USER_STORAGE_SCHEMA[feature].join(', ');\n\n throw new Error(\n `user-storage - invalid key provided for this feature: ${key}. Valid keys: ${validKeys}`,\n );\n }\n\n return { feature, key };\n};\n\n/**\n * Constructs a unique entry path for a user.\n * This can be done due to the uniqueness of the storage key (no users will share the same storage key).\n * The users entry is a unique hash that cannot be reversed.\n *\n * @param path - string in the form of `${feature}.${key}` that matches schema\n * @param storageKey - users storage key\n * @returns path to store entry\n */\nexport function createEntryPath(\n path: UserStoragePath,\n storageKey: string,\n): string {\n const { feature, key } = getFeatureAndKeyFromPath(path);\n const hashedKey = createSHA256Hash(key + storageKey);\n\n return `/${feature}/${hashedKey}`;\n}\n"],"mappings":";;;;;AAOO,IAAM,sBAAsB;AAAA,EACjC,eAAe,CAAC,sBAAsB;AACxC;AAgBO,IAAM,2BAA2B,CACtC,SAC6B;AAC7B,QAAM,YAAY;AAElB,MAAI,CAAC,UAAU,KAAK,IAAI,GAAG;AACzB,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM,CAAC,SAAS,GAAG,IAAI,KAAK,MAAM,GAAG;AAKrC,MAAI,EAAE,WAAW,sBAAsB;AACrC,UAAM,IAAI,MAAM,4CAA4C,OAAO,EAAE;AAAA,EACvE;AAEA,QAAM,eAAe,oBAAoB,OAAO;AAEhD,MAAI,CAAC,aAAa,SAAS,GAAG,GAAG;AAC/B,UAAM,YAAY,oBAAoB,OAAO,EAAE,KAAK,IAAI;AAExD,UAAM,IAAI;AAAA,MACR,yDAAyD,GAAG,iBAAiB,SAAS;AAAA,IACxF;AAAA,EACF;AAEA,SAAO,EAAE,SAAS,IAAI;AACxB;AAWO,SAAS,gBACd,MACA,YACQ;AACR,QAAM,EAAE,SAAS,IAAI,IAAI,yBAAyB,IAAI;AACtD,QAAM,YAAY,iBAAiB,MAAM,UAAU;AAEnD,SAAO,IAAI,OAAO,IAAI,SAAS;AACjC;","names":[]}
@@ -4,7 +4,7 @@ var _chunkYHGWG3EQjs = require('./chunk-YHGWG3EQ.js');
4
4
 
5
5
 
6
6
 
7
- var _chunk5SXXO4MVjs = require('./chunk-5SXXO4MV.js');
7
+ var _chunk3TE6M5TVjs = require('./chunk-3TE6M5TV.js');
8
8
 
9
9
 
10
10
  var _chunkT3FNDVE3js = require('./chunk-T3FNDVE3.js');
@@ -12,6 +12,7 @@ var _chunkT3FNDVE3js = require('./chunk-T3FNDVE3.js');
12
12
 
13
13
 
14
14
 
15
+
15
16
  var _chunkIGY2S5BCjs = require('./chunk-IGY2S5BC.js');
16
17
 
17
18
  // src/controllers/user-storage/UserStorageController.ts
@@ -31,7 +32,7 @@ var metadata = {
31
32
  anonymous: false
32
33
  }
33
34
  };
34
- var _auth, _notificationServices, _registerMessageHandlers, registerMessageHandlers_fn, _assertProfileSyncingEnabled, assertProfileSyncingEnabled_fn, _getStorageKeyAndBearerToken, getStorageKeyAndBearerToken_fn, _createStorageKey, createStorageKey_fn, __snapSignMessageCache, _snapSignMessage, snapSignMessage_fn, _setIsProfileSyncingUpdateLoading, setIsProfileSyncingUpdateLoading_fn;
35
+ var _auth, _notificationServices, _isUnlocked, _keyringController, _registerMessageHandlers, registerMessageHandlers_fn, _assertProfileSyncingEnabled, assertProfileSyncingEnabled_fn, _getStorageKeyAndBearerToken, getStorageKeyAndBearerToken_fn, _createStorageKey, createStorageKey_fn, __snapSignMessageCache, _snapSignMessage, snapSignMessage_fn, _setIsProfileSyncingUpdateLoading, setIsProfileSyncingUpdateLoading_fn;
35
36
  var UserStorageController = class extends _basecontroller.BaseController {
36
37
  constructor(params) {
37
38
  super({
@@ -102,8 +103,24 @@ var UserStorageController = class extends _basecontroller.BaseController {
102
103
  );
103
104
  }
104
105
  });
106
+ _chunkIGY2S5BCjs.__privateAdd.call(void 0, this, _isUnlocked, false);
107
+ _chunkIGY2S5BCjs.__privateAdd.call(void 0, this, _keyringController, {
108
+ setupLockedStateSubscriptions: () => {
109
+ const { isUnlocked } = this.messagingSystem.call(
110
+ "KeyringController:getState"
111
+ );
112
+ _chunkIGY2S5BCjs.__privateSet.call(void 0, this, _isUnlocked, isUnlocked);
113
+ this.messagingSystem.subscribe("KeyringController:unlock", () => {
114
+ _chunkIGY2S5BCjs.__privateSet.call(void 0, this, _isUnlocked, true);
115
+ });
116
+ this.messagingSystem.subscribe("KeyringController:lock", () => {
117
+ _chunkIGY2S5BCjs.__privateSet.call(void 0, this, _isUnlocked, false);
118
+ });
119
+ }
120
+ });
105
121
  _chunkIGY2S5BCjs.__privateAdd.call(void 0, this, __snapSignMessageCache, {});
106
122
  this.getMetaMetricsState = params.getMetaMetricsState;
123
+ _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _keyringController).setupLockedStateSubscriptions();
107
124
  _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _registerMessageHandlers, registerMessageHandlers_fn).call(this);
108
125
  }
109
126
  async enableProfileSyncing() {
@@ -143,7 +160,7 @@ var UserStorageController = class extends _basecontroller.BaseController {
143
160
  }
144
161
  const isMetaMetricsParticipation = this.getMetaMetricsState();
145
162
  if (!isMetaMetricsParticipation) {
146
- this.messagingSystem.call("AuthenticationController:performSignOut");
163
+ await _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _auth).signOut();
147
164
  }
148
165
  _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _setIsProfileSyncingUpdateLoading, setIsProfileSyncingUpdateLoading_fn).call(this, false);
149
166
  this.update((state) => {
@@ -161,14 +178,14 @@ var UserStorageController = class extends _basecontroller.BaseController {
161
178
  * Allows retrieval of stored data. Data stored is string formatted.
162
179
  * Developers can extend the entry path and entry name through the `schema.ts` file.
163
180
  *
164
- * @param entryKey - entry key that matches schema
181
+ * @param path - string in the form of `${feature}.${key}` that matches schema
165
182
  * @returns the decrypted string contents found from user storage (or null if not found)
166
183
  */
167
- async performGetStorage(entryKey) {
184
+ async performGetStorage(path) {
168
185
  _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _assertProfileSyncingEnabled, assertProfileSyncingEnabled_fn).call(this);
169
186
  const { bearerToken, storageKey } = await _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _getStorageKeyAndBearerToken, getStorageKeyAndBearerToken_fn).call(this);
170
- const result = await _chunk5SXXO4MVjs.getUserStorage.call(void 0, {
171
- entryKey,
187
+ const result = await _chunk3TE6M5TVjs.getUserStorage.call(void 0, {
188
+ path,
172
189
  bearerToken,
173
190
  storageKey
174
191
  });
@@ -178,15 +195,15 @@ var UserStorageController = class extends _basecontroller.BaseController {
178
195
  * Allows storage of user data. Data stored must be string formatted.
179
196
  * Developers can extend the entry path and entry name through the `schema.ts` file.
180
197
  *
181
- * @param entryKey - entry key that matches schema
198
+ * @param path - string in the form of `${feature}.${key}` that matches schema
182
199
  * @param value - The string data you want to store.
183
200
  * @returns nothing. NOTE that an error is thrown if fails to store data.
184
201
  */
185
- async performSetStorage(entryKey, value) {
202
+ async performSetStorage(path, value) {
186
203
  _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _assertProfileSyncingEnabled, assertProfileSyncingEnabled_fn).call(this);
187
204
  const { bearerToken, storageKey } = await _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _getStorageKeyAndBearerToken, getStorageKeyAndBearerToken_fn).call(this);
188
- await _chunk5SXXO4MVjs.upsertUserStorage.call(void 0, value, {
189
- entryKey,
205
+ await _chunk3TE6M5TVjs.upsertUserStorage.call(void 0, value, {
206
+ path,
190
207
  bearerToken,
191
208
  storageKey
192
209
  });
@@ -204,6 +221,8 @@ var UserStorageController = class extends _basecontroller.BaseController {
204
221
  };
205
222
  _auth = new WeakMap();
206
223
  _notificationServices = new WeakMap();
224
+ _isUnlocked = new WeakMap();
225
+ _keyringController = new WeakMap();
207
226
  _registerMessageHandlers = new WeakSet();
208
227
  registerMessageHandlers_fn = function() {
209
228
  this.messagingSystem.registerActionHandler(
@@ -260,6 +279,11 @@ snapSignMessage_fn = async function(message) {
260
279
  if (_chunkIGY2S5BCjs.__privateGet.call(void 0, this, __snapSignMessageCache)[message]) {
261
280
  return _chunkIGY2S5BCjs.__privateGet.call(void 0, this, __snapSignMessageCache)[message];
262
281
  }
282
+ if (!_chunkIGY2S5BCjs.__privateGet.call(void 0, this, _isUnlocked)) {
283
+ throw new Error(
284
+ "#snapSignMessage - unable to call snap, wallet is locked"
285
+ );
286
+ }
263
287
  const result = await this.messagingSystem.call(
264
288
  "SnapController:handleRequest",
265
289
  _chunkYHGWG3EQjs.createSnapSignMessageRequest.call(void 0, message)
@@ -278,4 +302,4 @@ setIsProfileSyncingUpdateLoading_fn = function(isProfileSyncingUpdateLoading) {
278
302
 
279
303
 
280
304
  exports.defaultState = defaultState; exports.UserStorageController = UserStorageController;
281
- //# sourceMappingURL=chunk-DDOYG42A.js.map
305
+ //# sourceMappingURL=chunk-JENTMRXO.js.map