Skip to content
Browse files

policy: add dependencies map for resources

Adds a "dependencies" field to resources in policy manifest files.
In order to ease development and testing while using manifests,
wildcard values for both "dependencies" and "integrity" have been
added using the boolean value "true" in the policy manifest.

PR-URL: #28767
Reviewed-By: Matteo Collina <>
Reviewed-By: Jan Krems <>
Reviewed-By: Colin Ihrig <>
Reviewed-By: Rich Trott <>
  • Loading branch information...
bmeck authored and targos committed Jul 18, 2019
1 parent 3a62202 commit 5d5c89a8f7ea7e0bbe69ccbe3bd052ca562e61dd
@@ -1430,6 +1430,13 @@ An attempt was made to load a resource, but the resource did not match the
integrity defined by the policy manifest. See the documentation for [policy]
manifests for more information.


An attempt was made to load a resource, but the resource was not listed as a
dependency from the location that attempted to load it. See the documentation
for [policy] manifests for more information.


@@ -1438,6 +1445,13 @@ entries for a resource which did not match each other. Update the manifest
entries to match in order to resolve this error. See the documentation for
[policy] manifests for more information.


A policy manifest resource had an invalid value for one of its fields. Update
the manifest entry to match in order to resolve this error. See the
documentation for [policy] manifests for more information.


@@ -38,7 +38,7 @@ node --experimental-policy=policy.json app.js
The policy manifest will be used to enforce constraints on code loaded by

In order to mitigate tampering with policy files on disk, an integrity for
To mitigate tampering with policy files on disk, an integrity for
the policy file itself may be provided via `--policy-integrity`.
This allows running `node` and asserting the policy file contents
even if the file is changed on disk.
@@ -105,9 +105,83 @@ When loading resources the entire URL must match including search parameters
and hash fragment. `./a.js?b` will not be used when attempting to load
`./a.js` and vice versa.

In order to generate integrity strings, a script such as
To generate integrity strings, a script such as
`printf "sha384-$(cat checked.js | openssl dgst -sha384 -binary | base64)"`
can be used.

Integrity can be specified as the boolean value `true` to accept any
body for the resource which can be useful for local development. It is not
recommended in production since it would allow unexpected alteration of
resources to be considered valid.

### Dependency Redirection

An application may need to ship patched versions of modules or to prevent
modules from allowing all modules access to all other modules. Redirection
can be used by intercepting attempts to load the modules wishing to be

"builtins": [],
"resources": {
"./app/checked.js": {
"dependencies": {
"fs": true,
"os": "./app/node_modules/alt-os"

The dependencies are keyed by the requested string specifier and have values
of either `true` or a string pointing to a module that will be resolved.

The specifier string does not perform any searching and must match exactly
what is provided to the `require()`. Therefore, multiple specifiers may be
needed in the policy if `require()` uses multiple different strings to point
to the same module (such as excluding the extension).

If the value of the redirection is `true` the default searching algorithms will
be used to find the module.

If the value of the redirection is a string, it will be resolved relative to
the manifest and then immediately be used without searching.

Any specifier string that is `require()`ed and not listed in the dependencies
will result in an error according to the policy.

Redirection will not prevent access to APIs through means such as direct access
to `require.cache` and/or through `module.constructor` which allow access to
loading modules. Policy redirection only affect specifiers to `require()`.
Other means such as to prevent undesired access to APIs through variables are
necessary to lock down that path of loading modules.

A boolean value of `true` for the dependencies map can be specified to allow a
module to load any specifier without redirection. This can be useful for local
development and may have some valid usage in production, but should be used
only with care after auditing a module to ensure its behavior is valid.

#### Example: Patched Dependency

Since a dependency can be redirected, you can provide attenuated or modified
forms of dependencies as fits your application. For example, you could log
data about timing of function durations by wrapping the original:

const original = require('fn');
module.exports = function fn(...args) {
try {
return ?
Reflect.construct(original, args) :
Reflect.apply(original, this, args);
} finally {

[relative url string]:
@@ -1028,9 +1028,15 @@ E('ERR_MANIFEST_ASSERT_INTEGRITY',
return msg;
}, Error);
'Manifest resource %s does not list %s as a dependency specifier',
'Manifest resource %s has multiple entries but integrity lists do not match',
'Manifest resource %s has invalid property value for %s',
E('ERR_MANIFEST_TDZ', 'Manifest initialization has not yet run', Error);
'Manifest specified unknown error behavior "%s".',
@@ -1,19 +1,72 @@
'use strict';

const { Object } = primordials;
const {
} = require('internal/errors').codes;
const { NativeModule } = require('internal/bootstrap/loaders');
const { getOptionValue } = require('internal/options');
const experimentalModules = getOptionValue('--experimental-modules');

const { validateString } = require('internal/validators');
const path = require('path');
const { pathToFileURL } = require('internal/url');
const { pathToFileURL, fileURLToPath } = require('internal/url');
const { URL } = require('url');

const debug = require('internal/util/debuglog').debuglog('module');

function loadNativeModule(filename, request, experimentalModules) {
const mod =;
if (mod) {
debug('load native module %s', request);
return mod;

// Invoke with makeRequireFunction(module) where |module| is the Module object
// to use as the context for the require() function.
function makeRequireFunction(mod) {
// Use redirects to set up a mapping from a policy and restrict dependencies
function makeRequireFunction(mod, redirects) {
const Module = mod.constructor;

function require(path) {
return mod.require(path);
let require;
if (redirects) {
const { map, reaction } = redirects;
const id = mod.filename ||;
require = function require(path) {
let missing = true;
if (map === true) {
missing = false;
} else if (map.has(path)) {
const redirect = map.get(path);
if (redirect === true) {
missing = false;
} else if (typeof redirect === 'string') {
const parsed = new URL(redirect);
if (parsed.protocol === 'node:') {
const specifier = parsed.pathname;
const mod = loadNativeModule(
if (mod && mod.canBeRequiredByUsers) return mod.exports;
throw new ERR_UNKNOWN_BUILTIN_MODULE(specifier);
} else if (parsed.protocol === 'file:') {
return mod.require(fileURLToPath(parsed));
if (missing) {
reaction(new ERR_MANIFEST_DEPENDENCY_MISSING(id, path));
return mod.require(path);
} else {
require = function require(path) {
return mod.require(path);

function resolve(request, options) {
@@ -134,6 +187,7 @@ function normalizeReferrerURL(referrer) {
module.exports = {
@@ -46,7 +46,8 @@ const {
} = require('internal/modules/cjs/helpers');
const { getOptionValue } = require('internal/options');
const preserveSymlinks = getOptionValue('--preserve-symlinks');
@@ -619,11 +620,8 @@ Module._load = function(request, parent, isMain) {
return cachedModule.exports;

const mod =;
if (mod && mod.canBeRequiredByUsers) {
debug('load native module %s', request);
return mod.compileForPublicLoader(experimentalModules);
const mod = loadNativeModule(filename, request, experimentalModules);
if (mod && mod.canBeRequiredByUsers) return mod.exports;

// Don't call updateChildren(), Module constructor already does.
const module = new Module(filename, parent);
@@ -784,8 +782,11 @@ let hasPausedEntry = false;
// the file.
// Returns exception, if any.
Module.prototype._compile = function(content, filename) {
let moduleURL;
let redirects;
if (manifest) {
const moduleURL = pathToFileURL(filename);
moduleURL = pathToFileURL(filename);
redirects = manifest.getRedirects(moduleURL);
manifest.assertIntegrity(moduleURL, content);

@@ -851,7 +852,7 @@ Module.prototype._compile = function(content, filename) {
const dirname = path.dirname(filename);
const require = makeRequireFunction(this);
const require = makeRequireFunction(this, redirects);
var result;
const exports = this.exports;
const thisValue = exports;
@@ -940,7 +941,7 @@ function createRequireFromPath(filename) {
m.filename = proxyPath;

m.paths = Module._nodeModulePaths(m.path);
return makeRequireFunction(m);
return makeRequireFunction(m, null);

Module.createRequireFromPath = createRequireFromPath;
@@ -9,10 +9,10 @@ const {
} = primordials;

const { NativeModule } = require('internal/bootstrap/loaders');
const {
} = require('internal/modules/cjs/helpers');
const CJSModule = require('internal/modules/cjs/loader');
const internalURLModule = require('internal/url');
@@ -94,11 +94,10 @@ translators.set('builtin', async function builtinStrategy(url) {
debug(`Translating BuiltinModule ${url}`);
// Slice 'node:' scheme
const id = url.slice(5);
const module =;
const module = loadNativeModule(id, url, true);
if (!module) {
return createDynamicModule(
[], [...module.exportKeys, 'default'], url, (reflect) => {
debug(`Loading BuiltinModule ${url}`);

0 comments on commit 5d5c89a

Please sign in to comment.
You can’t perform that action at this time.