2 * The `tls` module provides an implementation of the Transport Layer Security
3 * (TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL.
4 * The module can be accessed using:
7 * const tls = require('tls');
9 * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/tls.js)
11 declare module 'tls' {
12 import { X509Certificate } from 'node:crypto';
13 import * as net from 'node:net';
14 import * as stream from 'stream';
15 const CLIENT_RENEG_LIMIT: number;
16 const CLIENT_RENEG_WINDOW: number;
17 interface Certificate {
35 * Organizational unit.
43 interface PeerCertificate {
46 subjectaltname: string;
47 infoAccess: NodeJS.Dict<string[]>;
53 fingerprint256: string;
54 ext_key_usage: string[];
58 interface DetailedPeerCertificate extends PeerCertificate {
59 issuerCertificate: DetailedPeerCertificate;
61 interface CipherNameAndProtocol {
67 * SSL/TLS protocol version.
71 * IETF name for the cipher suite.
75 interface EphemeralKeyInfo {
77 * The supported types are 'DH' and 'ECDH'.
81 * The name property is available only when type is 'ECDH'.
83 name?: string | undefined;
85 * The size of parameter of an ephemeral key exchange.
91 * Private keys in PEM format.
95 * Optional passphrase.
97 passphrase?: string | undefined;
101 * PFX or PKCS12 encoded private key and certificate chain.
103 buf: string | Buffer;
105 * Optional passphrase.
107 passphrase?: string | undefined;
109 interface TLSSocketOptions extends SecureContextOptions, CommonConnectionOptions {
111 * If true the TLS socket will be instantiated in server-mode.
114 isServer?: boolean | undefined;
116 * An optional net.Server instance.
118 server?: net.Server | undefined;
120 * An optional Buffer instance containing a TLS session.
122 session?: Buffer | undefined;
124 * If true, specifies that the OCSP status request extension will be
125 * added to the client hello and an 'OCSPResponse' event will be
126 * emitted on the socket before establishing a secure communication
128 requestOCSP?: boolean | undefined;
131 * Performs transparent encryption of written data and all required TLS
134 * Instances of `tls.TLSSocket` implement the duplex `Stream` interface.
136 * Methods that return TLS connection metadata (e.g.{@link TLSSocket.getPeerCertificate} will only return data while the
137 * connection is open.
140 class TLSSocket extends net.Socket {
142 * Construct a new tls.TLSSocket object from an existing TCP socket.
144 constructor(socket: net.Socket, options?: TLSSocketOptions);
146 * This property is `true` if the peer certificate was signed by one of the CAs
147 * specified when creating the `tls.TLSSocket` instance, otherwise `false`.
152 * Returns the reason why the peer's certificate was not been verified. This
153 * property is set only when `tlsSocket.authorized === false`.
156 authorizationError: Error;
158 * Always returns `true`. This may be used to distinguish TLS sockets from regular`net.Socket` instances.
163 * String containing the selected ALPN protocol.
164 * Before a handshake has completed, this value is always null.
165 * When a handshake is completed but not ALPN protocol was selected, tlsSocket.alpnProtocol equals false.
167 alpnProtocol: string | false | null;
169 * Returns an object representing the local certificate. The returned object has
170 * some properties corresponding to the fields of the certificate.
172 * See {@link TLSSocket.getPeerCertificate} for an example of the certificate
175 * If there is no local certificate, an empty object will be returned. If the
176 * socket has been destroyed, `null` will be returned.
179 getCertificate(): PeerCertificate | object | null;
181 * Returns an object containing information on the negotiated cipher suite.
187 * "name": "AES128-SHA256",
188 * "standardName": "TLS_RSA_WITH_AES_128_CBC_SHA256",
189 * "version": "TLSv1.2"
193 * See [SSL\_CIPHER\_get\_name](https://www.openssl.org/docs/man1.1.1/man3/SSL_CIPHER_get_name.html) for more information.
196 getCipher(): CipherNameAndProtocol;
198 * Returns an object representing the type, name, and size of parameter of
199 * an ephemeral key exchange in `perfect forward secrecy` on a client
200 * connection. It returns an empty object when the key exchange is not
201 * ephemeral. As this is only supported on a client socket; `null` is returned
202 * if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The`name` property is available only when type is `'ECDH'`.
204 * For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`.
207 getEphemeralKeyInfo(): EphemeralKeyInfo | object | null;
209 * As the `Finished` messages are message digests of the complete handshake
210 * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can
211 * be used for external authentication procedures when the authentication
212 * provided by SSL/TLS is not desired or is not enough.
214 * Corresponds to the `SSL_get_finished` routine in OpenSSL and may be used
215 * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929).
217 * @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.
219 getFinished(): Buffer | undefined;
221 * Returns an object representing the peer's certificate. If the peer does not
222 * provide a certificate, an empty object will be returned. If the socket has been
223 * destroyed, `null` will be returned.
225 * If the full certificate chain was requested, each certificate will include an`issuerCertificate` property containing an object representing its issuer's
228 * @param detailed Include the full certificate chain if `true`, otherwise include just the peer's certificate.
229 * @return A certificate object.
231 getPeerCertificate(detailed: true): DetailedPeerCertificate;
232 getPeerCertificate(detailed?: false): PeerCertificate;
233 getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate;
235 * As the `Finished` messages are message digests of the complete handshake
236 * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can
237 * be used for external authentication procedures when the authentication
238 * provided by SSL/TLS is not desired or is not enough.
240 * Corresponds to the `SSL_get_peer_finished` routine in OpenSSL and may be used
241 * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929).
243 * @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
246 getPeerFinished(): Buffer | undefined;
248 * Returns a string containing the negotiated SSL/TLS protocol version of the
249 * current connection. The value `'unknown'` will be returned for connected
250 * sockets that have not completed the handshaking process. The value `null` will
251 * be returned for server sockets or disconnected client sockets.
253 * Protocol versions are:
261 * See the OpenSSL [`SSL_get_version`](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html) documentation for more information.
264 getProtocol(): string | null;
266 * Returns the TLS session data or `undefined` if no session was
267 * 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
270 * See `Session Resumption` for more information.
272 * Note: `getSession()` works only for TLSv1.2 and below. For TLSv1.3, applications
273 * must use the `'session'` event (it also works for TLSv1.2 and below).
276 getSession(): Buffer | undefined;
278 * See [SSL\_get\_shared\_sigalgs](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_shared_sigalgs.html) for more information.
280 * @return List of signature algorithms shared between the server and the client in the order of decreasing preference.
282 getSharedSigalgs(): string[];
284 * For a client, returns the TLS session ticket if one is available, or`undefined`. For a server, always returns `undefined`.
286 * It may be useful for debugging.
288 * See `Session Resumption` for more information.
291 getTLSTicket(): Buffer | undefined;
293 * See `Session Resumption` for more information.
295 * @return `true` if the session was reused, `false` otherwise.
297 isSessionReused(): boolean;
299 * The `tlsSocket.renegotiate()` method initiates a TLS renegotiation process.
300 * Upon completion, the `callback` function will be passed a single argument
301 * that is either an `Error` (if the request failed) or `null`.
303 * This method can be used to request a peer's certificate after the secure
304 * connection has been established.
306 * When running as the server, the socket will be destroyed with an error after`handshakeTimeout` timeout.
308 * For TLSv1.3, renegotiation cannot be initiated, it is not supported by the
311 * @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
312 * an error, unless the `tlsSocket` has been destroyed, in which case `callback` will not be called at all.
313 * @return `true` if renegotiation was initiated, `false` otherwise.
317 rejectUnauthorized?: boolean | undefined;
318 requestCert?: boolean | undefined;
320 callback: (err: Error | null) => void
321 ): undefined | boolean;
323 * The `tlsSocket.setMaxSendFragment()` method sets the maximum TLS fragment size.
324 * Returns `true` if setting the limit succeeded; `false` otherwise.
326 * Smaller fragment sizes decrease the buffering latency on the client: larger
327 * fragments are buffered by the TLS layer until the entire fragment is received
328 * and its integrity is verified; large fragments can span multiple roundtrips
329 * and their processing can be delayed due to packet loss or reordering. However,
330 * smaller fragments add extra TLS framing bytes and CPU overhead, which may
331 * decrease overall server throughput.
333 * @param [size=16384] The maximum TLS fragment size. The maximum value is `16384`.
335 setMaxSendFragment(size: number): boolean;
337 * Disables TLS renegotiation for this `TLSSocket` instance. Once called, attempts
338 * to renegotiate will trigger an `'error'` event on the `TLSSocket`.
341 disableRenegotiation(): void;
343 * When enabled, TLS packet trace information is written to `stderr`. This can be
344 * used to debug TLS connection problems.
346 * 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
347 * OpenSSL's `SSL_trace()` function, the format is undocumented, can change
348 * without notice, and should not be relied on.
353 * Returns the peer certificate as an `X509Certificate` object.
355 * If there is no peer certificate, or the socket has been destroyed,`undefined` will be returned.
358 getPeerX509Certificate(): X509Certificate | undefined;
360 * Returns the local certificate as an `X509Certificate` object.
362 * If there is no local certificate, or the socket has been destroyed,`undefined` will be returned.
365 getX509Certificate(): X509Certificate | undefined;
367 * Keying material is used for validations to prevent different kind of attacks in
368 * network protocols, for example in the specifications of IEEE 802.1X.
373 * const keyingMaterial = tlsSocket.exportKeyingMaterial(
375 * 'client finished');
378 * Example return value of keyingMaterial:
379 * <Buffer 76 26 af 99 c5 56 8e 42 09 91 ef 9f 93 cb ad 6c 7b 65 f8 53 f1 d8 d9
380 * 12 5a 33 b8 b5 25 df 7b 37 9f e0 e2 4f b8 67 83 a3 2f cd 5d 41 42 4c 91
381 * 74 ef 2c ... 78 more bytes>
385 * See the OpenSSL [`SSL_export_keying_material`](https://www.openssl.org/docs/man1.1.1/man3/SSL_export_keying_material.html) documentation for more
387 * @since v13.10.0, v12.17.0
388 * @param length number of bytes to retrieve from keying material
389 * @param label an application specific label, typically this will be a value from the [IANA Exporter Label
390 * Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels).
391 * @param context Optionally provide a context.
392 * @return requested bytes of the keying material
394 exportKeyingMaterial(length: number, label: string, context: Buffer): Buffer;
395 addListener(event: string, listener: (...args: any[]) => void): this;
396 addListener(event: 'OCSPResponse', listener: (response: Buffer) => void): this;
397 addListener(event: 'secureConnect', listener: () => void): this;
398 addListener(event: 'session', listener: (session: Buffer) => void): this;
399 addListener(event: 'keylog', listener: (line: Buffer) => void): this;
400 emit(event: string | symbol, ...args: any[]): boolean;
401 emit(event: 'OCSPResponse', response: Buffer): boolean;
402 emit(event: 'secureConnect'): boolean;
403 emit(event: 'session', session: Buffer): boolean;
404 emit(event: 'keylog', line: Buffer): boolean;
405 on(event: string, listener: (...args: any[]) => void): this;
406 on(event: 'OCSPResponse', listener: (response: Buffer) => void): this;
407 on(event: 'secureConnect', listener: () => void): this;
408 on(event: 'session', listener: (session: Buffer) => void): this;
409 on(event: 'keylog', listener: (line: Buffer) => void): this;
410 once(event: string, listener: (...args: any[]) => void): this;
411 once(event: 'OCSPResponse', listener: (response: Buffer) => void): this;
412 once(event: 'secureConnect', listener: () => void): this;
413 once(event: 'session', listener: (session: Buffer) => void): this;
414 once(event: 'keylog', listener: (line: Buffer) => void): this;
415 prependListener(event: string, listener: (...args: any[]) => void): this;
416 prependListener(event: 'OCSPResponse', listener: (response: Buffer) => void): this;
417 prependListener(event: 'secureConnect', listener: () => void): this;
418 prependListener(event: 'session', listener: (session: Buffer) => void): this;
419 prependListener(event: 'keylog', listener: (line: Buffer) => void): this;
420 prependOnceListener(event: string, listener: (...args: any[]) => void): this;
421 prependOnceListener(event: 'OCSPResponse', listener: (response: Buffer) => void): this;
422 prependOnceListener(event: 'secureConnect', listener: () => void): this;
423 prependOnceListener(event: 'session', listener: (session: Buffer) => void): this;
424 prependOnceListener(event: 'keylog', listener: (line: Buffer) => void): this;
426 interface CommonConnectionOptions {
428 * An optional TLS context object from tls.createSecureContext()
430 secureContext?: SecureContext | undefined;
432 * When enabled, TLS packet trace information is written to `stderr`. This can be
433 * used to debug TLS connection problems.
436 enableTrace?: boolean | undefined;
438 * If true the server will request a certificate from clients that
439 * connect and attempt to verify that certificate. Defaults to
442 requestCert?: boolean | undefined;
444 * An array of strings or a Buffer naming possible ALPN protocols.
445 * (Protocols should be ordered by their priority.)
447 ALPNProtocols?: string[] | Uint8Array[] | Uint8Array | undefined;
449 * SNICallback(servername, cb) <Function> A function that will be
450 * called if the client supports SNI TLS extension. Two arguments
451 * will be passed when called: servername and cb. SNICallback should
452 * invoke cb(null, ctx), where ctx is a SecureContext instance.
453 * (tls.createSecureContext(...) can be used to get a proper
454 * SecureContext.) If SNICallback wasn't provided the default callback
455 * with high-level API will be used (see below).
457 SNICallback?: ((servername: string, cb: (err: Error | null, ctx?: SecureContext) => void) => void) | undefined;
459 * If true the server will reject any connection which is not
460 * authorized with the list of supplied CAs. This option only has an
461 * effect if requestCert is true.
464 rejectUnauthorized?: boolean | undefined;
466 interface TlsOptions extends SecureContextOptions, CommonConnectionOptions, net.ServerOpts {
468 * Abort the connection if the SSL/TLS handshake does not finish in the
469 * specified number of milliseconds. A 'tlsClientError' is emitted on
470 * the tls.Server object whenever a handshake times out. Default:
471 * 120000 (120 seconds).
473 handshakeTimeout?: number | undefined;
475 * The number of seconds after which a TLS session created by the
476 * server will no longer be resumable. See Session Resumption for more
477 * information. Default: 300.
479 sessionTimeout?: number | undefined;
481 * 48-bytes of cryptographically strong pseudo-random data.
483 ticketKeys?: Buffer | undefined;
487 * @param identity identity parameter sent from the client.
488 * @return pre-shared key that must either be
489 * a buffer or `null` to stop the negotiation process. Returned PSK must be
490 * compatible with the selected cipher's digest.
492 * When negotiating TLS-PSK (pre-shared keys), this function is called
493 * with the identity provided by the client.
494 * If the return value is `null` the negotiation process will stop and an
495 * "unknown_psk_identity" alert message will be sent to the other party.
496 * If the server wishes to hide the fact that the PSK identity was not known,
497 * the callback must provide some random data as `psk` to make the connection
498 * fail with "decrypt_error" before negotiation is finished.
499 * PSK ciphers are disabled by default, and using TLS-PSK thus
500 * requires explicitly specifying a cipher suite with the `ciphers` option.
501 * More information can be found in the RFC 4279.
503 pskCallback?(socket: TLSSocket, identity: string): DataView | NodeJS.TypedArray | null;
505 * hint to send to a client to help
506 * with selecting the identity during TLS-PSK negotiation. Will be ignored
507 * in TLS 1.3. Upon failing to set pskIdentityHint `tlsClientError` will be
508 * emitted with `ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED` code.
510 pskIdentityHint?: string | undefined;
512 interface PSKCallbackNegotation {
513 psk: DataView | NodeJS.TypedArray;
516 interface ConnectionOptions extends SecureContextOptions, CommonConnectionOptions {
517 host?: string | undefined;
518 port?: number | undefined;
519 path?: string | undefined; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored.
520 socket?: stream.Duplex | undefined; // Establish secure connection on a given socket rather than creating a new socket
521 checkServerIdentity?: typeof checkServerIdentity | undefined;
522 servername?: string | undefined; // SNI TLS Extension
523 session?: Buffer | undefined;
524 minDHSize?: number | undefined;
525 lookup?: net.LookupFunction | undefined;
526 timeout?: number | undefined;
528 * When negotiating TLS-PSK (pre-shared keys), this function is called
529 * with optional identity `hint` provided by the server or `null`
530 * in case of TLS 1.3 where `hint` was removed.
531 * It will be necessary to provide a custom `tls.checkServerIdentity()`
532 * for the connection as the default one will try to check hostname/IP
533 * of the server against the certificate but that's not applicable for PSK
534 * because there won't be a certificate present.
535 * More information can be found in the RFC 4279.
537 * @param hint message sent from the server to help client
538 * decide which identity to use during negotiation.
539 * Always `null` if TLS 1.3 is used.
540 * @returns Return `null` to stop the negotiation process. `psk` must be
541 * compatible with the selected cipher's digest.
542 * `identity` must use UTF-8 encoding.
544 pskCallback?(hint: string | null): PSKCallbackNegotation | null;
547 * Accepts encrypted connections using TLS or SSL.
550 class Server extends net.Server {
551 constructor(secureConnectionListener?: (socket: TLSSocket) => void);
552 constructor(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void);
554 * The `server.addContext()` method adds a secure context that will be used if
555 * the client request's SNI name matches the supplied `hostname` (or wildcard).
557 * When there are multiple matching contexts, the most recently added one is
560 * @param hostname A SNI host name or wildcard (e.g. `'*'`)
561 * @param context An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc).
563 addContext(hostname: string, context: SecureContextOptions): void;
565 * Returns the session ticket keys.
567 * See `Session Resumption` for more information.
569 * @return A 48-byte buffer containing the session ticket keys.
571 getTicketKeys(): Buffer;
573 * The `server.setSecureContext()` method replaces the secure context of an
574 * existing server. Existing connections to the server are not interrupted.
576 * @param options An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc).
578 setSecureContext(options: SecureContextOptions): void;
580 * Sets the session ticket keys.
582 * Changes to the ticket keys are effective only for future server connections.
583 * Existing or currently pending server connections will use the previous keys.
585 * See `Session Resumption` for more information.
587 * @param keys A 48-byte buffer containing the session ticket keys.
589 setTicketKeys(keys: Buffer): void;
591 * events.EventEmitter
596 * 5. secureConnection
599 addListener(event: string, listener: (...args: any[]) => void): this;
600 addListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => void): this;
601 addListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this;
602 addListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this;
603 addListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this;
604 addListener(event: 'secureConnection', listener: (tlsSocket: TLSSocket) => void): this;
605 addListener(event: 'keylog', listener: (line: Buffer, tlsSocket: TLSSocket) => void): this;
606 emit(event: string | symbol, ...args: any[]): boolean;
607 emit(event: 'tlsClientError', err: Error, tlsSocket: TLSSocket): boolean;
608 emit(event: 'newSession', sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void): boolean;
609 emit(event: 'OCSPRequest', certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void): boolean;
610 emit(event: 'resumeSession', sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void): boolean;
611 emit(event: 'secureConnection', tlsSocket: TLSSocket): boolean;
612 emit(event: 'keylog', line: Buffer, tlsSocket: TLSSocket): boolean;
613 on(event: string, listener: (...args: any[]) => void): this;
614 on(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => void): this;
615 on(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this;
616 on(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this;
617 on(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this;
618 on(event: 'secureConnection', listener: (tlsSocket: TLSSocket) => void): this;
619 on(event: 'keylog', listener: (line: Buffer, tlsSocket: TLSSocket) => void): this;
620 once(event: string, listener: (...args: any[]) => void): this;
621 once(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => void): this;
622 once(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this;
623 once(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this;
624 once(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this;
625 once(event: 'secureConnection', listener: (tlsSocket: TLSSocket) => void): this;
626 once(event: 'keylog', listener: (line: Buffer, tlsSocket: TLSSocket) => void): this;
627 prependListener(event: string, listener: (...args: any[]) => void): this;
628 prependListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => void): this;
629 prependListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this;
630 prependListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this;
631 prependListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this;
632 prependListener(event: 'secureConnection', listener: (tlsSocket: TLSSocket) => void): this;
633 prependListener(event: 'keylog', listener: (line: Buffer, tlsSocket: TLSSocket) => void): this;
634 prependOnceListener(event: string, listener: (...args: any[]) => void): this;
635 prependOnceListener(event: 'tlsClientError', listener: (err: Error, tlsSocket: TLSSocket) => void): this;
636 prependOnceListener(event: 'newSession', listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this;
637 prependOnceListener(event: 'OCSPRequest', listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this;
638 prependOnceListener(event: 'resumeSession', listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this;
639 prependOnceListener(event: 'secureConnection', listener: (tlsSocket: TLSSocket) => void): this;
640 prependOnceListener(event: 'keylog', listener: (line: Buffer, tlsSocket: TLSSocket) => void): this;
643 * @deprecated since v0.11.3 Use `tls.TLSSocket` instead.
645 interface SecurePair {
646 encrypted: TLSSocket;
647 cleartext: TLSSocket;
649 type SecureVersion = 'TLSv1.3' | 'TLSv1.2' | 'TLSv1.1' | 'TLSv1';
650 interface SecureContextOptions {
652 * Optionally override the trusted CA certificates. Default is to trust
653 * the well-known CAs curated by Mozilla. Mozilla's CAs are completely
654 * replaced when CAs are explicitly specified using this option.
656 ca?: string | Buffer | Array<string | Buffer> | undefined;
658 * Cert chains in PEM format. One cert chain should be provided per
659 * private key. Each cert chain should consist of the PEM formatted
660 * certificate for a provided private key, followed by the PEM
661 * formatted intermediate certificates (if any), in order, and not
662 * including the root CA (the root CA must be pre-known to the peer,
663 * see ca). When providing multiple cert chains, they do not have to
664 * be in the same order as their private keys in key. If the
665 * intermediate certificates are not provided, the peer will not be
666 * able to validate the certificate, and the handshake will fail.
668 cert?: string | Buffer | Array<string | Buffer> | undefined;
670 * Colon-separated list of supported signature algorithms. The list
671 * can contain digest algorithms (SHA256, MD5 etc.), public key
672 * algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g
673 * 'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512).
675 sigalgs?: string | undefined;
677 * Cipher suite specification, replacing the default. For more
678 * information, see modifying the default cipher suite. Permitted
679 * ciphers can be obtained via tls.getCiphers(). Cipher names must be
680 * uppercased in order for OpenSSL to accept them.
682 ciphers?: string | undefined;
684 * Name of an OpenSSL engine which can provide the client certificate.
686 clientCertEngine?: string | undefined;
688 * PEM formatted CRLs (Certificate Revocation Lists).
690 crl?: string | Buffer | Array<string | Buffer> | undefined;
692 * Diffie Hellman parameters, required for Perfect Forward Secrecy. Use
693 * openssl dhparam to create the parameters. The key length must be
694 * greater than or equal to 1024 bits or else an error will be thrown.
695 * Although 1024 bits is permissible, use 2048 bits or larger for
696 * stronger security. If omitted or invalid, the parameters are
697 * silently discarded and DHE ciphers will not be available.
699 dhparam?: string | Buffer | undefined;
701 * A string describing a named curve or a colon separated list of curve
702 * NIDs or names, for example P-521:P-384:P-256, to use for ECDH key
703 * agreement. Set to auto to select the curve automatically. Use
704 * crypto.getCurves() to obtain a list of available curve names. On
705 * recent releases, openssl ecparam -list_curves will also display the
706 * name and description of each available elliptic curve. Default:
707 * tls.DEFAULT_ECDH_CURVE.
709 ecdhCurve?: string | undefined;
711 * Attempt to use the server's cipher suite preferences instead of the
712 * client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be
713 * set in secureOptions
715 honorCipherOrder?: boolean | undefined;
717 * Private keys in PEM format. PEM allows the option of private keys
718 * being encrypted. Encrypted keys will be decrypted with
719 * options.passphrase. Multiple keys using different algorithms can be
720 * provided either as an array of unencrypted key strings or buffers,
721 * or an array of objects in the form {pem: <string|buffer>[,
722 * passphrase: <string>]}. The object form can only occur in an array.
723 * object.passphrase is optional. Encrypted keys will be decrypted with
724 * object.passphrase if provided, or options.passphrase if it is not.
726 key?: string | Buffer | Array<string | Buffer | KeyObject> | undefined;
728 * Name of an OpenSSL engine to get private key from. Should be used
729 * together with privateKeyIdentifier.
731 privateKeyEngine?: string | undefined;
733 * Identifier of a private key managed by an OpenSSL engine. Should be
734 * used together with privateKeyEngine. Should not be set together with
735 * key, because both options define a private key in different ways.
737 privateKeyIdentifier?: string | undefined;
739 * Optionally set the maximum TLS version to allow. One
740 * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the
741 * `secureProtocol` option, use one or the other.
742 * **Default:** `'TLSv1.3'`, unless changed using CLI options. Using
743 * `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to
744 * `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used.
746 maxVersion?: SecureVersion | undefined;
748 * Optionally set the minimum TLS version to allow. One
749 * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the
750 * `secureProtocol` option, use one or the other. It is not recommended to use
751 * less than TLSv1.2, but it may be required for interoperability.
752 * **Default:** `'TLSv1.2'`, unless changed using CLI options. Using
753 * `--tls-v1.0` sets the default to `'TLSv1'`. Using `--tls-v1.1` sets the default to
754 * `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to
755 * 'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used.
757 minVersion?: SecureVersion | undefined;
759 * Shared passphrase used for a single private key and/or a PFX.
761 passphrase?: string | undefined;
763 * PFX or PKCS12 encoded private key and certificate chain. pfx is an
764 * alternative to providing key and cert individually. PFX is usually
765 * encrypted, if it is, passphrase will be used to decrypt it. Multiple
766 * PFX can be provided either as an array of unencrypted PFX buffers,
767 * or an array of objects in the form {buf: <string|buffer>[,
768 * passphrase: <string>]}. The object form can only occur in an array.
769 * object.passphrase is optional. Encrypted PFX will be decrypted with
770 * object.passphrase if provided, or options.passphrase if it is not.
772 pfx?: string | Buffer | Array<string | Buffer | PxfObject> | undefined;
774 * Optionally affect the OpenSSL protocol behavior, which is not
775 * usually necessary. This should be used carefully if at all! Value is
776 * a numeric bitmask of the SSL_OP_* options from OpenSSL Options
778 secureOptions?: number | undefined; // Value is a numeric bitmask of the `SSL_OP_*` options
780 * Legacy mechanism to select the TLS protocol version to use, it does
781 * not support independent control of the minimum and maximum version,
782 * and does not support limiting the protocol to TLSv1.3. Use
783 * minVersion and maxVersion instead. The possible values are listed as
784 * SSL_METHODS, use the function names as strings. For example, use
785 * 'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow
786 * any TLS protocol version up to TLSv1.3. It is not recommended to use
787 * TLS versions less than 1.2, but it may be required for
788 * interoperability. Default: none, see minVersion.
790 secureProtocol?: string | undefined;
792 * Opaque identifier used by servers to ensure session state is not
793 * shared between applications. Unused by clients.
795 sessionIdContext?: string | undefined;
797 * 48-bytes of cryptographically strong pseudo-random data.
798 * See Session Resumption for more information.
800 ticketKeys?: Buffer | undefined;
802 * The number of seconds after which a TLS session created by the
803 * server will no longer be resumable. See Session Resumption for more
804 * information. Default: 300.
806 sessionTimeout?: number | undefined;
808 interface SecureContext {
812 * Verifies the certificate `cert` is issued to `hostname`.
814 * Returns [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object, populating it with `reason`, `host`, and `cert` on
815 * failure. On success, returns [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type).
817 * This function is intended to be used in combination with the`checkServerIdentity` option that can be passed to {@link connect} and as
818 * such operates on a `certificate object`. For other purposes, consider using `x509.checkHost()` instead.
820 * This function can be overwritten by providing an alternative function as the`options.checkServerIdentity` option that is passed to `tls.connect()`. The
821 * overwriting function can call `tls.checkServerIdentity()` of course, to augment
822 * the checks done with additional verification.
824 * This function is only called if the certificate passed all other checks, such as
825 * being issued by trusted CA (`options.ca`).
827 * Earlier versions of Node.js incorrectly accepted certificates for a given`hostname` if a matching `uniformResourceIdentifier` subject alternative name
828 * 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
829 * a custom`options.checkServerIdentity` function that implements the desired behavior.
831 * @param hostname The host name or IP address to verify the certificate against.
832 * @param cert A `certificate object` representing the peer's certificate.
834 function checkServerIdentity(hostname: string, cert: PeerCertificate): Error | undefined;
836 * Creates a new {@link Server}. The `secureConnectionListener`, if provided, is
837 * automatically set as a listener for the `'secureConnection'` event.
839 * The `ticketKeys` options is automatically shared between `cluster` module
842 * The following illustrates a simple echo server:
845 * const tls = require('tls');
846 * const fs = require('fs');
849 * key: fs.readFileSync('server-key.pem'),
850 * cert: fs.readFileSync('server-cert.pem'),
852 * // This is necessary only if using client certificate authentication.
855 * // This is necessary only if the client uses a self-signed certificate.
856 * ca: [ fs.readFileSync('client-cert.pem') ]
859 * const server = tls.createServer(options, (socket) => {
860 * console.log('server connected',
861 * socket.authorized ? 'authorized' : 'unauthorized');
862 * socket.write('welcome!\n');
863 * socket.setEncoding('utf8');
864 * socket.pipe(socket);
866 * server.listen(8000, () => {
867 * console.log('server bound');
871 * The server can be tested by connecting to it using the example client from {@link connect}.
874 function createServer(secureConnectionListener?: (socket: TLSSocket) => void): Server;
875 function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server;
877 * The `callback` function, if specified, will be added as a listener for the `'secureConnect'` event.
879 * `tls.connect()` returns a {@link TLSSocket} object.
881 * Unlike the `https` API, `tls.connect()` does not enable the
882 * SNI (Server Name Indication) extension by default, which may cause some
883 * servers to return an incorrect certificate or reject the connection
884 * altogether. To enable SNI, set the `servername` option in addition
887 * The following illustrates a client for the echo server example from {@link createServer}:
890 * // Assumes an echo server that is listening on port 8000.
891 * const tls = require('tls');
892 * const fs = require('fs');
895 * // Necessary only if the server requires client certificate authentication.
896 * key: fs.readFileSync('client-key.pem'),
897 * cert: fs.readFileSync('client-cert.pem'),
899 * // Necessary only if the server uses a self-signed certificate.
900 * ca: [ fs.readFileSync('server-cert.pem') ],
902 * // Necessary only if the server's cert isn't for "localhost".
903 * checkServerIdentity: () => { return null; },
906 * const socket = tls.connect(8000, options, () => {
907 * console.log('client connected',
908 * socket.authorized ? 'authorized' : 'unauthorized');
909 * process.stdin.pipe(socket);
910 * process.stdin.resume();
912 * socket.setEncoding('utf8');
913 * socket.on('data', (data) => {
916 * socket.on('end', () => {
917 * console.log('server ends connection');
922 function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket;
923 function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket;
924 function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket;
926 * Creates a new secure pair object with two streams, one of which reads and writes
927 * the encrypted data and the other of which reads and writes the cleartext data.
928 * Generally, the encrypted stream is piped to/from an incoming encrypted data
929 * stream and the cleartext one is used as a replacement for the initial encrypted
932 * `tls.createSecurePair()` returns a `tls.SecurePair` object with `cleartext` and`encrypted` stream properties.
934 * Using `cleartext` has the same API as {@link TLSSocket}.
936 * The `tls.createSecurePair()` method is now deprecated in favor of`tls.TLSSocket()`. For example, the code:
939 * pair = tls.createSecurePair(// ... );
940 * pair.encrypted.pipe(socket);
941 * socket.pipe(pair.encrypted);
944 * can be replaced by:
947 * secureSocket = tls.TLSSocket(socket, options);
950 * where `secureSocket` has the same API as `pair.cleartext`.
952 * @deprecated Since v0.11.3 - Use {@link TLSSocket} instead.
953 * @param context A secure context object as returned by `tls.createSecureContext()`
954 * @param isServer `true` to specify that this TLS connection should be opened as a server.
955 * @param requestCert `true` to specify whether a server should request a certificate from a connecting client. Only applies when `isServer` is `true`.
956 * @param rejectUnauthorized If not `false` a server automatically reject clients with invalid certificates. Only applies when `isServer` is `true`.
958 function createSecurePair(context?: SecureContext, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair;
960 * {@link createServer} sets the default value of the `honorCipherOrder` option
961 * to `true`, other APIs that create secure contexts leave it unset.
963 * {@link createServer} uses a 128 bit truncated SHA1 hash value generated
964 * from `process.argv` as the default value of the `sessionIdContext` option, other
965 * APIs that create secure contexts have no default value.
967 * The `tls.createSecureContext()` method creates a `SecureContext` object. It is
968 * usable as an argument to several `tls` APIs, such as {@link createServer} and `server.addContext()`, but has no public methods.
970 * A key is _required_ for ciphers that use certificates. Either `key` or`pfx` can be used to provide it.
972 * If the `ca` option is not given, then Node.js will default to using [Mozilla's publicly trusted list of
973 * CAs](https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt).
976 function createSecureContext(options?: SecureContextOptions): SecureContext;
978 * Returns an array with the names of the supported TLS ciphers. The names are
979 * lower-case for historical reasons, but must be uppercased to be used in
980 * the `ciphers` option of {@link createSecureContext}.
982 * Not all supported ciphers are enabled by default. See `Modifying the default TLS cipher suite`.
984 * Cipher names that start with `'tls_'` are for TLSv1.3, all the others are for
988 * console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...]
992 function getCiphers(): string[];
994 * The default curve name to use for ECDH key agreement in a tls server.
995 * The default value is 'auto'. See tls.createSecureContext() for further
998 let DEFAULT_ECDH_CURVE: string;
1000 * The default value of the maxVersion option of
1001 * tls.createSecureContext(). It can be assigned any of the supported TLS
1002 * protocol versions, 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default:
1003 * 'TLSv1.3', unless changed using CLI options. Using --tls-max-v1.2 sets
1004 * the default to 'TLSv1.2'. Using --tls-max-v1.3 sets the default to
1005 * 'TLSv1.3'. If multiple of the options are provided, the highest maximum
1008 let DEFAULT_MAX_VERSION: SecureVersion;
1010 * The default value of the minVersion option of tls.createSecureContext().
1011 * It can be assigned any of the supported TLS protocol versions,
1012 * 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: 'TLSv1.2', unless
1013 * changed using CLI options. Using --tls-min-v1.0 sets the default to
1014 * 'TLSv1'. Using --tls-min-v1.1 sets the default to 'TLSv1.1'. Using
1015 * --tls-min-v1.3 sets the default to 'TLSv1.3'. If multiple of the options
1016 * are provided, the lowest minimum is used.
1018 let DEFAULT_MIN_VERSION: SecureVersion;
1020 * An immutable array of strings representing the root certificates (in PEM
1021 * format) used for verifying peer certificates. This is the default value
1022 * of the ca option to tls.createSecureContext().
1024 const rootCertificates: ReadonlyArray<string>;
1026 declare module 'node:tls' {
1027 export * from 'tls';