text
stringlengths 2
4k
|
---|
ptions)`.
* @since v19.4.0
*/
function setDefaultAutoSelectFamily(value: boolean): void;
/**
* Gets the current default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`.
* The initial default value is `250`.
* @since v19.8.0
*/
function getDefaultAutoSelectFamilyAttemptTimeout(): number;
/**
* Sets the default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`.
* @since v19.8.0
*/
function setDefaultAutoSelectFamilyAttemptTimeout(value: number): void;
/**
* Returns `6` if `input` is an IPv6 address. Returns `4` if `input` is an IPv4
* address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no leading zeroes. Otherwise, returns`0`.
*
* ```js
* net.isIP('::1'); // returns 6
* net.isIP('127.0.0.1'); // returns 4
* net.isIP('127.000.000.001'); // returns 0
* net.isIP('127.0.0.1/24'); // returns 0
* net.isIP('fhqwhgads'); // returns 0
* ```
* @since v0.3.0
*/
function isIP(input: string): number;
/**
* Returns `true` if `input` is an IPv4 address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no
* leading zeroes. Otherwise, returns `false`.
*
* ```js
* net.isIPv4('127.0.0.1'); // returns true
* net.isIPv4('127.000.000.001'); // returns false
* net.isIPv4('127.0.0.1/24'); // returns false
* net.isIPv4('fhqwhgads'); // returns false
* ```
* @since v0.3.0
*/
function isIPv4(input: string): boolean;
/**
* Returns `true` if `input` is an IPv6 address. Otherwise, returns `false`.
*
* ```js
* net.isIPv6('::1'); // returns true
* net.isIPv6('fhqwhgads'); // returns false
* ```
* @since v0.3.0
*/
function isIPv6(input: string): boolean;
interface SocketAddressInitOptions {
/**
* The network address as either an IPv4 or IPv6 string.
* @default 127.0.0.1
*/
address?: string | undefined;
/**
* @default `'ipv4'`
*/
family?: IPVersion | undefined;
/**
* An IPv6 flow-label used only if `family` is `'ipv6'`.
* @default 0
*/
flowlabel?: number | undefined;
/**
* An IP port.
* @default 0
*/
port?: number | undefined;
}
/**
* @since v15.14.0, v14.18.0
*/
class SocketAddress {
constructor(options: SocketAddressInitOptions);
/**
* Either \`'ipv4'\` or \`'ipv6'\`.
* @since v15.14.0, v14.18.0
*/
readonly address: string;
/**
* Either \`'ipv4'\` or \`'ipv6'\`.
* @since v15.14.0, v14.18.0
*/
readonly family: IPVersion;
/**
* @since v15.14.0, v14.18.0
*/
readonly port: number;
/**
* @since v15.14.0, v14.18.0
*/
readonly flowlabel: number;
}
}
declare module "node:net" {
export * from "net";
}
|
declare module "path/posix" {
import path = require("path");
export = path;
}
declare module "path/win32" {
import path = require("path");
export = path;
}
/**
* The `node:path` module provides utilities for working with file and directory
* paths. It can be accessed using:
*
* ```js
* const path = require('node:path');
* ```
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/path.js)
*/
declare module "path" {
namespace path {
/**
* A parsed path object generated by path.parse() or consumed by path.format().
*/
interface ParsedPath {
/**
* The root of the path such as '/' or 'c:\'
*/
root: string;
/**
* The full directory path such as '/home/user/dir' or 'c:\path\dir'
*/
dir: string;
/**
* The file name including extension (if any) such as 'index.html'
*/
base: string;
/**
* The file extension (if any) such as '.html'
*/
ext: string;
/**
* The file name without extension (if any) such as 'index'
*/
name: string;
}
interface FormatInputPathObject {
/**
* The root of the path such as '/' or 'c:\'
*/
root?: string | undefined;
/**
* The full directory path such as '/home/user/dir' or 'c:\path\dir'
*/
dir?: string | undefined;
/**
* The file name including extension (if any) such as 'index.html'
*/
base?: string | undefined;
/**
* The file extension (if any) such as '.html'
*/
ext?: string | undefined;
/**
* The file name without extension (if any) such as 'index'
*/
name?: string | undefined;
}
interface PlatformPath {
/**
* Normalize a string path, reducing '..' and '.' parts.
* When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used.
*
* @param path string path to normalize.
* @throws {TypeError} if `path` is not a string.
*/
normalize(path: string): string;
/**
* Join all arguments together and normalize the resulting path.
*
* @param paths paths to join.
* @throws {TypeError} if any of the path segments is not a string.
*/
join(...paths: string[]): string;
/**
* The right-most parameter is considered {to}. Other parameters are considered an array of {from}.
*
* Starting from leftmost {from} parameter, resolves {to} to an absolute path.
*
* If {to} isn't already absolute, {from} arguments are prepended in right to left order,
* until an absolute path is found. If after using all {from} paths still no absolute path is found,
* the current working directory is used as well. The resulting path is normalized,
* and trailing slashes are removed unless the path gets resolved to the root directory.
*
* @param paths A sequence of paths or path segments.
* @throws {TypeError} if any of the arguments is not a string.
*/
resolve(...paths: string[]): string;
/**
* Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory.
*
* If the given {path} is a zero-length string, `false` will be returned.
*
* @param path path to te |
st.
* @throws {TypeError} if `path` is not a string.
*/
isAbsolute(path: string): boolean;
/**
* Solve the relative path from {from} to {to} based on the current working directory.
* At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve.
*
* @throws {TypeError} if either `from` or `to` is not a string.
*/
relative(from: string, to: string): string;
/**
* Return the directory name of a path. Similar to the Unix dirname command.
*
* @param path the path to evaluate.
* @throws {TypeError} if `path` is not a string.
*/
dirname(path: string): string;
/**
* Return the last portion of a path. Similar to the Unix basename command.
* Often used to extract the file name from a fully qualified path.
*
* @param path the path to evaluate.
* @param suffix optionally, an extension to remove from the result.
* @throws {TypeError} if `path` is not a string or if `ext` is given and is not a string.
*/
basename(path: string, suffix?: string): string;
/**
* Return the extension of the path, from the last '.' to end of string in the last portion of the path.
* If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string.
*
* @param path the path to evaluate.
* @throws {TypeError} if `path` is not a string.
*/
extname(path: string): string;
/**
* The platform-specific file separator. '\\' or '/'.
*/
readonly sep: "\\" | "/";
/**
* The platform-specific file delimiter. ';' or ':'.
*/
readonly delimiter: ";" | ":";
/**
* Returns an object from a path string - the opposite of format().
*
* @param path path to evaluate.
* @throws {TypeError} if `path` is not a string.
*/
parse(path: string): ParsedPath;
/**
* Returns a path string from an object - the opposite of parse().
*
* @param pathObject path to evaluate.
*/
format(pathObject: FormatInputPathObject): string;
/**
* On Windows systems only, returns an equivalent namespace-prefixed path for the given path.
* If path is not a string, path will be returned without modifications.
* This method is meaningful only on Windows system.
* On POSIX systems, the method is non-operational and always returns path without modifications.
*/
toNamespacedPath(path: string): string;
/**
* Posix specific pathing.
* Same as parent object on posix.
*/
readonly posix: PlatformPath;
/**
* Windows specific pathing.
* Same as parent object on windows
*/
readonly win32: PlatformPath;
}
}
const path: path.PlatformPath;
export = path;
}
declare module "node:path" {
import path = require("path");
export = path;
}
declare module "node:path/posix" {
import path = require("path/posix");
export = path;
}
declare module "node:path/win32" {
import path = require("path/win32");
export = path;
}
|
/** @deprecated since v6.3.0 - use constants property exposed by the relevant module instead. */
declare module "constants" {
import { constants as osConstants, SignalConstants } from "node:os";
import { constants as cryptoConstants } from "node:crypto";
import { constants as fsConstants } from "node:fs";
const exp:
& typeof osConstants.errno
& typeof osConstants.priority
& SignalConstants
& typeof cryptoConstants
& typeof fsConstants;
export = exp;
}
declare module "node:constants" {
import constants = require("constants");
export = constants;
}
|
/**
* **This module is pending deprecation.** Once a replacement API has been
* finalized, this module will be fully deprecated. Most developers should
* **not** have cause to use this module. Users who absolutely must have
* the functionality that domains provide may rely on it for the time being
* but should expect to have to migrate to a different solution
* in the future.
*
* Domains provide a way to handle multiple different IO operations as a
* single group. If any of the event emitters or callbacks registered to a
* domain emit an `'error'` event, or throw an error, then the domain object
* will be notified, rather than losing the context of the error in the`process.on('uncaughtException')` handler, or causing the program to
* exit immediately with an error code.
* @deprecated Since v1.4.2 - Deprecated
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/domain.js)
*/
declare module "domain" {
import EventEmitter = require("node:events");
/**
* The `Domain` class encapsulates the functionality of routing errors and
* uncaught exceptions to the active `Domain` object.
*
* To handle the errors that it catches, listen to its `'error'` event.
*/
class Domain extends EventEmitter {
/**
* An array of timers and event emitters that have been explicitly added
* to the domain.
*/
members: Array<EventEmitter | NodeJS.Timer>;
/**
* The `enter()` method is plumbing used by the `run()`, `bind()`, and`intercept()` methods to set the active domain. It sets `domain.active` and`process.domain` to the domain, and implicitly
* pushes the domain onto the domain
* stack managed by the domain module (see {@link exit} for details on the
* domain stack). The call to `enter()` delimits the beginning of a chain of
* asynchronous calls and I/O operations bound to a domain.
*
* Calling `enter()` changes only the active domain, and does not alter the domain
* itself. `enter()` and `exit()` can be called an arbitrary number of times on a
* single domain.
*/
enter(): void;
/**
* The `exit()` method exits the current domain, popping it off the domain stack.
* Any time execution is going to switch to the context of a different chain of
* asynchronous calls, it's important to ensure that the current domain is exited.
* The call to `exit()` delimits either the end of or an interruption to the chain
* of asynchronous calls and I/O operations bound to a domain.
*
* If there are multiple, nested domains bound to the current execution context,`exit()` will exit any domains nested within this domain.
*
* Calling `exit()` changes only the active domain, and does not alter the domain
* itself. `enter()` and `exit()` can be called an arbitrary number of times on a
* single domain.
*/
exit(): void;
/**
* Run the supplied function in the context of the domain, implicitly
* binding all event emitters, timers, and low-level requests that are
* created in that context. Optionally, arguments can be passed to
* the function.
*
* This is the most basic way to use a domain.
*
* ```js
* const domain = require('node:domain');
* const fs = require('node:fs');
* const d = domain.create();
* d.on('error', (er) => {
* console.error('Caught error!', er);
* });
* d.run(() => {
* process.nextTick(() => {
* setTimeout(() => { // Simulating some various async stuff
* fs.open('non-existent file', 'r', (er, fd) => {
* if (er) throw er;
* // proceed...
* });
* }, 100);
* });
* });
* `` |
`
*
* In this example, the `d.on('error')` handler will be triggered, rather
* than crashing the program.
*/
run<T>(fn: (...args: any[]) => T, ...args: any[]): T;
/**
* Explicitly adds an emitter to the domain. If any event handlers called by
* the emitter throw an error, or if the emitter emits an `'error'` event, it
* will be routed to the domain's `'error'` event, just like with implicit
* binding.
*
* This also works with timers that are returned from `setInterval()` and `setTimeout()`. If their callback function throws, it will be caught by
* the domain `'error'` handler.
*
* If the Timer or `EventEmitter` was already bound to a domain, it is removed
* from that one, and bound to this one instead.
* @param emitter emitter or timer to be added to the domain
*/
add(emitter: EventEmitter | NodeJS.Timer): void;
/**
* The opposite of {@link add}. Removes domain handling from the
* specified emitter.
* @param emitter emitter or timer to be removed from the domain
*/
remove(emitter: EventEmitter | NodeJS.Timer): void;
/**
* The returned function will be a wrapper around the supplied callback
* function. When the returned function is called, any errors that are
* thrown will be routed to the domain's `'error'` event.
*
* ```js
* const d = domain.create();
*
* function readSomeFile(filename, cb) {
* fs.readFile(filename, 'utf8', d.bind((er, data) => {
* // If this throws, it will also be passed to the domain.
* return cb(er, data ? JSON.parse(data) : null);
* }));
* }
*
* d.on('error', (er) => {
* // An error occurred somewhere. If we throw it now, it will crash the program
* // with the normal line number and stack message.
* });
* ```
* @param callback The callback function
* @return The bound function
*/
bind<T extends Function>(callback: T): T;
/**
* This method is almost identical to {@link bind}. However, in
* addition to catching thrown errors, it will also intercept `Error` objects sent as the first argument to the function.
*
* In this way, the common `if (err) return callback(err);` pattern can be replaced
* with a single error handler in a single place.
*
* ```js
* const d = domain.create();
*
* function readSomeFile(filename, cb) {
* fs.readFile(filename, 'utf8', d.intercept((data) => {
* // Note, the first argument is never passed to the
* // callback since it is assumed to be the 'Error' argument
* // and thus intercepted by the domain.
*
* // If this throws, it will also be passed to the domain
* // so the error-handling logic can be moved to the 'error'
* // event on the domain instead of being repeated throughout
* // the program.
* return cb(null, JSON.parse(data));
* }));
* }
*
* d.on('error', (er) => {
* // An error occurred somewhere. If we throw it now, it will crash the program
* // with the normal line number and stack message.
* });
* ```
* @param callback The callback function
* @return The intercepted function
*/
intercept<T extends Function>(callback: T): T;
}
function create(): Domain;
}
declare module "node:domain" {
export * from "domain";
}
|
/**
* The `node:diagnostics_channel` module provides an API to create named channels
* to report arbitrary message data for diagnostics purposes.
*
* It can be accessed using:
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
* ```
*
* It is intended that a module writer wanting to report diagnostics messages
* will create one or many top-level channels to report messages through.
* Channels may also be acquired at runtime but it is not encouraged
* due to the additional overhead of doing so. Channels may be exported for
* convenience, but as long as the name is known it can be acquired anywhere.
*
* If you intend for your module to produce diagnostics data for others to
* consume it is recommended that you include documentation of what named
* channels are used along with the shape of the message data. Channel names
* should generally include the module name to avoid collisions with data from
* other modules.
* @since v15.1.0, v14.17.0
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/diagnostics_channel.js)
*/
declare module "diagnostics_channel" {
import { AsyncLocalStorage } from "node:async_hooks";
/**
* Check if there are active subscribers to the named channel. This is helpful if
* the message you want to send might be expensive to prepare.
*
* This API is optional but helpful when trying to publish messages from very
* performance-sensitive code.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* if (diagnostics_channel.hasSubscribers('my-channel')) {
* // There are subscribers, prepare and publish message
* }
* ```
* @since v15.1.0, v14.17.0
* @param name The channel name
* @return If there are active subscribers
*/
function hasSubscribers(name: string | symbol): boolean;
/**
* This is the primary entry-point for anyone wanting to publish to a named
* channel. It produces a channel object which is optimized to reduce overhead at
* publish time as much as possible.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* const channel = diagnostics_channel.channel('my-channel');
* ```
* @since v15.1.0, v14.17.0
* @param name The channel name
* @return The named channel object
*/
function channel(name: string | symbol): Channel;
type ChannelListener = (message: unknown, name: string | symbol) => void;
/**
* Register a message handler to subscribe to this channel. This message handler
* will be run synchronously whenever a message is published to the channel. Any
* errors thrown in the message handler will trigger an `'uncaughtException'`.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* diagnostics_channel.subscribe('my-channel', (message, name) => {
* // Received data
* });
* ```
* @since v18.7.0, v16.17.0
* @param name The channel name
* @param onMessage The handler to receive channel messages
*/
function subscribe(name: string | symbol, onMessage: ChannelListener): void;
/**
* Remove a message handler previously registered to this channel with {@link subscribe}.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* function onMessage(message, name) {
* // Received data
* }
*
* diagnostics_channel.subscribe('my-channel', onMessage);
*
* diagnostics_channel.unsubscribe('my-channel', onMessage);
* ```
* @since v18.7.0, v16.17.0
* @param name The channel name
* @param onMessage The previous subscribed handler to remove
* @return `true` if the handler was found, `false` otherwise.
*/
function unsubscribe(name: string | symbol, onMessage: ChannelListener): boolean;
/**
* Creates a `TracingChannel` wrapper for t |
he given `TracingChannel Channels`. If a name is given, the corresponding tracing
* channels will be created in the form of `tracing:${name}:${eventType}` where`eventType` corresponds to the types of `TracingChannel Channels`.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* const channelsByName = diagnostics_channel.tracingChannel('my-channel');
*
* // or...
*
* const channelsByCollection = diagnostics_channel.tracingChannel({
* start: diagnostics_channel.channel('tracing:my-channel:start'),
* end: diagnostics_channel.channel('tracing:my-channel:end'),
* asyncStart: diagnostics_channel.channel('tracing:my-channel:asyncStart'),
* asyncEnd: diagnostics_channel.channel('tracing:my-channel:asyncEnd'),
* error: diagnostics_channel.channel('tracing:my-channel:error'),
* });
* ```
* @since v19.9.0
* @experimental
* @param nameOrChannels Channel name or object containing all the `TracingChannel Channels`
* @return Collection of channels to trace with
*/
function tracingChannel<
StoreType = unknown,
ContextType extends object = StoreType extends object ? StoreType : object,
>(
nameOrChannels: string | TracingChannelCollection<StoreType, ContextType>,
): TracingChannel<StoreType, ContextType>;
/**
* The class `Channel` represents an individual named channel within the data
* pipeline. It is used to track subscribers and to publish messages when there
* are subscribers present. It exists as a separate object to avoid channel
* lookups at publish time, enabling very fast publish speeds and allowing
* for heavy use while incurring very minimal cost. Channels are created with {@link channel}, constructing a channel directly
* with `new Channel(name)` is not supported.
* @since v15.1.0, v14.17.0
*/
class Channel<StoreType = unknown, ContextType = StoreType> {
readonly name: string | symbol;
/**
* Check if there are active subscribers to this channel. This is helpful if
* the message you want to send might be expensive to prepare.
*
* This API is optional but helpful when trying to publish messages from very
* performance-sensitive code.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* const channel = diagnostics_channel.channel('my-channel');
*
* if (channel.hasSubscribers) {
* // There are subscribers, prepare and publish message
* }
* ```
* @since v15.1.0, v14.17.0
*/
readonly hasSubscribers: boolean;
private constructor(name: string | symbol);
/**
* Publish a message to any subscribers to the channel. This will trigger
* message handlers synchronously so they will execute within the same context.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* const channel = diagnostics_channel.channel('my-channel');
*
* channel.publish({
* some: 'message',
* });
* ```
* @since v15.1.0, v14.17.0
* @param message The message to send to the channel subscribers
*/
publish(message: unknown): void;
/**
* Register a message handler to subscribe to this channel. This message handler
* will be run synchronously whenever a message is published to the channel. Any
* errors thrown in the message handler will trigger an `'uncaughtException'`.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* const channel = diagnostics_channel.channel('my-channel');
*
* channel.subscribe((message, name) => {
* // Received data
|
* });
* ```
* @since v15.1.0, v14.17.0
* @deprecated Since v18.7.0,v16.17.0 - Use {@link subscribe(name, onMessage)}
* @param onMessage The handler to receive channel messages
*/
subscribe(onMessage: ChannelListener): void;
/**
* Remove a message handler previously registered to this channel with `channel.subscribe(onMessage)`.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* const channel = diagnostics_channel.channel('my-channel');
*
* function onMessage(message, name) {
* // Received data
* }
*
* channel.subscribe(onMessage);
*
* channel.unsubscribe(onMessage);
* ```
* @since v15.1.0, v14.17.0
* @deprecated Since v18.7.0,v16.17.0 - Use {@link unsubscribe(name, onMessage)}
* @param onMessage The previous subscribed handler to remove
* @return `true` if the handler was found, `false` otherwise.
*/
unsubscribe(onMessage: ChannelListener): void;
/**
* When `channel.runStores(context, ...)` is called, the given context data
* will be applied to any store bound to the channel. If the store has already been
* bound the previous `transform` function will be replaced with the new one.
* The `transform` function may be omitted to set the given context data as the
* context directly.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
* import { AsyncLocalStorage } from 'node:async_hooks';
*
* const store = new AsyncLocalStorage();
*
* const channel = diagnostics_channel.channel('my-channel');
*
* channel.bindStore(store, (data) => {
* return { data };
* });
* ```
* @since v19.9.0
* @experimental
* @param store The store to which to bind the context data
* @param transform Transform context data before setting the store context
*/
bindStore(store: AsyncLocalStorage<StoreType>, transform?: (context: ContextType) => StoreType): void;
/**
* Remove a message handler previously registered to this channel with `channel.bindStore(store)`.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
* import { AsyncLocalStorage } from 'node:async_hooks';
*
* const store = new AsyncLocalStorage();
*
* const channel = diagnostics_channel.channel('my-channel');
*
* channel.bindStore(store);
* channel.unbindStore(store);
* ```
* @since v19.9.0
* @experimental
* @param store The store to unbind from the channel.
* @return `true` if the store was found, `false` otherwise.
*/
unbindStore(store: any): void;
/**
* Applies the given data to any AsyncLocalStorage instances bound to the channel
* for the duration of the given function, then publishes to the channel within
* the scope of that data is applied to the stores.
*
* If a transform function was given to `channel.bindStore(store)` it will be
* applied to transform the message data before it becomes the context value for
* the store. The prior storage context is accessible from within the transform
* function in cases where context linking is required.
*
* The context applied to the store should be accessible in any async code which
* continues from execution which began during the given function, however
* there are some situations in which `context loss` may occur.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
* import { |
AsyncLocalStorage } from 'node:async_hooks';
*
* const store = new AsyncLocalStorage();
*
* const channel = diagnostics_channel.channel('my-channel');
*
* channel.bindStore(store, (message) => {
* const parent = store.getStore();
* return new Span(message, parent);
* });
* channel.runStores({ some: 'message' }, () => {
* store.getStore(); // Span({ some: 'message' })
* });
* ```
* @since v19.9.0
* @experimental
* @param context Message to send to subscribers and bind to stores
* @param fn Handler to run within the entered storage context
* @param thisArg The receiver to be used for the function call.
* @param args Optional arguments to pass to the function.
*/
runStores(): void;
}
interface TracingChannelSubscribers<ContextType extends object> {
start: (message: ContextType) => void;
end: (
message: ContextType & {
error?: unknown;
result?: unknown;
},
) => void;
asyncStart: (
message: ContextType & {
error?: unknown;
result?: unknown;
},
) => void;
asyncEnd: (
message: ContextType & {
error?: unknown;
result?: unknown;
},
) => void;
error: (
message: ContextType & {
error: unknown;
},
) => void;
}
interface TracingChannelCollection<StoreType = unknown, ContextType = StoreType> {
start: Channel<StoreType, ContextType>;
end: Channel<StoreType, ContextType>;
asyncStart: Channel<StoreType, ContextType>;
asyncEnd: Channel<StoreType, ContextType>;
error: Channel<StoreType, ContextType>;
}
/**
* The class `TracingChannel` is a collection of `TracingChannel Channels` which
* together express a single traceable action. It is used to formalize and
* simplify the process of producing events for tracing application flow.{@link tracingChannel} is used to construct a`TracingChannel`. As with `Channel` it is recommended to create and reuse a
* single `TracingChannel` at the top-level of the file rather than creating them
* dynamically.
* @since v19.9.0
* @experimental
*/
class TracingChannel<StoreType = unknown, ContextType extends object = {}> implements TracingChannelCollection {
start: Channel<StoreType, ContextType>;
end: Channel<StoreType, ContextType>;
asyncStart: Channel<StoreType, ContextType>;
asyncEnd: Channel<StoreType, ContextType>;
error: Channel<StoreType, ContextType>;
/**
* Helper to subscribe a collection of functions to the corresponding channels.
* This is the same as calling `channel.subscribe(onMessage)` on each channel
* individually.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* const channels = diagnostics_channel.tracingChannel('my-channel');
*
* channels.subscribe({
* start(message) {
* // Handle start message
* },
* end(message) {
* // Handle end message
* },
* asyncStart(message) {
* // Handle asyncStart message
* },
* asyncEnd(message) {
* // Handle asyncEnd message
* },
* error(message) {
* // Handle error message
* },
* });
* ```
* @since v19.9.0
* @experimental
* @param subscribers Set of `TracingChannel Channels` subscribers
*/
subscribe(subscribers: TracingChannelSubscribers<ContextType>): void;
/**
* Helper to unsubscribe |
a collection of functions from the corresponding channels.
* This is the same as calling `channel.unsubscribe(onMessage)` on each channel
* individually.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* const channels = diagnostics_channel.tracingChannel('my-channel');
*
* channels.unsubscribe({
* start(message) {
* // Handle start message
* },
* end(message) {
* // Handle end message
* },
* asyncStart(message) {
* // Handle asyncStart message
* },
* asyncEnd(message) {
* // Handle asyncEnd message
* },
* error(message) {
* // Handle error message
* },
* });
* ```
* @since v19.9.0
* @experimental
* @param subscribers Set of `TracingChannel Channels` subscribers
* @return `true` if all handlers were successfully unsubscribed, and `false` otherwise.
*/
unsubscribe(subscribers: TracingChannelSubscribers<ContextType>): void;
/**
* Trace a synchronous function call. This will always produce a `start event` and `end event` around the execution and may produce an `error event` if the given function throws an error.
* This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all
* events should have any bound stores set to match this trace context.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* const channels = diagnostics_channel.tracingChannel('my-channel');
*
* channels.traceSync(() => {
* // Do something
* }, {
* some: 'thing',
* });
* ```
* @since v19.9.0
* @experimental
* @param fn Function to wrap a trace around
* @param context Shared object to correlate events through
* @param thisArg The receiver to be used for the function call
* @param args Optional arguments to pass to the function
* @return The return value of the given function
*/
traceSync<ThisArg = any, Args extends any[] = any[]>(
fn: (this: ThisArg, ...args: Args) => any,
context?: ContextType,
thisArg?: ThisArg,
...args: Args
): void;
/**
* Trace a promise-returning function call. This will always produce a `start event` and `end event` around the synchronous portion of the
* function execution, and will produce an `asyncStart event` and `asyncEnd event` when a promise continuation is reached. It may also
* produce an `error event` if the given function throws an error or the
* returned promise rejects. This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all
* events should have any bound stores set to match this trace context.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* const channels = diagnostics_channel.tracingChannel('my-channel');
*
* channels.tracePromise(async () => {
* // Do something
* }, {
* some: 'thing',
* });
* ```
* @since v19.9.0
* @experimental
* @param fn Promise-returning function to wrap a trace around
* @param context Shared object to correlate trace events through
* @param thisArg The receiver to be used for the function call
* @param args Optional arguments to pass to the function
* @return Chained from promise returned by the given function
*/
tracePromise<ThisArg = any, Args extends any[] = any[]>(
|
fn: (this: ThisArg, ...args: Args) => Promise<any>,
context?: ContextType,
thisArg?: ThisArg,
...args: Args
): void;
/**
* Trace a callback-receiving function call. This will always produce a `start event` and `end event` around the synchronous portion of the
* function execution, and will produce a `asyncStart event` and `asyncEnd event` around the callback execution. It may also produce an `error event` if the given function throws an error or
* the returned
* promise rejects. This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all
* events should have any bound stores set to match this trace context.
*
* The `position` will be -1 by default to indicate the final argument should
* be used as the callback.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
*
* const channels = diagnostics_channel.tracingChannel('my-channel');
*
* channels.traceCallback((arg1, callback) => {
* // Do something
* callback(null, 'result');
* }, 1, {
* some: 'thing',
* }, thisArg, arg1, callback);
* ```
*
* The callback will also be run with `channel.runStores(context, ...)` which
* enables context loss recovery in some cases.
*
* ```js
* import diagnostics_channel from 'node:diagnostics_channel';
* import { AsyncLocalStorage } from 'node:async_hooks';
*
* const channels = diagnostics_channel.tracingChannel('my-channel');
* const myStore = new AsyncLocalStorage();
*
* // The start channel sets the initial store data to something
* // and stores that store data value on the trace context object
* channels.start.bindStore(myStore, (data) => {
* const span = new Span(data);
* data.span = span;
* return span;
* });
*
* // Then asyncStart can restore from that data it stored previously
* channels.asyncStart.bindStore(myStore, (data) => {
* return data.span;
* });
* ```
* @since v19.9.0
* @experimental
* @param fn callback using function to wrap a trace around
* @param position Zero-indexed argument position of expected callback
* @param context Shared object to correlate trace events through
* @param thisArg The receiver to be used for the function call
* @param args Optional arguments to pass to the function
* @return The return value of the given function
*/
traceCallback<Fn extends (this: any, ...args: any) => any>(
fn: Fn,
position: number | undefined,
context: ContextType | undefined,
thisArg: any,
...args: Parameters<Fn>
): void;
}
}
declare module "node:diagnostics_channel" {
export * from "diagnostics_channel";
}
|
export {}; // Make this a module
// #region Fetch and friends
// Conditional type aliases, used at the end of this file.
// Will either be empty if lib-dom is included, or the undici version otherwise.
type _Request = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Request;
type _Response = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Response;
type _FormData = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").FormData;
type _Headers = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Headers;
type _RequestInit = typeof globalThis extends { onmessage: any } ? {}
: import("undici-types").RequestInit;
type _ResponseInit = typeof globalThis extends { onmessage: any } ? {}
: import("undici-types").ResponseInit;
type _File = typeof globalThis extends { onmessage: any } ? {} : import("node:buffer").File;
// #endregion Fetch and friends
declare global {
// Declare "static" methods in Error
interface ErrorConstructor {
/** Create .stack property on a target object */
captureStackTrace(targetObject: object, constructorOpt?: Function): void;
/**
* Optional override for formatting stack traces
*
* @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces
*/
prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined;
stackTraceLimit: number;
}
/*-----------------------------------------------*
* *
* GLOBAL *
* *
------------------------------------------------*/
// For backwards compability
interface NodeRequire extends NodeJS.Require {}
interface RequireResolve extends NodeJS.RequireResolve {}
interface NodeModule extends NodeJS.Module {}
var process: NodeJS.Process;
var console: Console;
var __filename: string;
var __dirname: string;
var require: NodeRequire;
var module: NodeModule;
// Same as module.exports
var exports: any;
/**
* Only available if `--expose-gc` is passed to the process.
*/
var gc: undefined | (() => void);
// #region borrowed
// from https://github.com/microsoft/TypeScript/blob/38da7c600c83e7b31193a62495239a0fe478cb67/lib/lib.webworker.d.ts#L633 until moved to separate lib
/** A controller object that allows you to abort one or more DOM requests as and when desired. */
interface AbortController {
/**
* Returns the AbortSignal object associated with this object.
*/
readonly signal: AbortSignal;
/**
* Invoking this method will set this object's AbortSignal's aborted flag and signal to any observers that the associated activity is to be aborted.
*/
abort(reason?: any): void;
}
/** A signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. */
interface AbortSignal extends EventTarget {
/**
* Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise.
*/
readonly aborted: boolean;
readonly reason: any;
onabort: null | ((this: AbortSignal, event: Event) => any);
throwIfAborted(): void;
}
var AbortController: typeof globalThis extends { onmessage: any; AbortController: infer T } ? T
: {
prototype: AbortController;
new(): AbortController;
};
var AbortSignal: typeof globalThis extends { onmessage: any; AbortSignal: infer T } ? T
: {
prototype: AbortSignal;
new(): AbortSignal;
abort(reason?: any): AbortSignal;
timeout(milliseconds: number): AbortSignal;
};
// #endregion borrowed
|
// #region Disposable
interface SymbolConstructor {
/**
* A method that is used to release resources held by an object. Called by the semantics of the `using` statement.
*/
readonly dispose: unique symbol;
/**
* A method that is used to asynchronously release resources held by an object. Called by the semantics of the `await using` statement.
*/
readonly asyncDispose: unique symbol;
}
interface Disposable {
[Symbol.dispose](): void;
}
interface AsyncDisposable {
[Symbol.asyncDispose](): PromiseLike<void>;
}
// #endregion Disposable
// #region ArrayLike.at()
interface RelativeIndexable<T> {
/**
* Takes an integer value and returns the item at that index,
* allowing for positive and negative integers.
* Negative integers count back from the last item in the array.
*/
at(index: number): T | undefined;
}
interface String extends RelativeIndexable<string> {}
interface Array<T> extends RelativeIndexable<T> {}
interface ReadonlyArray<T> extends RelativeIndexable<T> {}
interface Int8Array extends RelativeIndexable<number> {}
interface Uint8Array extends RelativeIndexable<number> {}
interface Uint8ClampedArray extends RelativeIndexable<number> {}
interface Int16Array extends RelativeIndexable<number> {}
interface Uint16Array extends RelativeIndexable<number> {}
interface Int32Array extends RelativeIndexable<number> {}
interface Uint32Array extends RelativeIndexable<number> {}
interface Float32Array extends RelativeIndexable<number> {}
interface Float64Array extends RelativeIndexable<number> {}
interface BigInt64Array extends RelativeIndexable<bigint> {}
interface BigUint64Array extends RelativeIndexable<bigint> {}
// #endregion ArrayLike.at() end
/**
* @since v17.0.0
*
* Creates a deep clone of an object.
*/
function structuredClone<T>(
value: T,
transfer?: { transfer: ReadonlyArray<import("worker_threads").TransferListItem> },
): T;
/*----------------------------------------------*
* *
* GLOBAL INTERFACES *
* *
*-----------------------------------------------*/
namespace NodeJS {
interface CallSite {
/**
* Value of "this"
*/
getThis(): unknown;
/**
* Type of "this" as a string.
* This is the name of the function stored in the constructor field of
* "this", if available. Otherwise the object's [[Class]] internal
* property.
*/
getTypeName(): string | null;
/**
* Current function
*/
getFunction(): Function | undefined;
/**
* Name of the current function, typically its name property.
* If a name property is not available an attempt will be made to try
* to infer a name from the function's context.
*/
getFunctionName(): string | null;
/**
* Name of the property [of "this" or one of its prototypes] that holds
* the current function
*/
getMethodName(): string | null;
/**
* Name of the script [if this function was defined in a script]
*/
getFileName(): string | undefined;
/**
* Current line number [if this function was defined in a script]
*/
getLineNumber(): number | null;
/**
* Current column number [if this function was defined in a script]
*/
getColumnNumber(): number | null;
/**
* A call site object |
representing the location where eval was called
* [if this function was created using a call to eval]
*/
getEvalOrigin(): string | undefined;
/**
* Is this a toplevel invocation, that is, is "this" the global object?
*/
isToplevel(): boolean;
/**
* Does this call take place in code defined by a call to eval?
*/
isEval(): boolean;
/**
* Is this call in native V8 code?
*/
isNative(): boolean;
/**
* Is this a constructor call?
*/
isConstructor(): boolean;
/**
* is this an async call (i.e. await, Promise.all(), or Promise.any())?
*/
isAsync(): boolean;
/**
* is this an async call to Promise.all()?
*/
isPromiseAll(): boolean;
/**
* returns the index of the promise element that was followed in
* Promise.all() or Promise.any() for async stack traces, or null
* if the CallSite is not an async
*/
getPromiseIndex(): number | null;
getScriptNameOrSourceURL(): string;
getScriptHash(): string;
getEnclosingColumnNumber(): number;
getEnclosingLineNumber(): number;
getPosition(): number;
toString(): string;
}
interface ErrnoException extends Error {
errno?: number | undefined;
code?: string | undefined;
path?: string | undefined;
syscall?: string | undefined;
}
interface ReadableStream extends EventEmitter {
readable: boolean;
read(size?: number): string | Buffer;
setEncoding(encoding: BufferEncoding): this;
pause(): this;
resume(): this;
isPaused(): boolean;
pipe<T extends WritableStream>(destination: T, options?: { end?: boolean | undefined }): T;
unpipe(destination?: WritableStream): this;
unshift(chunk: string | Uint8Array, encoding?: BufferEncoding): void;
wrap(oldStream: ReadableStream): this;
[Symbol.asyncIterator](): AsyncIterableIterator<string | Buffer>;
}
interface WritableStream extends EventEmitter {
writable: boolean;
write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean;
write(str: string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean;
end(cb?: () => void): this;
end(data: string | Uint8Array, cb?: () => void): this;
end(str: string, encoding?: BufferEncoding, cb?: () => void): this;
}
interface ReadWriteStream extends ReadableStream, WritableStream {}
interface RefCounted {
ref(): this;
unref(): this;
}
type TypedArray =
| Uint8Array
| Uint8ClampedArray
| Uint16Array
| Uint32Array
| Int8Array
| Int16Array
| Int32Array
| BigUint64Array
| BigInt64Array
| Float32Array
| Float64Array;
type ArrayBufferView = TypedArray | DataView;
interface Require {
(id: string): any;
resolve: RequireResolve;
cache: Dict<NodeModule>;
/**
* @deprecated
*/
extensions: RequireExtensions;
main: Module | undefined;
}
interface RequireResolve {
(id: string, options?: { paths?: string[] | undefined }): string;
paths(request: string): string[] | null;
}
interface RequireExtensions extends Dict<(m: Module, filename: string) => any> {
".js": (m: Mo |
dule, filename: string) => any;
".json": (m: Module, filename: string) => any;
".node": (m: Module, filename: string) => any;
}
interface Module {
/**
* `true` if the module is running during the Node.js preload
*/
isPreloading: boolean;
exports: any;
require: Require;
id: string;
filename: string;
loaded: boolean;
/** @deprecated since v14.6.0 Please use `require.main` and `module.children` instead. */
parent: Module | null | undefined;
children: Module[];
/**
* @since v11.14.0
*
* The directory name of the module. This is usually the same as the path.dirname() of the module.id.
*/
path: string;
paths: string[];
}
interface Dict<T> {
[key: string]: T | undefined;
}
interface ReadOnlyDict<T> {
readonly [key: string]: T | undefined;
}
}
interface RequestInit extends _RequestInit {}
function fetch(
input: string | URL | globalThis.Request,
init?: RequestInit,
): Promise<Response>;
interface Request extends _Request {}
var Request: typeof globalThis extends {
onmessage: any;
Request: infer T;
} ? T
: typeof import("undici-types").Request;
interface ResponseInit extends _ResponseInit {}
interface Response extends _Response {}
var Response: typeof globalThis extends {
onmessage: any;
Response: infer T;
} ? T
: typeof import("undici-types").Response;
interface FormData extends _FormData {}
var FormData: typeof globalThis extends {
onmessage: any;
FormData: infer T;
} ? T
: typeof import("undici-types").FormData;
interface Headers extends _Headers {}
var Headers: typeof globalThis extends {
onmessage: any;
Headers: infer T;
} ? T
: typeof import("undici-types").Headers;
interface File extends _File {}
var File: typeof globalThis extends {
onmessage: any;
File: infer T;
} ? T
: typeof import("node:buffer").File;
}
|
/**
* The `node:string_decoder` module provides an API for decoding `Buffer` objects
* into strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16
* characters. It can be accessed using:
*
* ```js
* const { StringDecoder } = require('node:string_decoder');
* ```
*
* The following example shows the basic use of the `StringDecoder` class.
*
* ```js
* const { StringDecoder } = require('node:string_decoder');
* const decoder = new StringDecoder('utf8');
*
* const cent = Buffer.from([0xC2, 0xA2]);
* console.log(decoder.write(cent)); // Prints: ¢
*
* const euro = Buffer.from([0xE2, 0x82, 0xAC]);
* console.log(decoder.write(euro)); // Prints: €
* ```
*
* When a `Buffer` instance is written to the `StringDecoder` instance, an
* internal buffer is used to ensure that the decoded string does not contain
* any incomplete multibyte characters. These are held in the buffer until the
* next call to `stringDecoder.write()` or until `stringDecoder.end()` is called.
*
* In the following example, the three UTF-8 encoded bytes of the European Euro
* symbol (`€`) are written over three separate operations:
*
* ```js
* const { StringDecoder } = require('node:string_decoder');
* const decoder = new StringDecoder('utf8');
*
* decoder.write(Buffer.from([0xE2]));
* decoder.write(Buffer.from([0x82]));
* console.log(decoder.end(Buffer.from([0xAC]))); // Prints: €
* ```
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/string_decoder.js)
*/
declare module "string_decoder" {
class StringDecoder {
constructor(encoding?: BufferEncoding);
/**
* Returns a decoded string, ensuring that any incomplete multibyte characters at
* the end of the `Buffer`, or `TypedArray`, or `DataView` are omitted from the
* returned string and stored in an internal buffer for the next call to`stringDecoder.write()` or `stringDecoder.end()`.
* @since v0.1.99
* @param buffer The bytes to decode.
*/
write(buffer: string | Buffer | NodeJS.ArrayBufferView): string;
/**
* Returns any remaining input stored in the internal buffer as a string. Bytes
* representing incomplete UTF-8 and UTF-16 characters will be replaced with
* substitution characters appropriate for the character encoding.
*
* If the `buffer` argument is provided, one final call to `stringDecoder.write()`is performed before returning the remaining input.
* After `end()` is called, the `stringDecoder` object can be reused for new input.
* @since v0.9.3
* @param buffer The bytes to decode.
*/
end(buffer?: string | Buffer | NodeJS.ArrayBufferView): string;
}
}
declare module "node:string_decoder" {
export * from "string_decoder";
}
|
/**
* The `node:tls` module provides an implementation of the Transport Layer Security
* (TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL.
* The module can be accessed using:
*
* ```js
* const tls = require('node:tls');
* ```
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/tls.js)
*/
declare module "tls" {
import { X509Certificate } from "node:crypto";
import * as net from "node:net";
import * as stream from "stream";
const CLIENT_RENEG_LIMIT: number;
const CLIENT_RENEG_WINDOW: number;
interface Certificate {
/**
* Country code.
*/
C: string;
/**
* Street.
*/
ST: string;
/**
* Locality.
*/
L: string;
/**
* Organization.
*/
O: string;
/**
* Organizational unit.
*/
OU: string;
/**
* Common name.
*/
CN: string;
}
interface PeerCertificate {
/**
* `true` if a Certificate Authority (CA), `false` otherwise.
* @since v18.13.0
*/
ca: boolean;
/**
* The DER encoded X.509 certificate data.
*/
raw: Buffer;
/**
* The certificate subject.
*/
subject: Certificate;
/**
* The certificate issuer, described in the same terms as the `subject`.
*/
issuer: Certificate;
/**
* The date-time the certificate is valid from.
*/
valid_from: string;
/**
* The date-time the certificate is valid to.
*/
valid_to: string;
/**
* The certificate serial number, as a hex string.
*/
serialNumber: string;
/**
* The SHA-1 digest of the DER encoded certificate.
* It is returned as a `:` separated hexadecimal string.
*/
fingerprint: string;
/**
* The SHA-256 digest of the DER encoded certificate.
* It is returned as a `:` separated hexadecimal string.
*/
fingerprint256: string;
/**
* The SHA-512 digest of the DER encoded certificate.
* It is returned as a `:` separated hexadecimal string.
*/
fingerprint512: string;
/**
* The extended key usage, a set of OIDs.
*/
ext_key_usage?: string[];
/**
* A string containing concatenated names for the subject,
* an alternative to the `subject` names.
*/
subjectaltname?: string;
/**
* An array describing the AuthorityInfoAccess, used with OCSP.
*/
infoAccess?: NodeJS.Dict<string[]>;
/**
* For RSA keys: The RSA bit size.
*
* For EC keys: The key size in bits.
*/
bits?: number;
/**
* The RSA exponent, as a string in hexadecimal number notation.
*/
exponent?: string;
/**
* The RSA modulus, as a hexadecimal string.
*/
modulus?: string;
/**
* The public key.
*/
pubkey?: Buffer;
/**
* The ASN.1 name of the OID of the elliptic curve.
* Well-known curves are identified by an OID.
* While it is unusual, it is possible that the curve
* is identified by its mathematical properties,
* in which case it will not have an OID.
*/
asn1Curve?: string;
/**
* The NIST name for the elliptic curve,if it has one
* (not all well-known curves have been assigned names by NIST).
*/
nistCurve?: string;
}
interface DetailedPeerCertificate extends PeerCertificate {
/**
* The issuer certificate object.
* For self-signed certificates, this may be a circular reference.
*/
issuerCertificate |
: DetailedPeerCertificate;
}
interface CipherNameAndProtocol {
/**
* The cipher name.
*/
name: string;
/**
* SSL/TLS protocol version.
*/
version: string;
/**
* IETF name for the cipher suite.
*/
standardName: string;
}
interface EphemeralKeyInfo {
/**
* The supported types are 'DH' and 'ECDH'.
*/
type: string;
/**
* The name property is available only when type is 'ECDH'.
*/
name?: string | undefined;
/**
* The size of parameter of an ephemeral key exchange.
*/
size: number;
}
interface KeyObject {
/**
* Private keys in PEM format.
*/
pem: string | Buffer;
/**
* Optional passphrase.
*/
passphrase?: string | undefined;
}
interface PxfObject {
/**
* PFX or PKCS12 encoded private key and certificate chain.
*/
buf: string | Buffer;
/**
* Optional passphrase.
*/
passphrase?: string | undefined;
}
interface TLSSocketOptions extends SecureContextOptions, CommonConnectionOptions {
/**
* If true the TLS socket will be instantiated in server-mode.
* Defaults to false.
*/
isServer?: boolean | undefined;
/**
* An optional net.Server instance.
*/
server?: net.Server | undefined;
/**
* An optional Buffer instance containing a TLS session.
*/
session?: Buffer | undefined;
/**
* If true, specifies that the OCSP status request extension will be
* added to the client hello and an 'OCSPResponse' event will be
* emitted on the socket before establishing a secure communication
*/
requestOCSP?: boolean | undefined;
}
/**
* Performs transparent encryption of written data and all required TLS
* negotiation.
*
* Instances of `tls.TLSSocket` implement the duplex `Stream` interface.
*
* Methods that return TLS connection metadata (e.g.{@link TLSSocket.getPeerCertificate}) will only return data while the
* connection is open.
* @since v0.11.4
*/
class TLSSocket extends net.Socket {
/**
* Construct a new tls.TLSSocket object from an existing TCP socket.
*/
constructor(socket: net.Socket | stream.Duplex, options?: TLSSocketOptions);
/**
* This property is `true` if the peer certificate was signed by one of the CAs
* specified when creating the `tls.TLSSocket` instance, otherwise `false`.
* @since v0.11.4
*/
authorized: boolean;
/**
* Returns the reason why the peer's certificate was not been verified. This
* property is set only when `tlsSocket.authorized === false`.
* @since v0.11.4
*/
authorizationError: Error;
/**
* Always returns `true`. This may be used to distinguish TLS sockets from regular`net.Socket` instances.
* @since v0.11.4
*/
encrypted: true;
/**
* String containing the selected ALPN protocol.
* Before a handshake has completed, this value is always null.
* When a handshake is completed but not ALPN protocol was selected, tlsSocket.alpnProtocol equals false.
*/
alpnProtocol: string | false | null;
/**
* Returns an object representing the local certificate. The returned object has
* some properties corresponding to the fields of the certificate.
*
* See {@link TLSSocket.getPeerCertificate} for an example of the certificate
* structure.
*
* If there is no local certificate, an empty object will be returned. If the
* socket has been destroyed, `null |
` will be returned.
* @since v11.2.0
*/
getCertificate(): PeerCertificate | object | null;
/**
* Returns an object containing information on the negotiated cipher suite.
*
* For example, a TLSv1.2 protocol with AES256-SHA cipher:
*
* ```json
* {
* "name": "AES256-SHA",
* "standardName": "TLS_RSA_WITH_AES_256_CBC_SHA",
* "version": "SSLv3"
* }
* ```
*
* See [SSL\_CIPHER\_get\_name](https://www.openssl.org/docs/man1.1.1/man3/SSL_CIPHER_get_name.html) for more information.
* @since v0.11.4
*/
getCipher(): CipherNameAndProtocol;
/**
* Returns an object representing the type, name, and size of parameter of
* an ephemeral key exchange in `perfect forward secrecy` on a client
* connection. It returns an empty object when the key exchange is not
* ephemeral. As this is only supported on a client socket; `null` is returned
* if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The`name` property is available only when type is `'ECDH'`.
*
* For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`.
* @since v5.0.0
*/
getEphemeralKeyInfo(): EphemeralKeyInfo | object | null;
/**
* As the `Finished` messages are message digests of the complete handshake
* (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can
* be used for external authentication procedures when the authentication
* provided by SSL/TLS is not desired or is not enough.
*
* Corresponds to the `SSL_get_finished` routine in OpenSSL and may be used
* to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929).
* @since v9.9.0
* @return The latest `Finished` message that has been sent to the socket as part of a SSL/TLS handshake, or `undefined` if no `Finished` message has been sent yet.
*/
getFinished(): Buffer | undefined;
/**
* Returns an object representing the peer's certificate. If the peer does not
* provide a certificate, an empty object will be returned. If the socket has been
* destroyed, `null` will be returned.
*
* If the full certificate chain was requested, each certificate will include an`issuerCertificate` property containing an object representing its issuer's
* certificate.
* @since v0.11.4
* @param detailed Include the full certificate chain if `true`, otherwise include just the peer's certificate.
* @return A certificate object.
*/
getPeerCertificate(detailed: true): DetailedPeerCertificate;
getPeerCertificate(detailed?: false): PeerCertificate;
getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate;
/**
* As the `Finished` messages are message digests of the complete handshake
* (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can
* be used for external authentication procedures when the authentication
* provided by SSL/TLS is not desired or is not enough.
*
* Corresponds to the `SSL_get_peer_finished` routine in OpenSSL and may be used
* to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929).
* @since v9.9.0
* @return The latest `Finished` message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or `undefined` if there is no `Finished` message so
* far.
*/
getPeerFinished(): Buffer | undefined;
/**
* Returns a string containing the negotiated SSL/TLS protocol version of the
* current connection. The valu |
e `'unknown'` will be returned for connected
* sockets that have not completed the handshaking process. The value `null` will
* be returned for server sockets or disconnected client sockets.
*
* Protocol versions are:
*
* * `'SSLv3'`
* * `'TLSv1'`
* * `'TLSv1.1'`
* * `'TLSv1.2'`
* * `'TLSv1.3'`
*
* See the OpenSSL [`SSL_get_version`](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html) documentation for more information.
* @since v5.7.0
*/
getProtocol(): string | null;
/**
* Returns the TLS session data or `undefined` if no session was
* negotiated. On the client, the data can be provided to the `session` option of {@link connect} to resume the connection. On the server, it may be useful
* for debugging.
*
* See `Session Resumption` for more information.
*
* Note: `getSession()` works only for TLSv1.2 and below. For TLSv1.3, applications
* must use the `'session'` event (it also works for TLSv1.2 and below).
* @since v0.11.4
*/
getSession(): Buffer | undefined;
/**
* See [SSL\_get\_shared\_sigalgs](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_shared_sigalgs.html) for more information.
* @since v12.11.0
* @return List of signature algorithms shared between the server and the client in the order of decreasing preference.
*/
getSharedSigalgs(): string[];
/**
* For a client, returns the TLS session ticket if one is available, or`undefined`. For a server, always returns `undefined`.
*
* It may be useful for debugging.
*
* See `Session Resumption` for more information.
* @since v0.11.4
*/
getTLSTicket(): Buffer | undefined;
/**
* See `Session Resumption` for more information.
* @since v0.5.6
* @return `true` if the session was reused, `false` otherwise.
*/
isSessionReused(): boolean;
/**
* The `tlsSocket.renegotiate()` method initiates a TLS renegotiation process.
* Upon completion, the `callback` function will be passed a single argument
* that is either an `Error` (if the request failed) or `null`.
*
* This method can be used to request a peer's certificate after the secure
* connection has been established.
*
* When running as the server, the socket will be destroyed with an error after`handshakeTimeout` timeout.
*
* For TLSv1.3, renegotiation cannot be initiated, it is not supported by the
* protocol.
* @since v0.11.8
* @param callback If `renegotiate()` returned `true`, callback is attached once to the `'secure'` event. If `renegotiate()` returned `false`, `callback` will be called in the next tick with
* an error, unless the `tlsSocket` has been destroyed, in which case `callback` will not be called at all.
* @return `true` if renegotiation was initiated, `false` otherwise.
*/
renegotiate(
options: {
rejectUnauthorized?: boolean | undefined;
requestCert?: boolean | undefined;
},
callback: (err: Error | null) => void,
): undefined | boolean;
/**
* The `tlsSocket.setMaxSendFragment()` method sets the maximum TLS fragment size.
* Returns `true` if setting the limit succeeded; `false` otherwise.
*
* Smaller fragment sizes decrease the buffering latency on the client: larger
* fragments are buffered by the TLS layer until the entire fragment is received
* and its integrity is verified; large fragments can span multiple roundtrips
* and their processing can be delayed due to packet loss or reorderin |
g. However,
* smaller fragments add extra TLS framing bytes and CPU overhead, which may
* decrease overall server throughput.
* @since v0.11.11
* @param [size=16384] The maximum TLS fragment size. The maximum value is `16384`.
*/
setMaxSendFragment(size: number): boolean;
/**
* Disables TLS renegotiation for this `TLSSocket` instance. Once called, attempts
* to renegotiate will trigger an `'error'` event on the `TLSSocket`.
* @since v8.4.0
*/
disableRenegotiation(): void;
/**
* When enabled, TLS packet trace information is written to `stderr`. This can be
* used to debug TLS connection problems.
*
* The format of the output is identical to the output of`openssl s_client -trace` or `openssl s_server -trace`. While it is produced by
* OpenSSL's `SSL_trace()` function, the format is undocumented, can change
* without notice, and should not be relied on.
* @since v12.2.0
*/
enableTrace(): void;
/**
* Returns the peer certificate as an `X509Certificate` object.
*
* If there is no peer certificate, or the socket has been destroyed,`undefined` will be returned.
* @since v15.9.0
*/
getPeerX509Certificate(): X509Certificate | undefined;
/**
* Returns the local certificate as an `X509Certificate` object.
*
* If there is no local certificate, or the socket has been destroyed,`undefined` will be returned.
* @since v15.9.0
*/
getX509Certificate(): X509Certificate | undefined;
/**
* Keying material is used for validations to prevent different kind of attacks in
* network protocols, for example in the specifications of IEEE 802.1X.
*
* Example
*
* ```js
* const keyingMaterial = tlsSocket.exportKeyingMaterial(
* 128,
* 'client finished');
*
* /*
* Example return value of keyingMaterial:
* <Buffer 76 26 af 99 c5 56 8e 42 09 91 ef 9f 93 cb ad 6c 7b 65 f8 53 f1 d8 d9
* 12 5a 33 b8 b5 25 df 7b 37 9f e0 e2 4f b8 67 83 a3 2f cd 5d 41 42 4c 91
* 74 ef 2c ... 78 more bytes>
*
* ```
*
* See the OpenSSL [`SSL_export_keying_material`](https://www.openssl.org/docs/man1.1.1/man3/SSL_export_keying_material.html) documentation for more
* information.
* @since v13.10.0, v12.17.0
* @param length number of bytes to retrieve from keying material
* @param label an application specific label, typically this will be a value from the [IANA Exporter Label
* Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels).
* @param context Optionally provide a context.
* @return requested bytes of the keying material
*/
exportKeyingMaterial(length: number, label: string, context: Buffer): Buffer;
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this;
addListener(event: "secureConnect", listener: () => void): this;
addListener(event: "session", listener: (session: Buffer) => void): this;
addListener(event: "keylog", listener: (line: Buffer) => void): this;
emit(event: string | symbol, ...args: any[]): boolean;
emit(event: "OCSPResponse", response: Buffer): boolean;
emit(event: "secureConnect"): boolean;
emit(event: "session", session: Buffer): boolean;
emit(event: "keylog", line: Buffer): boolean;
on(event: string, listener: (...args: any[]) => void): this;
on(event: "OCSPResponse", listener: (response: Buffer) => void): this;
on(event: "secureConnect", listener: () |
=> void): this;
on(event: "session", listener: (session: Buffer) => void): this;
on(event: "keylog", listener: (line: Buffer) => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: "OCSPResponse", listener: (response: Buffer) => void): this;
once(event: "secureConnect", listener: () => void): this;
once(event: "session", listener: (session: Buffer) => void): this;
once(event: "keylog", listener: (line: Buffer) => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this;
prependListener(event: "secureConnect", listener: () => void): this;
prependListener(event: "session", listener: (session: Buffer) => void): this;
prependListener(event: "keylog", listener: (line: Buffer) => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this;
prependOnceListener(event: "secureConnect", listener: () => void): this;
prependOnceListener(event: "session", listener: (session: Buffer) => void): this;
prependOnceListener(event: "keylog", listener: (line: Buffer) => void): this;
}
interface CommonConnectionOptions {
/**
* An optional TLS context object from tls.createSecureContext()
*/
secureContext?: SecureContext | undefined;
/**
* When enabled, TLS packet trace information is written to `stderr`. This can be
* used to debug TLS connection problems.
* @default false
*/
enableTrace?: boolean | undefined;
/**
* If true the server will request a certificate from clients that
* connect and attempt to verify that certificate. Defaults to
* false.
*/
requestCert?: boolean | undefined;
/**
* An array of strings or a Buffer naming possible ALPN protocols.
* (Protocols should be ordered by their priority.)
*/
ALPNProtocols?: string[] | Uint8Array[] | Uint8Array | undefined;
/**
* SNICallback(servername, cb) <Function> A function that will be
* called if the client supports SNI TLS extension. Two arguments
* will be passed when called: servername and cb. SNICallback should
* invoke cb(null, ctx), where ctx is a SecureContext instance.
* (tls.createSecureContext(...) can be used to get a proper
* SecureContext.) If SNICallback wasn't provided the default callback
* with high-level API will be used (see below).
*/
SNICallback?: ((servername: string, cb: (err: Error | null, ctx?: SecureContext) => void) => void) | undefined;
/**
* If true the server will reject any connection which is not
* authorized with the list of supplied CAs. This option only has an
* effect if requestCert is true.
* @default true
*/
rejectUnauthorized?: boolean | undefined;
}
interface TlsOptions extends SecureContextOptions, CommonConnectionOptions, net.ServerOpts {
/**
* Abort the connection if the SSL/TLS handshake does not finish in the
* specified number of milliseconds. A 'tlsClientError' is emitted on
* the tls.Server object whenever a handshake times out. Default:
* 120000 (120 seconds).
*/
handshakeTimeout?: number | undefined;
/**
* The number of seconds after which a TLS session created by the
* server will no longer be resumable. See Session Resumption for more
* information. Default: 300.
*/
sessionTimeout?: number | undefined;
/**
* 48-bytes of cryptographically strong pseudo-random data.
*/
|
ticketKeys?: Buffer | undefined;
/**
* @param socket
* @param identity identity parameter sent from the client.
* @return pre-shared key that must either be
* a buffer or `null` to stop the negotiation process. Returned PSK must be
* compatible with the selected cipher's digest.
*
* When negotiating TLS-PSK (pre-shared keys), this function is called
* with the identity provided by the client.
* If the return value is `null` the negotiation process will stop and an
* "unknown_psk_identity" alert message will be sent to the other party.
* If the server wishes to hide the fact that the PSK identity was not known,
* the callback must provide some random data as `psk` to make the connection
* fail with "decrypt_error" before negotiation is finished.
* PSK ciphers are disabled by default, and using TLS-PSK thus
* requires explicitly specifying a cipher suite with the `ciphers` option.
* More information can be found in the RFC 4279.
*/
pskCallback?(socket: TLSSocket, identity: string): DataView | NodeJS.TypedArray | null;
/**
* hint to send to a client to help
* with selecting the identity during TLS-PSK negotiation. Will be ignored
* in TLS 1.3. Upon failing to set pskIdentityHint `tlsClientError` will be
* emitted with `ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED` code.
*/
pskIdentityHint?: string | undefined;
}
interface PSKCallbackNegotation {
psk: DataView | NodeJS.TypedArray;
identity: string;
}
interface ConnectionOptions extends SecureContextOptions, CommonConnectionOptions {
host?: string | undefined;
port?: number | undefined;
path?: string | undefined; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored.
socket?: stream.Duplex | undefined; // Establish secure connection on a given socket rather than creating a new socket
checkServerIdentity?: typeof checkServerIdentity | undefined;
servername?: string | undefined; // SNI TLS Extension
session?: Buffer | undefined;
minDHSize?: number | undefined;
lookup?: net.LookupFunction | undefined;
timeout?: number | undefined;
/**
* When negotiating TLS-PSK (pre-shared keys), this function is called
* with optional identity `hint` provided by the server or `null`
* in case of TLS 1.3 where `hint` was removed.
* It will be necessary to provide a custom `tls.checkServerIdentity()`
* for the connection as the default one will try to check hostname/IP
* of the server against the certificate but that's not applicable for PSK
* because there won't be a certificate present.
* More information can be found in the RFC 4279.
*
* @param hint message sent from the server to help client
* decide which identity to use during negotiation.
* Always `null` if TLS 1.3 is used.
* @returns Return `null` to stop the negotiation process. `psk` must be
* compatible with the selected cipher's digest.
* `identity` must use UTF-8 encoding.
*/
pskCallback?(hint: string | null): PSKCallbackNegotation | null;
}
/**
* Accepts encrypted connections using TLS or SSL.
* @since v0.3.2
*/
class Server extends net.Server {
constructor(secureConnectionListener?: (socket: TLSSocket) => void);
constructor(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void);
/**
* The `server.addContext()` method adds a secure context that will be used if
* the client request's SNI name matches the supplied `hostname` (or wildcard).
*
* When there are multiple matching contexts, the most rec |
ently added one is
* used.
* @since v0.5.3
* @param hostname A SNI host name or wildcard (e.g. `'*'`)
* @param context An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc), or a TLS context object created
* with {@link createSecureContext} itself.
*/
addContext(hostname: string, context: SecureContextOptions): void;
/**
* Returns the session ticket keys.
*
* See `Session Resumption` for more information.
* @since v3.0.0
* @return A 48-byte buffer containing the session ticket keys.
*/
getTicketKeys(): Buffer;
/**
* The `server.setSecureContext()` method replaces the secure context of an
* existing server. Existing connections to the server are not interrupted.
* @since v11.0.0
* @param options An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc).
*/
setSecureContext(options: SecureContextOptions): void;
/**
* Sets the session ticket keys.
*
* Changes to the ticket keys are effective only for future server connections.
* Existing or currently pending server connections will use the previous keys.
*
* See `Session Resumption` for more information.
* @since v3.0.0
* @param keys A 48-byte buffer containing the session ticket keys.
*/
setTicketKeys(keys: Buffer): void;
/**
* events.EventEmitter
* 1. tlsClientError
* 2. newSession
* 3. OCSPRequest
* 4. resumeSession
* 5. secureConnection
* 6. keylog
*/
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this;
addListener(
event: "newSession",
listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void,
): this;
addListener(
event: "OCSPRequest",
listener: (
certificate: Buffer,
issuer: Buffer,
callback: (err: Error | null, resp: Buffer) => void,
) => void,
): this;
addListener(
event: "resumeSession",
listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void,
): this;
addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this;
addListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this;
emit(event: string | symbol, ...args: any[]): boolean;
emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean;
emit(event: "newSession", sessionId: Buffer, sessionData: Buffer, callback: () => void): boolean;
emit(
event: "OCSPRequest",
certificate: Buffer,
issuer: Buffer,
callback: (err: Error | null, resp: Buffer) => void,
): boolean;
emit(
event: "resumeSession",
sessionId: Buffer,
callback: (err: Error | null, sessionData: Buffer | null) => void,
): boolean;
emit(event: "secureConnection", tlsSocket: TLSSocket): boolean;
emit(event: "keylog", line: Buffer, tlsSocket: TLSSocket): boolean;
on(event: string, listener: (...args: any[]) => void): this;
on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this;
on(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void): this;
on(
event: "OCSPRequest",
listener: (
|
certificate: Buffer,
issuer: Buffer,
callback: (err: Error | null, resp: Buffer) => void,
) => void,
): this;
on(
event: "resumeSession",
listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void,
): this;
on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this;
on(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this;
once(
event: "newSession",
listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void,
): this;
once(
event: "OCSPRequest",
listener: (
certificate: Buffer,
issuer: Buffer,
callback: (err: Error | null, resp: Buffer) => void,
) => void,
): this;
once(
event: "resumeSession",
listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void,
): this;
once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this;
once(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this;
prependListener(
event: "newSession",
listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void,
): this;
prependListener(
event: "OCSPRequest",
listener: (
certificate: Buffer,
issuer: Buffer,
callback: (err: Error | null, resp: Buffer) => void,
) => void,
): this;
prependListener(
event: "resumeSession",
listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void,
): this;
prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this;
prependListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this;
prependOnceListener(
event: "newSession",
listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void,
): this;
prependOnceListener(
event: "OCSPRequest",
listener: (
certificate: Buffer,
issuer: Buffer,
callback: (err: Error | null, resp: Buffer) => void,
) => void,
): this;
prependOnceListener(
event: "resumeSession",
listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void,
): this;
prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this;
prependOnceListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this;
}
/**
* @deprecated since v0.11.3 Use `tls.TLSSocket` instead.
*/
interface SecurePair {
encrypted: TLSSocket;
cleartext: TLSSocket;
}
type SecureVersion = "TLSv1.3" | "TLSv1.2" | "TLSv1.1" | "TLSv1";
interface SecureContextOptions {
/**
* If set, this will be called when a client opens a connection using the ALPN extension.
* One argument will be passed to the callback: an obj |
ect containing `servername` and `protocols` fields,
* respectively containing the server name from the SNI extension (if any) and an array of
* ALPN protocol name strings. The callback must return either one of the strings listed in `protocols`,
* which will be returned to the client as the selected ALPN protocol, or `undefined`,
* to reject the connection with a fatal alert. If a string is returned that does not match one of
* the client's ALPN protocols, an error will be thrown.
* This option cannot be used with the `ALPNProtocols` option, and setting both options will throw an error.
*/
ALPNCallback?: ((arg: { servername: string; protocols: string[] }) => string | undefined) | undefined;
/**
* Optionally override the trusted CA certificates. Default is to trust
* the well-known CAs curated by Mozilla. Mozilla's CAs are completely
* replaced when CAs are explicitly specified using this option.
*/
ca?: string | Buffer | Array<string | Buffer> | undefined;
/**
* Cert chains in PEM format. One cert chain should be provided per
* private key. Each cert chain should consist of the PEM formatted
* certificate for a provided private key, followed by the PEM
* formatted intermediate certificates (if any), in order, and not
* including the root CA (the root CA must be pre-known to the peer,
* see ca). When providing multiple cert chains, they do not have to
* be in the same order as their private keys in key. If the
* intermediate certificates are not provided, the peer will not be
* able to validate the certificate, and the handshake will fail.
*/
cert?: string | Buffer | Array<string | Buffer> | undefined;
/**
* Colon-separated list of supported signature algorithms. The list
* can contain digest algorithms (SHA256, MD5 etc.), public key
* algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g
* 'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512).
*/
sigalgs?: string | undefined;
/**
* Cipher suite specification, replacing the default. For more
* information, see modifying the default cipher suite. Permitted
* ciphers can be obtained via tls.getCiphers(). Cipher names must be
* uppercased in order for OpenSSL to accept them.
*/
ciphers?: string | undefined;
/**
* Name of an OpenSSL engine which can provide the client certificate.
*/
clientCertEngine?: string | undefined;
/**
* PEM formatted CRLs (Certificate Revocation Lists).
*/
crl?: string | Buffer | Array<string | Buffer> | undefined;
/**
* `'auto'` or custom Diffie-Hellman parameters, required for non-ECDHE perfect forward secrecy.
* If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available.
* ECDHE-based perfect forward secrecy will still be available.
*/
dhparam?: string | Buffer | undefined;
/**
* A string describing a named curve or a colon separated list of curve
* NIDs or names, for example P-521:P-384:P-256, to use for ECDH key
* agreement. Set to auto to select the curve automatically. Use
* crypto.getCurves() to obtain a list of available curve names. On
* recent releases, openssl ecparam -list_curves will also display the
* name and description of each available elliptic curve. Default:
* tls.DEFAULT_ECDH_CURVE.
*/
ecdhCurve?: string | undefined;
/**
* Attempt to use the server's cipher suite preferences instead of the
* client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be
* set in secureOptions
|
*/
honorCipherOrder?: boolean | undefined;
/**
* Private keys in PEM format. PEM allows the option of private keys
* being encrypted. Encrypted keys will be decrypted with
* options.passphrase. Multiple keys using different algorithms can be
* provided either as an array of unencrypted key strings or buffers,
* or an array of objects in the form {pem: <string|buffer>[,
* passphrase: <string>]}. The object form can only occur in an array.
* object.passphrase is optional. Encrypted keys will be decrypted with
* object.passphrase if provided, or options.passphrase if it is not.
*/
key?: string | Buffer | Array<string | Buffer | KeyObject> | undefined;
/**
* Name of an OpenSSL engine to get private key from. Should be used
* together with privateKeyIdentifier.
*/
privateKeyEngine?: string | undefined;
/**
* Identifier of a private key managed by an OpenSSL engine. Should be
* used together with privateKeyEngine. Should not be set together with
* key, because both options define a private key in different ways.
*/
privateKeyIdentifier?: string | undefined;
/**
* Optionally set the maximum TLS version to allow. One
* of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the
* `secureProtocol` option, use one or the other.
* **Default:** `'TLSv1.3'`, unless changed using CLI options. Using
* `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to
* `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used.
*/
maxVersion?: SecureVersion | undefined;
/**
* Optionally set the minimum TLS version to allow. One
* of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the
* `secureProtocol` option, use one or the other. It is not recommended to use
* less than TLSv1.2, but it may be required for interoperability.
* **Default:** `'TLSv1.2'`, unless changed using CLI options. Using
* `--tls-v1.0` sets the default to `'TLSv1'`. Using `--tls-v1.1` sets the default to
* `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to
* 'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used.
*/
minVersion?: SecureVersion | undefined;
/**
* Shared passphrase used for a single private key and/or a PFX.
*/
passphrase?: string | undefined;
/**
* PFX or PKCS12 encoded private key and certificate chain. pfx is an
* alternative to providing key and cert individually. PFX is usually
* encrypted, if it is, passphrase will be used to decrypt it. Multiple
* PFX can be provided either as an array of unencrypted PFX buffers,
* or an array of objects in the form {buf: <string|buffer>[,
* passphrase: <string>]}. The object form can only occur in an array.
* object.passphrase is optional. Encrypted PFX will be decrypted with
* object.passphrase if provided, or options.passphrase if it is not.
*/
pfx?: string | Buffer | Array<string | Buffer | PxfObject> | undefined;
/**
* Optionally affect the OpenSSL protocol behavior, which is not
* usually necessary. This should be used carefully if at all! Value is
* a numeric bitmask of the SSL_OP_* options from OpenSSL Options
*/
secureOptions?: number | undefined; // Value is a numeric bitmask of the `SSL_OP_*` options
/**
* Legacy mechanism to select the TLS protocol version to use, it does
* not support independent control of the minimum and maximum version,
* and does not support limiting the |
protocol to TLSv1.3. Use
* minVersion and maxVersion instead. The possible values are listed as
* SSL_METHODS, use the function names as strings. For example, use
* 'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow
* any TLS protocol version up to TLSv1.3. It is not recommended to use
* TLS versions less than 1.2, but it may be required for
* interoperability. Default: none, see minVersion.
*/
secureProtocol?: string | undefined;
/**
* Opaque identifier used by servers to ensure session state is not
* shared between applications. Unused by clients.
*/
sessionIdContext?: string | undefined;
/**
* 48-bytes of cryptographically strong pseudo-random data.
* See Session Resumption for more information.
*/
ticketKeys?: Buffer | undefined;
/**
* The number of seconds after which a TLS session created by the
* server will no longer be resumable. See Session Resumption for more
* information. Default: 300.
*/
sessionTimeout?: number | undefined;
}
interface SecureContext {
context: any;
}
/**
* Verifies the certificate `cert` is issued to `hostname`.
*
* Returns [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object, populating it with `reason`, `host`, and `cert` on
* failure. On success, returns [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type).
*
* This function is intended to be used in combination with the`checkServerIdentity` option that can be passed to {@link connect} and as
* such operates on a `certificate object`. For other purposes, consider using `x509.checkHost()` instead.
*
* This function can be overwritten by providing an alternative function as the`options.checkServerIdentity` option that is passed to `tls.connect()`. The
* overwriting function can call `tls.checkServerIdentity()` of course, to augment
* the checks done with additional verification.
*
* This function is only called if the certificate passed all other checks, such as
* being issued by trusted CA (`options.ca`).
*
* Earlier versions of Node.js incorrectly accepted certificates for a given`hostname` if a matching `uniformResourceIdentifier` subject alternative name
* was present (see [CVE-2021-44531](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44531)). Applications that wish to accept`uniformResourceIdentifier` subject alternative names can use
* a custom`options.checkServerIdentity` function that implements the desired behavior.
* @since v0.8.4
* @param hostname The host name or IP address to verify the certificate against.
* @param cert A `certificate object` representing the peer's certificate.
*/
function checkServerIdentity(hostname: string, cert: PeerCertificate): Error | undefined;
/**
* Creates a new {@link Server}. The `secureConnectionListener`, if provided, is
* automatically set as a listener for the `'secureConnection'` event.
*
* The `ticketKeys` options is automatically shared between `node:cluster` module
* workers.
*
* The following illustrates a simple echo server:
*
* ```js
* const tls = require('node:tls');
* const fs = require('node:fs');
*
* const options = {
* key: fs.readFileSync('server-key.pem'),
* cert: fs.readFileSync('server-cert.pem'),
*
* // This is necessary only if using client certificate authentication.
* requestCert: true,
*
* // This is necessary only if the client uses a self-signed certificate.
* ca: [ fs.readFileSync('client-cert.pem') ],
* };
*
* const server = tls.createServer(options, (socket) => {
* conso |
le.log('server connected',
* socket.authorized ? 'authorized' : 'unauthorized');
* socket.write('welcome!\n');
* socket.setEncoding('utf8');
* socket.pipe(socket);
* });
* server.listen(8000, () => {
* console.log('server bound');
* });
* ```
*
* The server can be tested by connecting to it using the example client from {@link connect}.
* @since v0.3.2
*/
function createServer(secureConnectionListener?: (socket: TLSSocket) => void): Server;
function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server;
/**
* The `callback` function, if specified, will be added as a listener for the `'secureConnect'` event.
*
* `tls.connect()` returns a {@link TLSSocket} object.
*
* Unlike the `https` API, `tls.connect()` does not enable the
* SNI (Server Name Indication) extension by default, which may cause some
* servers to return an incorrect certificate or reject the connection
* altogether. To enable SNI, set the `servername` option in addition
* to `host`.
*
* The following illustrates a client for the echo server example from {@link createServer}:
*
* ```js
* // Assumes an echo server that is listening on port 8000.
* const tls = require('node:tls');
* const fs = require('node:fs');
*
* const options = {
* // Necessary only if the server requires client certificate authentication.
* key: fs.readFileSync('client-key.pem'),
* cert: fs.readFileSync('client-cert.pem'),
*
* // Necessary only if the server uses a self-signed certificate.
* ca: [ fs.readFileSync('server-cert.pem') ],
*
* // Necessary only if the server's cert isn't for "localhost".
* checkServerIdentity: () => { return null; },
* };
*
* const socket = tls.connect(8000, options, () => {
* console.log('client connected',
* socket.authorized ? 'authorized' : 'unauthorized');
* process.stdin.pipe(socket);
* process.stdin.resume();
* });
* socket.setEncoding('utf8');
* socket.on('data', (data) => {
* console.log(data);
* });
* socket.on('end', () => {
* console.log('server ends connection');
* });
* ```
* @since v0.11.3
*/
function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket;
function connect(
port: number,
host?: string,
options?: ConnectionOptions,
secureConnectListener?: () => void,
): TLSSocket;
function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket;
/**
* Creates a new secure pair object with two streams, one of which reads and writes
* the encrypted data and the other of which reads and writes the cleartext data.
* Generally, the encrypted stream is piped to/from an incoming encrypted data
* stream and the cleartext one is used as a replacement for the initial encrypted
* stream.
*
* `tls.createSecurePair()` returns a `tls.SecurePair` object with `cleartext` and`encrypted` stream properties.
*
* Using `cleartext` has the same API as {@link TLSSocket}.
*
* The `tls.createSecurePair()` method is now deprecated in favor of`tls.TLSSocket()`. For example, the code:
*
* ```js
* pair = tls.createSecurePair(// ... );
* pair.encrypted.pipe(socket);
* socket.pipe(pair.encrypted);
* ```
*
* can be replaced by:
*
* ```js
* secureSocket = tls.TLSSocket(socket, options);
* ```
*
* where `secureSocket` has the same API as `pair.cleartext`.
* @since v0.3.2
* @deprecated Since v0.11.3 - Use {@link TLSSocket} instead.
* @param context A secure context object as returned by `tls.createSecureContext()`
* @param is |
Server `true` to specify that this TLS connection should be opened as a server.
* @param requestCert `true` to specify whether a server should request a certificate from a connecting client. Only applies when `isServer` is `true`.
* @param rejectUnauthorized If not `false` a server automatically reject clients with invalid certificates. Only applies when `isServer` is `true`.
*/
function createSecurePair(
context?: SecureContext,
isServer?: boolean,
requestCert?: boolean,
rejectUnauthorized?: boolean,
): SecurePair;
/**
* {@link createServer} sets the default value of the `honorCipherOrder` option
* to `true`, other APIs that create secure contexts leave it unset.
*
* {@link createServer} uses a 128 bit truncated SHA1 hash value generated
* from `process.argv` as the default value of the `sessionIdContext` option, other
* APIs that create secure contexts have no default value.
*
* The `tls.createSecureContext()` method creates a `SecureContext` object. It is
* usable as an argument to several `tls` APIs, such as `server.addContext()`,
* but has no public methods. The {@link Server} constructor and the {@link createServer} method do not support the `secureContext` option.
*
* A key is _required_ for ciphers that use certificates. Either `key` or`pfx` can be used to provide it.
*
* If the `ca` option is not given, then Node.js will default to using [Mozilla's publicly trusted list of
* CAs](https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt).
*
* Custom DHE parameters are discouraged in favor of the new `dhparam: 'auto'`option. When set to `'auto'`, well-known DHE parameters of sufficient strength
* will be selected automatically. Otherwise, if necessary, `openssl dhparam` can
* be used to create custom parameters. The key length must be greater than or
* equal to 1024 bits or else an error will be thrown. Although 1024 bits is
* permissible, use 2048 bits or larger for stronger security.
* @since v0.11.13
*/
function createSecureContext(options?: SecureContextOptions): SecureContext;
/**
* Returns an array with the names of the supported TLS ciphers. The names are
* lower-case for historical reasons, but must be uppercased to be used in
* the `ciphers` option of {@link createSecureContext}.
*
* Not all supported ciphers are enabled by default. See `Modifying the default TLS cipher suite`.
*
* Cipher names that start with `'tls_'` are for TLSv1.3, all the others are for
* TLSv1.2 and below.
*
* ```js
* console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...]
* ```
* @since v0.10.2
*/
function getCiphers(): string[];
/**
* The default curve name to use for ECDH key agreement in a tls server.
* The default value is 'auto'. See tls.createSecureContext() for further
* information.
*/
let DEFAULT_ECDH_CURVE: string;
/**
* The default value of the maxVersion option of
* tls.createSecureContext(). It can be assigned any of the supported TLS
* protocol versions, 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default:
* 'TLSv1.3', unless changed using CLI options. Using --tls-max-v1.2 sets
* the default to 'TLSv1.2'. Using --tls-max-v1.3 sets the default to
* 'TLSv1.3'. If multiple of the options are provided, the highest maximum
* is used.
*/
let DEFAULT_MAX_VERSION: SecureVersion;
/**
* The default value of the minVersion option of tls.createSecureContext().
* It can be assigned any of the supported TLS protocol versions,
* 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: 'TLSv1.2', unless
* changed using CLI options. Using --tls-min-v1.0 sets the default to
* 'TLSv1'. Using --tls-min-v1.1 sets the default to 'TLSv1. |
1'. Using
* --tls-min-v1.3 sets the default to 'TLSv1.3'. If multiple of the options
* are provided, the lowest minimum is used.
*/
let DEFAULT_MIN_VERSION: SecureVersion;
/**
* The default value of the ciphers option of tls.createSecureContext().
* It can be assigned any of the supported OpenSSL ciphers.
* Defaults to the content of crypto.constants.defaultCoreCipherList, unless
* changed using CLI options using --tls-default-ciphers.
*/
let DEFAULT_CIPHERS: string;
/**
* An immutable array of strings representing the root certificates (in PEM
* format) used for verifying peer certificates. This is the default value
* of the ca option to tls.createSecureContext().
*/
const rootCertificates: readonly string[];
}
declare module "node:tls" {
export * from "tls";
}
|
/**
* The `node:tty` module provides the `tty.ReadStream` and `tty.WriteStream`classes. In most cases, it will not be necessary or possible to use this module
* directly. However, it can be accessed using:
*
* ```js
* const tty = require('node:tty');
* ```
*
* When Node.js detects that it is being run with a text terminal ("TTY")
* attached, `process.stdin` will, by default, be initialized as an instance of`tty.ReadStream` and both `process.stdout` and `process.stderr` will, by
* default, be instances of `tty.WriteStream`. The preferred method of determining
* whether Node.js is being run within a TTY context is to check that the value of
* the `process.stdout.isTTY` property is `true`:
*
* ```console
* $ node -p -e "Boolean(process.stdout.isTTY)"
* true
* $ node -p -e "Boolean(process.stdout.isTTY)" | cat
* false
* ```
*
* In most cases, there should be little to no reason for an application to
* manually create instances of the `tty.ReadStream` and `tty.WriteStream`classes.
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/tty.js)
*/
declare module "tty" {
import * as net from "node:net";
/**
* The `tty.isatty()` method returns `true` if the given `fd` is associated with
* a TTY and `false` if it is not, including whenever `fd` is not a non-negative
* integer.
* @since v0.5.8
* @param fd A numeric file descriptor
*/
function isatty(fd: number): boolean;
/**
* Represents the readable side of a TTY. In normal circumstances `process.stdin` will be the only `tty.ReadStream` instance in a Node.js
* process and there should be no reason to create additional instances.
* @since v0.5.8
*/
class ReadStream extends net.Socket {
constructor(fd: number, options?: net.SocketConstructorOpts);
/**
* A `boolean` that is `true` if the TTY is currently configured to operate as a
* raw device.
*
* This flag is always `false` when a process starts, even if the terminal is
* operating in raw mode. Its value will change with subsequent calls to`setRawMode`.
* @since v0.7.7
*/
isRaw: boolean;
/**
* Allows configuration of `tty.ReadStream` so that it operates as a raw device.
*
* When in raw mode, input is always available character-by-character, not
* including modifiers. Additionally, all special processing of characters by the
* terminal is disabled, including echoing input
* characters. Ctrl+C will no longer cause a `SIGINT` when
* in this mode.
* @since v0.7.7
* @param mode If `true`, configures the `tty.ReadStream` to operate as a raw device. If `false`, configures the `tty.ReadStream` to operate in its default mode. The `readStream.isRaw`
* property will be set to the resulting mode.
* @return The read stream instance.
*/
setRawMode(mode: boolean): this;
/**
* A `boolean` that is always `true` for `tty.ReadStream` instances.
* @since v0.5.8
*/
isTTY: boolean;
}
/**
* -1 - to the left from cursor
* 0 - the entire line
* 1 - to the right from cursor
*/
type Direction = -1 | 0 | 1;
/**
* Represents the writable side of a TTY. In normal circumstances,`process.stdout` and `process.stderr` will be the only`tty.WriteStream` instances created for a Node.js process and there
* should be no reason to create additional instances.
* @since v0.5.8
*/
class WriteStream extends net.Socket {
constructor(fd: number);
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: "resize", listener: () => void): this;
emit(event: string | symbol, ...args: any[]): boolean;
emit(event: "resize"): boolean;
on(event: string, listener: (...args: any[]) => void): this;
|
on(event: "resize", listener: () => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: "resize", listener: () => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: "resize", listener: () => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: "resize", listener: () => void): this;
/**
* `writeStream.clearLine()` clears the current line of this `WriteStream` in a
* direction identified by `dir`.
* @since v0.7.7
* @param callback Invoked once the operation completes.
* @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.
*/
clearLine(dir: Direction, callback?: () => void): boolean;
/**
* `writeStream.clearScreenDown()` clears this `WriteStream` from the current
* cursor down.
* @since v0.7.7
* @param callback Invoked once the operation completes.
* @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.
*/
clearScreenDown(callback?: () => void): boolean;
/**
* `writeStream.cursorTo()` moves this `WriteStream`'s cursor to the specified
* position.
* @since v0.7.7
* @param callback Invoked once the operation completes.
* @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.
*/
cursorTo(x: number, y?: number, callback?: () => void): boolean;
cursorTo(x: number, callback: () => void): boolean;
/**
* `writeStream.moveCursor()` moves this `WriteStream`'s cursor _relative_ to its
* current position.
* @since v0.7.7
* @param callback Invoked once the operation completes.
* @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.
*/
moveCursor(dx: number, dy: number, callback?: () => void): boolean;
/**
* Returns:
*
* * `1` for 2,
* * `4` for 16,
* * `8` for 256,
* * `24` for 16,777,216 colors supported.
*
* Use this to determine what colors the terminal supports. Due to the nature of
* colors in terminals it is possible to either have false positives or false
* negatives. It depends on process information and the environment variables that
* may lie about what terminal is used.
* It is possible to pass in an `env` object to simulate the usage of a specific
* terminal. This can be useful to check how specific environment settings behave.
*
* To enforce a specific color support, use one of the below environment settings.
*
* * 2 colors: `FORCE_COLOR = 0` (Disables colors)
* * 16 colors: `FORCE_COLOR = 1`
* * 256 colors: `FORCE_COLOR = 2`
* * 16,777,216 colors: `FORCE_COLOR = 3`
*
* Disabling color support is also possible by using the `NO_COLOR` and`NODE_DISABLE_COLORS` environment variables.
* @since v9.9.0
* @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal.
*/
getColorDepth(env?: object): number;
/**
* Returns `true` if the `writeStream` supports at least as many colors as provided
* in `count`. Minimum support is 2 (black and white).
*
* This h |
as the same false positives and negatives as described in `writeStream.getColorDepth()`.
*
* ```js
* process.stdout.hasColors();
* // Returns true or false depending on if `stdout` supports at least 16 colors.
* process.stdout.hasColors(256);
* // Returns true or false depending on if `stdout` supports at least 256 colors.
* process.stdout.hasColors({ TMUX: '1' });
* // Returns true.
* process.stdout.hasColors(2 ** 24, { TMUX: '1' });
* // Returns false (the environment setting pretends to support 2 ** 8 colors).
* ```
* @since v11.13.0, v10.16.0
* @param [count=16] The number of colors that are requested (minimum 2).
* @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal.
*/
hasColors(count?: number): boolean;
hasColors(env?: object): boolean;
hasColors(count: number, env?: object): boolean;
/**
* `writeStream.getWindowSize()` returns the size of the TTY
* corresponding to this `WriteStream`. The array is of the type`[numColumns, numRows]` where `numColumns` and `numRows` represent the number
* of columns and rows in the corresponding TTY.
* @since v0.7.7
*/
getWindowSize(): [number, number];
/**
* A `number` specifying the number of columns the TTY currently has. This property
* is updated whenever the `'resize'` event is emitted.
* @since v0.7.7
*/
columns: number;
/**
* A `number` specifying the number of rows the TTY currently has. This property
* is updated whenever the `'resize'` event is emitted.
* @since v0.7.7
*/
rows: number;
/**
* A `boolean` that is always `true`.
* @since v0.5.8
*/
isTTY: boolean;
}
}
declare module "node:tty" {
export * from "tty";
}
|
/**
* **The version of the punycode module bundled in Node.js is being deprecated.**In a future major version of Node.js this module will be removed. Users
* currently depending on the `punycode` module should switch to using the
* userland-provided [Punycode.js](https://github.com/bestiejs/punycode.js) module instead. For punycode-based URL
* encoding, see `url.domainToASCII` or, more generally, the `WHATWG URL API`.
*
* The `punycode` module is a bundled version of the [Punycode.js](https://github.com/bestiejs/punycode.js) module. It
* can be accessed using:
*
* ```js
* const punycode = require('punycode');
* ```
*
* [Punycode](https://tools.ietf.org/html/rfc3492) is a character encoding scheme defined by RFC 3492 that is
* primarily intended for use in Internationalized Domain Names. Because host
* names in URLs are limited to ASCII characters only, Domain Names that contain
* non-ASCII characters must be converted into ASCII using the Punycode scheme.
* For instance, the Japanese character that translates into the English word,`'example'` is `'例'`. The Internationalized Domain Name, `'例.com'` (equivalent
* to `'example.com'`) is represented by Punycode as the ASCII string`'xn--fsq.com'`.
*
* The `punycode` module provides a simple implementation of the Punycode standard.
*
* The `punycode` module is a third-party dependency used by Node.js and
* made available to developers as a convenience. Fixes or other modifications to
* the module must be directed to the [Punycode.js](https://github.com/bestiejs/punycode.js) project.
* @deprecated Since v7.0.0 - Deprecated
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/punycode.js)
*/
declare module "punycode" {
/**
* The `punycode.decode()` method converts a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only
* characters to the equivalent string of Unicode codepoints.
*
* ```js
* punycode.decode('maana-pta'); // 'mañana'
* punycode.decode('--dqo34k'); // '☃-⌘'
* ```
* @since v0.5.1
*/
function decode(string: string): string;
/**
* The `punycode.encode()` method converts a string of Unicode codepoints to a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only characters.
*
* ```js
* punycode.encode('mañana'); // 'maana-pta'
* punycode.encode('☃-⌘'); // '--dqo34k'
* ```
* @since v0.5.1
*/
function encode(string: string): string;
/**
* The `punycode.toUnicode()` method converts a string representing a domain name
* containing [Punycode](https://tools.ietf.org/html/rfc3492) encoded characters into Unicode. Only the [Punycode](https://tools.ietf.org/html/rfc3492) encoded parts of the domain name are be
* converted.
*
* ```js
* // decode domain names
* punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com'
* punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com'
* punycode.toUnicode('example.com'); // 'example.com'
* ```
* @since v0.6.1
*/
function toUnicode(domain: string): string;
/**
* The `punycode.toASCII()` method converts a Unicode string representing an
* Internationalized Domain Name to [Punycode](https://tools.ietf.org/html/rfc3492). Only the non-ASCII parts of the
* domain name will be converted. Calling `punycode.toASCII()` on a string that
* already only contains ASCII characters will have no effect.
*
* ```js
* // encode domain names
* punycode.toASCII('mañana.com'); // 'xn--maana-pta.com'
* punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com'
* punycode.toASCII('example.com'); // 'example.com'
* ```
* @since v0.6.1
*/
function toASCII(domain: string): string;
/**
* @deprecated since v7.0.0
* The version of the punycode module bundled in Node.js is being deprecated.
* In a future major version of Node.js this module will be removed.
|
* Users currently depending on the punycode module should switch to using
* the userland-provided Punycode.js module instead.
*/
const ucs2: ucs2;
interface ucs2 {
/**
* @deprecated since v7.0.0
* The version of the punycode module bundled in Node.js is being deprecated.
* In a future major version of Node.js this module will be removed.
* Users currently depending on the punycode module should switch to using
* the userland-provided Punycode.js module instead.
*/
decode(string: string): number[];
/**
* @deprecated since v7.0.0
* The version of the punycode module bundled in Node.js is being deprecated.
* In a future major version of Node.js this module will be removed.
* Users currently depending on the punycode module should switch to using
* the userland-provided Punycode.js module instead.
*/
encode(codePoints: readonly number[]): string;
}
/**
* @deprecated since v7.0.0
* The version of the punycode module bundled in Node.js is being deprecated.
* In a future major version of Node.js this module will be removed.
* Users currently depending on the punycode module should switch to using
* the userland-provided Punycode.js module instead.
*/
const version: string;
}
declare module "node:punycode" {
export * from "punycode";
}
|
/**
* The `node:readline` module provides an interface for reading data from a `Readable` stream (such as `process.stdin`) one line at a time.
*
* To use the promise-based APIs:
*
* ```js
* import * as readline from 'node:readline/promises';
* ```
*
* To use the callback and sync APIs:
*
* ```js
* import * as readline from 'node:readline';
* ```
*
* The following simple example illustrates the basic use of the `node:readline`module.
*
* ```js
* import * as readline from 'node:readline/promises';
* import { stdin as input, stdout as output } from 'node:process';
*
* const rl = readline.createInterface({ input, output });
*
* const answer = await rl.question('What do you think of Node.js? ');
*
* console.log(`Thank you for your valuable feedback: ${answer}`);
*
* rl.close();
* ```
*
* Once this code is invoked, the Node.js application will not terminate until the`readline.Interface` is closed because the interface waits for data to be
* received on the `input` stream.
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/readline.js)
*/
declare module "readline" {
import { Abortable, EventEmitter } from "node:events";
import * as promises from "node:readline/promises";
export { promises };
export interface Key {
sequence?: string | undefined;
name?: string | undefined;
ctrl?: boolean | undefined;
meta?: boolean | undefined;
shift?: boolean | undefined;
}
/**
* Instances of the `readline.Interface` class are constructed using the`readline.createInterface()` method. Every instance is associated with a
* single `input` `Readable` stream and a single `output` `Writable` stream.
* The `output` stream is used to print prompts for user input that arrives on,
* and is read from, the `input` stream.
* @since v0.1.104
*/
export class Interface extends EventEmitter {
readonly terminal: boolean;
/**
* The current input data being processed by node.
*
* This can be used when collecting input from a TTY stream to retrieve the
* current value that has been processed thus far, prior to the `line` event
* being emitted. Once the `line` event has been emitted, this property will
* be an empty string.
*
* Be aware that modifying the value during the instance runtime may have
* unintended consequences if `rl.cursor` is not also controlled.
*
* **If not using a TTY stream for input, use the `'line'` event.**
*
* One possible use case would be as follows:
*
* ```js
* const values = ['lorem ipsum', 'dolor sit amet'];
* const rl = readline.createInterface(process.stdin);
* const showResults = debounce(() => {
* console.log(
* '\n',
* values.filter((val) => val.startsWith(rl.line)).join(' '),
* );
* }, 300);
* process.stdin.on('keypress', (c, k) => {
* showResults();
* });
* ```
* @since v0.1.98
*/
readonly line: string;
/**
* The cursor position relative to `rl.line`.
*
* This will track where the current cursor lands in the input string, when
* reading input from a TTY stream. The position of cursor determines the
* portion of the input string that will be modified as input is processed,
* as well as the column where the terminal caret will be rendered.
* @since v0.1.98
*/
readonly cursor: number;
/**
* NOTE: According to the documentation:
*
* > Instances of the `readline.Interface` class are constructed using the
* > `readline.createInterface()` method.
*
* @see https://nodejs.org/dist/latest-v20.x/docs/api/readline.html#class-interfaceconstructor
*/
pro |
tected constructor(
input: NodeJS.ReadableStream,
output?: NodeJS.WritableStream,
completer?: Completer | AsyncCompleter,
terminal?: boolean,
);
/**
* NOTE: According to the documentation:
*
* > Instances of the `readline.Interface` class are constructed using the
* > `readline.createInterface()` method.
*
* @see https://nodejs.org/dist/latest-v20.x/docs/api/readline.html#class-interfaceconstructor
*/
protected constructor(options: ReadLineOptions);
/**
* The `rl.getPrompt()` method returns the current prompt used by `rl.prompt()`.
* @since v15.3.0, v14.17.0
* @return the current prompt string
*/
getPrompt(): string;
/**
* The `rl.setPrompt()` method sets the prompt that will be written to `output`whenever `rl.prompt()` is called.
* @since v0.1.98
*/
setPrompt(prompt: string): void;
/**
* The `rl.prompt()` method writes the `Interface` instances configured`prompt` to a new line in `output` in order to provide a user with a new
* location at which to provide input.
*
* When called, `rl.prompt()` will resume the `input` stream if it has been
* paused.
*
* If the `Interface` was created with `output` set to `null` or`undefined` the prompt is not written.
* @since v0.1.98
* @param preserveCursor If `true`, prevents the cursor placement from being reset to `0`.
*/
prompt(preserveCursor?: boolean): void;
/**
* The `rl.question()` method displays the `query` by writing it to the `output`,
* waits for user input to be provided on `input`, then invokes the `callback`function passing the provided input as the first argument.
*
* When called, `rl.question()` will resume the `input` stream if it has been
* paused.
*
* If the `Interface` was created with `output` set to `null` or`undefined` the `query` is not written.
*
* The `callback` function passed to `rl.question()` does not follow the typical
* pattern of accepting an `Error` object or `null` as the first argument.
* The `callback` is called with the provided answer as the only argument.
*
* An error will be thrown if calling `rl.question()` after `rl.close()`.
*
* Example usage:
*
* ```js
* rl.question('What is your favorite food? ', (answer) => {
* console.log(`Oh, so your favorite food is ${answer}`);
* });
* ```
*
* Using an `AbortController` to cancel a question.
*
* ```js
* const ac = new AbortController();
* const signal = ac.signal;
*
* rl.question('What is your favorite food? ', { signal }, (answer) => {
* console.log(`Oh, so your favorite food is ${answer}`);
* });
*
* signal.addEventListener('abort', () => {
* console.log('The food question timed out');
* }, { once: true });
*
* setTimeout(() => ac.abort(), 10000);
* ```
* @since v0.3.3
* @param query A statement or query to write to `output`, prepended to the prompt.
* @param callback A callback function that is invoked with the user's input in response to the `query`.
*/
question(query: string, callback: (answer: string) => void): void;
question(query: string, options: Abortable, callback: (answer: string) => void): void;
/**
* The `rl.pause()` method pauses the `input` stream, allowing it to be resumed
* later if necessary.
*
* Calling `rl.pause()` does not immediately pause other events (including`'line'`) from being emitted by the `Interface` in |
stance.
* @since v0.3.4
*/
pause(): this;
/**
* The `rl.resume()` method resumes the `input` stream if it has been paused.
* @since v0.3.4
*/
resume(): this;
/**
* The `rl.close()` method closes the `Interface` instance and
* relinquishes control over the `input` and `output` streams. When called,
* the `'close'` event will be emitted.
*
* Calling `rl.close()` does not immediately stop other events (including `'line'`)
* from being emitted by the `Interface` instance.
* @since v0.1.98
*/
close(): void;
/**
* The `rl.write()` method will write either `data` or a key sequence identified
* by `key` to the `output`. The `key` argument is supported only if `output` is
* a `TTY` text terminal. See `TTY keybindings` for a list of key
* combinations.
*
* If `key` is specified, `data` is ignored.
*
* When called, `rl.write()` will resume the `input` stream if it has been
* paused.
*
* If the `Interface` was created with `output` set to `null` or`undefined` the `data` and `key` are not written.
*
* ```js
* rl.write('Delete this!');
* // Simulate Ctrl+U to delete the line written previously
* rl.write(null, { ctrl: true, name: 'u' });
* ```
*
* The `rl.write()` method will write the data to the `readline` `Interface`'s`input`_as if it were provided by the user_.
* @since v0.1.98
*/
write(data: string | Buffer, key?: Key): void;
write(data: undefined | null | string | Buffer, key: Key): void;
/**
* Returns the real position of the cursor in relation to the input
* prompt + string. Long input (wrapping) strings, as well as multiple
* line prompts are included in the calculations.
* @since v13.5.0, v12.16.0
*/
getCursorPos(): CursorPos;
/**
* events.EventEmitter
* 1. close
* 2. line
* 3. pause
* 4. resume
* 5. SIGCONT
* 6. SIGINT
* 7. SIGTSTP
* 8. history
*/
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: "close", listener: () => void): this;
addListener(event: "line", listener: (input: string) => void): this;
addListener(event: "pause", listener: () => void): this;
addListener(event: "resume", listener: () => void): this;
addListener(event: "SIGCONT", listener: () => void): this;
addListener(event: "SIGINT", listener: () => void): this;
addListener(event: "SIGTSTP", listener: () => void): this;
addListener(event: "history", listener: (history: string[]) => void): this;
emit(event: string | symbol, ...args: any[]): boolean;
emit(event: "close"): boolean;
emit(event: "line", input: string): boolean;
emit(event: "pause"): boolean;
emit(event: "resume"): boolean;
emit(event: "SIGCONT"): boolean;
emit(event: "SIGINT"): boolean;
emit(event: "SIGTSTP"): boolean;
emit(event: "history", history: string[]): boolean;
on(event: string, listener: (...args: any[]) => void): this;
on(event: "close", listener: () => void): this;
on(event: "line", listener: (input: string) => void): this;
on(event: "pause", listener: () => void): this;
on(event: "resume", listener: () => void): this;
on(event: "SIGCONT", listener: () => void): this;
on(event: "SIGINT", listener: () => void): this;
on(event: "SIGTSTP", listener: () => void): this;
on(event: "history", listener: (history: string[]) => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: |
"close", listener: () => void): this;
once(event: "line", listener: (input: string) => void): this;
once(event: "pause", listener: () => void): this;
once(event: "resume", listener: () => void): this;
once(event: "SIGCONT", listener: () => void): this;
once(event: "SIGINT", listener: () => void): this;
once(event: "SIGTSTP", listener: () => void): this;
once(event: "history", listener: (history: string[]) => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: "close", listener: () => void): this;
prependListener(event: "line", listener: (input: string) => void): this;
prependListener(event: "pause", listener: () => void): this;
prependListener(event: "resume", listener: () => void): this;
prependListener(event: "SIGCONT", listener: () => void): this;
prependListener(event: "SIGINT", listener: () => void): this;
prependListener(event: "SIGTSTP", listener: () => void): this;
prependListener(event: "history", listener: (history: string[]) => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: "close", listener: () => void): this;
prependOnceListener(event: "line", listener: (input: string) => void): this;
prependOnceListener(event: "pause", listener: () => void): this;
prependOnceListener(event: "resume", listener: () => void): this;
prependOnceListener(event: "SIGCONT", listener: () => void): this;
prependOnceListener(event: "SIGINT", listener: () => void): this;
prependOnceListener(event: "SIGTSTP", listener: () => void): this;
prependOnceListener(event: "history", listener: (history: string[]) => void): this;
[Symbol.asyncIterator](): AsyncIterableIterator<string>;
}
export type ReadLine = Interface; // type forwarded for backwards compatibility
export type Completer = (line: string) => CompleterResult;
export type AsyncCompleter = (
line: string,
callback: (err?: null | Error, result?: CompleterResult) => void,
) => void;
export type CompleterResult = [string[], string];
export interface ReadLineOptions {
input: NodeJS.ReadableStream;
output?: NodeJS.WritableStream | undefined;
completer?: Completer | AsyncCompleter | undefined;
terminal?: boolean | undefined;
/**
* Initial list of history lines. This option makes sense
* only if `terminal` is set to `true` by the user or by an internal `output`
* check, otherwise the history caching mechanism is not initialized at all.
* @default []
*/
history?: string[] | undefined;
historySize?: number | undefined;
prompt?: string | undefined;
crlfDelay?: number | undefined;
/**
* If `true`, when a new input line added
* to the history list duplicates an older one, this removes the older line
* from the list.
* @default false
*/
removeHistoryDuplicates?: boolean | undefined;
escapeCodeTimeout?: number | undefined;
tabSize?: number | undefined;
}
/**
* The `readline.createInterface()` method creates a new `readline.Interface`instance.
*
* ```js
* const readline = require('node:readline');
* const rl = readline.createInterface({
* input: process.stdin,
* output: process.stdout,
* });
* ```
*
* Once the `readline.Interface` instance is created, the most common case is to
* listen for the `'line'` event:
*
* ```js
* rl.on('line', (line) => {
* console.log(`Received: ${line}`);
* });
* ```
*
* If `terminal` is `true` for this instance then the `output` stream will get
* the best compatibility if it defines an `output. |
columns` property and emits
* a `'resize'` event on the `output` if or when the columns ever change
* (`process.stdout` does this automatically when it is a TTY).
*
* When creating a `readline.Interface` using `stdin` as input, the program
* will not terminate until it receives an [EOF character](https://en.wikipedia.org/wiki/End-of-file#EOF_character). To exit without
* waiting for user input, call `process.stdin.unref()`.
* @since v0.1.98
*/
export function createInterface(
input: NodeJS.ReadableStream,
output?: NodeJS.WritableStream,
completer?: Completer | AsyncCompleter,
terminal?: boolean,
): Interface;
export function createInterface(options: ReadLineOptions): Interface;
/**
* The `readline.emitKeypressEvents()` method causes the given `Readable` stream to begin emitting `'keypress'` events corresponding to received input.
*
* Optionally, `interface` specifies a `readline.Interface` instance for which
* autocompletion is disabled when copy-pasted input is detected.
*
* If the `stream` is a `TTY`, then it must be in raw mode.
*
* This is automatically called by any readline instance on its `input` if the`input` is a terminal. Closing the `readline` instance does not stop
* the `input` from emitting `'keypress'` events.
*
* ```js
* readline.emitKeypressEvents(process.stdin);
* if (process.stdin.isTTY)
* process.stdin.setRawMode(true);
* ```
*
* ## Example: Tiny CLI
*
* The following example illustrates the use of `readline.Interface` class to
* implement a small command-line interface:
*
* ```js
* const readline = require('node:readline');
* const rl = readline.createInterface({
* input: process.stdin,
* output: process.stdout,
* prompt: 'OHAI> ',
* });
*
* rl.prompt();
*
* rl.on('line', (line) => {
* switch (line.trim()) {
* case 'hello':
* console.log('world!');
* break;
* default:
* console.log(`Say what? I might have heard '${line.trim()}'`);
* break;
* }
* rl.prompt();
* }).on('close', () => {
* console.log('Have a great day!');
* process.exit(0);
* });
* ```
*
* ## Example: Read file stream line-by-Line
*
* A common use case for `readline` is to consume an input file one line at a
* time. The easiest way to do so is leveraging the `fs.ReadStream` API as
* well as a `for await...of` loop:
*
* ```js
* const fs = require('node:fs');
* const readline = require('node:readline');
*
* async function processLineByLine() {
* const fileStream = fs.createReadStream('input.txt');
*
* const rl = readline.createInterface({
* input: fileStream,
* crlfDelay: Infinity,
* });
* // Note: we use the crlfDelay option to recognize all instances of CR LF
* // ('\r\n') in input.txt as a single line break.
*
* for await (const line of rl) {
* // Each line in input.txt will be successively available here as `line`.
* console.log(`Line from file: ${line}`);
* }
* }
*
* processLineByLine();
* ```
*
* Alternatively, one could use the `'line'` event:
*
* ```js
* const fs = require('node:fs');
* const readline = require('node:readline');
*
* const rl = readline.createInterface({
* input: fs.createReadStream('sample.txt'),
* crlfDelay: Infinity,
* });
*
* rl.on('line', (line) => {
* console.log(`Line from file: ${line}`);
* });
* ```
*
* Currently, `for await...of` loop can be a bit slower. If `async` / `await`flow and speed are both essential, a mixed approach can be applied:
*
* ```js
* const { once } = |
require('node:events');
* const { createReadStream } = require('node:fs');
* const { createInterface } = require('node:readline');
*
* (async function processLineByLine() {
* try {
* const rl = createInterface({
* input: createReadStream('big-file.txt'),
* crlfDelay: Infinity,
* });
*
* rl.on('line', (line) => {
* // Process the line.
* });
*
* await once(rl, 'close');
*
* console.log('File processed.');
* } catch (err) {
* console.error(err);
* }
* })();
* ```
* @since v0.7.7
*/
export function emitKeypressEvents(stream: NodeJS.ReadableStream, readlineInterface?: Interface): void;
export type Direction = -1 | 0 | 1;
export interface CursorPos {
rows: number;
cols: number;
}
/**
* The `readline.clearLine()` method clears current line of given `TTY` stream
* in a specified direction identified by `dir`.
* @since v0.7.7
* @param callback Invoked once the operation completes.
* @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.
*/
export function clearLine(stream: NodeJS.WritableStream, dir: Direction, callback?: () => void): boolean;
/**
* The `readline.clearScreenDown()` method clears the given `TTY` stream from
* the current position of the cursor down.
* @since v0.7.7
* @param callback Invoked once the operation completes.
* @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.
*/
export function clearScreenDown(stream: NodeJS.WritableStream, callback?: () => void): boolean;
/**
* The `readline.cursorTo()` method moves cursor to the specified position in a
* given `TTY` `stream`.
* @since v0.7.7
* @param callback Invoked once the operation completes.
* @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.
*/
export function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number, callback?: () => void): boolean;
/**
* The `readline.moveCursor()` method moves the cursor _relative_ to its current
* position in a given `TTY` `stream`.
* @since v0.7.7
* @param callback Invoked once the operation completes.
* @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.
*/
export function moveCursor(stream: NodeJS.WritableStream, dx: number, dy: number, callback?: () => void): boolean;
}
declare module "node:readline" {
export * from "readline";
}
|
/**
* The `node:crypto` module provides cryptographic functionality that includes a
* set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify
* functions.
*
* ```js
* const { createHmac } = await import('node:crypto');
*
* const secret = 'abcdefg';
* const hash = createHmac('sha256', secret)
* .update('I love cupcakes')
* .digest('hex');
* console.log(hash);
* // Prints:
* // c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e
* ```
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/crypto.js)
*/
declare module "crypto" {
import * as stream from "node:stream";
import { PeerCertificate } from "node:tls";
/**
* SPKAC is a Certificate Signing Request mechanism originally implemented by
* Netscape and was specified formally as part of HTML5's `keygen` element.
*
* `<keygen>` is deprecated since [HTML 5.2](https://www.w3.org/TR/html52/changes.html#features-removed) and new projects
* should not use this element anymore.
*
* The `node:crypto` module provides the `Certificate` class for working with SPKAC
* data. The most common usage is handling output generated by the HTML5`<keygen>` element. Node.js uses [OpenSSL's SPKAC
* implementation](https://www.openssl.org/docs/man3.0/man1/openssl-spkac.html) internally.
* @since v0.11.8
*/
class Certificate {
/**
* ```js
* const { Certificate } = await import('node:crypto');
* const spkac = getSpkacSomehow();
* const challenge = Certificate.exportChallenge(spkac);
* console.log(challenge.toString('utf8'));
* // Prints: the challenge as a UTF8 string
* ```
* @since v9.0.0
* @param encoding The `encoding` of the `spkac` string.
* @return The challenge component of the `spkac` data structure, which includes a public key and a challenge.
*/
static exportChallenge(spkac: BinaryLike): Buffer;
/**
* ```js
* const { Certificate } = await import('node:crypto');
* const spkac = getSpkacSomehow();
* const publicKey = Certificate.exportPublicKey(spkac);
* console.log(publicKey);
* // Prints: the public key as <Buffer ...>
* ```
* @since v9.0.0
* @param encoding The `encoding` of the `spkac` string.
* @return The public key component of the `spkac` data structure, which includes a public key and a challenge.
*/
static exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer;
/**
* ```js
* import { Buffer } from 'node:buffer';
* const { Certificate } = await import('node:crypto');
*
* const spkac = getSpkacSomehow();
* console.log(Certificate.verifySpkac(Buffer.from(spkac)));
* // Prints: true or false
* ```
* @since v9.0.0
* @param encoding The `encoding` of the `spkac` string.
* @return `true` if the given `spkac` data structure is valid, `false` otherwise.
*/
static verifySpkac(spkac: NodeJS.ArrayBufferView): boolean;
/**
* @deprecated
* @param spkac
* @returns The challenge component of the `spkac` data structure,
* which includes a public key and a challenge.
*/
exportChallenge(spkac: BinaryLike): Buffer;
/**
* @deprecated
* @param spkac
* @param encoding The encoding of the spkac string.
* @returns The public key component of the `spkac` data structure,
* which includes a public key and a challenge.
*/
exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer;
/**
* @deprecated
* @param spkac
* @returns `true` if the given `spkac` data structure is valid,
* `false` otherwise.
*/
verifySpkac |
(spkac: NodeJS.ArrayBufferView): boolean;
}
namespace constants {
// https://nodejs.org/dist/latest-v20.x/docs/api/crypto.html#crypto-constants
const OPENSSL_VERSION_NUMBER: number;
/** Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail. */
const SSL_OP_ALL: number;
/** Instructs OpenSSL to allow a non-[EC]DHE-based key exchange mode for TLS v1.3 */
const SSL_OP_ALLOW_NO_DHE_KEX: number;
/** Allows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */
const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number;
/** Attempts to use the server's preferences instead of the client's when selecting a cipher. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */
const SSL_OP_CIPHER_SERVER_PREFERENCE: number;
/** Instructs OpenSSL to use Cisco's "speshul" version of DTLS_BAD_VER. */
const SSL_OP_CISCO_ANYCONNECT: number;
/** Instructs OpenSSL to turn on cookie exchange. */
const SSL_OP_COOKIE_EXCHANGE: number;
/** Instructs OpenSSL to add server-hello extension from an early version of the cryptopro draft. */
const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number;
/** Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d. */
const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number;
/** Allows initial connection to servers that do not support RI. */
const SSL_OP_LEGACY_SERVER_CONNECT: number;
/** Instructs OpenSSL to disable support for SSL/TLS compression. */
const SSL_OP_NO_COMPRESSION: number;
/** Instructs OpenSSL to disable encrypt-then-MAC. */
const SSL_OP_NO_ENCRYPT_THEN_MAC: number;
const SSL_OP_NO_QUERY_MTU: number;
/** Instructs OpenSSL to disable renegotiation. */
const SSL_OP_NO_RENEGOTIATION: number;
/** Instructs OpenSSL to always start a new session when performing renegotiation. */
const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number;
/** Instructs OpenSSL to turn off SSL v2 */
const SSL_OP_NO_SSLv2: number;
/** Instructs OpenSSL to turn off SSL v3 */
const SSL_OP_NO_SSLv3: number;
/** Instructs OpenSSL to disable use of RFC4507bis tickets. */
const SSL_OP_NO_TICKET: number;
/** Instructs OpenSSL to turn off TLS v1 */
const SSL_OP_NO_TLSv1: number;
/** Instructs OpenSSL to turn off TLS v1.1 */
const SSL_OP_NO_TLSv1_1: number;
/** Instructs OpenSSL to turn off TLS v1.2 */
const SSL_OP_NO_TLSv1_2: number;
/** Instructs OpenSSL to turn off TLS v1.3 */
const SSL_OP_NO_TLSv1_3: number;
/** Instructs OpenSSL server to prioritize ChaCha20-Poly1305 when the client does. This option has no effect if `SSL_OP_CIPHER_SERVER_PREFERENCE` is not enabled. */
const SSL_OP_PRIORITIZE_CHACHA: number;
/** Instructs OpenSSL to disable version rollback attack detection. */
const SSL_OP_TLS_ROLLBACK_BUG: number;
const ENGINE_METHOD_RSA: number;
const ENGINE_METHOD_DSA: number;
const ENGINE_METHOD_DH: number;
const ENGINE_METHOD_RAND: number;
const ENGINE_METHOD_EC: number;
const ENGINE_METHOD_CIPHERS: number;
const ENGINE_METHOD_DIGESTS: number;
const ENGINE_METHOD_PKEY_METHS: number;
const ENGINE_METHOD_PKEY_ASN1_METHS: number;
const ENGINE_METHOD_ALL: number;
const ENGINE_METHOD_NONE: number;
const DH_CHECK_P_NOT_SAFE_PRIME: number;
const DH_CHECK_P_NOT_PRIME: number;
const DH_UNABLE_TO_CHECK_GENERATOR: number;
const DH_NOT_SUITABLE_GENERATOR: number;
const RSA_PKCS1_PADDING: number;
const RSA_SSLV23_PADDING: |
number;
const RSA_NO_PADDING: number;
const RSA_PKCS1_OAEP_PADDING: number;
const RSA_X931_PADDING: number;
const RSA_PKCS1_PSS_PADDING: number;
/** Sets the salt length for RSA_PKCS1_PSS_PADDING to the digest size when signing or verifying. */
const RSA_PSS_SALTLEN_DIGEST: number;
/** Sets the salt length for RSA_PKCS1_PSS_PADDING to the maximum permissible value when signing data. */
const RSA_PSS_SALTLEN_MAX_SIGN: number;
/** Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature. */
const RSA_PSS_SALTLEN_AUTO: number;
const POINT_CONVERSION_COMPRESSED: number;
const POINT_CONVERSION_UNCOMPRESSED: number;
const POINT_CONVERSION_HYBRID: number;
/** Specifies the built-in default cipher list used by Node.js (colon-separated values). */
const defaultCoreCipherList: string;
/** Specifies the active default cipher list used by the current Node.js process (colon-separated values). */
const defaultCipherList: string;
}
interface HashOptions extends stream.TransformOptions {
/**
* For XOF hash functions such as `shake256`, the
* outputLength option can be used to specify the desired output length in bytes.
*/
outputLength?: number | undefined;
}
/** @deprecated since v10.0.0 */
const fips: boolean;
/**
* Creates and returns a `Hash` object that can be used to generate hash digests
* using the given `algorithm`. Optional `options` argument controls stream
* behavior. For XOF hash functions such as `'shake256'`, the `outputLength` option
* can be used to specify the desired output length in bytes.
*
* The `algorithm` is dependent on the available algorithms supported by the
* version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc.
* On recent releases of OpenSSL, `openssl list -digest-algorithms` will
* display the available digest algorithms.
*
* Example: generating the sha256 sum of a file
*
* ```js
* import {
* createReadStream,
* } from 'node:fs';
* import { argv } from 'node:process';
* const {
* createHash,
* } = await import('node:crypto');
*
* const filename = argv[2];
*
* const hash = createHash('sha256');
*
* const input = createReadStream(filename);
* input.on('readable', () => {
* // Only one element is going to be produced by the
* // hash stream.
* const data = input.read();
* if (data)
* hash.update(data);
* else {
* console.log(`${hash.digest('hex')} ${filename}`);
* }
* });
* ```
* @since v0.1.92
* @param options `stream.transform` options
*/
function createHash(algorithm: string, options?: HashOptions): Hash;
/**
* Creates and returns an `Hmac` object that uses the given `algorithm` and `key`.
* Optional `options` argument controls stream behavior.
*
* The `algorithm` is dependent on the available algorithms supported by the
* version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc.
* On recent releases of OpenSSL, `openssl list -digest-algorithms` will
* display the available digest algorithms.
*
* The `key` is the HMAC key used to generate the cryptographic HMAC hash. If it is
* a `KeyObject`, its type must be `secret`. If it is a string, please consider `caveats when using strings as inputs to cryptographic APIs`. If it was
* obtained from a cryptographically secure source of entropy, such as {@link randomBytes} or {@link generateKey}, its length should not
* exceed the block size of `algorithm` (e.g., 512 bits for SHA-256).
*
* Example: generating the sha256 HMAC of a file
*
* ```js
* import {
* crea |
teReadStream,
* } from 'node:fs';
* import { argv } from 'node:process';
* const {
* createHmac,
* } = await import('node:crypto');
*
* const filename = argv[2];
*
* const hmac = createHmac('sha256', 'a secret');
*
* const input = createReadStream(filename);
* input.on('readable', () => {
* // Only one element is going to be produced by the
* // hash stream.
* const data = input.read();
* if (data)
* hmac.update(data);
* else {
* console.log(`${hmac.digest('hex')} ${filename}`);
* }
* });
* ```
* @since v0.1.94
* @param options `stream.transform` options
*/
function createHmac(algorithm: string, key: BinaryLike | KeyObject, options?: stream.TransformOptions): Hmac;
// https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings
type BinaryToTextEncoding = "base64" | "base64url" | "hex" | "binary";
type CharacterEncoding = "utf8" | "utf-8" | "utf16le" | "utf-16le" | "latin1";
type LegacyCharacterEncoding = "ascii" | "binary" | "ucs2" | "ucs-2";
type Encoding = BinaryToTextEncoding | CharacterEncoding | LegacyCharacterEncoding;
type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid";
/**
* The `Hash` class is a utility for creating hash digests of data. It can be
* used in one of two ways:
*
* * As a `stream` that is both readable and writable, where data is written
* to produce a computed hash digest on the readable side, or
* * Using the `hash.update()` and `hash.digest()` methods to produce the
* computed hash.
*
* The {@link createHash} method is used to create `Hash` instances. `Hash`objects are not to be created directly using the `new` keyword.
*
* Example: Using `Hash` objects as streams:
*
* ```js
* const {
* createHash,
* } = await import('node:crypto');
*
* const hash = createHash('sha256');
*
* hash.on('readable', () => {
* // Only one element is going to be produced by the
* // hash stream.
* const data = hash.read();
* if (data) {
* console.log(data.toString('hex'));
* // Prints:
* // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
* }
* });
*
* hash.write('some data to hash');
* hash.end();
* ```
*
* Example: Using `Hash` and piped streams:
*
* ```js
* import { createReadStream } from 'node:fs';
* import { stdout } from 'node:process';
* const { createHash } = await import('node:crypto');
*
* const hash = createHash('sha256');
*
* const input = createReadStream('test.js');
* input.pipe(hash).setEncoding('hex').pipe(stdout);
* ```
*
* Example: Using the `hash.update()` and `hash.digest()` methods:
*
* ```js
* const {
* createHash,
* } = await import('node:crypto');
*
* const hash = createHash('sha256');
*
* hash.update('some data to hash');
* console.log(hash.digest('hex'));
* // Prints:
* // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
* ```
* @since v0.1.92
*/
class Hash extends stream.Transform {
private constructor();
/**
* Creates a new `Hash` object that contains a deep copy of the internal state
* of the current `Hash` object.
*
* The optional `options` argument controls stream behavior. For XOF hash
* functions such as `'shake256'`, the `outputLength` option can be used to
* specify the desired output length in bytes.
*
* An error is thrown when an attempt is made to copy the `Hash` object after
* its `hash.digest()` method has been called.
*
* ```js
* // Calculate a rolling hash.
* const {
* |
createHash,
* } = await import('node:crypto');
*
* const hash = createHash('sha256');
*
* hash.update('one');
* console.log(hash.copy().digest('hex'));
*
* hash.update('two');
* console.log(hash.copy().digest('hex'));
*
* hash.update('three');
* console.log(hash.copy().digest('hex'));
*
* // Etc.
* ```
* @since v13.1.0
* @param options `stream.transform` options
*/
copy(options?: HashOptions): Hash;
/**
* Updates the hash content with the given `data`, the encoding of which
* is given in `inputEncoding`.
* If `encoding` is not provided, and the `data` is a string, an
* encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored.
*
* This can be called many times with new data as it is streamed.
* @since v0.1.92
* @param inputEncoding The `encoding` of the `data` string.
*/
update(data: BinaryLike): Hash;
update(data: string, inputEncoding: Encoding): Hash;
/**
* Calculates the digest of all of the data passed to be hashed (using the `hash.update()` method).
* If `encoding` is provided a string will be returned; otherwise
* a `Buffer` is returned.
*
* The `Hash` object can not be used again after `hash.digest()` method has been
* called. Multiple calls will cause an error to be thrown.
* @since v0.1.92
* @param encoding The `encoding` of the return value.
*/
digest(): Buffer;
digest(encoding: BinaryToTextEncoding): string;
}
/**
* The `Hmac` class is a utility for creating cryptographic HMAC digests. It can
* be used in one of two ways:
*
* * As a `stream` that is both readable and writable, where data is written
* to produce a computed HMAC digest on the readable side, or
* * Using the `hmac.update()` and `hmac.digest()` methods to produce the
* computed HMAC digest.
*
* The {@link createHmac} method is used to create `Hmac` instances. `Hmac`objects are not to be created directly using the `new` keyword.
*
* Example: Using `Hmac` objects as streams:
*
* ```js
* const {
* createHmac,
* } = await import('node:crypto');
*
* const hmac = createHmac('sha256', 'a secret');
*
* hmac.on('readable', () => {
* // Only one element is going to be produced by the
* // hash stream.
* const data = hmac.read();
* if (data) {
* console.log(data.toString('hex'));
* // Prints:
* // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
* }
* });
*
* hmac.write('some data to hash');
* hmac.end();
* ```
*
* Example: Using `Hmac` and piped streams:
*
* ```js
* import { createReadStream } from 'node:fs';
* import { stdout } from 'node:process';
* const {
* createHmac,
* } = await import('node:crypto');
*
* const hmac = createHmac('sha256', 'a secret');
*
* const input = createReadStream('test.js');
* input.pipe(hmac).pipe(stdout);
* ```
*
* Example: Using the `hmac.update()` and `hmac.digest()` methods:
*
* ```js
* const {
* createHmac,
* } = await import('node:crypto');
*
* const hmac = createHmac('sha256', 'a secret');
*
* hmac.update('some data to hash');
* console.log(hmac.digest('hex'));
* // Prints:
* // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
* ```
* @since v0.1.94
*/
class Hmac extends stream.Transform {
private constructor();
/**
* Updates the `Hmac` content with the given `data`, the enco |
ding of which
* is given in `inputEncoding`.
* If `encoding` is not provided, and the `data` is a string, an
* encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored.
*
* This can be called many times with new data as it is streamed.
* @since v0.1.94
* @param inputEncoding The `encoding` of the `data` string.
*/
update(data: BinaryLike): Hmac;
update(data: string, inputEncoding: Encoding): Hmac;
/**
* Calculates the HMAC digest of all of the data passed using `hmac.update()`.
* If `encoding` is
* provided a string is returned; otherwise a `Buffer` is returned;
*
* The `Hmac` object can not be used again after `hmac.digest()` has been
* called. Multiple calls to `hmac.digest()` will result in an error being thrown.
* @since v0.1.94
* @param encoding The `encoding` of the return value.
*/
digest(): Buffer;
digest(encoding: BinaryToTextEncoding): string;
}
type KeyObjectType = "secret" | "public" | "private";
interface KeyExportOptions<T extends KeyFormat> {
type: "pkcs1" | "spki" | "pkcs8" | "sec1";
format: T;
cipher?: string | undefined;
passphrase?: string | Buffer | undefined;
}
interface JwkKeyExportOptions {
format: "jwk";
}
interface JsonWebKey {
crv?: string | undefined;
d?: string | undefined;
dp?: string | undefined;
dq?: string | undefined;
e?: string | undefined;
k?: string | undefined;
kty?: string | undefined;
n?: string | undefined;
p?: string | undefined;
q?: string | undefined;
qi?: string | undefined;
x?: string | undefined;
y?: string | undefined;
[key: string]: unknown;
}
interface AsymmetricKeyDetails {
/**
* Key size in bits (RSA, DSA).
*/
modulusLength?: number | undefined;
/**
* Public exponent (RSA).
*/
publicExponent?: bigint | undefined;
/**
* Name of the message digest (RSA-PSS).
*/
hashAlgorithm?: string | undefined;
/**
* Name of the message digest used by MGF1 (RSA-PSS).
*/
mgf1HashAlgorithm?: string | undefined;
/**
* Minimal salt length in bytes (RSA-PSS).
*/
saltLength?: number | undefined;
/**
* Size of q in bits (DSA).
*/
divisorLength?: number | undefined;
/**
* Name of the curve (EC).
*/
namedCurve?: string | undefined;
}
/**
* Node.js uses a `KeyObject` class to represent a symmetric or asymmetric key,
* and each kind of key exposes different functions. The {@link createSecretKey}, {@link createPublicKey} and {@link createPrivateKey} methods are used to create `KeyObject`instances. `KeyObject`
* objects are not to be created directly using the `new`keyword.
*
* Most applications should consider using the new `KeyObject` API instead of
* passing keys as strings or `Buffer`s due to improved security features.
*
* `KeyObject` instances can be passed to other threads via `postMessage()`.
* The receiver obtains a cloned `KeyObject`, and the `KeyObject` does not need to
* be listed in the `transferList` argument.
* @since v11.6.0
*/
class KeyObject {
private constructor();
/**
* Example: Converting a `CryptoKey` instance to a `KeyObject`:
*
* ```js
* const { KeyObject } = await import('node:crypto');
* const { subtle } = globalThis.crypto;
*
* const key = await subtle.generateKey({
* name: 'HMAC',
* hash: 'SHA-256',
* length: 256,
* }, tr |
ue, ['sign', 'verify']);
*
* const keyObject = KeyObject.from(key);
* console.log(keyObject.symmetricKeySize);
* // Prints: 32 (symmetric key size in bytes)
* ```
* @since v15.0.0
*/
static from(key: webcrypto.CryptoKey): KeyObject;
/**
* For asymmetric keys, this property represents the type of the key. Supported key
* types are:
*
* * `'rsa'` (OID 1.2.840.113549.1.1.1)
* * `'rsa-pss'` (OID 1.2.840.113549.1.1.10)
* * `'dsa'` (OID 1.2.840.10040.4.1)
* * `'ec'` (OID 1.2.840.10045.2.1)
* * `'x25519'` (OID 1.3.101.110)
* * `'x448'` (OID 1.3.101.111)
* * `'ed25519'` (OID 1.3.101.112)
* * `'ed448'` (OID 1.3.101.113)
* * `'dh'` (OID 1.2.840.113549.1.3.1)
*
* This property is `undefined` for unrecognized `KeyObject` types and symmetric
* keys.
* @since v11.6.0
*/
asymmetricKeyType?: KeyType | undefined;
/**
* For asymmetric keys, this property represents the size of the embedded key in
* bytes. This property is `undefined` for symmetric keys.
*/
asymmetricKeySize?: number | undefined;
/**
* This property exists only on asymmetric keys. Depending on the type of the key,
* this object contains information about the key. None of the information obtained
* through this property can be used to uniquely identify a key or to compromise
* the security of the key.
*
* For RSA-PSS keys, if the key material contains a `RSASSA-PSS-params` sequence,
* the `hashAlgorithm`, `mgf1HashAlgorithm`, and `saltLength` properties will be
* set.
*
* Other key details might be exposed via this API using additional attributes.
* @since v15.7.0
*/
asymmetricKeyDetails?: AsymmetricKeyDetails | undefined;
/**
* For symmetric keys, the following encoding options can be used:
*
* For public keys, the following encoding options can be used:
*
* For private keys, the following encoding options can be used:
*
* The result type depends on the selected encoding format, when PEM the
* result is a string, when DER it will be a buffer containing the data
* encoded as DER, when [JWK](https://tools.ietf.org/html/rfc7517) it will be an object.
*
* When [JWK](https://tools.ietf.org/html/rfc7517) encoding format was selected, all other encoding options are
* ignored.
*
* PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of
* the `cipher` and `format` options. The PKCS#8 `type` can be used with any`format` to encrypt any key algorithm (RSA, EC, or DH) by specifying a`cipher`. PKCS#1 and SEC1 can only be
* encrypted by specifying a `cipher`when the PEM `format` is used. For maximum compatibility, use PKCS#8 for
* encrypted private keys. Since PKCS#8 defines its own
* encryption mechanism, PEM-level encryption is not supported when encrypting
* a PKCS#8 key. See [RFC 5208](https://www.rfc-editor.org/rfc/rfc5208.txt) for PKCS#8 encryption and [RFC 1421](https://www.rfc-editor.org/rfc/rfc1421.txt) for
* PKCS#1 and SEC1 encryption.
* @since v11.6.0
*/
export(options: KeyExportOptions<"pem">): string | Buffer;
export(options?: KeyExportOptions<"der">): Buffer;
export(options?: JwkKeyExportOptions): JsonWebKey;
/**
* Returns `true` or `false` depending on whether the keys have exactly the same
* type, value, and parameters. This method is not [constant time](https://en.wikipedia.org/wiki/Timing_attack).
* @since v17.7.0, v16.15.0
* @param otherKeyObject A `KeyObject` with which to compare `ke |
yObject`.
*/
equals(otherKeyObject: KeyObject): boolean;
/**
* For secret keys, this property represents the size of the key in bytes. This
* property is `undefined` for asymmetric keys.
* @since v11.6.0
*/
symmetricKeySize?: number | undefined;
/**
* Depending on the type of this `KeyObject`, this property is either`'secret'` for secret (symmetric) keys, `'public'` for public (asymmetric) keys
* or `'private'` for private (asymmetric) keys.
* @since v11.6.0
*/
type: KeyObjectType;
}
type CipherCCMTypes = "aes-128-ccm" | "aes-192-ccm" | "aes-256-ccm" | "chacha20-poly1305";
type CipherGCMTypes = "aes-128-gcm" | "aes-192-gcm" | "aes-256-gcm";
type CipherOCBTypes = "aes-128-ocb" | "aes-192-ocb" | "aes-256-ocb";
type BinaryLike = string | NodeJS.ArrayBufferView;
type CipherKey = BinaryLike | KeyObject;
interface CipherCCMOptions extends stream.TransformOptions {
authTagLength: number;
}
interface CipherGCMOptions extends stream.TransformOptions {
authTagLength?: number | undefined;
}
interface CipherOCBOptions extends stream.TransformOptions {
authTagLength: number;
}
/**
* Creates and returns a `Cipher` object that uses the given `algorithm` and`password`.
*
* The `options` argument controls stream behavior and is optional except when a
* cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the
* authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication
* tag that will be returned by `getAuthTag()` and defaults to 16 bytes.
* For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes.
*
* The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On
* recent OpenSSL releases, `openssl list -cipher-algorithms` will
* display the available cipher algorithms.
*
* The `password` is used to derive the cipher key and initialization vector (IV).
* The value must be either a `'latin1'` encoded string, a `Buffer`, a`TypedArray`, or a `DataView`.
*
* **This function is semantically insecure for all**
* **supported ciphers and fatally flawed for ciphers in counter mode (such as CTR,**
* **GCM, or CCM).**
*
* The implementation of `crypto.createCipher()` derives keys using the OpenSSL
* function [`EVP_BytesToKey`](https://www.openssl.org/docs/man3.0/man3/EVP_BytesToKey.html) with the digest algorithm set to MD5, one
* iteration, and no salt. The lack of salt allows dictionary attacks as the same
* password always creates the same key. The low iteration count and
* non-cryptographically secure hash algorithm allow passwords to be tested very
* rapidly.
*
* In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man3.0/man3/EVP_BytesToKey.html) it is recommended that
* developers derive a key and IV on
* their own using {@link scrypt} and to use {@link createCipheriv} to create the `Cipher` object. Users should not use ciphers with counter mode
* (e.g. CTR, GCM, or CCM) in `crypto.createCipher()`. A warning is emitted when
* they are used in order to avoid the risk of IV reuse that causes
* vulnerabilities. For the case when IV is reused in GCM, see [Nonce-Disrespecting Adversaries](https://github.com/nonce-disrespect/nonce-disrespect) for details.
* @since v0.1.94
* @deprecated Since v10.0.0 - Use {@link createCipheriv} instead.
* @param options `stream.transform` options
*/
function createCipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): CipherCCM;
/** @d |
eprecated since v10.0.0 use `createCipheriv()` */
function createCipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): CipherGCM;
/** @deprecated since v10.0.0 use `createCipheriv()` */
function createCipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Cipher;
/**
* Creates and returns a `Cipher` object, with the given `algorithm`, `key` and
* initialization vector (`iv`).
*
* The `options` argument controls stream behavior and is optional except when a
* cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the
* authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication
* tag that will be returned by `getAuthTag()` and defaults to 16 bytes.
* For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes.
*
* The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On
* recent OpenSSL releases, `openssl list -cipher-algorithms` will
* display the available cipher algorithms.
*
* The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded
* strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be
* a `KeyObject` of type `secret`. If the cipher does not need
* an initialization vector, `iv` may be `null`.
*
* When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`.
*
* Initialization vectors should be unpredictable and unique; ideally, they will be
* cryptographically random. They do not have to be secret: IVs are typically just
* added to ciphertext messages unencrypted. It may sound contradictory that
* something has to be unpredictable and unique, but does not have to be secret;
* remember that an attacker must not be able to predict ahead of time what a
* given IV will be.
* @since v0.1.94
* @param options `stream.transform` options
*/
function createCipheriv(
algorithm: CipherCCMTypes,
key: CipherKey,
iv: BinaryLike,
options: CipherCCMOptions,
): CipherCCM;
function createCipheriv(
algorithm: CipherOCBTypes,
key: CipherKey,
iv: BinaryLike,
options: CipherOCBOptions,
): CipherOCB;
function createCipheriv(
algorithm: CipherGCMTypes,
key: CipherKey,
iv: BinaryLike,
options?: CipherGCMOptions,
): CipherGCM;
function createCipheriv(
algorithm: string,
key: CipherKey,
iv: BinaryLike | null,
options?: stream.TransformOptions,
): Cipher;
/**
* Instances of the `Cipher` class are used to encrypt data. The class can be
* used in one of two ways:
*
* * As a `stream` that is both readable and writable, where plain unencrypted
* data is written to produce encrypted data on the readable side, or
* * Using the `cipher.update()` and `cipher.final()` methods to produce
* the encrypted data.
*
* The {@link createCipher} or {@link createCipheriv} methods are
* used to create `Cipher` instances. `Cipher` objects are not to be created
* directly using the `new` keyword.
*
* Example: Using `Cipher` objects as streams:
*
* ```js
* const {
* scrypt,
* randomFill,
* createCipheriv,
* } = await import('node:crypto');
*
* const algorithm = 'aes-192-cbc';
* const password = 'Password used to generate key';
*
* // First, we'll generate the key. The key length is dependent on the algorithm.
* // In this case for aes192, it is 24 bytes (1 |
92 bits).
* scrypt(password, 'salt', 24, (err, key) => {
* if (err) throw err;
* // Then, we'll generate a random initialization vector
* randomFill(new Uint8Array(16), (err, iv) => {
* if (err) throw err;
*
* // Once we have the key and iv, we can create and use the cipher...
* const cipher = createCipheriv(algorithm, key, iv);
*
* let encrypted = '';
* cipher.setEncoding('hex');
*
* cipher.on('data', (chunk) => encrypted += chunk);
* cipher.on('end', () => console.log(encrypted));
*
* cipher.write('some clear text data');
* cipher.end();
* });
* });
* ```
*
* Example: Using `Cipher` and piped streams:
*
* ```js
* import {
* createReadStream,
* createWriteStream,
* } from 'node:fs';
*
* import {
* pipeline,
* } from 'node:stream';
*
* const {
* scrypt,
* randomFill,
* createCipheriv,
* } = await import('node:crypto');
*
* const algorithm = 'aes-192-cbc';
* const password = 'Password used to generate key';
*
* // First, we'll generate the key. The key length is dependent on the algorithm.
* // In this case for aes192, it is 24 bytes (192 bits).
* scrypt(password, 'salt', 24, (err, key) => {
* if (err) throw err;
* // Then, we'll generate a random initialization vector
* randomFill(new Uint8Array(16), (err, iv) => {
* if (err) throw err;
*
* const cipher = createCipheriv(algorithm, key, iv);
*
* const input = createReadStream('test.js');
* const output = createWriteStream('test.enc');
*
* pipeline(input, cipher, output, (err) => {
* if (err) throw err;
* });
* });
* });
* ```
*
* Example: Using the `cipher.update()` and `cipher.final()` methods:
*
* ```js
* const {
* scrypt,
* randomFill,
* createCipheriv,
* } = await import('node:crypto');
*
* const algorithm = 'aes-192-cbc';
* const password = 'Password used to generate key';
*
* // First, we'll generate the key. The key length is dependent on the algorithm.
* // In this case for aes192, it is 24 bytes (192 bits).
* scrypt(password, 'salt', 24, (err, key) => {
* if (err) throw err;
* // Then, we'll generate a random initialization vector
* randomFill(new Uint8Array(16), (err, iv) => {
* if (err) throw err;
*
* const cipher = createCipheriv(algorithm, key, iv);
*
* let encrypted = cipher.update('some clear text data', 'utf8', 'hex');
* encrypted += cipher.final('hex');
* console.log(encrypted);
* });
* });
* ```
* @since v0.1.94
*/
class Cipher extends stream.Transform {
private constructor();
/**
* Updates the cipher with `data`. If the `inputEncoding` argument is given,
* the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`, `TypedArray`, or`DataView`. If `data` is a `Buffer`,
* `TypedArray`, or `DataView`, then`inputEncoding` is ignored.
*
* The `outputEncoding` specifies the output format of the enciphered
* data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned.
*
* The `cipher.update()` method can be called multiple times with new data until `cipher.final()` is called. Calling `cipher.update()` after `cipher.final()` will result in an error being
* thrown.
* @since v0.1.94
* @param inputEncoding The `encoding` of the data.
* @param outputEncoding The `encoding` of the return value.
*/
|
update(data: BinaryLike): Buffer;
update(data: string, inputEncoding: Encoding): Buffer;
update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string;
update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string;
/**
* Once the `cipher.final()` method has been called, the `Cipher` object can no
* longer be used to encrypt data. Attempts to call `cipher.final()` more than
* once will result in an error being thrown.
* @since v0.1.94
* @param outputEncoding The `encoding` of the return value.
* @return Any remaining enciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned.
*/
final(): Buffer;
final(outputEncoding: BufferEncoding): string;
/**
* When using block encryption algorithms, the `Cipher` class will automatically
* add padding to the input data to the appropriate block size. To disable the
* default padding call `cipher.setAutoPadding(false)`.
*
* When `autoPadding` is `false`, the length of the entire input data must be a
* multiple of the cipher's block size or `cipher.final()` will throw an error.
* Disabling automatic padding is useful for non-standard padding, for instance
* using `0x0` instead of PKCS padding.
*
* The `cipher.setAutoPadding()` method must be called before `cipher.final()`.
* @since v0.7.1
* @param [autoPadding=true]
* @return for method chaining.
*/
setAutoPadding(autoPadding?: boolean): this;
}
interface CipherCCM extends Cipher {
setAAD(
buffer: NodeJS.ArrayBufferView,
options: {
plaintextLength: number;
},
): this;
getAuthTag(): Buffer;
}
interface CipherGCM extends Cipher {
setAAD(
buffer: NodeJS.ArrayBufferView,
options?: {
plaintextLength: number;
},
): this;
getAuthTag(): Buffer;
}
interface CipherOCB extends Cipher {
setAAD(
buffer: NodeJS.ArrayBufferView,
options?: {
plaintextLength: number;
},
): this;
getAuthTag(): Buffer;
}
/**
* Creates and returns a `Decipher` object that uses the given `algorithm` and`password` (key).
*
* The `options` argument controls stream behavior and is optional except when a
* cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the
* authentication tag in bytes, see `CCM mode`.
* For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes.
*
* **This function is semantically insecure for all**
* **supported ciphers and fatally flawed for ciphers in counter mode (such as CTR,**
* **GCM, or CCM).**
*
* The implementation of `crypto.createDecipher()` derives keys using the OpenSSL
* function [`EVP_BytesToKey`](https://www.openssl.org/docs/man3.0/man3/EVP_BytesToKey.html) with the digest algorithm set to MD5, one
* iteration, and no salt. The lack of salt allows dictionary attacks as the same
* password always creates the same key. The low iteration count and
* non-cryptographically secure hash algorithm allow passwords to be tested very
* rapidly.
*
* In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man3.0/man3/EVP_BytesToKey.html) it is recommended that
* developers derive a key and IV on
* their own using {@link scrypt} and to use {@link createDecipheriv} to create the `Decipher` object.
* @since v0.1.94
* @depr |
ecated Since v10.0.0 - Use {@link createDecipheriv} instead.
* @param options `stream.transform` options
*/
function createDecipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): DecipherCCM;
/** @deprecated since v10.0.0 use `createDecipheriv()` */
function createDecipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): DecipherGCM;
/** @deprecated since v10.0.0 use `createDecipheriv()` */
function createDecipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Decipher;
/**
* Creates and returns a `Decipher` object that uses the given `algorithm`, `key`and initialization vector (`iv`).
*
* The `options` argument controls stream behavior and is optional except when a
* cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the
* authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to restrict accepted authentication tags
* to those with the specified length.
* For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes.
*
* The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On
* recent OpenSSL releases, `openssl list -cipher-algorithms` will
* display the available cipher algorithms.
*
* The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded
* strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be
* a `KeyObject` of type `secret`. If the cipher does not need
* an initialization vector, `iv` may be `null`.
*
* When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`.
*
* Initialization vectors should be unpredictable and unique; ideally, they will be
* cryptographically random. They do not have to be secret: IVs are typically just
* added to ciphertext messages unencrypted. It may sound contradictory that
* something has to be unpredictable and unique, but does not have to be secret;
* remember that an attacker must not be able to predict ahead of time what a given
* IV will be.
* @since v0.1.94
* @param options `stream.transform` options
*/
function createDecipheriv(
algorithm: CipherCCMTypes,
key: CipherKey,
iv: BinaryLike,
options: CipherCCMOptions,
): DecipherCCM;
function createDecipheriv(
algorithm: CipherOCBTypes,
key: CipherKey,
iv: BinaryLike,
options: CipherOCBOptions,
): DecipherOCB;
function createDecipheriv(
algorithm: CipherGCMTypes,
key: CipherKey,
iv: BinaryLike,
options?: CipherGCMOptions,
): DecipherGCM;
function createDecipheriv(
algorithm: string,
key: CipherKey,
iv: BinaryLike | null,
options?: stream.TransformOptions,
): Decipher;
/**
* Instances of the `Decipher` class are used to decrypt data. The class can be
* used in one of two ways:
*
* * As a `stream` that is both readable and writable, where plain encrypted
* data is written to produce unencrypted data on the readable side, or
* * Using the `decipher.update()` and `decipher.final()` methods to
* produce the unencrypted data.
*
* The {@link createDecipher} or {@link createDecipheriv} methods are
* used to create `Decipher` instances. `Decipher` objects are not to be created
* directly using the `new` keyword.
*
* Example: Using `Decipher` objects as streams:
*
* ```js
* import { Buffer } from 'node:buffer';
* const {
* scryptSync,
* createDecipheriv,
|
* } = await import('node:crypto');
*
* const algorithm = 'aes-192-cbc';
* const password = 'Password used to generate key';
* // Key length is dependent on the algorithm. In this case for aes192, it is
* // 24 bytes (192 bits).
* // Use the async `crypto.scrypt()` instead.
* const key = scryptSync(password, 'salt', 24);
* // The IV is usually passed along with the ciphertext.
* const iv = Buffer.alloc(16, 0); // Initialization vector.
*
* const decipher = createDecipheriv(algorithm, key, iv);
*
* let decrypted = '';
* decipher.on('readable', () => {
* let chunk;
* while (null !== (chunk = decipher.read())) {
* decrypted += chunk.toString('utf8');
* }
* });
* decipher.on('end', () => {
* console.log(decrypted);
* // Prints: some clear text data
* });
*
* // Encrypted with same algorithm, key and iv.
* const encrypted =
* 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';
* decipher.write(encrypted, 'hex');
* decipher.end();
* ```
*
* Example: Using `Decipher` and piped streams:
*
* ```js
* import {
* createReadStream,
* createWriteStream,
* } from 'node:fs';
* import { Buffer } from 'node:buffer';
* const {
* scryptSync,
* createDecipheriv,
* } = await import('node:crypto');
*
* const algorithm = 'aes-192-cbc';
* const password = 'Password used to generate key';
* // Use the async `crypto.scrypt()` instead.
* const key = scryptSync(password, 'salt', 24);
* // The IV is usually passed along with the ciphertext.
* const iv = Buffer.alloc(16, 0); // Initialization vector.
*
* const decipher = createDecipheriv(algorithm, key, iv);
*
* const input = createReadStream('test.enc');
* const output = createWriteStream('test.js');
*
* input.pipe(decipher).pipe(output);
* ```
*
* Example: Using the `decipher.update()` and `decipher.final()` methods:
*
* ```js
* import { Buffer } from 'node:buffer';
* const {
* scryptSync,
* createDecipheriv,
* } = await import('node:crypto');
*
* const algorithm = 'aes-192-cbc';
* const password = 'Password used to generate key';
* // Use the async `crypto.scrypt()` instead.
* const key = scryptSync(password, 'salt', 24);
* // The IV is usually passed along with the ciphertext.
* const iv = Buffer.alloc(16, 0); // Initialization vector.
*
* const decipher = createDecipheriv(algorithm, key, iv);
*
* // Encrypted using same algorithm, key and iv.
* const encrypted =
* 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';
* let decrypted = decipher.update(encrypted, 'hex', 'utf8');
* decrypted += decipher.final('utf8');
* console.log(decrypted);
* // Prints: some clear text data
* ```
* @since v0.1.94
*/
class Decipher extends stream.Transform {
private constructor();
/**
* Updates the decipher with `data`. If the `inputEncoding` argument is given,
* the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`. If `data` is a `Buffer` then `inputEncoding` is
* ignored.
*
* The `outputEncoding` specifies the output format of the enciphered
* data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned.
*
* The `decipher.update()` method can be called multiple times with new data until `decipher.final()` is called. Calling `decipher.update()` after `decipher.final()` will result in an error
* being thrown.
* @since v0.1.94
* @param inputEncoding T |
he `encoding` of the `data` string.
* @param outputEncoding The `encoding` of the return value.
*/
update(data: NodeJS.ArrayBufferView): Buffer;
update(data: string, inputEncoding: Encoding): Buffer;
update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string;
update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string;
/**
* Once the `decipher.final()` method has been called, the `Decipher` object can
* no longer be used to decrypt data. Attempts to call `decipher.final()` more
* than once will result in an error being thrown.
* @since v0.1.94
* @param outputEncoding The `encoding` of the return value.
* @return Any remaining deciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned.
*/
final(): Buffer;
final(outputEncoding: BufferEncoding): string;
/**
* When data has been encrypted without standard block padding, calling`decipher.setAutoPadding(false)` will disable automatic padding to prevent `decipher.final()` from checking for and
* removing padding.
*
* Turning auto padding off will only work if the input data's length is a
* multiple of the ciphers block size.
*
* The `decipher.setAutoPadding()` method must be called before `decipher.final()`.
* @since v0.7.1
* @param [autoPadding=true]
* @return for method chaining.
*/
setAutoPadding(auto_padding?: boolean): this;
}
interface DecipherCCM extends Decipher {
setAuthTag(buffer: NodeJS.ArrayBufferView): this;
setAAD(
buffer: NodeJS.ArrayBufferView,
options: {
plaintextLength: number;
},
): this;
}
interface DecipherGCM extends Decipher {
setAuthTag(buffer: NodeJS.ArrayBufferView): this;
setAAD(
buffer: NodeJS.ArrayBufferView,
options?: {
plaintextLength: number;
},
): this;
}
interface DecipherOCB extends Decipher {
setAuthTag(buffer: NodeJS.ArrayBufferView): this;
setAAD(
buffer: NodeJS.ArrayBufferView,
options?: {
plaintextLength: number;
},
): this;
}
interface PrivateKeyInput {
key: string | Buffer;
format?: KeyFormat | undefined;
type?: "pkcs1" | "pkcs8" | "sec1" | undefined;
passphrase?: string | Buffer | undefined;
encoding?: string | undefined;
}
interface PublicKeyInput {
key: string | Buffer;
format?: KeyFormat | undefined;
type?: "pkcs1" | "spki" | undefined;
encoding?: string | undefined;
}
/**
* Asynchronously generates a new random secret key of the given `length`. The`type` will determine which validations will be performed on the `length`.
*
* ```js
* const {
* generateKey,
* } = await import('node:crypto');
*
* generateKey('hmac', { length: 512 }, (err, key) => {
* if (err) throw err;
* console.log(key.export().toString('hex')); // 46e..........620
* });
* ```
*
* The size of a generated HMAC key should not exceed the block size of the
* underlying hash function. See {@link createHmac} for more information.
* @since v15.0.0
* @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`.
*/
function generateKey(
type: "hmac" | "aes",
options: {
length: number;
},
callback: (err: Error | null, key: KeyObject) => void,
): void;
/**
* Synchronously generates a new random secret key of the given `length`. The`type` |
will determine which validations will be performed on the `length`.
*
* ```js
* const {
* generateKeySync,
* } = await import('node:crypto');
*
* const key = generateKeySync('hmac', { length: 512 });
* console.log(key.export().toString('hex')); // e89..........41e
* ```
*
* The size of a generated HMAC key should not exceed the block size of the
* underlying hash function. See {@link createHmac} for more information.
* @since v15.0.0
* @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`.
*/
function generateKeySync(
type: "hmac" | "aes",
options: {
length: number;
},
): KeyObject;
interface JsonWebKeyInput {
key: JsonWebKey;
format: "jwk";
}
/**
* Creates and returns a new key object containing a private key. If `key` is a
* string or `Buffer`, `format` is assumed to be `'pem'`; otherwise, `key`must be an object with the properties described above.
*
* If the private key is encrypted, a `passphrase` must be specified. The length
* of the passphrase is limited to 1024 bytes.
* @since v11.6.0
*/
function createPrivateKey(key: PrivateKeyInput | string | Buffer | JsonWebKeyInput): KeyObject;
/**
* Creates and returns a new key object containing a public key. If `key` is a
* string or `Buffer`, `format` is assumed to be `'pem'`; if `key` is a `KeyObject`with type `'private'`, the public key is derived from the given private key;
* otherwise, `key` must be an object with the properties described above.
*
* If the format is `'pem'`, the `'key'` may also be an X.509 certificate.
*
* Because public keys can be derived from private keys, a private key may be
* passed instead of a public key. In that case, this function behaves as if {@link createPrivateKey} had been called, except that the type of the
* returned `KeyObject` will be `'public'` and that the private key cannot be
* extracted from the returned `KeyObject`. Similarly, if a `KeyObject` with type`'private'` is given, a new `KeyObject` with type `'public'` will be returned
* and it will be impossible to extract the private key from the returned object.
* @since v11.6.0
*/
function createPublicKey(key: PublicKeyInput | string | Buffer | KeyObject | JsonWebKeyInput): KeyObject;
/**
* Creates and returns a new key object containing a secret key for symmetric
* encryption or `Hmac`.
* @since v11.6.0
* @param encoding The string encoding when `key` is a string.
*/
function createSecretKey(key: NodeJS.ArrayBufferView): KeyObject;
function createSecretKey(key: string, encoding: BufferEncoding): KeyObject;
/**
* Creates and returns a `Sign` object that uses the given `algorithm`. Use {@link getHashes} to obtain the names of the available digest algorithms.
* Optional `options` argument controls the `stream.Writable` behavior.
*
* In some cases, a `Sign` instance can be created using the name of a signature
* algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use
* the corresponding digest algorithm. This does not work for all signature
* algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest
* algorithm names.
* @since v0.1.92
* @param options `stream.Writable` options
*/
function createSign(algorithm: string, options?: stream.WritableOptions): Sign;
type DSAEncoding = "der" | "ieee-p1363";
interface SigningOptions {
/**
* @see crypto.constants.RSA_PKCS1_PADDING
*/
padding?: number | undefined;
saltLength?: number | undefined;
dsaEncoding?: DSAEncoding | undefined;
}
interface SignPrivateKeyInput extends PrivateKeyInput, SigningOptions {}
interface SignKeyObj |
ectInput extends SigningOptions {
key: KeyObject;
}
interface VerifyPublicKeyInput extends PublicKeyInput, SigningOptions {}
interface VerifyKeyObjectInput extends SigningOptions {
key: KeyObject;
}
interface VerifyJsonWebKeyInput extends JsonWebKeyInput, SigningOptions {}
type KeyLike = string | Buffer | KeyObject;
/**
* The `Sign` class is a utility for generating signatures. It can be used in one
* of two ways:
*
* * As a writable `stream`, where data to be signed is written and the `sign.sign()` method is used to generate and return the signature, or
* * Using the `sign.update()` and `sign.sign()` methods to produce the
* signature.
*
* The {@link createSign} method is used to create `Sign` instances. The
* argument is the string name of the hash function to use. `Sign` objects are not
* to be created directly using the `new` keyword.
*
* Example: Using `Sign` and `Verify` objects as streams:
*
* ```js
* const {
* generateKeyPairSync,
* createSign,
* createVerify,
* } = await import('node:crypto');
*
* const { privateKey, publicKey } = generateKeyPairSync('ec', {
* namedCurve: 'sect239k1',
* });
*
* const sign = createSign('SHA256');
* sign.write('some data to sign');
* sign.end();
* const signature = sign.sign(privateKey, 'hex');
*
* const verify = createVerify('SHA256');
* verify.write('some data to sign');
* verify.end();
* console.log(verify.verify(publicKey, signature, 'hex'));
* // Prints: true
* ```
*
* Example: Using the `sign.update()` and `verify.update()` methods:
*
* ```js
* const {
* generateKeyPairSync,
* createSign,
* createVerify,
* } = await import('node:crypto');
*
* const { privateKey, publicKey } = generateKeyPairSync('rsa', {
* modulusLength: 2048,
* });
*
* const sign = createSign('SHA256');
* sign.update('some data to sign');
* sign.end();
* const signature = sign.sign(privateKey);
*
* const verify = createVerify('SHA256');
* verify.update('some data to sign');
* verify.end();
* console.log(verify.verify(publicKey, signature));
* // Prints: true
* ```
* @since v0.1.92
*/
class Sign extends stream.Writable {
private constructor();
/**
* Updates the `Sign` content with the given `data`, the encoding of which
* is given in `inputEncoding`.
* If `encoding` is not provided, and the `data` is a string, an
* encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored.
*
* This can be called many times with new data as it is streamed.
* @since v0.1.92
* @param inputEncoding The `encoding` of the `data` string.
*/
update(data: BinaryLike): this;
update(data: string, inputEncoding: Encoding): this;
/**
* Calculates the signature on all the data passed through using either `sign.update()` or `sign.write()`.
*
* If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an
* object, the following additional properties can be passed:
*
* If `outputEncoding` is provided a string is returned; otherwise a `Buffer` is returned.
*
* The `Sign` object can not be again used after `sign.sign()` method has been
* called. Multiple calls to `sign.sign()` will result in an error being thrown.
* @since v0.1.92
*/
sign(privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput): Buffer;
sign(
privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput,
outputFormat: Bi |
naryToTextEncoding,
): string;
}
/**
* Creates and returns a `Verify` object that uses the given algorithm.
* Use {@link getHashes} to obtain an array of names of the available
* signing algorithms. Optional `options` argument controls the`stream.Writable` behavior.
*
* In some cases, a `Verify` instance can be created using the name of a signature
* algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use
* the corresponding digest algorithm. This does not work for all signature
* algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest
* algorithm names.
* @since v0.1.92
* @param options `stream.Writable` options
*/
function createVerify(algorithm: string, options?: stream.WritableOptions): Verify;
/**
* The `Verify` class is a utility for verifying signatures. It can be used in one
* of two ways:
*
* * As a writable `stream` where written data is used to validate against the
* supplied signature, or
* * Using the `verify.update()` and `verify.verify()` methods to verify
* the signature.
*
* The {@link createVerify} method is used to create `Verify` instances.`Verify` objects are not to be created directly using the `new` keyword.
*
* See `Sign` for examples.
* @since v0.1.92
*/
class Verify extends stream.Writable {
private constructor();
/**
* Updates the `Verify` content with the given `data`, the encoding of which
* is given in `inputEncoding`.
* If `inputEncoding` is not provided, and the `data` is a string, an
* encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored.
*
* This can be called many times with new data as it is streamed.
* @since v0.1.92
* @param inputEncoding The `encoding` of the `data` string.
*/
update(data: BinaryLike): Verify;
update(data: string, inputEncoding: Encoding): Verify;
/**
* Verifies the provided data using the given `object` and `signature`.
*
* If `object` is not a `KeyObject`, this function behaves as if`object` had been passed to {@link createPublicKey}. If it is an
* object, the following additional properties can be passed:
*
* The `signature` argument is the previously calculated signature for the data, in
* the `signatureEncoding`.
* If a `signatureEncoding` is specified, the `signature` is expected to be a
* string; otherwise `signature` is expected to be a `Buffer`,`TypedArray`, or `DataView`.
*
* The `verify` object can not be used again after `verify.verify()` has been
* called. Multiple calls to `verify.verify()` will result in an error being
* thrown.
*
* Because public keys can be derived from private keys, a private key may
* be passed instead of a public key.
* @since v0.1.92
*/
verify(
object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput,
signature: NodeJS.ArrayBufferView,
): boolean;
verify(
object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput,
signature: string,
signature_format?: BinaryToTextEncoding,
): boolean;
}
/**
* Creates a `DiffieHellman` key exchange object using the supplied `prime` and an
* optional specific `generator`.
*
* The `generator` argument can be a number, string, or `Buffer`. If`generator` is not specified, the value `2` is used.
*
* If `primeEncoding` is specified, `prime` is expected to be a string; otherwise
* a `Buffer`, `TypedArray`, or `DataView` is expected.
*
* If `generatorEncoding` is specified, ` |
generator` is expected to be a string;
* otherwise a number, `Buffer`, `TypedArray`, or `DataView` is expected.
* @since v0.11.12
* @param primeEncoding The `encoding` of the `prime` string.
* @param [generator=2]
* @param generatorEncoding The `encoding` of the `generator` string.
*/
function createDiffieHellman(primeLength: number, generator?: number): DiffieHellman;
function createDiffieHellman(
prime: ArrayBuffer | NodeJS.ArrayBufferView,
generator?: number | ArrayBuffer | NodeJS.ArrayBufferView,
): DiffieHellman;
function createDiffieHellman(
prime: ArrayBuffer | NodeJS.ArrayBufferView,
generator: string,
generatorEncoding: BinaryToTextEncoding,
): DiffieHellman;
function createDiffieHellman(
prime: string,
primeEncoding: BinaryToTextEncoding,
generator?: number | ArrayBuffer | NodeJS.ArrayBufferView,
): DiffieHellman;
function createDiffieHellman(
prime: string,
primeEncoding: BinaryToTextEncoding,
generator: string,
generatorEncoding: BinaryToTextEncoding,
): DiffieHellman;
/**
* The `DiffieHellman` class is a utility for creating Diffie-Hellman key
* exchanges.
*
* Instances of the `DiffieHellman` class can be created using the {@link createDiffieHellman} function.
*
* ```js
* import assert from 'node:assert';
*
* const {
* createDiffieHellman,
* } = await import('node:crypto');
*
* // Generate Alice's keys...
* const alice = createDiffieHellman(2048);
* const aliceKey = alice.generateKeys();
*
* // Generate Bob's keys...
* const bob = createDiffieHellman(alice.getPrime(), alice.getGenerator());
* const bobKey = bob.generateKeys();
*
* // Exchange and generate the secret...
* const aliceSecret = alice.computeSecret(bobKey);
* const bobSecret = bob.computeSecret(aliceKey);
*
* // OK
* assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
* ```
* @since v0.5.0
*/
class DiffieHellman {
private constructor();
/**
* Generates private and public Diffie-Hellman key values unless they have been
* generated or computed already, and returns
* the public key in the specified `encoding`. This key should be
* transferred to the other party.
* If `encoding` is provided a string is returned; otherwise a `Buffer` is returned.
*
* This function is a thin wrapper around [`DH_generate_key()`](https://www.openssl.org/docs/man3.0/man3/DH_generate_key.html). In particular,
* once a private key has been generated or set, calling this function only updates
* the public key but does not generate a new private key.
* @since v0.5.0
* @param encoding The `encoding` of the return value.
*/
generateKeys(): Buffer;
generateKeys(encoding: BinaryToTextEncoding): string;
/**
* Computes the shared secret using `otherPublicKey` as the other
* party's public key and returns the computed shared secret. The supplied
* key is interpreted using the specified `inputEncoding`, and secret is
* encoded using specified `outputEncoding`.
* If the `inputEncoding` is not
* provided, `otherPublicKey` is expected to be a `Buffer`,`TypedArray`, or `DataView`.
*
* If `outputEncoding` is given a string is returned; otherwise, a `Buffer` is returned.
* @since v0.5.0
* @param inputEncoding The `encoding` of an `otherPublicKey` string.
* @param outputEncoding The `encoding` of the return value.
*/
computeSecret(otherPublicKey: NodeJS.ArrayBufferView, inputEncoding?: null, outputEncoding?: null): Buffer;
computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding |
, outputEncoding?: null): Buffer;
computeSecret(
otherPublicKey: NodeJS.ArrayBufferView,
inputEncoding: null,
outputEncoding: BinaryToTextEncoding,
): string;
computeSecret(
otherPublicKey: string,
inputEncoding: BinaryToTextEncoding,
outputEncoding: BinaryToTextEncoding,
): string;
/**
* Returns the Diffie-Hellman prime in the specified `encoding`.
* If `encoding` is provided a string is
* returned; otherwise a `Buffer` is returned.
* @since v0.5.0
* @param encoding The `encoding` of the return value.
*/
getPrime(): Buffer;
getPrime(encoding: BinaryToTextEncoding): string;
/**
* Returns the Diffie-Hellman generator in the specified `encoding`.
* If `encoding` is provided a string is
* returned; otherwise a `Buffer` is returned.
* @since v0.5.0
* @param encoding The `encoding` of the return value.
*/
getGenerator(): Buffer;
getGenerator(encoding: BinaryToTextEncoding): string;
/**
* Returns the Diffie-Hellman public key in the specified `encoding`.
* If `encoding` is provided a
* string is returned; otherwise a `Buffer` is returned.
* @since v0.5.0
* @param encoding The `encoding` of the return value.
*/
getPublicKey(): Buffer;
getPublicKey(encoding: BinaryToTextEncoding): string;
/**
* Returns the Diffie-Hellman private key in the specified `encoding`.
* If `encoding` is provided a
* string is returned; otherwise a `Buffer` is returned.
* @since v0.5.0
* @param encoding The `encoding` of the return value.
*/
getPrivateKey(): Buffer;
getPrivateKey(encoding: BinaryToTextEncoding): string;
/**
* Sets the Diffie-Hellman public key. If the `encoding` argument is provided,`publicKey` is expected
* to be a string. If no `encoding` is provided, `publicKey` is expected
* to be a `Buffer`, `TypedArray`, or `DataView`.
* @since v0.5.0
* @param encoding The `encoding` of the `publicKey` string.
*/
setPublicKey(publicKey: NodeJS.ArrayBufferView): void;
setPublicKey(publicKey: string, encoding: BufferEncoding): void;
/**
* Sets the Diffie-Hellman private key. If the `encoding` argument is provided,`privateKey` is expected
* to be a string. If no `encoding` is provided, `privateKey` is expected
* to be a `Buffer`, `TypedArray`, or `DataView`.
*
* This function does not automatically compute the associated public key. Either `diffieHellman.setPublicKey()` or `diffieHellman.generateKeys()` can be
* used to manually provide the public key or to automatically derive it.
* @since v0.5.0
* @param encoding The `encoding` of the `privateKey` string.
*/
setPrivateKey(privateKey: NodeJS.ArrayBufferView): void;
setPrivateKey(privateKey: string, encoding: BufferEncoding): void;
/**
* A bit field containing any warnings and/or errors resulting from a check
* performed during initialization of the `DiffieHellman` object.
*
* The following values are valid for this property (as defined in `node:constants` module):
*
* * `DH_CHECK_P_NOT_SAFE_PRIME`
* * `DH_CHECK_P_NOT_PRIME`
* * `DH_UNABLE_TO_CHECK_GENERATOR`
* * `DH_NOT_SUITABLE_GENERATOR`
* @since v0.11.12
*/
verifyError: number;
}
/**
* The `DiffieHellmanGroup` class takes a well-known modp group as its argument.
* It works the same as `DiffieHellman`, except that it does not allow changing its keys after creation.
* In other words, it does not implement `setPublicKey()` or `setPr |
ivateKey()` methods.
*
* ```js
* const { createDiffieHellmanGroup } = await import('node:crypto');
* const dh = createDiffieHellmanGroup('modp1');
* ```
* The name (e.g. `'modp1'`) is taken from [RFC 2412](https://www.rfc-editor.org/rfc/rfc2412.txt) (modp1 and 2) and [RFC 3526](https://www.rfc-editor.org/rfc/rfc3526.txt):
* ```bash
* $ perl -ne 'print "$1\n" if /"(modp\d+)"/' src/node_crypto_groups.h
* modp1 # 768 bits
* modp2 # 1024 bits
* modp5 # 1536 bits
* modp14 # 2048 bits
* modp15 # etc.
* modp16
* modp17
* modp18
* ```
* @since v0.7.5
*/
const DiffieHellmanGroup: DiffieHellmanGroupConstructor;
interface DiffieHellmanGroupConstructor {
new(name: string): DiffieHellmanGroup;
(name: string): DiffieHellmanGroup;
readonly prototype: DiffieHellmanGroup;
}
type DiffieHellmanGroup = Omit<DiffieHellman, "setPublicKey" | "setPrivateKey">;
/**
* Creates a predefined `DiffieHellmanGroup` key exchange object. The
* supported groups are listed in the documentation for `DiffieHellmanGroup`.
*
* The returned object mimics the interface of objects created by {@link createDiffieHellman}, but will not allow changing
* the keys (with `diffieHellman.setPublicKey()`, for example). The
* advantage of using this method is that the parties do not have to
* generate nor exchange a group modulus beforehand, saving both processor
* and communication time.
*
* Example (obtaining a shared secret):
*
* ```js
* const {
* getDiffieHellman,
* } = await import('node:crypto');
* const alice = getDiffieHellman('modp14');
* const bob = getDiffieHellman('modp14');
*
* alice.generateKeys();
* bob.generateKeys();
*
* const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
* const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
*
* // aliceSecret and bobSecret should be the same
* console.log(aliceSecret === bobSecret);
* ```
* @since v0.7.5
*/
function getDiffieHellman(groupName: string): DiffieHellmanGroup;
/**
* An alias for {@link getDiffieHellman}
* @since v0.9.3
*/
function createDiffieHellmanGroup(name: string): DiffieHellmanGroup;
/**
* Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2)
* implementation. A selected HMAC digest algorithm specified by `digest` is
* applied to derive a key of the requested byte length (`keylen`) from the`password`, `salt` and `iterations`.
*
* The supplied `callback` function is called with two arguments: `err` and`derivedKey`. If an error occurs while deriving the key, `err` will be set;
* otherwise `err` will be `null`. By default, the successfully generated`derivedKey` will be passed to the callback as a `Buffer`. An error will be
* thrown if any of the input arguments specify invalid values or types.
*
* The `iterations` argument must be a number set as high as possible. The
* higher the number of iterations, the more secure the derived key will be,
* but will take a longer amount of time to complete.
*
* The `salt` should be as unique as possible. It is recommended that a salt is
* random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details.
*
* When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`.
*
* ```js
* const {
* pbkdf2,
* } = await import('node:crypto');
*
* pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => {
* if (err) throw err;
* console.log(derivedKey.toString('hex')); // '3745e48...08d59ae'
* });
* ```
*
* A |
n array of supported digest functions can be retrieved using {@link getHashes}.
*
* This API uses libuv's threadpool, which can have surprising and
* negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information.
* @since v0.5.5
*/
function pbkdf2(
password: BinaryLike,
salt: BinaryLike,
iterations: number,
keylen: number,
digest: string,
callback: (err: Error | null, derivedKey: Buffer) => void,
): void;
/**
* Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2)
* implementation. A selected HMAC digest algorithm specified by `digest` is
* applied to derive a key of the requested byte length (`keylen`) from the`password`, `salt` and `iterations`.
*
* If an error occurs an `Error` will be thrown, otherwise the derived key will be
* returned as a `Buffer`.
*
* The `iterations` argument must be a number set as high as possible. The
* higher the number of iterations, the more secure the derived key will be,
* but will take a longer amount of time to complete.
*
* The `salt` should be as unique as possible. It is recommended that a salt is
* random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details.
*
* When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`.
*
* ```js
* const {
* pbkdf2Sync,
* } = await import('node:crypto');
*
* const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512');
* console.log(key.toString('hex')); // '3745e48...08d59ae'
* ```
*
* An array of supported digest functions can be retrieved using {@link getHashes}.
* @since v0.9.3
*/
function pbkdf2Sync(
password: BinaryLike,
salt: BinaryLike,
iterations: number,
keylen: number,
digest: string,
): Buffer;
/**
* Generates cryptographically strong pseudorandom data. The `size` argument
* is a number indicating the number of bytes to generate.
*
* If a `callback` function is provided, the bytes are generated asynchronously
* and the `callback` function is invoked with two arguments: `err` and `buf`.
* If an error occurs, `err` will be an `Error` object; otherwise it is `null`. The`buf` argument is a `Buffer` containing the generated bytes.
*
* ```js
* // Asynchronous
* const {
* randomBytes,
* } = await import('node:crypto');
*
* randomBytes(256, (err, buf) => {
* if (err) throw err;
* console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`);
* });
* ```
*
* If the `callback` function is not provided, the random bytes are generated
* synchronously and returned as a `Buffer`. An error will be thrown if
* there is a problem generating the bytes.
*
* ```js
* // Synchronous
* const {
* randomBytes,
* } = await import('node:crypto');
*
* const buf = randomBytes(256);
* console.log(
* `${buf.length} bytes of random data: ${buf.toString('hex')}`);
* ```
*
* The `crypto.randomBytes()` method will not complete until there is
* sufficient entropy available.
* This should normally never take longer than a few milliseconds. The only time
* when generating the random bytes may conceivably block for a longer period of
* time is right after boot, when the whole system is still low on entropy.
*
* This API uses libuv's threadpool, which can have surprising and
* negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information.
*
* The asynchronous version of `crypto.rand |
omBytes()` is carried out in a single
* threadpool request. To minimize threadpool task length variation, partition
* large `randomBytes` requests when doing so as part of fulfilling a client
* request.
* @since v0.5.8
* @param size The number of bytes to generate. The `size` must not be larger than `2**31 - 1`.
* @return if the `callback` function is not provided.
*/
function randomBytes(size: number): Buffer;
function randomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void;
function pseudoRandomBytes(size: number): Buffer;
function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void;
/**
* Return a random integer `n` such that `min <= n < max`. This
* implementation avoids [modulo bias](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modulo_bias).
*
* The range (`max - min`) must be less than 2**48. `min` and `max` must
* be [safe integers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger).
*
* If the `callback` function is not provided, the random integer is
* generated synchronously.
*
* ```js
* // Asynchronous
* const {
* randomInt,
* } = await import('node:crypto');
*
* randomInt(3, (err, n) => {
* if (err) throw err;
* console.log(`Random number chosen from (0, 1, 2): ${n}`);
* });
* ```
*
* ```js
* // Synchronous
* const {
* randomInt,
* } = await import('node:crypto');
*
* const n = randomInt(3);
* console.log(`Random number chosen from (0, 1, 2): ${n}`);
* ```
*
* ```js
* // With `min` argument
* const {
* randomInt,
* } = await import('node:crypto');
*
* const n = randomInt(1, 7);
* console.log(`The dice rolled: ${n}`);
* ```
* @since v14.10.0, v12.19.0
* @param [min=0] Start of random range (inclusive).
* @param max End of random range (exclusive).
* @param callback `function(err, n) {}`.
*/
function randomInt(max: number): number;
function randomInt(min: number, max: number): number;
function randomInt(max: number, callback: (err: Error | null, value: number) => void): void;
function randomInt(min: number, max: number, callback: (err: Error | null, value: number) => void): void;
/**
* Synchronous version of {@link randomFill}.
*
* ```js
* import { Buffer } from 'node:buffer';
* const { randomFillSync } = await import('node:crypto');
*
* const buf = Buffer.alloc(10);
* console.log(randomFillSync(buf).toString('hex'));
*
* randomFillSync(buf, 5);
* console.log(buf.toString('hex'));
*
* // The above is equivalent to the following:
* randomFillSync(buf, 5, 5);
* console.log(buf.toString('hex'));
* ```
*
* Any `ArrayBuffer`, `TypedArray` or `DataView` instance may be passed as`buffer`.
*
* ```js
* import { Buffer } from 'node:buffer';
* const { randomFillSync } = await import('node:crypto');
*
* const a = new Uint32Array(10);
* console.log(Buffer.from(randomFillSync(a).buffer,
* a.byteOffset, a.byteLength).toString('hex'));
*
* const b = new DataView(new ArrayBuffer(10));
* console.log(Buffer.from(randomFillSync(b).buffer,
* b.byteOffset, b.byteLength).toString('hex'));
*
* const c = new ArrayBuffer(10);
* console.log(Buffer.from(randomFillSync(c)).toString('hex'));
* ```
* @since v7.10.0, v6.13.0
* @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`.
* @param [offset=0]
* @param [size=buffer.length - offset]
* @return The object passed as `buffer` argument.
*/
function randomFillSync<T ext |
ends NodeJS.ArrayBufferView>(buffer: T, offset?: number, size?: number): T;
/**
* This function is similar to {@link randomBytes} but requires the first
* argument to be a `Buffer` that will be filled. It also
* requires that a callback is passed in.
*
* If the `callback` function is not provided, an error will be thrown.
*
* ```js
* import { Buffer } from 'node:buffer';
* const { randomFill } = await import('node:crypto');
*
* const buf = Buffer.alloc(10);
* randomFill(buf, (err, buf) => {
* if (err) throw err;
* console.log(buf.toString('hex'));
* });
*
* randomFill(buf, 5, (err, buf) => {
* if (err) throw err;
* console.log(buf.toString('hex'));
* });
*
* // The above is equivalent to the following:
* randomFill(buf, 5, 5, (err, buf) => {
* if (err) throw err;
* console.log(buf.toString('hex'));
* });
* ```
*
* Any `ArrayBuffer`, `TypedArray`, or `DataView` instance may be passed as`buffer`.
*
* While this includes instances of `Float32Array` and `Float64Array`, this
* function should not be used to generate random floating-point numbers. The
* result may contain `+Infinity`, `-Infinity`, and `NaN`, and even if the array
* contains finite numbers only, they are not drawn from a uniform random
* distribution and have no meaningful lower or upper bounds.
*
* ```js
* import { Buffer } from 'node:buffer';
* const { randomFill } = await import('node:crypto');
*
* const a = new Uint32Array(10);
* randomFill(a, (err, buf) => {
* if (err) throw err;
* console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
* .toString('hex'));
* });
*
* const b = new DataView(new ArrayBuffer(10));
* randomFill(b, (err, buf) => {
* if (err) throw err;
* console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
* .toString('hex'));
* });
*
* const c = new ArrayBuffer(10);
* randomFill(c, (err, buf) => {
* if (err) throw err;
* console.log(Buffer.from(buf).toString('hex'));
* });
* ```
*
* This API uses libuv's threadpool, which can have surprising and
* negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information.
*
* The asynchronous version of `crypto.randomFill()` is carried out in a single
* threadpool request. To minimize threadpool task length variation, partition
* large `randomFill` requests when doing so as part of fulfilling a client
* request.
* @since v7.10.0, v6.13.0
* @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`.
* @param [offset=0]
* @param [size=buffer.length - offset]
* @param callback `function(err, buf) {}`.
*/
function randomFill<T extends NodeJS.ArrayBufferView>(
buffer: T,
callback: (err: Error | null, buf: T) => void,
): void;
function randomFill<T extends NodeJS.ArrayBufferView>(
buffer: T,
offset: number,
callback: (err: Error | null, buf: T) => void,
): void;
function randomFill<T extends NodeJS.ArrayBufferView>(
buffer: T,
offset: number,
size: number,
callback: (err: Error | null, buf: T) => void,
): void;
interface ScryptOptions {
cost?: number | undefined;
blockSize?: number | undefined;
parallelization?: number | undefined;
N?: number | undefined;
r?: number | undefined;
p?: number | undefined;
maxmem?: number | undefined;
}
/**
* Provides an asynchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based
* key derivation function that is designed to be expensive computational |
ly and
* memory-wise in order to make brute-force attacks unrewarding.
*
* The `salt` should be as unique as possible. It is recommended that a salt is
* random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details.
*
* When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`.
*
* The `callback` function is called with two arguments: `err` and `derivedKey`.`err` is an exception object when key derivation fails, otherwise `err` is`null`. `derivedKey` is passed to the
* callback as a `Buffer`.
*
* An exception is thrown when any of the input arguments specify invalid values
* or types.
*
* ```js
* const {
* scrypt,
* } = await import('node:crypto');
*
* // Using the factory defaults.
* scrypt('password', 'salt', 64, (err, derivedKey) => {
* if (err) throw err;
* console.log(derivedKey.toString('hex')); // '3745e48...08d59ae'
* });
* // Using a custom N parameter. Must be a power of two.
* scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => {
* if (err) throw err;
* console.log(derivedKey.toString('hex')); // '3745e48...aa39b34'
* });
* ```
* @since v10.5.0
*/
function scrypt(
password: BinaryLike,
salt: BinaryLike,
keylen: number,
callback: (err: Error | null, derivedKey: Buffer) => void,
): void;
function scrypt(
password: BinaryLike,
salt: BinaryLike,
keylen: number,
options: ScryptOptions,
callback: (err: Error | null, derivedKey: Buffer) => void,
): void;
/**
* Provides a synchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based
* key derivation function that is designed to be expensive computationally and
* memory-wise in order to make brute-force attacks unrewarding.
*
* The `salt` should be as unique as possible. It is recommended that a salt is
* random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details.
*
* When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`.
*
* An exception is thrown when key derivation fails, otherwise the derived key is
* returned as a `Buffer`.
*
* An exception is thrown when any of the input arguments specify invalid values
* or types.
*
* ```js
* const {
* scryptSync,
* } = await import('node:crypto');
* // Using the factory defaults.
*
* const key1 = scryptSync('password', 'salt', 64);
* console.log(key1.toString('hex')); // '3745e48...08d59ae'
* // Using a custom N parameter. Must be a power of two.
* const key2 = scryptSync('password', 'salt', 64, { N: 1024 });
* console.log(key2.toString('hex')); // '3745e48...aa39b34'
* ```
* @since v10.5.0
*/
function scryptSync(password: BinaryLike, salt: BinaryLike, keylen: number, options?: ScryptOptions): Buffer;
interface RsaPublicKey {
key: KeyLike;
padding?: number | undefined;
}
interface RsaPrivateKey {
key: KeyLike;
passphrase?: string | undefined;
/**
* @default 'sha1'
*/
oaepHash?: string | undefined;
oaepLabel?: NodeJS.TypedArray | undefined;
padding?: number | undefined;
}
/**
* Encrypts the content of `buffer` with `key` and returns a new `Buffer` with encrypted content. The returned data can be decrypted using
* the corresponding private key, for example using {@link privateDecrypt}.
*
* If `key` is not a `KeyObject`, this function behaves as if`key` h |
ad been passed to {@link createPublicKey}. If it is an
* object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_OAEP_PADDING`.
*
* Because RSA public keys can be derived from private keys, a private key may
* be passed instead of a public key.
* @since v0.11.14
*/
function publicEncrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer;
/**
* Decrypts `buffer` with `key`.`buffer` was previously encrypted using
* the corresponding private key, for example using {@link privateEncrypt}.
*
* If `key` is not a `KeyObject`, this function behaves as if`key` had been passed to {@link createPublicKey}. If it is an
* object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_PADDING`.
*
* Because RSA public keys can be derived from private keys, a private key may
* be passed instead of a public key.
* @since v1.1.0
*/
function publicDecrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer;
/**
* Decrypts `buffer` with `privateKey`. `buffer` was previously encrypted using
* the corresponding public key, for example using {@link publicEncrypt}.
*
* If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an
* object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_OAEP_PADDING`.
* @since v0.11.14
*/
function privateDecrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer;
/**
* Encrypts `buffer` with `privateKey`. The returned data can be decrypted using
* the corresponding public key, for example using {@link publicDecrypt}.
*
* If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an
* object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_PADDING`.
* @since v1.1.0
*/
function privateEncrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer;
/**
* ```js
* const {
* getCiphers,
* } = await import('node:crypto');
*
* console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...]
* ```
* @since v0.9.3
* @return An array with the names of the supported cipher algorithms.
*/
function getCiphers(): string[];
/**
* ```js
* const {
* getCurves,
* } = await import('node:crypto');
*
* console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]
* ```
* @since v2.3.0
* @return An array with the names of the supported elliptic curves.
*/
function getCurves(): string[];
/**
* @since v10.0.0
* @return `1` if and only if a FIPS compliant crypto provider is currently in use, `0` otherwise. A future semver-major release may change the return type of this API to a {boolean}.
*/
function getFips(): 1 | 0;
/**
* Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build.
* Throws an error if FIPS mode is not available.
* @since v10.0.0
* @param bool `true` to enable FIPS mode.
*/
function setFips(bool: boolean): void;
/**
* ```js
* const {
* getHashes,
* } = await import('node:crypto');
*
* console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]
* ```
* @since v0.9.3
* @return An array of the names of the supported hash algorithms, such as `'RSA-SHA256'`. Hash algorithms are also called "digest" algorithms.
*/
function getHashes(): string[];
/**
* The `ECDH` class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH)
* key exchanges.
*
* Instances of the `ECDH` class can be created using the |
{@link createECDH} function.
*
* ```js
* import assert from 'node:assert';
*
* const {
* createECDH,
* } = await import('node:crypto');
*
* // Generate Alice's keys...
* const alice = createECDH('secp521r1');
* const aliceKey = alice.generateKeys();
*
* // Generate Bob's keys...
* const bob = createECDH('secp521r1');
* const bobKey = bob.generateKeys();
*
* // Exchange and generate the secret...
* const aliceSecret = alice.computeSecret(bobKey);
* const bobSecret = bob.computeSecret(aliceKey);
*
* assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
* // OK
* ```
* @since v0.11.14
*/
class ECDH {
private constructor();
/**
* Converts the EC Diffie-Hellman public key specified by `key` and `curve` to the
* format specified by `format`. The `format` argument specifies point encoding
* and can be `'compressed'`, `'uncompressed'` or `'hybrid'`. The supplied key is
* interpreted using the specified `inputEncoding`, and the returned key is encoded
* using the specified `outputEncoding`.
*
* Use {@link getCurves} to obtain a list of available curve names.
* On recent OpenSSL releases, `openssl ecparam -list_curves` will also display
* the name and description of each available elliptic curve.
*
* If `format` is not specified the point will be returned in `'uncompressed'`format.
*
* If the `inputEncoding` is not provided, `key` is expected to be a `Buffer`,`TypedArray`, or `DataView`.
*
* Example (uncompressing a key):
*
* ```js
* const {
* createECDH,
* ECDH,
* } = await import('node:crypto');
*
* const ecdh = createECDH('secp256k1');
* ecdh.generateKeys();
*
* const compressedKey = ecdh.getPublicKey('hex', 'compressed');
*
* const uncompressedKey = ECDH.convertKey(compressedKey,
* 'secp256k1',
* 'hex',
* 'hex',
* 'uncompressed');
*
* // The converted key and the uncompressed public key should be the same
* console.log(uncompressedKey === ecdh.getPublicKey('hex'));
* ```
* @since v10.0.0
* @param inputEncoding The `encoding` of the `key` string.
* @param outputEncoding The `encoding` of the return value.
* @param [format='uncompressed']
*/
static convertKey(
key: BinaryLike,
curve: string,
inputEncoding?: BinaryToTextEncoding,
outputEncoding?: "latin1" | "hex" | "base64" | "base64url",
format?: "uncompressed" | "compressed" | "hybrid",
): Buffer | string;
/**
* Generates private and public EC Diffie-Hellman key values, and returns
* the public key in the specified `format` and `encoding`. This key should be
* transferred to the other party.
*
* The `format` argument specifies point encoding and can be `'compressed'` or`'uncompressed'`. If `format` is not specified, the point will be returned in`'uncompressed'` format.
*
* If `encoding` is provided a string is returned; otherwise a `Buffer` is returned.
* @since v0.11.14
* @param encoding The `encoding` of the return value.
* @param [format='uncompressed']
*/
generateKeys(): Buffer;
generateKeys(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string;
/**
* Computes the shared secret using `otherPublicKey` as the other
* party's public key and returns the computed sh |
ared secret. The supplied
* key is interpreted using specified `inputEncoding`, and the returned secret
* is encoded using the specified `outputEncoding`.
* If the `inputEncoding` is not
* provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or`DataView`.
*
* If `outputEncoding` is given a string will be returned; otherwise a `Buffer` is returned.
*
* `ecdh.computeSecret` will throw an`ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY` error when `otherPublicKey`lies outside of the elliptic curve. Since `otherPublicKey` is
* usually supplied from a remote user over an insecure network,
* be sure to handle this exception accordingly.
* @since v0.11.14
* @param inputEncoding The `encoding` of the `otherPublicKey` string.
* @param outputEncoding The `encoding` of the return value.
*/
computeSecret(otherPublicKey: NodeJS.ArrayBufferView): Buffer;
computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding): Buffer;
computeSecret(otherPublicKey: NodeJS.ArrayBufferView, outputEncoding: BinaryToTextEncoding): string;
computeSecret(
otherPublicKey: string,
inputEncoding: BinaryToTextEncoding,
outputEncoding: BinaryToTextEncoding,
): string;
/**
* If `encoding` is specified, a string is returned; otherwise a `Buffer` is
* returned.
* @since v0.11.14
* @param encoding The `encoding` of the return value.
* @return The EC Diffie-Hellman in the specified `encoding`.
*/
getPrivateKey(): Buffer;
getPrivateKey(encoding: BinaryToTextEncoding): string;
/**
* The `format` argument specifies point encoding and can be `'compressed'` or`'uncompressed'`. If `format` is not specified the point will be returned in`'uncompressed'` format.
*
* If `encoding` is specified, a string is returned; otherwise a `Buffer` is
* returned.
* @since v0.11.14
* @param encoding The `encoding` of the return value.
* @param [format='uncompressed']
* @return The EC Diffie-Hellman public key in the specified `encoding` and `format`.
*/
getPublicKey(encoding?: null, format?: ECDHKeyFormat): Buffer;
getPublicKey(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string;
/**
* Sets the EC Diffie-Hellman private key.
* If `encoding` is provided, `privateKey` is expected
* to be a string; otherwise `privateKey` is expected to be a `Buffer`,`TypedArray`, or `DataView`.
*
* If `privateKey` is not valid for the curve specified when the `ECDH` object was
* created, an error is thrown. Upon setting the private key, the associated
* public point (key) is also generated and set in the `ECDH` object.
* @since v0.11.14
* @param encoding The `encoding` of the `privateKey` string.
*/
setPrivateKey(privateKey: NodeJS.ArrayBufferView): void;
setPrivateKey(privateKey: string, encoding: BinaryToTextEncoding): void;
}
/**
* Creates an Elliptic Curve Diffie-Hellman (`ECDH`) key exchange object using a
* predefined curve specified by the `curveName` string. Use {@link getCurves} to obtain a list of available curve names. On recent
* OpenSSL releases, `openssl ecparam -list_curves` will also display the name
* and description of each available elliptic curve.
* @since v0.11.14
*/
function createECDH(curveName: string): ECDH;
/**
* This function compares the underlying bytes that represent the given`ArrayBuffer`, `TypedArray`, or `DataView` instances using a constant-time
* algorithm.
*
* This function does not leak timing information that
* would allow an attacker to guess one of the values. This is suitable for
|
* comparing HMAC digests or secret values like authentication cookies or [capability urls](https://www.w3.org/TR/capability-urls/).
*
* `a` and `b` must both be `Buffer`s, `TypedArray`s, or `DataView`s, and they
* must have the same byte length. An error is thrown if `a` and `b` have
* different byte lengths.
*
* If at least one of `a` and `b` is a `TypedArray` with more than one byte per
* entry, such as `Uint16Array`, the result will be computed using the platform
* byte order.
*
* **When both of the inputs are `Float32Array`s or`Float64Array`s, this function might return unexpected results due to IEEE 754**
* **encoding of floating-point numbers. In particular, neither `x === y` nor`Object.is(x, y)` implies that the byte representations of two floating-point**
* **numbers `x` and `y` are equal.**
*
* Use of `crypto.timingSafeEqual` does not guarantee that the _surrounding_ code
* is timing-safe. Care should be taken to ensure that the surrounding code does
* not introduce timing vulnerabilities.
* @since v6.6.0
*/
function timingSafeEqual(a: NodeJS.ArrayBufferView, b: NodeJS.ArrayBufferView): boolean;
type KeyType = "rsa" | "rsa-pss" | "dsa" | "ec" | "ed25519" | "ed448" | "x25519" | "x448";
type KeyFormat = "pem" | "der" | "jwk";
interface BasePrivateKeyEncodingOptions<T extends KeyFormat> {
format: T;
cipher?: string | undefined;
passphrase?: string | undefined;
}
interface KeyPairKeyObjectResult {
publicKey: KeyObject;
privateKey: KeyObject;
}
interface ED25519KeyPairKeyObjectOptions {}
interface ED448KeyPairKeyObjectOptions {}
interface X25519KeyPairKeyObjectOptions {}
interface X448KeyPairKeyObjectOptions {}
interface ECKeyPairKeyObjectOptions {
/**
* Name of the curve to use
*/
namedCurve: string;
/**
* Must be `'named'` or `'explicit'`. Default: `'named'`.
*/
paramEncoding?: "explicit" | "named" | undefined;
}
interface RSAKeyPairKeyObjectOptions {
/**
* Key size in bits
*/
modulusLength: number;
/**
* Public exponent
* @default 0x10001
*/
publicExponent?: number | undefined;
}
interface RSAPSSKeyPairKeyObjectOptions {
/**
* Key size in bits
*/
modulusLength: number;
/**
* Public exponent
* @default 0x10001
*/
publicExponent?: number | undefined;
/**
* Name of the message digest
*/
hashAlgorithm?: string;
/**
* Name of the message digest used by MGF1
*/
mgf1HashAlgorithm?: string;
/**
* Minimal salt length in bytes
*/
saltLength?: string;
}
interface DSAKeyPairKeyObjectOptions {
/**
* Key size in bits
*/
modulusLength: number;
/**
* Size of q in bits
*/
divisorLength: number;
}
interface RSAKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
/**
* Key size in bits
*/
modulusLength: number;
/**
* Public exponent
* @default 0x10001
*/
publicExponent?: number | undefined;
publicKeyEncoding: {
type: "pkcs1" | "spki";
format: PubF;
};
privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
type: "pkcs1" | "pkcs8";
};
}
interface RSAPSSKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
/**
* Key size in bits
*/
modulusLength: number;
/**
* Public exponent
* @default 0x10001
*/
publicExponent?: number | undefined;
/**
* Name of the message digest
|
*/
hashAlgorithm?: string;
/**
* Name of the message digest used by MGF1
*/
mgf1HashAlgorithm?: string;
/**
* Minimal salt length in bytes
*/
saltLength?: string;
publicKeyEncoding: {
type: "spki";
format: PubF;
};
privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
type: "pkcs8";
};
}
interface DSAKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
/**
* Key size in bits
*/
modulusLength: number;
/**
* Size of q in bits
*/
divisorLength: number;
publicKeyEncoding: {
type: "spki";
format: PubF;
};
privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
type: "pkcs8";
};
}
interface ECKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> extends ECKeyPairKeyObjectOptions {
publicKeyEncoding: {
type: "pkcs1" | "spki";
format: PubF;
};
privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
type: "sec1" | "pkcs8";
};
}
interface ED25519KeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
publicKeyEncoding: {
type: "spki";
format: PubF;
};
privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
type: "pkcs8";
};
}
interface ED448KeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
publicKeyEncoding: {
type: "spki";
format: PubF;
};
privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
type: "pkcs8";
};
}
interface X25519KeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
publicKeyEncoding: {
type: "spki";
format: PubF;
};
privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
type: "pkcs8";
};
}
interface X448KeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
publicKeyEncoding: {
type: "spki";
format: PubF;
};
privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
type: "pkcs8";
};
}
interface KeyPairSyncResult<T1 extends string | Buffer, T2 extends string | Buffer> {
publicKey: T1;
privateKey: T2;
}
/**
* Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC,
* Ed25519, Ed448, X25519, X448, and DH are currently supported.
*
* If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function
* behaves as if `keyObject.export()` had been called on its result. Otherwise,
* the respective part of the key is returned as a `KeyObject`.
*
* When encoding public keys, it is recommended to use `'spki'`. When encoding
* private keys, it is recommended to use `'pkcs8'` with a strong passphrase,
* and to keep the passphrase confidential.
*
* ```js
* const {
* generateKeyPairSync,
* } = await import('node:crypto');
*
* const {
* publicKey,
* privateKey,
* } = generateKeyPairSync('rsa', {
* modulusLength: 4096,
* publicKeyEncoding: {
* type: 'spki',
* format: 'pem',
* },
* privateKeyEncoding: {
* type: 'pkcs8',
* format: 'pem',
* cipher: 'aes-256-cbc',
* passphrase: 'top secret',
* },
* });
* ```
*
* The return value `{ publicKey, privateKey }` represents the generated key pair.
* When PEM encoding was selected, the respective key will be a string, otherwise
* it will be a buffer containing the data encoded as DER.
* @since v10.12.0
* @param type Must be `'rsa'`, `'rsa- |
pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`.
*/
function generateKeyPairSync(
type: "rsa",
options: RSAKeyPairOptions<"pem", "pem">,
): KeyPairSyncResult<string, string>;
function generateKeyPairSync(
type: "rsa",
options: RSAKeyPairOptions<"pem", "der">,
): KeyPairSyncResult<string, Buffer>;
function generateKeyPairSync(
type: "rsa",
options: RSAKeyPairOptions<"der", "pem">,
): KeyPairSyncResult<Buffer, string>;
function generateKeyPairSync(
type: "rsa",
options: RSAKeyPairOptions<"der", "der">,
): KeyPairSyncResult<Buffer, Buffer>;
function generateKeyPairSync(type: "rsa", options: RSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult;
function generateKeyPairSync(
type: "rsa-pss",
options: RSAPSSKeyPairOptions<"pem", "pem">,
): KeyPairSyncResult<string, string>;
function generateKeyPairSync(
type: "rsa-pss",
options: RSAPSSKeyPairOptions<"pem", "der">,
): KeyPairSyncResult<string, Buffer>;
function generateKeyPairSync(
type: "rsa-pss",
options: RSAPSSKeyPairOptions<"der", "pem">,
): KeyPairSyncResult<Buffer, string>;
function generateKeyPairSync(
type: "rsa-pss",
options: RSAPSSKeyPairOptions<"der", "der">,
): KeyPairSyncResult<Buffer, Buffer>;
function generateKeyPairSync(type: "rsa-pss", options: RSAPSSKeyPairKeyObjectOptions): KeyPairKeyObjectResult;
function generateKeyPairSync(
type: "dsa",
options: DSAKeyPairOptions<"pem", "pem">,
): KeyPairSyncResult<string, string>;
function generateKeyPairSync(
type: "dsa",
options: DSAKeyPairOptions<"pem", "der">,
): KeyPairSyncResult<string, Buffer>;
function generateKeyPairSync(
type: "dsa",
options: DSAKeyPairOptions<"der", "pem">,
): KeyPairSyncResult<Buffer, string>;
function generateKeyPairSync(
type: "dsa",
options: DSAKeyPairOptions<"der", "der">,
): KeyPairSyncResult<Buffer, Buffer>;
function generateKeyPairSync(type: "dsa", options: DSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult;
function generateKeyPairSync(
type: "ec",
options: ECKeyPairOptions<"pem", "pem">,
): KeyPairSyncResult<string, string>;
function generateKeyPairSync(
type: "ec",
options: ECKeyPairOptions<"pem", "der">,
): KeyPairSyncResult<string, Buffer>;
function generateKeyPairSync(
type: "ec",
options: ECKeyPairOptions<"der", "pem">,
): KeyPairSyncResult<Buffer, string>;
function generateKeyPairSync(
type: "ec",
options: ECKeyPairOptions<"der", "der">,
): KeyPairSyncResult<Buffer, Buffer>;
function generateKeyPairSync(type: "ec", options: ECKeyPairKeyObjectOptions): KeyPairKeyObjectResult;
function generateKeyPairSync(
type: "ed25519",
options: ED25519KeyPairOptions<"pem", "pem">,
): KeyPairSyncResult<string, string>;
function generateKeyPairSync(
type: "ed25519",
options: ED25519KeyPairOptions<"pem", "der">,
): KeyPairSyncResult<string, Buffer>;
function generateKeyPairSync(
type: "ed25519",
options: ED25519KeyPairOptions<"der", "pem">,
): KeyPairSyncResult<Buffer, string>;
function generateKeyPairSync(
type: "ed25519",
options: ED25519KeyPairOptions<"der", "der">,
): KeyPairSyncResult<Buffer, Buffer>;
function generateKeyPairSync(type: "ed25519", options?: ED25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult;
function generateKeyPairSync(
type: "ed448",
options: ED448KeyPairOptions<"pem", "pem">,
): KeyPairSyncResult<string, string>;
function generateKeyPairSync(
type: "ed448",
options: ED448KeyPairOptions<"pem", "der">,
): KeyPairSyncResult<string, Buffer>;
function generateKeyPairSync(
type: "ed448",
|
options: ED448KeyPairOptions<"der", "pem">,
): KeyPairSyncResult<Buffer, string>;
function generateKeyPairSync(
type: "ed448",
options: ED448KeyPairOptions<"der", "der">,
): KeyPairSyncResult<Buffer, Buffer>;
function generateKeyPairSync(type: "ed448", options?: ED448KeyPairKeyObjectOptions): KeyPairKeyObjectResult;
function generateKeyPairSync(
type: "x25519",
options: X25519KeyPairOptions<"pem", "pem">,
): KeyPairSyncResult<string, string>;
function generateKeyPairSync(
type: "x25519",
options: X25519KeyPairOptions<"pem", "der">,
): KeyPairSyncResult<string, Buffer>;
function generateKeyPairSync(
type: "x25519",
options: X25519KeyPairOptions<"der", "pem">,
): KeyPairSyncResult<Buffer, string>;
function generateKeyPairSync(
type: "x25519",
options: X25519KeyPairOptions<"der", "der">,
): KeyPairSyncResult<Buffer, Buffer>;
function generateKeyPairSync(type: "x25519", options?: X25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult;
function generateKeyPairSync(
type: "x448",
options: X448KeyPairOptions<"pem", "pem">,
): KeyPairSyncResult<string, string>;
function generateKeyPairSync(
type: "x448",
options: X448KeyPairOptions<"pem", "der">,
): KeyPairSyncResult<string, Buffer>;
function generateKeyPairSync(
type: "x448",
options: X448KeyPairOptions<"der", "pem">,
): KeyPairSyncResult<Buffer, string>;
function generateKeyPairSync(
type: "x448",
options: X448KeyPairOptions<"der", "der">,
): KeyPairSyncResult<Buffer, Buffer>;
function generateKeyPairSync(type: "x448", options?: X448KeyPairKeyObjectOptions): KeyPairKeyObjectResult;
/**
* Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC,
* Ed25519, Ed448, X25519, X448, and DH are currently supported.
*
* If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function
* behaves as if `keyObject.export()` had been called on its result. Otherwise,
* the respective part of the key is returned as a `KeyObject`.
*
* It is recommended to encode public keys as `'spki'` and private keys as`'pkcs8'` with encryption for long-term storage:
*
* ```js
* const {
* generateKeyPair,
* } = await import('node:crypto');
*
* generateKeyPair('rsa', {
* modulusLength: 4096,
* publicKeyEncoding: {
* type: 'spki',
* format: 'pem',
* },
* privateKeyEncoding: {
* type: 'pkcs8',
* format: 'pem',
* cipher: 'aes-256-cbc',
* passphrase: 'top secret',
* },
* }, (err, publicKey, privateKey) => {
* // Handle errors and use the generated key pair.
* });
* ```
*
* On completion, `callback` will be called with `err` set to `undefined` and`publicKey` / `privateKey` representing the generated key pair.
*
* If this method is invoked as its `util.promisify()` ed version, it returns
* a `Promise` for an `Object` with `publicKey` and `privateKey` properties.
* @since v10.12.0
* @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`.
*/
function generateKeyPair(
type: "rsa",
options: RSAKeyPairOptions<"pem", "pem">,
callback: (err: Error | null, publicKey: string, privateKey: string) => void,
): void;
function generateKeyPair(
type: "rsa",
options: RSAKeyPairOptions<"pem", "der">,
callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void,
): void;
function generateKeyPair(
type: "rsa",
options: RSAKeyPairOptions<"der", "pem">,
callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void,
): void;
function generateKeyPair(
type: |
"rsa",
options: RSAKeyPairOptions<"der", "der">,
callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void,
): void;
function generateKeyPair(
type: "rsa",
options: RSAKeyPairKeyObjectOptions,
callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void,
): void;
function generateKeyPair(
type: "rsa-pss",
options: RSAPSSKeyPairOptions<"pem", "pem">,
callback: (err: Error | null, publicKey: string, privateKey: string) => void,
): void;
function generateKeyPair(
type: "rsa-pss",
options: RSAPSSKeyPairOptions<"pem", "der">,
callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void,
): void;
function generateKeyPair(
type: "rsa-pss",
options: RSAPSSKeyPairOptions<"der", "pem">,
callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void,
): void;
function generateKeyPair(
type: "rsa-pss",
options: RSAPSSKeyPairOptions<"der", "der">,
callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void,
): void;
function generateKeyPair(
type: "rsa-pss",
options: RSAPSSKeyPairKeyObjectOptions,
callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void,
): void;
function generateKeyPair(
type: "dsa",
options: DSAKeyPairOptions<"pem", "pem">,
callback: (err: Error | null, publicKey: string, privateKey: string) => void,
): void;
function generateKeyPair(
type: "dsa",
options: DSAKeyPairOptions<"pem", "der">,
callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void,
): void;
function generateKeyPair(
type: "dsa",
options: DSAKeyPairOptions<"der", "pem">,
callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void,
): void;
function generateKeyPair(
type: "dsa",
options: DSAKeyPairOptions<"der", "der">,
callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void,
): void;
function generateKeyPair(
type: "dsa",
options: DSAKeyPairKeyObjectOptions,
callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void,
): void;
function generateKeyPair(
type: "ec",
options: ECKeyPairOptions<"pem", "pem">,
callback: (err: Error | null, publicKey: string, privateKey: string) => void,
): void;
function generateKeyPair(
type: "ec",
options: ECKeyPairOptions<"pem", "der">,
callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void,
): void;
function generateKeyPair(
type: "ec",
options: ECKeyPairOptions<"der", "pem">,
callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void,
): void;
function generateKeyPair(
type: "ec",
options: ECKeyPairOptions<"der", "der">,
callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void,
): void;
function generateKeyPair(
type: "ec",
options: ECKeyPairKeyObjectOptions,
callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void,
): void;
function generateKeyPair(
type: "ed25519",
options: ED25519KeyPairOptions<"pem", "pem">,
callback: (err: Error | null, publicKey: string, privateKey: string) => void,
): void;
function generateKeyPair(
type: "ed25519",
options: ED25519KeyPairOptions<"pem", "der">,
callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void,
): void;
function generateKeyPair(
type: "ed25519",
options: ED25519KeyPairOptions<"der", "pem">,
callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void,
|
): void;
function generateKeyPair(
type: "ed25519",
options: ED25519KeyPairOptions<"der", "der">,
callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void,
): void;
function generateKeyPair(
type: "ed25519",
options: ED25519KeyPairKeyObjectOptions | undefined,
callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void,
): void;
function generateKeyPair(
type: "ed448",
options: ED448KeyPairOptions<"pem", "pem">,
callback: (err: Error | null, publicKey: string, privateKey: string) => void,
): void;
function generateKeyPair(
type: "ed448",
options: ED448KeyPairOptions<"pem", "der">,
callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void,
): void;
function generateKeyPair(
type: "ed448",
options: ED448KeyPairOptions<"der", "pem">,
callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void,
): void;
function generateKeyPair(
type: "ed448",
options: ED448KeyPairOptions<"der", "der">,
callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void,
): void;
function generateKeyPair(
type: "ed448",
options: ED448KeyPairKeyObjectOptions | undefined,
callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void,
): void;
function generateKeyPair(
type: "x25519",
options: X25519KeyPairOptions<"pem", "pem">,
callback: (err: Error | null, publicKey: string, privateKey: string) => void,
): void;
function generateKeyPair(
type: "x25519",
options: X25519KeyPairOptions<"pem", "der">,
callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void,
): void;
function generateKeyPair(
type: "x25519",
options: X25519KeyPairOptions<"der", "pem">,
callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void,
): void;
function generateKeyPair(
type: "x25519",
options: X25519KeyPairOptions<"der", "der">,
callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void,
): void;
function generateKeyPair(
type: "x25519",
options: X25519KeyPairKeyObjectOptions | undefined,
callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void,
): void;
function generateKeyPair(
type: "x448",
options: X448KeyPairOptions<"pem", "pem">,
callback: (err: Error | null, publicKey: string, privateKey: string) => void,
): void;
function generateKeyPair(
type: "x448",
options: X448KeyPairOptions<"pem", "der">,
callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void,
): void;
function generateKeyPair(
type: "x448",
options: X448KeyPairOptions<"der", "pem">,
callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void,
): void;
function generateKeyPair(
type: "x448",
options: X448KeyPairOptions<"der", "der">,
callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void,
): void;
function generateKeyPair(
type: "x448",
options: X448KeyPairKeyObjectOptions | undefined,
callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void,
): void;
namespace generateKeyPair {
function __promisify__(
type: "rsa",
options: RSAKeyPairOptions<"pem", "pem">,
): Promise<{
publicKey: string;
privateKey: string;
}>;
function __promisify__(
type: "rsa",
options: RSAKeyPairOptions<"pem", "der">,
): Promise<{
publicKey: string;
privateKey: Buffer;
}>;
function |
__promisify__(
type: "rsa",
options: RSAKeyPairOptions<"der", "pem">,
): Promise<{
publicKey: Buffer;
privateKey: string;
}>;
function __promisify__(
type: "rsa",
options: RSAKeyPairOptions<"der", "der">,
): Promise<{
publicKey: Buffer;
privateKey: Buffer;
}>;
function __promisify__(type: "rsa", options: RSAKeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
function __promisify__(
type: "rsa-pss",
options: RSAPSSKeyPairOptions<"pem", "pem">,
): Promise<{
publicKey: string;
privateKey: string;
}>;
function __promisify__(
type: "rsa-pss",
options: RSAPSSKeyPairOptions<"pem", "der">,
): Promise<{
publicKey: string;
privateKey: Buffer;
}>;
function __promisify__(
type: "rsa-pss",
options: RSAPSSKeyPairOptions<"der", "pem">,
): Promise<{
publicKey: Buffer;
privateKey: string;
}>;
function __promisify__(
type: "rsa-pss",
options: RSAPSSKeyPairOptions<"der", "der">,
): Promise<{
publicKey: Buffer;
privateKey: Buffer;
}>;
function __promisify__(
type: "rsa-pss",
options: RSAPSSKeyPairKeyObjectOptions,
): Promise<KeyPairKeyObjectResult>;
function __promisify__(
type: "dsa",
options: DSAKeyPairOptions<"pem", "pem">,
): Promise<{
publicKey: string;
privateKey: string;
}>;
function __promisify__(
type: "dsa",
options: DSAKeyPairOptions<"pem", "der">,
): Promise<{
publicKey: string;
privateKey: Buffer;
}>;
function __promisify__(
type: "dsa",
options: DSAKeyPairOptions<"der", "pem">,
): Promise<{
publicKey: Buffer;
privateKey: string;
}>;
function __promisify__(
type: "dsa",
options: DSAKeyPairOptions<"der", "der">,
): Promise<{
publicKey: Buffer;
privateKey: Buffer;
}>;
function __promisify__(type: "dsa", options: DSAKeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
function __promisify__(
type: "ec",
options: ECKeyPairOptions<"pem", "pem">,
): Promise<{
publicKey: string;
privateKey: string;
}>;
function __promisify__(
type: "ec",
options: ECKeyPairOptions<"pem", "der">,
): Promise<{
publicKey: string;
privateKey: Buffer;
}>;
function __promisify__(
type: "ec",
options: ECKeyPairOptions<"der", "pem">,
): Promise<{
publicKey: Buffer;
privateKey: string;
}>;
function __promisify__(
type: "ec",
options: ECKeyPairOptions<"der", "der">,
): Promise<{
publicKey: Buffer;
privateKey: Buffer;
}>;
function __promisify__(type: "ec", options: ECKeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
function __promisify__(
type: "ed25519",
options: ED25519KeyPairOptions<"pem", "pem">,
): Promise<{
publicKey: string;
privateKey: string;
}>;
function __promisify__(
type: "ed25519",
options: ED25519KeyPairOptions<"pem", "der">,
): Promise<{
publicKey: string;
privateKey: Buffer;
}>;
function __promisify__(
type: "ed25519",
options: ED25519KeyPairOptions<"der", "pem">,
): Promise<{
publicKey: Buffe |
r;
privateKey: string;
}>;
function __promisify__(
type: "ed25519",
options: ED25519KeyPairOptions<"der", "der">,
): Promise<{
publicKey: Buffer;
privateKey: Buffer;
}>;
function __promisify__(
type: "ed25519",
options?: ED25519KeyPairKeyObjectOptions,
): Promise<KeyPairKeyObjectResult>;
function __promisify__(
type: "ed448",
options: ED448KeyPairOptions<"pem", "pem">,
): Promise<{
publicKey: string;
privateKey: string;
}>;
function __promisify__(
type: "ed448",
options: ED448KeyPairOptions<"pem", "der">,
): Promise<{
publicKey: string;
privateKey: Buffer;
}>;
function __promisify__(
type: "ed448",
options: ED448KeyPairOptions<"der", "pem">,
): Promise<{
publicKey: Buffer;
privateKey: string;
}>;
function __promisify__(
type: "ed448",
options: ED448KeyPairOptions<"der", "der">,
): Promise<{
publicKey: Buffer;
privateKey: Buffer;
}>;
function __promisify__(type: "ed448", options?: ED448KeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
function __promisify__(
type: "x25519",
options: X25519KeyPairOptions<"pem", "pem">,
): Promise<{
publicKey: string;
privateKey: string;
}>;
function __promisify__(
type: "x25519",
options: X25519KeyPairOptions<"pem", "der">,
): Promise<{
publicKey: string;
privateKey: Buffer;
}>;
function __promisify__(
type: "x25519",
options: X25519KeyPairOptions<"der", "pem">,
): Promise<{
publicKey: Buffer;
privateKey: string;
}>;
function __promisify__(
type: "x25519",
options: X25519KeyPairOptions<"der", "der">,
): Promise<{
publicKey: Buffer;
privateKey: Buffer;
}>;
function __promisify__(
type: "x25519",
options?: X25519KeyPairKeyObjectOptions,
): Promise<KeyPairKeyObjectResult>;
function __promisify__(
type: "x448",
options: X448KeyPairOptions<"pem", "pem">,
): Promise<{
publicKey: string;
privateKey: string;
}>;
function __promisify__(
type: "x448",
options: X448KeyPairOptions<"pem", "der">,
): Promise<{
publicKey: string;
privateKey: Buffer;
}>;
function __promisify__(
type: "x448",
options: X448KeyPairOptions<"der", "pem">,
): Promise<{
publicKey: Buffer;
privateKey: string;
}>;
function __promisify__(
type: "x448",
options: X448KeyPairOptions<"der", "der">,
): Promise<{
publicKey: Buffer;
privateKey: Buffer;
}>;
function __promisify__(type: "x448", options?: X448KeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
}
/**
* Calculates and returns the signature for `data` using the given private key and
* algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is
* dependent upon the key type (especially Ed25519 and Ed448).
*
* If `key` is not a `KeyObject`, this function behaves as if `key` had been
* passed to {@link createPrivateKey}. If it is an object, the following
* additional properties can be passed:
*
* If the `callback` function is provided this function uses libuv's threadpool.
* @since v12.0.0
*/
function sign(
algorithm: string | null | undefined,
|
data: NodeJS.ArrayBufferView,
key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput,
): Buffer;
function sign(
algorithm: string | null | undefined,
data: NodeJS.ArrayBufferView,
key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput,
callback: (error: Error | null, data: Buffer) => void,
): void;
/**
* Verifies the given signature for `data` using the given key and algorithm. If`algorithm` is `null` or `undefined`, then the algorithm is dependent upon the
* key type (especially Ed25519 and Ed448).
*
* If `key` is not a `KeyObject`, this function behaves as if `key` had been
* passed to {@link createPublicKey}. If it is an object, the following
* additional properties can be passed:
*
* The `signature` argument is the previously calculated signature for the `data`.
*
* Because public keys can be derived from private keys, a private key or a public
* key may be passed for `key`.
*
* If the `callback` function is provided this function uses libuv's threadpool.
* @since v12.0.0
*/
function verify(
algorithm: string | null | undefined,
data: NodeJS.ArrayBufferView,
key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput,
signature: NodeJS.ArrayBufferView,
): boolean;
function verify(
algorithm: string | null | undefined,
data: NodeJS.ArrayBufferView,
key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput,
signature: NodeJS.ArrayBufferView,
callback: (error: Error | null, result: boolean) => void,
): void;
/**
* Computes the Diffie-Hellman secret based on a `privateKey` and a `publicKey`.
* Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'`(for Diffie-Hellman), `'ec'` (for ECDH), `'x448'`, or `'x25519'` (for ECDH-ES).
* @since v13.9.0, v12.17.0
*/
function diffieHellman(options: { privateKey: KeyObject; publicKey: KeyObject }): Buffer;
type CipherMode = "cbc" | "ccm" | "cfb" | "ctr" | "ecb" | "gcm" | "ocb" | "ofb" | "stream" | "wrap" | "xts";
interface CipherInfoOptions {
/**
* A test key length.
*/
keyLength?: number | undefined;
/**
* A test IV length.
*/
ivLength?: number | undefined;
}
interface CipherInfo {
/**
* The name of the cipher.
*/
name: string;
/**
* The nid of the cipher.
*/
nid: number;
/**
* The block size of the cipher in bytes.
* This property is omitted when mode is 'stream'.
*/
blockSize?: number | undefined;
/**
* The expected or default initialization vector length in bytes.
* This property is omitted if the cipher does not use an initialization vector.
*/
ivLength?: number | undefined;
/**
* The expected or default key length in bytes.
*/
keyLength: number;
/**
* The cipher mode.
*/
mode: CipherMode;
}
/**
* Returns information about a given cipher.
*
* Some ciphers accept variable length keys and initialization vectors. By default,
* the `crypto.getCipherInfo()` method will return the default values for these
* ciphers. To test if a given key length or iv length is acceptable for given
* cipher, use the `keyLength` and `ivLength` options. If the given values are
* unacceptable, `undefined` will be returned.
* @since v15.0.0
* @param nameOrNid The name or nid of the cipher to query.
*/
function getCipherInfo(nameOrNid: string | number, options?: CipherInfoOptions): CipherInfo | undefined;
/**
* HKDF is a simple key derivation function defined in RFC 5869\. The given `ikm`,`salt` and `info` are used with the `dig |
est` to derive a key of `keylen` bytes.
*
* The supplied `callback` function is called with two arguments: `err` and`derivedKey`. If an errors occurs while deriving the key, `err` will be set;
* otherwise `err` will be `null`. The successfully generated `derivedKey` will
* be passed to the callback as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). An error will be thrown if any
* of the input arguments specify invalid values or types.
*
* ```js
* import { Buffer } from 'node:buffer';
* const {
* hkdf,
* } = await import('node:crypto');
*
* hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => {
* if (err) throw err;
* console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653'
* });
* ```
* @since v15.0.0
* @param digest The digest algorithm to use.
* @param ikm The input keying material. Must be provided but can be zero-length.
* @param salt The salt value. Must be provided but can be zero-length.
* @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes.
* @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512`
* generates 64-byte hashes, making the maximum HKDF output 16320 bytes).
*/
function hkdf(
digest: string,
irm: BinaryLike | KeyObject,
salt: BinaryLike,
info: BinaryLike,
keylen: number,
callback: (err: Error | null, derivedKey: ArrayBuffer) => void,
): void;
/**
* Provides a synchronous HKDF key derivation function as defined in RFC 5869\. The
* given `ikm`, `salt` and `info` are used with the `digest` to derive a key of`keylen` bytes.
*
* The successfully generated `derivedKey` will be returned as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer).
*
* An error will be thrown if any of the input arguments specify invalid values or
* types, or if the derived key cannot be generated.
*
* ```js
* import { Buffer } from 'node:buffer';
* const {
* hkdfSync,
* } = await import('node:crypto');
*
* const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64);
* console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653'
* ```
* @since v15.0.0
* @param digest The digest algorithm to use.
* @param ikm The input keying material. Must be provided but can be zero-length.
* @param salt The salt value. Must be provided but can be zero-length.
* @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes.
* @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512`
* generates 64-byte hashes, making the maximum HKDF output 16320 bytes).
*/
function hkdfSync(
digest: string,
ikm: BinaryLike | KeyObject,
salt: BinaryLike,
info: BinaryLike,
keylen: number,
): ArrayBuffer;
interface SecureHeapUsage {
/**
* The total allocated secure heap size as specified using the `--secure-heap=n` command-line flag.
*/
total: number;
/**
* The minimum allocation from the secure heap as specified using the `--secure-heap-min` command-line flag.
*/
min: number;
/**
* The total number of bytes currently allocated from the secure heap.
*/
used: number;
/**
* The calculated ratio of `used` to `total` allocated bytes.
*/
|
utilization: number;
}
/**
* @since v15.6.0
*/
function secureHeapUsed(): SecureHeapUsage;
interface RandomUUIDOptions {
/**
* By default, to improve performance,
* Node.js will pre-emptively generate and persistently cache enough
* random data to generate up to 128 random UUIDs. To generate a UUID
* without using the cache, set `disableEntropyCache` to `true`.
*
* @default `false`
*/
disableEntropyCache?: boolean | undefined;
}
type UUID = `${string}-${string}-${string}-${string}-${string}`;
/**
* Generates a random [RFC 4122](https://www.rfc-editor.org/rfc/rfc4122.txt) version 4 UUID. The UUID is generated using a
* cryptographic pseudorandom number generator.
* @since v15.6.0, v14.17.0
*/
function randomUUID(options?: RandomUUIDOptions): UUID;
interface X509CheckOptions {
/**
* @default 'always'
*/
subject?: "always" | "default" | "never";
/**
* @default true
*/
wildcards?: boolean;
/**
* @default true
*/
partialWildcards?: boolean;
/**
* @default false
*/
multiLabelWildcards?: boolean;
/**
* @default false
*/
singleLabelSubdomains?: boolean;
}
/**
* Encapsulates an X509 certificate and provides read-only access to
* its information.
*
* ```js
* const { X509Certificate } = await import('node:crypto');
*
* const x509 = new X509Certificate('{... pem encoded cert ...}');
*
* console.log(x509.subject);
* ```
* @since v15.6.0
*/
class X509Certificate {
/**
* Will be \`true\` if this is a Certificate Authority (CA) certificate.
* @since v15.6.0
*/
readonly ca: boolean;
/**
* The SHA-1 fingerprint of this certificate.
*
* Because SHA-1 is cryptographically broken and because the security of SHA-1 is
* significantly worse than that of algorithms that are commonly used to sign
* certificates, consider using `x509.fingerprint256` instead.
* @since v15.6.0
*/
readonly fingerprint: string;
/**
* The SHA-256 fingerprint of this certificate.
* @since v15.6.0
*/
readonly fingerprint256: string;
/**
* The SHA-512 fingerprint of this certificate.
*
* Because computing the SHA-256 fingerprint is usually faster and because it is
* only half the size of the SHA-512 fingerprint, `x509.fingerprint256` may be
* a better choice. While SHA-512 presumably provides a higher level of security in
* general, the security of SHA-256 matches that of most algorithms that are
* commonly used to sign certificates.
* @since v17.2.0, v16.14.0
*/
readonly fingerprint512: string;
/**
* The complete subject of this certificate.
* @since v15.6.0
*/
readonly subject: string;
/**
* The subject alternative name specified for this certificate.
*
* This is a comma-separated list of subject alternative names. Each entry begins
* with a string identifying the kind of the subject alternative name followed by
* a colon and the value associated with the entry.
*
* Earlier versions of Node.js incorrectly assumed that it is safe to split this
* property at the two-character sequence `', '` (see [CVE-2021-44532](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44532)). However,
* both malicious and legitimate certificates can contain subject alternative names
* that include this sequence when represented as a string.
*
* After the prefix denoting the type of the entry, the rem |
ainder of each entry
* might be enclosed in quotes to indicate that the value is a JSON string literal.
* For backward compatibility, Node.js only uses JSON string literals within this
* property when necessary to avoid ambiguity. Third-party code should be prepared
* to handle both possible entry formats.
* @since v15.6.0
*/
readonly subjectAltName: string | undefined;
/**
* A textual representation of the certificate's authority information access
* extension.
*
* This is a line feed separated list of access descriptions. Each line begins with
* the access method and the kind of the access location, followed by a colon and
* the value associated with the access location.
*
* After the prefix denoting the access method and the kind of the access location,
* the remainder of each line might be enclosed in quotes to indicate that the
* value is a JSON string literal. For backward compatibility, Node.js only uses
* JSON string literals within this property when necessary to avoid ambiguity.
* Third-party code should be prepared to handle both possible entry formats.
* @since v15.6.0
*/
readonly infoAccess: string | undefined;
/**
* An array detailing the key usages for this certificate.
* @since v15.6.0
*/
readonly keyUsage: string[];
/**
* The issuer identification included in this certificate.
* @since v15.6.0
*/
readonly issuer: string;
/**
* The issuer certificate or `undefined` if the issuer certificate is not
* available.
* @since v15.9.0
*/
readonly issuerCertificate?: X509Certificate | undefined;
/**
* The public key `KeyObject` for this certificate.
* @since v15.6.0
*/
readonly publicKey: KeyObject;
/**
* A `Buffer` containing the DER encoding of this certificate.
* @since v15.6.0
*/
readonly raw: Buffer;
/**
* The serial number of this certificate.
*
* Serial numbers are assigned by certificate authorities and do not uniquely
* identify certificates. Consider using `x509.fingerprint256` as a unique
* identifier instead.
* @since v15.6.0
*/
readonly serialNumber: string;
/**
* The date/time from which this certificate is considered valid.
* @since v15.6.0
*/
readonly validFrom: string;
/**
* The date/time until which this certificate is considered valid.
* @since v15.6.0
*/
readonly validTo: string;
constructor(buffer: BinaryLike);
/**
* Checks whether the certificate matches the given email address.
*
* If the `'subject'` option is undefined or set to `'default'`, the certificate
* subject is only considered if the subject alternative name extension either does
* not exist or does not contain any email addresses.
*
* If the `'subject'` option is set to `'always'` and if the subject alternative
* name extension either does not exist or does not contain a matching email
* address, the certificate subject is considered.
*
* If the `'subject'` option is set to `'never'`, the certificate subject is never
* considered, even if the certificate contains no subject alternative names.
* @since v15.6.0
* @return Returns `email` if the certificate matches, `undefined` if it does not.
*/
checkEmail(email: string, options?: Pick<X509CheckOptions, "subject">): string | undefined;
/**
* Checks whether the certificate matches the given host name.
*
* If the certif |
icate matches the given host name, the matching subject name is
* returned. The returned name might be an exact match (e.g., `foo.example.com`)
* or it might contain wildcards (e.g., `*.example.com`). Because host name
* comparisons are case-insensitive, the returned subject name might also differ
* from the given `name` in capitalization.
*
* If the `'subject'` option is undefined or set to `'default'`, the certificate
* subject is only considered if the subject alternative name extension either does
* not exist or does not contain any DNS names. This behavior is consistent with [RFC 2818](https://www.rfc-editor.org/rfc/rfc2818.txt) ("HTTP Over TLS").
*
* If the `'subject'` option is set to `'always'` and if the subject alternative
* name extension either does not exist or does not contain a matching DNS name,
* the certificate subject is considered.
*
* If the `'subject'` option is set to `'never'`, the certificate subject is never
* considered, even if the certificate contains no subject alternative names.
* @since v15.6.0
* @return Returns a subject name that matches `name`, or `undefined` if no subject name matches `name`.
*/
checkHost(name: string, options?: X509CheckOptions): string | undefined;
/**
* Checks whether the certificate matches the given IP address (IPv4 or IPv6).
*
* Only [RFC 5280](https://www.rfc-editor.org/rfc/rfc5280.txt) `iPAddress` subject alternative names are considered, and they
* must match the given `ip` address exactly. Other subject alternative names as
* well as the subject field of the certificate are ignored.
* @since v15.6.0
* @return Returns `ip` if the certificate matches, `undefined` if it does not.
*/
checkIP(ip: string): string | undefined;
/**
* Checks whether this certificate was issued by the given `otherCert`.
* @since v15.6.0
*/
checkIssued(otherCert: X509Certificate): boolean;
/**
* Checks whether the public key for this certificate is consistent with
* the given private key.
* @since v15.6.0
* @param privateKey A private key.
*/
checkPrivateKey(privateKey: KeyObject): boolean;
/**
* There is no standard JSON encoding for X509 certificates. The`toJSON()` method returns a string containing the PEM encoded
* certificate.
* @since v15.6.0
*/
toJSON(): string;
/**
* Returns information about this certificate using the legacy `certificate object` encoding.
* @since v15.6.0
*/
toLegacyObject(): PeerCertificate;
/**
* Returns the PEM-encoded certificate.
* @since v15.6.0
*/
toString(): string;
/**
* Verifies that this certificate was signed by the given public key.
* Does not perform any other validation checks on the certificate.
* @since v15.6.0
* @param publicKey A public key.
*/
verify(publicKey: KeyObject): boolean;
}
type LargeNumberLike = NodeJS.ArrayBufferView | SharedArrayBuffer | ArrayBuffer | bigint;
interface GeneratePrimeOptions {
add?: LargeNumberLike | undefined;
rem?: LargeNumberLike | undefined;
/**
* @default false
*/
safe?: boolean | undefined;
bigint?: boolean | undefined;
}
interface GeneratePrimeOptionsBigInt extends GeneratePrimeOptions {
bigint: true;
}
interface GeneratePrimeOptionsArrayBuffer extends GeneratePrimeOptions {
bigint?: false | undefined;
}
/**
* Generates a pseudorandom prime of `size` bits.
*
* If `options.safe` is `true`, the prime will be a safe prime -- that is,`(prime - |
1) / 2` will also be a prime.
*
* The `options.add` and `options.rem` parameters can be used to enforce additional
* requirements, e.g., for Diffie-Hellman:
*
* * If `options.add` and `options.rem` are both set, the prime will satisfy the
* condition that `prime % add = rem`.
* * If only `options.add` is set and `options.safe` is not `true`, the prime will
* satisfy the condition that `prime % add = 1`.
* * If only `options.add` is set and `options.safe` is set to `true`, the prime
* will instead satisfy the condition that `prime % add = 3`. This is necessary
* because `prime % add = 1` for `options.add > 2` would contradict the condition
* enforced by `options.safe`.
* * `options.rem` is ignored if `options.add` is not given.
*
* Both `options.add` and `options.rem` must be encoded as big-endian sequences
* if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or`DataView`.
*
* By default, the prime is encoded as a big-endian sequence of octets
* in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a
* [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided.
* @since v15.8.0
* @param size The size (in bits) of the prime to generate.
*/
function generatePrime(size: number, callback: (err: Error | null, prime: ArrayBuffer) => void): void;
function generatePrime(
size: number,
options: GeneratePrimeOptionsBigInt,
callback: (err: Error | null, prime: bigint) => void,
): void;
function generatePrime(
size: number,
options: GeneratePrimeOptionsArrayBuffer,
callback: (err: Error | null, prime: ArrayBuffer) => void,
): void;
function generatePrime(
size: number,
options: GeneratePrimeOptions,
callback: (err: Error | null, prime: ArrayBuffer | bigint) => void,
): void;
/**
* Generates a pseudorandom prime of `size` bits.
*
* If `options.safe` is `true`, the prime will be a safe prime -- that is,`(prime - 1) / 2` will also be a prime.
*
* The `options.add` and `options.rem` parameters can be used to enforce additional
* requirements, e.g., for Diffie-Hellman:
*
* * If `options.add` and `options.rem` are both set, the prime will satisfy the
* condition that `prime % add = rem`.
* * If only `options.add` is set and `options.safe` is not `true`, the prime will
* satisfy the condition that `prime % add = 1`.
* * If only `options.add` is set and `options.safe` is set to `true`, the prime
* will instead satisfy the condition that `prime % add = 3`. This is necessary
* because `prime % add = 1` for `options.add > 2` would contradict the condition
* enforced by `options.safe`.
* * `options.rem` is ignored if `options.add` is not given.
*
* Both `options.add` and `options.rem` must be encoded as big-endian sequences
* if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or`DataView`.
*
* By default, the prime is encoded as a big-endian sequence of octets
* in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a
* [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided.
* @since v15.8.0
* @param size The size (in bits) of the prime to generate.
*/
function generatePrimeSync(size: number): ArrayBuffer;
function generatePrimeSync(size: number, options: GeneratePrimeOptionsBigInt): bigint;
function generatePrimeSync(size: number, options: GeneratePrimeOptionsArrayBuffer): ArrayBuffer;
function generatePrimeSync(size: number, options: GeneratePri |
meOptions): ArrayBuffer | bigint;
interface CheckPrimeOptions {
/**
* The number of Miller-Rabin probabilistic primality iterations to perform.
* When the value is 0 (zero), a number of checks is used that yields a false positive rate of at most `2**-64` for random input.
* Care must be used when selecting a number of checks.
* Refer to the OpenSSL documentation for the BN_is_prime_ex function nchecks options for more details.
*
* @default 0
*/
checks?: number | undefined;
}
/**
* Checks the primality of the `candidate`.
* @since v15.8.0
* @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length.
*/
function checkPrime(value: LargeNumberLike, callback: (err: Error | null, result: boolean) => void): void;
function checkPrime(
value: LargeNumberLike,
options: CheckPrimeOptions,
callback: (err: Error | null, result: boolean) => void,
): void;
/**
* Checks the primality of the `candidate`.
* @since v15.8.0
* @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length.
* @return `true` if the candidate is a prime with an error probability less than `0.25 ** options.checks`.
*/
function checkPrimeSync(candidate: LargeNumberLike, options?: CheckPrimeOptions): boolean;
/**
* Load and set the `engine` for some or all OpenSSL functions (selected by flags).
*
* `engine` could be either an id or a path to the engine's shared library.
*
* The optional `flags` argument uses `ENGINE_METHOD_ALL` by default. The `flags`is a bit field taking one of or a mix of the following flags (defined in`crypto.constants`):
*
* * `crypto.constants.ENGINE_METHOD_RSA`
* * `crypto.constants.ENGINE_METHOD_DSA`
* * `crypto.constants.ENGINE_METHOD_DH`
* * `crypto.constants.ENGINE_METHOD_RAND`
* * `crypto.constants.ENGINE_METHOD_EC`
* * `crypto.constants.ENGINE_METHOD_CIPHERS`
* * `crypto.constants.ENGINE_METHOD_DIGESTS`
* * `crypto.constants.ENGINE_METHOD_PKEY_METHS`
* * `crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS`
* * `crypto.constants.ENGINE_METHOD_ALL`
* * `crypto.constants.ENGINE_METHOD_NONE`
* @since v0.11.11
* @param flags
*/
function setEngine(engine: string, flags?: number): void;
/**
* A convenient alias for {@link webcrypto.getRandomValues}. This
* implementation is not compliant with the Web Crypto spec, to write
* web-compatible code use {@link webcrypto.getRandomValues} instead.
* @since v17.4.0
* @return Returns `typedArray`.
*/
function getRandomValues<T extends webcrypto.BufferSource>(typedArray: T): T;
/**
* A convenient alias for `crypto.webcrypto.subtle`.
* @since v17.4.0
*/
const subtle: webcrypto.SubtleCrypto;
/**
* An implementation of the Web Crypto API standard.
*
* See the {@link https://nodejs.org/docs/latest/api/webcrypto.html Web Crypto API documentation} for details.
* @since v15.0.0
*/
const webcrypto: webcrypto.Crypto;
namespace webcrypto {
type BufferSource = ArrayBufferView | ArrayBuffer;
type KeyFormat = "jwk" | "pkcs8" | "raw" | "spki";
type KeyType = "private" | "public" | "secret";
type KeyUsage =
| "decrypt"
| "deriveBits"
| "deriveKey"
| "encrypt"
| "sign"
| "unwrapKey"
| "verify"
| "wrapKey";
type AlgorithmIdentifier = Algorithm | string;
type HashAlgorithmIdentifier = AlgorithmIdentifier;
type NamedCurve = string;
type BigInteger = Uint8Array;
interface AesCbcParams extends Algorithm {
iv: BufferSource;
}
interface AesCtrParams extends Algorithm {
counter: Buff |
erSource;
length: number;
}
interface AesDerivedKeyParams extends Algorithm {
length: number;
}
interface AesGcmParams extends Algorithm {
additionalData?: BufferSource;
iv: BufferSource;
tagLength?: number;
}
interface AesKeyAlgorithm extends KeyAlgorithm {
length: number;
}
interface AesKeyGenParams extends Algorithm {
length: number;
}
interface Algorithm {
name: string;
}
interface EcKeyAlgorithm extends KeyAlgorithm {
namedCurve: NamedCurve;
}
interface EcKeyGenParams extends Algorithm {
namedCurve: NamedCurve;
}
interface EcKeyImportParams extends Algorithm {
namedCurve: NamedCurve;
}
interface EcdhKeyDeriveParams extends Algorithm {
public: CryptoKey;
}
interface EcdsaParams extends Algorithm {
hash: HashAlgorithmIdentifier;
}
interface Ed448Params extends Algorithm {
context?: BufferSource;
}
interface HkdfParams extends Algorithm {
hash: HashAlgorithmIdentifier;
info: BufferSource;
salt: BufferSource;
}
interface HmacImportParams extends Algorithm {
hash: HashAlgorithmIdentifier;
length?: number;
}
interface HmacKeyAlgorithm extends KeyAlgorithm {
hash: KeyAlgorithm;
length: number;
}
interface HmacKeyGenParams extends Algorithm {
hash: HashAlgorithmIdentifier;
length?: number;
}
interface JsonWebKey {
alg?: string;
crv?: string;
d?: string;
dp?: string;
dq?: string;
e?: string;
ext?: boolean;
k?: string;
key_ops?: string[];
kty?: string;
n?: string;
oth?: RsaOtherPrimesInfo[];
p?: string;
q?: string;
qi?: string;
use?: string;
x?: string;
y?: string;
}
interface KeyAlgorithm {
name: string;
}
interface Pbkdf2Params extends Algorithm {
hash: HashAlgorithmIdentifier;
iterations: number;
salt: BufferSource;
}
interface RsaHashedImportParams extends Algorithm {
hash: HashAlgorithmIdentifier;
}
interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm {
hash: KeyAlgorithm;
}
interface RsaHashedKeyGenParams extends RsaKeyGenParams {
hash: HashAlgorithmIdentifier;
}
interface RsaKeyAlgorithm extends KeyAlgorithm {
modulusLength: number;
publicExponent: BigInteger;
}
interface RsaKeyGenParams extends Algorithm {
modulusLength: number;
publicExponent: BigInteger;
}
interface RsaOaepParams extends Algorithm {
label?: BufferSource;
}
interface RsaOtherPrimesInfo {
d?: string;
r?: string;
t?: string;
}
interface RsaPssParams extends Algorithm {
saltLength: number;
}
/**
* Calling `require('node:crypto').webcrypto` returns an instance of the `Crypto` class.
* `Crypto` is a singleton that provides access to the remainder of the crypto API.
* @since v15.0.0
*/
interface Crypto {
/**
* Provides access to the `SubtleCrypto` API.
* @since v15.0.0
*/
readonly subtle: SubtleCrypto;
/**
* Generates cryptographically strong random values.
* The given `typedArray` is filled with random values, and a refer |
ence to `typedArray` is returned.
*
* The given `typedArray` must be an integer-based instance of {@link NodeJS.TypedArray}, i.e. `Float32Array` and `Float64Array` are not accepted.
*
* An error will be thrown if the given `typedArray` is larger than 65,536 bytes.
* @since v15.0.0
*/
getRandomValues<T extends Exclude<NodeJS.TypedArray, Float32Array | Float64Array>>(typedArray: T): T;
/**
* Generates a random {@link https://www.rfc-editor.org/rfc/rfc4122.txt RFC 4122} version 4 UUID.
* The UUID is generated using a cryptographic pseudorandom number generator.
* @since v16.7.0
*/
randomUUID(): UUID;
CryptoKey: CryptoKeyConstructor;
}
// This constructor throws ILLEGAL_CONSTRUCTOR so it should not be newable.
interface CryptoKeyConstructor {
/** Illegal constructor */
(_: { readonly _: unique symbol }): never; // Allows instanceof to work but not be callable by the user.
readonly length: 0;
readonly name: "CryptoKey";
readonly prototype: CryptoKey;
}
/**
* @since v15.0.0
*/
interface CryptoKey {
/**
* An object detailing the algorithm for which the key can be used along with additional algorithm-specific parameters.
* @since v15.0.0
*/
readonly algorithm: KeyAlgorithm;
/**
* When `true`, the {@link CryptoKey} can be extracted using either `subtleCrypto.exportKey()` or `subtleCrypto.wrapKey()`.
* @since v15.0.0
*/
readonly extractable: boolean;
/**
* A string identifying whether the key is a symmetric (`'secret'`) or asymmetric (`'private'` or `'public'`) key.
* @since v15.0.0
*/
readonly type: KeyType;
/**
* An array of strings identifying the operations for which the key may be used.
*
* The possible usages are:
* - `'encrypt'` - The key may be used to encrypt data.
* - `'decrypt'` - The key may be used to decrypt data.
* - `'sign'` - The key may be used to generate digital signatures.
* - `'verify'` - The key may be used to verify digital signatures.
* - `'deriveKey'` - The key may be used to derive a new key.
* - `'deriveBits'` - The key may be used to derive bits.
* - `'wrapKey'` - The key may be used to wrap another key.
* - `'unwrapKey'` - The key may be used to unwrap another key.
*
* Valid key usages depend on the key algorithm (identified by `cryptokey.algorithm.name`).
* @since v15.0.0
*/
readonly usages: KeyUsage[];
}
/**
* The `CryptoKeyPair` is a simple dictionary object with `publicKey` and `privateKey` properties, representing an asymmetric key pair.
* @since v15.0.0
*/
interface CryptoKeyPair {
/**
* A {@link CryptoKey} whose type will be `'private'`.
* @since v15.0.0
*/
privateKey: CryptoKey;
/**
* A {@link CryptoKey} whose type will be `'public'`.
* @since v15.0.0
*/
publicKey: CryptoKey;
}
/**
* @since v15.0.0
*/
interface SubtleCrypto {
/**
* Using the method and parameters specified in `algorithm` and the keying material provided by `key`,
* `subtle.decrypt()` attempts to decipher the provided `data`. If successful,
* the returned promise will be resolved with an `<ArrayBuffer>` containing the plaintext result.
*
* The a |
lgorithms currently supported include:
*
* - `'RSA-OAEP'`
* - `'AES-CTR'`
* - `'AES-CBC'`
* - `'AES-GCM'`
* @since v15.0.0
*/
decrypt(
algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams,
key: CryptoKey,
data: BufferSource,
): Promise<ArrayBuffer>;
/**
* Using the method and parameters specified in `algorithm` and the keying material provided by `baseKey`,
* `subtle.deriveBits()` attempts to generate `length` bits.
* The Node.js implementation requires that when `length` is a number it must be multiple of `8`.
* When `length` is `null` the maximum number of bits for a given algorithm is generated. This is allowed
* for the `'ECDH'`, `'X25519'`, and `'X448'` algorithms.
* If successful, the returned promise will be resolved with an `<ArrayBuffer>` containing the generated data.
*
* The algorithms currently supported include:
*
* - `'ECDH'`
* - `'X25519'`
* - `'X448'`
* - `'HKDF'`
* - `'PBKDF2'`
* @since v15.0.0
*/
deriveBits(algorithm: EcdhKeyDeriveParams, baseKey: CryptoKey, length: number | null): Promise<ArrayBuffer>;
deriveBits(
algorithm: AlgorithmIdentifier | HkdfParams | Pbkdf2Params,
baseKey: CryptoKey,
length: number,
): Promise<ArrayBuffer>;
/**
* Using the method and parameters specified in `algorithm`, and the keying material provided by `baseKey`,
* `subtle.deriveKey()` attempts to generate a new <CryptoKey>` based on the method and parameters in `derivedKeyAlgorithm`.
*
* Calling `subtle.deriveKey()` is equivalent to calling `subtle.deriveBits()` to generate raw keying material,
* then passing the result into the `subtle.importKey()` method using the `deriveKeyAlgorithm`, `extractable`, and `keyUsages` parameters as input.
*
* The algorithms currently supported include:
*
* - `'ECDH'`
* - `'X25519'`
* - `'X448'`
* - `'HKDF'`
* - `'PBKDF2'`
* @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}.
* @since v15.0.0
*/
deriveKey(
algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params,
baseKey: CryptoKey,
derivedKeyAlgorithm:
| AlgorithmIdentifier
| AesDerivedKeyParams
| HmacImportParams
| HkdfParams
| Pbkdf2Params,
extractable: boolean,
keyUsages: readonly KeyUsage[],
): Promise<CryptoKey>;
/**
* Using the method identified by `algorithm`, `subtle.digest()` attempts to generate a digest of `data`.
* If successful, the returned promise is resolved with an `<ArrayBuffer>` containing the computed digest.
*
* If `algorithm` is provided as a `<string>`, it must be one of:
*
* - `'SHA-1'`
* - `'SHA-256'`
* - `'SHA-384'`
* - `'SHA-512'`
*
* If `algorithm` is provided as an `<Object>`, it must have a `name` property whose value is one of the above.
* @since v15.0.0
*/
digest(algorithm: AlgorithmIdentifier, data: BufferSource): Promise<ArrayBuffer>;
/**
* Using the method and parameters specified by `algorithm` and the keyi |
ng material provided by `key`,
* `subtle.encrypt()` attempts to encipher `data`. If successful,
* the returned promise is resolved with an `<ArrayBuffer>` containing the encrypted result.
*
* The algorithms currently supported include:
*
* - `'RSA-OAEP'`
* - `'AES-CTR'`
* - `'AES-CBC'`
* - `'AES-GCM'`
* @since v15.0.0
*/
encrypt(
algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams,
key: CryptoKey,
data: BufferSource,
): Promise<ArrayBuffer>;
/**
* Exports the given key into the specified format, if supported.
*
* If the `<CryptoKey>` is not extractable, the returned promise will reject.
*
* When `format` is either `'pkcs8'` or `'spki'` and the export is successful,
* the returned promise will be resolved with an `<ArrayBuffer>` containing the exported key data.
*
* When `format` is `'jwk'` and the export is successful, the returned promise will be resolved with a
* JavaScript object conforming to the {@link https://tools.ietf.org/html/rfc7517 JSON Web Key} specification.
* @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`.
* @returns `<Promise>` containing `<ArrayBuffer>`.
* @since v15.0.0
*/
exportKey(format: "jwk", key: CryptoKey): Promise<JsonWebKey>;
exportKey(format: Exclude<KeyFormat, "jwk">, key: CryptoKey): Promise<ArrayBuffer>;
/**
* Using the method and parameters provided in `algorithm`,
* `subtle.generateKey()` attempts to generate new keying material.
* Depending the method used, the method may generate either a single `<CryptoKey>` or a `<CryptoKeyPair>`.
*
* The `<CryptoKeyPair>` (public and private key) generating algorithms supported include:
*
* - `'RSASSA-PKCS1-v1_5'`
* - `'RSA-PSS'`
* - `'RSA-OAEP'`
* - `'ECDSA'`
* - `'Ed25519'`
* - `'Ed448'`
* - `'ECDH'`
* - `'X25519'`
* - `'X448'`
* The `<CryptoKey>` (secret key) generating algorithms supported include:
*
* - `'HMAC'`
* - `'AES-CTR'`
* - `'AES-CBC'`
* - `'AES-GCM'`
* - `'AES-KW'`
* @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}.
* @since v15.0.0
*/
generateKey(
algorithm: RsaHashedKeyGenParams | EcKeyGenParams,
extractable: boolean,
keyUsages: readonly KeyUsage[],
): Promise<CryptoKeyPair>;
generateKey(
algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params,
extractable: boolean,
keyUsages: readonly KeyUsage[],
): Promise<CryptoKey>;
generateKey(
algorithm: AlgorithmIdentifier,
extractable: boolean,
keyUsages: KeyUsage[],
): Promise<CryptoKeyPair | CryptoKey>;
/**
* The `subtle.importKey()` method attempts to interpret the provided `keyData` as the given `format`
* to create a `<CryptoKey>` instance using the provided `algorithm`, `extractable`, and `keyUsages` arguments.
* If the import is successful, the returned promise will be resolved with the created `<CryptoKey>`.
*
* If importing a `'PBKDF2'` key, `extractable` must be `false`.
* @param format Must be one of `'raw'`, `'pkcs8'`, `'sp |
ki'`, or `'jwk'`.
* @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}.
* @since v15.0.0
*/
importKey(
format: "jwk",
keyData: JsonWebKey,
algorithm:
| AlgorithmIdentifier
| RsaHashedImportParams
| EcKeyImportParams
| HmacImportParams
| AesKeyAlgorithm,
extractable: boolean,
keyUsages: readonly KeyUsage[],
): Promise<CryptoKey>;
importKey(
format: Exclude<KeyFormat, "jwk">,
keyData: BufferSource,
algorithm:
| AlgorithmIdentifier
| RsaHashedImportParams
| EcKeyImportParams
| HmacImportParams
| AesKeyAlgorithm,
extractable: boolean,
keyUsages: KeyUsage[],
): Promise<CryptoKey>;
/**
* Using the method and parameters given by `algorithm` and the keying material provided by `key`,
* `subtle.sign()` attempts to generate a cryptographic signature of `data`. If successful,
* the returned promise is resolved with an `<ArrayBuffer>` containing the generated signature.
*
* The algorithms currently supported include:
*
* - `'RSASSA-PKCS1-v1_5'`
* - `'RSA-PSS'`
* - `'ECDSA'`
* - `'Ed25519'`
* - `'Ed448'`
* - `'HMAC'`
* @since v15.0.0
*/
sign(
algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | Ed448Params,
key: CryptoKey,
data: BufferSource,
): Promise<ArrayBuffer>;
/**
* In cryptography, "wrapping a key" refers to exporting and then encrypting the keying material.
* The `subtle.unwrapKey()` method attempts to decrypt a wrapped key and create a `<CryptoKey>` instance.
* It is equivalent to calling `subtle.decrypt()` first on the encrypted key data (using the `wrappedKey`, `unwrapAlgo`, and `unwrappingKey` arguments as input)
* then passing the results in to the `subtle.importKey()` method using the `unwrappedKeyAlgo`, `extractable`, and `keyUsages` arguments as inputs.
* If successful, the returned promise is resolved with a `<CryptoKey>` object.
*
* The wrapping algorithms currently supported include:
*
* - `'RSA-OAEP'`
* - `'AES-CTR'`
* - `'AES-CBC'`
* - `'AES-GCM'`
* - `'AES-KW'`
*
* The unwrapped key algorithms supported include:
*
* - `'RSASSA-PKCS1-v1_5'`
* - `'RSA-PSS'`
* - `'RSA-OAEP'`
* - `'ECDSA'`
* - `'Ed25519'`
* - `'Ed448'`
* - `'ECDH'`
* - `'X25519'`
* - `'X448'`
* - `'HMAC'`
* - `'AES-CTR'`
* - `'AES-CBC'`
* - `'AES-GCM'`
* - `'AES-KW'`
* @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`.
* @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}.
* @since v15.0.0
*/
unwrapKey(
format: KeyFormat,
wrappedKey: BufferSource,
unwrappingKey: CryptoKey,
unwrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams,
unwrappedKeyAlgorithm:
| AlgorithmIdentifier
| RsaHashedImportParams
|
| EcKeyImportParams
| HmacImportParams
| AesKeyAlgorithm,
extractable: boolean,
keyUsages: KeyUsage[],
): Promise<CryptoKey>;
/**
* Using the method and parameters given in `algorithm` and the keying material provided by `key`,
* `subtle.verify()` attempts to verify that `signature` is a valid cryptographic signature of `data`.
* The returned promise is resolved with either `true` or `false`.
*
* The algorithms currently supported include:
*
* - `'RSASSA-PKCS1-v1_5'`
* - `'RSA-PSS'`
* - `'ECDSA'`
* - `'Ed25519'`
* - `'Ed448'`
* - `'HMAC'`
* @since v15.0.0
*/
verify(
algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | Ed448Params,
key: CryptoKey,
signature: BufferSource,
data: BufferSource,
): Promise<boolean>;
/**
* In cryptography, "wrapping a key" refers to exporting and then encrypting the keying material.
* The `subtle.wrapKey()` method exports the keying material into the format identified by `format`,
* then encrypts it using the method and parameters specified by `wrapAlgo` and the keying material provided by `wrappingKey`.
* It is the equivalent to calling `subtle.exportKey()` using `format` and `key` as the arguments,
* then passing the result to the `subtle.encrypt()` method using `wrappingKey` and `wrapAlgo` as inputs.
* If successful, the returned promise will be resolved with an `<ArrayBuffer>` containing the encrypted key data.
*
* The wrapping algorithms currently supported include:
*
* - `'RSA-OAEP'`
* - `'AES-CTR'`
* - `'AES-CBC'`
* - `'AES-GCM'`
* - `'AES-KW'`
* @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`.
* @since v15.0.0
*/
wrapKey(
format: KeyFormat,
key: CryptoKey,
wrappingKey: CryptoKey,
wrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams,
): Promise<ArrayBuffer>;
}
}
global {
var crypto: typeof globalThis extends {
crypto: infer T;
onmessage: any;
} ? T
: webcrypto.Crypto;
}
}
declare module "node:crypto" {
export * from "crypto";
}
|
/**
* The `node:os` module provides operating system-related utility methods and
* properties. It can be accessed using:
*
* ```js
* const os = require('node:os');
* ```
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/os.js)
*/
declare module "os" {
interface CpuInfo {
model: string;
speed: number;
times: {
user: number;
nice: number;
sys: number;
idle: number;
irq: number;
};
}
interface NetworkInterfaceBase {
address: string;
netmask: string;
mac: string;
internal: boolean;
cidr: string | null;
}
interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase {
family: "IPv4";
scopeid?: undefined;
}
interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase {
family: "IPv6";
scopeid: number;
}
interface UserInfo<T> {
username: T;
uid: number;
gid: number;
shell: T | null;
homedir: T;
}
type NetworkInterfaceInfo = NetworkInterfaceInfoIPv4 | NetworkInterfaceInfoIPv6;
/**
* Returns the host name of the operating system as a string.
* @since v0.3.3
*/
function hostname(): string;
/**
* Returns an array containing the 1, 5, and 15 minute load averages.
*
* The load average is a measure of system activity calculated by the operating
* system and expressed as a fractional number.
*
* The load average is a Unix-specific concept. On Windows, the return value is
* always `[0, 0, 0]`.
* @since v0.3.3
*/
function loadavg(): number[];
/**
* Returns the system uptime in number of seconds.
* @since v0.3.3
*/
function uptime(): number;
/**
* Returns the amount of free system memory in bytes as an integer.
* @since v0.3.3
*/
function freemem(): number;
/**
* Returns the total amount of system memory in bytes as an integer.
* @since v0.3.3
*/
function totalmem(): number;
/**
* Returns an array of objects containing information about each logical CPU core.
* The array will be empty if no CPU information is available, such as if the`/proc` file system is unavailable.
*
* The properties included on each object include:
*
* ```js
* [
* {
* model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
* speed: 2926,
* times: {
* user: 252020,
* nice: 0,
* sys: 30340,
* idle: 1070356870,
* irq: 0,
* },
* },
* {
* model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
* speed: 2926,
* times: {
* user: 306960,
* nice: 0,
* sys: 26980,
* idle: 1071569080,
* irq: 0,
* },
* },
* {
* model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
* speed: 2926,
* times: {
* user: 248450,
* nice: 0,
* sys: 21750,
* idle: 1070919370,
* irq: 0,
* },
* },
* {
* model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
* speed: 2926,
* times: {
* user: 256880,
* nice: 0,
* sys: 19430,
* idle: 1070905480,
* irq: 20,
* },
* },
* ]
* ```
*
* `nice` values are POSIX-only. On Windows, the `nice` values of all processors
* are always 0.
*
* `os.cpus().length` should not be used to calculate the amount of parallelism
* available to an application. Use {@link availableParallelism} for this purpose.
* @since v0.3.3
*/
function cpus(): CpuInfo[];
/**
* Returns an estimate of the default amount of parallelism a program should use.
* Always return |
s a value greater than zero.
*
* This function is a small wrapper about libuv's [`uv_available_parallelism()`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_available_parallelism).
* @since v19.4.0, v18.14.0
*/
function availableParallelism(): number;
/**
* Returns the operating system name as returned by [`uname(3)`](https://linux.die.net/man/3/uname). For example, it
* returns `'Linux'` on Linux, `'Darwin'` on macOS, and `'Windows_NT'` on Windows.
*
* See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for additional information
* about the output of running [`uname(3)`](https://linux.die.net/man/3/uname) on various operating systems.
* @since v0.3.3
*/
function type(): string;
/**
* Returns the operating system as a string.
*
* On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `GetVersionExW()` is used. See
* [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information.
* @since v0.3.3
*/
function release(): string;
/**
* Returns an object containing network interfaces that have been assigned a
* network address.
*
* Each key on the returned object identifies a network interface. The associated
* value is an array of objects that each describe an assigned network address.
*
* The properties available on the assigned network address object include:
*
* ```js
* {
* lo: [
* {
* address: '127.0.0.1',
* netmask: '255.0.0.0',
* family: 'IPv4',
* mac: '00:00:00:00:00:00',
* internal: true,
* cidr: '127.0.0.1/8'
* },
* {
* address: '::1',
* netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff',
* family: 'IPv6',
* mac: '00:00:00:00:00:00',
* scopeid: 0,
* internal: true,
* cidr: '::1/128'
* }
* ],
* eth0: [
* {
* address: '192.168.1.108',
* netmask: '255.255.255.0',
* family: 'IPv4',
* mac: '01:02:03:0a:0b:0c',
* internal: false,
* cidr: '192.168.1.108/24'
* },
* {
* address: 'fe80::a00:27ff:fe4e:66a1',
* netmask: 'ffff:ffff:ffff:ffff::',
* family: 'IPv6',
* mac: '01:02:03:0a:0b:0c',
* scopeid: 1,
* internal: false,
* cidr: 'fe80::a00:27ff:fe4e:66a1/64'
* }
* ]
* }
* ```
* @since v0.6.0
*/
function networkInterfaces(): NodeJS.Dict<NetworkInterfaceInfo[]>;
/**
* Returns the string path of the current user's home directory.
*
* On POSIX, it uses the `$HOME` environment variable if defined. Otherwise it
* uses the [effective UID](https://en.wikipedia.org/wiki/User_identifier#Effective_user_ID) to look up the user's home directory.
*
* On Windows, it uses the `USERPROFILE` environment variable if defined.
* Otherwise it uses the path to the profile directory of the current user.
* @since v2.3.0
*/
function homedir(): string;
/**
* Returns information about the currently effective user. On POSIX platforms,
* this is typically a subset of the password file. The returned object includes
* the `username`, `uid`, `gid`, `shell`, and `homedir`. On Windows, the `uid` and`gid` fields are `-1`, and `shell` is `null`.
*
* The value of `homedir` returned by `os.userInfo()` is provided by the operating
* system. This differs from the result of `os.homedir()`, which queries
* environment variables for the home directory before falling back to the
* operating system response.
*
* Throws a `SystemError` if a user |
has no `username` or `homedir`.
* @since v6.0.0
*/
function userInfo(options: { encoding: "buffer" }): UserInfo<Buffer>;
function userInfo(options?: { encoding: BufferEncoding }): UserInfo<string>;
type SignalConstants = {
[key in NodeJS.Signals]: number;
};
namespace constants {
const UV_UDP_REUSEADDR: number;
namespace signals {}
const signals: SignalConstants;
namespace errno {
const E2BIG: number;
const EACCES: number;
const EADDRINUSE: number;
const EADDRNOTAVAIL: number;
const EAFNOSUPPORT: number;
const EAGAIN: number;
const EALREADY: number;
const EBADF: number;
const EBADMSG: number;
const EBUSY: number;
const ECANCELED: number;
const ECHILD: number;
const ECONNABORTED: number;
const ECONNREFUSED: number;
const ECONNRESET: number;
const EDEADLK: number;
const EDESTADDRREQ: number;
const EDOM: number;
const EDQUOT: number;
const EEXIST: number;
const EFAULT: number;
const EFBIG: number;
const EHOSTUNREACH: number;
const EIDRM: number;
const EILSEQ: number;
const EINPROGRESS: number;
const EINTR: number;
const EINVAL: number;
const EIO: number;
const EISCONN: number;
const EISDIR: number;
const ELOOP: number;
const EMFILE: number;
const EMLINK: number;
const EMSGSIZE: number;
const EMULTIHOP: number;
const ENAMETOOLONG: number;
const ENETDOWN: number;
const ENETRESET: number;
const ENETUNREACH: number;
const ENFILE: number;
const ENOBUFS: number;
const ENODATA: number;
const ENODEV: number;
const ENOENT: number;
const ENOEXEC: number;
const ENOLCK: number;
const ENOLINK: number;
const ENOMEM: number;
const ENOMSG: number;
const ENOPROTOOPT: number;
const ENOSPC: number;
const ENOSR: number;
const ENOSTR: number;
const ENOSYS: number;
const ENOTCONN: number;
const ENOTDIR: number;
const ENOTEMPTY: number;
const ENOTSOCK: number;
const ENOTSUP: number;
const ENOTTY: number;
const ENXIO: number;
const EOPNOTSUPP: number;
const EOVERFLOW: number;
const EPERM: number;
const EPIPE: number;
const EPROTO: number;
const EPROTONOSUPPORT: number;
const EPROTOTYPE: number;
const ERANGE: number;
const EROFS: number;
const ESPIPE: number;
const ESRCH: number;
const ESTALE: number;
const ETIME: number;
const ETIMEDOUT: number;
const ETXTBSY: number;
const EWOULDBLOCK: number;
const EXDEV: number;
const WSAEINTR: number;
const WSAEBADF: number;
const WSAEACCES: number;
const WSAEFAULT: number;
const WSAEINVAL: number;
const WSAEMFILE: number;
const WSAEWOULDBLOCK: number;
const WSAEINPROGRESS: number;
const WSAEALREADY: number;
const WSAENOTSOCK: number;
const WSAEDESTADDRREQ: number;
const WSAEMSGSIZE: number;
const WSAEPROTOTYPE: number;
const WSAENOPROTOOPT: number;
const WSAEPROTONOSUPPORT: number;
const WSAESOCKTNOSUPPORT: number;
const WSAEOPNOTSUPP: number;
const WSAEPFNOSUPPORT: number;
const WSAEAFNOSUPP |
ORT: number;
const WSAEADDRINUSE: number;
const WSAEADDRNOTAVAIL: number;
const WSAENETDOWN: number;
const WSAENETUNREACH: number;
const WSAENETRESET: number;
const WSAECONNABORTED: number;
const WSAECONNRESET: number;
const WSAENOBUFS: number;
const WSAEISCONN: number;
const WSAENOTCONN: number;
const WSAESHUTDOWN: number;
const WSAETOOMANYREFS: number;
const WSAETIMEDOUT: number;
const WSAECONNREFUSED: number;
const WSAELOOP: number;
const WSAENAMETOOLONG: number;
const WSAEHOSTDOWN: number;
const WSAEHOSTUNREACH: number;
const WSAENOTEMPTY: number;
const WSAEPROCLIM: number;
const WSAEUSERS: number;
const WSAEDQUOT: number;
const WSAESTALE: number;
const WSAEREMOTE: number;
const WSASYSNOTREADY: number;
const WSAVERNOTSUPPORTED: number;
const WSANOTINITIALISED: number;
const WSAEDISCON: number;
const WSAENOMORE: number;
const WSAECANCELLED: number;
const WSAEINVALIDPROCTABLE: number;
const WSAEINVALIDPROVIDER: number;
const WSAEPROVIDERFAILEDINIT: number;
const WSASYSCALLFAILURE: number;
const WSASERVICE_NOT_FOUND: number;
const WSATYPE_NOT_FOUND: number;
const WSA_E_NO_MORE: number;
const WSA_E_CANCELLED: number;
const WSAEREFUSED: number;
}
namespace priority {
const PRIORITY_LOW: number;
const PRIORITY_BELOW_NORMAL: number;
const PRIORITY_NORMAL: number;
const PRIORITY_ABOVE_NORMAL: number;
const PRIORITY_HIGH: number;
const PRIORITY_HIGHEST: number;
}
}
const devNull: string;
const EOL: string;
/**
* Returns the operating system CPU architecture for which the Node.js binary was
* compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`,`'mips'`, `'mipsel'`, `'ppc'`, `'ppc64'`, `'riscv64'`, `'s390'`, `'s390x'`,
* and `'x64'`.
*
* The return value is equivalent to `process.arch`.
* @since v0.5.0
*/
function arch(): string;
/**
* Returns a string identifying the kernel version.
*
* On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not
* available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information.
* @since v13.11.0, v12.17.0
*/
function version(): string;
/**
* Returns a string identifying the operating system platform for which
* the Node.js binary was compiled. The value is set at compile time.
* Possible values are `'aix'`, `'darwin'`, `'freebsd'`,`'linux'`,`'openbsd'`, `'sunos'`, and `'win32'`.
*
* The return value is equivalent to `process.platform`.
*
* The value `'android'` may also be returned if Node.js is built on the Android
* operating system. [Android support is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os).
* @since v0.5.0
*/
function platform(): NodeJS.Platform;
/**
* Returns the machine type as a string, such as `arm`, `arm64`, `aarch64`,`mips`, `mips64`, `ppc64`, `ppc64le`, `s390`, `s390x`, `i386`, `i686`, `x86_64`.
*
* On POSIX systems, the machine type is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not
* available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https:// |
en.wikipedia.org/wiki/Uname#Examples) for more information.
* @since v18.9.0, v16.18.0
*/
function machine(): string;
/**
* Returns the operating system's default directory for temporary files as a
* string.
* @since v0.9.9
*/
function tmpdir(): string;
/**
* Returns a string identifying the endianness of the CPU for which the Node.js
* binary was compiled.
*
* Possible values are `'BE'` for big endian and `'LE'` for little endian.
* @since v0.9.4
*/
function endianness(): "BE" | "LE";
/**
* Returns the scheduling priority for the process specified by `pid`. If `pid` is
* not provided or is `0`, the priority of the current process is returned.
* @since v10.10.0
* @param [pid=0] The process ID to retrieve scheduling priority for.
*/
function getPriority(pid?: number): number;
/**
* Attempts to set the scheduling priority for the process specified by `pid`. If`pid` is not provided or is `0`, the process ID of the current process is used.
*
* The `priority` input must be an integer between `-20` (high priority) and `19`(low priority). Due to differences between Unix priority levels and Windows
* priority classes, `priority` is mapped to one of six priority constants in`os.constants.priority`. When retrieving a process priority level, this range
* mapping may cause the return value to be slightly different on Windows. To avoid
* confusion, set `priority` to one of the priority constants.
*
* On Windows, setting priority to `PRIORITY_HIGHEST` requires elevated user
* privileges. Otherwise the set priority will be silently reduced to`PRIORITY_HIGH`.
* @since v10.10.0
* @param [pid=0] The process ID to set scheduling priority for.
* @param priority The scheduling priority to assign to the process.
*/
function setPriority(priority: number): void;
function setPriority(pid: number, priority: number): void;
}
declare module "node:os" {
export * from "os";
}
|
/**
* `Buffer` objects are used to represent a fixed-length sequence of bytes. Many
* Node.js APIs support `Buffer`s.
*
* The `Buffer` class is a subclass of JavaScript's [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) class and
* extends it with methods that cover additional use cases. Node.js APIs accept
* plain [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) s wherever `Buffer`s are supported as well.
*
* While the `Buffer` class is available within the global scope, it is still
* recommended to explicitly reference it via an import or require statement.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* // Creates a zero-filled Buffer of length 10.
* const buf1 = Buffer.alloc(10);
*
* // Creates a Buffer of length 10,
* // filled with bytes which all have the value `1`.
* const buf2 = Buffer.alloc(10, 1);
*
* // Creates an uninitialized buffer of length 10.
* // This is faster than calling Buffer.alloc() but the returned
* // Buffer instance might contain old data that needs to be
* // overwritten using fill(), write(), or other functions that fill the Buffer's
* // contents.
* const buf3 = Buffer.allocUnsafe(10);
*
* // Creates a Buffer containing the bytes [1, 2, 3].
* const buf4 = Buffer.from([1, 2, 3]);
*
* // Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries
* // are all truncated using `(value & 255)` to fit into the range 0–255.
* const buf5 = Buffer.from([257, 257.5, -255, '1']);
*
* // Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést':
* // [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation)
* // [116, 195, 169, 115, 116] (in decimal notation)
* const buf6 = Buffer.from('tést');
*
* // Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74].
* const buf7 = Buffer.from('tést', 'latin1');
* ```
* @see [source](https://github.com/nodejs/node/blob/v20.2.0/lib/buffer.js)
*/
declare module "buffer" {
import { BinaryLike } from "node:crypto";
import { ReadableStream as WebReadableStream } from "node:stream/web";
/**
* This function returns `true` if `input` contains only valid UTF-8-encoded data,
* including the case in which `input` is empty.
*
* Throws if the `input` is a detached array buffer.
* @since v19.4.0, v18.14.0
* @param input The input to validate.
*/
export function isUtf8(input: Buffer | ArrayBuffer | NodeJS.TypedArray): boolean;
/**
* This function returns `true` if `input` contains only valid ASCII-encoded data,
* including the case in which `input` is empty.
*
* Throws if the `input` is a detached array buffer.
* @since v19.6.0, v18.15.0
* @param input The input to validate.
*/
export function isAscii(input: Buffer | ArrayBuffer | NodeJS.TypedArray): boolean;
export const INSPECT_MAX_BYTES: number;
export const kMaxLength: number;
export const kStringMaxLength: number;
export const constants: {
MAX_LENGTH: number;
MAX_STRING_LENGTH: number;
};
export type TranscodeEncoding =
| "ascii"
| "utf8"
| "utf-8"
| "utf16le"
| "utf-16le"
| "ucs2"
| "ucs-2"
| "latin1"
| "binary";
/**
* Re-encodes the given `Buffer` or `Uint8Array` instance from one character
* encoding to another. Returns a new `Buffer` instance.
*
* Throws if the `fromEnc` or `toEnc` specify invalid character encodings or if
* conversion from `fromEnc` to `toEnc` is not permitted.
*
* Encodings supported by `buffer.transcode()` are: `'ascii'`, `'utf8'`,`'utf16le'`, `'ucs2'`, `'latin1'`, and `'binary'`.
*
* The transcoding process will use substitution characters if a given byte
* sequence cannot be adequately represented in the target encoding. For instance:
*
|
* ```js
* import { Buffer, transcode } from 'node:buffer';
*
* const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii');
* console.log(newBuf.toString('ascii'));
* // Prints: '?'
* ```
*
* Because the Euro (`€`) sign is not representable in US-ASCII, it is replaced
* with `?` in the transcoded `Buffer`.
* @since v7.1.0
* @param source A `Buffer` or `Uint8Array` instance.
* @param fromEnc The current encoding.
* @param toEnc To target encoding.
*/
export function transcode(source: Uint8Array, fromEnc: TranscodeEncoding, toEnc: TranscodeEncoding): Buffer;
export const SlowBuffer: {
/** @deprecated since v6.0.0, use `Buffer.allocUnsafeSlow()` */
new(size: number): Buffer;
prototype: Buffer;
};
/**
* Resolves a `'blob:nodedata:...'` an associated `Blob` object registered using
* a prior call to `URL.createObjectURL()`.
* @since v16.7.0
* @experimental
* @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`.
*/
export function resolveObjectURL(id: string): Blob | undefined;
export { Buffer };
/**
* @experimental
*/
export interface BlobOptions {
/**
* @default 'utf8'
*/
encoding?: BufferEncoding | undefined;
/**
* The Blob content-type. The intent is for `type` to convey
* the MIME media type of the data, however no validation of the type format
* is performed.
*/
type?: string | undefined;
}
/**
* A [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) encapsulates immutable, raw data that can be safely shared across
* multiple worker threads.
* @since v15.7.0, v14.18.0
*/
export class Blob {
/**
* The total size of the `Blob` in bytes.
* @since v15.7.0, v14.18.0
*/
readonly size: number;
/**
* The content-type of the `Blob`.
* @since v15.7.0, v14.18.0
*/
readonly type: string;
/**
* Creates a new `Blob` object containing a concatenation of the given sources.
*
* {ArrayBuffer}, {TypedArray}, {DataView}, and {Buffer} sources are copied into
* the 'Blob' and can therefore be safely modified after the 'Blob' is created.
*
* String sources are also copied into the `Blob`.
*/
constructor(sources: Array<BinaryLike | Blob>, options?: BlobOptions);
/**
* Returns a promise that fulfills with an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) containing a copy of
* the `Blob` data.
* @since v15.7.0, v14.18.0
*/
arrayBuffer(): Promise<ArrayBuffer>;
/**
* Creates and returns a new `Blob` containing a subset of this `Blob` objects
* data. The original `Blob` is not altered.
* @since v15.7.0, v14.18.0
* @param start The starting index.
* @param end The ending index.
* @param type The content-type for the new `Blob`
*/
slice(start?: number, end?: number, type?: string): Blob;
/**
* Returns a promise that fulfills with the contents of the `Blob` decoded as a
* UTF-8 string.
* @since v15.7.0, v14.18.0
*/
text(): Promise<string>;
/**
* Returns a new `ReadableStream` that allows the content of the `Blob` to be read.
* @since v16.7.0
*/
stream(): WebReadableStream;
}
export interface FileOptions {
/**
* One of either `'transparent'` or `'native'`. When set to `'native'`, line endings in string source parts will be
* converted to the platform native line-ending as specified by `require('node:os').EOL`.
*/
endings?: "nativ |
e" | "transparent";
/** The File content-type. */
type?: string;
/** The last modified date of the file. `Default`: Date.now(). */
lastModified?: number;
}
/**
* A [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) provides information about files.
* @since v19.2.0, v18.13.0
*/
export class File extends Blob {
constructor(sources: Array<BinaryLike | Blob>, fileName: string, options?: FileOptions);
/**
* The name of the `File`.
* @since v19.2.0, v18.13.0
*/
readonly name: string;
/**
* The last modified date of the `File`.
* @since v19.2.0, v18.13.0
*/
readonly lastModified: number;
}
export import atob = globalThis.atob;
export import btoa = globalThis.btoa;
import { Blob as NodeBlob } from "buffer";
// This conditional type will be the existing global Blob in a browser, or
// the copy below in a Node environment.
type __Blob = typeof globalThis extends { onmessage: any; Blob: any } ? {} : NodeBlob;
global {
namespace NodeJS {
export { BufferEncoding };
}
// Buffer class
type BufferEncoding =
| "ascii"
| "utf8"
| "utf-8"
| "utf16le"
| "utf-16le"
| "ucs2"
| "ucs-2"
| "base64"
| "base64url"
| "latin1"
| "binary"
| "hex";
type WithImplicitCoercion<T> =
| T
| {
valueOf(): T;
};
/**
* Raw data is stored in instances of the Buffer class.
* A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized.
* Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'base64url'|'binary'(deprecated)|'hex'
*/
interface BufferConstructor {
/**
* Allocates a new buffer containing the given {str}.
*
* @param str String to store in buffer.
* @param encoding encoding to use, optional. Default is 'utf8'
* @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead.
*/
new(str: string, encoding?: BufferEncoding): Buffer;
/**
* Allocates a new buffer of {size} octets.
*
* @param size count of octets to allocate.
* @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`).
*/
new(size: number): Buffer;
/**
* Allocates a new buffer containing the given {array} of octets.
*
* @param array The octets to store.
* @deprecated since v10.0.0 - Use `Buffer.from(array)` instead.
*/
new(array: Uint8Array): Buffer;
/**
* Produces a Buffer backed by the same allocated memory as
* the given {ArrayBuffer}/{SharedArrayBuffer}.
*
* @param arrayBuffer The ArrayBuffer with which to share memory.
* @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead.
*/
new(arrayBuffer: ArrayBuffer | SharedArrayBuffer): Buffer;
/**
* Allocates a new buffer containing the given {array} of octets.
*
* @param array The octets to store.
* @deprecated since v10.0.0 - Use `Buffer.from(array)` instead.
*/
new(array: readonly any[]): Buffer;
/**
* Copies the passed {buffer} data onto a new {Buffer} instance.
*
* @param buffer The buffer to copy.
* @deprecated since v10.0.0 - Use `Buffer.from(buf |
fer)` instead.
*/
new(buffer: Buffer): Buffer;
/**
* Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`.
* Array entries outside that range will be truncated to fit into it.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.
* const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);
* ```
*
* If `array` is an `Array`\-like object (that is, one with a `length` property of
* type `number`), it is treated as if it is an array, unless it is a `Buffer` or
* a `Uint8Array`. This means all other `TypedArray` variants get treated as an`Array`. To create a `Buffer` from the bytes backing a `TypedArray`, use `Buffer.copyBytesFrom()`.
*
* A `TypeError` will be thrown if `array` is not an `Array` or another type
* appropriate for `Buffer.from()` variants.
*
* `Buffer.from(array)` and `Buffer.from(string)` may also use the internal`Buffer` pool like `Buffer.allocUnsafe()` does.
* @since v5.10.0
*/
from(
arrayBuffer: WithImplicitCoercion<ArrayBuffer | SharedArrayBuffer>,
byteOffset?: number,
length?: number,
): Buffer;
/**
* Creates a new Buffer using the passed {data}
* @param data data to create a new Buffer
*/
from(data: Uint8Array | readonly number[]): Buffer;
from(data: WithImplicitCoercion<Uint8Array | readonly number[] | string>): Buffer;
/**
* Creates a new Buffer containing the given JavaScript string {str}.
* If provided, the {encoding} parameter identifies the character encoding.
* If not provided, {encoding} defaults to 'utf8'.
*/
from(
str:
| WithImplicitCoercion<string>
| {
[Symbol.toPrimitive](hint: "string"): string;
},
encoding?: BufferEncoding,
): Buffer;
/**
* Creates a new Buffer using the passed {data}
* @param values to create a new Buffer
*/
of(...items: number[]): Buffer;
/**
* Returns `true` if `obj` is a `Buffer`, `false` otherwise.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* Buffer.isBuffer(Buffer.alloc(10)); // true
* Buffer.isBuffer(Buffer.from('foo')); // true
* Buffer.isBuffer('a string'); // false
* Buffer.isBuffer([]); // false
* Buffer.isBuffer(new Uint8Array(1024)); // false
* ```
* @since v0.1.101
*/
isBuffer(obj: any): obj is Buffer;
/**
* Returns `true` if `encoding` is the name of a supported character encoding,
* or `false` otherwise.
*
* ```js
* import { Buffer } from 'node:buffer';
*
* console.log(Buffer.isEncoding('utf8'));
* // Prints: true
*
* console.log(Buffer.isEncoding('hex'));
* // Prints: true
*
* console.log(Buffer.isEncoding('utf/8'));
* // Prints: false
*
* console.log(Buffer.isEncoding(''));
* // Prints: false
* ```
* @since v0.9.1
* @param encoding A character encoding name to check.
*/
isEncoding(encoding: string): encoding is BufferEncoding;
/**
* Returns the byte |