{ "type": "module", "source": "doc/api/policy.md", "introduced_in": "v11.8.0", "stability": 1, "stabilityText": "Experimental", "miscs": [ { "textRaw": "Policies", "name": "policy", "introduced_in": "v11.8.0", "type": "misc", "stability": 1, "stabilityText": "Experimental", "desc": "

Node.js contains experimental support for creating policies on loading code.

\n

Policies are a security feature intended to allow guarantees\nabout what code Node.js is able to load. The use of policies assumes\nsafe practices for the policy files such as ensuring that policy\nfiles cannot be overwritten by the Node.js application by using\nfile permissions.

\n

A best practice would be to ensure that the policy manifest is read-only for\nthe running Node.js application and that the file cannot be changed\nby the running Node.js application in any way. A typical setup would be to\ncreate the policy file as a different user id than the one running Node.js\nand granting read permissions to the user id running Node.js.

", "miscs": [ { "textRaw": "Enabling", "name": "Enabling", "type": "misc", "desc": "

The --experimental-policy flag can be used to enable features for policies\nwhen loading modules.

\n

Once this has been set, all modules must conform to a policy manifest file\npassed to the flag:

\n
node --experimental-policy=policy.json app.js\n
\n

The policy manifest will be used to enforce constraints on code loaded by\nNode.js.

\n

To mitigate tampering with policy files on disk, an integrity for\nthe policy file itself may be provided via --policy-integrity.\nThis allows running node and asserting the policy file contents\neven if the file is changed on disk.

\n
node --experimental-policy=policy.json --policy-integrity=\"sha384-SggXRQHwCG8g+DktYYzxkXRIkTiEYWBHqev0xnpCxYlqMBufKZHAHQM3/boDaI/0\" app.js\n
" }, { "textRaw": "Features", "name": "features", "modules": [ { "textRaw": "Error behavior", "name": "error_behavior", "desc": "

When a policy check fails, Node.js by default will throw an error.\nIt is possible to change the error behavior to one of a few possibilities\nby defining an \"onerror\" field in a policy manifest. The following values are\navailable to change the behavior:

\n\n
{\n  \"onerror\": \"log\",\n  \"resources\": {\n    \"./app/checked.js\": {\n      \"integrity\": \"sha384-SggXRQHwCG8g+DktYYzxkXRIkTiEYWBHqev0xnpCxYlqMBufKZHAHQM3/boDaI/0\"\n    }\n  }\n}\n
", "type": "module", "displayName": "Error behavior" }, { "textRaw": "Integrity checks", "name": "integrity_checks", "desc": "

Policy files must use integrity checks with Subresource Integrity strings\ncompatible with the browser\nintegrity attribute\nassociated with absolute URLs.

\n

When using require() or import all resources involved in loading are checked\nfor integrity if a policy manifest has been specified. If a resource does not\nmatch the integrity listed in the manifest, an error will be thrown.

\n

An example policy file that would allow loading a file checked.js:

\n
{\n  \"resources\": {\n    \"./app/checked.js\": {\n      \"integrity\": \"sha384-SggXRQHwCG8g+DktYYzxkXRIkTiEYWBHqev0xnpCxYlqMBufKZHAHQM3/boDaI/0\"\n    }\n  }\n}\n
\n

Each resource listed in the policy manifest can be of one the following\nformats to determine its location:

\n
    \n
  1. A relative-URL string to a resource from the manifest such as ./resource.js, ../resource.js, or /resource.js.
  2. \n
  3. A complete URL string to a resource such as file:///resource.js.
  4. \n
\n

When loading resources the entire URL must match including search parameters\nand hash fragment. ./a.js?b will not be used when attempting to load\n./a.js and vice versa.

\n

To generate integrity strings, a script such as\nnode -e 'process.stdout.write(\"sha256-\");process.stdin.pipe(crypto.createHash(\"sha256\").setEncoding(\"base64\")).pipe(process.stdout)' < FILE\ncan be used.

\n

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

", "type": "module", "displayName": "Integrity checks" }, { "textRaw": "Dependency redirection", "name": "dependency_redirection", "desc": "

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

\n
{\n  \"resources\": {\n    \"./app/checked.js\": {\n      \"dependencies\": {\n        \"fs\": true,\n        \"os\": \"./app/node_modules/alt-os\",\n        \"http\": { \"import\": true }\n      }\n    }\n  }\n}\n
\n

The dependencies are keyed by the requested specifier string and have values\nof either true, null, a string pointing to a module to be resolved,\nor a conditions object.

\n

The specifier string does not perform any searching and must match exactly what\nis provided to the require() or import except for a canonicalization step.\nTherefore, multiple specifiers may be needed in the policy if it uses multiple\ndifferent strings to point to the same module (such as excluding the extension).

\n

Specifier strings are canonicalized but not resolved prior to be used for\nmatching in order to have some compatibility with import maps, for example if a\nresource file:///C:/app/server.js was given the following redirection from a\npolicy located at file:///C:/app/policy.json:

\n
{\n  \"resources\": {\n    \"file:///C:/app/utils.js\": {\n      \"dependencies\": {\n        \"./utils.js\": \"./utils-v2.js\"\n      }\n    }\n  }\n}\n
\n

Any specifier used to load file:///C:/app/utils.js would then be intercepted\nand redirected to file:///C:/app/utils-v2.js instead regardless of using an\nabsolute or relative specifier. However, if a specifier that is not an absolute\nor relative URL string is used, it would not be intercepted. So, if an import\nsuch as import('#utils') was used, it would not be intercepted.

\n

If the value of the redirection is true, a \"dependencies\" field at the top of\nthe policy file will be used. If that field at the top of the policy file is\ntrue the default node searching algorithms are used to find the module.

\n

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

\n

Any specifier string for which resolution is attempted and that is not listed in\nthe dependencies results in an error according to the policy.

\n

Redirection does not prevent access to APIs through means such as direct access\nto require.cache or through module.constructor which allow access to\nloading modules. Policy redirection only affects specifiers to require() and\nimport. Other means, such as to prevent undesired access to APIs through\nvariables, are necessary to lock down that path of loading modules.

\n

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

\n

Similar to \"exports\" in package.json, dependencies can also be specified to\nbe objects containing conditions which branch how dependencies are loaded. In\nthe preceding example, \"http\" is allowed when the \"import\" condition is\npart of loading it.

\n

A value of null for the resolved value causes the resolution to fail. This\ncan be used to ensure some kinds of dynamic access are explicitly prevented.

\n

Unknown values for the resolved module location cause failures but are\nnot guaranteed to be forward compatible.

\n

Example: Patched dependency

\n

Redirected dependencies can provide attenuated or modified functionality as fits\nthe application. For example, log data about timing of function durations by\nwrapping the original:

\n
const original = require('fn');\nmodule.exports = function fn(...args) {\n  console.time();\n  try {\n    return new.target ?\n      Reflect.construct(original, args) :\n      Reflect.apply(original, this, args);\n  } finally {\n    console.timeEnd();\n  }\n};\n
", "type": "module", "displayName": "Dependency redirection" }, { "textRaw": "Scopes", "name": "scopes", "desc": "

Use the \"scopes\" field of a manifest to set configuration for many resources\nat once. The \"scopes\" field works by matching resources by their segments.\nIf a scope or resource includes \"cascade\": true, unknown specifiers will\nbe searched for in their containing scope. The containing scope for cascading\nis found by recursively reducing the resource URL by removing segments for\nspecial schemes, keeping trailing \"/\" suffixes, and removing the query and\nhash fragment. This leads to the eventual reduction of the URL to its origin.\nIf the URL is non-special the scope will be located by the URL's origin. If no\nscope is found for the origin or in the case of opaque origins, a protocol\nstring can be used as a scope. If no scope is found for the URL's protocol, a\nfinal empty string \"\" scope will be used.

\n

Note, blob: URLs adopt their origin from the path they contain, and so a scope\nof \"blob:https://nodejs.org\" will have no effect since no URL can have an\norigin of blob:https://nodejs.org; URLs starting with\nblob:https://nodejs.org/ will use https://nodejs.org for its origin and\nthus https: for its protocol scope. For opaque origin blob: URLs they will\nhave blob: for their protocol scope since they do not adopt origins.

\n

Example

\n
{\n  \"scopes\": {\n    \"file:///C:/app/\": {},\n    \"file:\": {},\n    \"\": {}\n  }\n}\n
\n

Given a file located at file:///C:/app/bin/main.js, the following scopes would\nbe checked in order:

\n
    \n
  1. \"file:///C:/app/bin/\"
  2. \n
\n

This determines the policy for all file based resources within\n\"file:///C:/app/bin/\". This is not in the \"scopes\" field of the policy and\nwould be skipped. Adding this scope to the policy would cause it to be used\nprior to the \"file:///C:/app/\" scope.

\n
    \n
  1. \"file:///C:/app/\"
  2. \n
\n

This determines the policy for all file based resources within\n\"file:///C:/app/\". This is in the \"scopes\" field of the policy and it would\ndetermine the policy for the resource at file:///C:/app/bin/main.js. If the\nscope has \"cascade\": true, any unsatisfied queries about the resource would\ndelegate to the next relevant scope for file:///C:/app/bin/main.js, \"file:\".

\n
    \n
  1. \"file:///C:/\"
  2. \n
\n

This determines the policy for all file based resources within \"file:///C:/\".\nThis is not in the \"scopes\" field of the policy and would be skipped. It would\nnot be used for file:///C:/app/bin/main.js unless \"file:///\" is set to\ncascade or is not in the \"scopes\" of the policy.

\n
    \n
  1. \"file:///\"
  2. \n
\n

This determines the policy for all file based resources on the localhost. This\nis not in the \"scopes\" field of the policy and would be skipped. It would not\nbe used for file:///C:/app/bin/main.js unless \"file:///\" is set to cascade\nor is not in the \"scopes\" of the policy.

\n
    \n
  1. \"file:\"
  2. \n
\n

This determines the policy for all file based resources. It would not be used\nfor file:///C:/app/bin/main.js unless \"file:///\" is set to cascade or is not\nin the \"scopes\" of the policy.

\n
    \n
  1. \"\"
  2. \n
\n

This determines the policy for all resources. It would not be used for\nfile:///C:/app/bin/main.js unless \"file:\" is set to cascade.

", "modules": [ { "textRaw": "Integrity using scopes", "name": "integrity_using_scopes", "desc": "

Setting an integrity to true on a scope will set the integrity for any\nresource not found in the manifest to true.

\n

Setting an integrity to null on a scope will set the integrity for any\nresource not found in the manifest to fail matching.

\n

Not including an integrity is the same as setting the integrity to null.

\n

\"cascade\" for integrity checks will be ignored if \"integrity\" is explicitly\nset.

\n

The following example allows loading any file:

\n
{\n  \"scopes\": {\n    \"file:\": {\n      \"integrity\": true\n    }\n  }\n}\n
", "type": "module", "displayName": "Integrity using scopes" }, { "textRaw": "Dependency redirection using scopes", "name": "dependency_redirection_using_scopes", "desc": "

The following example, would allow access to fs for all resources within\n./app/:

\n
{\n  \"resources\": {\n    \"./app/checked.js\": {\n      \"cascade\": true,\n      \"integrity\": true\n    }\n  },\n  \"scopes\": {\n    \"./app/\": {\n      \"dependencies\": {\n        \"fs\": true\n      }\n    }\n  }\n}\n
\n

The following example, would allow access to fs for all data: resources:

\n
{\n  \"resources\": {\n    \"data:text/javascript,import('fs');\": {\n      \"cascade\": true,\n      \"integrity\": true\n    }\n  },\n  \"scopes\": {\n    \"data:\": {\n      \"dependencies\": {\n        \"fs\": true\n      }\n    }\n  }\n}\n
\n

Example: import maps emulation

\n

Given an import map:

\n
{\n  \"imports\": {\n    \"react\": \"./app/node_modules/react/index.js\"\n  },\n  \"scopes\": {\n    \"./ssr/\": {\n      \"react\": \"./app/node_modules/server-side-react/index.js\"\n    }\n  }\n}\n
\n
{\n  \"dependencies\": true,\n  \"scopes\": {\n    \"\": {\n      \"cascade\": true,\n      \"dependencies\": {\n        \"react\": \"./app/node_modules/react/index.js\"\n      }\n    },\n    \"./ssr/\": {\n      \"cascade\": true,\n      \"dependencies\": {\n        \"react\": \"./app/node_modules/server-side-react/index.js\"\n      }\n    }\n  }\n}\n
\n

Import maps assume you can get any resource by default. This means\n\"dependencies\" at the top level of the policy should be set to true.\nPolicies require this to be opt-in since it enables all resources of the\napplication cross linkage which doesn't make sense for many scenarios. They also\nassume any given scope has access to any scope above its allowed dependencies;\nall scopes emulating import maps must set \"cascade\": true.

\n

Import maps only have a single top level scope for their \"imports\". So for\nemulating \"imports\" use the \"\" scope. For emulating \"scopes\" use the\n\"scopes\" in a similar manner to how \"scopes\" works in import maps.

\n

Caveats: Policies do not use string matching for various finding of scope. They\ndo URL traversals. This means things like blob: and data: URLs might not be\nentirely interoperable between the two systems. For example import maps can\npartially match a data: or blob: URL by partitioning the URL on a /\ncharacter, policies intentionally cannot. For blob: URLs import map scopes do\nnot adopt the origin of the blob: URL.

\n

Additionally, import maps only work on import so it may be desirable to add a\n\"import\" condition to all dependency mappings.

", "type": "module", "displayName": "Dependency redirection using scopes" } ], "type": "module", "displayName": "Scopes" } ], "type": "misc", "displayName": "Features" } ] } ] }