AK-21/Graphite-Industrial-Intelligence
0
1/**2 * The `node:tls` module provides an implementation of the Transport Layer Security3 * (TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL.4 * The module can be accessed using:5 *6 * ```js7 * import tls from 'node:tls';8 * ```9 * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/tls.js)10 */11declare module "tls" {12 import { NonSharedBuffer } from "node:buffer";13 import { X509Certificate } from "node:crypto";14 import * as net from "node:net";15 import * as stream from "stream";16 const CLIENT_RENEG_LIMIT: number;17 const CLIENT_RENEG_WINDOW: number;18 interface Certificate extends NodeJS.Dict<string | string[]> {19 /**20 * Country code.21 */22 C?: string | string[];23 /**24 * Street.25 */26 ST?: string | string[];27 /**28 * Locality.29 */30 L?: string | string[];31 /**32 * Organization.33 */34 O?: string | string[];35 /**36 * Organizational unit.37 */38 OU?: string | string[];39 /**40 * Common name.41 */42 CN?: string | string[];43 }44 interface PeerCertificate {45 /**46 * `true` if a Certificate Authority (CA), `false` otherwise.47 * @since v18.13.048 */49 ca: boolean;50 /**51 * The DER encoded X.509 certificate data.52 */53 raw: NonSharedBuffer;54 /**55 * The certificate subject.56 */57 subject: Certificate;58 /**59 * The certificate issuer, described in the same terms as the `subject`.60 */61 issuer: Certificate;62 /**63 * The date-time the certificate is valid from.64 */65 valid_from: string;66 /**67 * The date-time the certificate is valid to.68 */69 valid_to: string;70 /**71 * The certificate serial number, as a hex string.72 */73 serialNumber: string;74 /**75 * The SHA-1 digest of the DER encoded certificate.76 * It is returned as a `:` separated hexadecimal string.77 */78 fingerprint: string;79 /**80 * The SHA-256 digest of the DER encoded certificate.81 * It is returned as a `:` separated hexadecimal string.82 */83 fingerprint256: string;84 /**85 * The SHA-512 digest of the DER encoded certificate.86 * It is returned as a `:` separated hexadecimal string.87 */88 fingerprint512: string;89 /**90 * The extended key usage, a set of OIDs.91 */92 ext_key_usage?: string[];93 /**94 * A string containing concatenated names for the subject,95 * an alternative to the `subject` names.96 */97 subjectaltname?: string;98 /**99 * An array describing the AuthorityInfoAccess, used with OCSP.100 */101 infoAccess?: NodeJS.Dict<string[]>;102 /**103 * For RSA keys: The RSA bit size.104 *105 * For EC keys: The key size in bits.106 */107 bits?: number;108 /**109 * The RSA exponent, as a string in hexadecimal number notation.110 */111 exponent?: string;112 /**113 * The RSA modulus, as a hexadecimal string.114 */115 modulus?: string;116 /**117 * The public key.118 */119 pubkey?: NonSharedBuffer;120 /**121 * The ASN.1 name of the OID of the elliptic curve.122 * Well-known curves are identified by an OID.123 * While it is unusual, it is possible that the curve124 * is identified by its mathematical properties,125 * in which case it will not have an OID.126 */127 asn1Curve?: string;128 /**129 * The NIST name for the elliptic curve, if it has one130 * (not all well-known curves have been assigned names by NIST).131 */132 nistCurve?: string;133 }134 interface DetailedPeerCertificate extends PeerCertificate {135 /**136 * The issuer certificate object.137 * For self-signed certificates, this may be a circular reference.138 */139 issuerCertificate: DetailedPeerCertificate;140 }141 interface CipherNameAndProtocol {142 /**143 * The cipher name.144 */145 name: string;146 /**147 * SSL/TLS protocol version.148 */149 version: string;150 /**151 * IETF name for the cipher suite.152 */153 standardName: string;154 }155 interface EphemeralKeyInfo {156 /**157 * The supported types are 'DH' and 'ECDH'.158 */159 type: string;160 /**161 * The name property is available only when type is 'ECDH'.162 */163 name?: string | undefined;164 /**165 * The size of parameter of an ephemeral key exchange.166 */167 size: number;168 }169 interface KeyObject {170 /**171 * Private keys in PEM format.172 */173 pem: string | Buffer;174 /**175 * Optional passphrase.176 */177 passphrase?: string | undefined;178 }179 interface PxfObject {180 /**181 * PFX or PKCS12 encoded private key and certificate chain.182 */183 buf: string | Buffer;184 /**185 * Optional passphrase.186 */187 passphrase?: string | undefined;188 }189 interface TLSSocketOptions extends SecureContextOptions, CommonConnectionOptions {190 /**191 * If true the TLS socket will be instantiated in server-mode.192 * Defaults to false.193 */194 isServer?: boolean | undefined;195 /**196 * An optional net.Server instance.197 */198 server?: net.Server | undefined;199 /**200 * An optional Buffer instance containing a TLS session.201 */202 session?: Buffer | undefined;203 }204 /**205 * Performs transparent encryption of written data and all required TLS206 * negotiation.207 *208 * Instances of `tls.TLSSocket` implement the duplex `Stream` interface.209 *210 * Methods that return TLS connection metadata (e.g.{@link TLSSocket.getPeerCertificate}) will only return data while the211 * connection is open.212 * @since v0.11.4213 */214 class TLSSocket extends net.Socket {215 /**216 * Construct a new tls.TLSSocket object from an existing TCP socket.217 */218 constructor(socket: net.Socket | stream.Duplex, options?: TLSSocketOptions);219 /**220 * This property is `true` if the peer certificate was signed by one of the CAs221 * specified when creating the `tls.TLSSocket` instance, otherwise `false`.222 * @since v0.11.4223 */224 authorized: boolean;225 /**226 * Returns the reason why the peer's certificate was not been verified. This227 * property is set only when `tlsSocket.authorized === false`.228 * @since v0.11.4229 */230 authorizationError: Error;231 /**232 * Always returns `true`. This may be used to distinguish TLS sockets from regular`net.Socket` instances.233 * @since v0.11.4234 */235 encrypted: true;236 /**237 * String containing the selected ALPN protocol.238 * Before a handshake has completed, this value is always null.239 * When a handshake is completed but not ALPN protocol was selected, tlsSocket.alpnProtocol equals false.240 */241 alpnProtocol: string | false | null;242 /**243 * String containing the server name requested via SNI (Server Name Indication) TLS extension.244 */245 servername: string | false | null;246 /**247 * Returns an object representing the local certificate. The returned object has248 * some properties corresponding to the fields of the certificate.249 *250 * See {@link TLSSocket.getPeerCertificate} for an example of the certificate251 * structure.252 *253 * If there is no local certificate, an empty object will be returned. If the254 * socket has been destroyed, `null` will be returned.255 * @since v11.2.0256 */257 getCertificate(): PeerCertificate | object | null;258 /**259 * Returns an object containing information on the negotiated cipher suite.260 *261 * For example, a TLSv1.2 protocol with AES256-SHA cipher:262 *263 * ```json264 * {265 * "name": "AES256-SHA",266 * "standardName": "TLS_RSA_WITH_AES_256_CBC_SHA",267 * "version": "SSLv3"268 * }269 * ```270 *271 * See [SSL\_CIPHER\_get\_name](https://www.openssl.org/docs/man1.1.1/man3/SSL_CIPHER_get_name.html) for more information.272 * @since v0.11.4273 */274 getCipher(): CipherNameAndProtocol;275 /**276 * Returns an object representing the type, name, and size of parameter of277 * an ephemeral key exchange in `perfect forward secrecy` on a client278 * connection. It returns an empty object when the key exchange is not279 * ephemeral. As this is only supported on a client socket; `null` is returned280 * if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The `name` property is available only when type is `'ECDH'`.281 *282 * For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`.283 * @since v5.0.0284 */285 getEphemeralKeyInfo(): EphemeralKeyInfo | object | null;286 /**287 * As the `Finished` messages are message digests of the complete handshake288 * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can289 * be used for external authentication procedures when the authentication290 * provided by SSL/TLS is not desired or is not enough.291 *292 * Corresponds to the `SSL_get_finished` routine in OpenSSL and may be used293 * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929).294 * @since v9.9.0295 * @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.296 */297 getFinished(): NonSharedBuffer | undefined;298 /**299 * Returns an object representing the peer's certificate. If the peer does not300 * provide a certificate, an empty object will be returned. If the socket has been301 * destroyed, `null` will be returned.302 *303 * If the full certificate chain was requested, each certificate will include an`issuerCertificate` property containing an object representing its issuer's304 * certificate.305 * @since v0.11.4306 * @param detailed Include the full certificate chain if `true`, otherwise include just the peer's certificate.307 * @return A certificate object.308 */309 getPeerCertificate(detailed: true): DetailedPeerCertificate;310 getPeerCertificate(detailed?: false): PeerCertificate;311 getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate;312 /**313 * As the `Finished` messages are message digests of the complete handshake314 * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can315 * be used for external authentication procedures when the authentication316 * provided by SSL/TLS is not desired or is not enough.317 *318 * Corresponds to the `SSL_get_peer_finished` routine in OpenSSL and may be used319 * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929).320 * @since v9.9.0321 * @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 so322 * far.323 */324 getPeerFinished(): NonSharedBuffer | undefined;325 /**326 * Returns a string containing the negotiated SSL/TLS protocol version of the327 * current connection. The value `'unknown'` will be returned for connected328 * sockets that have not completed the handshaking process. The value `null` will329 * be returned for server sockets or disconnected client sockets.330 *331 * Protocol versions are:332 *333 * * `'SSLv3'`334 * * `'TLSv1'`335 * * `'TLSv1.1'`336 * * `'TLSv1.2'`337 * * `'TLSv1.3'`338 *339 * See the OpenSSL [`SSL_get_version`](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html) documentation for more information.340 * @since v5.7.0341 */342 getProtocol(): string | null;343 /**344 * Returns the TLS session data or `undefined` if no session was345 * 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 useful346 * for debugging.347 *348 * See `Session Resumption` for more information.349 *350 * Note: `getSession()` works only for TLSv1.2 and below. For TLSv1.3, applications351 * must use the `'session'` event (it also works for TLSv1.2 and below).352 * @since v0.11.4353 */354 getSession(): NonSharedBuffer | undefined;355 /**356 * See [SSL\_get\_shared\_sigalgs](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_shared_sigalgs.html) for more information.357 * @since v12.11.0358 * @return List of signature algorithms shared between the server and the client in the order of decreasing preference.359 */360 getSharedSigalgs(): string[];361 /**362 * For a client, returns the TLS session ticket if one is available, or`undefined`. For a server, always returns `undefined`.363 *364 * It may be useful for debugging.365 *366 * See `Session Resumption` for more information.367 * @since v0.11.4368 */369 getTLSTicket(): NonSharedBuffer | undefined;370 /**371 * See `Session Resumption` for more information.372 * @since v0.5.6373 * @return `true` if the session was reused, `false` otherwise.374 */375 isSessionReused(): boolean;376 /**377 * The `tlsSocket.renegotiate()` method initiates a TLS renegotiation process.378 * Upon completion, the `callback` function will be passed a single argument379 * that is either an `Error` (if the request failed) or `null`.380 *381 * This method can be used to request a peer's certificate after the secure382 * connection has been established.383 *384 * When running as the server, the socket will be destroyed with an error after `handshakeTimeout` timeout.385 *386 * For TLSv1.3, renegotiation cannot be initiated, it is not supported by the387 * protocol.388 * @since v0.11.8389 * @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 with390 * an error, unless the `tlsSocket` has been destroyed, in which case `callback` will not be called at all.391 * @return `true` if renegotiation was initiated, `false` otherwise.392 */393 renegotiate(394 options: {395 rejectUnauthorized?: boolean | undefined;396 requestCert?: boolean | undefined;397 },398 callback: (err: Error | null) => void,399 ): undefined | boolean;400 /**401 * The `tlsSocket.setKeyCert()` method sets the private key and certificate to use for the socket.402 * This is mainly useful if you wish to select a server certificate from a TLS server's `ALPNCallback`.403 * @since v22.5.0, v20.17.0404 * @param context An object containing at least `key` and `cert` properties from the {@link createSecureContext()} `options`,405 * or a TLS context object created with {@link createSecureContext()} itself.406 */407 setKeyCert(context: SecureContextOptions | SecureContext): void;408 /**409 * The `tlsSocket.setMaxSendFragment()` method sets the maximum TLS fragment size.410 * Returns `true` if setting the limit succeeded; `false` otherwise.411 *412 * Smaller fragment sizes decrease the buffering latency on the client: larger413 * fragments are buffered by the TLS layer until the entire fragment is received414 * and its integrity is verified; large fragments can span multiple roundtrips415 * and their processing can be delayed due to packet loss or reordering. However,416 * smaller fragments add extra TLS framing bytes and CPU overhead, which may417 * decrease overall server throughput.418 * @since v0.11.11419 * @param [size=16384] The maximum TLS fragment size. The maximum value is `16384`.420 */421 setMaxSendFragment(size: number): boolean;422 /**423 * Disables TLS renegotiation for this `TLSSocket` instance. Once called, attempts424 * to renegotiate will trigger an `'error'` event on the `TLSSocket`.425 * @since v8.4.0426 */427 disableRenegotiation(): void;428 /**429 * When enabled, TLS packet trace information is written to `stderr`. This can be430 * used to debug TLS connection problems.431 *432 * The format of the output is identical to the output of`openssl s_client -trace` or `openssl s_server -trace`. While it is produced by433 * OpenSSL's `SSL_trace()` function, the format is undocumented, can change434 * without notice, and should not be relied on.435 * @since v12.2.0436 */437 enableTrace(): void;438 /**439 * Returns the peer certificate as an `X509Certificate` object.440 *441 * If there is no peer certificate, or the socket has been destroyed,`undefined` will be returned.442 * @since v15.9.0443 */444 getPeerX509Certificate(): X509Certificate | undefined;445 /**446 * Returns the local certificate as an `X509Certificate` object.447 *448 * If there is no local certificate, or the socket has been destroyed,`undefined` will be returned.449 * @since v15.9.0450 */451 getX509Certificate(): X509Certificate | undefined;452 /**453 * Keying material is used for validations to prevent different kind of attacks in454 * network protocols, for example in the specifications of IEEE 802.1X.455 *456 * Example457 *458 * ```js459 * const keyingMaterial = tlsSocket.exportKeyingMaterial(460 * 128,461 * 'client finished');462 *463 * /*464 * Example return value of keyingMaterial:465 * <Buffer 76 26 af 99 c5 56 8e 42 09 91 ef 9f 93 cb ad 6c 7b 65 f8 53 f1 d8 d9466 * 12 5a 33 b8 b5 25 df 7b 37 9f e0 e2 4f b8 67 83 a3 2f cd 5d 41 42 4c 91467 * 74 ef 2c ... 78 more bytes>468 *469 * ```470 *471 * See the OpenSSL [`SSL_export_keying_material`](https://www.openssl.org/docs/man1.1.1/man3/SSL_export_keying_material.html) documentation for more472 * information.473 * @since v13.10.0, v12.17.0474 * @param length number of bytes to retrieve from keying material475 * @param label an application specific label, typically this will be a value from the [IANA Exporter Label476 * Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels).477 * @param context Optionally provide a context.478 * @return requested bytes of the keying material479 */480 exportKeyingMaterial(length: number, label: string, context: Buffer): NonSharedBuffer;481 addListener(event: string, listener: (...args: any[]) => void): this;482 addListener(event: "OCSPResponse", listener: (response: NonSharedBuffer) => void): this;483 addListener(event: "secure", listener: () => void): this;484 addListener(event: "secureConnect", listener: () => void): this;485 addListener(event: "session", listener: (session: NonSharedBuffer) => void): this;486 addListener(event: "keylog", listener: (line: NonSharedBuffer) => void): this;487 emit(event: string | symbol, ...args: any[]): boolean;488 emit(event: "OCSPResponse", response: NonSharedBuffer): boolean;489 emit(event: "secure"): boolean;490 emit(event: "secureConnect"): boolean;491 emit(event: "session", session: NonSharedBuffer): boolean;492 emit(event: "keylog", line: NonSharedBuffer): boolean;493 on(event: string, listener: (...args: any[]) => void): this;494 on(event: "OCSPResponse", listener: (response: NonSharedBuffer) => void): this;495 on(event: "secure", listener: () => void): this;496 on(event: "secureConnect", listener: () => void): this;497 on(event: "session", listener: (session: NonSharedBuffer) => void): this;498 on(event: "keylog", listener: (line: NonSharedBuffer) => void): this;499 once(event: string, listener: (...args: any[]) => void): this;500 once(event: "OCSPResponse", listener: (response: NonSharedBuffer) => void): this;501 once(event: "secure", listener: () => void): this;502 once(event: "secureConnect", listener: () => void): this;503 once(event: "session", listener: (session: NonSharedBuffer) => void): this;504 once(event: "keylog", listener: (line: NonSharedBuffer) => void): this;505 prependListener(event: string, listener: (...args: any[]) => void): this;506 prependListener(event: "OCSPResponse", listener: (response: NonSharedBuffer) => void): this;507 prependListener(event: "secure", listener: () => void): this;508 prependListener(event: "secureConnect", listener: () => void): this;509 prependListener(event: "session", listener: (session: NonSharedBuffer) => void): this;510 prependListener(event: "keylog", listener: (line: NonSharedBuffer) => void): this;511 prependOnceListener(event: string, listener: (...args: any[]) => void): this;512 prependOnceListener(event: "OCSPResponse", listener: (response: NonSharedBuffer) => void): this;513 prependOnceListener(event: "secure", listener: () => void): this;514 prependOnceListener(event: "secureConnect", listener: () => void): this;515 prependOnceListener(event: "session", listener: (session: NonSharedBuffer) => void): this;516 prependOnceListener(event: "keylog", listener: (line: NonSharedBuffer) => void): this;517 }518 interface CommonConnectionOptions {519 /**520 * An optional TLS context object from tls.createSecureContext()521 */522 secureContext?: SecureContext | undefined;523 /**524 * When enabled, TLS packet trace information is written to `stderr`. This can be525 * used to debug TLS connection problems.526 * @default false527 */528 enableTrace?: boolean | undefined;529 /**530 * If true the server will request a certificate from clients that531 * connect and attempt to verify that certificate. Defaults to532 * false.533 */534 requestCert?: boolean | undefined;535 /**536 * An array of strings or a Buffer naming possible ALPN protocols.537 * (Protocols should be ordered by their priority.)538 */539 ALPNProtocols?: readonly string[] | NodeJS.ArrayBufferView | undefined;540 /**541 * SNICallback(servername, cb) <Function> A function that will be542 * called if the client supports SNI TLS extension. Two arguments543 * will be passed when called: servername and cb. SNICallback should544 * invoke cb(null, ctx), where ctx is a SecureContext instance.545 * (tls.createSecureContext(...) can be used to get a proper546 * SecureContext.) If SNICallback wasn't provided the default callback547 * with high-level API will be used (see below).548 */549 SNICallback?: ((servername: string, cb: (err: Error | null, ctx?: SecureContext) => void) => void) | undefined;550 /**551 * If true the server will reject any connection which is not552 * authorized with the list of supplied CAs. This option only has an553 * effect if requestCert is true.554 * @default true555 */556 rejectUnauthorized?: boolean | undefined;557 /**558 * If true, specifies that the OCSP status request extension will be559 * added to the client hello and an 'OCSPResponse' event will be560 * emitted on the socket before establishing a secure communication.561 */562 requestOCSP?: boolean | undefined;563 }564 interface TlsOptions extends SecureContextOptions, CommonConnectionOptions, net.ServerOpts {565 /**566 * Abort the connection if the SSL/TLS handshake does not finish in the567 * specified number of milliseconds. A 'tlsClientError' is emitted on568 * the tls.Server object whenever a handshake times out. Default:569 * 120000 (120 seconds).570 */571 handshakeTimeout?: number | undefined;572 /**573 * The number of seconds after which a TLS session created by the574 * server will no longer be resumable. See Session Resumption for more575 * information. Default: 300.576 */577 sessionTimeout?: number | undefined;578 /**579 * 48-bytes of cryptographically strong pseudo-random data.580 */581 ticketKeys?: Buffer | undefined;582 /**583 * @param socket584 * @param identity identity parameter sent from the client.585 * @return pre-shared key that must either be586 * a buffer or `null` to stop the negotiation process. Returned PSK must be587 * compatible with the selected cipher's digest.588 *589 * When negotiating TLS-PSK (pre-shared keys), this function is called590 * with the identity provided by the client.591 * If the return value is `null` the negotiation process will stop and an592 * "unknown_psk_identity" alert message will be sent to the other party.593 * If the server wishes to hide the fact that the PSK identity was not known,594 * the callback must provide some random data as `psk` to make the connection595 * fail with "decrypt_error" before negotiation is finished.596 * PSK ciphers are disabled by default, and using TLS-PSK thus597 * requires explicitly specifying a cipher suite with the `ciphers` option.598 * More information can be found in the RFC 4279.599 */600 pskCallback?: ((socket: TLSSocket, identity: string) => NodeJS.ArrayBufferView | null) | undefined;601 /**602 * hint to send to a client to help603 * with selecting the identity during TLS-PSK negotiation. Will be ignored604 * in TLS 1.3. Upon failing to set pskIdentityHint `tlsClientError` will be605 * emitted with `ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED` code.606 */607 pskIdentityHint?: string | undefined;608 }609 interface PSKCallbackNegotation {610 psk: NodeJS.ArrayBufferView;611 identity: string;612 }613 interface ConnectionOptions extends SecureContextOptions, CommonConnectionOptions {614 host?: string | undefined;615 port?: number | undefined;616 path?: string | undefined; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored.617 socket?: stream.Duplex | undefined; // Establish secure connection on a given socket rather than creating a new socket618 checkServerIdentity?: typeof checkServerIdentity | undefined;619 servername?: string | undefined; // SNI TLS Extension620 session?: Buffer | undefined;621 minDHSize?: number | undefined;622 lookup?: net.LookupFunction | undefined;623 timeout?: number | undefined;624 /**625 * When negotiating TLS-PSK (pre-shared keys), this function is called626 * with optional identity `hint` provided by the server or `null`627 * in case of TLS 1.3 where `hint` was removed.628 * It will be necessary to provide a custom `tls.checkServerIdentity()`629 * for the connection as the default one will try to check hostname/IP630 * of the server against the certificate but that's not applicable for PSK631 * because there won't be a certificate present.632 * More information can be found in the RFC 4279.633 *634 * @param hint message sent from the server to help client635 * decide which identity to use during negotiation.636 * Always `null` if TLS 1.3 is used.637 * @returns Return `null` to stop the negotiation process. `psk` must be638 * compatible with the selected cipher's digest.639 * `identity` must use UTF-8 encoding.640 */641 pskCallback?: ((hint: string | null) => PSKCallbackNegotation | null) | undefined;642 }643 /**644 * Accepts encrypted connections using TLS or SSL.645 * @since v0.3.2646 */647 class Server extends net.Server {648 constructor(secureConnectionListener?: (socket: TLSSocket) => void);649 constructor(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void);650 /**651 * The `server.addContext()` method adds a secure context that will be used if652 * the client request's SNI name matches the supplied `hostname` (or wildcard).653 *654 * When there are multiple matching contexts, the most recently added one is655 * used.656 * @since v0.5.3657 * @param hostname A SNI host name or wildcard (e.g. `'*'`)658 * @param context An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc), or a TLS context object created659 * with {@link createSecureContext} itself.660 */661 addContext(hostname: string, context: SecureContextOptions | SecureContext): void;662 /**663 * Returns the session ticket keys.664 *665 * See `Session Resumption` for more information.666 * @since v3.0.0667 * @return A 48-byte buffer containing the session ticket keys.668 */669 getTicketKeys(): NonSharedBuffer;670 /**671 * The `server.setSecureContext()` method replaces the secure context of an672 * existing server. Existing connections to the server are not interrupted.673 * @since v11.0.0674 * @param options An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc).675 */676 setSecureContext(options: SecureContextOptions): void;677 /**678 * Sets the session ticket keys.679 *680 * Changes to the ticket keys are effective only for future server connections.681 * Existing or currently pending server connections will use the previous keys.682 *683 * See `Session Resumption` for more information.684 * @since v3.0.0685 * @param keys A 48-byte buffer containing the session ticket keys.686 */687 setTicketKeys(keys: Buffer): void;688 /**689 * events.EventEmitter690 * 1. tlsClientError691 * 2. newSession692 * 3. OCSPRequest693 * 4. resumeSession694 * 5. secureConnection695 * 6. keylog696 */697 addListener(event: string, listener: (...args: any[]) => void): this;698 addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this;699 addListener(700 event: "newSession",701 listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void,702 ): this;703 addListener(704 event: "OCSPRequest",705 listener: (706 certificate: NonSharedBuffer,707 issuer: NonSharedBuffer,708 callback: (err: Error | null, resp: Buffer | null) => void,709 ) => void,710 ): this;711 addListener(712 event: "resumeSession",713 listener: (714 sessionId: NonSharedBuffer,715 callback: (err: Error | null, sessionData: Buffer | null) => void,716 ) => void,717 ): this;718 addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this;719 addListener(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: TLSSocket) => void): this;720 emit(event: string | symbol, ...args: any[]): boolean;721 emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean;722 emit(723 event: "newSession",724 sessionId: NonSharedBuffer,725 sessionData: NonSharedBuffer,726 callback: () => void,727 ): boolean;728 emit(729 event: "OCSPRequest",730 certificate: NonSharedBuffer,731 issuer: NonSharedBuffer,732 callback: (err: Error | null, resp: Buffer | null) => void,733 ): boolean;734 emit(735 event: "resumeSession",736 sessionId: NonSharedBuffer,737 callback: (err: Error | null, sessionData: Buffer | null) => void,738 ): boolean;739 emit(event: "secureConnection", tlsSocket: TLSSocket): boolean;740 emit(event: "keylog", line: NonSharedBuffer, tlsSocket: TLSSocket): boolean;741 on(event: string, listener: (...args: any[]) => void): this;742 on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this;743 on(744 event: "newSession",745 listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void,746 ): this;747 on(748 event: "OCSPRequest",749 listener: (750 certificate: NonSharedBuffer,751 issuer: NonSharedBuffer,752 callback: (err: Error | null, resp: Buffer | null) => void,753 ) => void,754 ): this;755 on(756 event: "resumeSession",757 listener: (758 sessionId: NonSharedBuffer,759 callback: (err: Error | null, sessionData: Buffer | null) => void,760 ) => void,761 ): this;762 on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this;763 on(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: TLSSocket) => void): this;764 once(event: string, listener: (...args: any[]) => void): this;765 once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this;766 once(767 event: "newSession",768 listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void,769 ): this;770 once(771 event: "OCSPRequest",772 listener: (773 certificate: NonSharedBuffer,774 issuer: NonSharedBuffer,775 callback: (err: Error | null, resp: Buffer | null) => void,776 ) => void,777 ): this;778 once(779 event: "resumeSession",780 listener: (781 sessionId: NonSharedBuffer,782 callback: (err: Error | null, sessionData: Buffer | null) => void,783 ) => void,784 ): this;785 once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this;786 once(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: TLSSocket) => void): this;787 prependListener(event: string, listener: (...args: any[]) => void): this;788 prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this;789 prependListener(790 event: "newSession",791 listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void,792 ): this;793 prependListener(794 event: "OCSPRequest",795 listener: (796 certificate: NonSharedBuffer,797 issuer: NonSharedBuffer,798 callback: (err: Error | null, resp: Buffer | null) => void,799 ) => void,800 ): this;801 prependListener(802 event: "resumeSession",803 listener: (804 sessionId: NonSharedBuffer,805 callback: (err: Error | null, sessionData: Buffer | null) => void,806 ) => void,807 ): this;808 prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this;809 prependListener(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: TLSSocket) => void): this;810 prependOnceListener(event: string, listener: (...args: any[]) => void): this;811 prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this;812 prependOnceListener(813 event: "newSession",814 listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void,815 ): this;816 prependOnceListener(817 event: "OCSPRequest",818 listener: (819 certificate: NonSharedBuffer,820 issuer: NonSharedBuffer,821 callback: (err: Error | null, resp: Buffer | null) => void,822 ) => void,823 ): this;824 prependOnceListener(825 event: "resumeSession",826 listener: (827 sessionId: NonSharedBuffer,828 callback: (err: Error | null, sessionData: Buffer | null) => void,829 ) => void,830 ): this;831 prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this;832 prependOnceListener(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: TLSSocket) => void): this;833 }834 type SecureVersion = "TLSv1.3" | "TLSv1.2" | "TLSv1.1" | "TLSv1";835 interface SecureContextOptions {836 /**837 * If set, this will be called when a client opens a connection using the ALPN extension.838 * One argument will be passed to the callback: an object containing `servername` and `protocols` fields,839 * respectively containing the server name from the SNI extension (if any) and an array of840 * ALPN protocol name strings. The callback must return either one of the strings listed in `protocols`,841 * which will be returned to the client as the selected ALPN protocol, or `undefined`,842 * to reject the connection with a fatal alert. If a string is returned that does not match one of843 * the client's ALPN protocols, an error will be thrown.844 * This option cannot be used with the `ALPNProtocols` option, and setting both options will throw an error.845 */846 ALPNCallback?: ((arg: { servername: string; protocols: string[] }) => string | undefined) | undefined;847 /**848 * Treat intermediate (non-self-signed)849 * certificates in the trust CA certificate list as trusted.850 * @since v22.9.0, v20.18.0851 */852 allowPartialTrustChain?: boolean | undefined;853 /**854 * Optionally override the trusted CA certificates. Default is to trust855 * the well-known CAs curated by Mozilla. Mozilla's CAs are completely856 * replaced when CAs are explicitly specified using this option.857 */858 ca?: string | Buffer | Array<string | Buffer> | undefined;859 /**860 * Cert chains in PEM format. One cert chain should be provided per861 * private key. Each cert chain should consist of the PEM formatted862 * certificate for a provided private key, followed by the PEM863 * formatted intermediate certificates (if any), in order, and not864 * including the root CA (the root CA must be pre-known to the peer,865 * see ca). When providing multiple cert chains, they do not have to866 * be in the same order as their private keys in key. If the867 * intermediate certificates are not provided, the peer will not be868 * able to validate the certificate, and the handshake will fail.869 */870 cert?: string | Buffer | Array<string | Buffer> | undefined;871 /**872 * Colon-separated list of supported signature algorithms. The list873 * can contain digest algorithms (SHA256, MD5 etc.), public key874 * algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g875 * 'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512).876 */877 sigalgs?: string | undefined;878 /**879 * Cipher suite specification, replacing the default. For more880 * information, see modifying the default cipher suite. Permitted881 * ciphers can be obtained via tls.getCiphers(). Cipher names must be882 * uppercased in order for OpenSSL to accept them.883 */884 ciphers?: string | undefined;885 /**886 * Name of an OpenSSL engine which can provide the client certificate.887 * @deprecated888 */889 clientCertEngine?: string | undefined;890 /**891 * PEM formatted CRLs (Certificate Revocation Lists).892 */893 crl?: string | Buffer | Array<string | Buffer> | undefined;894 /**895 * `'auto'` or custom Diffie-Hellman parameters, required for non-ECDHE perfect forward secrecy.896 * If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available.897 * ECDHE-based perfect forward secrecy will still be available.898 */899 dhparam?: string | Buffer | undefined;900 /**901 * A string describing a named curve or a colon separated list of curve902 * NIDs or names, for example P-521:P-384:P-256, to use for ECDH key903 * agreement. Set to auto to select the curve automatically. Use904 * crypto.getCurves() to obtain a list of available curve names. On905 * recent releases, openssl ecparam -list_curves will also display the906 * name and description of each available elliptic curve. Default:907 * tls.DEFAULT_ECDH_CURVE.908 */909 ecdhCurve?: string | undefined;910 /**911 * Attempt to use the server's cipher suite preferences instead of the912 * client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be913 * set in secureOptions914 */915 honorCipherOrder?: boolean | undefined;916 /**917 * Private keys in PEM format. PEM allows the option of private keys918 * being encrypted. Encrypted keys will be decrypted with919 * options.passphrase. Multiple keys using different algorithms can be920 * provided either as an array of unencrypted key strings or buffers,921 * or an array of objects in the form {pem: <string|buffer>[,922 * passphrase: <string>]}. The object form can only occur in an array.923 * object.passphrase is optional. Encrypted keys will be decrypted with924 * object.passphrase if provided, or options.passphrase if it is not.925 */926 key?: string | Buffer | Array<string | Buffer | KeyObject> | undefined;927 /**928 * Name of an OpenSSL engine to get private key from. Should be used929 * together with privateKeyIdentifier.930 * @deprecated931 */932 privateKeyEngine?: string | undefined;933 /**934 * Identifier of a private key managed by an OpenSSL engine. Should be935 * used together with privateKeyEngine. Should not be set together with936 * key, because both options define a private key in different ways.937 * @deprecated938 */939 privateKeyIdentifier?: string | undefined;940 /**941 * Optionally set the maximum TLS version to allow. One942 * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the943 * `secureProtocol` option, use one or the other.944 * **Default:** `'TLSv1.3'`, unless changed using CLI options. Using945 * `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to946 * `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used.947 */948 maxVersion?: SecureVersion | undefined;949 /**950 * Optionally set the minimum TLS version to allow. One951 * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the952 * `secureProtocol` option, use one or the other. It is not recommended to use953 * less than TLSv1.2, but it may be required for interoperability.954 * **Default:** `'TLSv1.2'`, unless changed using CLI options. Using955 * `--tls-v1.0` sets the default to `'TLSv1'`. Using `--tls-v1.1` sets the default to956 * `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to957 * 'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used.958 */959 minVersion?: SecureVersion | undefined;960 /**961 * Shared passphrase used for a single private key and/or a PFX.962 */963 passphrase?: string | undefined;964 /**965 * PFX or PKCS12 encoded private key and certificate chain. pfx is an966 * alternative to providing key and cert individually. PFX is usually967 * encrypted, if it is, passphrase will be used to decrypt it. Multiple968 * PFX can be provided either as an array of unencrypted PFX buffers,969 * or an array of objects in the form {buf: <string|buffer>[,970 * passphrase: <string>]}. The object form can only occur in an array.971 * object.passphrase is optional. Encrypted PFX will be decrypted with972 * object.passphrase if provided, or options.passphrase if it is not.973 */974 pfx?: string | Buffer | Array<string | Buffer | PxfObject> | undefined;975 /**976 * Optionally affect the OpenSSL protocol behavior, which is not977 * usually necessary. This should be used carefully if at all! Value is978 * a numeric bitmask of the SSL_OP_* options from OpenSSL Options979 */980 secureOptions?: number | undefined; // Value is a numeric bitmask of the `SSL_OP_*` options981 /**982 * Legacy mechanism to select the TLS protocol version to use, it does983 * not support independent control of the minimum and maximum version,984 * and does not support limiting the protocol to TLSv1.3. Use985 * minVersion and maxVersion instead. The possible values are listed as986 * SSL_METHODS, use the function names as strings. For example, use987 * 'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow988 * any TLS protocol version up to TLSv1.3. It is not recommended to use989 * TLS versions less than 1.2, but it may be required for990 * interoperability. Default: none, see minVersion.991 */992 secureProtocol?: string | undefined;993 /**994 * Opaque identifier used by servers to ensure session state is not995 * shared between applications. Unused by clients.996 */997 sessionIdContext?: string | undefined;998 /**999 * 48-bytes of cryptographically strong pseudo-random data.1000 * See Session Resumption for more information.1001 */1002 ticketKeys?: Buffer | undefined;1003 /**1004 * The number of seconds after which a TLS session created by the1005 * server will no longer be resumable. See Session Resumption for more1006 * information. Default: 300.1007 */1008 sessionTimeout?: number | undefined;1009 }1010 interface SecureContext {1011 context: any;1012 }1013 /**1014 * Verifies the certificate `cert` is issued to `hostname`.1015 *1016 * Returns [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object, populating it with `reason`, `host`, and `cert` on1017 * failure. On success, returns [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type).1018 *1019 * This function is intended to be used in combination with the`checkServerIdentity` option that can be passed to {@link connect} and as1020 * such operates on a `certificate object`. For other purposes, consider using `x509.checkHost()` instead.1021 *1022 * This function can be overwritten by providing an alternative function as the `options.checkServerIdentity` option that is passed to `tls.connect()`. The1023 * overwriting function can call `tls.checkServerIdentity()` of course, to augment1024 * the checks done with additional verification.1025 *1026 * This function is only called if the certificate passed all other checks, such as1027 * being issued by trusted CA (`options.ca`).1028 *1029 * Earlier versions of Node.js incorrectly accepted certificates for a given`hostname` if a matching `uniformResourceIdentifier` subject alternative name1030 * 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 use1031 * a custom `options.checkServerIdentity` function that implements the desired behavior.1032 * @since v0.8.41033 * @param hostname The host name or IP address to verify the certificate against.1034 * @param cert A `certificate object` representing the peer's certificate.1035 */1036 function checkServerIdentity(hostname: string, cert: PeerCertificate): Error | undefined;1037 /**1038 * Creates a new {@link Server}. The `secureConnectionListener`, if provided, is1039 * automatically set as a listener for the `'secureConnection'` event.1040 *1041 * The `ticketKeys` options is automatically shared between `node:cluster` module1042 * workers.1043 *1044 * The following illustrates a simple echo server:1045 *1046 * ```js1047 * import tls from 'node:tls';1048 * import fs from 'node:fs';1049 *1050 * const options = {1051 * key: fs.readFileSync('server-key.pem'),1052 * cert: fs.readFileSync('server-cert.pem'),1053 *1054 * // This is necessary only if using client certificate authentication.1055 * requestCert: true,1056 *1057 * // This is necessary only if the client uses a self-signed certificate.1058 * ca: [ fs.readFileSync('client-cert.pem') ],1059 * };1060 *1061 * const server = tls.createServer(options, (socket) => {1062 * console.log('server connected',1063 * socket.authorized ? 'authorized' : 'unauthorized');1064 * socket.write('welcome!\n');1065 * socket.setEncoding('utf8');1066 * socket.pipe(socket);1067 * });1068 * server.listen(8000, () => {1069 * console.log('server bound');1070 * });1071 * ```1072 *1073 * The server can be tested by connecting to it using the example client from {@link connect}.1074 * @since v0.3.21075 */1076 function createServer(secureConnectionListener?: (socket: TLSSocket) => void): Server;1077 function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server;1078 /**1079 * The `callback` function, if specified, will be added as a listener for the `'secureConnect'` event.1080 *1081 * `tls.connect()` returns a {@link TLSSocket} object.1082 *1083 * Unlike the `https` API, `tls.connect()` does not enable the1084 * SNI (Server Name Indication) extension by default, which may cause some1085 * servers to return an incorrect certificate or reject the connection1086 * altogether. To enable SNI, set the `servername` option in addition1087 * to `host`.1088 *1089 * The following illustrates a client for the echo server example from {@link createServer}:1090 *1091 * ```js1092 * // Assumes an echo server that is listening on port 8000.1093 * import tls from 'node:tls';1094 * import fs from 'node:fs';1095 *1096 * const options = {1097 * // Necessary only if the server requires client certificate authentication.1098 * key: fs.readFileSync('client-key.pem'),1099 * cert: fs.readFileSync('client-cert.pem'),1100 *1101 * // Necessary only if the server uses a self-signed certificate.1102 * ca: [ fs.readFileSync('server-cert.pem') ],1103 *1104 * // Necessary only if the server's cert isn't for "localhost".1105 * checkServerIdentity: () => { return null; },1106 * };1107 *1108 * const socket = tls.connect(8000, options, () => {1109 * console.log('client connected',1110 * socket.authorized ? 'authorized' : 'unauthorized');1111 * process.stdin.pipe(socket);1112 * process.stdin.resume();1113 * });1114 * socket.setEncoding('utf8');1115 * socket.on('data', (data) => {1116 * console.log(data);1117 * });1118 * socket.on('end', () => {1119 * console.log('server ends connection');1120 * });1121 * ```1122 * @since v0.11.31123 */1124 function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket;1125 function connect(1126 port: number,1127 host?: string,1128 options?: ConnectionOptions,1129 secureConnectListener?: () => void,1130 ): TLSSocket;1131 function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket;1132 /**1133 * `{@link createServer}` sets the default value of the `honorCipherOrder` option1134 * to `true`, other APIs that create secure contexts leave it unset.1135 *1136 * `{@link createServer}` uses a 128 bit truncated SHA1 hash value generated1137 * from `process.argv` as the default value of the `sessionIdContext` option, other1138 * APIs that create secure contexts have no default value.1139 *1140 * The `tls.createSecureContext()` method creates a `SecureContext` object. It is1141 * usable as an argument to several `tls` APIs, such as `server.addContext()`,1142 * but has no public methods. The {@link Server} constructor and the {@link createServer} method do not support the `secureContext` option.1143 *1144 * A key is _required_ for ciphers that use certificates. Either `key` or `pfx` can be used to provide it.1145 *1146 * If the `ca` option is not given, then Node.js will default to using [Mozilla's publicly trusted list of1147 * CAs](https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt).1148 *1149 * Custom DHE parameters are discouraged in favor of the new `dhparam: 'auto' `option. When set to `'auto'`, well-known DHE parameters of sufficient strength1150 * will be selected automatically. Otherwise, if necessary, `openssl dhparam` can1151 * be used to create custom parameters. The key length must be greater than or1152 * equal to 1024 bits or else an error will be thrown. Although 1024 bits is1153 * permissible, use 2048 bits or larger for stronger security.1154 * @since v0.11.131155 */1156 function createSecureContext(options?: SecureContextOptions): SecureContext;1157 /**1158 * Returns an array containing the CA certificates from various sources, depending on `type`:1159 *1160 * * `"default"`: return the CA certificates that will be used by the Node.js TLS clients by default.1161 * * When `--use-bundled-ca` is enabled (default), or `--use-openssl-ca` is not enabled,1162 * this would include CA certificates from the bundled Mozilla CA store.1163 * * When `--use-system-ca` is enabled, this would also include certificates from the system's1164 * trusted store.1165 * * When `NODE_EXTRA_CA_CERTS` is used, this would also include certificates loaded from the specified1166 * file.1167 * * `"system"`: return the CA certificates that are loaded from the system's trusted store, according1168 * to rules set by `--use-system-ca`. This can be used to get the certificates from the system1169 * when `--use-system-ca` is not enabled.1170 * * `"bundled"`: return the CA certificates from the bundled Mozilla CA store. This would be the same1171 * as `tls.rootCertificates`.1172 * * `"extra"`: return the CA certificates loaded from `NODE_EXTRA_CA_CERTS`. It's an empty array if1173 * `NODE_EXTRA_CA_CERTS` is not set.1174 * @since v22.15.01175 * @param type The type of CA certificates that will be returned. Valid values1176 * are `"default"`, `"system"`, `"bundled"` and `"extra"`.1177 * **Default:** `"default"`.1178 * @returns An array of PEM-encoded certificates. The array may contain duplicates1179 * if the same certificate is repeatedly stored in multiple sources.1180 */1181 function getCACertificates(type?: "default" | "system" | "bundled" | "extra"): string[];1182 /**1183 * Returns an array with the names of the supported TLS ciphers. The names are1184 * lower-case for historical reasons, but must be uppercased to be used in1185 * the `ciphers` option of `{@link createSecureContext}`.1186 *1187 * Not all supported ciphers are enabled by default. See1188 * [Modifying the default TLS cipher suite](https://nodejs.org/docs/latest-v24.x/api/tls.html#modifying-the-default-tls-cipher-suite).1189 *1190 * Cipher names that start with `'tls_'` are for TLSv1.3, all the others are for1191 * TLSv1.2 and below.1192 *1193 * ```js1194 * console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...]1195 * ```1196 * @since v0.10.21197 */1198 function getCiphers(): string[];1199 /**1200 * Sets the default CA certificates used by Node.js TLS clients. If the provided