Make ip work when the Object prototype is frozen #129
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Background
Note: examples use the Node.js REPL with strict mode:
node --use_strict
.Inheritance and Shadowing
Objects in JavaScript inherit properties from their prototype chain. For example, the "toString" property can be accessed on all objects, but it doesn't actually exist on each object, it exists on the global Object prototype:
Under normal circumstances, you can assign a property to an object using the
=
operator, and any property of the same name in the object's prototype chain will not be modified, but will be "shadowed" by the new property:Prototype Pollution
From Snyk:
There are a few different ways to mitigate Prototype Pollution, and one way to do it across the board is to freeze the global "root" objects and their prototypes (Object, Function, Array, etc.)
From MDN:
This means that any attempt to change the Object prototype will fail. If using strict mode, it will throw an error; otherwise, it will be silently ignored.
If the Object prototype becomes frozen, all of its properties are no longer writable or configurable:
This also prevents shadowing properties with assignment. If an object doesn't already have a property defined (such as "toString"), and it inherits a non-writable property of that name from its prototype chain, any attempt to assign the property on that object will fail:
This behavior is described in the ECMAScript 2016 specification:
The Problem
Unfortunately, this package uses assignment to shadow the "toString" function for the ip module:
node-ip/lib/ip.js
Line 61 in 4b2f4e7
This means that projects cannot use this package if they have frozen the global Object prototype.
The Solution
You can still shadow non-writable prototype properties by explicitly defining a new data property on the object:
The ip module can be changed to use this method of shadowing so it is compatible with this approach of mitigating Prototype Pollution 🎉