@cuxt/sandboxjs 0.1.1 → 0.1.3

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 (226) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +198 -185
  3. package/{build → dist/cjs}/Sandbox.d.ts +15 -6
  4. package/dist/cjs/Sandbox.js +126 -0
  5. package/dist/{SandboxExec.d.ts → cjs/SandboxExec.d.ts} +8 -17
  6. package/dist/cjs/SandboxExec.js +227 -0
  7. package/{build/eval.d.ts → dist/cjs/eval/index.d.ts} +10 -2
  8. package/dist/cjs/eval/index.js +233 -0
  9. package/dist/cjs/executor/executorUtils.d.ts +161 -0
  10. package/dist/cjs/executor/executorUtils.js +930 -0
  11. package/dist/cjs/executor/index.d.ts +1 -0
  12. package/dist/cjs/executor/index.js +2 -0
  13. package/dist/cjs/executor/ops/assignment.d.ts +1 -0
  14. package/dist/cjs/executor/ops/assignment.js +88 -0
  15. package/dist/cjs/executor/ops/call.d.ts +1 -0
  16. package/dist/cjs/executor/ops/call.js +160 -0
  17. package/dist/cjs/executor/ops/comparison.d.ts +1 -0
  18. package/dist/cjs/executor/ops/comparison.js +36 -0
  19. package/dist/cjs/executor/ops/control.d.ts +1 -0
  20. package/dist/cjs/executor/ops/control.js +203 -0
  21. package/dist/cjs/executor/ops/functions.d.ts +1 -0
  22. package/dist/cjs/executor/ops/functions.js +55 -0
  23. package/dist/cjs/executor/ops/index.d.ts +0 -0
  24. package/dist/cjs/executor/ops/index.js +11 -0
  25. package/dist/cjs/executor/ops/literals.d.ts +1 -0
  26. package/dist/cjs/executor/ops/literals.js +45 -0
  27. package/dist/cjs/executor/ops/misc.d.ts +1 -0
  28. package/dist/cjs/executor/ops/misc.js +25 -0
  29. package/dist/cjs/executor/ops/object.d.ts +1 -0
  30. package/dist/cjs/executor/ops/object.js +51 -0
  31. package/dist/cjs/executor/ops/prop.d.ts +1 -0
  32. package/dist/cjs/executor/ops/prop.js +70 -0
  33. package/dist/cjs/executor/ops/unary.d.ts +1 -0
  34. package/dist/cjs/executor/ops/unary.js +48 -0
  35. package/dist/cjs/executor/ops/variables.d.ts +1 -0
  36. package/dist/cjs/executor/ops/variables.js +16 -0
  37. package/dist/cjs/executor/opsRegistry.d.ts +33 -0
  38. package/dist/cjs/executor/opsRegistry.js +8 -0
  39. package/dist/cjs/package.json +3 -0
  40. package/dist/cjs/parser/index.d.ts +3 -0
  41. package/dist/cjs/parser/index.js +1 -0
  42. package/dist/{parser.d.ts → cjs/parser/lisp.d.ts} +29 -42
  43. package/dist/cjs/parser/lispTypes/conditionals.d.ts +2 -0
  44. package/dist/cjs/parser/lispTypes/conditionals.js +135 -0
  45. package/dist/cjs/parser/lispTypes/control.d.ts +2 -0
  46. package/dist/cjs/parser/lispTypes/control.js +204 -0
  47. package/dist/cjs/parser/lispTypes/declarations.d.ts +2 -0
  48. package/dist/cjs/parser/lispTypes/declarations.js +99 -0
  49. package/dist/cjs/parser/lispTypes/index.d.ts +3 -0
  50. package/dist/cjs/parser/lispTypes/index.js +17 -0
  51. package/dist/cjs/parser/lispTypes/operators.d.ts +2 -0
  52. package/dist/cjs/parser/lispTypes/operators.js +252 -0
  53. package/dist/cjs/parser/lispTypes/shared.d.ts +38 -0
  54. package/dist/cjs/parser/lispTypes/structures.d.ts +2 -0
  55. package/dist/cjs/parser/lispTypes/structures.js +188 -0
  56. package/dist/cjs/parser/lispTypes/values.d.ts +2 -0
  57. package/dist/cjs/parser/lispTypes/values.js +89 -0
  58. package/dist/cjs/parser/parserUtils.d.ts +34 -0
  59. package/dist/cjs/parser/parserUtils.js +968 -0
  60. package/dist/cjs/utils/CodeString.d.ts +16 -0
  61. package/dist/cjs/utils/CodeString.js +64 -0
  62. package/dist/cjs/utils/ExecContext.d.ts +34 -0
  63. package/dist/cjs/utils/ExecContext.js +171 -0
  64. package/dist/cjs/utils/Prop.d.ts +16 -0
  65. package/dist/cjs/utils/Prop.js +81 -0
  66. package/dist/cjs/utils/Scope.d.ts +47 -0
  67. package/dist/cjs/utils/Scope.js +127 -0
  68. package/dist/cjs/utils/errors.d.ts +10 -0
  69. package/dist/cjs/utils/errors.js +12 -0
  70. package/dist/cjs/utils/functionReplacements.d.ts +11 -0
  71. package/dist/cjs/utils/functionReplacements.js +362 -0
  72. package/dist/cjs/utils/index.d.ts +7 -0
  73. package/dist/cjs/utils/index.js +7 -0
  74. package/dist/cjs/utils/types.d.ts +221 -0
  75. package/dist/cjs/utils/types.js +164 -0
  76. package/dist/cjs/utils/unraw.js +145 -0
  77. package/dist/{node → esm}/Sandbox.d.ts +15 -6
  78. package/dist/esm/Sandbox.js +115 -0
  79. package/dist/esm/Sandbox.js.map +1 -0
  80. package/{build → dist/esm}/SandboxExec.d.ts +8 -17
  81. package/dist/esm/SandboxExec.js +224 -0
  82. package/dist/esm/SandboxExec.js.map +1 -0
  83. package/dist/{eval.d.ts → esm/eval/index.d.ts} +10 -2
  84. package/dist/esm/eval/index.js +235 -0
  85. package/dist/esm/eval/index.js.map +1 -0
  86. package/dist/esm/executor/executorUtils.d.ts +161 -0
  87. package/dist/esm/executor/executorUtils.js +898 -0
  88. package/dist/esm/executor/executorUtils.js.map +1 -0
  89. package/dist/esm/executor/index.d.ts +1 -0
  90. package/dist/esm/executor/index.js +2 -0
  91. package/dist/esm/executor/ops/assignment.d.ts +1 -0
  92. package/dist/esm/executor/ops/assignment.js +90 -0
  93. package/dist/esm/executor/ops/assignment.js.map +1 -0
  94. package/dist/esm/executor/ops/call.d.ts +1 -0
  95. package/dist/esm/executor/ops/call.js +162 -0
  96. package/dist/esm/executor/ops/call.js.map +1 -0
  97. package/dist/esm/executor/ops/comparison.d.ts +1 -0
  98. package/dist/esm/executor/ops/comparison.js +38 -0
  99. package/dist/esm/executor/ops/comparison.js.map +1 -0
  100. package/dist/esm/executor/ops/control.d.ts +1 -0
  101. package/dist/esm/executor/ops/control.js +205 -0
  102. package/dist/esm/executor/ops/control.js.map +1 -0
  103. package/dist/esm/executor/ops/functions.d.ts +1 -0
  104. package/dist/esm/executor/ops/functions.js +57 -0
  105. package/dist/esm/executor/ops/functions.js.map +1 -0
  106. package/dist/esm/executor/ops/index.d.ts +0 -0
  107. package/dist/esm/executor/ops/index.js +11 -0
  108. package/dist/esm/executor/ops/literals.d.ts +1 -0
  109. package/dist/esm/executor/ops/literals.js +47 -0
  110. package/dist/esm/executor/ops/literals.js.map +1 -0
  111. package/dist/esm/executor/ops/misc.d.ts +1 -0
  112. package/dist/esm/executor/ops/misc.js +27 -0
  113. package/dist/esm/executor/ops/misc.js.map +1 -0
  114. package/dist/esm/executor/ops/object.d.ts +1 -0
  115. package/dist/esm/executor/ops/object.js +53 -0
  116. package/dist/esm/executor/ops/object.js.map +1 -0
  117. package/dist/esm/executor/ops/prop.d.ts +1 -0
  118. package/dist/esm/executor/ops/prop.js +72 -0
  119. package/dist/esm/executor/ops/prop.js.map +1 -0
  120. package/dist/esm/executor/ops/unary.d.ts +1 -0
  121. package/dist/esm/executor/ops/unary.js +50 -0
  122. package/dist/esm/executor/ops/unary.js.map +1 -0
  123. package/dist/esm/executor/ops/variables.d.ts +1 -0
  124. package/dist/esm/executor/ops/variables.js +18 -0
  125. package/dist/esm/executor/ops/variables.js.map +1 -0
  126. package/dist/esm/executor/opsRegistry.d.ts +33 -0
  127. package/dist/esm/executor/opsRegistry.js +9 -0
  128. package/dist/esm/executor/opsRegistry.js.map +1 -0
  129. package/dist/esm/package.json +3 -0
  130. package/dist/esm/parser/index.d.ts +3 -0
  131. package/dist/esm/parser/index.js +1 -0
  132. package/{build/parser.d.ts → dist/esm/parser/lisp.d.ts} +29 -42
  133. package/dist/esm/parser/lispTypes/conditionals.d.ts +2 -0
  134. package/dist/esm/parser/lispTypes/conditionals.js +137 -0
  135. package/dist/esm/parser/lispTypes/conditionals.js.map +1 -0
  136. package/dist/esm/parser/lispTypes/control.d.ts +2 -0
  137. package/dist/esm/parser/lispTypes/control.js +206 -0
  138. package/dist/esm/parser/lispTypes/control.js.map +1 -0
  139. package/dist/esm/parser/lispTypes/declarations.d.ts +2 -0
  140. package/dist/esm/parser/lispTypes/declarations.js +101 -0
  141. package/dist/esm/parser/lispTypes/declarations.js.map +1 -0
  142. package/dist/esm/parser/lispTypes/index.d.ts +3 -0
  143. package/dist/esm/parser/lispTypes/index.js +19 -0
  144. package/dist/esm/parser/lispTypes/index.js.map +1 -0
  145. package/dist/esm/parser/lispTypes/operators.d.ts +2 -0
  146. package/dist/esm/parser/lispTypes/operators.js +254 -0
  147. package/dist/esm/parser/lispTypes/operators.js.map +1 -0
  148. package/dist/esm/parser/lispTypes/shared.d.ts +38 -0
  149. package/dist/esm/parser/lispTypes/structures.d.ts +2 -0
  150. package/dist/esm/parser/lispTypes/structures.js +190 -0
  151. package/dist/esm/parser/lispTypes/structures.js.map +1 -0
  152. package/dist/esm/parser/lispTypes/values.d.ts +2 -0
  153. package/dist/esm/parser/lispTypes/values.js +91 -0
  154. package/dist/esm/parser/lispTypes/values.js.map +1 -0
  155. package/dist/esm/parser/parserUtils.d.ts +34 -0
  156. package/dist/esm/parser/parserUtils.js +959 -0
  157. package/dist/esm/parser/parserUtils.js.map +1 -0
  158. package/dist/esm/utils/CodeString.d.ts +16 -0
  159. package/dist/esm/utils/CodeString.js +66 -0
  160. package/dist/esm/utils/CodeString.js.map +1 -0
  161. package/dist/esm/utils/ExecContext.d.ts +34 -0
  162. package/dist/esm/utils/ExecContext.js +168 -0
  163. package/dist/esm/utils/ExecContext.js.map +1 -0
  164. package/dist/esm/utils/Prop.d.ts +16 -0
  165. package/dist/esm/utils/Prop.js +80 -0
  166. package/dist/esm/utils/Prop.js.map +1 -0
  167. package/dist/esm/utils/Scope.d.ts +47 -0
  168. package/dist/esm/utils/Scope.js +122 -0
  169. package/dist/esm/utils/Scope.js.map +1 -0
  170. package/dist/esm/utils/errors.d.ts +10 -0
  171. package/dist/esm/utils/errors.js +10 -0
  172. package/dist/esm/utils/errors.js.map +1 -0
  173. package/dist/esm/utils/functionReplacements.d.ts +11 -0
  174. package/dist/esm/utils/functionReplacements.js +361 -0
  175. package/dist/esm/utils/functionReplacements.js.map +1 -0
  176. package/dist/esm/utils/index.d.ts +7 -0
  177. package/dist/esm/utils/index.js +7 -0
  178. package/dist/esm/utils/types.d.ts +221 -0
  179. package/dist/esm/utils/types.js +160 -0
  180. package/dist/esm/utils/types.js.map +1 -0
  181. package/dist/esm/utils/unraw.js +147 -0
  182. package/dist/esm/utils/unraw.js.map +1 -0
  183. package/dist/umd/Sandbox.min.js +2 -0
  184. package/dist/umd/Sandbox.min.js.map +1 -0
  185. package/dist/umd/SandboxExec.min.js +2 -0
  186. package/dist/umd/SandboxExec.min.js.map +1 -0
  187. package/package.json +11 -9
  188. package/build/Sandbox.js +0 -62
  189. package/build/SandboxExec.js +0 -214
  190. package/build/eval.js +0 -205
  191. package/build/executor.d.ts +0 -124
  192. package/build/executor.js +0 -1554
  193. package/build/parser.js +0 -1527
  194. package/build/unraw.js +0 -168
  195. package/build/utils.d.ts +0 -264
  196. package/build/utils.js +0 -362
  197. package/dist/Sandbox.d.ts +0 -25
  198. package/dist/Sandbox.js +0 -270
  199. package/dist/Sandbox.js.map +0 -1
  200. package/dist/Sandbox.min.js +0 -2
  201. package/dist/Sandbox.min.js.map +0 -1
  202. package/dist/SandboxExec.js +0 -218
  203. package/dist/SandboxExec.js.map +0 -1
  204. package/dist/SandboxExec.min.js +0 -2
  205. package/dist/SandboxExec.min.js.map +0 -1
  206. package/dist/executor.d.ts +0 -124
  207. package/dist/executor.js +0 -1558
  208. package/dist/executor.js.map +0 -1
  209. package/dist/node/Sandbox.js +0 -277
  210. package/dist/node/SandboxExec.d.ts +0 -66
  211. package/dist/node/SandboxExec.js +0 -225
  212. package/dist/node/eval.d.ts +0 -27
  213. package/dist/node/executor.d.ts +0 -124
  214. package/dist/node/executor.js +0 -1575
  215. package/dist/node/parser.d.ts +0 -154
  216. package/dist/node/parser.js +0 -1704
  217. package/dist/node/utils.d.ts +0 -264
  218. package/dist/node/utils.js +0 -385
  219. package/dist/parser.js +0 -1690
  220. package/dist/parser.js.map +0 -1
  221. package/dist/unraw.d.ts +0 -11
  222. package/dist/utils.d.ts +0 -264
  223. package/dist/utils.js +0 -365
  224. package/dist/utils.js.map +0 -1
  225. /package/{build → dist/cjs/utils}/unraw.d.ts +0 -0
  226. /package/dist/{node → esm/utils}/unraw.d.ts +0 -0
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2019 nyariv
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2019 nyariv
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,186 +1,199 @@
1
- [![GitHub](https://img.shields.io/github/license/nyariv/SandboxJS)](https://github.com/nyariv/SandboxJS/blob/main/LICENSE) ![npm (scoped)](https://img.shields.io/npm/v/@nyariv/sandboxjs) ![Package size gzipped](https://img.shields.io/bundlephobia/minzip/@nyariv/sandboxjs) [![GitHub issues](https://img.shields.io/github/issues-raw/nyariv/SandboxJS)](https://github.com/nyariv/SandboxJS/issues) [![codecov](https://codecov.io/gh/nyariv/SandboxJS/branch/main/graph/badge.svg)](https://codecov.io/gh/nyariv/SandboxJS)
2
-
3
- # SandboxJS - Safe eval runtime
4
-
5
- This is a javascript sandboxing library. When embedding any kind of js code inside your app (either web or nodejs based) you are essentially giving access to the entire kingdom, hoping there is no malicious code in a dependency such as with supply chain attacks. For securing code, sandboxing is needed.
6
-
7
- > a "sandbox" is a security mechanism for separating running programs, usually in an effort to mitigate system failures or software vulnerabilities from spreading. It is often used to execute untested or untrusted programs or code, possibly from unverified or untrusted third parties, suppliers, users or websites, without risking harm to the host machine or operating system. - Wikipedia
8
-
9
- There are many vulnerable modules available on the global scope of a js environment, and unfortunately it is way to easy to get access to that if 3rd party code is allowed to be included. The main way is through the `eval` or `Function` globals because they execute code in the global context. Trying to block access to some global components through proxies or limiting scope variables is fruitless because of one main issue: _every function inherits the `Function` prototype, and can invoke `eval` by calling its constructor_, essentially making `eval` at most two properties away from anything in js.
10
-
11
- Example:
12
- ```javascript
13
- [].filter.constructor("alert('jailbreak')")()
14
- ```
15
-
16
- To make matters worse, it is extremely difficult to blacklist functions because code is easily obfuscated. For example, it is possible to execute anything using only `(`, `)`, `[`, `]`, `!`, and `+`. ([source](http://www.jsfuck.com/))
17
-
18
- ```javascript
19
- [+!+[]]+[] // This evaluates to the number one, go a head type that in console
20
- ```
21
-
22
- **SandboxJS** solves this problem by parsing js code and executing it though its own js runtime, while in the process checking every single prototype function that is being called. This allows whitelisting anything and everything, regardless of obfuscation.
23
-
24
- This means that you can potentially give different libraries different permissions, such as allowing `fetch()` for one library, or allowing access to the `Node` prototype for another, depending what the library requires and nothing more, and any objects that are gotten from the sandbox will remain sandboxed when used outside of it.
25
-
26
- Additionaly, `eval` and `Function` are sandboxed as well, and can be used recursively safely, which is why they are considered safe globals in SandboxJS.
27
-
28
- There is an `audit` method that will return all the accessed functions and prototypes during runtime if you need to know what permissions to give a certain library.
29
-
30
- Since parsing and executing are separated, execution with SandboxJS can be sometimes even faster than `eval`, allowing to prepare the execution code ahead of time.
31
-
32
- ## Installation
33
-
34
- ```
35
- npm install @nyariv/sandboxjs
36
- ```
37
-
38
- ## Usage
39
-
40
- The following is the bare minimum of code for using SandboxJS. This assumes safe whilelisted defaults.
41
-
42
- ```javascript
43
- const code = `return myTest;`;
44
- const scope = { myTest: "hello world" };
45
- const sandbox = new Sandbox();
46
- const exec = sandbox.compile(code);
47
- const result = exec(scope).run(); // result: "hello world"
48
- ```
49
-
50
- It is possible to defined multiple scopes in case you are reusing scopes with multiple layers.
51
-
52
- ```javascript
53
- const sandbox = new Sandbox();
54
-
55
- const scopeA = {a: 1};
56
- const scopeB = {b: 2};
57
- const scopeC = {c: 3};
58
-
59
- const code = `a = 4; let d = 5; let b = 6`;
60
- const exec = sandbox.compile(code);
61
- exec(scopeA, scopeB, scopeC).run();
62
-
63
- console.log(scopeA); // {a: 4}
64
- console.log(scopeB); // {b: 2}
65
- console.log(scopeC); // {c: 3, d: 5, b: 6}
66
- ```
67
-
68
- You can set your own whilelisted prototypes and global properties like so (`alert` and `Node` are added to whitelist in the following code):
69
-
70
- ```javascript
71
- const prototypeWhitelist = Sandbox.SAFE_PROTOTYPES;
72
- prototypeWhitelist.set(Node, new Set());
73
-
74
- const globals = {...Sandbox.SAFE_GLOBALS, alert};
75
-
76
- const sandbox = new Sandbox({globals, prototypeWhitelist});
77
- ```
78
-
79
- You can audit a piece of code, which will permit all globals and prototypes but will return a json with accessed globals and prototypes over time.
80
-
81
- ```javascript
82
- const code = `console.log("test")`;
83
- console.log(Sandbox.audit(code));
84
- ```
85
-
86
- ## Safe Globals
87
-
88
- - `globalThis`
89
- - `Function`
90
- - `eval`
91
- - `setTimeout` - excluded by default
92
- - `setInterval` - excluded by default
93
- - `clearTimeout` - excluded by default
94
- - `clearInterval` - excluded by default
95
- - `console`
96
- - `isFinite`
97
- - `isNaN`
98
- - `parseFloat`
99
- - `parseInt`
100
- - `decodeURI`
101
- - `decodeURIComponent`
102
- - `encodeURI`
103
- - `encodeURIComponent`
104
- - `escape`
105
- - `unescape`
106
- - `Boolean`
107
- - `Number`
108
- - `BigInt`
109
- - `String`
110
- - `Object`
111
- - `Array`
112
- - `Symbol`
113
- - `Error`
114
- - `EvalError`
115
- - `RangeError`
116
- - `ReferenceError`
117
- - `SyntaxError`
118
- - `TypeError`
119
- - `URIError`
120
- - `Int8Array`
121
- - `Uint8Array`
122
- - `Uint8ClampedArray`
123
- - `Int16Array`
124
- - `Uint16Array`
125
- - `Int32Array`
126
- - `Uint32Array`
127
- - `Float32Array`
128
- - `Float64Array`
129
- - `Map`
130
- - `Set`
131
- - `WeakMap`
132
- - `WeakSet`
133
- - `Promise`
134
- - `Intl`
135
- - `JSON`
136
- - `Math`
137
-
138
- # Safe Prototypes
139
-
140
- - `SandboxGlobal`
141
- - `Function`
142
- - `Boolean`
143
- - `Object`
144
- - `Number`
145
- - `BigInt`
146
- - `String`
147
- - `Date`
148
- - `RegExp`
149
- - `Error`
150
- - `Array`
151
- - `Int8Array`
152
- - `Uint8Array`
153
- - `Uint8ClampedArray`
154
- - `Int16Array`
155
- - `Uint16Array`
156
- - `Int32Array`
157
- - `Uint32Array`
158
- - `Float32Array`
159
- - `Float64Array`
160
- - `Map`
161
- - `Set`
162
- - `WeakMap`
163
- - `WeakSet`
164
- - `Promise`
165
-
166
- ## Goals
167
-
168
- |Feature|Status|
169
- |---|---|
170
- |Prototype access protection|done|
171
- |Globals access protection|done|
172
- |Prototype proxying|done|
173
- |Single line sandboxing|done|
174
- |Multi line sandboxing|done|
175
- |Functions support|done|
176
- |Audit prototype and globals access|done|
177
- |Code blocks (try/catch, ifs, and loops)|done|
178
- |Async/await|done|
179
- |Execution time protection|done|
180
- |Extensibility|done|
181
- |Full ECMAScript support|90%|
182
- |Script source and import sandboxing|Won't fix - handled by 3rd party|
183
- |DOM ownership and inherited permissions|See [scope-js](https://github.com/nyariv/scope-js)|
184
- |Tests|done|
185
-
1
+ [![GitHub](https://img.shields.io/github/license/nyariv/SandboxJS)](https://github.com/nyariv/SandboxJS/blob/main/LICENSE) ![npm](https://img.shields.io/npm/v/@nyariv/sandboxjs) ![Bundle size](https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/nyariv/dd4a46f4c2fff1c43d4f2e8fb4b52862/raw/bundle-size.json)
2
+ [![GitHub issues](https://img.shields.io/github/issues-raw/nyariv/SandboxJS)](https://github.com/nyariv/SandboxJS/issues) [![codecov](https://codecov.io/gh/nyariv/SandboxJS/branch/main/graph/badge.svg)](https://codecov.io/gh/nyariv/SandboxJS) [![passing tests](https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/nyariv/dd4a46f4c2fff1c43d4f2e8fb4b52862/raw/tests.json)](https://nyariv.github.io/SandboxJS/) [![Sandbox protected](https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/nyariv/dd4a46f4c2fff1c43d4f2e8fb4b52862/raw/sandbox-protected.json)](https://github.com/nyariv/SandboxJS)
3
+ ---
4
+ <table><tr><td width="100">
5
+
6
+ ![sanboxjs logo](./logo.svg)
7
+
8
+ </td><td width="400">
9
+ <h1>SandboxJS</h1>
10
+ <i>Safe eval runtime</i>
11
+ </td></tr></table>
12
+
13
+ ---
14
+
15
+
16
+
17
+
18
+ This is a javascript sandboxing library. When embedding any kind of js code inside your app (either web or nodejs based) you are essentially giving access to the entire kingdom, hoping there is no malicious code in a dependency such as with supply chain attacks. For securing code, sandboxing is needed.
19
+
20
+ > a "sandbox" is a security mechanism for separating running programs, usually in an effort to mitigate system failures or software vulnerabilities from spreading. It is often used to execute untested or untrusted programs or code, possibly from unverified or untrusted third parties, suppliers, users or websites, without risking harm to the host machine or operating system. - Wikipedia
21
+
22
+ There are many vulnerable modules available on the global scope of a js environment, and unfortunately it is way to easy to get access to that if 3rd party code is allowed to be included. The main way is through the `eval` or `Function` globals because they execute code in the global context. Trying to block access to some global components through proxies or limiting scope variables is fruitless because of one main issue: _every function inherits the `Function` prototype, and can invoke `eval` by calling its constructor_, essentially making `eval` at most two properties away from anything in js.
23
+
24
+ Example:
25
+ ```javascript
26
+ [].filter.constructor("alert('jailbreak')")()
27
+ ```
28
+
29
+ To make matters worse, it is extremely difficult to blacklist functions because code is easily obfuscated. For example, it is possible to execute anything using only `(`, `)`, `[`, `]`, `!`, and `+`. ([source](http://www.jsfuck.com/))
30
+
31
+ ```javascript
32
+ [+!+[]]+[] // This evaluates to the number one, go a head type that in console
33
+ ```
34
+
35
+ **SandboxJS** solves this problem by parsing js code and executing it though its own js runtime, while in the process checking every single prototype function that is being called. This allows whitelisting anything and everything, regardless of obfuscation.
36
+
37
+ This means that you can potentially give different libraries different permissions, such as allowing `fetch()` for one library, or allowing access to the `Node` prototype for another, depending what the library requires and nothing more, and any objects that are gotten from the sandbox will remain sandboxed when used outside of it.
38
+
39
+ Additionaly, `eval` and `Function` are sandboxed as well, and can be used recursively safely, which is why they are considered safe globals in SandboxJS.
40
+
41
+ There is an `audit` method that will return all the accessed functions and prototypes during runtime if you need to know what permissions to give a certain library.
42
+
43
+ Since parsing and executing are separated, execution with SandboxJS can be sometimes even faster than `eval`, allowing to prepare the execution code ahead of time.
44
+
45
+ ## Installation
46
+
47
+ ```
48
+ npm install @nyariv/sandboxjs
49
+ ```
50
+
51
+ ## Usage
52
+
53
+ The following is the bare minimum of code for using SandboxJS. This assumes safe whitelisted defaults.
54
+
55
+ ```javascript
56
+ const code = `return myTest;`;
57
+ const scope = { myTest: "hello world" };
58
+ const sandbox = new Sandbox();
59
+ const exec = sandbox.compile(code);
60
+ const result = exec(scope).run(); // result: "hello world"
61
+ ```
62
+
63
+ It is possible to defined multiple scopes in case you are reusing scopes with multiple layers.
64
+
65
+ ```javascript
66
+ const sandbox = new Sandbox();
67
+
68
+ const scopeA = {a: 1};
69
+ const scopeB = {b: 2};
70
+ const scopeC = {c: 3};
71
+
72
+ const code = `a = 4; let d = 5; let b = 6`;
73
+ const exec = sandbox.compile(code);
74
+ exec(scopeA, scopeB, scopeC).run();
75
+
76
+ console.log(scopeA); // {a: 4}
77
+ console.log(scopeB); // {b: 2}
78
+ console.log(scopeC); // {c: 3, d: 5, b: 6}
79
+ ```
80
+
81
+ You can set your own whilelisted prototypes and global properties like so (`alert` and `Node` are added to whitelist in the following code):
82
+
83
+ ```javascript
84
+ const prototypeWhitelist = Sandbox.SAFE_PROTOTYPES;
85
+ prototypeWhitelist.set(Node, new Set());
86
+
87
+ const globals = {...Sandbox.SAFE_GLOBALS, alert};
88
+
89
+ const sandbox = new Sandbox({globals, prototypeWhitelist});
90
+ ```
91
+
92
+ You can audit a piece of code, which will permit all globals and prototypes but will return a json with accessed globals and prototypes over time.
93
+
94
+ ```javascript
95
+ const code = `console.log("test")`;
96
+ console.log(Sandbox.audit(code));
97
+ ```
98
+
99
+ ## Safe Globals
100
+
101
+ - `globalThis`
102
+ - `Function`
103
+ - `eval`
104
+ - `setTimeout` - excluded by default
105
+ - `setInterval` - excluded by default
106
+ - `clearTimeout` - excluded by default
107
+ - `clearInterval` - excluded by default
108
+ - `console`
109
+ - `isFinite`
110
+ - `isNaN`
111
+ - `parseFloat`
112
+ - `parseInt`
113
+ - `decodeURI`
114
+ - `decodeURIComponent`
115
+ - `encodeURI`
116
+ - `encodeURIComponent`
117
+ - `escape`
118
+ - `unescape`
119
+ - `Boolean`
120
+ - `Number`
121
+ - `BigInt`
122
+ - `String`
123
+ - `Object`
124
+ - `Array`
125
+ - `Symbol`
126
+ - `Error`
127
+ - `EvalError`
128
+ - `RangeError`
129
+ - `ReferenceError`
130
+ - `SyntaxError`
131
+ - `TypeError`
132
+ - `URIError`
133
+ - `Int8Array`
134
+ - `Uint8Array`
135
+ - `Uint8ClampedArray`
136
+ - `Int16Array`
137
+ - `Uint16Array`
138
+ - `Int32Array`
139
+ - `Uint32Array`
140
+ - `Float32Array`
141
+ - `Float64Array`
142
+ - `Map`
143
+ - `Set`
144
+ - `WeakMap`
145
+ - `WeakSet`
146
+ - `Promise`
147
+ - `Intl`
148
+ - `JSON`
149
+ - `Math`
150
+
151
+ # Safe Prototypes
152
+
153
+ - `SandboxGlobal`
154
+ - `Function`
155
+ - `Boolean`
156
+ - `Object`
157
+ - `Number`
158
+ - `BigInt`
159
+ - `String`
160
+ - `Date`
161
+ - `RegExp`
162
+ - `Error`
163
+ - `Array`
164
+ - `Int8Array`
165
+ - `Uint8Array`
166
+ - `Uint8ClampedArray`
167
+ - `Int16Array`
168
+ - `Uint16Array`
169
+ - `Int32Array`
170
+ - `Uint32Array`
171
+ - `Float32Array`
172
+ - `Float64Array`
173
+ - `Map`
174
+ - `Set`
175
+ - `WeakMap`
176
+ - `WeakSet`
177
+ - `Promise`
178
+
179
+ ## Goals
180
+
181
+ |Feature|Status|
182
+ |---|---|
183
+ |Prototype access protection|done|
184
+ |Globals access protection|done|
185
+ |Prototype proxying|done|
186
+ |Single line sandboxing|done|
187
+ |Multi line sandboxing|done|
188
+ |Functions support|done|
189
+ |Audit prototype and globals access|done|
190
+ |Code blocks (try/catch, ifs, and loops)|done|
191
+ |Async/await|done|
192
+ |Execution time protection|done|
193
+ |Extensibility|done|
194
+ |Full ECMAScript support|90%|
195
+ |Script source and import sandboxing|Won't fix - handled by 3rd party|
196
+ |DOM ownership and inherited permissions|See [scope-js](https://github.com/nyariv/scope-js)|
197
+ |Tests|done|
198
+
186
199
  📋 **[ECMAScript Feature Implementation Status](TODO.md)** - See which JavaScript features are supported and tested (~90% of core ES5-ES2018 features)
@@ -1,11 +1,19 @@
1
- import { IExecContext, IOptionParams, IScope } from './utils.js';
2
- import { ExecReturn } from './executor.js';
3
- import SandboxExec from './SandboxExec.js';
4
- export { LocalScope, SandboxExecutionTreeError, SandboxCapabilityError, SandboxAccessError, SandboxError, } from './utils.js';
5
- export default class Sandbox extends SandboxExec {
1
+ import { IExecContext, IOptionParams, IScope } from './utils';
2
+ import { ExecReturn } from './executor';
3
+ import { default as SandboxExec } from './SandboxExec';
4
+ export { ParseError } from './parser';
5
+ export { LocalScope, SandboxExecutionTreeError, SandboxCapabilityError, SandboxAccessError, SandboxExecutionQuotaExceededError, SandboxError, delaySynchronousResult, } from './utils';
6
+ export type * from './utils';
7
+ export type * from './parser';
8
+ export type * from './executor';
9
+ export type * from './eval';
10
+ export declare class Sandbox extends SandboxExec {
6
11
  constructor(options?: IOptionParams);
7
12
  static audit<T>(code: string, scopes?: IScope[]): ExecReturn<T>;
8
- static parse(code: string): import("./parser.js").IExecutionTree;
13
+ static parse(code: string): import('./parser').IExecutionTree;
14
+ get Function(): Function;
15
+ get AsyncFunction(): Function;
16
+ get eval(): Function;
9
17
  compile<T>(code: string, optimize?: boolean): (...scopes: IScope[]) => {
10
18
  context: IExecContext;
11
19
  run: () => T;
@@ -23,3 +31,4 @@ export default class Sandbox extends SandboxExec {
23
31
  run: () => Promise<T>;
24
32
  };
25
33
  }
34
+ export default Sandbox;
@@ -0,0 +1,126 @@
1
+ Object.defineProperties(exports, {
2
+ __esModule: { value: true },
3
+ [Symbol.toStringTag]: { value: "Module" }
4
+ });
5
+ const require_errors = require("./utils/errors.js");
6
+ const require_types = require("./utils/types.js");
7
+ const require_Scope = require("./utils/Scope.js");
8
+ const require_ExecContext = require("./utils/ExecContext.js");
9
+ require("./utils/index.js");
10
+ const require_parserUtils = require("./parser/parserUtils.js");
11
+ require("./parser/index.js");
12
+ const require_index$2 = require("./eval/index.js");
13
+ const require_SandboxExec = require("./SandboxExec.js");
14
+ //#region src/Sandbox.ts
15
+ var Sandbox = class extends require_SandboxExec.SandboxExec {
16
+ constructor(options) {
17
+ super(options, require_index$2.createEvalContext());
18
+ }
19
+ static audit(code, scopes = []) {
20
+ const globals = {};
21
+ for (const i of Object.getOwnPropertyNames(globalThis)) globals[i] = globalThis[i];
22
+ const sandbox = new require_SandboxExec.SandboxExec({
23
+ globals,
24
+ audit: true
25
+ });
26
+ return sandbox.executeTree(require_ExecContext.createExecContext(sandbox, require_parserUtils.default(code, true, false, sandbox.context.options.maxParserRecursionDepth), require_index$2.createEvalContext()), scopes);
27
+ }
28
+ static parse(code) {
29
+ return require_parserUtils.default(code, true);
30
+ }
31
+ get Function() {
32
+ return require_ExecContext.createExecContext(this, {
33
+ tree: [],
34
+ constants: {
35
+ strings: [],
36
+ eager: true,
37
+ literals: [],
38
+ maxDepth: this.context.options.maxParserRecursionDepth,
39
+ regexes: []
40
+ }
41
+ }, this.evalContext).evals.get(Function);
42
+ }
43
+ get AsyncFunction() {
44
+ return require_ExecContext.createExecContext(this, {
45
+ tree: [],
46
+ constants: {
47
+ strings: [],
48
+ eager: true,
49
+ literals: [],
50
+ maxDepth: this.context.options.maxParserRecursionDepth,
51
+ regexes: []
52
+ }
53
+ }, this.evalContext).evals.get(require_types.AsyncFunction);
54
+ }
55
+ get eval() {
56
+ return require_ExecContext.createExecContext(this, {
57
+ tree: [],
58
+ constants: {
59
+ strings: [],
60
+ eager: true,
61
+ literals: [],
62
+ maxDepth: this.context.options.maxParserRecursionDepth,
63
+ regexes: []
64
+ }
65
+ }, this.evalContext).evals.get(eval);
66
+ }
67
+ compile(code, optimize = false) {
68
+ if (this.context.options.nonBlocking) throw new require_errors.SandboxCapabilityError("Non-blocking mode is enabled, use Sandbox.compileAsync() instead.");
69
+ const parsed = require_parserUtils.default(code, optimize, false, this.context.options.maxParserRecursionDepth);
70
+ const context = require_ExecContext.createExecContext(this, parsed, this.evalContext);
71
+ const exec = (...scopes) => {
72
+ require_Scope.sanitizeScopes(scopes, context);
73
+ return {
74
+ context,
75
+ run: () => this.executeTree(context, [...scopes]).result
76
+ };
77
+ };
78
+ return exec;
79
+ }
80
+ compileAsync(code, optimize = false) {
81
+ const parsed = require_parserUtils.default(code, optimize, false, this.context.options.maxParserRecursionDepth);
82
+ const context = require_ExecContext.createExecContext(this, parsed, this.evalContext);
83
+ const exec = (...scopes) => {
84
+ require_Scope.sanitizeScopes(scopes, context);
85
+ return {
86
+ context,
87
+ run: () => this.executeTreeAsync(context, [...scopes]).then((ret) => ret.result)
88
+ };
89
+ };
90
+ return exec;
91
+ }
92
+ compileExpression(code, optimize = false) {
93
+ const parsed = require_parserUtils.default(code, optimize, true, this.context.options.maxParserRecursionDepth);
94
+ const context = require_ExecContext.createExecContext(this, parsed, this.evalContext);
95
+ const exec = (...scopes) => {
96
+ require_Scope.sanitizeScopes(scopes, context);
97
+ return {
98
+ context,
99
+ run: () => this.executeTree(context, [...scopes]).result
100
+ };
101
+ };
102
+ return exec;
103
+ }
104
+ compileExpressionAsync(code, optimize = false) {
105
+ const parsed = require_parserUtils.default(code, optimize, true, this.context.options.maxParserRecursionDepth);
106
+ const context = require_ExecContext.createExecContext(this, parsed, this.evalContext);
107
+ const exec = (...scopes) => {
108
+ return {
109
+ context,
110
+ run: () => this.executeTreeAsync(context, [...scopes]).then((ret) => ret.result)
111
+ };
112
+ };
113
+ return exec;
114
+ }
115
+ };
116
+ //#endregion
117
+ exports.LocalScope = require_Scope.LocalScope;
118
+ exports.ParseError = require_parserUtils.ParseError;
119
+ exports.Sandbox = Sandbox;
120
+ exports.default = Sandbox;
121
+ exports.SandboxAccessError = require_errors.SandboxAccessError;
122
+ exports.SandboxCapabilityError = require_errors.SandboxCapabilityError;
123
+ exports.SandboxError = require_errors.SandboxError;
124
+ exports.SandboxExecutionQuotaExceededError = require_errors.SandboxExecutionQuotaExceededError;
125
+ exports.SandboxExecutionTreeError = require_errors.SandboxExecutionTreeError;
126
+ exports.delaySynchronousResult = require_Scope.delaySynchronousResult;
@@ -1,8 +1,7 @@
1
- import { IEvalContext } from './eval.js';
2
- import { Change, ExecReturn } from './executor.js';
3
- import { IContext, IExecContext, IGlobals, IOptionParams, IScope, Scope, SubscriptionSubject, Ticks } from './utils.js';
4
- export { IOptions, IContext, IExecContext, LocalScope, SandboxExecutionTreeError, SandboxCapabilityError, SandboxAccessError, SandboxError, } from './utils.js';
5
- export default class SandboxExec {
1
+ import { IEvalContext } from './eval';
2
+ import { Change, ExecReturn } from './executor';
3
+ import { IContext, IExecContext, IGlobals, IOptionParams, IScope, ISymbolWhitelist, SubscriptionSubject, HaltContext } from './utils';
4
+ export declare class SandboxExec {
6
5
  evalContext?: IEvalContext | undefined;
7
6
  readonly context: IContext;
8
7
  readonly setSubscriptions: WeakMap<SubscriptionSubject, Map<string, Set<(modification: Change) => void>>>;
@@ -32,6 +31,7 @@ export default class SandboxExec {
32
31
  }>;
33
32
  constructor(options?: IOptionParams, evalContext?: IEvalContext | undefined);
34
33
  static get SAFE_GLOBALS(): IGlobals;
34
+ static get SAFE_SYMBOLS(): ISymbolWhitelist;
35
35
  static get SAFE_PROTOTYPES(): Map<any, Set<string>>;
36
36
  subscribeGet(callback: (obj: SubscriptionSubject, name: string) => void, context: IExecContext): {
37
37
  unsubscribe: () => void;
@@ -42,25 +42,16 @@ export default class SandboxExec {
42
42
  subscribeSetGlobal(obj: SubscriptionSubject, name: string, callback: (modification: Change) => void): {
43
43
  unsubscribe: () => void;
44
44
  };
45
- subscribeHalt(cb: (args?: {
46
- error: Error;
47
- ticks: Ticks;
48
- scope: Scope;
49
- context: IExecContext;
50
- }) => void): {
45
+ subscribeHalt(cb: (context: HaltContext) => void): {
51
46
  unsubscribe: () => void;
52
47
  };
53
48
  subscribeResume(cb: () => void): {
54
49
  unsubscribe: () => void;
55
50
  };
56
- haltExecution(haltContext?: {
57
- error: Error;
58
- ticks: Ticks;
59
- scope: Scope;
60
- context: IExecContext;
61
- }): void;
51
+ haltExecution(haltContext?: HaltContext): void;
62
52
  resumeExecution(): void;
63
53
  getContext(fn: (...args: any[]) => any): IExecContext | undefined;
64
54
  executeTree<T>(context: IExecContext, scopes?: IScope[]): ExecReturn<T>;
65
55
  executeTreeAsync<T>(context: IExecContext, scopes?: IScope[]): Promise<ExecReturn<T>>;
66
56
  }
57
+ export default SandboxExec;