diff options
author | Antoine du Hamel <duhamelantoine1995@gmail.com> | 2022-05-02 20:46:13 +0300 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-05-02 20:46:13 +0300 |
commit | 52ba02e874203c1a0d7f97f21e720b88e537731f (patch) | |
tree | e08b0f44165d036d988e4ace647e0976586080f2 /doc | |
parent | 75dbb86c58d6abb1a0b1202381be019d8e8c5792 (diff) |
doc: add section regarding property definition in `primordials.md`
PR-URL: https://github.com/nodejs/node/pull/42921
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Akhil Marsonya <akhil.marsonya27@gmail.com>
Diffstat (limited to 'doc')
-rw-r--r-- | doc/contributing/primordials.md | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/doc/contributing/primordials.md b/doc/contributing/primordials.md index ad996b4de64..a847852ed7f 100644 --- a/doc/contributing/primordials.md +++ b/doc/contributing/primordials.md @@ -594,3 +594,59 @@ ObjectDefineProperties(regex, { }); console.log(RegExpPrototypeSymbolReplace(regex, 'foo', 'a')); // 'faa' ``` + +### Defining object own properties + +When defining property descriptor (to add or update an own property to a +JavaScript object), be sure to always use a null-prototype object to avoid +prototype pollution. + +```js +// User-land +Object.prototype.get = function get() {}; + +// Core +try { + ObjectDefineProperty({}, 'someProperty', { value: 0 }); +} catch (err) { + console.log(err); // TypeError: Invalid property descriptor. +} +``` + +```js +// User-land +Object.prototype.get = function get() {}; + +// Core +ObjectDefineProperty({}, 'someProperty', { __proto__: null, value: 0 }); +console.log('no errors'); // no errors. +``` + +Same applies when trying to modify an existing property, e.g. trying to make a +read-only property enumerable: + +```js +// User-land +Object.prototype.value = 'Unrelated user-provided data'; + +// Core +class SomeClass { + get readOnlyProperty() { return 'genuine data'; } +} +ObjectDefineProperty(SomeClass.prototype, 'readOnlyProperty', { enumerable: true }); +console.log(new SomeClass().readOnlyProperty); // Unrelated user-provided data +``` + +```js +// User-land +Object.prototype.value = 'Unrelated user-provided data'; + +// Core +const kEnumerableProperty = { __proto__: null, enumerable: true }; +// In core, use const {kEnumerableProperty} = require('internal/util'); +class SomeClass { + get readOnlyProperty() { return 'genuine data'; } +} +ObjectDefineProperty(SomeClass.prototype, 'readOnlyProperty', kEnumerableProperty); +console.log(new SomeClass().readOnlyProperty); // genuine data +``` |