Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

crypto: expose Web Crypto API on the global scope #41938

Merged
merged 7 commits into from
Feb 14, 2022
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -340,5 +340,6 @@ module.exports = {
Headers: 'readable',
Request: 'readable',
Response: 'readable',
crypto: 'readable',
},
};
10 changes: 10 additions & 0 deletions doc/api/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,14 @@ added: v17.5.0

Enable experimental support for the [Fetch API][].

### `--experimental-global-webcrypto`

<!-- YAML
added: REPLACEME
-->

Expose the [Web Crypto API][] on the global scope.

### `--experimental-import-meta-resolve`

<!-- YAML
Expand Down Expand Up @@ -1580,6 +1588,7 @@ Node.js options that are allowed are:
* `--enable-source-maps`
* `--experimental-abortcontroller`
* `--experimental-fetch`
* `--experimental-global-webcrypto`
* `--experimental-import-meta-resolve`
* `--experimental-json-modules`
* `--experimental-loader`
Expand Down Expand Up @@ -1982,6 +1991,7 @@ $ node --max-old-space-size=1536 index.js
[Source Map]: https://sourcemaps.info/spec.html
[Subresource Integrity]: https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity
[V8 JavaScript code coverage]: https://v8project.blogspot.com/2017/12/javascript-code-coverage.html
[Web Crypto API]: webcrypto.md
[`"type"`]: packages.md#type
[`--cpu-prof-dir`]: #--cpu-prof-dir
[`--diagnostic-dir`]: #--diagnostic-dirdirectory
Expand Down
12 changes: 7 additions & 5 deletions doc/api/crypto.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,13 @@ calling `require('crypto')` will result in an error being thrown.
When using CommonJS, the error thrown can be caught using try/catch:

```cjs
let crypto;
try {
crypto = require('crypto');
} catch (err) {
console.log('crypto support is disabled!');
{
let crypto;
try {
crypto = require('crypto');
} catch (err) {
console.log('crypto support is disabled!');
}
aduh95 marked this conversation as resolved.
Show resolved Hide resolved
}
```

Expand Down
13 changes: 13 additions & 0 deletions doc/api/globals.md
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,17 @@ added: v0.1.100

Used to print to stdout and stderr. See the [`console`][] section.

## `crypto`

<!-- YAML
added: REPLACEME
-->

> Stability: 1 - Experimental. Enable this API with the
> [`--experimental-global-webcrypto`][] CLI flag.

A browser-compatible implementation of the [Web Crypto API][].

## `Event`

<!-- YAML
Expand Down Expand Up @@ -598,7 +609,9 @@ The object that acts as the namespace for all W3C
[WebAssembly][webassembly-org] related functionality. See the
[Mozilla Developer Network][webassembly-mdn] for usage and compatibility.

[Web Crypto API]: webcrypto.md
[`--experimental-fetch`]: cli.md#--experimental-fetch
[`--experimental-global-webcrypto`]: cli.md#--experimental-global-webcrypto
[`AbortController`]: https://developer.mozilla.org/en-US/docs/Web/API/AbortController
[`DOMException`]: https://developer.mozilla.org/en-US/docs/Web/API/DOMException
[`EventTarget` and `Event` API]: events.md#eventtarget-and-event-api
Expand Down
3 changes: 3 additions & 0 deletions doc/node.1
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,9 @@ Enable Source Map V3 support for stack traces.
.It Fl -experimental-fetch
Enable experimental support for the Fetch API.
.
.It Fl -experimental-global-webcrypto
Expose the Web Crypto API on the global scope.
.
.It Fl -experimental-import-meta-resolve
Enable experimental ES modules support for import.meta.resolve().
.
Expand Down
2 changes: 2 additions & 0 deletions lib/.eslintrc.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,8 @@ rules:
message: "Use `const { atob } = require('buffer');` instead of the global."
- name: btoa
message: "Use `const { btoa } = require('buffer');` instead of the global."
- name: crypto
message: "Use `const { crypto } = require('internal/crypto/webcrypto');` instead of the global."
- name: global
message: "Use `const { globalThis } = primordials;` instead of `global`."
- name: globalThis
Expand Down
21 changes: 21 additions & 0 deletions lib/internal/bootstrap/pre_execution.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
const {
NumberParseInt,
ObjectDefineProperty,
ObjectGetOwnPropertyDescriptor,
SafeMap,
SafeWeakMap,
StringPrototypeStartsWith,
Expand Down Expand Up @@ -36,6 +37,7 @@ function prepareMainThreadExecution(expandArgv1 = false) {
setupInspectorHooks();
setupWarningHandler();
setupFetch();
setupWebCrypto();

// Resolve the coverage directory to an absolute path, and
// overwrite process.env so that the original path gets passed
Expand Down Expand Up @@ -162,6 +164,24 @@ function setupFetch() {
exposeInterface(globalThis, 'Response', undici.Response);
}

// TODO(aduh95): move this to internal/bootstrap/browser when the CLI flag is
// removed.
function setupWebCrypto() {
if (!getOptionValue('--experimental-global-webcrypto')) {
return;
}

let crypto;
ObjectDefineProperty(globalThis, 'crypto',
ObjectGetOwnPropertyDescriptor({
get crypto() {
crypto ??= require('internal/crypto/webcrypto').crypto;
return crypto;
}
}, 'crypto'));

}

// Setup User-facing NODE_V8_COVERAGE environment variable that writes
// ScriptCoverage to a specified file.
function setupCoverageHooks(dir) {
Expand Down Expand Up @@ -503,6 +523,7 @@ module.exports = {
setupCoverageHooks,
setupWarningHandler,
setupFetch,
setupWebCrypto,
setupDebugEnv,
setupPerfHooks,
prepareMainThreadExecution,
Expand Down
2 changes: 2 additions & 0 deletions lib/internal/main/worker_thread.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ const {
setupInspectorHooks,
setupWarningHandler,
setupFetch,
setupWebCrypto,
setupDebugEnv,
setupPerfHooks,
initializeDeprecations,
Expand Down Expand Up @@ -69,6 +70,7 @@ setupDebugEnv();

setupWarningHandler();
setupFetch();
setupWebCrypto();
initializeSourceMapsHandlers();

// Since worker threads cannot switch cwd, we do not need to
Expand Down
4 changes: 4 additions & 0 deletions src/node_options.cc
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,10 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() {
"experimental Fetch API",
&EnvironmentOptions::experimental_fetch,
kAllowedInEnvironment);
AddOption("--experimental-global-webcrypto",
"expose experimental Web Crypto API on the global scope",
&EnvironmentOptions::experimental_global_web_crypto,
kAllowedInEnvironment);
AddOption("--experimental-json-modules", "", NoOp{}, kAllowedInEnvironment);
AddOption("--experimental-loader",
"use the specified module as a custom loader",
Expand Down
1 change: 1 addition & 0 deletions src/node_options.h
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ class EnvironmentOptions : public Options {
std::string dns_result_order;
bool enable_source_maps = false;
bool experimental_fetch = false;
bool experimental_global_web_crypto = false;
bool experimental_https_modules = false;
std::string experimental_specifier_resolution;
bool experimental_wasm_modules = false;
Expand Down
3 changes: 3 additions & 0 deletions test/common/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,9 @@ if (global.fetch) {
global.Headers,
);
}
if (hasCrypto && global.crypto) {
knownGlobals.push(global.crypto);
}

function allowGlobals(...allowlist) {
knownGlobals = knownGlobals.concat(allowlist);
Expand Down
11 changes: 11 additions & 0 deletions test/parallel/test-global-webcrypto.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// Flags: --experimental-global-webcrypto
'use strict';

const common = require('../common');
if (!common.hasCrypto)
common.skip('missing crypto');

const assert = require('assert');
const crypto = require('crypto');

assert.strictEqual(globalThis.crypto, crypto.webcrypto);