GithubHelp home page GithubHelp logo

dimfeld / devalue Goto Github PK

View Code? Open in Web Editor NEW

This project forked from rich-harris/devalue

0.0 1.0 0.0 121 KB

Gets the job done when JSON.stringify can't

Home Page: https://npm.runkit.com/devalue

License: MIT License

JavaScript 100.00%

devalue's Introduction

devalue

This fork is the devalue package built as an IIFE for use inside Ergo.

Like JSON.stringify, but handles

  • cyclical references (obj.self = obj)
  • repeated references ([value, value])
  • undefined, Infinity, NaN, -0
  • regular expressions
  • dates
  • Map and Set
  • BigInt

Try it out here.

Goals:

Non-goals:

  • Human-readable output
  • Stringifying functions or non-POJOs

Usage

There are two ways to use devalue:

uneval

This function takes a JavaScript value and returns the JavaScript code to create an equivalent value — sort of like eval in reverse:

import * as devalue from 'devalue';

let obj = { message: 'hello' };
devalue.uneval(obj); // '{message:"hello"}'

obj.self = obj;
devalue.uneval(obj); // '(function(a){a.message="hello";a.self=a;return a}({}))'

Use uneval when you want the most compact possible output and don't want to include any code for parsing the serialized value.

stringify and parse

These two functions are analogous to JSON.stringify and JSON.parse:

import * as devalue from 'devalue';

let obj = { message: 'hello' };

let stringified = devalue.stringify(obj); // '[{"message":1},"hello"]'
devalue.parse(stringified); // { message: 'hello' }

obj.self = obj;

stringified = devalue.stringify(obj); // '[{"message":1,"self":0},"hello"]'
devalue.parse(stringified); // { message: 'hello', self: [Circular] }

Use stringify and parse when evaluating JavaScript isn't an option.

unflatten

In the case where devalued data is one part of a larger JSON string, unflatten allows you to revive just the bit you need:

import * as devalue from 'devalue';

const json = `{
  "type": "data",
  "data": ${devalue.stringify(data)}
}`;

const data = devalue.unflatten(JSON.parse(json).data);

Error handling

If uneval or stringify encounters a function or a non-POJO, it will throw an error. You can find where in the input data the offending value lives by inspecting error.path:

try {
	const map = new Map();
	map.set('key', function invalid() {});

	uneval({
		object: {
			array: [map]
		}
	});
} catch (e) {
	console.log(e.path); // '.object.array[0].get("key")'
}

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:

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:

<script>
	// NEVER DO THIS
	var preloaded = {"userinput":"
</script>
<script src="https://evil.com/mwahaha.js">
	"};
</script>

Using uneval or stringify, we're protected against that attack:

const template = `
<script>
  var preloaded = ${uneval(state)};
</script>`;
<script>
	var preloaded = {
		userinput:
			"\\u003C\\u002Fscript\\u003E\\u003Cscript src='https:\\u002F\\u002Fevil.com\\u002Fmwahaha.js'\\u003E"
	};
</script>

This, along with the fact that uneval and stringify bail on functions and non-POJOs, stops attackers from executing arbitrary code. Strings generated by uneval can be safely deserialized with eval or new Function:

const value = (0, eval)('(' + str + ')');

Other security considerations

While uneval 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 uneval 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:

{
	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

License

MIT

devalue's People

Contributors

conduitry avatar danielruf avatar dimfeld avatar haines avatar knorpelsenf avatar rich-harris avatar skaji avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.