@metamask/snaps-controllers 1.0.2 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (318) hide show
  1. package/CHANGELOG.md +36 -562
  2. package/dist/cjs/cronjob/CronjobController.js +294 -0
  3. package/dist/cjs/cronjob/CronjobController.js.map +1 -0
  4. package/dist/cjs/cronjob/index.js +20 -0
  5. package/dist/cjs/cronjob/index.js.map +1 -0
  6. package/dist/cjs/fsm.js +69 -0
  7. package/dist/cjs/fsm.js.map +1 -0
  8. package/dist/cjs/index.js +23 -0
  9. package/dist/cjs/index.js.map +1 -0
  10. package/dist/cjs/logging.js +15 -0
  11. package/dist/cjs/logging.js.map +1 -0
  12. package/dist/cjs/services/AbstractExecutionService.js +390 -0
  13. package/dist/cjs/services/AbstractExecutionService.js.map +1 -0
  14. package/dist/cjs/services/ExecutionService.js +7 -0
  15. package/dist/cjs/services/ExecutionService.js.map +1 -0
  16. package/dist/cjs/services/ProxyPostMessageStream.js +116 -0
  17. package/dist/cjs/services/ProxyPostMessageStream.js.map +1 -0
  18. package/dist/cjs/services/browser.js +32 -0
  19. package/dist/cjs/services/browser.js.map +1 -0
  20. package/dist/cjs/services/iframe/IframeExecutionService.js +54 -0
  21. package/dist/cjs/services/iframe/IframeExecutionService.js.map +1 -0
  22. package/dist/cjs/services/iframe/index.js +20 -0
  23. package/dist/cjs/services/iframe/index.js.map +1 -0
  24. package/dist/cjs/services/index.js +32 -0
  25. package/dist/cjs/services/index.js.map +1 -0
  26. package/dist/cjs/services/node/NodeProcessExecutionService.js +30 -0
  27. package/dist/cjs/services/node/NodeProcessExecutionService.js.map +1 -0
  28. package/dist/cjs/services/node/NodeThreadExecutionService.js +30 -0
  29. package/dist/cjs/services/node/NodeThreadExecutionService.js.map +1 -0
  30. package/dist/cjs/services/node/index.js +21 -0
  31. package/dist/cjs/services/node/index.js.map +1 -0
  32. package/dist/cjs/services/offscreen/OffscreenExecutionService.js +159 -0
  33. package/dist/cjs/services/offscreen/OffscreenExecutionService.js.map +1 -0
  34. package/dist/cjs/services/offscreen/index.js +20 -0
  35. package/dist/cjs/services/offscreen/index.js.map +1 -0
  36. package/dist/cjs/services/webworker/WebWorkerExecutionService.js +148 -0
  37. package/dist/cjs/services/webworker/WebWorkerExecutionService.js.map +1 -0
  38. package/dist/cjs/services/webworker/index.js +20 -0
  39. package/dist/cjs/services/webworker/index.js.map +1 -0
  40. package/dist/cjs/snaps/RequestQueue.js +63 -0
  41. package/dist/cjs/snaps/RequestQueue.js.map +1 -0
  42. package/dist/cjs/snaps/SnapController.js +1729 -0
  43. package/dist/cjs/snaps/SnapController.js.map +1 -0
  44. package/dist/cjs/snaps/Timer.js +117 -0
  45. package/dist/cjs/snaps/Timer.js.map +1 -0
  46. package/dist/cjs/snaps/endowments/cronjob.js +100 -0
  47. package/dist/cjs/snaps/endowments/cronjob.js.map +1 -0
  48. package/dist/cjs/snaps/endowments/enum.js +23 -0
  49. package/dist/cjs/snaps/endowments/enum.js.map +1 -0
  50. package/dist/cjs/snaps/endowments/ethereum-provider.js +43 -0
  51. package/dist/cjs/snaps/endowments/ethereum-provider.js.map +1 -0
  52. package/dist/cjs/snaps/endowments/index.js +88 -0
  53. package/dist/cjs/snaps/endowments/index.js.map +1 -0
  54. package/dist/cjs/snaps/endowments/lifecycle-hooks.js +37 -0
  55. package/dist/cjs/snaps/endowments/lifecycle-hooks.js.map +1 -0
  56. package/dist/cjs/snaps/endowments/name-lookup.js +106 -0
  57. package/dist/cjs/snaps/endowments/name-lookup.js.map +1 -0
  58. package/dist/cjs/snaps/endowments/network-access.js +44 -0
  59. package/dist/cjs/snaps/endowments/network-access.js.map +1 -0
  60. package/dist/cjs/snaps/endowments/rpc.js +99 -0
  61. package/dist/cjs/snaps/endowments/rpc.js.map +1 -0
  62. package/dist/cjs/snaps/endowments/transaction-insight.js +106 -0
  63. package/dist/cjs/snaps/endowments/transaction-insight.js.map +1 -0
  64. package/dist/cjs/snaps/endowments/web-assembly.js +42 -0
  65. package/dist/cjs/snaps/endowments/web-assembly.js.map +1 -0
  66. package/dist/cjs/snaps/index.js +25 -0
  67. package/dist/cjs/snaps/index.js.map +1 -0
  68. package/dist/cjs/snaps/location/http.js +106 -0
  69. package/dist/cjs/snaps/location/http.js.map +1 -0
  70. package/dist/cjs/snaps/location/index.js +23 -0
  71. package/dist/cjs/snaps/location/index.js.map +1 -0
  72. package/dist/cjs/snaps/location/local.js +93 -0
  73. package/dist/cjs/snaps/location/local.js.map +1 -0
  74. package/dist/cjs/snaps/location/location.js +34 -0
  75. package/dist/cjs/snaps/location/location.js.map +1 -0
  76. package/dist/cjs/snaps/location/npm.js +293 -0
  77. package/dist/cjs/snaps/location/npm.js.map +1 -0
  78. package/dist/cjs/snaps/permissions.js +61 -0
  79. package/dist/cjs/snaps/permissions.js.map +1 -0
  80. package/dist/cjs/snaps/registry/index.js +21 -0
  81. package/dist/cjs/snaps/registry/index.js.map +1 -0
  82. package/dist/cjs/snaps/registry/json.js +277 -0
  83. package/dist/cjs/snaps/registry/json.js.map +1 -0
  84. package/dist/cjs/snaps/registry/registry.js +18 -0
  85. package/dist/cjs/snaps/registry/registry.js.map +1 -0
  86. package/dist/cjs/snaps/selectors.js +13 -0
  87. package/dist/cjs/snaps/selectors.js.map +1 -0
  88. package/dist/cjs/utils.js +70 -0
  89. package/dist/cjs/utils.js.map +1 -0
  90. package/dist/esm/cronjob/CronjobController.js +279 -0
  91. package/dist/esm/cronjob/CronjobController.js.map +1 -0
  92. package/dist/esm/cronjob/index.js +3 -0
  93. package/dist/esm/cronjob/index.js.map +1 -0
  94. package/dist/esm/fsm.js +70 -0
  95. package/dist/esm/fsm.js.map +1 -0
  96. package/dist/esm/index.js +6 -0
  97. package/dist/esm/index.js.map +1 -0
  98. package/dist/esm/logging.js +10 -0
  99. package/dist/esm/logging.js.map +1 -0
  100. package/dist/esm/services/AbstractExecutionService.js +373 -0
  101. package/dist/esm/services/AbstractExecutionService.js.map +1 -0
  102. package/dist/esm/services/ExecutionService.js +4 -0
  103. package/dist/esm/services/ExecutionService.js.map +1 -0
  104. package/dist/esm/services/ProxyPostMessageStream.js +109 -0
  105. package/dist/esm/services/ProxyPostMessageStream.js.map +1 -0
  106. package/dist/esm/services/browser.js +9 -0
  107. package/dist/esm/services/browser.js.map +1 -0
  108. package/dist/esm/services/iframe/IframeExecutionService.js +44 -0
  109. package/dist/esm/services/iframe/IframeExecutionService.js.map +1 -0
  110. package/dist/esm/services/iframe/index.js +3 -0
  111. package/dist/esm/services/iframe/index.js.map +1 -0
  112. package/dist/esm/services/index.js +9 -0
  113. package/dist/esm/services/index.js.map +1 -0
  114. package/dist/esm/services/node/NodeProcessExecutionService.js +20 -0
  115. package/dist/esm/services/node/NodeProcessExecutionService.js.map +1 -0
  116. package/dist/esm/services/node/NodeThreadExecutionService.js +21 -0
  117. package/dist/esm/services/node/NodeThreadExecutionService.js.map +1 -0
  118. package/dist/esm/services/node/index.js +4 -0
  119. package/dist/esm/services/node/index.js.map +1 -0
  120. package/dist/esm/services/offscreen/OffscreenExecutionService.js +149 -0
  121. package/dist/esm/services/offscreen/OffscreenExecutionService.js.map +1 -0
  122. package/dist/esm/services/offscreen/index.js +3 -0
  123. package/dist/esm/services/offscreen/index.js.map +1 -0
  124. package/dist/esm/services/webworker/WebWorkerExecutionService.js +130 -0
  125. package/dist/esm/services/webworker/WebWorkerExecutionService.js.map +1 -0
  126. package/dist/esm/services/webworker/index.js +3 -0
  127. package/dist/esm/services/webworker/index.js.map +1 -0
  128. package/dist/esm/snaps/RequestQueue.js +53 -0
  129. package/dist/esm/snaps/RequestQueue.js.map +1 -0
  130. package/dist/esm/snaps/SnapController.js +1708 -0
  131. package/dist/esm/snaps/SnapController.js.map +1 -0
  132. package/dist/esm/snaps/Timer.js +107 -0
  133. package/dist/esm/snaps/Timer.js.map +1 -0
  134. package/dist/esm/snaps/endowments/cronjob.js +99 -0
  135. package/dist/esm/snaps/endowments/cronjob.js.map +1 -0
  136. package/dist/esm/snaps/endowments/enum.js +13 -0
  137. package/dist/esm/snaps/endowments/enum.js.map +1 -0
  138. package/dist/esm/snaps/endowments/ethereum-provider.js +33 -0
  139. package/dist/esm/snaps/endowments/ethereum-provider.js.map +1 -0
  140. package/dist/esm/snaps/endowments/index.js +45 -0
  141. package/dist/esm/snaps/endowments/index.js.map +1 -0
  142. package/dist/esm/snaps/endowments/lifecycle-hooks.js +27 -0
  143. package/dist/esm/snaps/endowments/lifecycle-hooks.js.map +1 -0
  144. package/dist/esm/snaps/endowments/name-lookup.js +98 -0
  145. package/dist/esm/snaps/endowments/name-lookup.js.map +1 -0
  146. package/dist/esm/snaps/endowments/network-access.js +34 -0
  147. package/dist/esm/snaps/endowments/network-access.js.map +1 -0
  148. package/dist/esm/snaps/endowments/rpc.js +88 -0
  149. package/dist/esm/snaps/endowments/rpc.js.map +1 -0
  150. package/dist/esm/snaps/endowments/transaction-insight.js +99 -0
  151. package/dist/esm/snaps/endowments/transaction-insight.js.map +1 -0
  152. package/dist/esm/snaps/endowments/web-assembly.js +32 -0
  153. package/dist/esm/snaps/endowments/web-assembly.js.map +1 -0
  154. package/dist/esm/snaps/index.js +8 -0
  155. package/dist/esm/snaps/index.js.map +1 -0
  156. package/dist/{snaps → esm/snaps}/location/http.js +52 -31
  157. package/dist/esm/snaps/location/http.js.map +1 -0
  158. package/dist/esm/snaps/location/index.js +6 -0
  159. package/dist/esm/snaps/location/index.js.map +1 -0
  160. package/dist/esm/snaps/location/local.js +83 -0
  161. package/dist/esm/snaps/location/local.js.map +1 -0
  162. package/dist/esm/snaps/location/location.js +30 -0
  163. package/dist/esm/snaps/location/location.js.map +1 -0
  164. package/dist/{snaps → esm/snaps}/location/npm.js +143 -117
  165. package/dist/esm/snaps/location/npm.js.map +1 -0
  166. package/dist/esm/snaps/permissions.js +50 -0
  167. package/dist/esm/snaps/permissions.js.map +1 -0
  168. package/dist/esm/snaps/registry/index.js +4 -0
  169. package/dist/esm/snaps/registry/index.js.map +1 -0
  170. package/dist/esm/snaps/registry/json.js +267 -0
  171. package/dist/esm/snaps/registry/json.js.map +1 -0
  172. package/dist/esm/snaps/registry/registry.js +8 -0
  173. package/dist/esm/snaps/registry/registry.js.map +1 -0
  174. package/dist/esm/snaps/selectors.js +3 -0
  175. package/dist/esm/snaps/selectors.js.map +1 -0
  176. package/dist/{utils.js → esm/utils.js} +21 -30
  177. package/dist/esm/utils.js.map +1 -0
  178. package/dist/{cronjob → types/cronjob}/CronjobController.d.ts +12 -11
  179. package/dist/{fsm.d.ts → types/fsm.d.ts} +1 -1
  180. package/dist/{index.d.ts → types/index.d.ts} +0 -1
  181. package/dist/{services → types/services}/AbstractExecutionService.d.ts +4 -4
  182. package/dist/{services → types/services}/ExecutionService.d.ts +3 -3
  183. package/dist/{services/offscreen/OffscreenPostMessageStream.d.ts → types/services/ProxyPostMessageStream.d.ts} +10 -10
  184. package/dist/{services → types/services}/browser.d.ts +2 -0
  185. package/dist/{services → types/services}/iframe/IframeExecutionService.d.ts +3 -2
  186. package/dist/{services → types/services}/index.d.ts +2 -0
  187. package/dist/{services → types/services}/node/NodeProcessExecutionService.d.ts +4 -3
  188. package/dist/{services → types/services}/node/NodeThreadExecutionService.d.ts +3 -2
  189. package/dist/{services → types/services}/offscreen/OffscreenExecutionService.d.ts +4 -3
  190. package/dist/types/services/offscreen/index.d.ts +1 -0
  191. package/dist/types/services/webworker/WebWorkerExecutionService.d.ts +45 -0
  192. package/dist/types/services/webworker/index.d.ts +1 -0
  193. package/dist/{snaps → types/snaps}/SnapController.d.ts +78 -39
  194. package/dist/{snaps → types/snaps}/endowments/cronjob.d.ts +5 -3
  195. package/dist/{snaps → types/snaps}/endowments/enum.d.ts +3 -3
  196. package/dist/{snaps → types/snaps}/endowments/ethereum-provider.d.ts +2 -1
  197. package/dist/{snaps → types/snaps}/endowments/index.d.ts +23 -23
  198. package/dist/types/snaps/endowments/lifecycle-hooks.d.ts +15 -0
  199. package/dist/types/snaps/endowments/name-lookup.d.ts +38 -0
  200. package/dist/{snaps → types/snaps}/endowments/network-access.d.ts +2 -1
  201. package/dist/{snaps → types/snaps}/endowments/rpc.d.ts +5 -3
  202. package/dist/{snaps → types/snaps}/endowments/transaction-insight.d.ts +3 -2
  203. package/dist/{snaps → types/snaps}/endowments/web-assembly.d.ts +2 -1
  204. package/dist/{snaps → types/snaps}/index.d.ts +2 -0
  205. package/dist/{snaps → types/snaps}/location/http.d.ts +3 -2
  206. package/dist/{snaps → types/snaps}/location/local.d.ts +3 -3
  207. package/dist/{snaps → types/snaps}/location/location.d.ts +2 -2
  208. package/dist/types/snaps/location/npm.d.ts +49 -0
  209. package/dist/types/snaps/permissions.d.ts +16 -0
  210. package/dist/{snaps → types/snaps}/registry/json.d.ts +5 -4
  211. package/dist/{snaps → types/snaps}/registry/registry.d.ts +5 -5
  212. package/dist/types/snaps/selectors.d.ts +2 -0
  213. package/dist/{utils.d.ts → types/utils.d.ts} +14 -14
  214. package/package.json +55 -45
  215. package/dist/cronjob/CronjobController.js +0 -248
  216. package/dist/cronjob/CronjobController.js.map +0 -1
  217. package/dist/cronjob/index.js +0 -18
  218. package/dist/cronjob/index.js.map +0 -1
  219. package/dist/fsm.js +0 -75
  220. package/dist/fsm.js.map +0 -1
  221. package/dist/index.js +0 -22
  222. package/dist/index.js.map +0 -1
  223. package/dist/logging.js +0 -13
  224. package/dist/logging.js.map +0 -1
  225. package/dist/multichain/MultiChainController.d.ts +0 -137
  226. package/dist/multichain/MultiChainController.js +0 -339
  227. package/dist/multichain/MultiChainController.js.map +0 -1
  228. package/dist/multichain/index.d.ts +0 -3
  229. package/dist/multichain/index.js +0 -20
  230. package/dist/multichain/index.js.map +0 -1
  231. package/dist/multichain/matching.d.ts +0 -9
  232. package/dist/multichain/matching.js +0 -57
  233. package/dist/multichain/matching.js.map +0 -1
  234. package/dist/multichain/middleware.d.ts +0 -14
  235. package/dist/multichain/middleware.js +0 -42
  236. package/dist/multichain/middleware.js.map +0 -1
  237. package/dist/services/AbstractExecutionService.js +0 -318
  238. package/dist/services/AbstractExecutionService.js.map +0 -1
  239. package/dist/services/ExecutionService.js +0 -4
  240. package/dist/services/ExecutionService.js.map +0 -1
  241. package/dist/services/browser.js +0 -22
  242. package/dist/services/browser.js.map +0 -1
  243. package/dist/services/iframe/IframeExecutionService.js +0 -30
  244. package/dist/services/iframe/IframeExecutionService.js.map +0 -1
  245. package/dist/services/iframe/index.js +0 -18
  246. package/dist/services/iframe/index.js.map +0 -1
  247. package/dist/services/index.js +0 -22
  248. package/dist/services/index.js.map +0 -1
  249. package/dist/services/node/NodeProcessExecutionService.js +0 -18
  250. package/dist/services/node/NodeProcessExecutionService.js.map +0 -1
  251. package/dist/services/node/NodeThreadExecutionService.js +0 -19
  252. package/dist/services/node/NodeThreadExecutionService.js.map +0 -1
  253. package/dist/services/node/index.js +0 -19
  254. package/dist/services/node/index.js.map +0 -1
  255. package/dist/services/offscreen/OffscreenExecutionService.js +0 -100
  256. package/dist/services/offscreen/OffscreenExecutionService.js.map +0 -1
  257. package/dist/services/offscreen/OffscreenPostMessageStream.js +0 -66
  258. package/dist/services/offscreen/OffscreenPostMessageStream.js.map +0 -1
  259. package/dist/services/offscreen/index.d.ts +0 -2
  260. package/dist/services/offscreen/index.js +0 -19
  261. package/dist/services/offscreen/index.js.map +0 -1
  262. package/dist/snaps/RequestQueue.js +0 -44
  263. package/dist/snaps/RequestQueue.js.map +0 -1
  264. package/dist/snaps/SnapController.js +0 -1478
  265. package/dist/snaps/SnapController.js.map +0 -1
  266. package/dist/snaps/Timer.js +0 -86
  267. package/dist/snaps/Timer.js.map +0 -1
  268. package/dist/snaps/endowments/cronjob.js +0 -105
  269. package/dist/snaps/endowments/cronjob.js.map +0 -1
  270. package/dist/snaps/endowments/enum.js +0 -15
  271. package/dist/snaps/endowments/enum.js.map +0 -1
  272. package/dist/snaps/endowments/ethereum-provider.js +0 -32
  273. package/dist/snaps/endowments/ethereum-provider.js.map +0 -1
  274. package/dist/snaps/endowments/index.js +0 -60
  275. package/dist/snaps/endowments/index.js.map +0 -1
  276. package/dist/snaps/endowments/keyring.d.ts +0 -40
  277. package/dist/snaps/endowments/keyring.js +0 -103
  278. package/dist/snaps/endowments/keyring.js.map +0 -1
  279. package/dist/snaps/endowments/long-running.d.ts +0 -13
  280. package/dist/snaps/endowments/long-running.js +0 -29
  281. package/dist/snaps/endowments/long-running.js.map +0 -1
  282. package/dist/snaps/endowments/network-access.js +0 -30
  283. package/dist/snaps/endowments/network-access.js.map +0 -1
  284. package/dist/snaps/endowments/rpc.js +0 -92
  285. package/dist/snaps/endowments/rpc.js.map +0 -1
  286. package/dist/snaps/endowments/transaction-insight.js +0 -106
  287. package/dist/snaps/endowments/transaction-insight.js.map +0 -1
  288. package/dist/snaps/endowments/web-assembly.js +0 -31
  289. package/dist/snaps/endowments/web-assembly.js.map +0 -1
  290. package/dist/snaps/index.js +0 -21
  291. package/dist/snaps/index.js.map +0 -1
  292. package/dist/snaps/location/http.js.map +0 -1
  293. package/dist/snaps/location/index.js +0 -21
  294. package/dist/snaps/location/index.js.map +0 -1
  295. package/dist/snaps/location/local.js +0 -51
  296. package/dist/snaps/location/local.js.map +0 -1
  297. package/dist/snaps/location/location.js +0 -34
  298. package/dist/snaps/location/location.js.map +0 -1
  299. package/dist/snaps/location/npm.d.ts +0 -28
  300. package/dist/snaps/location/npm.js.map +0 -1
  301. package/dist/snaps/registry/index.js +0 -19
  302. package/dist/snaps/registry/index.js.map +0 -1
  303. package/dist/snaps/registry/json.js +0 -197
  304. package/dist/snaps/registry/json.js.map +0 -1
  305. package/dist/snaps/registry/registry.js +0 -11
  306. package/dist/snaps/registry/registry.js.map +0 -1
  307. package/dist/snaps/selectors.d.ts +0 -2
  308. package/dist/snaps/selectors.js +0 -6
  309. package/dist/snaps/selectors.js.map +0 -1
  310. package/dist/utils.js.map +0 -1
  311. /package/dist/{cronjob → types/cronjob}/index.d.ts +0 -0
  312. /package/dist/{logging.d.ts → types/logging.d.ts} +0 -0
  313. /package/dist/{services → types/services}/iframe/index.d.ts +0 -0
  314. /package/dist/{services → types/services}/node/index.d.ts +0 -0
  315. /package/dist/{snaps → types/snaps}/RequestQueue.d.ts +0 -0
  316. /package/dist/{snaps → types/snaps}/Timer.d.ts +0 -0
  317. /package/dist/{snaps → types/snaps}/location/index.d.ts +0 -0
  318. /package/dist/{snaps → types/snaps}/registry/index.d.ts +0 -0
@@ -0,0 +1,1729 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ function _export(target, all) {
6
+ for(var name in all)Object.defineProperty(target, name, {
7
+ enumerable: true,
8
+ get: all[name]
9
+ });
10
+ }
11
+ _export(exports, {
12
+ controllerName: function() {
13
+ return controllerName;
14
+ },
15
+ SNAP_APPROVAL_INSTALL: function() {
16
+ return SNAP_APPROVAL_INSTALL;
17
+ },
18
+ SNAP_APPROVAL_UPDATE: function() {
19
+ return SNAP_APPROVAL_UPDATE;
20
+ },
21
+ SNAP_APPROVAL_RESULT: function() {
22
+ return SNAP_APPROVAL_RESULT;
23
+ },
24
+ SnapController: function() {
25
+ return SnapController;
26
+ }
27
+ });
28
+ const _basecontroller = require("@metamask/base-controller");
29
+ const _permissioncontroller = require("@metamask/permission-controller");
30
+ const _rpcmethods = require("@metamask/rpc-methods");
31
+ const _snapsutils = require("@metamask/snaps-utils");
32
+ const _utils = require("@metamask/utils");
33
+ const _fsm = require("@xstate/fsm");
34
+ const _ethrpcerrors = require("eth-rpc-errors");
35
+ const _nanoid = require("nanoid");
36
+ const _fsm1 = require("../fsm");
37
+ const _logging = require("../logging");
38
+ const _utils1 = require("../utils");
39
+ const _endowments = require("./endowments");
40
+ const _rpc = require("./endowments/rpc");
41
+ const _location = require("./location");
42
+ const _permissions = require("./permissions");
43
+ const _registry = require("./registry");
44
+ const _RequestQueue = require("./RequestQueue");
45
+ const _Timer = require("./Timer");
46
+ function _check_private_redeclaration(obj, privateCollection) {
47
+ if (privateCollection.has(obj)) {
48
+ throw new TypeError("Cannot initialize the same private elements twice on an object");
49
+ }
50
+ }
51
+ function _class_apply_descriptor_get(receiver, descriptor) {
52
+ if (descriptor.get) {
53
+ return descriptor.get.call(receiver);
54
+ }
55
+ return descriptor.value;
56
+ }
57
+ function _class_apply_descriptor_set(receiver, descriptor, value) {
58
+ if (descriptor.set) {
59
+ descriptor.set.call(receiver, value);
60
+ } else {
61
+ if (!descriptor.writable) {
62
+ throw new TypeError("attempted to set read only private field");
63
+ }
64
+ descriptor.value = value;
65
+ }
66
+ }
67
+ function _class_extract_field_descriptor(receiver, privateMap, action) {
68
+ if (!privateMap.has(receiver)) {
69
+ throw new TypeError("attempted to " + action + " private field on non-instance");
70
+ }
71
+ return privateMap.get(receiver);
72
+ }
73
+ function _class_private_field_get(receiver, privateMap) {
74
+ var descriptor = _class_extract_field_descriptor(receiver, privateMap, "get");
75
+ return _class_apply_descriptor_get(receiver, descriptor);
76
+ }
77
+ function _class_private_field_init(obj, privateMap, value) {
78
+ _check_private_redeclaration(obj, privateMap);
79
+ privateMap.set(obj, value);
80
+ }
81
+ function _class_private_field_set(receiver, privateMap, value) {
82
+ var descriptor = _class_extract_field_descriptor(receiver, privateMap, "set");
83
+ _class_apply_descriptor_set(receiver, descriptor, value);
84
+ return value;
85
+ }
86
+ function _class_private_method_get(receiver, privateSet, fn) {
87
+ if (!privateSet.has(receiver)) {
88
+ throw new TypeError("attempted to get private field on non-instance");
89
+ }
90
+ return fn;
91
+ }
92
+ function _class_private_method_init(obj, privateSet) {
93
+ _check_private_redeclaration(obj, privateSet);
94
+ privateSet.add(obj);
95
+ }
96
+ function _define_property(obj, key, value) {
97
+ if (key in obj) {
98
+ Object.defineProperty(obj, key, {
99
+ value: value,
100
+ enumerable: true,
101
+ configurable: true,
102
+ writable: true
103
+ });
104
+ } else {
105
+ obj[key] = value;
106
+ }
107
+ return obj;
108
+ }
109
+ const controllerName = 'SnapController';
110
+ const SNAP_APPROVAL_INSTALL = 'wallet_installSnap';
111
+ const SNAP_APPROVAL_UPDATE = 'wallet_updateSnap';
112
+ const SNAP_APPROVAL_RESULT = 'wallet_installSnapResult';
113
+ const TRUNCATED_SNAP_PROPERTIES = new Set([
114
+ 'initialPermissions',
115
+ 'id',
116
+ 'version',
117
+ 'enabled',
118
+ 'blocked'
119
+ ]);
120
+ const defaultState = {
121
+ snapErrors: {},
122
+ snaps: {},
123
+ snapStates: {}
124
+ };
125
+ /**
126
+ * Truncates the properties of a snap to only ones that are easily serializable.
127
+ *
128
+ * @param snap - The snap to truncate.
129
+ * @returns Object with serializable snap properties.
130
+ */ function truncateSnap(snap) {
131
+ const truncatedSnap = Object.keys(snap).reduce((serialized, key)=>{
132
+ if (TRUNCATED_SNAP_PROPERTIES.has(key)) {
133
+ serialized[key] = snap[key];
134
+ }
135
+ return serialized;
136
+ }, {});
137
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
138
+ return truncatedSnap;
139
+ }
140
+ const name = 'SnapController';
141
+ var _closeAllConnections = /*#__PURE__*/ new WeakMap(), _dynamicPermissions = /*#__PURE__*/ new WeakMap(), _environmentEndowmentPermissions = /*#__PURE__*/ new WeakMap(), _excludedPermissions = /*#__PURE__*/ new WeakMap(), _featureFlags = /*#__PURE__*/ new WeakMap(), _fetchFunction = /*#__PURE__*/ new WeakMap(), _idleTimeCheckInterval = /*#__PURE__*/ new WeakMap(), _maxIdleTime = /*#__PURE__*/ new WeakMap(), _detectSnapLocation = /*#__PURE__*/ new WeakMap(), _snapsRuntimeData = /*#__PURE__*/ new WeakMap(), _rollbackSnapshots = /*#__PURE__*/ new WeakMap(), _timeoutForLastRequestStatus = /*#__PURE__*/ new WeakMap(), _statusMachine = /*#__PURE__*/ new WeakMap(), /**
142
+ * We track status of a Snap using a finite-state-machine.
143
+ * It keeps track of whether the snap is started / stopped / etc.
144
+ *
145
+ * @see {@link SnapController.transition} for interacting with the machine.
146
+ */ // We initialize the machine in the instance because the status is currently tightly coupled
147
+ // with the SnapController - the guard checks for enabled status inside the SnapController state.
148
+ // In the future, side-effects could be added to the machine during transitions.
149
+ _initializeStateMachine = /*#__PURE__*/ new WeakSet(), /**
150
+ * Constructor helper for registering the controller's messaging system
151
+ * actions.
152
+ */ _registerMessageHandlers = /*#__PURE__*/ new WeakSet(), _pollForLastRequestStatus = /*#__PURE__*/ new WeakSet(), _blockSnap = /*#__PURE__*/ new WeakSet(), /**
153
+ * Unblocks a snap so that it can be enabled and started again. Emits
154
+ * {@link SnapUnblocked}. Does nothing if the snap is not installed or already
155
+ * unblocked.
156
+ *
157
+ * @param snapId - The id of the snap to unblock.
158
+ */ _unblockSnap = /*#__PURE__*/ new WeakSet(), _assertIsInstallAllowed = /*#__PURE__*/ new WeakSet(), _stopSnapsLastRequestPastMax = /*#__PURE__*/ new WeakSet(), /**
159
+ * Transitions between states using `snapStatusStateMachineConfig` as the template to figure out
160
+ * the next state. This transition function uses a very minimal subset of XState conventions:
161
+ * - supports initial state
162
+ * - .on supports raw event target string
163
+ * - .on supports {target, cond} object
164
+ * - the arguments for `cond` is the `SerializedSnap` instead of Xstate convention of `(event,
165
+ * context) => boolean`
166
+ *
167
+ * @param snapId - The id of the snap to transition.
168
+ * @param event - The event enum to use to transition.
169
+ */ _transition = /*#__PURE__*/ new WeakSet(), _terminateSnap = /*#__PURE__*/ new WeakSet(), /**
170
+ * Removes a snap's permission (caveat) from all subjects.
171
+ *
172
+ * @param snapId - The id of the Snap.
173
+ */ _removeSnapFromSubjects = /*#__PURE__*/ new WeakSet(), /**
174
+ * Safely revokes all permissions granted to a Snap.
175
+ *
176
+ * @param snapId - The snap ID.
177
+ */ _revokeAllSnapPermissions = /*#__PURE__*/ new WeakSet(), _createApproval = /*#__PURE__*/ new WeakSet(), _updateApproval = /*#__PURE__*/ new WeakSet(), _add = /*#__PURE__*/ new WeakSet(), _startSnap = /*#__PURE__*/ new WeakSet(), _getEndowments = /*#__PURE__*/ new WeakSet(), /**
178
+ * Sets a snap in state. Called when a snap is installed or updated. Performs
179
+ * various validation checks on the received arguments, and will throw if
180
+ * validation fails.
181
+ *
182
+ * The snap will be enabled and unblocked by the time this method returns,
183
+ * regardless of its previous state.
184
+ *
185
+ * See {@link SnapController.add} and {@link SnapController.updateSnap} for
186
+ * usage.
187
+ *
188
+ * @param args - The add snap args.
189
+ * @returns The resulting snap object.
190
+ */ _set = /*#__PURE__*/ new WeakSet(), _fetchSnap = /*#__PURE__*/ new WeakSet(), _validateSnapPermissions = /*#__PURE__*/ new WeakSet(), /**
191
+ * Gets the RPC message handler for the given snap.
192
+ *
193
+ * @param snapId - The id of the Snap whose message handler to get.
194
+ * @returns The RPC handler for the given snap.
195
+ */ _getRpcRequestHandler = /*#__PURE__*/ new WeakSet(), _executeWithTimeout = /*#__PURE__*/ new WeakSet(), _recordSnapRpcRequestStart = /*#__PURE__*/ new WeakSet(), _recordSnapRpcRequestFinish = /*#__PURE__*/ new WeakSet(), /**
196
+ * Retrieves the rollback snapshot of a snap.
197
+ *
198
+ * @param snapId - The snap id.
199
+ * @returns A `RollbackSnapshot` or `undefined` if one doesn't exist.
200
+ */ _getRollbackSnapshot = /*#__PURE__*/ new WeakSet(), /**
201
+ * Creates a `RollbackSnapshot` that is used to help ensure
202
+ * atomicity in multiple snap updates.
203
+ *
204
+ * @param snapId - The snap id.
205
+ * @throws {@link Error}. If the snap exists before creation or if creation fails.
206
+ * @returns A `RollbackSnapshot`.
207
+ */ _createRollbackSnapshot = /*#__PURE__*/ new WeakSet(), _rollbackSnap = /*#__PURE__*/ new WeakSet(), _rollbackSnaps = /*#__PURE__*/ new WeakSet(), _getRuntime = /*#__PURE__*/ new WeakSet(), _getRuntimeExpect = /*#__PURE__*/ new WeakSet(), _setupRuntime = /*#__PURE__*/ new WeakSet(), _calculatePermissionsChange = /*#__PURE__*/ new WeakSet(), /**
208
+ * Checks if a snap will pass version validation checks
209
+ * with the new version range that is requested. The first
210
+ * check that is done is to check if the existing snap version
211
+ * falls inside the requested range. If it does, we want to return
212
+ * false because we do not care to create a rollback snapshot in
213
+ * that scenario. The second check is to ensure that the current
214
+ * snap version is not greater than all possible versions in
215
+ * the requested version range. If it is, then we also want
216
+ * to return false in that scenario.
217
+ *
218
+ * @param snapId - The snap id.
219
+ * @param newVersionRange - The new version range being requsted.
220
+ * @returns `true` if validation checks pass and `false` if they do not.
221
+ */ _isValidUpdate = /*#__PURE__*/ new WeakSet(), _callLifecycleHook = /*#__PURE__*/ new WeakSet();
222
+ class SnapController extends _basecontroller.BaseControllerV2 {
223
+ /**
224
+ * Checks all installed snaps against the block list and
225
+ * blocks/unblocks snaps as appropriate. See {@link SnapController.blockSnap}
226
+ * for more information.
227
+ */ async updateBlockedSnaps() {
228
+ await this.messagingSystem.call('SnapsRegistry:update');
229
+ const blockedSnaps = await this.messagingSystem.call('SnapsRegistry:get', Object.values(this.state.snaps).reduce((blockListArg, snap)=>{
230
+ blockListArg[snap.id] = {
231
+ version: snap.version,
232
+ checksum: snap.manifest.source.shasum
233
+ };
234
+ return blockListArg;
235
+ }, {}));
236
+ await Promise.all(Object.entries(blockedSnaps).map(async ([snapId, { status, reason }])=>{
237
+ if (status === _registry.SnapsRegistryStatus.Blocked) {
238
+ return _class_private_method_get(this, _blockSnap, blockSnap).call(this, snapId, reason);
239
+ }
240
+ return _class_private_method_get(this, _unblockSnap, unblockSnap).call(this, snapId);
241
+ }));
242
+ }
243
+ _onUnhandledSnapError(snapId, error) {
244
+ this.stopSnap(snapId, _snapsutils.SnapStatusEvents.Crash).then(()=>this.addSnapError(error)).catch((stopSnapError)=>{
245
+ // TODO: Decide how to handle errors.
246
+ (0, _snapsutils.logError)(stopSnapError);
247
+ });
248
+ }
249
+ _onOutboundRequest(snapId) {
250
+ const runtime = _class_private_method_get(this, _getRuntimeExpect, getRuntimeExpect).call(this, snapId);
251
+ // Ideally we would only pause the pending request that is making the outbound request
252
+ // but right now we don't have a way to know which request initiated the outbound request
253
+ runtime.pendingInboundRequests.filter((pendingRequest)=>pendingRequest.timer.status === 'running').forEach((pendingRequest)=>pendingRequest.timer.pause());
254
+ runtime.pendingOutboundRequests += 1;
255
+ }
256
+ _onOutboundResponse(snapId) {
257
+ const runtime = _class_private_method_get(this, _getRuntimeExpect, getRuntimeExpect).call(this, snapId);
258
+ runtime.pendingOutboundRequests -= 1;
259
+ if (runtime.pendingOutboundRequests === 0) {
260
+ runtime.pendingInboundRequests.filter((pendingRequest)=>pendingRequest.timer.status === 'paused').forEach((pendingRequest)=>pendingRequest.timer.resume());
261
+ }
262
+ }
263
+ /**
264
+ * Starts the given snap. Throws an error if no such snap exists
265
+ * or if it is already running.
266
+ *
267
+ * @param snapId - The id of the Snap to start.
268
+ */ async startSnap(snapId) {
269
+ const snap = this.state.snaps[snapId];
270
+ if (snap.enabled === false) {
271
+ throw new Error(`Snap "${snapId}" is disabled.`);
272
+ }
273
+ await _class_private_method_get(this, _startSnap, startSnap).call(this, {
274
+ snapId,
275
+ sourceCode: snap.sourceCode
276
+ });
277
+ }
278
+ /**
279
+ * Enables the given snap. A snap can only be started if it is enabled. A snap
280
+ * can only be enabled if it isn't blocked.
281
+ *
282
+ * @param snapId - The id of the Snap to enable.
283
+ */ enableSnap(snapId) {
284
+ this.getExpect(snapId);
285
+ if (this.state.snaps[snapId].blocked) {
286
+ throw new Error(`Snap "${snapId}" is blocked and cannot be enabled.`);
287
+ }
288
+ this.update((state)=>{
289
+ state.snaps[snapId].enabled = true;
290
+ });
291
+ this.messagingSystem.publish('SnapController:snapEnabled', this.getTruncatedExpect(snapId));
292
+ }
293
+ /**
294
+ * Disables the given snap. A snap can only be started if it is enabled.
295
+ *
296
+ * @param snapId - The id of the Snap to disable.
297
+ * @returns A promise that resolves once the snap has been disabled.
298
+ */ async disableSnap(snapId) {
299
+ if (!this.has(snapId)) {
300
+ throw new Error(`Snap "${snapId}" not found.`);
301
+ }
302
+ this.update((state)=>{
303
+ state.snaps[snapId].enabled = false;
304
+ });
305
+ if (this.isRunning(snapId)) {
306
+ await this.stopSnap(snapId, _snapsutils.SnapStatusEvents.Stop);
307
+ }
308
+ this.messagingSystem.publish('SnapController:snapDisabled', this.getTruncatedExpect(snapId));
309
+ }
310
+ /**
311
+ * Stops the given snap, removes all hooks, closes all connections, and
312
+ * terminates its worker.
313
+ *
314
+ * @param snapId - The id of the Snap to stop.
315
+ * @param statusEvent - The Snap status event that caused the snap to be
316
+ * stopped.
317
+ */ async stopSnap(snapId, statusEvent = _snapsutils.SnapStatusEvents.Stop) {
318
+ const runtime = _class_private_method_get(this, _getRuntime, getRuntime).call(this, snapId);
319
+ if (!runtime) {
320
+ throw new Error(`The snap "${snapId}" is not running.`);
321
+ }
322
+ // Reset request tracking
323
+ runtime.lastRequest = null;
324
+ runtime.pendingInboundRequests = [];
325
+ runtime.pendingOutboundRequests = 0;
326
+ try {
327
+ if (this.isRunning(snapId)) {
328
+ _class_private_field_get(this, _closeAllConnections).call(this, snapId);
329
+ await _class_private_method_get(this, _terminateSnap, terminateSnap).call(this, snapId);
330
+ }
331
+ } finally{
332
+ if (this.isRunning(snapId)) {
333
+ _class_private_method_get(this, _transition, transition).call(this, snapId, statusEvent);
334
+ }
335
+ }
336
+ }
337
+ /**
338
+ * Returns whether the given snap is running.
339
+ * Throws an error if the snap doesn't exist.
340
+ *
341
+ * @param snapId - The id of the Snap to check.
342
+ * @returns `true` if the snap is running, otherwise `false`.
343
+ */ isRunning(snapId) {
344
+ return this.getExpect(snapId).status === 'running';
345
+ }
346
+ /**
347
+ * Returns whether the given snap has been added to state.
348
+ *
349
+ * @param snapId - The id of the Snap to check for.
350
+ * @returns `true` if the snap exists in the controller state, otherwise `false`.
351
+ */ has(snapId) {
352
+ return Boolean(this.get(snapId));
353
+ }
354
+ /**
355
+ * Gets the snap with the given id if it exists, including all data.
356
+ * This should not be used if the snap is to be serializable, as e.g.
357
+ * the snap sourceCode may be quite large.
358
+ *
359
+ * @param snapId - The id of the Snap to get.
360
+ * @returns The entire snap object from the controller state.
361
+ */ get(snapId) {
362
+ return this.state.snaps[snapId];
363
+ }
364
+ /**
365
+ * Gets the snap with the given id, throws if doesn't.
366
+ * This should not be used if the snap is to be serializable, as e.g.
367
+ * the snap sourceCode may be quite large.
368
+ *
369
+ * @see {@link SnapController.get}
370
+ * @throws {@link Error}. If the snap doesn't exist
371
+ * @param snapId - The id of the snap to get.
372
+ * @returns The entire snap object.
373
+ */ getExpect(snapId) {
374
+ const snap = this.get(snapId);
375
+ (0, _utils.assert)(snap !== undefined, new Error(`Snap "${snapId}" not found.`));
376
+ return snap;
377
+ }
378
+ /**
379
+ * Gets the snap with the given id if it exists, excluding any
380
+ * non-serializable or expensive-to-serialize data.
381
+ *
382
+ * @param snapId - The id of the Snap to get.
383
+ * @returns A truncated version of the snap state, that is less expensive to serialize.
384
+ */ // TODO(ritave): this.get returns undefined, this.getTruncated returns null
385
+ getTruncated(snapId) {
386
+ const snap = this.get(snapId);
387
+ return snap ? truncateSnap(snap) : null;
388
+ }
389
+ /**
390
+ * Gets the snap with the given id, throw if it doesn't exist.
391
+ *
392
+ * @throws {@link Error}. If snap doesn't exist
393
+ * @param snapId - The id of the snap to get.
394
+ * @returns A truncated version of the snap state, that is less expensive to serialize.
395
+ */ getTruncatedExpect(snapId) {
396
+ return truncateSnap(this.getExpect(snapId));
397
+ }
398
+ /**
399
+ * Updates the own state of the snap with the given id.
400
+ * This is distinct from the state MetaMask uses to manage snaps.
401
+ *
402
+ * @param snapId - The id of the Snap whose state should be updated.
403
+ * @param newSnapState - The new state of the snap.
404
+ */ async updateSnapState(snapId, newSnapState) {
405
+ this.update((state)=>{
406
+ state.snapStates[snapId] = newSnapState;
407
+ });
408
+ }
409
+ /**
410
+ * Clears the state of the snap with the given id.
411
+ * This is distinct from the state MetaMask uses to manage snaps.
412
+ *
413
+ * @param snapId - The id of the Snap whose state should be cleared.
414
+ */ clearSnapState(snapId) {
415
+ this.update((state)=>{
416
+ state.snapStates[snapId] = null;
417
+ });
418
+ }
419
+ /**
420
+ * Adds error from a snap to the SnapController state.
421
+ *
422
+ * @param snapError - The error to store on the SnapController.
423
+ */ addSnapError(snapError) {
424
+ this.update((state)=>{
425
+ const id = (0, _nanoid.nanoid)();
426
+ state.snapErrors[id] = {
427
+ ...snapError,
428
+ internalID: id
429
+ };
430
+ });
431
+ }
432
+ /**
433
+ * Removes an error by internalID from the SnapControllers state.
434
+ *
435
+ * @param internalID - The internal error ID to remove on the SnapController.
436
+ */ removeSnapError(internalID) {
437
+ this.update((state)=>{
438
+ delete state.snapErrors[internalID];
439
+ });
440
+ }
441
+ /**
442
+ * Clears all errors from the SnapControllers state.
443
+ */ clearSnapErrors() {
444
+ this.update((state)=>{
445
+ state.snapErrors = {};
446
+ });
447
+ }
448
+ /**
449
+ * Gets the own state of the snap with the given id.
450
+ * This is distinct from the state MetaMask uses to manage snaps.
451
+ *
452
+ * @param snapId - The id of the Snap whose state to get.
453
+ * @returns A promise that resolves with the decrypted snap state or null if no state exists.
454
+ * @throws If the snap state decryption fails.
455
+ */ async getSnapState(snapId) {
456
+ const state = this.state.snapStates[snapId];
457
+ return state ?? null;
458
+ }
459
+ /**
460
+ * Completely clear the controller's state: delete all associated data,
461
+ * handlers, event listeners, and permissions; tear down all snap providers.
462
+ */ async clearState() {
463
+ const snapIds = Object.keys(this.state.snaps);
464
+ snapIds.forEach((snapId)=>{
465
+ _class_private_field_get(this, _closeAllConnections).call(this, snapId);
466
+ });
467
+ await this.messagingSystem.call('ExecutionService:terminateAllSnaps');
468
+ snapIds.forEach((snapId)=>_class_private_method_get(this, _revokeAllSnapPermissions, revokeAllSnapPermissions).call(this, snapId));
469
+ this.update((state)=>{
470
+ state.snaps = {};
471
+ state.snapStates = {};
472
+ });
473
+ }
474
+ /**
475
+ * Removes the given snap from state, and clears all associated handlers
476
+ * and listeners.
477
+ *
478
+ * @param snapId - The id of the Snap.
479
+ * @returns A promise that resolves once the snap has been removed.
480
+ */ async removeSnap(snapId) {
481
+ return this.removeSnaps([
482
+ snapId
483
+ ]);
484
+ }
485
+ /**
486
+ * Stops the given snaps, removes them from state, and clears all associated
487
+ * permissions, handlers, and listeners.
488
+ *
489
+ * @param snapIds - The ids of the Snaps.
490
+ */ async removeSnaps(snapIds) {
491
+ if (!Array.isArray(snapIds)) {
492
+ throw new Error('Expected array of snap ids.');
493
+ }
494
+ await Promise.all(snapIds.map(async (snapId)=>{
495
+ const truncated = this.getTruncatedExpect(snapId);
496
+ // Disable the snap and revoke all of its permissions before deleting
497
+ // it. This ensures that the snap will not be restarted or otherwise
498
+ // affect the host environment while we are deleting it.
499
+ await this.disableSnap(snapId);
500
+ _class_private_method_get(this, _revokeAllSnapPermissions, revokeAllSnapPermissions).call(this, snapId);
501
+ _class_private_method_get(this, _removeSnapFromSubjects, removeSnapFromSubjects).call(this, snapId);
502
+ _class_private_field_get(this, _snapsRuntimeData).delete(snapId);
503
+ this.update((state)=>{
504
+ delete state.snaps[snapId];
505
+ delete state.snapStates[snapId];
506
+ });
507
+ this.messagingSystem.publish(`SnapController:snapRemoved`, truncated);
508
+ }));
509
+ }
510
+ /**
511
+ * Removes a snap's permission (caveat) from the specified subject.
512
+ *
513
+ * @param origin - The origin from which to remove the snap.
514
+ * @param snapId - The id of the snap to remove.
515
+ */ removeSnapFromSubject(origin, snapId) {
516
+ const subjectPermissions = this.messagingSystem.call('PermissionController:getPermissions', origin);
517
+ const snapIdsCaveat = subjectPermissions?.[_rpcmethods.WALLET_SNAP_PERMISSION_KEY]?.caveats?.find((caveat)=>caveat.type === _snapsutils.SnapCaveatType.SnapIds);
518
+ if (!snapIdsCaveat) {
519
+ return;
520
+ }
521
+ const caveatHasSnap = Boolean(snapIdsCaveat.value?.[snapId]);
522
+ if (caveatHasSnap) {
523
+ const newCaveatValue = {
524
+ ...snapIdsCaveat.value
525
+ };
526
+ delete newCaveatValue[snapId];
527
+ if (Object.keys(newCaveatValue).length > 0) {
528
+ this.messagingSystem.call('PermissionController:updateCaveat', origin, _rpcmethods.WALLET_SNAP_PERMISSION_KEY, _snapsutils.SnapCaveatType.SnapIds, newCaveatValue);
529
+ } else {
530
+ this.messagingSystem.call('PermissionController:revokePermissions', {
531
+ [origin]: [
532
+ _rpcmethods.WALLET_SNAP_PERMISSION_KEY
533
+ ]
534
+ });
535
+ }
536
+ }
537
+ }
538
+ /**
539
+ * Checks if a list of permissions are dynamic and allowed to be revoked, if they are they will all be revoked.
540
+ *
541
+ * @param snapId - The snap ID.
542
+ * @param permissionNames - The names of the permissions.
543
+ * @throws If non-dynamic permissions are passed.
544
+ */ revokeDynamicSnapPermissions(snapId, permissionNames) {
545
+ (0, _utils.assert)(permissionNames.every((permissionName)=>_class_private_field_get(this, _dynamicPermissions).includes(permissionName)), 'Non-dynamic permissions cannot be revoked');
546
+ this.messagingSystem.call('PermissionController:revokePermissions', {
547
+ [snapId]: permissionNames
548
+ });
549
+ }
550
+ /**
551
+ * Handles incrementing the activeReferences counter.
552
+ *
553
+ * @param snapId - The snap id of the snap that was referenced.
554
+ */ incrementActiveReferences(snapId) {
555
+ const runtime = _class_private_method_get(this, _getRuntimeExpect, getRuntimeExpect).call(this, snapId);
556
+ runtime.activeReferences += 1;
557
+ }
558
+ /**
559
+ * Handles decrement the activeReferences counter.
560
+ *
561
+ * @param snapId - The snap id of the snap that was referenced..
562
+ */ decrementActiveReferences(snapId) {
563
+ const runtime = _class_private_method_get(this, _getRuntimeExpect, getRuntimeExpect).call(this, snapId);
564
+ (0, _utils.assert)(runtime.activeReferences > 0, 'SnapController reference management is in an invalid state.');
565
+ runtime.activeReferences -= 1;
566
+ }
567
+ /**
568
+ * Gets all snaps in their truncated format.
569
+ *
570
+ * @returns All installed snaps in their truncated format.
571
+ */ getAllSnaps() {
572
+ return Object.values(this.state.snaps).map(truncateSnap);
573
+ }
574
+ /**
575
+ * Gets the serialized permitted snaps of the given origin, if any.
576
+ *
577
+ * @param origin - The origin whose permitted snaps to retrieve.
578
+ * @returns The serialized permitted snaps for the origin.
579
+ */ getPermittedSnaps(origin) {
580
+ const permissions = this.messagingSystem.call('PermissionController:getPermissions', origin) ?? {};
581
+ const snaps = permissions[_rpcmethods.WALLET_SNAP_PERMISSION_KEY]?.caveats?.find((caveat)=>caveat.type === _snapsutils.SnapCaveatType.SnapIds)?.value ?? {};
582
+ return Object.keys(snaps).reduce((permittedSnaps, snapId)=>{
583
+ const snap = this.get(snapId);
584
+ const truncatedSnap = this.getTruncated(snapId);
585
+ if (truncatedSnap && snap?.status !== _snapsutils.SnapStatus.Installing) {
586
+ permittedSnaps[snapId] = truncatedSnap;
587
+ }
588
+ return permittedSnaps;
589
+ }, {});
590
+ }
591
+ /**
592
+ * Installs the snaps requested by the given origin, returning the snap
593
+ * object if the origin is permitted to install it, and an authorization error
594
+ * otherwise.
595
+ *
596
+ * @param origin - The origin that requested to install the snaps.
597
+ * @param requestedSnaps - The snaps to install.
598
+ * @returns An object of snap ids and snap objects, or errors if a
599
+ * snap couldn't be installed.
600
+ */ async installSnaps(origin, requestedSnaps) {
601
+ const result = {};
602
+ const snapIds = Object.keys(requestedSnaps);
603
+ const pendingUpdates = [];
604
+ const pendingInstalls = [];
605
+ try {
606
+ for (const [snapId, { version: rawVersion }] of Object.entries(requestedSnaps)){
607
+ (0, _snapsutils.assertIsValidSnapId)(snapId);
608
+ const [error, version] = (0, _snapsutils.resolveVersionRange)(rawVersion);
609
+ if (error) {
610
+ throw _ethrpcerrors.ethErrors.rpc.invalidParams(`The "version" field must be a valid SemVer version range if specified. Received: "${rawVersion}".`);
611
+ }
612
+ const location = _class_private_field_get(this, _detectSnapLocation).call(this, snapId, {
613
+ versionRange: version,
614
+ fetch: _class_private_field_get(this, _fetchFunction),
615
+ allowLocal: _class_private_field_get(this, _featureFlags).allowLocalSnaps
616
+ });
617
+ // Existing snaps may need to be updated, unless they should be re-installed (e.g. local snaps)
618
+ // Everything else is treated as an install
619
+ const isUpdate = this.has(snapId) && !location.shouldAlwaysReload;
620
+ if (isUpdate && _class_private_method_get(this, _isValidUpdate, isValidUpdate).call(this, snapId, version)) {
621
+ pendingUpdates.push(snapId);
622
+ let rollbackSnapshot = _class_private_method_get(this, _getRollbackSnapshot, getRollbackSnapshot).call(this, snapId);
623
+ if (rollbackSnapshot === undefined) {
624
+ rollbackSnapshot = _class_private_method_get(this, _createRollbackSnapshot, createRollbackSnapshot).call(this, snapId);
625
+ rollbackSnapshot.newVersion = version;
626
+ } else {
627
+ throw new Error('This snap is already being updated.');
628
+ }
629
+ } else if (!isUpdate) {
630
+ pendingInstalls.push(snapId);
631
+ }
632
+ result[snapId] = await this.processRequestedSnap(origin, snapId, location, version);
633
+ }
634
+ snapIds.forEach((snapId)=>_class_private_field_get(this, _rollbackSnapshots).delete(snapId));
635
+ } catch (error) {
636
+ const installed = pendingInstalls.filter((snapId)=>this.has(snapId));
637
+ await this.removeSnaps(installed);
638
+ const snapshottedSnaps = [
639
+ ..._class_private_field_get(this, _rollbackSnapshots).keys()
640
+ ];
641
+ const snapsToRollback = pendingUpdates.filter((snapId)=>snapshottedSnaps.includes(snapId));
642
+ await _class_private_method_get(this, _rollbackSnaps, rollbackSnaps).call(this, snapsToRollback);
643
+ throw error;
644
+ }
645
+ return result;
646
+ }
647
+ /**
648
+ * Adds, authorizes, and runs the given snap with a snap provider.
649
+ * Results from this method should be efficiently serializable.
650
+ *
651
+ * @param origin - The origin requesting the snap.
652
+ * @param snapId - The id of the snap.
653
+ * @param location - The location implementation of the snap.
654
+ * @param versionRange - The semver range of the snap to install.
655
+ * @returns The resulting snap object, or an error if something went wrong.
656
+ */ async processRequestedSnap(origin, snapId, location, versionRange) {
657
+ const existingSnap = this.getTruncated(snapId);
658
+ // For devX we always re-install local snaps.
659
+ if (existingSnap && !location.shouldAlwaysReload) {
660
+ if ((0, _utils.satisfiesVersionRange)(existingSnap.version, versionRange)) {
661
+ return existingSnap;
662
+ }
663
+ if (_class_private_field_get(this, _featureFlags).dappsCanUpdateSnaps === true) {
664
+ return await this.updateSnap(origin, snapId, location, versionRange);
665
+ }
666
+ throw _ethrpcerrors.ethErrors.rpc.invalidParams(`Version mismatch with already installed snap. ${snapId}@${existingSnap.version} doesn't satisfy requested version ${versionRange}.`);
667
+ }
668
+ let pendingApproval = _class_private_method_get(this, _createApproval, createApproval).call(this, {
669
+ origin,
670
+ snapId,
671
+ type: SNAP_APPROVAL_INSTALL
672
+ });
673
+ // Existing snaps must be stopped before overwriting
674
+ if (existingSnap && this.isRunning(snapId)) {
675
+ await this.stopSnap(snapId, _snapsutils.SnapStatusEvents.Stop);
676
+ }
677
+ // Existing snaps that should be re-installed should not maintain their existing permissions
678
+ if (existingSnap && location.shouldAlwaysReload) {
679
+ _class_private_method_get(this, _revokeAllSnapPermissions, revokeAllSnapPermissions).call(this, snapId);
680
+ }
681
+ try {
682
+ const { sourceCode } = await _class_private_method_get(this, _add, add).call(this, {
683
+ origin,
684
+ id: snapId,
685
+ location,
686
+ versionRange
687
+ });
688
+ await this.authorize(snapId, pendingApproval);
689
+ pendingApproval = _class_private_method_get(this, _createApproval, createApproval).call(this, {
690
+ origin,
691
+ snapId,
692
+ type: SNAP_APPROVAL_RESULT
693
+ });
694
+ await _class_private_method_get(this, _startSnap, startSnap).call(this, {
695
+ snapId,
696
+ sourceCode
697
+ });
698
+ const truncated = this.getTruncatedExpect(snapId);
699
+ _class_private_method_get(this, _updateApproval, updateApproval).call(this, pendingApproval.id, {
700
+ loading: false,
701
+ type: SNAP_APPROVAL_INSTALL
702
+ });
703
+ this.messagingSystem.publish(`SnapController:snapInstalled`, truncated);
704
+ return truncated;
705
+ } catch (error) {
706
+ (0, _snapsutils.logError)(`Error when adding ${snapId}.`, error);
707
+ _class_private_method_get(this, _updateApproval, updateApproval).call(this, pendingApproval.id, {
708
+ loading: false,
709
+ type: SNAP_APPROVAL_INSTALL,
710
+ error: error instanceof Error ? error.message : error.toString()
711
+ });
712
+ throw error;
713
+ }
714
+ }
715
+ /**
716
+ * Updates an installed snap. The flow is similar to
717
+ * {@link SnapController.installSnaps}. The user will be asked if they want
718
+ * to update, then approve any permission changes, and finally the snap will
719
+ * be restarted.
720
+ *
721
+ * The update will fail if the user rejects any prompt or if the new version
722
+ * of the snap is blocked.
723
+ *
724
+ * If the original version of the snap was blocked and the update succeeded,
725
+ * the snap will be unblocked and enabled before it is restarted.
726
+ *
727
+ * @param origin - The origin requesting the snap update.
728
+ * @param snapId - The id of the Snap to be updated.
729
+ * @param location - The location implementation of the snap.
730
+ * @param newVersionRange - A semver version range in which the maximum version will be chosen.
731
+ * @returns The snap metadata if updated, `null` otherwise.
732
+ */ async updateSnap(origin, snapId, location, newVersionRange = _snapsutils.DEFAULT_REQUESTED_SNAP_VERSION) {
733
+ if (!(0, _utils.isValidSemVerRange)(newVersionRange)) {
734
+ throw new Error(`Received invalid snap version range: "${newVersionRange}".`);
735
+ }
736
+ let pendingApproval = _class_private_method_get(this, _createApproval, createApproval).call(this, {
737
+ origin,
738
+ snapId,
739
+ type: SNAP_APPROVAL_UPDATE
740
+ });
741
+ try {
742
+ const snap = this.getExpect(snapId);
743
+ const newSnap = await _class_private_method_get(this, _fetchSnap, fetchSnap).call(this, snapId, location);
744
+ const newVersion = newSnap.manifest.result.version;
745
+ if (!(0, _utils.gtVersion)(newVersion, snap.version)) {
746
+ throw _ethrpcerrors.ethErrors.rpc.invalidParams(`Snap "${snapId}@${snap.version}" is already installed. Couldn't update to a version inside requested "${newVersionRange}" range.`);
747
+ }
748
+ if (!(0, _utils.satisfiesVersionRange)(newVersion, newVersionRange)) {
749
+ throw new Error(`Version mismatch. Manifest for "${snapId}" specifies version "${newVersion}" which doesn't satisfy requested version range "${newVersionRange}".`);
750
+ }
751
+ await _class_private_method_get(this, _assertIsInstallAllowed, assertIsInstallAllowed).call(this, snapId, {
752
+ version: newVersion,
753
+ checksum: newSnap.manifest.result.source.shasum
754
+ });
755
+ const processedPermissions = (0, _permissions.processSnapPermissions)(newSnap.manifest.result.initialPermissions);
756
+ _class_private_method_get(this, _validateSnapPermissions, validateSnapPermissions).call(this, processedPermissions);
757
+ const { newPermissions, unusedPermissions, approvedPermissions } = _class_private_method_get(this, _calculatePermissionsChange, calculatePermissionsChange).call(this, snapId, processedPermissions);
758
+ _class_private_method_get(this, _updateApproval, updateApproval).call(this, pendingApproval.id, {
759
+ permissions: newPermissions,
760
+ newVersion: newSnap.manifest.result.version,
761
+ newPermissions,
762
+ approvedPermissions,
763
+ unusedPermissions,
764
+ loading: false
765
+ });
766
+ const { permissions: approvedNewPermissions, ...requestData } = await pendingApproval.promise;
767
+ pendingApproval = _class_private_method_get(this, _createApproval, createApproval).call(this, {
768
+ origin,
769
+ snapId,
770
+ type: SNAP_APPROVAL_RESULT
771
+ });
772
+ if (this.isRunning(snapId)) {
773
+ await this.stopSnap(snapId, _snapsutils.SnapStatusEvents.Stop);
774
+ }
775
+ _class_private_method_get(this, _transition, transition).call(this, snapId, _snapsutils.SnapStatusEvents.Update);
776
+ _class_private_method_get(this, _set, set).call(this, {
777
+ origin,
778
+ id: snapId,
779
+ manifest: newSnap.manifest,
780
+ files: newSnap.files,
781
+ isUpdate: true
782
+ });
783
+ const unusedPermissionsKeys = Object.keys(unusedPermissions);
784
+ if ((0, _utils.isNonEmptyArray)(unusedPermissionsKeys)) {
785
+ this.messagingSystem.call('PermissionController:revokePermissions', {
786
+ [snapId]: unusedPermissionsKeys
787
+ });
788
+ }
789
+ if ((0, _utils.isNonEmptyArray)(Object.keys(approvedNewPermissions))) {
790
+ this.messagingSystem.call('PermissionController:grantPermissions', {
791
+ approvedPermissions: approvedNewPermissions,
792
+ subject: {
793
+ origin: snapId
794
+ },
795
+ requestData
796
+ });
797
+ }
798
+ const rollbackSnapshot = _class_private_method_get(this, _getRollbackSnapshot, getRollbackSnapshot).call(this, snapId);
799
+ if (rollbackSnapshot !== undefined) {
800
+ rollbackSnapshot.permissions.revoked = unusedPermissions;
801
+ rollbackSnapshot.permissions.granted = Object.keys(approvedNewPermissions);
802
+ rollbackSnapshot.permissions.requestData = requestData;
803
+ }
804
+ const normalizedSourcePath = (0, _snapsutils.normalizeRelative)(newSnap.manifest.result.source.location.npm.filePath);
805
+ const sourceCode = newSnap.files.find((file)=>file.path === normalizedSourcePath)?.toString();
806
+ (0, _utils.assert)(typeof sourceCode === 'string' && sourceCode.length > 0, `Invalid source code for snap "${snapId}".`);
807
+ try {
808
+ await _class_private_method_get(this, _startSnap, startSnap).call(this, {
809
+ snapId,
810
+ sourceCode
811
+ });
812
+ } catch {
813
+ throw new Error(`Snap ${snapId} crashed with updated source code.`);
814
+ }
815
+ const truncatedSnap = this.getTruncatedExpect(snapId);
816
+ this.messagingSystem.publish('SnapController:snapUpdated', truncatedSnap, snap.version);
817
+ _class_private_method_get(this, _updateApproval, updateApproval).call(this, pendingApproval.id, {
818
+ loading: false,
819
+ type: SNAP_APPROVAL_UPDATE
820
+ });
821
+ return truncatedSnap;
822
+ } catch (error) {
823
+ (0, _snapsutils.logError)(`Error when updating ${snapId},`, error);
824
+ _class_private_method_get(this, _updateApproval, updateApproval).call(this, pendingApproval.id, {
825
+ loading: false,
826
+ error: error instanceof Error ? error.message : error.toString(),
827
+ type: SNAP_APPROVAL_UPDATE
828
+ });
829
+ throw error;
830
+ }
831
+ }
832
+ /**
833
+ * Get metadata for the given snap ID.
834
+ *
835
+ * @param snapId - The ID of the snap to get metadata for.
836
+ * @returns The metadata for the given snap ID, or `null` if the snap is not
837
+ * verified.
838
+ */ async getRegistryMetadata(snapId) {
839
+ return await this.messagingSystem.call('SnapsRegistry:getMetadata', snapId);
840
+ }
841
+ /**
842
+ * Initiates a request for the given snap's initial permissions.
843
+ * Must be called in order. See processRequestedSnap.
844
+ *
845
+ * This function is not hash private yet because of tests.
846
+ *
847
+ * @param snapId - The id of the Snap.
848
+ * @param pendingApproval - Pending approval to update.
849
+ * @returns The snap's approvedPermissions.
850
+ */ async authorize(snapId, pendingApproval) {
851
+ (0, _logging.log)(`Authorizing snap: ${snapId}`);
852
+ const snapsState = this.state.snaps;
853
+ const snap = snapsState[snapId];
854
+ const { initialPermissions } = snap;
855
+ try {
856
+ const processedPermissions = (0, _permissions.processSnapPermissions)(initialPermissions);
857
+ _class_private_method_get(this, _validateSnapPermissions, validateSnapPermissions).call(this, processedPermissions);
858
+ _class_private_method_get(this, _updateApproval, updateApproval).call(this, pendingApproval.id, {
859
+ loading: false,
860
+ permissions: processedPermissions
861
+ });
862
+ const { permissions: approvedPermissions, ...requestData } = await pendingApproval.promise;
863
+ if ((0, _utils.isNonEmptyArray)(Object.keys(approvedPermissions))) {
864
+ this.messagingSystem.call('PermissionController:grantPermissions', {
865
+ approvedPermissions,
866
+ subject: {
867
+ origin: snapId
868
+ },
869
+ requestData
870
+ });
871
+ }
872
+ } finally{
873
+ const runtime = _class_private_method_get(this, _getRuntimeExpect, getRuntimeExpect).call(this, snapId);
874
+ runtime.installPromise = null;
875
+ }
876
+ }
877
+ destroy() {
878
+ super.destroy();
879
+ if (_class_private_field_get(this, _timeoutForLastRequestStatus)) {
880
+ clearTimeout(_class_private_field_get(this, _timeoutForLastRequestStatus));
881
+ }
882
+ /* eslint-disable @typescript-eslint/unbound-method */ this.messagingSystem.unsubscribe('ExecutionService:unhandledError', this._onUnhandledSnapError);
883
+ this.messagingSystem.unsubscribe('ExecutionService:outboundRequest', this._onOutboundRequest);
884
+ this.messagingSystem.unsubscribe('ExecutionService:outboundResponse', this._onOutboundResponse);
885
+ /* eslint-enable @typescript-eslint/unbound-method */ }
886
+ /**
887
+ * Passes a JSON-RPC request object to the RPC handler function of a snap.
888
+ *
889
+ * @param options - A bag of options.
890
+ * @param options.snapId - The ID of the recipient snap.
891
+ * @param options.origin - The origin of the RPC request.
892
+ * @param options.handler - The handler to trigger on the snap for the request.
893
+ * @param options.request - The JSON-RPC request object.
894
+ * @returns The result of the JSON-RPC request.
895
+ */ async handleRequest({ snapId, origin, handler: handlerType, request: rawRequest }) {
896
+ const request = {
897
+ jsonrpc: '2.0',
898
+ id: (0, _nanoid.nanoid)(),
899
+ ...rawRequest
900
+ };
901
+ (0, _utils.assertIsJsonRpcRequest)(request);
902
+ const permissionName = _endowments.handlerEndowments[handlerType];
903
+ const hasPermission = this.messagingSystem.call('PermissionController:hasPermission', snapId, permissionName);
904
+ if (!hasPermission) {
905
+ throw new Error(`Snap "${snapId}" is not permitted to use "${permissionName}".`);
906
+ }
907
+ if (permissionName === _endowments.SnapEndowments.Rpc) {
908
+ const subject = this.messagingSystem.call('SubjectMetadataController:getSubjectMetadata', origin);
909
+ const isSnap = subject?.subjectType === _permissioncontroller.SubjectType.Snap;
910
+ const permissions = this.messagingSystem.call('PermissionController:getPermissions', snapId);
911
+ const rpcPermission = permissions?.[_endowments.SnapEndowments.Rpc];
912
+ (0, _utils.assert)(rpcPermission);
913
+ const origins = (0, _rpc.getRpcCaveatOrigins)(rpcPermission);
914
+ (0, _utils.assert)(origins);
915
+ if (isSnap && !origins.snaps || !isSnap && !origins.dapps) {
916
+ throw new Error(`Snap "${snapId}" is not permitted to handle JSON-RPC requests from "${origin}".`);
917
+ }
918
+ }
919
+ const handler = await _class_private_method_get(this, _getRpcRequestHandler, getRpcRequestHandler).call(this, snapId);
920
+ if (!handler) {
921
+ throw new Error(`Snap RPC message handler not found for snap "${snapId}".`);
922
+ }
923
+ return handler({
924
+ origin,
925
+ handler: handlerType,
926
+ request
927
+ });
928
+ }
929
+ constructor({ closeAllConnections, messenger, state, dynamicPermissions = [
930
+ 'eth_accounts'
931
+ ], environmentEndowmentPermissions = [], excludedPermissions = {}, idleTimeCheckInterval = (0, _utils.inMilliseconds)(5, _utils.Duration.Second), maxIdleTime = (0, _utils.inMilliseconds)(30, _utils.Duration.Second), maxRequestTime = (0, _utils.inMilliseconds)(60, _utils.Duration.Second), fetchFunction = globalThis.fetch.bind(globalThis), featureFlags = {}, detectSnapLocation: detectSnapLocationFunction = _location.detectSnapLocation }){
932
+ super({
933
+ messenger,
934
+ metadata: {
935
+ snapErrors: {
936
+ persist: false,
937
+ anonymous: false
938
+ },
939
+ snapStates: {
940
+ persist: true,
941
+ anonymous: false
942
+ },
943
+ snaps: {
944
+ persist: (snaps)=>{
945
+ return Object.values(snaps).map((snap)=>{
946
+ return {
947
+ ...snap,
948
+ // At the time state is rehydrated, no snap will be running.
949
+ status: _snapsutils.SnapStatus.Stopped
950
+ };
951
+ }).reduce((memo, snap)=>{
952
+ memo[snap.id] = snap;
953
+ return memo;
954
+ }, {});
955
+ },
956
+ anonymous: false
957
+ }
958
+ },
959
+ name,
960
+ state: {
961
+ ...defaultState,
962
+ ...state
963
+ }
964
+ });
965
+ _class_private_method_init(this, _initializeStateMachine);
966
+ _class_private_method_init(this, _registerMessageHandlers);
967
+ _class_private_method_init(this, _pollForLastRequestStatus);
968
+ /**
969
+ * Blocks an installed snap and prevents it from being started again. Emits
970
+ * {@link SnapBlocked}. Does nothing if the snap is not installed.
971
+ *
972
+ * @param snapId - The snap to block.
973
+ * @param blockedSnapInfo - Information detailing why the snap is blocked.
974
+ */ _class_private_method_init(this, _blockSnap);
975
+ _class_private_method_init(this, _unblockSnap);
976
+ _class_private_method_init(this, _assertIsInstallAllowed);
977
+ _class_private_method_init(this, _stopSnapsLastRequestPastMax);
978
+ _class_private_method_init(this, _transition);
979
+ /**
980
+ * Terminates the specified snap and emits the `snapTerminated` event.
981
+ *
982
+ * @param snapId - The snap to terminate.
983
+ */ _class_private_method_init(this, _terminateSnap);
984
+ _class_private_method_init(this, _removeSnapFromSubjects);
985
+ _class_private_method_init(this, _revokeAllSnapPermissions);
986
+ _class_private_method_init(this, _createApproval);
987
+ _class_private_method_init(this, _updateApproval);
988
+ /**
989
+ * Returns a promise representing the complete installation of the requested snap.
990
+ * If the snap is already being installed, the previously pending promise will be returned.
991
+ *
992
+ * @param args - Object containing the snap id and either the URL of the snap's manifest,
993
+ * or the snap's manifest and source code. The object may also optionally contain a target
994
+ * version.
995
+ * @returns The resulting snap object.
996
+ */ _class_private_method_init(this, _add);
997
+ _class_private_method_init(this, _startSnap);
998
+ /**
999
+ * Gets the names of all endowments that will be added to the Snap's
1000
+ * Compartment when it executes. These should be the names of global
1001
+ * JavaScript APIs accessible in the root realm of the execution environment.
1002
+ *
1003
+ * Throws an error if the endowment getter for a permission returns a truthy
1004
+ * value that is not an array of strings.
1005
+ *
1006
+ * @param snapId - The id of the snap whose SES endowments to get.
1007
+ * @returns An array of the names of the endowments.
1008
+ */ _class_private_method_init(this, _getEndowments);
1009
+ _class_private_method_init(this, _set);
1010
+ /**
1011
+ * Fetches the manifest and source code of a snap.
1012
+ *
1013
+ * This function is not hash private yet because of tests.
1014
+ *
1015
+ * @param snapId - The id of the Snap.
1016
+ * @param location - Source from which snap will be fetched.
1017
+ * @returns A tuple of the Snap manifest object and the Snap source code.
1018
+ */ _class_private_method_init(this, _fetchSnap);
1019
+ _class_private_method_init(this, _validateSnapPermissions);
1020
+ _class_private_method_init(this, _getRpcRequestHandler);
1021
+ /**
1022
+ * Awaits the specified promise and rejects if the promise doesn't resolve
1023
+ * before the timeout.
1024
+ *
1025
+ * @param promise - The promise to await.
1026
+ * @param timer - An optional timer object to control the timeout.
1027
+ * @returns The result of the promise or rejects if the promise times out.
1028
+ * @template PromiseValue - The value of the Promise.
1029
+ */ _class_private_method_init(this, _executeWithTimeout);
1030
+ _class_private_method_init(this, _recordSnapRpcRequestStart);
1031
+ _class_private_method_init(this, _recordSnapRpcRequestFinish);
1032
+ _class_private_method_init(this, _getRollbackSnapshot);
1033
+ _class_private_method_init(this, _createRollbackSnapshot);
1034
+ /**
1035
+ * Rolls back a snap to its previous state, permissions
1036
+ * and source code based on the `RollbackSnapshot` that
1037
+ * is captured during the update process. After rolling back,
1038
+ * the function also emits an event indicating that the
1039
+ * snap has been rolled back and it clears the snapshot
1040
+ * for that snap.
1041
+ *
1042
+ * @param snapId - The snap id.
1043
+ * @throws {@link Error}. If a snapshot does not exist.
1044
+ */ _class_private_method_init(this, _rollbackSnap);
1045
+ /**
1046
+ * Iterates through an array of snap ids
1047
+ * and calls `rollbackSnap` on them.
1048
+ *
1049
+ * @param snapIds - An array of snap ids.
1050
+ */ _class_private_method_init(this, _rollbackSnaps);
1051
+ _class_private_method_init(this, _getRuntime);
1052
+ _class_private_method_init(this, _getRuntimeExpect);
1053
+ _class_private_method_init(this, _setupRuntime);
1054
+ _class_private_method_init(this, _calculatePermissionsChange);
1055
+ _class_private_method_init(this, _isValidUpdate);
1056
+ /**
1057
+ * Call a lifecycle hook on a snap, if the snap has the
1058
+ * `endowment:lifecycle-hooks` permission. If the snap does not have the
1059
+ * permission, nothing happens.
1060
+ *
1061
+ * @param snapId - The snap ID.
1062
+ * @param handler - The lifecycle hook to call. This should be one of the
1063
+ * supported lifecycle hooks.
1064
+ * @private
1065
+ */ _class_private_method_init(this, _callLifecycleHook);
1066
+ _class_private_field_init(this, _closeAllConnections, {
1067
+ writable: true,
1068
+ value: void 0
1069
+ });
1070
+ _class_private_field_init(this, _dynamicPermissions, {
1071
+ writable: true,
1072
+ value: void 0
1073
+ });
1074
+ _class_private_field_init(this, _environmentEndowmentPermissions, {
1075
+ writable: true,
1076
+ value: void 0
1077
+ });
1078
+ _class_private_field_init(this, _excludedPermissions, {
1079
+ writable: true,
1080
+ value: void 0
1081
+ });
1082
+ _class_private_field_init(this, _featureFlags, {
1083
+ writable: true,
1084
+ value: void 0
1085
+ });
1086
+ _class_private_field_init(this, _fetchFunction, {
1087
+ writable: true,
1088
+ value: void 0
1089
+ });
1090
+ _class_private_field_init(this, _idleTimeCheckInterval, {
1091
+ writable: true,
1092
+ value: void 0
1093
+ });
1094
+ _class_private_field_init(this, _maxIdleTime, {
1095
+ writable: true,
1096
+ value: void 0
1097
+ });
1098
+ // This property cannot be hash private yet because of tests.
1099
+ _define_property(this, "maxRequestTime", void 0);
1100
+ _class_private_field_init(this, _detectSnapLocation, {
1101
+ writable: true,
1102
+ value: void 0
1103
+ });
1104
+ _class_private_field_init(this, _snapsRuntimeData, {
1105
+ writable: true,
1106
+ value: void 0
1107
+ });
1108
+ _class_private_field_init(this, _rollbackSnapshots, {
1109
+ writable: true,
1110
+ value: void 0
1111
+ });
1112
+ _class_private_field_init(this, _timeoutForLastRequestStatus, {
1113
+ writable: true,
1114
+ value: void 0
1115
+ });
1116
+ _class_private_field_init(this, _statusMachine, {
1117
+ writable: true,
1118
+ value: void 0
1119
+ });
1120
+ _class_private_field_set(this, _closeAllConnections, closeAllConnections);
1121
+ _class_private_field_set(this, _dynamicPermissions, dynamicPermissions);
1122
+ _class_private_field_set(this, _environmentEndowmentPermissions, environmentEndowmentPermissions);
1123
+ _class_private_field_set(this, _excludedPermissions, excludedPermissions);
1124
+ _class_private_field_set(this, _featureFlags, featureFlags);
1125
+ _class_private_field_set(this, _fetchFunction, fetchFunction);
1126
+ _class_private_field_set(this, _idleTimeCheckInterval, idleTimeCheckInterval);
1127
+ _class_private_field_set(this, _maxIdleTime, maxIdleTime);
1128
+ this.maxRequestTime = maxRequestTime;
1129
+ _class_private_field_set(this, _detectSnapLocation, detectSnapLocationFunction);
1130
+ this._onUnhandledSnapError = this._onUnhandledSnapError.bind(this);
1131
+ this._onOutboundRequest = this._onOutboundRequest.bind(this);
1132
+ this._onOutboundResponse = this._onOutboundResponse.bind(this);
1133
+ _class_private_field_set(this, _rollbackSnapshots, new Map());
1134
+ _class_private_field_set(this, _snapsRuntimeData, new Map());
1135
+ _class_private_method_get(this, _pollForLastRequestStatus, pollForLastRequestStatus).call(this);
1136
+ /* eslint-disable @typescript-eslint/unbound-method */ this.messagingSystem.subscribe('ExecutionService:unhandledError', this._onUnhandledSnapError);
1137
+ this.messagingSystem.subscribe('ExecutionService:outboundRequest', this._onOutboundRequest);
1138
+ this.messagingSystem.subscribe('ExecutionService:outboundResponse', this._onOutboundResponse);
1139
+ /* eslint-enable @typescript-eslint/unbound-method */ this.messagingSystem.subscribe('SnapController:snapInstalled', ({ id })=>{
1140
+ _class_private_method_get(this, _callLifecycleHook, callLifecycleHook).call(this, id, _snapsutils.HandlerType.OnInstall).catch((error)=>{
1141
+ (0, _snapsutils.logError)(`Error when calling \`onInstall\` lifecycle hook for snap "${id}": ${(0, _snapsutils.getErrorMessage)(error)}`);
1142
+ });
1143
+ });
1144
+ this.messagingSystem.subscribe('SnapController:snapUpdated', ({ id })=>{
1145
+ _class_private_method_get(this, _callLifecycleHook, callLifecycleHook).call(this, id, _snapsutils.HandlerType.OnUpdate).catch((error)=>{
1146
+ (0, _snapsutils.logError)(`Error when calling \`onUpdate\` lifecycle hook for snap "${id}": ${(0, _snapsutils.getErrorMessage)(error)}`);
1147
+ });
1148
+ });
1149
+ _class_private_method_get(this, _initializeStateMachine, initializeStateMachine).call(this);
1150
+ _class_private_method_get(this, _registerMessageHandlers, registerMessageHandlers).call(this);
1151
+ Object.values(state?.snaps ?? {}).forEach((snap)=>_class_private_method_get(this, _setupRuntime, setupRuntime).call(this, snap.id, {
1152
+ sourceCode: snap.sourceCode,
1153
+ state: state?.snapStates?.[snap.id] ?? null
1154
+ }));
1155
+ }
1156
+ }
1157
+ function initializeStateMachine() {
1158
+ const disableGuard = ({ snapId })=>{
1159
+ return this.getExpect(snapId).enabled;
1160
+ };
1161
+ const statusConfig = {
1162
+ initial: _snapsutils.SnapStatus.Installing,
1163
+ states: {
1164
+ [_snapsutils.SnapStatus.Installing]: {
1165
+ on: {
1166
+ [_snapsutils.SnapStatusEvents.Start]: {
1167
+ target: _snapsutils.SnapStatus.Running,
1168
+ cond: disableGuard
1169
+ }
1170
+ }
1171
+ },
1172
+ [_snapsutils.SnapStatus.Updating]: {
1173
+ on: {
1174
+ [_snapsutils.SnapStatusEvents.Start]: {
1175
+ target: _snapsutils.SnapStatus.Running,
1176
+ cond: disableGuard
1177
+ },
1178
+ [_snapsutils.SnapStatusEvents.Stop]: _snapsutils.SnapStatus.Stopped
1179
+ }
1180
+ },
1181
+ [_snapsutils.SnapStatus.Running]: {
1182
+ on: {
1183
+ [_snapsutils.SnapStatusEvents.Stop]: _snapsutils.SnapStatus.Stopped,
1184
+ [_snapsutils.SnapStatusEvents.Crash]: _snapsutils.SnapStatus.Crashed
1185
+ }
1186
+ },
1187
+ [_snapsutils.SnapStatus.Stopped]: {
1188
+ on: {
1189
+ [_snapsutils.SnapStatusEvents.Start]: {
1190
+ target: _snapsutils.SnapStatus.Running,
1191
+ cond: disableGuard
1192
+ },
1193
+ [_snapsutils.SnapStatusEvents.Update]: _snapsutils.SnapStatus.Updating
1194
+ }
1195
+ },
1196
+ [_snapsutils.SnapStatus.Crashed]: {
1197
+ on: {
1198
+ [_snapsutils.SnapStatusEvents.Start]: {
1199
+ target: _snapsutils.SnapStatus.Running,
1200
+ cond: disableGuard
1201
+ },
1202
+ [_snapsutils.SnapStatusEvents.Update]: _snapsutils.SnapStatus.Updating
1203
+ }
1204
+ }
1205
+ }
1206
+ };
1207
+ _class_private_field_set(this, _statusMachine, (0, _fsm.createMachine)(statusConfig));
1208
+ (0, _fsm1.validateMachine)(_class_private_field_get(this, _statusMachine));
1209
+ }
1210
+ function registerMessageHandlers() {
1211
+ this.messagingSystem.registerActionHandler(`${controllerName}:clearSnapState`, (...args)=>this.clearSnapState(...args));
1212
+ this.messagingSystem.registerActionHandler(`${controllerName}:get`, (...args)=>this.get(...args));
1213
+ this.messagingSystem.registerActionHandler(`${controllerName}:getSnapState`, async (...args)=>this.getSnapState(...args));
1214
+ this.messagingSystem.registerActionHandler(`${controllerName}:handleRequest`, async (...args)=>this.handleRequest(...args));
1215
+ this.messagingSystem.registerActionHandler(`${controllerName}:has`, (...args)=>this.has(...args));
1216
+ this.messagingSystem.registerActionHandler(`${controllerName}:updateBlockedSnaps`, async ()=>this.updateBlockedSnaps());
1217
+ this.messagingSystem.registerActionHandler(`${controllerName}:updateSnapState`, async (...args)=>this.updateSnapState(...args));
1218
+ this.messagingSystem.registerActionHandler(`${controllerName}:enable`, (...args)=>this.enableSnap(...args));
1219
+ this.messagingSystem.registerActionHandler(`${controllerName}:disable`, async (...args)=>this.disableSnap(...args));
1220
+ this.messagingSystem.registerActionHandler(`${controllerName}:remove`, async (...args)=>this.removeSnap(...args));
1221
+ this.messagingSystem.registerActionHandler(`${controllerName}:getPermitted`, (...args)=>this.getPermittedSnaps(...args));
1222
+ this.messagingSystem.registerActionHandler(`${controllerName}:install`, async (...args)=>this.installSnaps(...args));
1223
+ this.messagingSystem.registerActionHandler(`${controllerName}:removeSnapError`, (...args)=>this.removeSnapError(...args));
1224
+ this.messagingSystem.registerActionHandler(`${controllerName}:getAll`, (...args)=>this.getAllSnaps(...args));
1225
+ this.messagingSystem.registerActionHandler(`${controllerName}:incrementActiveReferences`, (...args)=>this.incrementActiveReferences(...args));
1226
+ this.messagingSystem.registerActionHandler(`${controllerName}:decrementActiveReferences`, (...args)=>this.decrementActiveReferences(...args));
1227
+ this.messagingSystem.registerActionHandler(`${controllerName}:getRegistryMetadata`, async (...args)=>this.getRegistryMetadata(...args));
1228
+ this.messagingSystem.registerActionHandler(`${controllerName}:disconnectOrigin`, (...args)=>this.removeSnapFromSubject(...args));
1229
+ this.messagingSystem.registerActionHandler(`${controllerName}:revokeDynamicPermissions`, (...args)=>this.revokeDynamicSnapPermissions(...args));
1230
+ }
1231
+ function pollForLastRequestStatus() {
1232
+ _class_private_field_set(this, _timeoutForLastRequestStatus, setTimeout(()=>{
1233
+ _class_private_method_get(this, _stopSnapsLastRequestPastMax, stopSnapsLastRequestPastMax).call(this).catch((error)=>{
1234
+ // TODO: Decide how to handle errors.
1235
+ (0, _snapsutils.logError)(error);
1236
+ });
1237
+ _class_private_method_get(this, _pollForLastRequestStatus, pollForLastRequestStatus).call(this);
1238
+ }, _class_private_field_get(this, _idleTimeCheckInterval)));
1239
+ }
1240
+ async function blockSnap(snapId, blockedSnapInfo) {
1241
+ if (!this.has(snapId)) {
1242
+ return;
1243
+ }
1244
+ try {
1245
+ this.update((state)=>{
1246
+ state.snaps[snapId].blocked = true;
1247
+ state.snaps[snapId].blockInformation = blockedSnapInfo;
1248
+ });
1249
+ await this.disableSnap(snapId);
1250
+ } catch (error) {
1251
+ (0, _snapsutils.logError)(`Encountered error when stopping blocked snap "${snapId}".`, error);
1252
+ }
1253
+ this.messagingSystem.publish(`${controllerName}:snapBlocked`, snapId, blockedSnapInfo);
1254
+ }
1255
+ function unblockSnap(snapId) {
1256
+ if (!this.has(snapId) || !this.state.snaps[snapId].blocked) {
1257
+ return;
1258
+ }
1259
+ this.update((state)=>{
1260
+ state.snaps[snapId].blocked = false;
1261
+ delete state.snaps[snapId].blockInformation;
1262
+ });
1263
+ this.messagingSystem.publish(`${controllerName}:snapUnblocked`, snapId);
1264
+ }
1265
+ async function assertIsInstallAllowed(snapId, snapInfo) {
1266
+ const results = await this.messagingSystem.call('SnapsRegistry:get', {
1267
+ [snapId]: snapInfo
1268
+ });
1269
+ const result = results[snapId];
1270
+ if (result.status === _registry.SnapsRegistryStatus.Blocked) {
1271
+ throw new Error(`Cannot install version "${snapInfo.version}" of snap "${snapId}": The version is blocked. ${result.reason?.explanation ?? ''}`);
1272
+ } else if (_class_private_field_get(this, _featureFlags).requireAllowlist && result.status !== _registry.SnapsRegistryStatus.Verified) {
1273
+ throw new Error(`Cannot install version "${snapInfo.version}" of snap "${snapId}": The snap is not on the allow list.`);
1274
+ }
1275
+ }
1276
+ async function stopSnapsLastRequestPastMax() {
1277
+ const entries = [
1278
+ ..._class_private_field_get(this, _snapsRuntimeData).entries()
1279
+ ];
1280
+ return Promise.all(entries.filter(([_snapId, runtime])=>runtime.activeReferences === 0 && runtime.pendingInboundRequests.length === 0 && // lastRequest should always be set here but TypeScript wants this check
1281
+ runtime.lastRequest && _class_private_field_get(this, _maxIdleTime) && (0, _utils.timeSince)(runtime.lastRequest) > _class_private_field_get(this, _maxIdleTime)).map(async ([snapId])=>this.stopSnap(snapId, _snapsutils.SnapStatusEvents.Stop)));
1282
+ }
1283
+ function transition(snapId, event) {
1284
+ const { interpreter } = _class_private_method_get(this, _getRuntimeExpect, getRuntimeExpect).call(this, snapId);
1285
+ interpreter.send(event);
1286
+ this.update((state)=>{
1287
+ state.snaps[snapId].status = interpreter.state.value;
1288
+ });
1289
+ }
1290
+ async function terminateSnap(snapId) {
1291
+ await this.messagingSystem.call('ExecutionService:terminateSnap', snapId);
1292
+ this.messagingSystem.publish('SnapController:snapTerminated', this.getTruncatedExpect(snapId));
1293
+ }
1294
+ function removeSnapFromSubjects(snapId) {
1295
+ const subjects = this.messagingSystem.call('PermissionController:getSubjectNames');
1296
+ for (const subject of subjects){
1297
+ this.removeSnapFromSubject(subject, snapId);
1298
+ }
1299
+ }
1300
+ function revokeAllSnapPermissions(snapId) {
1301
+ if (this.messagingSystem.call('PermissionController:hasPermissions', snapId)) {
1302
+ this.messagingSystem.call('PermissionController:revokeAllPermissions', snapId);
1303
+ }
1304
+ }
1305
+ function createApproval({ origin, snapId, type }) {
1306
+ const id = (0, _nanoid.nanoid)();
1307
+ const promise = this.messagingSystem.call('ApprovalController:addRequest', {
1308
+ origin,
1309
+ id,
1310
+ type,
1311
+ requestData: {
1312
+ // Mirror previous installation metadata
1313
+ metadata: {
1314
+ id,
1315
+ origin: snapId,
1316
+ dappOrigin: origin
1317
+ },
1318
+ snapId
1319
+ },
1320
+ requestState: {
1321
+ loading: true
1322
+ }
1323
+ }, true);
1324
+ return {
1325
+ id,
1326
+ promise
1327
+ };
1328
+ }
1329
+ function updateApproval(id, requestState) {
1330
+ try {
1331
+ this.messagingSystem.call('ApprovalController:updateRequestState', {
1332
+ id,
1333
+ requestState
1334
+ });
1335
+ } catch {
1336
+ // Do nothing
1337
+ }
1338
+ }
1339
+ async function add(args) {
1340
+ const { id: snapId, location, versionRange } = args;
1341
+ _class_private_method_get(this, _setupRuntime, setupRuntime).call(this, snapId, {
1342
+ sourceCode: null,
1343
+ state: null
1344
+ });
1345
+ const runtime = _class_private_method_get(this, _getRuntimeExpect, getRuntimeExpect).call(this, snapId);
1346
+ if (!runtime.installPromise) {
1347
+ (0, _logging.log)(`Adding snap: ${snapId}`);
1348
+ // If fetching and setting the snap succeeds, this property will be set
1349
+ // to null in the authorize() method.
1350
+ runtime.installPromise = (async ()=>{
1351
+ const fetchedSnap = await _class_private_method_get(this, _fetchSnap, fetchSnap).call(this, snapId, location);
1352
+ const manifest = fetchedSnap.manifest.result;
1353
+ if (!(0, _utils.satisfiesVersionRange)(manifest.version, versionRange)) {
1354
+ throw new Error(`Version mismatch. Manifest for "${snapId}" specifies version "${manifest.version}" which doesn't satisfy requested version range "${versionRange}".`);
1355
+ }
1356
+ await _class_private_method_get(this, _assertIsInstallAllowed, assertIsInstallAllowed).call(this, snapId, {
1357
+ version: manifest.version,
1358
+ checksum: manifest.source.shasum
1359
+ });
1360
+ return _class_private_method_get(this, _set, set).call(this, {
1361
+ ...args,
1362
+ ...fetchedSnap,
1363
+ id: snapId
1364
+ });
1365
+ })();
1366
+ }
1367
+ try {
1368
+ return await runtime.installPromise;
1369
+ } catch (error) {
1370
+ // Reset promise so users can retry installation in case the problem is
1371
+ // temporary.
1372
+ runtime.installPromise = null;
1373
+ throw error;
1374
+ }
1375
+ }
1376
+ async function startSnap(snapData) {
1377
+ const { snapId } = snapData;
1378
+ if (this.isRunning(snapId)) {
1379
+ throw new Error(`Snap "${snapId}" is already started.`);
1380
+ }
1381
+ try {
1382
+ const result = await _class_private_method_get(this, _executeWithTimeout, executeWithTimeout).call(this, this.messagingSystem.call('ExecutionService:executeSnap', {
1383
+ ...snapData,
1384
+ endowments: await _class_private_method_get(this, _getEndowments, getEndowments).call(this, snapId)
1385
+ }));
1386
+ _class_private_method_get(this, _transition, transition).call(this, snapId, _snapsutils.SnapStatusEvents.Start);
1387
+ return result;
1388
+ } catch (error) {
1389
+ await _class_private_method_get(this, _terminateSnap, terminateSnap).call(this, snapId);
1390
+ throw error;
1391
+ }
1392
+ }
1393
+ async function getEndowments(snapId) {
1394
+ let allEndowments = [];
1395
+ for (const permissionName of _class_private_field_get(this, _environmentEndowmentPermissions)){
1396
+ if (this.messagingSystem.call('PermissionController:hasPermission', snapId, permissionName)) {
1397
+ const endowments = await this.messagingSystem.call('PermissionController:getEndowments', snapId, permissionName);
1398
+ if (endowments) {
1399
+ // We don't have any guarantees about the type of the endowments
1400
+ // value, so we have to guard at runtime.
1401
+ if (!Array.isArray(endowments) || endowments.some((value)=>typeof value !== 'string')) {
1402
+ throw new Error('Expected an array of string endowment names.');
1403
+ }
1404
+ allEndowments = allEndowments.concat(endowments);
1405
+ }
1406
+ }
1407
+ }
1408
+ const dedupedEndowments = [
1409
+ ...new Set([
1410
+ ..._snapsutils.DEFAULT_ENDOWMENTS,
1411
+ ...allEndowments
1412
+ ])
1413
+ ];
1414
+ if (dedupedEndowments.length < // This is a bug in TypeScript: https://github.com/microsoft/TypeScript/issues/48313
1415
+ // eslint-disable-next-line @typescript-eslint/restrict-plus-operands
1416
+ _snapsutils.DEFAULT_ENDOWMENTS.length + allEndowments.length) {
1417
+ (0, _snapsutils.logError)(`Duplicate endowments found for ${snapId}. Default endowments should not be requested.`, allEndowments);
1418
+ }
1419
+ return dedupedEndowments;
1420
+ }
1421
+ function set(args) {
1422
+ const { id: snapId, origin, manifest, files, isUpdate = false } = args;
1423
+ (0, _snapsutils.assertIsSnapManifest)(manifest.result);
1424
+ const { version } = manifest.result;
1425
+ const normalizedSourcePath = (0, _snapsutils.normalizeRelative)(manifest.result.source.location.npm.filePath);
1426
+ const { iconPath } = manifest.result.source.location.npm;
1427
+ const normalizedIconPath = iconPath && (0, _snapsutils.normalizeRelative)(iconPath);
1428
+ const sourceCode = files.find((file)=>file.path === normalizedSourcePath)?.toString();
1429
+ const svgIcon = normalizedIconPath ? files.find((file)=>file.path === normalizedIconPath) : undefined;
1430
+ (0, _utils.assert)(typeof sourceCode === 'string' && sourceCode.length > 0, `Invalid source code for snap "${snapId}".`);
1431
+ const snapsState = this.state.snaps;
1432
+ const existingSnap = snapsState[snapId];
1433
+ const previousVersionHistory = existingSnap?.versionHistory ?? [];
1434
+ const versionHistory = [
1435
+ ...previousVersionHistory,
1436
+ {
1437
+ version,
1438
+ date: Date.now(),
1439
+ origin
1440
+ }
1441
+ ];
1442
+ const snap = {
1443
+ // Restore relevant snap state if it exists
1444
+ ...existingSnap,
1445
+ // Note that the snap will be unblocked and enabled, regardless of its
1446
+ // previous state.
1447
+ blocked: false,
1448
+ enabled: true,
1449
+ id: snapId,
1450
+ initialPermissions: manifest.result.initialPermissions,
1451
+ manifest: manifest.result,
1452
+ status: _class_private_field_get(this, _statusMachine).config.initial,
1453
+ sourceCode,
1454
+ version,
1455
+ versionHistory
1456
+ };
1457
+ // If the snap was blocked, it isn't any longer
1458
+ delete snap.blockInformation;
1459
+ // store the snap back in state
1460
+ const { inversePatches } = this.update((state)=>{
1461
+ state.snaps[snapId] = snap;
1462
+ });
1463
+ // checking for isUpdate here as this function is also used in
1464
+ // the install flow, we do not care to create snapshots for installs
1465
+ if (isUpdate) {
1466
+ const rollbackSnapshot = _class_private_method_get(this, _getRollbackSnapshot, getRollbackSnapshot).call(this, snapId);
1467
+ if (rollbackSnapshot !== undefined) {
1468
+ rollbackSnapshot.statePatches = inversePatches;
1469
+ }
1470
+ }
1471
+ this.messagingSystem.publish(`SnapController:snapAdded`, snap, svgIcon?.toString());
1472
+ return {
1473
+ ...snap,
1474
+ sourceCode
1475
+ };
1476
+ }
1477
+ async function fetchSnap(snapId, location) {
1478
+ try {
1479
+ const manifest = await location.manifest();
1480
+ const sourceCode = await location.fetch(manifest.result.source.location.npm.filePath);
1481
+ const { iconPath } = manifest.result.source.location.npm;
1482
+ const svgIcon = iconPath ? await location.fetch(iconPath) : undefined;
1483
+ const files = [
1484
+ sourceCode
1485
+ ];
1486
+ if (svgIcon) {
1487
+ files.push(svgIcon);
1488
+ }
1489
+ (0, _snapsutils.validateFetchedSnap)({
1490
+ manifest,
1491
+ sourceCode,
1492
+ svgIcon
1493
+ });
1494
+ return {
1495
+ manifest,
1496
+ files,
1497
+ location
1498
+ };
1499
+ } catch (error) {
1500
+ throw new Error(`Failed to fetch snap "${snapId}": ${(0, _snapsutils.getErrorMessage)(error)}.`);
1501
+ }
1502
+ }
1503
+ function validateSnapPermissions(processedPermissions) {
1504
+ const permissionKeys = Object.keys(processedPermissions);
1505
+ const handlerPermissions = Array.from(new Set(Object.values(_endowments.handlerEndowments)));
1506
+ (0, _utils.assert)(permissionKeys.some((key)=>handlerPermissions.includes(key)), `A snap must request at least one of the following permissions: ${handlerPermissions.join(', ')}.`);
1507
+ const excludedPermissionErrors = permissionKeys.reduce((errors, permission)=>{
1508
+ if ((0, _utils.hasProperty)(_class_private_field_get(this, _excludedPermissions), permission)) {
1509
+ errors.push(_class_private_field_get(this, _excludedPermissions)[permission]);
1510
+ }
1511
+ return errors;
1512
+ }, []);
1513
+ (0, _utils.assert)(excludedPermissionErrors.length === 0, `One or more permissions are not allowed:\n${excludedPermissionErrors.join('\n')}`);
1514
+ }
1515
+ function getRpcRequestHandler(snapId) {
1516
+ const runtime = _class_private_method_get(this, _getRuntimeExpect, getRuntimeExpect).call(this, snapId);
1517
+ const existingHandler = runtime.rpcHandler;
1518
+ if (existingHandler) {
1519
+ return existingHandler;
1520
+ }
1521
+ const requestQueue = new _RequestQueue.RequestQueue(5);
1522
+ // We need to set up this promise map to map snapIds to their respective startPromises,
1523
+ // because otherwise we would lose context on the correct startPromise.
1524
+ const startPromises = new Map();
1525
+ const rpcHandler = async ({ origin, handler: handlerType, request })=>{
1526
+ if (this.state.snaps[snapId].enabled === false) {
1527
+ throw new Error(`Snap "${snapId}" is disabled.`);
1528
+ }
1529
+ if (this.state.snaps[snapId].status === _snapsutils.SnapStatus.Installing) {
1530
+ throw new Error(`Snap "${snapId}" is currently being installed. Please try again later.`);
1531
+ }
1532
+ if (!this.isRunning(snapId)) {
1533
+ let localStartPromise = startPromises.get(snapId);
1534
+ if (!localStartPromise) {
1535
+ localStartPromise = this.startSnap(snapId);
1536
+ startPromises.set(snapId, localStartPromise);
1537
+ } else if (requestQueue.get(origin) >= requestQueue.maxQueueSize) {
1538
+ throw new Error('Exceeds maximum number of requests waiting to be resolved, please try again.');
1539
+ }
1540
+ requestQueue.increment(origin);
1541
+ try {
1542
+ await localStartPromise;
1543
+ } finally{
1544
+ requestQueue.decrement(origin);
1545
+ // Only delete startPromise for a snap if its value hasn't changed
1546
+ if (startPromises.get(snapId) === localStartPromise) {
1547
+ startPromises.delete(snapId);
1548
+ }
1549
+ }
1550
+ }
1551
+ const timer = new _Timer.Timer(this.maxRequestTime);
1552
+ _class_private_method_get(this, _recordSnapRpcRequestStart, recordSnapRpcRequestStart).call(this, snapId, request.id, timer);
1553
+ const handleRpcRequestPromise = this.messagingSystem.call('ExecutionService:handleRpcRequest', snapId, {
1554
+ origin,
1555
+ handler: handlerType,
1556
+ request
1557
+ });
1558
+ // This will either get the result or reject due to the timeout.
1559
+ try {
1560
+ const result = await _class_private_method_get(this, _executeWithTimeout, executeWithTimeout).call(this, handleRpcRequestPromise, timer);
1561
+ _class_private_method_get(this, _recordSnapRpcRequestFinish, recordSnapRpcRequestFinish).call(this, snapId, request.id);
1562
+ return result;
1563
+ } catch (error) {
1564
+ await this.stopSnap(snapId, _snapsutils.SnapStatusEvents.Crash);
1565
+ throw error;
1566
+ }
1567
+ };
1568
+ runtime.rpcHandler = rpcHandler;
1569
+ return rpcHandler;
1570
+ }
1571
+ async function executeWithTimeout(promise, timer) {
1572
+ const result = await (0, _utils1.withTimeout)(promise, timer ?? this.maxRequestTime);
1573
+ if (result === _utils1.hasTimedOut) {
1574
+ throw new Error('The request timed out.');
1575
+ }
1576
+ return result;
1577
+ }
1578
+ function recordSnapRpcRequestStart(snapId, requestId, timer) {
1579
+ const runtime = _class_private_method_get(this, _getRuntimeExpect, getRuntimeExpect).call(this, snapId);
1580
+ runtime.pendingInboundRequests.push({
1581
+ requestId,
1582
+ timer
1583
+ });
1584
+ runtime.lastRequest = null;
1585
+ }
1586
+ function recordSnapRpcRequestFinish(snapId, requestId) {
1587
+ const runtime = _class_private_method_get(this, _getRuntimeExpect, getRuntimeExpect).call(this, snapId);
1588
+ runtime.pendingInboundRequests = runtime.pendingInboundRequests.filter((request)=>request.requestId !== requestId);
1589
+ if (runtime.pendingInboundRequests.length === 0) {
1590
+ runtime.lastRequest = Date.now();
1591
+ }
1592
+ }
1593
+ function getRollbackSnapshot(snapId) {
1594
+ return _class_private_field_get(this, _rollbackSnapshots).get(snapId);
1595
+ }
1596
+ function createRollbackSnapshot(snapId) {
1597
+ (0, _utils.assert)(_class_private_field_get(this, _rollbackSnapshots).get(snapId) === undefined, new Error(`Snap "${snapId}" rollback snapshot already exists.`));
1598
+ _class_private_field_get(this, _rollbackSnapshots).set(snapId, {
1599
+ statePatches: [],
1600
+ permissions: {
1601
+ revoked: null,
1602
+ granted: [],
1603
+ requestData: null
1604
+ },
1605
+ newVersion: ''
1606
+ });
1607
+ const newRollbackSnapshot = _class_private_field_get(this, _rollbackSnapshots).get(snapId);
1608
+ (0, _utils.assert)(newRollbackSnapshot !== undefined, new Error(`Snapshot creation failed for ${snapId}.`));
1609
+ return newRollbackSnapshot;
1610
+ }
1611
+ async function rollbackSnap(snapId) {
1612
+ const rollbackSnapshot = _class_private_method_get(this, _getRollbackSnapshot, getRollbackSnapshot).call(this, snapId);
1613
+ if (!rollbackSnapshot) {
1614
+ throw new Error('A snapshot does not exist for this snap.');
1615
+ }
1616
+ await this.stopSnap(snapId, _snapsutils.SnapStatusEvents.Stop);
1617
+ // Always set to stopped even if it wasn't running initially
1618
+ if (this.get(snapId)?.status !== _snapsutils.SnapStatus.Stopped) {
1619
+ _class_private_method_get(this, _transition, transition).call(this, snapId, _snapsutils.SnapStatusEvents.Stop);
1620
+ }
1621
+ const { statePatches, permissions } = rollbackSnapshot;
1622
+ if (statePatches?.length) {
1623
+ this.applyPatches(statePatches);
1624
+ }
1625
+ // Reset snap status, as we may have been in another state when we stored state patches
1626
+ // But now we are 100% in a stopped state
1627
+ if (this.get(snapId)?.status !== _snapsutils.SnapStatus.Stopped) {
1628
+ this.update((state)=>{
1629
+ state.snaps[snapId].status = _snapsutils.SnapStatus.Stopped;
1630
+ });
1631
+ }
1632
+ if (permissions.revoked && Object.keys(permissions.revoked).length) {
1633
+ this.messagingSystem.call('PermissionController:grantPermissions', {
1634
+ approvedPermissions: permissions.revoked,
1635
+ subject: {
1636
+ origin: snapId
1637
+ },
1638
+ requestData: permissions.requestData
1639
+ });
1640
+ }
1641
+ if (permissions.granted?.length) {
1642
+ this.messagingSystem.call('PermissionController:revokePermissions', {
1643
+ [snapId]: permissions.granted
1644
+ });
1645
+ }
1646
+ const truncatedSnap = this.getTruncatedExpect(snapId);
1647
+ this.messagingSystem.publish('SnapController:snapRolledback', truncatedSnap, rollbackSnapshot.newVersion);
1648
+ _class_private_field_get(this, _rollbackSnapshots).delete(snapId);
1649
+ }
1650
+ async function rollbackSnaps(snapIds) {
1651
+ for (const snapId of snapIds){
1652
+ await _class_private_method_get(this, _rollbackSnap, rollbackSnap).call(this, snapId);
1653
+ }
1654
+ }
1655
+ function getRuntime(snapId) {
1656
+ return _class_private_field_get(this, _snapsRuntimeData).get(snapId);
1657
+ }
1658
+ function getRuntimeExpect(snapId) {
1659
+ const runtime = _class_private_method_get(this, _getRuntime, getRuntime).call(this, snapId);
1660
+ (0, _utils.assert)(runtime !== undefined, new Error(`Snap "${snapId}" runtime data not found`));
1661
+ return runtime;
1662
+ }
1663
+ function setupRuntime(snapId, data) {
1664
+ if (_class_private_field_get(this, _snapsRuntimeData).has(snapId)) {
1665
+ return;
1666
+ }
1667
+ const snap = this.get(snapId);
1668
+ const interpreter = (0, _fsm.interpret)(_class_private_field_get(this, _statusMachine));
1669
+ interpreter.start({
1670
+ context: {
1671
+ snapId
1672
+ },
1673
+ value: snap?.status ?? _class_private_field_get(this, _statusMachine).config.initial
1674
+ });
1675
+ (0, _fsm1.forceStrict)(interpreter);
1676
+ _class_private_field_get(this, _snapsRuntimeData).set(snapId, {
1677
+ lastRequest: null,
1678
+ rpcHandler: null,
1679
+ installPromise: null,
1680
+ activeReferences: 0,
1681
+ pendingInboundRequests: [],
1682
+ pendingOutboundRequests: 0,
1683
+ interpreter,
1684
+ ...data
1685
+ });
1686
+ }
1687
+ function calculatePermissionsChange(snapId, desiredPermissionsSet) {
1688
+ const oldPermissions = this.messagingSystem.call('PermissionController:getPermissions', snapId) ?? {};
1689
+ const newPermissions = (0, _utils1.setDiff)(desiredPermissionsSet, oldPermissions);
1690
+ // TODO(ritave): The assumption that these are unused only holds so long as we do not
1691
+ // permit dynamic permission requests.
1692
+ const unusedPermissions = (0, _utils1.setDiff)(oldPermissions, desiredPermissionsSet);
1693
+ // It's a Set Intersection of oldPermissions and desiredPermissionsSet
1694
+ // oldPermissions ∖ (oldPermissions ∖ desiredPermissionsSet) ⟺ oldPermissions ∩ desiredPermissionsSet
1695
+ const approvedPermissions = (0, _utils1.setDiff)(oldPermissions, unusedPermissions);
1696
+ return {
1697
+ newPermissions,
1698
+ unusedPermissions,
1699
+ approvedPermissions
1700
+ };
1701
+ }
1702
+ function isValidUpdate(snapId, newVersionRange) {
1703
+ const existingSnap = this.getExpect(snapId);
1704
+ if ((0, _utils.satisfiesVersionRange)(existingSnap.version, newVersionRange)) {
1705
+ return false;
1706
+ }
1707
+ if ((0, _utils.gtRange)(existingSnap.version, newVersionRange)) {
1708
+ return false;
1709
+ }
1710
+ return true;
1711
+ }
1712
+ async function callLifecycleHook(snapId, handler) {
1713
+ const permissionName = _endowments.handlerEndowments[handler];
1714
+ const hasPermission = this.messagingSystem.call('PermissionController:hasPermission', snapId, permissionName);
1715
+ if (!hasPermission) {
1716
+ return;
1717
+ }
1718
+ await this.handleRequest({
1719
+ snapId,
1720
+ handler,
1721
+ origin: '',
1722
+ request: {
1723
+ jsonrpc: '2.0',
1724
+ method: handler
1725
+ }
1726
+ });
1727
+ }
1728
+
1729
+ //# sourceMappingURL=SnapController.js.map