@metamask/profile-sync-controller 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (168) hide show
  1. package/CHANGELOG.md +34 -1
  2. package/auth/mocks/package.json +9 -0
  3. package/auth/package.json +9 -0
  4. package/dist/{chunk-BDO3VJEU.mjs → chunk-2CWF7ZTL.mjs} +2 -2
  5. package/dist/{chunk-7KMONAQI.mjs → chunk-4WXZXVLI.mjs} +7 -9
  6. package/dist/{chunk-7KMONAQI.mjs.map → chunk-4WXZXVLI.mjs.map} +1 -1
  7. package/dist/{chunk-VD2IGTS3.js → chunk-4ZGRRVMI.js} +5 -5
  8. package/dist/{chunk-WWQ65CZY.mjs → chunk-D4SNJOID.mjs} +2 -2
  9. package/dist/chunk-D4SNJOID.mjs.map +1 -0
  10. package/dist/{chunk-SMKTWM6I.js → chunk-DF24ZX4H.js} +2 -3
  11. package/dist/chunk-DF24ZX4H.js.map +1 -0
  12. package/dist/{chunk-NPH5AHLH.mjs → chunk-E7Z5TCQT.mjs} +54 -6
  13. package/dist/chunk-E7Z5TCQT.mjs.map +1 -0
  14. package/dist/chunk-EHZFPUJH.mjs +53 -0
  15. package/dist/chunk-EHZFPUJH.mjs.map +1 -0
  16. package/dist/{chunk-SLHAVOTE.js → chunk-EYZFHZR2.js} +11 -4
  17. package/dist/chunk-EYZFHZR2.js.map +1 -0
  18. package/dist/{chunk-KW3X4TT5.js → chunk-F6BAOSH2.js} +6 -6
  19. package/dist/chunk-F6BAOSH2.js.map +1 -0
  20. package/dist/chunk-GQXYWBFK.js +28 -0
  21. package/dist/chunk-GQXYWBFK.js.map +1 -0
  22. package/dist/{chunk-3TE6M5TV.js → chunk-HMRRB4EX.js} +40 -7
  23. package/dist/chunk-HMRRB4EX.js.map +1 -0
  24. package/dist/{chunk-DRD22DR5.mjs → chunk-J7NSK6BO.mjs} +2 -2
  25. package/dist/chunk-JAQ5TPSZ.js +53 -0
  26. package/dist/chunk-JAQ5TPSZ.js.map +1 -0
  27. package/dist/{chunk-PSR2V3R4.js → chunk-JJ5BDCKD.js} +17 -19
  28. package/dist/chunk-JJ5BDCKD.js.map +1 -0
  29. package/dist/{chunk-G4NU4KP7.js → chunk-KIVBL6OM.js} +6 -6
  30. package/dist/{chunk-FQ5SDMRE.mjs → chunk-KTCSRECK.mjs} +2 -3
  31. package/dist/{chunk-FQ5SDMRE.mjs.map → chunk-KTCSRECK.mjs.map} +1 -1
  32. package/dist/chunk-LDYHGAP4.js +11 -0
  33. package/dist/chunk-LDYHGAP4.js.map +1 -0
  34. package/dist/{chunk-7SW3CC66.mjs → chunk-LGXQBALM.mjs} +2 -2
  35. package/dist/{chunk-5C53GKTU.js.map → chunk-LGXQBALM.mjs.map} +1 -1
  36. package/dist/{chunk-BOET676P.js → chunk-LLG4D2SC.js} +8 -8
  37. package/dist/{chunk-JENTMRXO.js → chunk-LNECIW4K.js} +214 -8
  38. package/dist/chunk-LNECIW4K.js.map +1 -0
  39. package/dist/{chunk-FU7PSGFP.mjs → chunk-LYDHYB6I.mjs} +36 -3
  40. package/dist/chunk-LYDHYB6I.mjs.map +1 -0
  41. package/dist/{chunk-QE5X2BT3.mjs → chunk-M23ZCTKE.mjs} +212 -6
  42. package/dist/chunk-M23ZCTKE.mjs.map +1 -0
  43. package/dist/{chunk-ILIZJQ6X.mjs → chunk-NSSHFDIS.mjs} +10 -3
  44. package/dist/chunk-NSSHFDIS.mjs.map +1 -0
  45. package/dist/{chunk-MNVUKRZC.js → chunk-PRYLTXW4.js} +15 -9
  46. package/dist/chunk-PRYLTXW4.js.map +1 -0
  47. package/dist/{chunk-XSSIP3PJ.js → chunk-Q5KTSMRE.js} +8 -8
  48. package/dist/chunk-QU4EXKJO.mjs +11 -0
  49. package/dist/chunk-QU4EXKJO.mjs.map +1 -0
  50. package/dist/{chunk-CJLDMVV3.mjs → chunk-UHP2Y32K.mjs} +9 -3
  51. package/dist/chunk-UHP2Y32K.mjs.map +1 -0
  52. package/dist/{chunk-4DQF2YNS.js → chunk-WAFY3R2F.js} +41 -16
  53. package/dist/chunk-WAFY3R2F.js.map +1 -0
  54. package/dist/{chunk-VYZPOR47.mjs → chunk-YKOMKXG4.mjs} +4 -4
  55. package/dist/{chunk-WB6MUIML.mjs → chunk-YLURF2PF.mjs} +2 -2
  56. package/dist/{chunk-FUPEFLXB.js → chunk-ZMQRPWJN.js} +60 -12
  57. package/dist/chunk-ZMQRPWJN.js.map +1 -0
  58. package/dist/chunk-ZUPTMFEA.mjs +28 -0
  59. package/dist/chunk-ZUPTMFEA.mjs.map +1 -0
  60. package/dist/{chunk-5C53GKTU.js → chunk-ZX2KHPXG.js} +5 -5
  61. package/dist/chunk-ZX2KHPXG.js.map +1 -0
  62. package/dist/{chunk-XMYWJQNH.mjs → chunk-ZYYAQJ56.mjs} +38 -13
  63. package/dist/chunk-ZYYAQJ56.mjs.map +1 -0
  64. package/dist/controllers/authentication/AuthenticationController.js +4 -21
  65. package/dist/controllers/authentication/AuthenticationController.mjs +3 -20
  66. package/dist/controllers/authentication/index.js +7 -22
  67. package/dist/controllers/authentication/index.mjs +6 -21
  68. package/dist/controllers/authentication/services.js +3 -20
  69. package/dist/controllers/authentication/services.mjs +2 -19
  70. package/dist/controllers/index.js +11 -21
  71. package/dist/controllers/index.mjs +10 -20
  72. package/dist/controllers/user-storage/UserStorageController.js +7 -17
  73. package/dist/controllers/user-storage/UserStorageController.mjs +6 -16
  74. package/dist/controllers/user-storage/accounts/constants.js +12 -0
  75. package/dist/controllers/user-storage/accounts/constants.js.map +1 -0
  76. package/dist/controllers/user-storage/accounts/constants.mjs +12 -0
  77. package/dist/controllers/user-storage/accounts/constants.mjs.map +1 -0
  78. package/dist/controllers/user-storage/accounts/user-storage.js +11 -0
  79. package/dist/controllers/user-storage/accounts/user-storage.js.map +1 -0
  80. package/dist/controllers/user-storage/accounts/user-storage.mjs +11 -0
  81. package/dist/controllers/user-storage/accounts/user-storage.mjs.map +1 -0
  82. package/dist/controllers/user-storage/index.js +10 -18
  83. package/dist/controllers/user-storage/index.mjs +10 -18
  84. package/dist/controllers/user-storage/schema.js +4 -2
  85. package/dist/controllers/user-storage/schema.mjs +5 -3
  86. package/dist/controllers/user-storage/services.js +6 -16
  87. package/dist/controllers/user-storage/services.mjs +5 -15
  88. package/dist/index.js +18 -16
  89. package/dist/index.mjs +17 -15
  90. package/dist/sdk/authentication-jwt-bearer/flow-siwe.js +4 -4
  91. package/dist/sdk/authentication-jwt-bearer/flow-siwe.mjs +3 -3
  92. package/dist/sdk/authentication-jwt-bearer/flow-srp.js +4 -4
  93. package/dist/sdk/authentication-jwt-bearer/flow-srp.mjs +3 -3
  94. package/dist/sdk/authentication-jwt-bearer/services.js +3 -3
  95. package/dist/sdk/authentication-jwt-bearer/services.mjs +2 -2
  96. package/dist/sdk/authentication.js +6 -6
  97. package/dist/sdk/authentication.mjs +5 -5
  98. package/dist/sdk/encryption.js +5 -3
  99. package/dist/sdk/encryption.mjs +6 -4
  100. package/dist/sdk/env.js +2 -2
  101. package/dist/sdk/env.mjs +1 -1
  102. package/dist/sdk/index.js +13 -15
  103. package/dist/sdk/index.mjs +12 -14
  104. package/dist/sdk/user-storage.js +5 -5
  105. package/dist/sdk/user-storage.mjs +4 -4
  106. package/dist/tsconfig.build.tsbuildinfo +1 -1
  107. package/dist/types/controllers/authentication/AuthenticationController.d.ts +6 -3
  108. package/dist/types/controllers/authentication/AuthenticationController.d.ts.map +1 -1
  109. package/dist/types/controllers/authentication/__fixtures__/mockResponses.d.ts +1 -1
  110. package/dist/types/controllers/authentication/__fixtures__/mockResponses.d.ts.map +1 -1
  111. package/dist/types/controllers/authentication/index.d.ts +2 -0
  112. package/dist/types/controllers/authentication/index.d.ts.map +1 -1
  113. package/dist/types/controllers/user-storage/UserStorageController.d.ts +48 -10
  114. package/dist/types/controllers/user-storage/UserStorageController.d.ts.map +1 -1
  115. package/dist/types/controllers/user-storage/__fixtures__/mockAccounts.d.ts +63 -0
  116. package/dist/types/controllers/user-storage/__fixtures__/mockAccounts.d.ts.map +1 -0
  117. package/dist/types/controllers/user-storage/__fixtures__/mockResponses.d.ts +10 -4
  118. package/dist/types/controllers/user-storage/__fixtures__/mockResponses.d.ts.map +1 -1
  119. package/dist/types/controllers/user-storage/__fixtures__/mockServices.d.ts +4 -2
  120. package/dist/types/controllers/user-storage/__fixtures__/mockServices.d.ts.map +1 -1
  121. package/dist/types/controllers/user-storage/accounts/constants.d.ts +4 -0
  122. package/dist/types/controllers/user-storage/accounts/constants.d.ts.map +1 -0
  123. package/dist/types/controllers/user-storage/accounts/user-storage.d.ts +32 -0
  124. package/dist/types/controllers/user-storage/accounts/user-storage.d.ts.map +1 -0
  125. package/dist/types/controllers/user-storage/index.d.ts +2 -0
  126. package/dist/types/controllers/user-storage/index.d.ts.map +1 -1
  127. package/dist/types/controllers/user-storage/schema.d.ts +13 -6
  128. package/dist/types/controllers/user-storage/schema.d.ts.map +1 -1
  129. package/dist/types/controllers/user-storage/services.d.ts +20 -4
  130. package/dist/types/controllers/user-storage/services.d.ts.map +1 -1
  131. package/dist/types/sdk/__fixtures__/mock-userstorage.d.ts +1 -0
  132. package/dist/types/sdk/__fixtures__/mock-userstorage.d.ts.map +1 -1
  133. package/dist/types/sdk/encryption.d.ts +3 -19
  134. package/dist/types/sdk/encryption.d.ts.map +1 -1
  135. package/dist/types/sdk/user-storage.d.ts +4 -3
  136. package/dist/types/sdk/user-storage.d.ts.map +1 -1
  137. package/package.json +37 -6
  138. package/user-storage/mocks/package.json +9 -0
  139. package/user-storage/package.json +9 -0
  140. package/dist/chunk-3TE6M5TV.js.map +0 -1
  141. package/dist/chunk-4DQF2YNS.js.map +0 -1
  142. package/dist/chunk-7SW3CC66.mjs.map +0 -1
  143. package/dist/chunk-B5DBQDB3.mjs +0 -140
  144. package/dist/chunk-B5DBQDB3.mjs.map +0 -1
  145. package/dist/chunk-CJLDMVV3.mjs.map +0 -1
  146. package/dist/chunk-FU7PSGFP.mjs.map +0 -1
  147. package/dist/chunk-FUPEFLXB.js.map +0 -1
  148. package/dist/chunk-ILIZJQ6X.mjs.map +0 -1
  149. package/dist/chunk-JENTMRXO.js.map +0 -1
  150. package/dist/chunk-KW3X4TT5.js.map +0 -1
  151. package/dist/chunk-MNVUKRZC.js.map +0 -1
  152. package/dist/chunk-NPH5AHLH.mjs.map +0 -1
  153. package/dist/chunk-P4DUDLMY.js +0 -140
  154. package/dist/chunk-P4DUDLMY.js.map +0 -1
  155. package/dist/chunk-PSR2V3R4.js.map +0 -1
  156. package/dist/chunk-QE5X2BT3.mjs.map +0 -1
  157. package/dist/chunk-SLHAVOTE.js.map +0 -1
  158. package/dist/chunk-SMKTWM6I.js.map +0 -1
  159. package/dist/chunk-WWQ65CZY.mjs.map +0 -1
  160. package/dist/chunk-XMYWJQNH.mjs.map +0 -1
  161. /package/dist/{chunk-BDO3VJEU.mjs.map → chunk-2CWF7ZTL.mjs.map} +0 -0
  162. /package/dist/{chunk-VD2IGTS3.js.map → chunk-4ZGRRVMI.js.map} +0 -0
  163. /package/dist/{chunk-DRD22DR5.mjs.map → chunk-J7NSK6BO.mjs.map} +0 -0
  164. /package/dist/{chunk-G4NU4KP7.js.map → chunk-KIVBL6OM.js.map} +0 -0
  165. /package/dist/{chunk-BOET676P.js.map → chunk-LLG4D2SC.js.map} +0 -0
  166. /package/dist/{chunk-XSSIP3PJ.js.map → chunk-Q5KTSMRE.js.map} +0 -0
  167. /package/dist/{chunk-VYZPOR47.mjs.map → chunk-YKOMKXG4.mjs.map} +0 -0
  168. /package/dist/{chunk-WB6MUIML.mjs.map → chunk-YLURF2PF.mjs.map} +0 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask/profile-sync-controller",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "The profile sync helps developers synchronize data across multiple clients and devices in a privacy-preserving way. All data saved in the user storage database is encrypted client-side to preserve privacy. The user storage provides a modular design, giving developers the flexibility to construct and manage their storage spaces in a way that best suits their needs",
5
5
  "keywords": [
6
6
  "MetaMask",
@@ -22,12 +22,39 @@
22
22
  "require": "./dist/index.js",
23
23
  "types": "./dist/types/index.d.ts"
24
24
  },
25
+ "./sdk": {
26
+ "import": "./dist/sdk/index.mjs",
27
+ "require": "./dist/sdk/index.js",
28
+ "types": "./dist/types/sdk/index.d.ts"
29
+ },
30
+ "./auth": {
31
+ "import": "./dist/controllers/authentication/index.mjs",
32
+ "require": "./dist/controllers/authentication/index.js",
33
+ "types": "./dist/types/controllers/authentication/index.d.ts"
34
+ },
35
+ "./auth/mocks": {
36
+ "import": "./dist/controllers/authentication/__fixtures__/index.mjs",
37
+ "require": "./dist/controllers/authentication/__fixtures__/index.js",
38
+ "types": "./dist/types/controllers/authentication/__fixtures__/index.d.ts"
39
+ },
40
+ "./user-storage": {
41
+ "import": "./dist/controllers/user-storage/index.mjs",
42
+ "require": "./dist/controllers/user-storage/index.js",
43
+ "types": "./dist/types/controllers/user-storage/index.d.ts"
44
+ },
45
+ "./user-storage/mocks": {
46
+ "import": "./dist/controllers/user-storage/__fixtures__/index.mjs",
47
+ "require": "./dist/controllers/user-storage/__fixtures__/index.js",
48
+ "types": "./dist/types/controllers/user-storage/__fixtures__/index.d.ts"
49
+ },
25
50
  "./package.json": "./package.json"
26
51
  },
27
52
  "main": "./dist/index.js",
28
53
  "types": "./dist/types/index.d.ts",
29
54
  "files": [
30
- "dist/"
55
+ "dist/",
56
+ "auth/",
57
+ "user-storage/"
31
58
  ],
32
59
  "scripts": {
33
60
  "build": "tsup --config ../../tsup.config.ts --tsconfig ./tsconfig.build.json --clean",
@@ -35,13 +62,14 @@
35
62
  "changelog:update": "../../scripts/update-changelog.sh @metamask/profile-sync-controller",
36
63
  "changelog:validate": "../../scripts/validate-changelog.sh @metamask/profile-sync-controller",
37
64
  "publish:preview": "yarn npm publish --tag preview",
65
+ "since-latest-release": "../../scripts/since-latest-release.sh",
38
66
  "test": "NODE_OPTIONS=--experimental-vm-modules jest --reporters=jest-silent-reporter",
39
67
  "test:clean": "NODE_OPTIONS=--experimental-vm-modules jest --clearCache",
40
68
  "test:verbose": "NODE_OPTIONS=--experimental-vm-modules jest --verbose",
41
69
  "test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch"
42
70
  },
43
71
  "dependencies": {
44
- "@metamask/base-controller": "^6.0.2",
72
+ "@metamask/base-controller": "^7.0.0",
45
73
  "@metamask/snaps-sdk": "^6.1.1",
46
74
  "@metamask/snaps-utils": "^7.8.1",
47
75
  "@noble/ciphers": "^0.5.2",
@@ -52,8 +80,10 @@
52
80
  },
53
81
  "devDependencies": {
54
82
  "@lavamoat/allow-scripts": "^3.0.4",
83
+ "@metamask/accounts-controller": "^18.1.1",
55
84
  "@metamask/auto-changelog": "^3.4.4",
56
- "@metamask/keyring-controller": "^17.1.2",
85
+ "@metamask/keyring-api": "^8.1.0",
86
+ "@metamask/keyring-controller": "^17.2.0",
57
87
  "@metamask/snaps-controllers": "^9.3.1",
58
88
  "@types/jest": "^27.4.1",
59
89
  "deepmerge": "^4.2.2",
@@ -64,10 +94,11 @@
64
94
  "ts-jest": "^27.1.4",
65
95
  "typedoc": "^0.24.8",
66
96
  "typedoc-plugin-missing-exports": "^2.0.0",
67
- "typescript": "~5.1.6"
97
+ "typescript": "~5.2.2"
68
98
  },
69
99
  "peerDependencies": {
70
- "@metamask/keyring-controller": "^17.0.0",
100
+ "@metamask/accounts-controller": "^18.1.1",
101
+ "@metamask/keyring-controller": "^17.2.0",
71
102
  "@metamask/snaps-controllers": "^9.3.0"
72
103
  },
73
104
  "engines": {
@@ -0,0 +1,9 @@
1
+ {
2
+ "version": "1.0.0",
3
+ "private": true,
4
+ "description": "",
5
+ "license": "MIT",
6
+ "sideEffects": false,
7
+ "main": "../../dist/controllers/user-storage/__fixtures__/index.js",
8
+ "types": "../../dist/types/controllers/user-storage/__fixtures__/index.d.ts"
9
+ }
@@ -0,0 +1,9 @@
1
+ {
2
+ "version": "1.0.0",
3
+ "private": true,
4
+ "description": "",
5
+ "license": "MIT",
6
+ "sideEffects": false,
7
+ "main": "../dist/controllers/user-storage/index.js",
8
+ "types": "../dist/types/controllers/user-storage/index.d.ts"
9
+ }
@@ -1 +0,0 @@
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 +0,0 @@
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 +0,0 @@
1
- {"version":3,"sources":["../src/controllers/authentication/services.ts"],"sourcesContent":["import { Env, Platform, getEnvUrls, getOidcClientId } from '../../sdk';\n\nconst ENV_URLS = getEnvUrls(Env.PRD);\n\nconst AUTH_ENDPOINT: string = ENV_URLS.authApiUrl;\nexport const AUTH_NONCE_ENDPOINT = `${AUTH_ENDPOINT}/api/v2/nonce`;\nexport const AUTH_LOGIN_ENDPOINT = `${AUTH_ENDPOINT}/api/v2/srp/login`;\n\nconst OIDC_ENDPOINT: string = ENV_URLS.oidcApiUrl || '';\nexport const OIDC_TOKENS_ENDPOINT = `${OIDC_ENDPOINT}/oauth2/token`;\nconst OIDC_CLIENT_ID = (platform: 'mobile' | 'extension') => {\n if (platform === 'extension') {\n return getOidcClientId(Env.PRD, Platform.EXTENSION);\n }\n if (platform === 'mobile') {\n return getOidcClientId(Env.PRD, Platform.MOBILE);\n }\n\n throw new Error(`Unsupported platform - ${platform as string}`);\n};\nconst OIDC_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:jwt-bearer';\n\nexport type NonceResponse = {\n nonce: string;\n};\n\n/**\n * Auth Service - Get Nonce. Used for the initial JWTBearer flow\n *\n * @param publicKey - public key to associate a nonce with\n * @returns the nonce or null if failed\n */\nexport async function getNonce(publicKey: string): Promise<string | null> {\n const nonceUrl = new URL(AUTH_NONCE_ENDPOINT);\n nonceUrl.searchParams.set('identifier', publicKey);\n\n try {\n const nonceResponse = await fetch(nonceUrl.toString());\n if (!nonceResponse.ok) {\n return null;\n }\n\n const nonceJson: NonceResponse = await nonceResponse.json();\n return nonceJson?.nonce ?? null;\n } catch (e) {\n console.error('authentication-controller/services: unable to get nonce', e);\n return null;\n }\n}\n\n/**\n * The Login API Server Response Shape\n */\nexport type LoginResponse = {\n token: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n expires_in: string;\n /**\n * Contains anonymous information about the logged in profile.\n *\n * @property identifier_id - a deterministic unique identifier on the method used to sign in\n * @property profile_id - a unique id for a given profile\n * @property metametrics_id - an anonymous server id\n */\n profile: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n identifier_id: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n profile_id: string;\n };\n};\n\ntype ClientMetaMetrics = {\n metametricsId: string;\n agent: 'extension' | 'mobile';\n};\n\n/**\n * Auth Service - Login. Will perform login with a given signature and will return a single use JWT Token.\n *\n * @param rawMessage - the original message before signing\n * @param signature - the signed message\n * @param clientMetaMetrics - optional client metametrics id (to associate on backend)\n * @returns The Login Response\n */\nexport async function login(\n rawMessage: string,\n signature: string,\n clientMetaMetrics: ClientMetaMetrics,\n): Promise<LoginResponse | null> {\n try {\n const response = await fetch(AUTH_LOGIN_ENDPOINT, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n signature,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n raw_message: rawMessage,\n metametrics: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n metametrics_id: clientMetaMetrics.metametricsId,\n agent: clientMetaMetrics.agent,\n },\n }),\n });\n\n if (!response.ok) {\n return null;\n }\n\n const loginResponse: LoginResponse = await response.json();\n return loginResponse ?? null;\n } catch (e) {\n console.error('authentication-controller/services: unable to login', e);\n return null;\n }\n}\n\n/**\n * The Auth API Token Response Shape\n */\nexport type OAuthTokenResponse = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n access_token: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n expires_in: number;\n};\n\n/**\n * OIDC Service - Access Token. Trades the Auth Token for an access token (to be used for other authenticated endpoints)\n * NOTE - the access token is short lived, which means it is best practice to validate session before calling authenticated endpoints\n *\n * @param jwtToken - the JWT Auth Token, received from `/login`\n * @param platform - the OIDC platform to retrieve access token\n * @returns JWT Access token to store and use on authorized endpoints.\n */\nexport async function getAccessToken(\n jwtToken: string,\n platform: ClientMetaMetrics['agent'],\n): Promise<string | null> {\n const headers = new Headers({\n 'Content-Type': 'application/x-www-form-urlencoded',\n });\n\n const urlEncodedBody = new URLSearchParams();\n urlEncodedBody.append('grant_type', OIDC_GRANT_TYPE);\n urlEncodedBody.append('client_id', OIDC_CLIENT_ID(platform));\n urlEncodedBody.append('assertion', jwtToken);\n\n try {\n const response = await fetch(OIDC_TOKENS_ENDPOINT, {\n method: 'POST',\n headers,\n body: urlEncodedBody.toString(),\n });\n\n if (!response.ok) {\n return null;\n }\n\n const accessTokenResponse: OAuthTokenResponse = await response.json();\n return accessTokenResponse?.access_token ?? null;\n } catch (e) {\n console.error(\n 'authentication-controller/services: unable to get access token',\n e,\n );\n return null;\n }\n}\n\n/**\n * Utility to create the raw login message for the JWT bearer flow (via SRP)\n *\n * @param nonce - nonce received from `/nonce` endpoint\n * @param publicKey - public key used to retrieve nonce and for message signing\n * @returns Raw Message which will be used for signing & logging in.\n */\nexport function createLoginRawMessage(\n nonce: string,\n publicKey: string,\n): `metamask:${string}:${string}` {\n return `metamask:${nonce}:${publicKey}` as const;\n}\n"],"mappings":";;;;;;AAEA,IAAM,WAAW,0BAAkB;AAEnC,IAAM,gBAAwB,SAAS;AAChC,IAAM,sBAAsB,GAAG,aAAa;AAC5C,IAAM,sBAAsB,GAAG,aAAa;AAEnD,IAAM,gBAAwB,SAAS,cAAc;AAC9C,IAAM,uBAAuB,GAAG,aAAa;AACpD,IAAM,iBAAiB,CAAC,aAAqC;AAC3D,MAAI,aAAa,aAAa;AAC5B,WAAO,4DAA2C;AAAA,EACpD;AACA,MAAI,aAAa,UAAU;AACzB,WAAO,sDAAwC;AAAA,EACjD;AAEA,QAAM,IAAI,MAA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AAW,MAAM,MAAM,sBAAsB;AAAA,MACjD,QAAQ;AAAA,MACR;AAAA,MACA,MAAM,eAAe,SAAS;AAAA,IAChC,CAAC;AAED,QAAI,CAAC,SAAS,IAAI;AAChB,aAAO;AAAA,IACT;AAEA,UAAM,sBAA0C,MAAM,SAAS,KAAK;AACpE,WAAO,qBAAqB,gBAAgB;AAAA,EAC9C,SAAS,GAAG;AACV,YAAQ;AAAA,MACN;AAAA,MACA;AAAA,IACF;AACA,WAAO;AAAA,EACT;AACF;AASO,SAAS,sBACd,OACA,WACgC;AAChC,SAAO,YAAY,KAAK,IAAI,SAAS;AACvC;","names":[]}
@@ -1,140 +0,0 @@
1
- import {
2
- __privateAdd,
3
- __privateGet,
4
- __privateMethod
5
- } from "./chunk-U5UIDVOO.mjs";
6
-
7
- // src/sdk/encryption.ts
8
- import { gcm } from "@noble/ciphers/aes";
9
- import { randomBytes } from "@noble/ciphers/webcrypto";
10
- import { pbkdf2 } from "@noble/hashes/pbkdf2";
11
- import { sha256 } from "@noble/hashes/sha256";
12
- import { utf8ToBytes, concatBytes, bytesToHex } from "@noble/hashes/utils";
13
- function byteArrayToBase64(byteArray) {
14
- return Buffer.from(byteArray).toString("base64");
15
- }
16
- function base64ToByteArray(base64) {
17
- return new Uint8Array(Buffer.from(base64, "base64"));
18
- }
19
- function bytesToUtf8(byteArray) {
20
- const decoder = new TextDecoder("utf-8");
21
- return decoder.decode(byteArray);
22
- }
23
- var _ALGORITHM_NONCE_SIZE, _ALGORITHM_KEY_SIZE, _PBKDF2_SALT_SIZE, _PBKDF2_ITERATIONS, _encryptStringV1, encryptStringV1_fn, _decryptStringV1, decryptStringV1_fn, _encrypt, encrypt_fn, _decrypt, decrypt_fn;
24
- var EncryptorDecryptor = class {
25
- constructor() {
26
- __privateAdd(this, _encryptStringV1);
27
- __privateAdd(this, _decryptStringV1);
28
- __privateAdd(this, _encrypt);
29
- __privateAdd(this, _decrypt);
30
- // TODO: Either fix this lint violation or explain why it's necessary to ignore.
31
- // eslint-disable-next-line @typescript-eslint/naming-convention
32
- __privateAdd(this, _ALGORITHM_NONCE_SIZE, 12);
33
- // 12 bytes
34
- // TODO: Either fix this lint violation or explain why it's necessary to ignore.
35
- // eslint-disable-next-line @typescript-eslint/naming-convention
36
- __privateAdd(this, _ALGORITHM_KEY_SIZE, 16);
37
- // 16 bytes
38
- // TODO: Either fix this lint violation or explain why it's necessary to ignore.
39
- // eslint-disable-next-line @typescript-eslint/naming-convention
40
- __privateAdd(this, _PBKDF2_SALT_SIZE, 16);
41
- // 16 bytes
42
- // TODO: Either fix this lint violation or explain why it's necessary to ignore.
43
- // eslint-disable-next-line @typescript-eslint/naming-convention
44
- __privateAdd(this, _PBKDF2_ITERATIONS, 9e5);
45
- }
46
- encryptString(plaintext, password) {
47
- try {
48
- if (plaintext.trim().length === 0) {
49
- throw new Error("No plain text provided");
50
- }
51
- return __privateMethod(this, _encryptStringV1, encryptStringV1_fn).call(this, plaintext, password);
52
- } catch (e) {
53
- const errorMessage = e instanceof Error ? e.message : String(e);
54
- throw new Error(`Unable to encrypt string - ${errorMessage}`);
55
- }
56
- }
57
- decryptString(encryptedDataStr, password) {
58
- try {
59
- const encryptedData = JSON.parse(encryptedDataStr);
60
- if (encryptedData.v === "1") {
61
- return __privateMethod(this, _decryptStringV1, decryptStringV1_fn).call(this, encryptedData, password);
62
- }
63
- throw new Error(
64
- `Unsupported encrypted data payload - ${JSON.stringify(encryptedData)}`
65
- );
66
- } catch (e) {
67
- const errorMessage = e instanceof Error ? e.message : String(e);
68
- throw new Error(`Unable to decrypt string - ${errorMessage}`);
69
- }
70
- }
71
- };
72
- _ALGORITHM_NONCE_SIZE = new WeakMap();
73
- _ALGORITHM_KEY_SIZE = new WeakMap();
74
- _PBKDF2_SALT_SIZE = new WeakMap();
75
- _PBKDF2_ITERATIONS = new WeakMap();
76
- _encryptStringV1 = new WeakSet();
77
- encryptStringV1_fn = function(plaintext, password) {
78
- const salt = randomBytes(__privateGet(this, _PBKDF2_SALT_SIZE));
79
- const key = pbkdf2(sha256, password, salt, {
80
- c: __privateGet(this, _PBKDF2_ITERATIONS),
81
- dkLen: __privateGet(this, _ALGORITHM_KEY_SIZE)
82
- });
83
- const plaintextRaw = utf8ToBytes(plaintext);
84
- const ciphertextAndNonceAndSalt = concatBytes(
85
- salt,
86
- __privateMethod(this, _encrypt, encrypt_fn).call(this, plaintextRaw, key)
87
- );
88
- const encryptedData = byteArrayToBase64(ciphertextAndNonceAndSalt);
89
- const encryptedPayload = {
90
- v: "1",
91
- d: encryptedData,
92
- iterations: __privateGet(this, _PBKDF2_ITERATIONS)
93
- };
94
- return JSON.stringify(encryptedPayload);
95
- };
96
- _decryptStringV1 = new WeakSet();
97
- decryptStringV1_fn = function(data, password) {
98
- const { iterations, d: base64CiphertextAndNonceAndSalt } = data;
99
- const ciphertextAndNonceAndSalt = base64ToByteArray(
100
- base64CiphertextAndNonceAndSalt
101
- );
102
- const salt = ciphertextAndNonceAndSalt.slice(0, __privateGet(this, _PBKDF2_SALT_SIZE));
103
- const ciphertextAndNonce = ciphertextAndNonceAndSalt.slice(
104
- __privateGet(this, _PBKDF2_SALT_SIZE),
105
- ciphertextAndNonceAndSalt.length
106
- );
107
- const key = pbkdf2(sha256, password, salt, {
108
- c: iterations,
109
- dkLen: __privateGet(this, _ALGORITHM_KEY_SIZE)
110
- });
111
- return bytesToUtf8(__privateMethod(this, _decrypt, decrypt_fn).call(this, ciphertextAndNonce, key));
112
- };
113
- _encrypt = new WeakSet();
114
- encrypt_fn = function(plaintext, key) {
115
- const nonce = randomBytes(__privateGet(this, _ALGORITHM_NONCE_SIZE));
116
- const ciphertext = gcm(key, nonce).encrypt(plaintext);
117
- return concatBytes(nonce, ciphertext);
118
- };
119
- _decrypt = new WeakSet();
120
- decrypt_fn = function(ciphertextAndNonce, key) {
121
- const nonce = ciphertextAndNonce.slice(0, __privateGet(this, _ALGORITHM_NONCE_SIZE));
122
- const ciphertext = ciphertextAndNonce.slice(
123
- __privateGet(this, _ALGORITHM_NONCE_SIZE),
124
- ciphertextAndNonce.length
125
- );
126
- return gcm(key, nonce).decrypt(ciphertext);
127
- };
128
- var Encryption = new EncryptorDecryptor();
129
- var encryption_default = Encryption;
130
- function createSHA256Hash(data) {
131
- const hashedData = sha256(data);
132
- return bytesToHex(hashedData);
133
- }
134
-
135
- export {
136
- Encryption,
137
- encryption_default,
138
- createSHA256Hash
139
- };
140
- //# sourceMappingURL=chunk-B5DBQDB3.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/sdk/encryption.ts"],"sourcesContent":["import { gcm } from '@noble/ciphers/aes';\nimport { randomBytes } from '@noble/ciphers/webcrypto';\nimport { pbkdf2 } from '@noble/hashes/pbkdf2';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { utf8ToBytes, concatBytes, bytesToHex } from '@noble/hashes/utils';\n\nexport type EncryptedPayload = {\n v: '1'; // version\n d: string; // data\n iterations: number;\n};\n\n/**\n * Converts Byte Array to Base64 String\n *\n * @param byteArray - array of bytes\n * @returns base64 string\n */\nfunction byteArrayToBase64(byteArray: Uint8Array): string {\n return Buffer.from(byteArray).toString('base64');\n}\n\n/**\n * Converts Base64 String into Byte Array\n *\n * @param base64 - base64 encoded string\n * @returns byte array\n */\nfunction base64ToByteArray(base64: string): Uint8Array {\n return new Uint8Array(Buffer.from(base64, 'base64'));\n}\n\n/**\n * Converts Bytes into UTF-8 Encoded String\n * @param byteArray - array of bytes\n * @returns uft-8 encoded string\n */\nfunction bytesToUtf8(byteArray: Uint8Array): string {\n const decoder = new TextDecoder('utf-8');\n return decoder.decode(byteArray);\n}\n\nclass EncryptorDecryptor {\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 #ALGORITHM_NONCE_SIZE = 12; // 12 bytes\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 #ALGORITHM_KEY_SIZE = 16; // 16 bytes\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 #PBKDF2_SALT_SIZE = 16; // 16 bytes\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 #PBKDF2_ITERATIONS = 900_000;\n\n encryptString(plaintext: string, password: string): string {\n try {\n if (plaintext.trim().length === 0) {\n throw new Error('No plain text provided');\n }\n\n return this.#encryptStringV1(plaintext, password);\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage = e instanceof Error ? e.message : String(e);\n throw new Error(`Unable to encrypt string - ${errorMessage}`);\n }\n }\n\n decryptString(encryptedDataStr: string, password: string): string {\n try {\n const encryptedData: EncryptedPayload = JSON.parse(encryptedDataStr);\n if (encryptedData.v === '1') {\n return this.#decryptStringV1(encryptedData, password);\n }\n throw new Error(\n `Unsupported encrypted data payload - ${JSON.stringify(encryptedData)}`,\n );\n } catch (e) {\n /* istanbul ignore next */\n const errorMessage = e instanceof Error ? e.message : String(e);\n throw new Error(`Unable to decrypt string - ${errorMessage}`);\n }\n }\n\n #encryptStringV1(plaintext: string, password: string): string {\n const salt = randomBytes(this.#PBKDF2_SALT_SIZE);\n\n // Derive a key using PBKDF2.\n const key = pbkdf2(sha256, password, salt, {\n c: this.#PBKDF2_ITERATIONS,\n dkLen: this.#ALGORITHM_KEY_SIZE,\n });\n\n // Encrypt and prepend salt.\n const plaintextRaw = utf8ToBytes(plaintext);\n const ciphertextAndNonceAndSalt = concatBytes(\n salt,\n this.#encrypt(plaintextRaw, key),\n );\n\n // Convert to Base64\n const encryptedData = byteArrayToBase64(ciphertextAndNonceAndSalt);\n\n const encryptedPayload: EncryptedPayload = {\n v: '1',\n d: encryptedData,\n iterations: this.#PBKDF2_ITERATIONS,\n };\n\n return JSON.stringify(encryptedPayload);\n }\n\n #decryptStringV1(data: EncryptedPayload, password: string): string {\n const { iterations, d: base64CiphertextAndNonceAndSalt } = data;\n\n // Decode the base64.\n const ciphertextAndNonceAndSalt = base64ToByteArray(\n base64CiphertextAndNonceAndSalt,\n );\n\n // Create buffers of salt and ciphertextAndNonce.\n const salt = ciphertextAndNonceAndSalt.slice(0, this.#PBKDF2_SALT_SIZE);\n const ciphertextAndNonce = ciphertextAndNonceAndSalt.slice(\n this.#PBKDF2_SALT_SIZE,\n ciphertextAndNonceAndSalt.length,\n );\n\n // Derive the key using PBKDF2.\n const key = pbkdf2(sha256, password, salt, {\n c: iterations,\n dkLen: this.#ALGORITHM_KEY_SIZE,\n });\n\n // Decrypt and return result.\n return bytesToUtf8(this.#decrypt(ciphertextAndNonce, key));\n }\n\n #encrypt(plaintext: Uint8Array, key: Uint8Array): Uint8Array {\n const nonce = randomBytes(this.#ALGORITHM_NONCE_SIZE);\n\n // Encrypt and prepend nonce.\n const ciphertext = gcm(key, nonce).encrypt(plaintext);\n\n return concatBytes(nonce, ciphertext);\n }\n\n #decrypt(ciphertextAndNonce: Uint8Array, key: Uint8Array): Uint8Array {\n // Create buffers of nonce and ciphertext.\n const nonce = ciphertextAndNonce.slice(0, this.#ALGORITHM_NONCE_SIZE);\n const ciphertext = ciphertextAndNonce.slice(\n this.#ALGORITHM_NONCE_SIZE,\n ciphertextAndNonce.length,\n );\n\n // Decrypt and return result.\n return gcm(key, nonce).decrypt(ciphertext);\n }\n}\n\nexport const Encryption = new EncryptorDecryptor();\nexport default Encryption;\n\n/**\n * Create a SHA-256 hash from a given string.\n *\n * @param data - input\n * @returns hash\n */\nexport function createSHA256Hash(data: string): string {\n const hashedData = sha256(data);\n return bytesToHex(hashedData);\n}\n"],"mappings":";;;;;;;AAAA,SAAS,WAAW;AACpB,SAAS,mBAAmB;AAC5B,SAAS,cAAc;AACvB,SAAS,cAAc;AACvB,SAAS,aAAa,aAAa,kBAAkB;AAcrD,SAAS,kBAAkB,WAA+B;AACxD,SAAO,OAAO,KAAK,SAAS,EAAE,SAAS,QAAQ;AACjD;AAQA,SAAS,kBAAkB,QAA4B;AAC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qBAAQ;AAQR,SAAS,iBAAiB,MAAsB;AACrD,QAAM,aAAa,OAAO,IAAI;AAC9B,SAAO,WAAW,UAAU;AAC9B;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/controllers/authentication/index.ts","../src/controllers/authentication/__fixtures__/index.ts","../src/controllers/authentication/__fixtures__/mockResponses.ts"],"sourcesContent":["import Controller from './AuthenticationController';\n\nexport { Controller };\nexport * from './AuthenticationController';\nexport * as Mocks from './__fixtures__';\n","export * from './mockResponses';\n","import type {\n LoginResponse,\n NonceResponse,\n OAuthTokenResponse,\n} from '../services';\nimport {\n AUTH_LOGIN_ENDPOINT,\n AUTH_NONCE_ENDPOINT,\n OIDC_TOKENS_ENDPOINT,\n} from '../services';\n\ntype MockResponse = {\n url: string;\n requestMethod: 'GET' | 'POST' | 'PUT';\n response: unknown;\n};\n\nexport const MOCK_NONCE = '4cbfqzoQpcNxVImGv';\nexport const MOCK_NONCE_RESPONSE: NonceResponse = {\n nonce: MOCK_NONCE,\n};\n\nexport const getMockAuthNonceResponse = () => {\n return {\n url: AUTH_NONCE_ENDPOINT,\n requestMethod: 'GET',\n response: MOCK_NONCE_RESPONSE,\n } satisfies MockResponse;\n};\n\nexport const MOCK_JWT =\n 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';\nexport const MOCK_LOGIN_RESPONSE: LoginResponse = {\n token: MOCK_JWT,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n expires_in: new Date().toString(),\n profile: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n identifier_id: 'MOCK_IDENTIFIER',\n // eslint-disable-next-line @typescript-eslint/naming-convention\n profile_id: 'MOCK_PROFILE_ID',\n },\n};\n\nexport const getMockAuthLoginResponse = () => {\n return {\n url: AUTH_LOGIN_ENDPOINT,\n requestMethod: 'POST',\n response: MOCK_LOGIN_RESPONSE,\n } satisfies MockResponse;\n};\n\nexport const MOCK_ACCESS_TOKEN = `MOCK_ACCESS_TOKEN-${MOCK_JWT}`;\nexport const MOCK_OATH_TOKEN_RESPONSE: OAuthTokenResponse = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n access_token: MOCK_ACCESS_TOKEN,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n expires_in: new Date().getTime(),\n};\n\nexport const getMockAuthAccessTokenResponse = () => {\n return {\n url: OIDC_TOKENS_ENDPOINT,\n requestMethod: 'POST',\n response: MOCK_OATH_TOKEN_RESPONSE,\n } satisfies MockResponse;\n};\n"],"mappings":";;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACiBO,IAAM,aAAa;AACnB,IAAM,sBAAqC;AAAA,EAChD,OAAO;AACT;AAEO,IAAM,2BAA2B,MAAM;AAC5C,SAAO;AAAA,IACL,KAAK;AAAA,IACL,eAAe;AAAA,IACf,UAAU;AAAA,EACZ;AACF;AAEO,IAAM,WACX;AACK,IAAM,sBAAqC;AAAA,EAChD,OAAO;AAAA;AAAA,EAEP,aAAY,oBAAI,KAAK,GAAE,SAAS;AAAA,EAChC,SAAS;AAAA;AAAA,IAEP,eAAe;AAAA;AAAA,IAEf,YAAY;AAAA,EACd;AACF;AAEO,IAAM,2BAA2B,MAAM;AAC5C,SAAO;AAAA,IACL,KAAK;AAAA,IACL,eAAe;AAAA,IACf,UAAU;AAAA,EACZ;AACF;AAEO,IAAM,oBAAoB,qBAAqB,QAAQ;AACvD,IAAM,2BAA+C;AAAA;AAAA,EAE1D,cAAc;AAAA;AAAA,EAEd,aAAY,oBAAI,KAAK,GAAE,QAAQ;AACjC;AAEO,IAAM,iCAAiC,MAAM;AAClD,SAAO;AAAA,IACL,KAAK;AAAA,IACL,eAAe;AAAA,IACf,UAAU;AAAA,EACZ;AACF;","names":[]}
@@ -1 +0,0 @@
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,MAA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AM,aAAa,MAAM,KAAK,cAAc;AAC5C,UAAM,gBAAgB,gBAAgB,MAAM,UAAU;AAEtD,UAAM,MAAM,IAAI,IAAI,YAAY,KAAK,KAAK,aAAa,CAAC;AAExD,UAAM,WAAW,MAAM,MAAM,IAAI,SAAS,GAAG;AAAA,MAC3C,SAAS;AAAA,QACP,gBAAgB;AAAA,QAChB,GAAG;AAAA,MACL;AAAA,IACF,CAAC;AAED,QAAI,SAAS,WAAW,KAAK;AAC3B,YAAM,IAAI;AAAA,QACR,uCAAuC,IAAI;AAAA,MAC7C;AAAA,IACF;AAEA,QAAI,CAAC,SAAS,IAAI;AAChB,YAAM,eAAgB,MAAM,SAAS,KAAK;AAC1C,YAAM,IAAI;AAAA,QACR,uBAAuB,aAAa,OAAO,YAAY,aAAa,KAAK;AAAA,MAC3E;AAAA,IACF;AAEA,UAAM,EAAE,MAAM,cAAc,IAAI,MAAM,SAAS,KAAK;AACpD,WAAO,mBAAW,cAAc,eAAe,UAAU;AAAA,EAC3D,SAAS,GAAG;AACV,QAAI,aAAa,eAAe;AAC9B,YAAM;AAAA,IACR;AAGA,UAAM,eACJ,aAAa,QAAQ,EAAE,UAAU,KAAK,UAAU,KAAK,EAAE;AAEzD,UAAM,IAAI;AAAA,MACR,wCAAwC,IAAI,MAAM,YAAY;AAAA,IAChE;AAAA,EACF;AACF;AAEA;AAAA,oBAAe,SAAC,KAAa,YAA4B;AACvD,QAAM,YAAY,iBAAiB,MAAM,UAAU;AACnD,SAAO;AACT;AAIM;AAAA,4BAAuB,iBAAuC;AAClE,QAAM,cAAc,MAAM,KAAK,OAAO,KAAK,eAAe;AAC1D,SAAO,EAAE,eAAe,UAAU,WAAW,GAAG;AAClD","sourcesContent":["import type { 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"]}
@@ -1 +0,0 @@
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":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/controllers/user-storage/UserStorageController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAIA,SAAS,sBAAsB;AAiC/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;AAjEA;AAiIA,IAAqB,wBAArB,cAAmD,eAIjD;AAAA,EA8DA,YAAY,QAIT;AACD,UAAM;AAAA,MACJ,WAAW,OAAO;AAAA,MAClB;AAAA,MACA,MAAM;AAAA,MACN,OAAO,EAAE,GAAG,cAAc,GAAG,OAAO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CAA4B,WAAS;AACnC,MAAI,CAAC,KAAK,MAAM,yBAAyB;AACvC,UAAM,IAAI;AAAA,MACR,GAAG,cAAc;AAAA,IACnB;AAAA,EACF;AACF;AAKM;AAAA,iCAA4B,iBAG/B;AACD,QAAM,cAAc,MAAM,mBAAK,OAAM,eAAe;AACpD,MAAI,CAAC,aAAa;AAChB,UAAM,IAAI,MAAM,oDAAoD;AAAA,EACtE;AACA,QAAM,aAAa,MAAM,sBAAK,wCAAL;AAEzB,SAAO,EAAE,aAAa,WAAW;AACnC;AAOM;AAAA,sBAAiB,iBAAoB;AACzC,QAAM,KAAa,MAAM,mBAAK,OAAM,aAAa;AACjD,MAAI,CAAC,IAAI;AACP,UAAM,IAAI,MAAM,sDAAsD;AAAA,EACxE;AAEA,QAAM,sBAAsB,MAAM,sBAAK,sCAAL,WAAsB,YAAY,EAAE;AACtE,QAAM,aAAa,iBAAiB,mBAAmB;AACvD,SAAO;AACT;AAEA;AAQM;AAAA,qBAAgB,eAAC,SAAgD;AACrE,MAAI,mBAAK,wBAAuB,OAAO,GAAG;AACxC,WAAO,mBAAK,wBAAuB,OAAO;AAAA,EAC5C;AAEA,MAAI,CAAC,mBAAK,cAAa;AACrB,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM,SAAU,MAAM,KAAK,gBAAgB;AAAA,IACzC;AAAA,IACA,6BAA6B,OAAO;AAAA,EACtC;AAEA,qBAAK,wBAAuB,OAAO,IAAI;AAEvC,SAAO;AACT;AAEA;AAAA,sCAAiC,SAC/B,+BACM;AACN,OAAK,OAAO,CAAC,UAAU;AACrB,UAAM,gCAAgC;AAAA,EACxC,CAAC;AACH","sourcesContent":["import type {\n RestrictedControllerMessenger,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\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 { createSHA256Hash } from './encryption';\nimport type { UserStoragePath } from './schema';\nimport { getUserStorage, upsertUserStorage } from './services';\n\n// TODO: fix external dependencies\nexport declare type NotificationServicesControllerDisableNotificationServices =\n {\n type: `NotificationServicesController:disableNotificationServices`;\n handler: () => Promise<void>;\n };\n\nexport declare type NotificationServicesControllerSelectIsNotificationServicesEnabled =\n {\n type: `NotificationServicesController:selectIsNotificationServicesEnabled`;\n handler: () => boolean;\n };\n\nconst controllerName = 'UserStorageController';\n\n// State\nexport type UserStorageControllerState = {\n /**\n * Condition used by UI and to determine if we can use some of the User Storage methods.\n */\n isProfileSyncingEnabled: boolean | null;\n /**\n * Loading state for the profile syncing update\n */\n isProfileSyncingUpdateLoading: boolean;\n};\n\nexport const defaultState: UserStorageControllerState = {\n isProfileSyncingEnabled: true,\n isProfileSyncingUpdateLoading: false,\n};\n\nconst metadata: StateMetadata<UserStorageControllerState> = {\n isProfileSyncingEnabled: {\n persist: true,\n anonymous: true,\n },\n isProfileSyncingUpdateLoading: {\n persist: false,\n anonymous: false,\n },\n};\n\n// Messenger Actions\ntype CreateActionsObj<Controller extends keyof UserStorageController> = {\n [K in Controller]: {\n type: `${typeof controllerName}:${K}`;\n handler: UserStorageController[K];\n };\n};\ntype ActionsObj = CreateActionsObj<\n | 'performGetStorage'\n | 'performSetStorage'\n | 'getStorageKey'\n | 'enableProfileSyncing'\n | 'disableProfileSyncing'\n>;\nexport type Actions = ActionsObj[keyof ActionsObj];\nexport type UserStorageControllerPerformGetStorage =\n ActionsObj['performGetStorage'];\nexport type UserStorageControllerPerformSetStorage =\n ActionsObj['performSetStorage'];\nexport type UserStorageControllerGetStorageKey = ActionsObj['getStorageKey'];\nexport type UserStorageControllerEnableProfileSyncing =\n ActionsObj['enableProfileSyncing'];\nexport type UserStorageControllerDisableProfileSyncing =\n ActionsObj['disableProfileSyncing'];\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\nexport type AllowedEvents =\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent;\n\n// Messenger\nexport type UserStorageControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n Actions | AllowedActions,\n 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 #notificationServices = {\n disableNotificationServices: async () => {\n return await this.messagingSystem.call(\n 'NotificationServicesController:disableNotificationServices',\n );\n },\n selectIsNotificationServicesEnabled: async () => {\n return this.messagingSystem.call(\n 'NotificationServicesController:selectIsNotificationServicesEnabled',\n );\n },\n };\n\n #isUnlocked = false;\n\n #keyringController = {\n setupLockedStateSubscriptions: () => {\n const { isUnlocked } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n this.#isUnlocked = isUnlocked;\n\n this.messagingSystem.subscribe('KeyringController:unlock', () => {\n this.#isUnlocked = true;\n });\n\n this.messagingSystem.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n },\n };\n\n getMetaMetricsState: () => boolean;\n\n constructor(params: {\n messenger: UserStorageControllerMessenger;\n state?: UserStorageControllerState;\n getMetaMetricsState: () => boolean;\n }) {\n super({\n messenger: params.messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...params.state },\n });\n\n this.getMetaMetricsState = params.getMetaMetricsState;\n this.#keyringController.setupLockedStateSubscriptions();\n this.#registerMessageHandlers();\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performGetStorage',\n this.performGetStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController: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\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: UserStoragePath,\n ): Promise<string | null> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n const result = await getUserStorage({\n path,\n bearerToken,\n storageKey,\n });\n\n return result;\n }\n\n /**\n * Allows 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: UserStoragePath,\n value: string,\n ): Promise<void> {\n this.#assertProfileSyncingEnabled();\n\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n await upsertUserStorage(value, {\n path,\n bearerToken,\n storageKey,\n });\n }\n\n /**\n * Retrieves the storage key, for internal use only!\n *\n * @returns the storage key\n */\n public async getStorageKey(): Promise<string> {\n this.#assertProfileSyncingEnabled();\n const storageKey = await this.#createStorageKey();\n return storageKey;\n }\n\n #assertProfileSyncingEnabled(): void {\n if (!this.state.isProfileSyncingEnabled) {\n throw new Error(\n `${controllerName}: Unable to call method, user is not authenticated`,\n );\n }\n }\n\n /**\n * Utility to get the bearer token and storage key\n */\n async #getStorageKeyAndBearerToken(): Promise<{\n bearerToken: string;\n storageKey: string;\n }> {\n const bearerToken = await this.#auth.getBearerToken();\n if (!bearerToken) {\n throw new Error('UserStorageController - unable to get bearer token');\n }\n const storageKey = await this.#createStorageKey();\n\n return { bearerToken, storageKey };\n }\n\n /**\n * Rather than storing the storage key, we can compute the storage key when needed.\n *\n * @returns the storage key\n */\n async #createStorageKey(): Promise<string> {\n const id: string = await this.#auth.getProfileId();\n if (!id) {\n throw new Error('UserStorageController - unable to create storage key');\n }\n\n const storageKeySignature = await this.#snapSignMessage(`metamask:${id}`);\n const storageKey = createSHA256Hash(storageKeySignature);\n return storageKey;\n }\n\n #_snapSignMessageCache: Record<`metamask:${string}`, string> = {};\n\n /**\n * Signs a specific message using an underlying auth snap.\n *\n * @param message - A specific tagged message to sign.\n * @returns A Signature created by the snap.\n */\n async #snapSignMessage(message: `metamask:${string}`): Promise<string> {\n if (this.#_snapSignMessageCache[message]) {\n return this.#_snapSignMessageCache[message];\n }\n\n if (!this.#isUnlocked) {\n throw new Error(\n '#snapSignMessage - unable to call snap, wallet is locked',\n );\n }\n\n const result = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n createSnapSignMessageRequest(message),\n )) as string;\n\n this.#_snapSignMessageCache[message] = result;\n\n return result;\n }\n\n #setIsProfileSyncingUpdateLoading(\n isProfileSyncingUpdateLoading: boolean,\n ): void {\n this.update((state) => {\n state.isProfileSyncingUpdateLoading = isProfileSyncingUpdateLoading;\n });\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/controllers/authentication/AuthenticationController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAIA,SAAS,sBAAsB;AAmB/B,IAAM,gBAAgB,MAAO,KAAK;AAElC,IAAM,iBAAiB;AA8BhB,IAAM,eAA8C;AAAA,EACzD,YAAY;AACd;AACA,IAAM,WAAyD;AAAA,EAC7D,YAAY;AAAA,IACV,SAAS;AAAA,IACT,WAAW;AAAA,EACb;AAAA,EACA,aAAa;AAAA,IACX,SAAS;AAAA,IACT,WAAW;AAAA,EACb;AACF;AAnEA;AAmHA,IAAqB,2BAArB,cAAsD,eAIpD;AAAA,EAsBA,YAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,EACF,GAQG;AACD,UAAM;AAAA,MACJ;AAAA,MACA;AAAA,MACA,MAAM;AAAA,MACN,OAAO,EAAE,GAAG,cAAc,GAAG,MAAM;AAAA,IACrC,CAAC;AAgBH;AAAA;AAAA;AAAA;AAAA;AAyEA;AAQA,uBAAM;AA+DN;AAyBA;AAAA;AAAA;AAAA;AAAA;AAAA,uBAAM;AA6BN;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,uBAAM;AA7PN;AAEA,oCAAc;AAEd,2CAAqB;AAAA,MACnB,+BAA+B,MAAM;AACnC,cAAM,EAAE,WAAW,IAAI,KAAK,gBAAgB;AAAA,UAC1C;AAAA,QACF;AACA,2BAAK,aAAc;AAEnB,aAAK,gBAAgB,UAAU,4BAA4B,MAAM;AAC/D,6BAAK,aAAc;AAAA,QACrB,CAAC;AAED,aAAK,gBAAgB,UAAU,0BAA0B,MAAM;AAC7D,6BAAK,aAAc;AAAA,QACrB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EvC,SAAO;AACT","sourcesContent":["import type {\n RestrictedControllerMessenger,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n} from '@metamask/keyring-controller';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\n\nimport {\n createSnapPublicKeyRequest,\n createSnapSignMessageRequest,\n} from './auth-snap-requests';\nimport {\n createLoginRawMessage,\n getAccessToken,\n getNonce,\n login,\n} from './services';\n\nconst THIRTY_MIN_MS = 1000 * 60 * 30;\n\nconst controllerName = 'AuthenticationController';\n\n// State\ntype SessionProfile = {\n identifierId: string;\n profileId: string;\n};\n\ntype SessionData = {\n /** profile - anonymous profile data for the given logged in user */\n profile: SessionProfile;\n /** accessToken - used to make requests authorized endpoints */\n accessToken: string;\n /** expiresIn - string date to determine if new access token is required */\n expiresIn: string;\n};\n\ntype MetaMetricsAuth = {\n getMetaMetricsId: () => string | Promise<string>;\n agent: 'extension' | 'mobile';\n};\n\nexport type AuthenticationControllerState = {\n /**\n * Global isSignedIn state.\n * Can be used to determine if \"Profile Syncing\" is enabled.\n */\n isSignedIn: boolean;\n sessionData?: SessionData;\n};\nexport const defaultState: AuthenticationControllerState = {\n isSignedIn: false,\n};\nconst metadata: StateMetadata<AuthenticationControllerState> = {\n isSignedIn: {\n persist: true,\n anonymous: true,\n },\n sessionData: {\n persist: true,\n anonymous: false,\n },\n};\n\n// Messenger Actions\ntype CreateActionsObj<Controller extends keyof AuthenticationController> = {\n [K in Controller]: {\n type: `${typeof controllerName}:${K}`;\n handler: AuthenticationController[K];\n };\n};\ntype ActionsObj = CreateActionsObj<\n | 'performSignIn'\n | 'performSignOut'\n | 'getBearerToken'\n | 'getSessionProfile'\n | 'isSignedIn'\n>;\nexport type Actions = ActionsObj[keyof ActionsObj];\nexport type AuthenticationControllerPerformSignIn = ActionsObj['performSignIn'];\nexport type AuthenticationControllerPerformSignOut =\n ActionsObj['performSignOut'];\nexport type AuthenticationControllerGetBearerToken =\n ActionsObj['getBearerToken'];\nexport type AuthenticationControllerGetSessionProfile =\n ActionsObj['getSessionProfile'];\nexport type AuthenticationControllerIsSignedIn = ActionsObj['isSignedIn'];\n\n// Allowed Actions\nexport type AllowedActions =\n | HandleSnapRequest\n | KeyringControllerGetStateAction;\n\nexport type AllowedEvents =\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent;\n\n// Messenger\nexport type AuthenticationControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n Actions | AllowedActions,\n AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Controller that enables authentication for restricted endpoints.\n * Used for Global Profile Syncing and Notifications\n */\nexport default class AuthenticationController extends BaseController<\n typeof controllerName,\n AuthenticationControllerState,\n AuthenticationControllerMessenger\n> {\n #metametrics: MetaMetricsAuth;\n\n #isUnlocked = false;\n\n #keyringController = {\n setupLockedStateSubscriptions: () => {\n const { isUnlocked } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n this.#isUnlocked = isUnlocked;\n\n this.messagingSystem.subscribe('KeyringController:unlock', () => {\n this.#isUnlocked = true;\n });\n\n this.messagingSystem.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n });\n },\n };\n\n constructor({\n messenger,\n state,\n metametrics,\n }: {\n messenger: AuthenticationControllerMessenger;\n state?: AuthenticationControllerState;\n /**\n * Not using the Messaging System as we\n * do not want to tie this strictly to extension\n */\n metametrics: MetaMetricsAuth;\n }) {\n super({\n messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...state },\n });\n\n if (!metametrics) {\n throw new Error('`metametrics` field is required');\n }\n\n this.#metametrics = metametrics;\n\n this.#keyringController.setupLockedStateSubscriptions();\n this.#registerMessageHandlers();\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n 'AuthenticationController:getBearerToken',\n this.getBearerToken.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'AuthenticationController:getSessionProfile',\n this.getSessionProfile.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'AuthenticationController:isSignedIn',\n this.isSignedIn.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'AuthenticationController:performSignIn',\n this.performSignIn.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'AuthenticationController:performSignOut',\n this.performSignOut.bind(this),\n );\n }\n\n public async performSignIn(): Promise<string> {\n const { accessToken } = await this.#performAuthenticationFlow();\n return accessToken;\n }\n\n public performSignOut(): void {\n this.#assertLoggedIn();\n\n this.update((state) => {\n state.isSignedIn = false;\n state.sessionData = undefined;\n });\n }\n\n public async getBearerToken(): Promise<string> {\n this.#assertLoggedIn();\n\n if (this.#hasValidSession(this.state.sessionData)) {\n return this.state.sessionData.accessToken;\n }\n\n const { accessToken } = await this.#performAuthenticationFlow();\n return accessToken;\n }\n\n /**\n * Will return a session profile.\n * Throws if a user is not logged in.\n *\n * @returns profile for the session.\n */\n public async getSessionProfile(): Promise<SessionProfile> {\n this.#assertLoggedIn();\n\n if (this.#hasValidSession(this.state.sessionData)) {\n return this.state.sessionData.profile;\n }\n\n const { profile } = await this.#performAuthenticationFlow();\n return profile;\n }\n\n public isSignedIn(): boolean {\n return this.state.isSignedIn;\n }\n\n #assertLoggedIn(): void {\n if (!this.state.isSignedIn) {\n throw new Error(\n `${controllerName}: Unable to call method, user is not authenticated`,\n );\n }\n }\n\n async #performAuthenticationFlow(): Promise<{\n profile: SessionProfile;\n accessToken: string;\n }> {\n try {\n // 1. Nonce\n const publicKey = await this.#snapGetPublicKey();\n const nonce = await getNonce(publicKey);\n if (!nonce) {\n throw new Error(`Unable to get nonce`);\n }\n\n // 2. Login\n const rawMessage = createLoginRawMessage(nonce, publicKey);\n const signature = await this.#snapSignMessage(rawMessage);\n const loginResponse = await login(rawMessage, signature, {\n metametricsId: await this.#metametrics.getMetaMetricsId(),\n agent: this.#metametrics.agent,\n });\n if (!loginResponse?.token) {\n throw new Error(`Unable to login`);\n }\n\n const profile: SessionProfile = {\n identifierId: loginResponse.profile.identifier_id,\n profileId: loginResponse.profile.profile_id,\n };\n\n // 3. Trade for Access Token\n const accessToken = await getAccessToken(\n loginResponse.token,\n this.#metametrics.agent,\n );\n if (!accessToken) {\n throw new Error(`Unable to get Access Token`);\n }\n\n // Update Internal State\n this.update((state) => {\n state.isSignedIn = true;\n const expiresIn = new Date();\n expiresIn.setTime(expiresIn.getTime() + THIRTY_MIN_MS);\n state.sessionData = {\n profile,\n accessToken,\n expiresIn: expiresIn.toString(),\n };\n });\n\n return {\n profile,\n accessToken,\n };\n } catch (e) {\n console.error('Failed to authenticate', e);\n const errorMessage =\n e instanceof Error ? e.message : JSON.stringify(e ?? '');\n throw new Error(\n `${controllerName}: Failed to authenticate - ${errorMessage}`,\n );\n }\n }\n\n #hasValidSession(\n sessionData: SessionData | undefined,\n ): sessionData is SessionData {\n if (!sessionData) {\n return false;\n }\n\n const prevDate = Date.parse(sessionData.expiresIn);\n if (isNaN(prevDate)) {\n return false;\n }\n\n const currentDate = new Date();\n const diffMs = Math.abs(currentDate.getTime() - prevDate);\n\n return THIRTY_MIN_MS > diffMs;\n }\n\n #_snapPublicKeyCache: string | undefined;\n\n /**\n * Returns the auth snap public key.\n *\n * @returns The snap public key.\n */\n async #snapGetPublicKey(): Promise<string> {\n if (this.#_snapPublicKeyCache) {\n return this.#_snapPublicKeyCache;\n }\n\n if (!this.#isUnlocked) {\n throw new Error(\n '#snapGetPublicKey - unable to call snap, wallet is locked',\n );\n }\n\n const result = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n createSnapPublicKeyRequest(),\n )) as string;\n\n this.#_snapPublicKeyCache = result;\n\n return result;\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"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/controllers/authentication/index.ts","../src/controllers/authentication/__fixtures__/index.ts","../src/controllers/authentication/__fixtures__/mockResponses.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACiBO,IAAM,aAAa;AACnB,IAAM,sBAAqC;AAAA,EAChD,OAAO;AACT;AAEO,IAAM,2BAA2B,MAAM;AAC5C,SAAO;AAAA,IACL,KAAK;AAAA,IACL,eAAe;AAAA,IACf,UAAU;AAAA,EACZ;AACF;AAEO,IAAM,WACX;AACK,IAAM,sBAAqC;AAAA,EAChD,OAAO;AAAA;AAAA,EAEP,aAAY,oBAAI,KAAK,GAAE,SAAS;AAAA,EAChC,SAAS;AAAA;AAAA,IAEP,eAAe;AAAA;AAAA,IAEf,YAAY;AAAA,EACd;AACF;AAEO,IAAM,2BAA2B,MAAM;AAC5C,SAAO;AAAA,IACL,KAAK;AAAA,IACL,eAAe;AAAA,IACf,UAAU;AAAA,EACZ;AACF;AAEO,IAAM,oBAAoB,qBAAqB,QAAQ;AACvD,IAAM,2BAA+C;AAAA;AAAA,EAE1D,cAAc;AAAA;AAAA,EAEd,aAAY,oBAAI,KAAK,GAAE,QAAQ;AACjC;AAEO,IAAM,iCAAiC,MAAM;AAClD,SAAO;AAAA,IACL,KAAK;AAAA,IACL,eAAe;AAAA,IACf,UAAU;AAAA,EACZ;AACF","sourcesContent":["import Controller from './AuthenticationController';\n\nexport { Controller };\nexport * from './AuthenticationController';\nexport * as Mocks from './__fixtures__';\n","export * from './mockResponses';\n","import type {\n LoginResponse,\n NonceResponse,\n OAuthTokenResponse,\n} from '../services';\nimport {\n AUTH_LOGIN_ENDPOINT,\n AUTH_NONCE_ENDPOINT,\n OIDC_TOKENS_ENDPOINT,\n} from '../services';\n\ntype MockResponse = {\n url: string;\n requestMethod: 'GET' | 'POST' | 'PUT';\n response: unknown;\n};\n\nexport const MOCK_NONCE = '4cbfqzoQpcNxVImGv';\nexport const MOCK_NONCE_RESPONSE: NonceResponse = {\n nonce: MOCK_NONCE,\n};\n\nexport const getMockAuthNonceResponse = () => {\n return {\n url: AUTH_NONCE_ENDPOINT,\n requestMethod: 'GET',\n response: MOCK_NONCE_RESPONSE,\n } satisfies MockResponse;\n};\n\nexport const MOCK_JWT =\n 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';\nexport const MOCK_LOGIN_RESPONSE: LoginResponse = {\n token: MOCK_JWT,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n expires_in: new Date().toString(),\n profile: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n identifier_id: 'MOCK_IDENTIFIER',\n // eslint-disable-next-line @typescript-eslint/naming-convention\n profile_id: 'MOCK_PROFILE_ID',\n },\n};\n\nexport const getMockAuthLoginResponse = () => {\n return {\n url: AUTH_LOGIN_ENDPOINT,\n requestMethod: 'POST',\n response: MOCK_LOGIN_RESPONSE,\n } satisfies MockResponse;\n};\n\nexport const MOCK_ACCESS_TOKEN = `MOCK_ACCESS_TOKEN-${MOCK_JWT}`;\nexport const MOCK_OATH_TOKEN_RESPONSE: OAuthTokenResponse = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n access_token: MOCK_ACCESS_TOKEN,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n expires_in: new Date().getTime(),\n};\n\nexport const getMockAuthAccessTokenResponse = () => {\n return {\n url: OIDC_TOKENS_ENDPOINT,\n requestMethod: 'POST',\n response: MOCK_OATH_TOKEN_RESPONSE,\n } satisfies MockResponse;\n};\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/sdk/user-storage.ts"],"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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAQO,IAAM,cAAc,CAAC,KAAU,kBACpC,GAAG,WAAW,GAAG,EAAE,iBAAiB,uBAAuB,aAAa;AAT1E;AA8BO,IAAM,cAAN,MAAkB;AAAA,EAOvB,YAAY,QAA2B,SAA6B;AA6BpE,uBAAM;AAqCN,uBAAM;AA6CN;AAOA;AAAA;AAAA,uBAAM;AArHJ,SAAK,MAAM,OAAO;AAClB,SAAK,SAAS;AACd,SAAK,UAAU;AAAA,EACjB;AAAA,EAEA,MAAM,QAAQ,MAAuB,OAA8B;AACjE,UAAM,sBAAK,0CAAL,WAAwB,MAAM;AAAA,EACtC;AAAA,EAEA,MAAM,QAAQ,MAAwC;AACpD,WAAO,sBAAK,oCAAL,WAAqB;AAAA,EAC9B;AAAA,EAEA,MAAM,gBAAiC;AACrC,UAAM,aAAa,MAAM,KAAK,QAAQ,SAAS,cAAc;AAC7D,QAAI,YAAY;AACd,aAAO;AAAA,IACT;AAEA,UAAM,cAAc,MAAM,KAAK,OAAO,KAAK,eAAe;AAC1D,UAAM,sBAAsB,MAAM,KAAK,OAAO,KAAK;AAAA,MACjD,YAAY,YAAY,SAAS;AAAA,IACnC;AACA,UAAM,4BAA4B,iBAAiB,mBAAmB;AACtE,UAAM,KAAK,QAAQ,SAAS,cAAc,yBAAyB;AACnE,WAAO;AAAA,EACT;AA+FF;AA7FQ;AAAA,uBAAkB,eAAC,MAAuB,MAA6B;AAC3E,MAAI;AACF,UAAM,UAAU,MAAM,sB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AAAA,MAC7C;AAAA,IACF;AAEA,QAAI,CAAC,SAAS,IAAI;AAChB,YAAM,eAAgB,MAAM,SAAS,KAAK;AAC1C,YAAM,IAAI;AAAA,QACR,uBAAuB,aAAa,OAAO,YAAY,aAAa,KAAK;AAAA,MAC3E;AAAA,IACF;AAEA,UAAM,EAAE,MAAM,cAAc,IAAI,MAAM,SAAS,KAAK;AACpD,WAAO,mBAAW,cAAc,eAAe,UAAU;AAAA,EAC3D,SAAS,GAAG;AACV,QAAI,aAAa,eAAe;AAC9B,YAAM;AAAA,IACR;AAGA,UAAM,eACJ,aAAa,QAAQ,EAAE,UAAU,KAAK,UAAU,KAAK,EAAE;AAEzD,UAAM,IAAI;AAAA,MACR,wCAAwC,IAAI,MAAM,YAAY;AAAA,IAChE;AAAA,EACF;AACF;AAEA;AAAA,oBAAe,SAAC,KAAa,YAA4B;AACvD,QAAM,YAAY,iBAAiB,MAAM,UAAU;AACnD,SAAO;AACT;AAIM;AAAA,4BAAuB,iBAAuC;AAClE,QAAM,cAAc,MAAM,KAAK,OAAO,KAAK,eAAe;AAC1D,SAAO,EAAE,eAAe,UAAU,WAAW,GAAG;AAClD;","names":[]}
@@ -1,140 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
-
3
-
4
-
5
- var _chunkIGY2S5BCjs = require('./chunk-IGY2S5BC.js');
6
-
7
- // src/sdk/encryption.ts
8
- var _aes = require('@noble/ciphers/aes');
9
- var _webcrypto = require('@noble/ciphers/webcrypto');
10
- var _pbkdf2 = require('@noble/hashes/pbkdf2');
11
- var _sha256 = require('@noble/hashes/sha256');
12
- var _utils = require('@noble/hashes/utils');
13
- function byteArrayToBase64(byteArray) {
14
- return Buffer.from(byteArray).toString("base64");
15
- }
16
- function base64ToByteArray(base64) {
17
- return new Uint8Array(Buffer.from(base64, "base64"));
18
- }
19
- function bytesToUtf8(byteArray) {
20
- const decoder = new TextDecoder("utf-8");
21
- return decoder.decode(byteArray);
22
- }
23
- var _ALGORITHM_NONCE_SIZE, _ALGORITHM_KEY_SIZE, _PBKDF2_SALT_SIZE, _PBKDF2_ITERATIONS, _encryptStringV1, encryptStringV1_fn, _decryptStringV1, decryptStringV1_fn, _encrypt, encrypt_fn, _decrypt, decrypt_fn;
24
- var EncryptorDecryptor = class {
25
- constructor() {
26
- _chunkIGY2S5BCjs.__privateAdd.call(void 0, this, _encryptStringV1);
27
- _chunkIGY2S5BCjs.__privateAdd.call(void 0, this, _decryptStringV1);
28
- _chunkIGY2S5BCjs.__privateAdd.call(void 0, this, _encrypt);
29
- _chunkIGY2S5BCjs.__privateAdd.call(void 0, this, _decrypt);
30
- // TODO: Either fix this lint violation or explain why it's necessary to ignore.
31
- // eslint-disable-next-line @typescript-eslint/naming-convention
32
- _chunkIGY2S5BCjs.__privateAdd.call(void 0, this, _ALGORITHM_NONCE_SIZE, 12);
33
- // 12 bytes
34
- // TODO: Either fix this lint violation or explain why it's necessary to ignore.
35
- // eslint-disable-next-line @typescript-eslint/naming-convention
36
- _chunkIGY2S5BCjs.__privateAdd.call(void 0, this, _ALGORITHM_KEY_SIZE, 16);
37
- // 16 bytes
38
- // TODO: Either fix this lint violation or explain why it's necessary to ignore.
39
- // eslint-disable-next-line @typescript-eslint/naming-convention
40
- _chunkIGY2S5BCjs.__privateAdd.call(void 0, this, _PBKDF2_SALT_SIZE, 16);
41
- // 16 bytes
42
- // TODO: Either fix this lint violation or explain why it's necessary to ignore.
43
- // eslint-disable-next-line @typescript-eslint/naming-convention
44
- _chunkIGY2S5BCjs.__privateAdd.call(void 0, this, _PBKDF2_ITERATIONS, 9e5);
45
- }
46
- encryptString(plaintext, password) {
47
- try {
48
- if (plaintext.trim().length === 0) {
49
- throw new Error("No plain text provided");
50
- }
51
- return _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _encryptStringV1, encryptStringV1_fn).call(this, plaintext, password);
52
- } catch (e) {
53
- const errorMessage = e instanceof Error ? e.message : String(e);
54
- throw new Error(`Unable to encrypt string - ${errorMessage}`);
55
- }
56
- }
57
- decryptString(encryptedDataStr, password) {
58
- try {
59
- const encryptedData = JSON.parse(encryptedDataStr);
60
- if (encryptedData.v === "1") {
61
- return _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _decryptStringV1, decryptStringV1_fn).call(this, encryptedData, password);
62
- }
63
- throw new Error(
64
- `Unsupported encrypted data payload - ${JSON.stringify(encryptedData)}`
65
- );
66
- } catch (e) {
67
- const errorMessage = e instanceof Error ? e.message : String(e);
68
- throw new Error(`Unable to decrypt string - ${errorMessage}`);
69
- }
70
- }
71
- };
72
- _ALGORITHM_NONCE_SIZE = new WeakMap();
73
- _ALGORITHM_KEY_SIZE = new WeakMap();
74
- _PBKDF2_SALT_SIZE = new WeakMap();
75
- _PBKDF2_ITERATIONS = new WeakMap();
76
- _encryptStringV1 = new WeakSet();
77
- encryptStringV1_fn = function(plaintext, password) {
78
- const salt = _webcrypto.randomBytes.call(void 0, _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _PBKDF2_SALT_SIZE));
79
- const key = _pbkdf2.pbkdf2.call(void 0, _sha256.sha256, password, salt, {
80
- c: _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _PBKDF2_ITERATIONS),
81
- dkLen: _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _ALGORITHM_KEY_SIZE)
82
- });
83
- const plaintextRaw = _utils.utf8ToBytes.call(void 0, plaintext);
84
- const ciphertextAndNonceAndSalt = _utils.concatBytes.call(void 0,
85
- salt,
86
- _chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _encrypt, encrypt_fn).call(this, plaintextRaw, key)
87
- );
88
- const encryptedData = byteArrayToBase64(ciphertextAndNonceAndSalt);
89
- const encryptedPayload = {
90
- v: "1",
91
- d: encryptedData,
92
- iterations: _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _PBKDF2_ITERATIONS)
93
- };
94
- return JSON.stringify(encryptedPayload);
95
- };
96
- _decryptStringV1 = new WeakSet();
97
- decryptStringV1_fn = function(data, password) {
98
- const { iterations, d: base64CiphertextAndNonceAndSalt } = data;
99
- const ciphertextAndNonceAndSalt = base64ToByteArray(
100
- base64CiphertextAndNonceAndSalt
101
- );
102
- const salt = ciphertextAndNonceAndSalt.slice(0, _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _PBKDF2_SALT_SIZE));
103
- const ciphertextAndNonce = ciphertextAndNonceAndSalt.slice(
104
- _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _PBKDF2_SALT_SIZE),
105
- ciphertextAndNonceAndSalt.length
106
- );
107
- const key = _pbkdf2.pbkdf2.call(void 0, _sha256.sha256, password, salt, {
108
- c: iterations,
109
- dkLen: _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _ALGORITHM_KEY_SIZE)
110
- });
111
- return bytesToUtf8(_chunkIGY2S5BCjs.__privateMethod.call(void 0, this, _decrypt, decrypt_fn).call(this, ciphertextAndNonce, key));
112
- };
113
- _encrypt = new WeakSet();
114
- encrypt_fn = function(plaintext, key) {
115
- const nonce = _webcrypto.randomBytes.call(void 0, _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _ALGORITHM_NONCE_SIZE));
116
- const ciphertext = _aes.gcm.call(void 0, key, nonce).encrypt(plaintext);
117
- return _utils.concatBytes.call(void 0, nonce, ciphertext);
118
- };
119
- _decrypt = new WeakSet();
120
- decrypt_fn = function(ciphertextAndNonce, key) {
121
- const nonce = ciphertextAndNonce.slice(0, _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _ALGORITHM_NONCE_SIZE));
122
- const ciphertext = ciphertextAndNonce.slice(
123
- _chunkIGY2S5BCjs.__privateGet.call(void 0, this, _ALGORITHM_NONCE_SIZE),
124
- ciphertextAndNonce.length
125
- );
126
- return _aes.gcm.call(void 0, key, nonce).decrypt(ciphertext);
127
- };
128
- var Encryption = new EncryptorDecryptor();
129
- var encryption_default = Encryption;
130
- function createSHA256Hash(data) {
131
- const hashedData = _sha256.sha256.call(void 0, data);
132
- return _utils.bytesToHex.call(void 0, hashedData);
133
- }
134
-
135
-
136
-
137
-
138
-
139
- exports.Encryption = Encryption; exports.encryption_default = encryption_default; exports.createSHA256Hash = createSHA256Hash;
140
- //# sourceMappingURL=chunk-P4DUDLMY.js.map