Skip to main content

tls

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:

import tls from 'node:tls';

Usage in Deno

import * as mod from "node:tls";

Functions

f
checkServerIdentity

Verifies the certificate cert is issued to hostname.

    f
    connect

    The callback function, if specified, will be added as a listener for the 'secureConnect' event.

      f
      createSecureContext

      [createServer](/api/node/tls/ sets the default value of the honorCipherOrder option to true, other APIs that create secure contexts leave it unset.

        f
        createServer

        Creates a new Server. The secureConnectionListener, if provided, is automatically set as a listener for the 'secureConnection' event.

          f
          getCiphers

          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 [createSecureContext](/api/node/tls/.

            f
            createSecurePair
            No documentation available

              Type Aliases

              T
              SecureVersion
              No documentation available

                Variables

                v
                CLIENT_RENEG_LIMIT
                No documentation available
                  v
                  CLIENT_RENEG_WINDOW
                  No documentation available
                    v
                    DEFAULT_CIPHERS

                    The default value of the ciphers option of 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.

                      v
                      DEFAULT_ECDH_CURVE

                      The default curve name to use for ECDH key agreement in a tls server. The default value is 'auto'. See createSecureContext() for further information.

                        v
                        DEFAULT_MAX_VERSION

                        The default value of the maxVersion option of 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.

                          v
                          DEFAULT_MIN_VERSION

                          The default value of the minVersion option of 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.

                            v
                            rootCertificates

                            An immutable array of strings representing the root certificates (in PEM format) from the bundled Mozilla CA store as supplied by the current Node.js version.


                              class Server

                              extends net.Server

                              Usage in Deno

                              import { Server } from "node:tls";
                              

                              Accepts encrypted connections using TLS or SSL.

                              Constructors #

                              #Server(secureConnectionListener?: (socket: TLSSocket) => void)
                              new
                              #Server(
                              options: TlsOptions,
                              secureConnectionListener?: (socket: TLSSocket) => void,
                              )
                              new

                              Methods #

                              #addContext(
                              hostname: string,
                              ): 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 recently added one is used.

                              #addListener(
                              event: string,
                              listener: (...args: any[]) => void,
                              ): this

                              events.EventEmitter

                              1. tlsClientError
                              2. newSession
                              3. OCSPRequest
                              4. resumeSession
                              5. secureConnection
                              6. keylog
                              #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
                              #getTicketKeys(): Buffer

                              Returns the session ticket keys.

                              See Session Resumption for more information.

                              #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

                              The server.setSecureContext() method replaces the secure context of an existing server. Existing connections to the server are not interrupted.

                              #setTicketKeys(keys: Buffer): 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.


                              class TLSSocket

                              extends net.Socket

                              Usage in Deno

                              import { TLSSocket } from "node:tls";
                              

                              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.TLSSocket.getPeerCertificate) will only return data while the connection is open.

                              Constructors #

                              #TLSSocket(
                              socket: net.Socket | stream.Duplex,
                              options?: TLSSocketOptions,
                              )
                              new

                              Construct a new tls.TLSSocket object from an existing TCP socket.

                              Properties #

                              #alpnProtocol:
                              string
                              | false
                              | null

                              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.

                              Returns the reason why the peer's certificate was not been verified. This property is set only when tlsSocket.authorized === false.

                              #authorized: boolean

                              This property is true if the peer certificate was signed by one of the CAs specified when creating the tls.TLSSocket instance, otherwise false.

                              #encrypted: true

                              Always returns true. This may be used to distinguish TLS sockets from regularnet.Socket instances.

                              Methods #

                              #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

                              Disables TLS renegotiation for this TLSSocket instance. Once called, attempts to renegotiate will trigger an 'error' event on the TLSSocket.

                              #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
                              #enableTrace(): 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 ofopenssl 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.

                              #exportKeyingMaterial(
                              length: number,
                              label: string,
                              context: Buffer,
                              ): Buffer

                              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

                              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 documentation for more information.

                              #getCertificate():
                              PeerCertificate
                              | object
                              | null

                              Returns an object representing the local certificate. The returned object has some properties corresponding to the fields of the certificate.

                              See 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.

                              Returns an object containing information on the negotiated cipher suite.

                              For example, a TLSv1.2 protocol with AES256-SHA cipher:

                              {
                                  "name": "AES256-SHA",
                                  "standardName": "TLS_RSA_WITH_AES_256_CBC_SHA",
                                  "version": "SSLv3"
                              }
                              

                              See SSL_CIPHER_get_name for more information.

                              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 }.

                              #getFinished(): Buffer | undefined

                              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.

                              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 anissuerCertificate property containing an object representing its issuer's certificate.

                              #getPeerFinished(): Buffer | undefined

                              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.

                              Returns the peer certificate as an X509Certificate object.

                              If there is no peer certificate, or the socket has been destroyed,undefined will be returned.

                              #getProtocol(): string | null

                              Returns a string containing the negotiated SSL/TLS protocol version of the current connection. The value '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 documentation for more information.

                              #getSession(): Buffer | undefined

                              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 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).

                              #getSharedSigalgs(): string[]

                              See SSL_get_shared_sigalgs for more information.

                              #getTLSTicket(): Buffer | undefined

                              For a client, returns the TLS session ticket if one is available, orundefined. For a server, always returns undefined.

                              It may be useful for debugging.

                              See Session Resumption for more information.

                              Returns the local certificate as an X509Certificate object.

                              If there is no local certificate, or the socket has been destroyed,undefined will be returned.

                              #isSessionReused(): boolean

                              See Session Resumption for more information.

                              #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
                              #renegotiate(
                              options: { rejectUnauthorized?: boolean | undefined; requestCert?: boolean | undefined; },
                              callback: (err: Error | null) => void,
                              ): undefined | 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.

                              #setMaxSendFragment(size: number): 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 reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, which may decrease overall server throughput.


                              function checkServerIdentity

                              Usage in Deno

                              import { checkServerIdentity } from "node:tls";
                              
                              #checkServerIdentity(
                              hostname: string,
                              ): Error | undefined

                              Verifies the certificate cert is issued to hostname.

                              Returns Error object, populating it with reason, host, and cert on failure. On success, returns undefined.

                              This function is intended to be used in combination with thecheckServerIdentity option that can be passed to 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 givenhostname if a matching uniformResourceIdentifier subject alternative name was present (see CVE-2021-44531). Applications that wish to acceptuniformResourceIdentifier subject alternative names can use a custom options.checkServerIdentity function that implements the desired behavior.

                              Parameters #

                              #hostname: string

                              The host name or IP address to verify the certificate against.

                              A certificate object representing the peer's certificate.

                              Return Type #

                              Error | undefined

                              function connect

                              Usage in Deno

                              import { connect } from "node:tls";
                              

                              Overload 1

                              #connect(
                              secureConnectListener?: () => void,
                              ): TLSSocket

                              The callback function, if specified, will be added as a listener for the 'secureConnect' event.

                              tls.connect() returns a 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 createServer:

                              // Assumes an echo server that is listening on port 8000.
                              import tls from 'node:tls';
                              import fs from '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');
                              });
                              

                              Parameters #

                              #secureConnectListener: () => void
                              optional

                              Return Type #

                              Overload 2

                              #connect(
                              port: number,
                              host?: string,
                              secureConnectListener?: () => void,
                              ): TLSSocket

                              Parameters #

                              #port: number
                              #host: string
                              optional
                              #options: ConnectionOptions
                              optional
                              #secureConnectListener: () => void
                              optional

                              Return Type #

                              Overload 3

                              #connect(
                              port: number,
                              secureConnectListener?: () => void,
                              ): TLSSocket

                              Parameters #

                              #port: number
                              #options: ConnectionOptions
                              optional
                              #secureConnectListener: () => void
                              optional

                              Return Type #


                              function createSecureContext

                              Usage in Deno

                              import { createSecureContext } from "node:tls";
                              
                              #createSecureContext(options?: SecureContextOptions): SecureContext

                              [createServer](/api/node/tls/ sets the default value of the honorCipherOrder option to true, other APIs that create secure contexts leave it unset.

                              [createServer](/api/node/tls/ 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 Server constructor and the 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.

                              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.

                              Parameters #

                              #options: SecureContextOptions
                              optional

                              Return Type #


                              function createServer

                              Usage in Deno

                              import { createServer } from "node:tls";
                              

                              Overload 1

                              #createServer(secureConnectionListener?: (socket: TLSSocket) => void): Server

                              Creates a new 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:

                              import tls from 'node:tls';
                              import fs from '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) => {
                                console.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 connect.

                              Parameters #

                              #secureConnectionListener: (socket: TLSSocket) => void
                              optional

                              Return Type #

                              Overload 2

                              #createServer(
                              options: TlsOptions,
                              secureConnectionListener?: (socket: TLSSocket) => void,
                              ): Server

                              Parameters #

                              #options: TlsOptions
                              #secureConnectionListener: (socket: TLSSocket) => void
                              optional

                              Return Type #


                              function getCiphers

                              Usage in Deno

                              import { getCiphers } from "node:tls";
                              
                              #getCiphers(): string[]

                              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 [createSecureContext](/api/node/tls/.

                              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.

                              console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...]
                              

                              Return Type #

                              string[]

                              function createSecurePair

                              Usage in Deno

                              import { createSecurePair } from "node:tls";
                              
                              #createSecurePair(
                              context?: SecureContext,
                              isServer?: boolean,
                              requestCert?: boolean,
                              rejectUnauthorized?: boolean,
                              ): SecurePair
                              Deprecated

                              Deno compatibility

                              This symbol is currently not supported.

                              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 TLSSocket.

                              The tls.createSecurePair() method is now deprecated in favor oftls.TLSSocket(). For example, the code:

                              pair = tls.createSecurePair(// ... );
                              pair.encrypted.pipe(socket);
                              socket.pipe(pair.encrypted);
                              

                              can be replaced by:

                              secureSocket = tls.TLSSocket(socket, options);
                              

                              where secureSocket has the same API as pair.cleartext.

                              Parameters #

                              #context: SecureContext
                              optional

                              A secure context object as returned by tls.createSecureContext()

                              #isServer: boolean
                              optional

                              true to specify that this TLS connection should be opened as a server.

                              #requestCert: boolean
                              optional

                              true to specify whether a server should request a certificate from a connecting client. Only applies when isServer is true.

                              #rejectUnauthorized: boolean
                              optional

                              If not false a server automatically reject clients with invalid certificates. Only applies when isServer is true.

                              Return Type #


                              interface Certificate

                              Usage in Deno

                              import { type Certificate } from "node:tls";
                              

                              Properties #

                              #C: string

                              Country code.

                              #ST: string

                              Street.

                              #L: string

                              Locality.

                              #O: string

                              Organization.

                              #OU: string

                              Organizational unit.

                              #CN: string

                              Common name.



                              interface CommonConnectionOptions

                              Usage in Deno

                              import { type CommonConnectionOptions } from "node:tls";
                              

                              Properties #

                              #secureContext: SecureContext | undefined
                              optional

                              An optional TLS context object from tls.createSecureContext()

                              #enableTrace: boolean | undefined
                              optional

                              When enabled, TLS packet trace information is written to stderr. This can be used to debug TLS connection problems.

                              #requestCert: boolean | undefined
                              optional

                              If true the server will request a certificate from clients that connect and attempt to verify that certificate. Defaults to false.

                              #ALPNProtocols:
                              string[]
                              | Uint8Array[]
                              | Uint8Array
                              | undefined
                              optional

                              An array of strings or a Buffer naming possible ALPN protocols. (Protocols should be ordered by their priority.)

                              #SNICallback: ((
                              servername: string,
                              cb: (
                              err: Error | null,
                              ) => void
                              ,
                              ) => void) | undefined
                              optional

                              SNICallback(servername, cb) 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).

                              #rejectUnauthorized: boolean | undefined
                              optional

                              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.


                              interface ConnectionOptions

                              Usage in Deno

                              import { type ConnectionOptions } from "node:tls";
                              

                              Properties #

                              #host: string | undefined
                              optional
                              #port: number | undefined
                              optional
                              #path: string | undefined
                              optional
                              #socket: stream.Duplex | undefined
                              optional
                              #servername: string | undefined
                              optional
                              #session: Buffer | undefined
                              optional
                              #minDHSize: number | undefined
                              optional
                              #lookup: net.LookupFunction | undefined
                              optional
                              #timeout: number | undefined
                              optional

                              Methods #

                              #pskCallback(hint: string | null): PSKCallbackNegotation | null
                              optional

                              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.



                              interface EphemeralKeyInfo

                              Usage in Deno

                              import { type EphemeralKeyInfo } from "node:tls";
                              

                              Properties #

                              #type: string

                              The supported types are 'DH' and 'ECDH'.

                              #name: string | undefined
                              optional

                              The name property is available only when type is 'ECDH'.

                              #size: number

                              The size of parameter of an ephemeral key exchange.


                              interface KeyObject

                              Usage in Deno

                              import { type KeyObject } from "node:tls";
                              

                              Properties #

                              #pem: string | Buffer

                              Private keys in PEM format.

                              #passphrase: string | undefined
                              optional

                              Optional passphrase.


                              interface PeerCertificate

                              Usage in Deno

                              import { type PeerCertificate } from "node:tls";
                              

                              Properties #

                              #ca: boolean

                              true if a Certificate Authority (CA), false otherwise.

                              #raw: Buffer

                              The DER encoded X.509 certificate data.

                              The certificate subject.

                              The certificate issuer, described in the same terms as the subject.

                              #valid_from: string

                              The date-time the certificate is valid from.

                              #valid_to: string

                              The date-time the certificate is valid to.

                              #serialNumber: string

                              The certificate serial number, as a hex string.

                              #fingerprint: string

                              The SHA-1 digest of the DER encoded certificate. It is returned as a : separated hexadecimal string.

                              The SHA-256 digest of the DER encoded certificate. It is returned as a : separated hexadecimal string.

                              The SHA-512 digest of the DER encoded certificate. It is returned as a : separated hexadecimal string.

                              #ext_key_usage: string[]
                              optional

                              The extended key usage, a set of OIDs.

                              #subjectaltname: string
                              optional

                              A string containing concatenated names for the subject, an alternative to the subject names.

                              #infoAccess: Dict<string[]>
                              optional

                              An array describing the AuthorityInfoAccess, used with OCSP.

                              #bits: number
                              optional

                              For RSA keys: The RSA bit size.

                              For EC keys: The key size in bits.

                              #exponent: string
                              optional

                              The RSA exponent, as a string in hexadecimal number notation.

                              #modulus: string
                              optional

                              The RSA modulus, as a hexadecimal string.

                              #pubkey: Buffer
                              optional

                              The public key.

                              #asn1Curve: string
                              optional

                              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.

                              #nistCurve: string
                              optional

                              The NIST name for the elliptic curve, if it has one (not all well-known curves have been assigned names by NIST).



                              interface PxfObject

                              Usage in Deno

                              import { type PxfObject } from "node:tls";
                              

                              Properties #

                              #buf: string | Buffer

                              PFX or PKCS12 encoded private key and certificate chain.

                              #passphrase: string | undefined
                              optional

                              Optional passphrase.



                              interface SecureContextOptions

                              Usage in Deno

                              import { type SecureContextOptions } from "node:tls";
                              

                              Properties #

                              #ALPNCallback: ((arg: { servername: string; protocols: string[]; }) => string | undefined) | undefined
                              optional

                              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 object 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.

                              #allowPartialTrustChain: boolean | undefined
                              optional

                              Treat intermediate (non-self-signed) certificates in the trust CA certificate list as trusted.

                              #ca:
                              string
                              | Buffer
                              | Array<string | Buffer>
                              | undefined
                              optional

                              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.

                              #cert:
                              string
                              | Buffer
                              | Array<string | Buffer>
                              | undefined
                              optional

                              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.

                              #sigalgs: string | undefined
                              optional

                              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).

                              #ciphers: string | undefined
                              optional

                              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.

                              #clientCertEngine: string | undefined
                              deprecated
                              optional

                              Name of an OpenSSL engine which can provide the client certificate.

                              #crl:
                              string
                              | Buffer
                              | Array<string | Buffer>
                              | undefined
                              optional

                              PEM formatted CRLs (Certificate Revocation Lists).

                              #dhparam:
                              string
                              | Buffer
                              | undefined
                              optional

                              '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.

                              #ecdhCurve: string | undefined
                              optional

                              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.

                              #honorCipherOrder: boolean | undefined
                              optional

                              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

                              #key:
                              string
                              | Buffer
                              | Array<
                              string
                              | Buffer
                              | KeyObject
                              >

                              | undefined
                              optional

                              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: ]}. 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.

                              #privateKeyEngine: string | undefined
                              deprecated
                              optional

                              Name of an OpenSSL engine to get private key from. Should be used together with privateKeyIdentifier.

                              #privateKeyIdentifier: string | undefined
                              deprecated
                              optional

                              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.

                              #maxVersion: SecureVersion | undefined
                              optional

                              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.

                              #minVersion: SecureVersion | undefined
                              optional

                              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.

                              #passphrase: string | undefined
                              optional

                              Shared passphrase used for a single private key and/or a PFX.

                              #pfx:
                              string
                              | Buffer
                              | Array<
                              string
                              | Buffer
                              | PxfObject
                              >

                              | undefined
                              optional

                              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: ]}. 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.

                              #secureOptions: number | undefined
                              optional

                              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

                              #secureProtocol: string | undefined
                              optional

                              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.

                              #sessionIdContext: string | undefined
                              optional

                              Opaque identifier used by servers to ensure session state is not shared between applications. Unused by clients.

                              #ticketKeys: Buffer | undefined
                              optional

                              48-bytes of cryptographically strong pseudo-random data. See Session Resumption for more information.

                              #sessionTimeout: number | undefined
                              optional

                              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.


                              interface TlsOptions

                              Usage in Deno

                              import { type TlsOptions } from "node:tls";
                              

                              Properties #

                              #handshakeTimeout: number | undefined
                              optional

                              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).

                              #sessionTimeout: number | undefined
                              optional

                              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.

                              #ticketKeys: Buffer | undefined
                              optional

                              48-bytes of cryptographically strong pseudo-random data.

                              #pskIdentityHint: string | undefined
                              optional

                              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.

                              Methods #

                              #pskCallback(
                              socket: TLSSocket,
                              identity: string,
                              ):
                              DataView
                              | TypedArray
                              | null
                              optional

                              interface TLSSocketOptions

                              Usage in Deno

                              import { type TLSSocketOptions } from "node:tls";
                              

                              Properties #

                              #isServer: boolean | undefined
                              optional

                              If true the TLS socket will be instantiated in server-mode. Defaults to false.

                              #server: net.Server | undefined
                              optional

                              An optional net.Server instance.

                              #session: Buffer | undefined
                              optional

                              An optional Buffer instance containing a TLS session.

                              #requestOCSP: boolean | undefined
                              optional

                              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



                              type alias SecureVersion

                              Usage in Deno

                              import { type SecureVersion } from "node:tls";
                              

                              Definition #

                              "TLSv1.3"
                              | "TLSv1.2"
                              | "TLSv1.1"
                              | "TLSv1"

                              variable CLIENT_RENEG_LIMIT

                              Usage in Deno

                              import { CLIENT_RENEG_LIMIT } from "node:tls";
                              

                              Type #

                              number

                              variable CLIENT_RENEG_WINDOW

                              Usage in Deno

                              import { CLIENT_RENEG_WINDOW } from "node:tls";
                              

                              Type #

                              number

                              variable DEFAULT_CIPHERS

                              Usage in Deno

                              import { DEFAULT_CIPHERS } from "node:tls";
                              

                              The default value of the ciphers option of 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.

                              Type #

                              string

                              variable DEFAULT_ECDH_CURVE

                              Usage in Deno

                              import { DEFAULT_ECDH_CURVE } from "node:tls";
                              

                              The default curve name to use for ECDH key agreement in a tls server. The default value is 'auto'. See createSecureContext() for further information.

                              Type #

                              string

                              variable DEFAULT_MAX_VERSION

                              Usage in Deno

                              import { DEFAULT_MAX_VERSION } from "node:tls";
                              

                              The default value of the maxVersion option of 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.

                              Type #


                              variable DEFAULT_MIN_VERSION

                              Usage in Deno

                              import { DEFAULT_MIN_VERSION } from "node:tls";
                              

                              The default value of the minVersion option of 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.

                              Type #


                              variable rootCertificates

                              Usage in Deno

                              import { rootCertificates } from "node:tls";
                              

                              An immutable array of strings representing the root certificates (in PEM format) from the bundled Mozilla CA store as supplied by the current Node.js version.

                              The bundled CA store, as supplied by Node.js, is a snapshot of Mozilla CA store that is fixed at release time. It is identical on all supported platforms.

                              Type #

                              readonly string[]

                              Did you find what you needed?

                              Privacy policy