@metamask/snaps-execution-environments 0.35.1-flask.1 → 1.0.0-prerelease.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 (231) hide show
  1. package/CHANGELOG.md +5 -39
  2. package/dist/browserify/iframe/bundle.js +12 -0
  3. package/dist/browserify/iframe/index.html +12128 -0
  4. package/dist/browserify/node-process/bundle.js +12127 -0
  5. package/dist/browserify/node-thread/bundle.js +12127 -0
  6. package/dist/browserify/offscreen/bundle.js +10 -0
  7. package/dist/browserify/offscreen/index.html +12128 -0
  8. package/dist/{types/common → common}/BaseSnapExecutor.d.ts +4 -4
  9. package/dist/common/BaseSnapExecutor.js +370 -0
  10. package/dist/common/BaseSnapExecutor.js.map +1 -0
  11. package/dist/common/commands.js +65 -0
  12. package/dist/common/commands.js.map +1 -0
  13. package/dist/{types/common → common}/endowments/commonEndowmentFactory.d.ts +1 -5
  14. package/dist/common/endowments/commonEndowmentFactory.js +75 -0
  15. package/dist/common/endowments/commonEndowmentFactory.js.map +1 -0
  16. package/dist/{types/common → common}/endowments/crypto.d.ts +0 -4
  17. package/dist/common/endowments/crypto.js +28 -0
  18. package/dist/common/endowments/crypto.js.map +1 -0
  19. package/dist/{esm/common → common}/endowments/date.js +16 -20
  20. package/dist/common/endowments/date.js.map +1 -0
  21. package/dist/{types/common → common}/endowments/index.d.ts +1 -3
  22. package/dist/{esm/common → common}/endowments/index.js +36 -34
  23. package/dist/common/endowments/index.js.map +1 -0
  24. package/dist/{esm/common → common}/endowments/interval.js +12 -13
  25. package/dist/common/endowments/interval.js.map +1 -0
  26. package/dist/{esm/common → common}/endowments/math.js +15 -21
  27. package/dist/common/endowments/math.js.map +1 -0
  28. package/dist/common/endowments/network.js +170 -0
  29. package/dist/common/endowments/network.js.map +1 -0
  30. package/dist/common/endowments/textDecoder.js +18 -0
  31. package/dist/common/endowments/textDecoder.js.map +1 -0
  32. package/dist/common/endowments/textEncoder.js +18 -0
  33. package/dist/common/endowments/textEncoder.js.map +1 -0
  34. package/dist/{esm/common → common}/endowments/timeout.js +13 -14
  35. package/dist/common/endowments/timeout.js.map +1 -0
  36. package/dist/{types/common → common}/globalEvents.d.ts +0 -1
  37. package/dist/common/globalEvents.js +47 -0
  38. package/dist/common/globalEvents.js.map +1 -0
  39. package/dist/common/globalObject.js +50 -0
  40. package/dist/{cjs/common → common}/globalObject.js.map +1 -1
  41. package/dist/common/keyring.d.ts +12 -0
  42. package/dist/common/keyring.js +42 -0
  43. package/dist/common/keyring.js.map +1 -0
  44. package/dist/common/lockdown/lockdown-events.js +60 -0
  45. package/dist/common/lockdown/lockdown-events.js.map +1 -0
  46. package/dist/{esm/common → common}/lockdown/lockdown-more.js +22 -15
  47. package/dist/common/lockdown/lockdown-more.js.map +1 -0
  48. package/dist/{esm/common → common}/lockdown/lockdown.js +11 -6
  49. package/dist/common/lockdown/lockdown.js.map +1 -0
  50. package/dist/{esm/common → common}/sortParams.js +13 -7
  51. package/dist/common/sortParams.js.map +1 -0
  52. package/dist/common/utils.js +133 -0
  53. package/dist/common/utils.js.map +1 -0
  54. package/dist/common/validation.js +109 -0
  55. package/dist/common/validation.js.map +1 -0
  56. package/dist/iframe/IFrameSnapExecutor.js +42 -0
  57. package/dist/iframe/IFrameSnapExecutor.js.map +1 -0
  58. package/dist/iframe/index.js +10 -0
  59. package/dist/iframe/index.js.map +1 -0
  60. package/dist/logging.js +13 -0
  61. package/dist/logging.js.map +1 -0
  62. package/dist/node-process/ChildProcessSnapExecutor.js +30 -0
  63. package/dist/node-process/ChildProcessSnapExecutor.js.map +1 -0
  64. package/dist/node-process/index.js +8 -0
  65. package/dist/node-process/index.js.map +1 -0
  66. package/dist/node-thread/ThreadSnapExecutor.js +30 -0
  67. package/dist/node-thread/ThreadSnapExecutor.js.map +1 -0
  68. package/dist/node-thread/index.js +8 -0
  69. package/dist/node-thread/index.js.map +1 -0
  70. package/dist/offscreen/OffscreenSnapExecutor.js +104 -0
  71. package/dist/offscreen/OffscreenSnapExecutor.js.map +1 -0
  72. package/dist/offscreen/index.js +16 -0
  73. package/dist/offscreen/index.js.map +1 -0
  74. package/dist/openrpc.json +210 -0
  75. package/package.json +26 -67
  76. package/dist/cjs/common/BaseSnapExecutor.js +0 -415
  77. package/dist/cjs/common/BaseSnapExecutor.js.map +0 -1
  78. package/dist/cjs/common/commands.js +0 -65
  79. package/dist/cjs/common/commands.js.map +0 -1
  80. package/dist/cjs/common/endowments/commonEndowmentFactory.js +0 -147
  81. package/dist/cjs/common/endowments/commonEndowmentFactory.js.map +0 -1
  82. package/dist/cjs/common/endowments/console.js +0 -134
  83. package/dist/cjs/common/endowments/console.js.map +0 -1
  84. package/dist/cjs/common/endowments/crypto.js +0 -44
  85. package/dist/cjs/common/endowments/crypto.js.map +0 -1
  86. package/dist/cjs/common/endowments/date.js +0 -53
  87. package/dist/cjs/common/endowments/date.js.map +0 -1
  88. package/dist/cjs/common/endowments/index.js +0 -91
  89. package/dist/cjs/common/endowments/index.js.map +0 -1
  90. package/dist/cjs/common/endowments/interval.js +0 -61
  91. package/dist/cjs/common/endowments/interval.js.map +0 -1
  92. package/dist/cjs/common/endowments/math.js +0 -67
  93. package/dist/cjs/common/endowments/math.js.map +0 -1
  94. package/dist/cjs/common/endowments/network.js +0 -206
  95. package/dist/cjs/common/endowments/network.js.map +0 -1
  96. package/dist/cjs/common/endowments/textDecoder.js +0 -28
  97. package/dist/cjs/common/endowments/textDecoder.js.map +0 -1
  98. package/dist/cjs/common/endowments/textEncoder.js +0 -28
  99. package/dist/cjs/common/endowments/textEncoder.js.map +0 -1
  100. package/dist/cjs/common/endowments/timeout.js +0 -63
  101. package/dist/cjs/common/endowments/timeout.js.map +0 -1
  102. package/dist/cjs/common/globalEvents.js +0 -39
  103. package/dist/cjs/common/globalEvents.js.map +0 -1
  104. package/dist/cjs/common/globalObject.js +0 -53
  105. package/dist/cjs/common/lockdown/lockdown-events.js +0 -74
  106. package/dist/cjs/common/lockdown/lockdown-events.js.map +0 -1
  107. package/dist/cjs/common/lockdown/lockdown-more.js +0 -73
  108. package/dist/cjs/common/lockdown/lockdown-more.js.map +0 -1
  109. package/dist/cjs/common/lockdown/lockdown.js +0 -30
  110. package/dist/cjs/common/lockdown/lockdown.js.map +0 -1
  111. package/dist/cjs/common/sortParams.js +0 -26
  112. package/dist/cjs/common/sortParams.js.map +0 -1
  113. package/dist/cjs/common/utils.js +0 -116
  114. package/dist/cjs/common/utils.js.map +0 -1
  115. package/dist/cjs/common/validation.js +0 -114
  116. package/dist/cjs/common/validation.js.map +0 -1
  117. package/dist/cjs/iframe/IFrameSnapExecutor.js +0 -50
  118. package/dist/cjs/iframe/IFrameSnapExecutor.js.map +0 -1
  119. package/dist/cjs/iframe/index.js +0 -13
  120. package/dist/cjs/iframe/index.js.map +0 -1
  121. package/dist/cjs/logging.js +0 -15
  122. package/dist/cjs/logging.js.map +0 -1
  123. package/dist/cjs/node-process/ChildProcessSnapExecutor.js +0 -39
  124. package/dist/cjs/node-process/ChildProcessSnapExecutor.js.map +0 -1
  125. package/dist/cjs/node-process/index.js +0 -11
  126. package/dist/cjs/node-process/index.js.map +0 -1
  127. package/dist/cjs/node-thread/ThreadSnapExecutor.js +0 -39
  128. package/dist/cjs/node-thread/ThreadSnapExecutor.js.map +0 -1
  129. package/dist/cjs/node-thread/index.js +0 -11
  130. package/dist/cjs/node-thread/index.js.map +0 -1
  131. package/dist/cjs/offscreen/OffscreenSnapExecutor.js +0 -173
  132. package/dist/cjs/offscreen/OffscreenSnapExecutor.js.map +0 -1
  133. package/dist/cjs/offscreen/index.js +0 -19
  134. package/dist/cjs/offscreen/index.js.map +0 -1
  135. package/dist/cjs/webworker/executor/WebWorkerSnapExecutor.js +0 -45
  136. package/dist/cjs/webworker/executor/WebWorkerSnapExecutor.js.map +0 -1
  137. package/dist/cjs/webworker/executor/index.js +0 -13
  138. package/dist/cjs/webworker/executor/index.js.map +0 -1
  139. package/dist/cjs/webworker/pool/WebWorkerPool.js +0 -248
  140. package/dist/cjs/webworker/pool/WebWorkerPool.js.map +0 -1
  141. package/dist/cjs/webworker/pool/index.js +0 -13
  142. package/dist/cjs/webworker/pool/index.js.map +0 -1
  143. package/dist/esm/common/BaseSnapExecutor.js +0 -400
  144. package/dist/esm/common/BaseSnapExecutor.js.map +0 -1
  145. package/dist/esm/common/commands.js +0 -64
  146. package/dist/esm/common/commands.js.map +0 -1
  147. package/dist/esm/common/endowments/commonEndowmentFactory.js +0 -132
  148. package/dist/esm/common/endowments/commonEndowmentFactory.js.map +0 -1
  149. package/dist/esm/common/endowments/console.js +0 -116
  150. package/dist/esm/common/endowments/console.js.map +0 -1
  151. package/dist/esm/common/endowments/crypto.js +0 -26
  152. package/dist/esm/common/endowments/crypto.js.map +0 -1
  153. package/dist/esm/common/endowments/date.js.map +0 -1
  154. package/dist/esm/common/endowments/index.js.map +0 -1
  155. package/dist/esm/common/endowments/interval.js.map +0 -1
  156. package/dist/esm/common/endowments/math.js.map +0 -1
  157. package/dist/esm/common/endowments/network.js +0 -196
  158. package/dist/esm/common/endowments/network.js.map +0 -1
  159. package/dist/esm/common/endowments/textDecoder.js +0 -18
  160. package/dist/esm/common/endowments/textDecoder.js.map +0 -1
  161. package/dist/esm/common/endowments/textEncoder.js +0 -18
  162. package/dist/esm/common/endowments/textEncoder.js.map +0 -1
  163. package/dist/esm/common/endowments/timeout.js.map +0 -1
  164. package/dist/esm/common/globalEvents.js +0 -35
  165. package/dist/esm/common/globalEvents.js.map +0 -1
  166. package/dist/esm/common/globalObject.js +0 -36
  167. package/dist/esm/common/globalObject.js.map +0 -1
  168. package/dist/esm/common/lockdown/lockdown-events.js +0 -66
  169. package/dist/esm/common/lockdown/lockdown-events.js.map +0 -1
  170. package/dist/esm/common/lockdown/lockdown-more.js.map +0 -1
  171. package/dist/esm/common/lockdown/lockdown.js.map +0 -1
  172. package/dist/esm/common/sortParams.js.map +0 -1
  173. package/dist/esm/common/utils.js +0 -120
  174. package/dist/esm/common/utils.js.map +0 -1
  175. package/dist/esm/common/validation.js +0 -92
  176. package/dist/esm/common/validation.js.map +0 -1
  177. package/dist/esm/iframe/IFrameSnapExecutor.js +0 -35
  178. package/dist/esm/iframe/IFrameSnapExecutor.js.map +0 -1
  179. package/dist/esm/iframe/index.js +0 -9
  180. package/dist/esm/iframe/index.js.map +0 -1
  181. package/dist/esm/logging.js +0 -10
  182. package/dist/esm/logging.js.map +0 -1
  183. package/dist/esm/node-process/ChildProcessSnapExecutor.js +0 -24
  184. package/dist/esm/node-process/ChildProcessSnapExecutor.js.map +0 -1
  185. package/dist/esm/node-process/index.js +0 -7
  186. package/dist/esm/node-process/index.js.map +0 -1
  187. package/dist/esm/node-thread/ThreadSnapExecutor.js +0 -24
  188. package/dist/esm/node-thread/ThreadSnapExecutor.js.map +0 -1
  189. package/dist/esm/node-thread/index.js +0 -7
  190. package/dist/esm/node-thread/index.js.map +0 -1
  191. package/dist/esm/offscreen/OffscreenSnapExecutor.js +0 -176
  192. package/dist/esm/offscreen/OffscreenSnapExecutor.js.map +0 -1
  193. package/dist/esm/offscreen/index.js +0 -15
  194. package/dist/esm/offscreen/index.js.map +0 -1
  195. package/dist/esm/webworker/executor/WebWorkerSnapExecutor.js +0 -30
  196. package/dist/esm/webworker/executor/WebWorkerSnapExecutor.js.map +0 -1
  197. package/dist/esm/webworker/executor/index.js +0 -9
  198. package/dist/esm/webworker/executor/index.js.map +0 -1
  199. package/dist/esm/webworker/pool/WebWorkerPool.js +0 -245
  200. package/dist/esm/webworker/pool/WebWorkerPool.js.map +0 -1
  201. package/dist/esm/webworker/pool/index.js +0 -9
  202. package/dist/esm/webworker/pool/index.js.map +0 -1
  203. package/dist/types/common/endowments/console.d.ts +0 -45
  204. package/dist/types/webworker/executor/WebWorkerSnapExecutor.d.ts +0 -13
  205. package/dist/types/webworker/executor/index.d.ts +0 -1
  206. package/dist/types/webworker/pool/WebWorkerPool.d.ts +0 -22
  207. package/dist/types/webworker/pool/index.d.ts +0 -1
  208. /package/dist/{types/common → common}/commands.d.ts +0 -0
  209. /package/dist/{types/common → common}/endowments/date.d.ts +0 -0
  210. /package/dist/{types/common → common}/endowments/interval.d.ts +0 -0
  211. /package/dist/{types/common → common}/endowments/math.d.ts +0 -0
  212. /package/dist/{types/common → common}/endowments/network.d.ts +0 -0
  213. /package/dist/{types/common → common}/endowments/textDecoder.d.ts +0 -0
  214. /package/dist/{types/common → common}/endowments/textEncoder.d.ts +0 -0
  215. /package/dist/{types/common → common}/endowments/timeout.d.ts +0 -0
  216. /package/dist/{types/common → common}/globalObject.d.ts +0 -0
  217. /package/dist/{types/common → common}/lockdown/lockdown-events.d.ts +0 -0
  218. /package/dist/{types/common → common}/lockdown/lockdown-more.d.ts +0 -0
  219. /package/dist/{types/common → common}/lockdown/lockdown.d.ts +0 -0
  220. /package/dist/{types/common → common}/sortParams.d.ts +0 -0
  221. /package/dist/{types/common → common}/utils.d.ts +0 -0
  222. /package/dist/{types/common → common}/validation.d.ts +0 -0
  223. /package/dist/{types/iframe → iframe}/IFrameSnapExecutor.d.ts +0 -0
  224. /package/dist/{types/iframe → iframe}/index.d.ts +0 -0
  225. /package/dist/{types/logging.d.ts → logging.d.ts} +0 -0
  226. /package/dist/{types/node-process → node-process}/ChildProcessSnapExecutor.d.ts +0 -0
  227. /package/dist/{types/node-process → node-process}/index.d.ts +0 -0
  228. /package/dist/{types/node-thread → node-thread}/ThreadSnapExecutor.d.ts +0 -0
  229. /package/dist/{types/node-thread → node-thread}/index.d.ts +0 -0
  230. /package/dist/{types/offscreen → offscreen}/OffscreenSnapExecutor.d.ts +0 -0
  231. /package/dist/{types/offscreen → offscreen}/index.d.ts +0 -0
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const globalObject_1 = require("../globalObject");
4
+ const createCrypto = () => {
5
+ if ('crypto' in globalObject_1.rootRealmGlobal &&
6
+ typeof globalObject_1.rootRealmGlobal.crypto === 'object' &&
7
+ 'SubtleCrypto' in globalObject_1.rootRealmGlobal &&
8
+ typeof globalObject_1.rootRealmGlobal.SubtleCrypto === 'function') {
9
+ return {
10
+ crypto: harden(globalObject_1.rootRealmGlobal.crypto),
11
+ SubtleCrypto: harden(globalObject_1.rootRealmGlobal.SubtleCrypto),
12
+ };
13
+ }
14
+ // For now, we expose the experimental webcrypto API for Node.js execution environments
15
+ // TODO: Figure out if this is enough long-term or if we should use a polyfill.
16
+ /* eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires, node/global-require */
17
+ const crypto = require('crypto').webcrypto;
18
+ return {
19
+ crypto: harden(crypto),
20
+ SubtleCrypto: harden(crypto.subtle.constructor),
21
+ };
22
+ };
23
+ const endowmentModule = {
24
+ names: ['crypto', 'SubtleCrypto'],
25
+ factory: createCrypto,
26
+ };
27
+ exports.default = endowmentModule;
28
+ //# sourceMappingURL=crypto.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crypto.js","sourceRoot":"","sources":["../../../src/common/endowments/crypto.ts"],"names":[],"mappings":";;AAAA,kDAAkD;AAElD,MAAM,YAAY,GAAG,GAAG,EAAE;IACxB,IACE,QAAQ,IAAI,8BAAe;QAC3B,OAAO,8BAAe,CAAC,MAAM,KAAK,QAAQ;QAC1C,cAAc,IAAI,8BAAe;QACjC,OAAO,8BAAe,CAAC,YAAY,KAAK,UAAU,EAClD;QACA,OAAO;YACL,MAAM,EAAE,MAAM,CAAC,8BAAe,CAAC,MAAM,CAAC;YACtC,YAAY,EAAE,MAAM,CAAC,8BAAe,CAAC,YAAY,CAAC;SACnD,CAAC;KACH;IACD,uFAAuF;IACvF,+EAA+E;IAC/E,6HAA6H;IAC7H,MAAM,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC,SAAS,CAAC;IAC3C,OAAO;QACL,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC;QACtB,YAAY,EAAE,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,WAAW,CAAC;KACvC,CAAC;AACb,CAAC,CAAC;AAEF,MAAM,eAAe,GAAG;IACtB,KAAK,EAAE,CAAC,QAAQ,EAAE,cAAc,CAAU;IAC1C,OAAO,EAAE,YAAY;CACtB,CAAC;AACF,kBAAe,eAAe,CAAC","sourcesContent":["import { rootRealmGlobal } from '../globalObject';\n\nconst createCrypto = () => {\n if (\n 'crypto' in rootRealmGlobal &&\n typeof rootRealmGlobal.crypto === 'object' &&\n 'SubtleCrypto' in rootRealmGlobal &&\n typeof rootRealmGlobal.SubtleCrypto === 'function'\n ) {\n return {\n crypto: harden(rootRealmGlobal.crypto),\n SubtleCrypto: harden(rootRealmGlobal.SubtleCrypto),\n };\n }\n // For now, we expose the experimental webcrypto API for Node.js execution environments\n // TODO: Figure out if this is enough long-term or if we should use a polyfill.\n /* eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires, node/global-require */\n const crypto = require('crypto').webcrypto;\n return {\n crypto: harden(crypto),\n SubtleCrypto: harden(crypto.subtle.constructor),\n } as const;\n};\n\nconst endowmentModule = {\n names: ['crypto', 'SubtleCrypto'] as const,\n factory: createCrypto,\n};\nexport default endowmentModule;\n"]}
@@ -1,43 +1,39 @@
1
- import { rootRealmGlobal } from '../globalObject';
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const globalObject_1 = require("../globalObject");
2
4
  /**
3
5
  * Creates a {@link Date} constructor, with most of the same properties as the global object.
4
6
  * The Date.now() function has added noise as to limit its precision and prevent potential timing attacks.
5
7
  * The Date constructor uses this now() function to seed itself if no arguments are given to the constructor.
6
8
  *
7
9
  * @returns A modified {@link Date} constructor with limited precision.
8
- */ function createDate() {
9
- const keys = Object.getOwnPropertyNames(rootRealmGlobal.Date);
10
+ */
11
+ function createDate() {
12
+ const keys = Object.getOwnPropertyNames(globalObject_1.rootRealmGlobal.Date);
10
13
  let currentTime = 0;
11
- const now = ()=>{
12
- const actual = rootRealmGlobal.Date.now();
14
+ const now = () => {
15
+ const actual = globalObject_1.rootRealmGlobal.Date.now();
13
16
  const newTime = Math.round(actual + Math.random());
14
17
  if (newTime > currentTime) {
15
18
  currentTime = newTime;
16
19
  }
17
20
  return currentTime;
18
21
  };
19
- const NewDate = function(...args) {
20
- return Reflect.construct(rootRealmGlobal.Date, args.length === 0 ? [
21
- now()
22
- ] : args, new.target);
22
+ const NewDate = function (...args) {
23
+ return Reflect.construct(globalObject_1.rootRealmGlobal.Date, args.length === 0 ? [now()] : args, new.target);
23
24
  };
24
- keys.forEach((key)=>{
25
+ keys.forEach((key) => {
25
26
  Reflect.defineProperty(NewDate, key, {
26
27
  configurable: false,
27
28
  writable: false,
28
- value: key === 'now' ? now : rootRealmGlobal.Date[key]
29
+ value: key === 'now' ? now : globalObject_1.rootRealmGlobal.Date[key],
29
30
  });
30
31
  });
31
- return {
32
- Date: harden(NewDate)
33
- };
32
+ return { Date: harden(NewDate) };
34
33
  }
35
34
  const endowmentModule = {
36
- names: [
37
- 'Date'
38
- ],
39
- factory: createDate
35
+ names: ['Date'],
36
+ factory: createDate,
40
37
  };
41
- export default endowmentModule;
42
-
38
+ exports.default = endowmentModule;
43
39
  //# sourceMappingURL=date.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"date.js","sourceRoot":"","sources":["../../../src/common/endowments/date.ts"],"names":[],"mappings":";;AAAA,kDAAkD;AAElD;;;;;;GAMG;AACH,SAAS,UAAU;IACjB,MAAM,IAAI,GAAG,MAAM,CAAC,mBAAmB,CACrC,8BAAe,CAAC,IAAI,CACI,CAAC;IAE3B,IAAI,WAAW,GAAG,CAAC,CAAC;IACpB,MAAM,GAAG,GAAG,GAAG,EAAE;QACf,MAAM,MAAM,GAAG,8BAAe,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC;QAC1C,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;QACnD,IAAI,OAAO,GAAG,WAAW,EAAE;YACzB,WAAW,GAAG,OAAO,CAAC;SACvB;QACD,OAAO,WAAW,CAAC;IACrB,CAAC,CAAC;IAEF,MAAM,OAAO,GAAG,UAAU,GAAG,IAAe;QAC1C,OAAO,OAAO,CAAC,SAAS,CACtB,8BAAe,CAAC,IAAI,EACpB,IAAI,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,EAClC,GAAG,CAAC,MAAM,CACX,CAAC;IACJ,CAAoB,CAAC;IAErB,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE;QACnB,OAAO,CAAC,cAAc,CAAC,OAAO,EAAE,GAAG,EAAE;YACnC,YAAY,EAAE,KAAK;YACnB,QAAQ,EAAE,KAAK;YACf,KAAK,EAAE,GAAG,KAAK,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,8BAAe,CAAC,IAAI,CAAC,GAAG,CAAC;SACvD,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,OAAO,EAAE,IAAI,EAAE,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC;AACnC,CAAC;AAED,MAAM,eAAe,GAAG;IACtB,KAAK,EAAE,CAAC,MAAM,CAAU;IACxB,OAAO,EAAE,UAAU;CACpB,CAAC;AAEF,kBAAe,eAAe,CAAC","sourcesContent":["import { rootRealmGlobal } from '../globalObject';\n\n/**\n * Creates a {@link Date} constructor, with most of the same properties as the global object.\n * The Date.now() function has added noise as to limit its precision and prevent potential timing attacks.\n * The Date constructor uses this now() function to seed itself if no arguments are given to the constructor.\n *\n * @returns A modified {@link Date} constructor with limited precision.\n */\nfunction createDate() {\n const keys = Object.getOwnPropertyNames(\n rootRealmGlobal.Date,\n ) as (keyof typeof Date)[];\n\n let currentTime = 0;\n const now = () => {\n const actual = rootRealmGlobal.Date.now();\n const newTime = Math.round(actual + Math.random());\n if (newTime > currentTime) {\n currentTime = newTime;\n }\n return currentTime;\n };\n\n const NewDate = function (...args: unknown[]) {\n return Reflect.construct(\n rootRealmGlobal.Date,\n args.length === 0 ? [now()] : args,\n new.target,\n );\n } as DateConstructor;\n\n keys.forEach((key) => {\n Reflect.defineProperty(NewDate, key, {\n configurable: false,\n writable: false,\n value: key === 'now' ? now : rootRealmGlobal.Date[key],\n });\n });\n\n return { Date: harden(NewDate) };\n}\n\nconst endowmentModule = {\n names: ['Date'] as const,\n factory: createDate,\n};\n\nexport default endowmentModule;\n"]}
@@ -1,6 +1,5 @@
1
1
  import { StreamProvider } from '@metamask/providers';
2
2
  import { SnapsGlobalObject } from '@metamask/rpc-methods';
3
- import { SnapId } from '@metamask/snaps-utils';
4
3
  /**
5
4
  * Gets the endowments for a particular Snap. Some endowments, like `setTimeout`
6
5
  * and `clearTimeout`, must be attenuated so that they can only affect behavior
@@ -10,11 +9,10 @@ import { SnapId } from '@metamask/snaps-utils';
10
9
  *
11
10
  * @param snap - The Snaps global API object.
12
11
  * @param ethereum - The Snap's EIP-1193 provider object.
13
- * @param snapId - The id of the snap that will use the created endowments.
14
12
  * @param endowments - The list of endowments to provide to the snap.
15
13
  * @returns An object containing the Snap's endowments.
16
14
  */
17
- export declare function createEndowments(snap: SnapsGlobalObject, ethereum: StreamProvider, snapId: SnapId, endowments?: string[]): {
15
+ export declare function createEndowments(snap: SnapsGlobalObject, ethereum: StreamProvider, endowments?: string[]): {
18
16
  endowments: Record<string, unknown>;
19
17
  teardown: () => Promise<void>;
20
18
  };
@@ -1,16 +1,24 @@
1
- import { logWarning } from '@metamask/snaps-utils';
2
- import { hasProperty } from '@metamask/utils';
3
- import { rootRealmGlobal } from '../globalObject';
4
- import buildCommonEndowments from './commonEndowmentFactory';
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.createEndowments = void 0;
7
+ const snaps_utils_1 = require("@metamask/snaps-utils");
8
+ const utils_1 = require("@metamask/utils");
9
+ const globalObject_1 = require("../globalObject");
10
+ const commonEndowmentFactory_1 = __importDefault(require("./commonEndowmentFactory"));
5
11
  /**
6
12
  * Retrieve consolidated endowment factories for common endowments.
7
- */ const registeredEndowments = buildCommonEndowments();
13
+ */
14
+ const registeredEndowments = (0, commonEndowmentFactory_1.default)();
8
15
  /**
9
16
  * A map of endowment names to their factory functions. Some endowments share
10
17
  * the same factory function, but we only call each factory once for each snap.
11
18
  * See {@link createEndowments} for details.
12
- */ const endowmentFactories = registeredEndowments.reduce((factories, builder)=>{
13
- builder.names.forEach((name)=>{
19
+ */
20
+ const endowmentFactories = registeredEndowments.reduce((factories, builder) => {
21
+ builder.names.forEach((name) => {
14
22
  factories.set(name, builder.factory);
15
23
  });
16
24
  return factories;
@@ -24,65 +32,59 @@ import buildCommonEndowments from './commonEndowmentFactory';
24
32
  *
25
33
  * @param snap - The Snaps global API object.
26
34
  * @param ethereum - The Snap's EIP-1193 provider object.
27
- * @param snapId - The id of the snap that will use the created endowments.
28
35
  * @param endowments - The list of endowments to provide to the snap.
29
36
  * @returns An object containing the Snap's endowments.
30
- */ export function createEndowments(snap, ethereum, snapId, endowments = []) {
37
+ */
38
+ function createEndowments(snap, ethereum, endowments = []) {
31
39
  const attenuatedEndowments = {};
32
40
  // TODO: All endowments should be hardened to prevent covert communication
33
41
  // channels. Hardening the returned objects breaks tests elsewhere in the
34
42
  // monorepo, so further research is needed.
35
- const result = endowments.reduce(({ allEndowments, teardowns }, endowmentName)=>{
43
+ const result = endowments.reduce(({ allEndowments, teardowns }, endowmentName) => {
36
44
  // First, check if the endowment has a factory, and default to that.
37
45
  if (endowmentFactories.has(endowmentName)) {
38
- if (!hasProperty(attenuatedEndowments, endowmentName)) {
46
+ if (!(0, utils_1.hasProperty)(attenuatedEndowments, endowmentName)) {
39
47
  // Call the endowment factory for the current endowment. If the factory
40
48
  // creates multiple endowments, they will all be assigned to the
41
49
  // `attenuatedEndowments` object, but will only be passed on to the snap
42
50
  // if explicitly listed among its endowment.
43
51
  // This may not have an actual use case, but, safety first.
44
52
  // We just confirmed that endowmentFactories has the specified key.
53
+ const { teardownFunction, ...endowment } =
45
54
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
46
- const { teardownFunction, ...endowment } = endowmentFactories.get(endowmentName)({
47
- snapId
48
- });
55
+ endowmentFactories.get(endowmentName)();
49
56
  Object.assign(attenuatedEndowments, endowment);
50
57
  if (teardownFunction) {
51
58
  teardowns.push(teardownFunction);
52
59
  }
53
60
  }
54
61
  allEndowments[endowmentName] = attenuatedEndowments[endowmentName];
55
- } else if (endowmentName === 'ethereum') {
62
+ }
63
+ else if (endowmentName === 'ethereum') {
56
64
  // Special case for adding the EIP-1193 provider.
57
65
  allEndowments[endowmentName] = ethereum;
58
- } else if (endowmentName in rootRealmGlobal) {
59
- logWarning(`Access to unhardened global ${endowmentName}.`);
66
+ }
67
+ else if (endowmentName in globalObject_1.rootRealmGlobal) {
68
+ (0, snaps_utils_1.logWarning)(`Access to unhardened global ${endowmentName}.`);
60
69
  // If the endowment doesn't have a factory, just use whatever is on the
61
70
  // global object.
62
- const globalValue = rootRealmGlobal[endowmentName];
71
+ const globalValue = globalObject_1.rootRealmGlobal[endowmentName];
63
72
  allEndowments[endowmentName] = globalValue;
64
- } else {
73
+ }
74
+ else {
65
75
  // If we get to this point, we've been passed an endowment that doesn't
66
76
  // exist in our current environment.
67
77
  throw new Error(`Unknown endowment: "${endowmentName}".`);
68
78
  }
69
- return {
70
- allEndowments,
71
- teardowns
72
- };
79
+ return { allEndowments, teardowns };
73
80
  }, {
74
- allEndowments: {
75
- snap
76
- },
77
- teardowns: []
81
+ allEndowments: { snap },
82
+ teardowns: [],
78
83
  });
79
- const teardown = async ()=>{
80
- await Promise.all(result.teardowns.map((teardownFunction)=>teardownFunction()));
81
- };
82
- return {
83
- endowments: result.allEndowments,
84
- teardown
84
+ const teardown = async () => {
85
+ await Promise.all(result.teardowns.map((teardownFunction) => teardownFunction()));
85
86
  };
87
+ return { endowments: result.allEndowments, teardown };
86
88
  }
87
-
89
+ exports.createEndowments = createEndowments;
88
90
  //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/common/endowments/index.ts"],"names":[],"mappings":";;;;;;AAEA,uDAAmD;AACnD,2CAA8C;AAE9C,kDAAkD;AAClD,sFAA6D;AAe7D;;GAEG;AACH,MAAM,oBAAoB,GAAG,IAAA,gCAAqB,GAAE,CAAC;AAErD;;;;GAIG;AACH,MAAM,kBAAkB,GAAG,oBAAoB,CAAC,MAAM,CAAC,CAAC,SAAS,EAAE,OAAO,EAAE,EAAE;IAC5E,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE;QAC7B,SAAS,CAAC,GAAG,CAAC,IAAI,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;IACvC,CAAC,CAAC,CAAC;IACH,OAAO,SAAS,CAAC;AACnB,CAAC,EAAE,IAAI,GAAG,EAAwC,CAAC,CAAC;AAEpD;;;;;;;;;;;GAWG;AACH,SAAgB,gBAAgB,CAC9B,IAAuB,EACvB,QAAwB,EACxB,aAAuB,EAAE;IAEzB,MAAM,oBAAoB,GAA4B,EAAE,CAAC;IAEzD,0EAA0E;IAC1E,yEAAyE;IACzE,2CAA2C;IAC3C,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,CAI9B,CAAC,EAAE,aAAa,EAAE,SAAS,EAAE,EAAE,aAAa,EAAE,EAAE;QAC9C,oEAAoE;QACpE,IAAI,kBAAkB,CAAC,GAAG,CAAC,aAAa,CAAC,EAAE;YACzC,IAAI,CAAC,IAAA,mBAAW,EAAC,oBAAoB,EAAE,aAAa,CAAC,EAAE;gBACrD,uEAAuE;gBACvE,gEAAgE;gBAChE,wEAAwE;gBACxE,4CAA4C;gBAC5C,2DAA2D;gBAE3D,mEAAmE;gBACnE,MAAM,EAAE,gBAAgB,EAAE,GAAG,SAAS,EAA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sGlobalObject } from '@metamask/rpc-methods';\nimport { logWarning } from '@metamask/snaps-utils';\nimport { hasProperty } from '@metamask/utils';\n\nimport { rootRealmGlobal } from '../globalObject';\nimport buildCommonEndowments from './commonEndowmentFactory';\n\ntype EndowmentFactoryResult = {\n /**\n * A function that performs any necessary teardown when the snap becomes idle.\n *\n * NOTE:** The endowments are not reconstructed if the snap is re-invoked\n * before being terminated, so the teardown operation must not render the\n * endowments unusable; it should simply restore the endowments to their\n * original state.\n */\n teardownFunction?: () => Promise<void> | void;\n [key: string]: unknown;\n};\n\n/**\n * Retrieve consolidated endowment factories for common endowments.\n */\nconst registeredEndowments = buildCommonEndowments();\n\n/**\n * A map of endowment names to their factory functions. Some endowments share\n * the same factory function, but we only call each factory once for each snap.\n * See {@link createEndowments} for details.\n */\nconst endowmentFactories = registeredEndowments.reduce((factories, builder) => {\n builder.names.forEach((name) => {\n factories.set(name, builder.factory);\n });\n return factories;\n}, new Map<string, () => EndowmentFactoryResult>());\n\n/**\n * Gets the endowments for a particular Snap. Some endowments, like `setTimeout`\n * and `clearTimeout`, must be attenuated so that they can only affect behavior\n * within the Snap's own realm. Therefore, we use factory functions to create\n * such attenuated / modified endowments. Otherwise, the value that's on the\n * root realm global will be used.\n *\n * @param snap - The Snaps global API object.\n * @param ethereum - The Snap's EIP-1193 provider object.\n * @param endowments - The list of endowments to provide to the snap.\n * @returns An object containing the Snap's endowments.\n */\nexport function createEndowments(\n snap: SnapsGlobalObject,\n ethereum: StreamProvider,\n endowments: string[] = [],\n): { endowments: Record<string, unknown>; teardown: () => Promise<void> } {\n const attenuatedEndowments: Record<string, unknown> = {};\n\n // TODO: All endowments should be hardened to prevent covert communication\n // channels. Hardening the returned objects breaks tests elsewhere in the\n // monorepo, so further research is needed.\n const result = endowments.reduce<{\n allEndowments: Record<string, unknown>;\n teardowns: (() => Promise<void> | void)[];\n }>(\n ({ allEndowments, teardowns }, endowmentName) => {\n // First, check if the endowment has a factory, and default to that.\n if (endowmentFactories.has(endowmentName)) {\n if (!hasProperty(attenuatedEndowments, endowmentName)) {\n // Call the endowment factory for the current endowment. If the factory\n // creates multiple endowments, they will all be assigned to the\n // `attenuatedEndowments` object, but will only be passed on to the snap\n // if explicitly listed among its endowment.\n // This may not have an actual use case, but, safety first.\n\n // We just confirmed that endowmentFactories has the specified key.\n const { teardownFunction, ...endowment } =\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n endowmentFactories.get(endowmentName)!();\n Object.assign(attenuatedEndowments, endowment);\n if (teardownFunction) {\n teardowns.push(teardownFunction);\n }\n }\n\n allEndowments[endowmentName] = attenuatedEndowments[endowmentName];\n } else if (endowmentName === 'ethereum') {\n // Special case for adding the EIP-1193 provider.\n allEndowments[endowmentName] = ethereum;\n } else if (endowmentName in rootRealmGlobal) {\n logWarning(`Access to unhardened global ${endowmentName}.`);\n // If the endowment doesn't have a factory, just use whatever is on the\n // global object.\n const globalValue = (rootRealmGlobal as Record<string, unknown>)[\n endowmentName\n ];\n allEndowments[endowmentName] = globalValue;\n } else {\n // If we get to this point, we've been passed an endowment that doesn't\n // exist in our current environment.\n throw new Error(`Unknown endowment: \"${endowmentName}\".`);\n }\n return { allEndowments, teardowns };\n },\n {\n allEndowments: { snap },\n teardowns: [],\n },\n );\n\n const teardown = async () => {\n await Promise.all(\n result.teardowns.map((teardownFunction) => teardownFunction()),\n );\n };\n return { endowments: result.allEndowments, teardown };\n}\n"]}
@@ -1,3 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
1
3
  const MINIMUM_INTERVAL = 10;
2
4
  /**
3
5
  * Creates a pair of `setInterval` and `clearInterval` functions attenuated such
@@ -8,9 +10,10 @@ const MINIMUM_INTERVAL = 10;
8
10
  *
9
11
  * @returns An object with the attenuated `setInterval` and `clearInterval`
10
12
  * functions.
11
- */ const createInterval = ()=>{
13
+ */
14
+ const createInterval = () => {
12
15
  const registeredHandles = new Map();
13
- const _setInterval = (handler, timeout)=>{
16
+ const _setInterval = (handler, timeout) => {
14
17
  if (typeof handler !== 'function') {
15
18
  throw new Error(`The interval handler must be a function. Received: ${typeof handler}`);
16
19
  }
@@ -20,7 +23,7 @@ const MINIMUM_INTERVAL = 10;
20
23
  registeredHandles.set(handle, platformHandle);
21
24
  return handle;
22
25
  };
23
- const _clearInterval = (handle)=>{
26
+ const _clearInterval = (handle) => {
24
27
  harden(handle);
25
28
  const platformHandle = registeredHandles.get(handle);
26
29
  if (platformHandle !== undefined) {
@@ -28,24 +31,20 @@ const MINIMUM_INTERVAL = 10;
28
31
  registeredHandles.delete(handle);
29
32
  }
30
33
  };
31
- const teardownFunction = ()=>{
32
- for (const handle of registeredHandles.keys()){
34
+ const teardownFunction = () => {
35
+ for (const handle of registeredHandles.keys()) {
33
36
  _clearInterval(handle);
34
37
  }
35
38
  };
36
39
  return {
37
40
  setInterval: harden(_setInterval),
38
41
  clearInterval: harden(_clearInterval),
39
- teardownFunction
42
+ teardownFunction,
40
43
  };
41
44
  };
42
45
  const endowmentModule = {
43
- names: [
44
- 'setInterval',
45
- 'clearInterval'
46
- ],
47
- factory: createInterval
46
+ names: ['setInterval', 'clearInterval'],
47
+ factory: createInterval,
48
48
  };
49
- export default endowmentModule;
50
-
49
+ exports.default = endowmentModule;
51
50
  //# sourceMappingURL=interval.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"interval.js","sourceRoot":"","sources":["../../../src/common/endowments/interval.ts"],"names":[],"mappings":";;AAAA,MAAM,gBAAgB,GAAG,EAAE,CAAC;AAE5B;;;;;;;;;GASG;AACH,MAAM,cAAc,GAAG,GAAG,EAAE;IAC1B,MAAM,iBAAiB,GAAG,IAAI,GAAG,EAAoB,CAAC;IAEtD,MAAM,YAAY,GAAG,CAAC,OAAqB,EAAE,OAAgB,EAAW,EAAE;QACxE,IAAI,OAAO,OAAO,KAAK,UAAU,EAAE;YACjC,MAAM,IAAI,KAAK,CACb,sDAAsD,OAAO,OAAO,EAAE,CACvE,CAAC;SACH;QACD,MAAM,CAAC,OAAO,CAAC,CAAC;QAChB,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;QAClD,MAAM,cAAc,GAAG,WAAW,CAChC,OAAO,EACP,IAAI,CAAC,GAAG,CAAC,gBAAgB,EAAE,OAAO,IAAI,CAAC,CAAC,CACzC,CAAC;QACF,iBAAiB,CAAC,GAAG,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;QAC9C,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;IAEF,MAAM,cAAc,GAAG,CAAC,MAAe,EAAQ,EAAE;QAC/C,MAAM,CAAC,MAAM,CAAC,CAAC;QACf,MAAM,cAAc,GAAG,iBAAiB,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACrD,IAAI,cAAc,KAAK,SAAS,EAAE;YAChC,aAAa,CAAC,cAAqB,CAAC,CAAC;YACrC,iBAAiB,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;SAClC;IACH,CAAC,CAAC;IAEF,MAAM,gBAAgB,GAAG,GAAS,EAAE;QAClC,KAAK,MAAM,MAAM,IAAI,iBAAiB,CAAC,IAAI,EAAE,EAAE;YAC7C,cAAc,CAAC,MAAM,CAAC,CAAC;SACxB;IACH,CAAC,CAAC;IAEF,OAAO;QACL,WAAW,EAAE,MAAM,CAAC,YAAY,CAAC;QACjC,aAAa,EAAE,MAAM,CAAC,cAAc,CAAC;QACrC,gBAAgB;KACR,CAAC;AACb,CAAC,CAAC;AAEF,MAAM,eAAe,GAAG;IACtB,KAAK,EAAE,CAAC,aAAa,EAAE,eAAe,CAAU;IAChD,OAAO,EAAE,cAAc;CACxB,CAAC;AACF,kBAAe,eAAe,CAAC","sourcesContent":["const MINIMUM_INTERVAL = 10;\n\n/**\n * Creates a pair of `setInterval` and `clearInterval` functions attenuated such\n * that:\n * - `setInterval` throws if its \"handler\" parameter is not a function.\n * - `clearInterval` only clears timeouts created by its sibling `setInterval`,\n * or else no-ops.\n *\n * @returns An object with the attenuated `setInterval` and `clearInterval`\n * functions.\n */\nconst createInterval = () => {\n const registeredHandles = new Map<unknown, unknown>();\n\n const _setInterval = (handler: TimerHandler, timeout?: number): unknown => {\n if (typeof handler !== 'function') {\n throw new Error(\n `The interval handler must be a function. Received: ${typeof handler}`,\n );\n }\n harden(handler);\n const handle = Object.freeze(Object.create(null));\n const platformHandle = setInterval(\n handler,\n Math.max(MINIMUM_INTERVAL, timeout ?? 0),\n );\n registeredHandles.set(handle, platformHandle);\n return handle;\n };\n\n const _clearInterval = (handle: unknown): void => {\n harden(handle);\n const platformHandle = registeredHandles.get(handle);\n if (platformHandle !== undefined) {\n clearInterval(platformHandle as any);\n registeredHandles.delete(handle);\n }\n };\n\n const teardownFunction = (): void => {\n for (const handle of registeredHandles.keys()) {\n _clearInterval(handle);\n }\n };\n\n return {\n setInterval: harden(_setInterval),\n clearInterval: harden(_clearInterval),\n teardownFunction,\n } as const;\n};\n\nconst endowmentModule = {\n names: ['setInterval', 'clearInterval'] as const,\n factory: createInterval,\n};\nexport default endowmentModule;\n"]}
@@ -1,30 +1,27 @@
1
- import { rootRealmGlobal } from '../globalObject';
2
- import { createCrypto } from './crypto';
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const globalObject_1 = require("../globalObject");
3
4
  /**
4
5
  * Create a {@link Math} object, with the same properties as the global
5
6
  * {@link Math} object, but with the {@link Math.random} method replaced.
6
7
  *
7
8
  * @returns The {@link Math} object with the {@link Math.random} method
8
9
  * replaced.
9
- */ function createMath() {
10
+ */
11
+ function createMath() {
10
12
  // `Math` does not work with `Object.keys`, `Object.entries`, etc., so we
11
13
  // need to create a new object with the same properties.
12
- const keys = Object.getOwnPropertyNames(rootRealmGlobal.Math);
13
- const math = keys.reduce((target, key)=>{
14
+ const keys = Object.getOwnPropertyNames(globalObject_1.rootRealmGlobal.Math);
15
+ const math = keys.reduce((target, key) => {
14
16
  if (key === 'random') {
15
17
  return target;
16
18
  }
17
- return {
18
- ...target,
19
- [key]: rootRealmGlobal.Math[key]
20
- };
19
+ return { ...target, [key]: globalObject_1.rootRealmGlobal.Math[key] };
21
20
  }, {});
22
- // Since the math endowment requires crypto, we can leverage the crypto endowment factory to get a hardened and platform agnostic instance of webcrypto
23
- const { crypto: hardenedCrypto } = createCrypto();
24
21
  return harden({
25
22
  Math: {
26
23
  ...math,
27
- random: ()=>{
24
+ random: () => {
28
25
  // NOTE: This is not intended to be a secure replacement for the weak
29
26
  // random number generator used by `Math.random`. It is only intended to
30
27
  // prevent side channel attacks of `Math.random` by replacing it with an
@@ -41,17 +38,14 @@ import { createCrypto } from './crypto';
41
38
  //
42
39
  // - https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey
43
40
  // - https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
44
- return hardenedCrypto.getRandomValues(new Uint32Array(1))[0] / 2 ** 32;
45
- }
46
- }
41
+ return crypto.getRandomValues(new Uint32Array(1))[0] / 2 ** 32;
42
+ },
43
+ },
47
44
  });
48
45
  }
49
46
  const endowmentModule = {
50
- names: [
51
- 'Math'
52
- ],
53
- factory: createMath
47
+ names: ['Math'],
48
+ factory: createMath,
54
49
  };
55
- export default endowmentModule;
56
-
50
+ exports.default = endowmentModule;
57
51
  //# sourceMappingURL=math.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"math.js","sourceRoot":"","sources":["../../../src/common/endowments/math.ts"],"names":[],"mappings":";;AAAA,kDAAkD;AAElD;;;;;;GAMG;AACH,SAAS,UAAU;IACjB,yEAAyE;IACzE,wDAAwD;IACxD,MAAM,IAAI,GAAG,MAAM,CAAC,mBAAmB,CACrC,8BAAe,CAAC,IAAI,CACI,CAAC;IAE3B,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAgB,CAAC,MAAM,EAAE,GAAG,EAAE,EAAE;QACtD,IAAI,GAAG,KAAK,QAAQ,EAAE;YACpB,OAAO,MAAM,CAAC;SACf;QAED,OAAO,EAAE,GAAG,MAAM,EAAE,CAAC,GAAG,CAAC,EAAE,8BAAe,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;IACzD,CAAC,EAAE,EAAE,CAAC,CAAC;IAEP,OAAO,MAAM,CAAC;QACZ,IAAI,EAAE;YACJ,GAAG,IAAI;YACP,MAAM,EAAE,GAAG,EAAE;gBACX,qEAAqE;gBACrE,wEAAwE;gBACxE,wEAAwE;gBACxE,gEAAgE;gBAChE,WAAW;gBACX,EAAE;gBACF,mEAAmE;gBACnE,qEAAqE;gBACrE,0BAA0B;gBAC1B,EAAE;gBACF,sEAAsE;gBACtE,sEAAsE;gBACtE,OAAO;gBACP,EAAE;gBACF,8EAA8E;gBAC9E,4EAA4E;gBAC5E,OAAO,MAAM,CAAC,eAAe,CAAC,IAAI,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC;YACjE,CAAC;SACF;KACF,CAAC,CAAC;AACL,CAAC;AAED,MAAM,eAAe,GAAG;IACtB,KAAK,EAAE,CAAC,MAAM,CAAU;IACxB,OAAO,EAAE,UAAU;CACpB,CAAC;AAEF,kBAAe,eAAe,CAAC","sourcesContent":["import { rootRealmGlobal } from '../globalObject';\n\n/**\n * Create a {@link Math} object, with the same properties as the global\n * {@link Math} object, but with the {@link Math.random} method replaced.\n *\n * @returns The {@link Math} object with the {@link Math.random} method\n * replaced.\n */\nfunction createMath() {\n // `Math` does not work with `Object.keys`, `Object.entries`, etc., so we\n // need to create a new object with the same properties.\n const keys = Object.getOwnPropertyNames(\n rootRealmGlobal.Math,\n ) as (keyof typeof Math)[];\n\n const math = keys.reduce<Partial<Math>>((target, key) => {\n if (key === 'random') {\n return target;\n }\n\n return { ...target, [key]: rootRealmGlobal.Math[key] };\n }, {});\n\n return harden({\n Math: {\n ...math,\n random: () => {\n // NOTE: This is not intended to be a secure replacement for the weak\n // random number generator used by `Math.random`. It is only intended to\n // prevent side channel attacks of `Math.random` by replacing it with an\n // alternative implementation that is not vulnerable to the same\n // attacks.\n //\n // This does not mean that this implementation is secure. It is not\n // intended to be used in a security context, and this implementation\n // may change at any time.\n //\n // To securely generate random numbers, use a cryptographically secure\n // random number generator, such as the one provided by the Web Crypto\n // API:\n //\n // - https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey\n // - https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues\n return crypto.getRandomValues(new Uint32Array(1))[0] / 2 ** 32;\n },\n },\n });\n}\n\nconst endowmentModule = {\n names: ['Math'] as const,\n factory: createMath,\n};\n\nexport default endowmentModule;\n"]}
@@ -0,0 +1,170 @@
1
+ "use strict";
2
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
+ if (kind === "m") throw new TypeError("Private method is not writable");
4
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
+ };
8
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
9
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
10
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
+ };
13
+ var _ResponseWrapper_teardownRef, _ResponseWrapper_ogResponse;
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const utils_1 = require("../utils");
16
+ /**
17
+ * This class wraps a Response object.
18
+ * That way, a teardown process can stop any processes left.
19
+ */
20
+ class ResponseWrapper {
21
+ constructor(ogResponse, teardownRef) {
22
+ _ResponseWrapper_teardownRef.set(this, void 0);
23
+ _ResponseWrapper_ogResponse.set(this, void 0);
24
+ __classPrivateFieldSet(this, _ResponseWrapper_ogResponse, ogResponse, "f");
25
+ __classPrivateFieldSet(this, _ResponseWrapper_teardownRef, teardownRef, "f");
26
+ }
27
+ get body() {
28
+ return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").body;
29
+ }
30
+ get bodyUsed() {
31
+ return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").bodyUsed;
32
+ }
33
+ get headers() {
34
+ return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").headers;
35
+ }
36
+ get ok() {
37
+ return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").ok;
38
+ }
39
+ get redirected() {
40
+ return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").redirected;
41
+ }
42
+ get status() {
43
+ return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").status;
44
+ }
45
+ get statusText() {
46
+ return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").statusText;
47
+ }
48
+ get type() {
49
+ return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").type;
50
+ }
51
+ get url() {
52
+ return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").url;
53
+ }
54
+ async text() {
55
+ return (0, utils_1.withTeardown)(__classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").text(), this);
56
+ }
57
+ async arrayBuffer() {
58
+ return (0, utils_1.withTeardown)(__classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").arrayBuffer(), this);
59
+ }
60
+ async blob() {
61
+ return (0, utils_1.withTeardown)(__classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").blob(), this);
62
+ }
63
+ clone() {
64
+ const newResponse = __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").clone();
65
+ return new ResponseWrapper(newResponse, __classPrivateFieldGet(this, _ResponseWrapper_teardownRef, "f"));
66
+ }
67
+ async formData() {
68
+ return (0, utils_1.withTeardown)(__classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").formData(), this);
69
+ }
70
+ async json() {
71
+ return (0, utils_1.withTeardown)(__classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").json(), this);
72
+ }
73
+ }
74
+ _ResponseWrapper_teardownRef = new WeakMap(), _ResponseWrapper_ogResponse = new WeakMap();
75
+ /**
76
+ * Create a network endowment, consisting of a `fetch` function.
77
+ * This allows us to provide a teardown function, so that we can cancel
78
+ * any pending requests, connections, streams, etc. that may be open when a snap
79
+ * is terminated.
80
+ *
81
+ * This wraps the original implementation of `fetch`,
82
+ * to ensure that a bad actor cannot get access to the original function, thus
83
+ * potentially preventing the network requests from being torn down.
84
+ *
85
+ * @returns An object containing a wrapped `fetch`
86
+ * function, as well as a teardown function.
87
+ */
88
+ const createNetwork = () => {
89
+ // Open fetch calls or open body streams
90
+ const openConnections = new Set();
91
+ // Track last teardown count
92
+ const teardownRef = { lastTeardown: 0 };
93
+ // Remove items from openConnections after they were garbage collected
94
+ const cleanup = new FinalizationRegistry(
95
+ /* istanbul ignore next: can't test garbage collection without modifying node parameters */
96
+ (callback) => callback());
97
+ const _fetch = async (input, init) => {
98
+ const abortController = new AbortController();
99
+ if (init?.signal !== null && init?.signal !== undefined) {
100
+ const originalSignal = init.signal;
101
+ // Merge abort controllers
102
+ originalSignal.addEventListener('abort', () => {
103
+ abortController.abort(originalSignal.reason);
104
+ }, { once: true });
105
+ }
106
+ let res;
107
+ let openFetchConnection;
108
+ try {
109
+ const fetchPromise = fetch(input, {
110
+ ...init,
111
+ signal: abortController.signal,
112
+ });
113
+ openFetchConnection = {
114
+ cancel: async () => {
115
+ abortController.abort();
116
+ try {
117
+ await fetchPromise;
118
+ }
119
+ catch {
120
+ /* do nothing */
121
+ }
122
+ },
123
+ };
124
+ openConnections.add(openFetchConnection);
125
+ res = new ResponseWrapper(await (0, utils_1.withTeardown)(fetchPromise, teardownRef), teardownRef);
126
+ }
127
+ finally {
128
+ if (openFetchConnection !== undefined) {
129
+ openConnections.delete(openFetchConnection);
130
+ }
131
+ }
132
+ if (res.body !== null) {
133
+ const body = new WeakRef(res.body);
134
+ const openBodyConnection = {
135
+ cancel:
136
+ /* istanbul ignore next: see it.todo('can be torn down during body read') test */
137
+ async () => {
138
+ try {
139
+ await body.deref()?.cancel();
140
+ }
141
+ catch {
142
+ /* do nothing */
143
+ }
144
+ },
145
+ };
146
+ openConnections.add(openBodyConnection);
147
+ cleanup.register(res.body,
148
+ /* istanbul ignore next: can't test garbage collection without modifying node parameters */
149
+ () => openConnections.delete(openBodyConnection));
150
+ }
151
+ return harden(res);
152
+ };
153
+ const teardownFunction = async () => {
154
+ teardownRef.lastTeardown += 1;
155
+ const promises = [];
156
+ openConnections.forEach(({ cancel }) => promises.push(cancel()));
157
+ openConnections.clear();
158
+ await Promise.all(promises);
159
+ };
160
+ return {
161
+ fetch: harden(_fetch),
162
+ teardownFunction,
163
+ };
164
+ };
165
+ const endowmentModule = {
166
+ names: ['fetch'],
167
+ factory: createNetwork,
168
+ };
169
+ exports.default = endowmentModule;
170
+ //# sourceMappingURL=network.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"network.js","sourceRoot":"","sources":["../../../src/common/endowments/network.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,oCAAwC;AAExC;;;GAGG;AACH,MAAM,eAAe;IAKnB,YAAY,UAAoB,EAAE,WAAqC;QAJvE,+CAAgD;QAEhD,8CAAsB;QAGpB,uBAAA,IAAI,+BAAe,UAAU,MAAA,CAAC;QAC9B,uBAAA,IAAI,gCAAgB,WAAW,MAAA,CAAC;IAClC,CAAC;IAED,IAAI,IAAI;QACN,OAAO,uBAAA,IAAI,mCAAY,CAAC,IAAI,CAAC;IAC/B,CAAC;IAED,IAAI,QAAQ;QACV,OAAO,uBAAA,IAAI,mCAAY,CAAC,QAAQ,CAAC;IACnC,CAAC;IAED,IAAI,OAAO;QACT,OAAO,uBAAA,IAAI,mCAAY,CAAC,OAAO,CAAC;IAClC,CAA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QACL,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC;QACrB,gBAAgB;KACjB,CAAC;AACJ,CAAC,CAAC;AAEF,MAAM,eAAe,GAAG;IACtB,KAAK,EAAE,CAAC,OAAO,CAAU;IACzB,OAAO,EAAE,aAAa;CACvB,CAAC;AACF,kBAAe,eAAe,CAAC","sourcesContent":["import { withTeardown } from '../utils';\n\n/**\n * This class wraps a Response object.\n * That way, a teardown process can stop any processes left.\n */\nclass ResponseWrapper implements Response {\n readonly #teardownRef: { lastTeardown: number };\n\n #ogResponse: Response;\n\n constructor(ogResponse: Response, teardownRef: { lastTeardown: number }) {\n this.#ogResponse = ogResponse;\n this.#teardownRef = teardownRef;\n }\n\n get body(): ReadableStream<Uint8Array> | null {\n return this.#ogResponse.body;\n }\n\n get bodyUsed() {\n return this.#ogResponse.bodyUsed;\n }\n\n get headers() {\n return this.#ogResponse.headers;\n }\n\n get ok() {\n return this.#ogResponse.ok;\n }\n\n get redirected() {\n return this.#ogResponse.redirected;\n }\n\n get status() {\n return this.#ogResponse.status;\n }\n\n get statusText() {\n return this.#ogResponse.statusText;\n }\n\n get type() {\n return this.#ogResponse.type;\n }\n\n get url() {\n return this.#ogResponse.url;\n }\n\n async text() {\n return withTeardown<string>(this.#ogResponse.text(), this as any);\n }\n\n async arrayBuffer(): Promise<ArrayBuffer> {\n return withTeardown<ArrayBuffer>(\n this.#ogResponse.arrayBuffer(),\n this as any,\n );\n }\n\n async blob(): Promise<Blob> {\n return withTeardown<Blob>(this.#ogResponse.blob(), this as any);\n }\n\n clone(): Response {\n const newResponse = this.#ogResponse.clone();\n return new ResponseWrapper(newResponse, this.#teardownRef);\n }\n\n async formData(): Promise<FormData> {\n return withTeardown<FormData>(this.#ogResponse.formData(), this as any);\n }\n\n async json(): Promise<any> {\n return withTeardown(this.#ogResponse.json(), this as any);\n }\n}\n\n/**\n * Create a network endowment, consisting of a `fetch` function.\n * This allows us to provide a teardown function, so that we can cancel\n * any pending requests, connections, streams, etc. that may be open when a snap\n * is terminated.\n *\n * This wraps the original implementation of `fetch`,\n * to ensure that a bad actor cannot get access to the original function, thus\n * potentially preventing the network requests from being torn down.\n *\n * @returns An object containing a wrapped `fetch`\n * function, as well as a teardown function.\n */\nconst createNetwork = () => {\n // Open fetch calls or open body streams\n const openConnections = new Set<{ cancel: () => Promise<void> }>();\n // Track last teardown count\n const teardownRef = { lastTeardown: 0 };\n\n // Remove items from openConnections after they were garbage collected\n const cleanup = new FinalizationRegistry<() => void>(\n /* istanbul ignore next: can't test garbage collection without modifying node parameters */\n (callback) => callback(),\n );\n\n const _fetch: typeof fetch = async (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n const abortController = new AbortController();\n if (init?.signal !== null && init?.signal !== undefined) {\n const originalSignal = init.signal;\n // Merge abort controllers\n originalSignal.addEventListener(\n 'abort',\n () => {\n abortController.abort((originalSignal as any).reason);\n },\n { once: true },\n );\n }\n\n let res: Response;\n let openFetchConnection: { cancel: () => Promise<void> } | undefined;\n try {\n const fetchPromise = fetch(input, {\n ...init,\n signal: abortController.signal,\n });\n\n openFetchConnection = {\n cancel: async () => {\n abortController.abort();\n try {\n await fetchPromise;\n } catch {\n /* do nothing */\n }\n },\n };\n openConnections.add(openFetchConnection);\n\n res = new ResponseWrapper(\n await withTeardown(fetchPromise, teardownRef),\n teardownRef,\n );\n } finally {\n if (openFetchConnection !== undefined) {\n openConnections.delete(openFetchConnection);\n }\n }\n\n if (res.body !== null) {\n const body = new WeakRef<ReadableStream>(res.body);\n\n const openBodyConnection = {\n cancel:\n /* istanbul ignore next: see it.todo('can be torn down during body read') test */\n async () => {\n try {\n await body.deref()?.cancel();\n } catch {\n /* do nothing */\n }\n },\n };\n openConnections.add(openBodyConnection);\n cleanup.register(\n res.body,\n /* istanbul ignore next: can't test garbage collection without modifying node parameters */\n () => openConnections.delete(openBodyConnection),\n );\n }\n return harden(res);\n };\n\n const teardownFunction = async () => {\n teardownRef.lastTeardown += 1;\n const promises: Promise<void>[] = [];\n openConnections.forEach(({ cancel }) => promises.push(cancel()));\n openConnections.clear();\n await Promise.all(promises);\n };\n\n return {\n fetch: harden(_fetch),\n teardownFunction,\n };\n};\n\nconst endowmentModule = {\n names: ['fetch'] as const,\n factory: createNetwork,\n};\nexport default endowmentModule;\n"]}
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ /**
4
+ * Creates TextDecoder function hardened by SES.
5
+ *
6
+ * @returns An object with the attenuated `TextDecoder` function.
7
+ */
8
+ const createTextDecoder = () => {
9
+ return {
10
+ TextDecoder: harden(TextDecoder),
11
+ };
12
+ };
13
+ const endowmentModule = {
14
+ names: ['TextDecoder'],
15
+ factory: createTextDecoder,
16
+ };
17
+ exports.default = endowmentModule;
18
+ //# sourceMappingURL=textDecoder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"textDecoder.js","sourceRoot":"","sources":["../../../src/common/endowments/textDecoder.ts"],"names":[],"mappings":";;AAAA;;;;GAIG;AACH,MAAM,iBAAiB,GAAG,GAAG,EAAE;IAC7B,OAAO;QACL,WAAW,EAAE,MAAM,CAAC,WAAW,CAAC;KACxB,CAAC;AACb,CAAC,CAAC;AAEF,MAAM,eAAe,GAAG;IACtB,KAAK,EAAE,CAAC,aAAa,CAAU;IAC/B,OAAO,EAAE,iBAAiB;CAC3B,CAAC;AACF,kBAAe,eAAe,CAAC","sourcesContent":["/**\n * Creates TextDecoder function hardened by SES.\n *\n * @returns An object with the attenuated `TextDecoder` function.\n */\nconst createTextDecoder = () => {\n return {\n TextDecoder: harden(TextDecoder),\n } as const;\n};\n\nconst endowmentModule = {\n names: ['TextDecoder'] as const,\n factory: createTextDecoder,\n};\nexport default endowmentModule;\n"]}
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ /**
4
+ * Creates TextEncoder function hardened by SES.
5
+ *
6
+ * @returns An object with the attenuated `TextEncoder` function.
7
+ */
8
+ const createTextEncoder = () => {
9
+ return {
10
+ TextEncoder: harden(TextEncoder),
11
+ };
12
+ };
13
+ const endowmentModule = {
14
+ names: ['TextEncoder'],
15
+ factory: createTextEncoder,
16
+ };
17
+ exports.default = endowmentModule;
18
+ //# sourceMappingURL=textEncoder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"textEncoder.js","sourceRoot":"","sources":["../../../src/common/endowments/textEncoder.ts"],"names":[],"mappings":";;AAAA;;;;GAIG;AACH,MAAM,iBAAiB,GAAG,GAAG,EAAE;IAC7B,OAAO;QACL,WAAW,EAAE,MAAM,CAAC,WAAW,CAAC;KACxB,CAAC;AACb,CAAC,CAAC;AAEF,MAAM,eAAe,GAAG;IACtB,KAAK,EAAE,CAAC,aAAa,CAAU;IAC/B,OAAO,EAAE,iBAAiB;CAC3B,CAAC;AACF,kBAAe,eAAe,CAAC","sourcesContent":["/**\n * Creates TextEncoder function hardened by SES.\n *\n * @returns An object with the attenuated `TextEncoder` function.\n */\nconst createTextEncoder = () => {\n return {\n TextEncoder: harden(TextEncoder),\n } as const;\n};\n\nconst endowmentModule = {\n names: ['TextEncoder'] as const,\n factory: createTextEncoder,\n};\nexport default endowmentModule;\n"]}