tls.d.ts (51678B)
1 /** 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: 5 * 6 * ```js 7 * import tls from 'node:tls'; 8 * ``` 9 * @see [source](https://github.com/nodejs/node/blob/v16.9.0/lib/tls.js) 10 */ 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 { 18 /** 19 * Country code. 20 */ 21 C: string; 22 /** 23 * Street. 24 */ 25 ST: string; 26 /** 27 * Locality. 28 */ 29 L: string; 30 /** 31 * Organization. 32 */ 33 O: string; 34 /** 35 * Organizational unit. 36 */ 37 OU: string; 38 /** 39 * Common name. 40 */ 41 CN: string; 42 } 43 interface PeerCertificate { 44 subject: Certificate; 45 issuer: Certificate; 46 subjectaltname: string; 47 infoAccess: NodeJS.Dict<string[]>; 48 modulus: string; 49 exponent: string; 50 valid_from: string; 51 valid_to: string; 52 fingerprint: string; 53 fingerprint256: string; 54 ext_key_usage: string[]; 55 serialNumber: string; 56 raw: Buffer; 57 } 58 interface DetailedPeerCertificate extends PeerCertificate { 59 issuerCertificate: DetailedPeerCertificate; 60 } 61 interface CipherNameAndProtocol { 62 /** 63 * The cipher name. 64 */ 65 name: string; 66 /** 67 * SSL/TLS protocol version. 68 */ 69 version: string; 70 /** 71 * IETF name for the cipher suite. 72 */ 73 standardName: string; 74 } 75 interface EphemeralKeyInfo { 76 /** 77 * The supported types are 'DH' and 'ECDH'. 78 */ 79 type: string; 80 /** 81 * The name property is available only when type is 'ECDH'. 82 */ 83 name?: string | undefined; 84 /** 85 * The size of parameter of an ephemeral key exchange. 86 */ 87 size: number; 88 } 89 interface KeyObject { 90 /** 91 * Private keys in PEM format. 92 */ 93 pem: string | Buffer; 94 /** 95 * Optional passphrase. 96 */ 97 passphrase?: string | undefined; 98 } 99 interface PxfObject { 100 /** 101 * PFX or PKCS12 encoded private key and certificate chain. 102 */ 103 buf: string | Buffer; 104 /** 105 * Optional passphrase. 106 */ 107 passphrase?: string | undefined; 108 } 109 interface TLSSocketOptions extends SecureContextOptions, CommonConnectionOptions { 110 /** 111 * If true the TLS socket will be instantiated in server-mode. 112 * Defaults to false. 113 */ 114 isServer?: boolean | undefined; 115 /** 116 * An optional net.Server instance. 117 */ 118 server?: net.Server | undefined; 119 /** 120 * An optional Buffer instance containing a TLS session. 121 */ 122 session?: Buffer | undefined; 123 /** 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 127 */ 128 requestOCSP?: boolean | undefined; 129 } 130 /** 131 * Performs transparent encryption of written data and all required TLS 132 * negotiation. 133 * 134 * Instances of `tls.TLSSocket` implement the duplex `Stream` interface. 135 * 136 * Methods that return TLS connection metadata (e.g.{@link TLSSocket.getPeerCertificate} will only return data while the 137 * connection is open. 138 * @since v0.11.4 139 */ 140 class TLSSocket extends net.Socket { 141 /** 142 * Construct a new tls.TLSSocket object from an existing TCP socket. 143 */ 144 constructor(socket: net.Socket | stream.Duplex, options?: TLSSocketOptions); 145 /** 146 * Returns `true` if the peer certificate was signed by one of the CAs specified 147 * when creating the `tls.TLSSocket` instance, otherwise `false`. 148 * @since v0.11.4 149 */ 150 authorized: boolean; 151 /** 152 * Returns the reason why the peer's certificate was not been verified. This 153 * property is set only when `tlsSocket.authorized === false`. 154 * @since v0.11.4 155 */ 156 authorizationError: Error; 157 /** 158 * Always returns `true`. This may be used to distinguish TLS sockets from regular`net.Socket` instances. 159 * @since v0.11.4 160 */ 161 encrypted: true; 162 /** 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. 166 */ 167 alpnProtocol: string | false | null; 168 /** 169 * Returns an object representing the local certificate. The returned object has 170 * some properties corresponding to the fields of the certificate. 171 * 172 * See {@link TLSSocket.getPeerCertificate} for an example of the certificate 173 * structure. 174 * 175 * If there is no local certificate, an empty object will be returned. If the 176 * socket has been destroyed, `null` will be returned. 177 * @since v11.2.0 178 */ 179 getCertificate(): PeerCertificate | object | null; 180 /** 181 * Returns an object containing information on the negotiated cipher suite. 182 * 183 * For example: 184 * 185 * ```json 186 * { 187 * "name": "AES128-SHA256", 188 * "standardName": "TLS_RSA_WITH_AES_128_CBC_SHA256", 189 * "version": "TLSv1.2" 190 * } 191 * ``` 192 * 193 * See [SSL\_CIPHER\_get\_name](https://www.openssl.org/docs/man1.1.1/man3/SSL_CIPHER_get_name.html) for more information. 194 * @since v0.11.4 195 */ 196 getCipher(): CipherNameAndProtocol; 197 /** 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'`. 203 * 204 * For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`. 205 * @since v5.0.0 206 */ 207 getEphemeralKeyInfo(): EphemeralKeyInfo | object | null; 208 /** 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. 213 * 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). 216 * @since v9.9.0 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. 218 */ 219 getFinished(): Buffer | undefined; 220 /** 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. 224 * 225 * If the full certificate chain was requested, each certificate will include an`issuerCertificate` property containing an object representing its issuer's 226 * certificate. 227 * @since v0.11.4 228 * @param detailed Include the full certificate chain if `true`, otherwise include just the peer's certificate. 229 * @return A certificate object. 230 */ 231 getPeerCertificate(detailed: true): DetailedPeerCertificate; 232 getPeerCertificate(detailed?: false): PeerCertificate; 233 getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; 234 /** 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. 239 * 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). 242 * @since v9.9.0 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 244 * far. 245 */ 246 getPeerFinished(): Buffer | undefined; 247 /** 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. 252 * 253 * Protocol versions are: 254 * 255 * * `'SSLv3'` 256 * * `'TLSv1'` 257 * * `'TLSv1.1'` 258 * * `'TLSv1.2'` 259 * * `'TLSv1.3'` 260 * 261 * See the OpenSSL [`SSL_get_version`](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html) documentation for more information. 262 * @since v5.7.0 263 */ 264 getProtocol(): string | null; 265 /** 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 268 * for debugging. 269 * 270 * See `Session Resumption` for more information. 271 * 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). 274 * @since v0.11.4 275 */ 276 getSession(): Buffer | undefined; 277 /** 278 * See [SSL\_get\_shared\_sigalgs](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_shared_sigalgs.html) for more information. 279 * @since v12.11.0 280 * @return List of signature algorithms shared between the server and the client in the order of decreasing preference. 281 */ 282 getSharedSigalgs(): string[]; 283 /** 284 * For a client, returns the TLS session ticket if one is available, or`undefined`. For a server, always returns `undefined`. 285 * 286 * It may be useful for debugging. 287 * 288 * See `Session Resumption` for more information. 289 * @since v0.11.4 290 */ 291 getTLSTicket(): Buffer | undefined; 292 /** 293 * See `Session Resumption` for more information. 294 * @since v0.5.6 295 * @return `true` if the session was reused, `false` otherwise. 296 */ 297 isSessionReused(): boolean; 298 /** 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`. 302 * 303 * This method can be used to request a peer's certificate after the secure 304 * connection has been established. 305 * 306 * When running as the server, the socket will be destroyed with an error after`handshakeTimeout` timeout. 307 * 308 * For TLSv1.3, renegotiation cannot be initiated, it is not supported by the 309 * protocol. 310 * @since v0.11.8 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. 314 */ 315 renegotiate( 316 options: { 317 rejectUnauthorized?: boolean | undefined; 318 requestCert?: boolean | undefined; 319 }, 320 callback: (err: Error | null) => void, 321 ): undefined | boolean; 322 /** 323 * The `tlsSocket.setMaxSendFragment()` method sets the maximum TLS fragment size. 324 * Returns `true` if setting the limit succeeded; `false` otherwise. 325 * 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. 332 * @since v0.11.11 333 * @param [size=16384] The maximum TLS fragment size. The maximum value is `16384`. 334 */ 335 setMaxSendFragment(size: number): boolean; 336 /** 337 * Disables TLS renegotiation for this `TLSSocket` instance. Once called, attempts 338 * to renegotiate will trigger an `'error'` event on the `TLSSocket`. 339 * @since v8.4.0 340 */ 341 disableRenegotiation(): void; 342 /** 343 * When enabled, TLS packet trace information is written to `stderr`. This can be 344 * used to debug TLS connection problems. 345 * 346 * Note: The format of the output is identical to the output of `openssl s_client -trace` or `openssl s_server -trace`. While it is produced by OpenSSL's`SSL_trace()` function, the format is 347 * undocumented, can change without notice, 348 * and should not be relied on. 349 * @since v12.2.0 350 */ 351 enableTrace(): void; 352 /** 353 * Returns the peer certificate as an `X509Certificate` object. 354 * 355 * If there is no peer certificate, or the socket has been destroyed,`undefined` will be returned. 356 * @since v15.9.0 357 */ 358 getPeerX509Certificate(): X509Certificate | undefined; 359 /** 360 * Returns the local certificate as an `X509Certificate` object. 361 * 362 * If there is no local certificate, or the socket has been destroyed,`undefined` will be returned. 363 * @since v15.9.0 364 */ 365 getX509Certificate(): X509Certificate | undefined; 366 /** 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. 369 * 370 * Example 371 * 372 * ```js 373 * const keyingMaterial = tlsSocket.exportKeyingMaterial( 374 * 128, 375 * 'client finished'); 376 * 377 * Example return value of keyingMaterial: 378 * <Buffer 76 26 af 99 c5 56 8e 42 09 91 ef 9f 93 cb ad 6c 7b 65 f8 53 f1 d8 d9 379 * 12 5a 33 b8 b5 25 df 7b 37 9f e0 e2 4f b8 67 83 a3 2f cd 5d 41 42 4c 91 380 * 74 ef 2c ... 78 more bytes> 381 * 382 * ``` 383 * 384 * See the OpenSSL [`SSL_export_keying_material`](https://www.openssl.org/docs/man1.1.1/man3/SSL_export_keying_material.html) documentation for more 385 * information. 386 * @since v13.10.0, v12.17.0 387 * @param length number of bytes to retrieve from keying material 388 * @param label an application specific label, typically this will be a value from the [IANA Exporter Label 389 * Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels). 390 * @param context Optionally provide a context. 391 * @return requested bytes of the keying material 392 */ 393 exportKeyingMaterial(length: number, label: string, context: Buffer): Buffer; 394 addListener(event: string, listener: (...args: any[]) => void): this; 395 addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; 396 addListener(event: "secureConnect", listener: () => void): this; 397 addListener(event: "session", listener: (session: Buffer) => void): this; 398 addListener(event: "keylog", listener: (line: Buffer) => void): this; 399 emit(event: string | symbol, ...args: any[]): boolean; 400 emit(event: "OCSPResponse", response: Buffer): boolean; 401 emit(event: "secureConnect"): boolean; 402 emit(event: "session", session: Buffer): boolean; 403 emit(event: "keylog", line: Buffer): boolean; 404 on(event: string, listener: (...args: any[]) => void): this; 405 on(event: "OCSPResponse", listener: (response: Buffer) => void): this; 406 on(event: "secureConnect", listener: () => void): this; 407 on(event: "session", listener: (session: Buffer) => void): this; 408 on(event: "keylog", listener: (line: Buffer) => void): this; 409 once(event: string, listener: (...args: any[]) => void): this; 410 once(event: "OCSPResponse", listener: (response: Buffer) => void): this; 411 once(event: "secureConnect", listener: () => void): this; 412 once(event: "session", listener: (session: Buffer) => void): this; 413 once(event: "keylog", listener: (line: Buffer) => void): this; 414 prependListener(event: string, listener: (...args: any[]) => void): this; 415 prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; 416 prependListener(event: "secureConnect", listener: () => void): this; 417 prependListener(event: "session", listener: (session: Buffer) => void): this; 418 prependListener(event: "keylog", listener: (line: Buffer) => void): this; 419 prependOnceListener(event: string, listener: (...args: any[]) => void): this; 420 prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; 421 prependOnceListener(event: "secureConnect", listener: () => void): this; 422 prependOnceListener(event: "session", listener: (session: Buffer) => void): this; 423 prependOnceListener(event: "keylog", listener: (line: Buffer) => void): this; 424 } 425 interface CommonConnectionOptions { 426 /** 427 * An optional TLS context object from tls.createSecureContext() 428 */ 429 secureContext?: SecureContext | undefined; 430 /** 431 * When enabled, TLS packet trace information is written to `stderr`. This can be 432 * used to debug TLS connection problems. 433 * @default false 434 */ 435 enableTrace?: boolean | undefined; 436 /** 437 * If true the server will request a certificate from clients that 438 * connect and attempt to verify that certificate. Defaults to 439 * false. 440 */ 441 requestCert?: boolean | undefined; 442 /** 443 * An array of strings or a Buffer naming possible ALPN protocols. 444 * (Protocols should be ordered by their priority.) 445 */ 446 ALPNProtocols?: string[] | Uint8Array[] | Uint8Array | undefined; 447 /** 448 * SNICallback(servername, cb) <Function> A function that will be 449 * called if the client supports SNI TLS extension. Two arguments 450 * will be passed when called: servername and cb. SNICallback should 451 * invoke cb(null, ctx), where ctx is a SecureContext instance. 452 * (tls.createSecureContext(...) can be used to get a proper 453 * SecureContext.) If SNICallback wasn't provided the default callback 454 * with high-level API will be used (see below). 455 */ 456 SNICallback?: ((servername: string, cb: (err: Error | null, ctx?: SecureContext) => void) => void) | undefined; 457 /** 458 * If true the server will reject any connection which is not 459 * authorized with the list of supplied CAs. This option only has an 460 * effect if requestCert is true. 461 * @default true 462 */ 463 rejectUnauthorized?: boolean | undefined; 464 } 465 interface TlsOptions extends SecureContextOptions, CommonConnectionOptions, net.ServerOpts { 466 /** 467 * Abort the connection if the SSL/TLS handshake does not finish in the 468 * specified number of milliseconds. A 'tlsClientError' is emitted on 469 * the tls.Server object whenever a handshake times out. Default: 470 * 120000 (120 seconds). 471 */ 472 handshakeTimeout?: number | undefined; 473 /** 474 * The number of seconds after which a TLS session created by the 475 * server will no longer be resumable. See Session Resumption for more 476 * information. Default: 300. 477 */ 478 sessionTimeout?: number | undefined; 479 /** 480 * 48-bytes of cryptographically strong pseudo-random data. 481 */ 482 ticketKeys?: Buffer | undefined; 483 /** 484 * @param socket 485 * @param identity identity parameter sent from the client. 486 * @return pre-shared key that must either be 487 * a buffer or `null` to stop the negotiation process. Returned PSK must be 488 * compatible with the selected cipher's digest. 489 * 490 * When negotiating TLS-PSK (pre-shared keys), this function is called 491 * with the identity provided by the client. 492 * If the return value is `null` the negotiation process will stop and an 493 * "unknown_psk_identity" alert message will be sent to the other party. 494 * If the server wishes to hide the fact that the PSK identity was not known, 495 * the callback must provide some random data as `psk` to make the connection 496 * fail with "decrypt_error" before negotiation is finished. 497 * PSK ciphers are disabled by default, and using TLS-PSK thus 498 * requires explicitly specifying a cipher suite with the `ciphers` option. 499 * More information can be found in the RFC 4279. 500 */ 501 pskCallback?(socket: TLSSocket, identity: string): DataView | NodeJS.TypedArray | null; 502 /** 503 * hint to send to a client to help 504 * with selecting the identity during TLS-PSK negotiation. Will be ignored 505 * in TLS 1.3. Upon failing to set pskIdentityHint `tlsClientError` will be 506 * emitted with `ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED` code. 507 */ 508 pskIdentityHint?: string | undefined; 509 } 510 interface PSKCallbackNegotation { 511 psk: DataView | NodeJS.TypedArray; 512 identity: string; 513 } 514 interface ConnectionOptions extends SecureContextOptions, CommonConnectionOptions { 515 host?: string | undefined; 516 port?: number | undefined; 517 path?: string | undefined; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. 518 socket?: net.Socket | undefined; // Establish secure connection on a given socket rather than creating a new socket 519 checkServerIdentity?: typeof checkServerIdentity | undefined; 520 servername?: string | undefined; // SNI TLS Extension 521 session?: Buffer | undefined; 522 minDHSize?: number | undefined; 523 lookup?: net.LookupFunction | undefined; 524 timeout?: number | undefined; 525 /** 526 * When negotiating TLS-PSK (pre-shared keys), this function is called 527 * with optional identity `hint` provided by the server or `null` 528 * in case of TLS 1.3 where `hint` was removed. 529 * It will be necessary to provide a custom `tls.checkServerIdentity()` 530 * for the connection as the default one will try to check hostname/IP 531 * of the server against the certificate but that's not applicable for PSK 532 * because there won't be a certificate present. 533 * More information can be found in the RFC 4279. 534 * 535 * @param hint message sent from the server to help client 536 * decide which identity to use during negotiation. 537 * Always `null` if TLS 1.3 is used. 538 * @returns Return `null` to stop the negotiation process. `psk` must be 539 * compatible with the selected cipher's digest. 540 * `identity` must use UTF-8 encoding. 541 */ 542 pskCallback?(hint: string | null): PSKCallbackNegotation | null; 543 } 544 /** 545 * Accepts encrypted connections using TLS or SSL. 546 * @since v0.3.2 547 */ 548 class Server extends net.Server { 549 constructor(secureConnectionListener?: (socket: TLSSocket) => void); 550 constructor(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void); 551 /** 552 * The `server.addContext()` method adds a secure context that will be used if 553 * the client request's SNI name matches the supplied `hostname` (or wildcard). 554 * 555 * When there are multiple matching contexts, the most recently added one is 556 * used. 557 * @since v0.5.3 558 * @param hostname A SNI host name or wildcard (e.g. `'*'`) 559 * @param context An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc). 560 */ 561 addContext(hostname: string, context: SecureContextOptions): void; 562 /** 563 * Returns the session ticket keys. 564 * 565 * See `Session Resumption` for more information. 566 * @since v3.0.0 567 * @return A 48-byte buffer containing the session ticket keys. 568 */ 569 getTicketKeys(): Buffer; 570 /** 571 * The `server.setSecureContext()` method replaces the secure context of an 572 * existing server. Existing connections to the server are not interrupted. 573 * @since v11.0.0 574 * @param options An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc). 575 */ 576 setSecureContext(options: SecureContextOptions): void; 577 /** 578 * Sets the session ticket keys. 579 * 580 * Changes to the ticket keys are effective only for future server connections. 581 * Existing or currently pending server connections will use the previous keys. 582 * 583 * See `Session Resumption` for more information. 584 * @since v3.0.0 585 * @param keys A 48-byte buffer containing the session ticket keys. 586 */ 587 setTicketKeys(keys: Buffer): void; 588 /** 589 * events.EventEmitter 590 * 1. tlsClientError 591 * 2. newSession 592 * 3. OCSPRequest 593 * 4. resumeSession 594 * 5. secureConnection 595 * 6. keylog 596 */ 597 addListener(event: string, listener: (...args: any[]) => void): this; 598 addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; 599 addListener( 600 event: "newSession", 601 listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, 602 ): this; 603 addListener( 604 event: "OCSPRequest", 605 listener: ( 606 certificate: Buffer, 607 issuer: Buffer, 608 callback: (err: Error | null, resp: Buffer) => void, 609 ) => void, 610 ): this; 611 addListener( 612 event: "resumeSession", 613 listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, 614 ): this; 615 addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; 616 addListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; 617 emit(event: string | symbol, ...args: any[]): boolean; 618 emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; 619 emit(event: "newSession", sessionId: Buffer, sessionData: Buffer, callback: () => void): boolean; 620 emit( 621 event: "OCSPRequest", 622 certificate: Buffer, 623 issuer: Buffer, 624 callback: (err: Error | null, resp: Buffer) => void, 625 ): boolean; 626 emit( 627 event: "resumeSession", 628 sessionId: Buffer, 629 callback: (err: Error | null, sessionData: Buffer | null) => void, 630 ): boolean; 631 emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; 632 emit(event: "keylog", line: Buffer, tlsSocket: TLSSocket): boolean; 633 on(event: string, listener: (...args: any[]) => void): this; 634 on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; 635 on(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void): this; 636 on( 637 event: "OCSPRequest", 638 listener: ( 639 certificate: Buffer, 640 issuer: Buffer, 641 callback: (err: Error | null, resp: Buffer) => void, 642 ) => void, 643 ): this; 644 on( 645 event: "resumeSession", 646 listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, 647 ): this; 648 on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; 649 on(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; 650 once(event: string, listener: (...args: any[]) => void): this; 651 once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; 652 once( 653 event: "newSession", 654 listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, 655 ): this; 656 once( 657 event: "OCSPRequest", 658 listener: ( 659 certificate: Buffer, 660 issuer: Buffer, 661 callback: (err: Error | null, resp: Buffer) => void, 662 ) => void, 663 ): this; 664 once( 665 event: "resumeSession", 666 listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, 667 ): this; 668 once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; 669 once(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; 670 prependListener(event: string, listener: (...args: any[]) => void): this; 671 prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; 672 prependListener( 673 event: "newSession", 674 listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, 675 ): this; 676 prependListener( 677 event: "OCSPRequest", 678 listener: ( 679 certificate: Buffer, 680 issuer: Buffer, 681 callback: (err: Error | null, resp: Buffer) => void, 682 ) => void, 683 ): this; 684 prependListener( 685 event: "resumeSession", 686 listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, 687 ): this; 688 prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; 689 prependListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; 690 prependOnceListener(event: string, listener: (...args: any[]) => void): this; 691 prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; 692 prependOnceListener( 693 event: "newSession", 694 listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, 695 ): this; 696 prependOnceListener( 697 event: "OCSPRequest", 698 listener: ( 699 certificate: Buffer, 700 issuer: Buffer, 701 callback: (err: Error | null, resp: Buffer) => void, 702 ) => void, 703 ): this; 704 prependOnceListener( 705 event: "resumeSession", 706 listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, 707 ): this; 708 prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; 709 prependOnceListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; 710 } 711 /** 712 * @deprecated since v0.11.3 Use `tls.TLSSocket` instead. 713 */ 714 interface SecurePair { 715 encrypted: TLSSocket; 716 cleartext: TLSSocket; 717 } 718 type SecureVersion = "TLSv1.3" | "TLSv1.2" | "TLSv1.1" | "TLSv1"; 719 interface SecureContextOptions { 720 /** 721 * Optionally override the trusted CA certificates. Default is to trust 722 * the well-known CAs curated by Mozilla. Mozilla's CAs are completely 723 * replaced when CAs are explicitly specified using this option. 724 */ 725 ca?: string | Buffer | Array<string | Buffer> | undefined; 726 /** 727 * Cert chains in PEM format. One cert chain should be provided per 728 * private key. Each cert chain should consist of the PEM formatted 729 * certificate for a provided private key, followed by the PEM 730 * formatted intermediate certificates (if any), in order, and not 731 * including the root CA (the root CA must be pre-known to the peer, 732 * see ca). When providing multiple cert chains, they do not have to 733 * be in the same order as their private keys in key. If the 734 * intermediate certificates are not provided, the peer will not be 735 * able to validate the certificate, and the handshake will fail. 736 */ 737 cert?: string | Buffer | Array<string | Buffer> | undefined; 738 /** 739 * Colon-separated list of supported signature algorithms. The list 740 * can contain digest algorithms (SHA256, MD5 etc.), public key 741 * algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g 742 * 'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512). 743 */ 744 sigalgs?: string | undefined; 745 /** 746 * Cipher suite specification, replacing the default. For more 747 * information, see modifying the default cipher suite. Permitted 748 * ciphers can be obtained via tls.getCiphers(). Cipher names must be 749 * uppercased in order for OpenSSL to accept them. 750 */ 751 ciphers?: string | undefined; 752 /** 753 * Name of an OpenSSL engine which can provide the client certificate. 754 */ 755 clientCertEngine?: string | undefined; 756 /** 757 * PEM formatted CRLs (Certificate Revocation Lists). 758 */ 759 crl?: string | Buffer | Array<string | Buffer> | undefined; 760 /** 761 * Diffie Hellman parameters, required for Perfect Forward Secrecy. Use 762 * openssl dhparam to create the parameters. The key length must be 763 * greater than or equal to 1024 bits or else an error will be thrown. 764 * Although 1024 bits is permissible, use 2048 bits or larger for 765 * stronger security. If omitted or invalid, the parameters are 766 * silently discarded and DHE ciphers will not be available. 767 */ 768 dhparam?: string | Buffer | undefined; 769 /** 770 * A string describing a named curve or a colon separated list of curve 771 * NIDs or names, for example P-521:P-384:P-256, to use for ECDH key 772 * agreement. Set to auto to select the curve automatically. Use 773 * crypto.getCurves() to obtain a list of available curve names. On 774 * recent releases, openssl ecparam -list_curves will also display the 775 * name and description of each available elliptic curve. Default: 776 * tls.DEFAULT_ECDH_CURVE. 777 */ 778 ecdhCurve?: string | undefined; 779 /** 780 * Attempt to use the server's cipher suite preferences instead of the 781 * client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be 782 * set in secureOptions 783 */ 784 honorCipherOrder?: boolean | undefined; 785 /** 786 * Private keys in PEM format. PEM allows the option of private keys 787 * being encrypted. Encrypted keys will be decrypted with 788 * options.passphrase. Multiple keys using different algorithms can be 789 * provided either as an array of unencrypted key strings or buffers, 790 * or an array of objects in the form {pem: <string|buffer>[, 791 * passphrase: <string>]}. The object form can only occur in an array. 792 * object.passphrase is optional. Encrypted keys will be decrypted with 793 * object.passphrase if provided, or options.passphrase if it is not. 794 */ 795 key?: string | Buffer | Array<Buffer | KeyObject> | undefined; 796 /** 797 * Name of an OpenSSL engine to get private key from. Should be used 798 * together with privateKeyIdentifier. 799 */ 800 privateKeyEngine?: string | undefined; 801 /** 802 * Identifier of a private key managed by an OpenSSL engine. Should be 803 * used together with privateKeyEngine. Should not be set together with 804 * key, because both options define a private key in different ways. 805 */ 806 privateKeyIdentifier?: string | undefined; 807 /** 808 * Optionally set the maximum TLS version to allow. One 809 * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the 810 * `secureProtocol` option, use one or the other. 811 * **Default:** `'TLSv1.3'`, unless changed using CLI options. Using 812 * `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to 813 * `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used. 814 */ 815 maxVersion?: SecureVersion | undefined; 816 /** 817 * Optionally set the minimum TLS version to allow. One 818 * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the 819 * `secureProtocol` option, use one or the other. It is not recommended to use 820 * less than TLSv1.2, but it may be required for interoperability. 821 * **Default:** `'TLSv1.2'`, unless changed using CLI options. Using 822 * `--tls-v1.0` sets the default to `'TLSv1'`. Using `--tls-v1.1` sets the default to 823 * `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to 824 * 'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used. 825 */ 826 minVersion?: SecureVersion | undefined; 827 /** 828 * Shared passphrase used for a single private key and/or a PFX. 829 */ 830 passphrase?: string | undefined; 831 /** 832 * PFX or PKCS12 encoded private key and certificate chain. pfx is an 833 * alternative to providing key and cert individually. PFX is usually 834 * encrypted, if it is, passphrase will be used to decrypt it. Multiple 835 * PFX can be provided either as an array of unencrypted PFX buffers, 836 * or an array of objects in the form {buf: <string|buffer>[, 837 * passphrase: <string>]}. The object form can only occur in an array. 838 * object.passphrase is optional. Encrypted PFX will be decrypted with 839 * object.passphrase if provided, or options.passphrase if it is not. 840 */ 841 pfx?: string | Buffer | Array<string | Buffer | PxfObject> | undefined; 842 /** 843 * Optionally affect the OpenSSL protocol behavior, which is not 844 * usually necessary. This should be used carefully if at all! Value is 845 * a numeric bitmask of the SSL_OP_* options from OpenSSL Options 846 */ 847 secureOptions?: number | undefined; // Value is a numeric bitmask of the `SSL_OP_*` options 848 /** 849 * Legacy mechanism to select the TLS protocol version to use, it does 850 * not support independent control of the minimum and maximum version, 851 * and does not support limiting the protocol to TLSv1.3. Use 852 * minVersion and maxVersion instead. The possible values are listed as 853 * SSL_METHODS, use the function names as strings. For example, use 854 * 'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow 855 * any TLS protocol version up to TLSv1.3. It is not recommended to use 856 * TLS versions less than 1.2, but it may be required for 857 * interoperability. Default: none, see minVersion. 858 */ 859 secureProtocol?: string | undefined; 860 /** 861 * Opaque identifier used by servers to ensure session state is not 862 * shared between applications. Unused by clients. 863 */ 864 sessionIdContext?: string | undefined; 865 /** 866 * 48-bytes of cryptographically strong pseudo-random data. 867 * See Session Resumption for more information. 868 */ 869 ticketKeys?: Buffer | undefined; 870 /** 871 * The number of seconds after which a TLS session created by the 872 * server will no longer be resumable. See Session Resumption for more 873 * information. Default: 300. 874 */ 875 sessionTimeout?: number | undefined; 876 } 877 interface SecureContext { 878 context: any; 879 } 880 /** 881 * Verifies the certificate `cert` is issued to `hostname`. 882 * 883 * Returns [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object, populating it with `reason`, `host`, and `cert` on 884 * failure. On success, returns [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type). 885 * 886 * This function can be overwritten by providing alternative function as part of 887 * the `options.checkServerIdentity` option passed to `tls.connect()`. The 888 * overwriting function can call `tls.checkServerIdentity()` of course, to augment 889 * the checks done with additional verification. 890 * 891 * This function is only called if the certificate passed all other checks, such as 892 * being issued by trusted CA (`options.ca`). 893 * @since v0.8.4 894 * @param hostname The host name or IP address to verify the certificate against. 895 * @param cert A `certificate object` representing the peer's certificate. 896 */ 897 function checkServerIdentity(hostname: string, cert: PeerCertificate): Error | undefined; 898 /** 899 * Creates a new {@link Server}. The `secureConnectionListener`, if provided, is 900 * automatically set as a listener for the `'secureConnection'` event. 901 * 902 * The `ticketKeys` options is automatically shared between `cluster` module 903 * workers. 904 * 905 * The following illustrates a simple echo server: 906 * 907 * ```js 908 * import tls from 'node:tls'; 909 * import fs from 'node:fs'; 910 * 911 * const options = { 912 * key: fs.readFileSync('server-key.pem'), 913 * cert: fs.readFileSync('server-cert.pem'), 914 * 915 * // This is necessary only if using client certificate authentication. 916 * requestCert: true, 917 * 918 * // This is necessary only if the client uses a self-signed certificate. 919 * ca: [ fs.readFileSync('client-cert.pem') ] 920 * }; 921 * 922 * const server = tls.createServer(options, (socket) => { 923 * console.log('server connected', 924 * socket.authorized ? 'authorized' : 'unauthorized'); 925 * socket.write('welcome!\n'); 926 * socket.setEncoding('utf8'); 927 * socket.pipe(socket); 928 * }); 929 * server.listen(8000, () => { 930 * console.log('server bound'); 931 * }); 932 * ``` 933 * 934 * The server can be tested by connecting to it using the example client from {@link connect}. 935 * @since v0.3.2 936 */ 937 function createServer(secureConnectionListener?: (socket: TLSSocket) => void): Server; 938 function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; 939 /** 940 * The `callback` function, if specified, will be added as a listener for the `'secureConnect'` event. 941 * 942 * `tls.connect()` returns a {@link TLSSocket} object. 943 * 944 * Unlike the `https` API, `tls.connect()` does not enable the 945 * SNI (Server Name Indication) extension by default, which may cause some 946 * servers to return an incorrect certificate or reject the connection 947 * altogether. To enable SNI, set the `servername` option in addition 948 * to `host`. 949 * 950 * The following illustrates a client for the echo server example from {@link createServer}: 951 * 952 * ```js 953 * // Assumes an echo server that is listening on port 8000. 954 * import tls from 'node:tls'; 955 * import fs from 'node:fs'; 956 * 957 * const options = { 958 * // Necessary only if the server requires client certificate authentication. 959 * key: fs.readFileSync('client-key.pem'), 960 * cert: fs.readFileSync('client-cert.pem'), 961 * 962 * // Necessary only if the server uses a self-signed certificate. 963 * ca: [ fs.readFileSync('server-cert.pem') ], 964 * 965 * // Necessary only if the server's cert isn't for "localhost". 966 * checkServerIdentity: () => { return null; }, 967 * }; 968 * 969 * const socket = tls.connect(8000, options, () => { 970 * console.log('client connected', 971 * socket.authorized ? 'authorized' : 'unauthorized'); 972 * process.stdin.pipe(socket); 973 * process.stdin.resume(); 974 * }); 975 * socket.setEncoding('utf8'); 976 * socket.on('data', (data) => { 977 * console.log(data); 978 * }); 979 * socket.on('end', () => { 980 * console.log('server ends connection'); 981 * }); 982 * ``` 983 * @since v0.11.3 984 */ 985 function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; 986 function connect( 987 port: number, 988 host?: string, 989 options?: ConnectionOptions, 990 secureConnectListener?: () => void, 991 ): TLSSocket; 992 function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; 993 /** 994 * Creates a new secure pair object with two streams, one of which reads and writes 995 * the encrypted data and the other of which reads and writes the cleartext data. 996 * Generally, the encrypted stream is piped to/from an incoming encrypted data 997 * stream and the cleartext one is used as a replacement for the initial encrypted 998 * stream. 999 * 1000 * `tls.createSecurePair()` returns a `tls.SecurePair` object with `cleartext` and `encrypted` stream properties. 1001 * 1002 * Using `cleartext` has the same API as {@link TLSSocket}. 1003 * 1004 * The `tls.createSecurePair()` method is now deprecated in favor of`tls.TLSSocket()`. For example, the code: 1005 * 1006 * ```js 1007 * pair = tls.createSecurePair(// ... ); 1008 * pair.encrypted.pipe(socket); 1009 * socket.pipe(pair.encrypted); 1010 * ``` 1011 * 1012 * can be replaced by: 1013 * 1014 * ```js 1015 * secureSocket = tls.TLSSocket(socket, options); 1016 * ``` 1017 * 1018 * where `secureSocket` has the same API as `pair.cleartext`. 1019 * @since v0.3.2 1020 * @deprecated Since v0.11.3 - Use {@link TLSSocket} instead. 1021 * @param context A secure context object as returned by `tls.createSecureContext()` 1022 * @param isServer `true` to specify that this TLS connection should be opened as a server. 1023 * @param requestCert `true` to specify whether a server should request a certificate from a connecting client. Only applies when `isServer` is `true`. 1024 * @param rejectUnauthorized If not `false` a server automatically reject clients with invalid certificates. Only applies when `isServer` is `true`. 1025 */ 1026 function createSecurePair( 1027 context?: SecureContext, 1028 isServer?: boolean, 1029 requestCert?: boolean, 1030 rejectUnauthorized?: boolean, 1031 ): SecurePair; 1032 /** 1033 * {@link createServer} sets the default value of the `honorCipherOrder` option 1034 * to `true`, other APIs that create secure contexts leave it unset. 1035 * 1036 * {@link createServer} uses a 128 bit truncated SHA1 hash value generated 1037 * from `process.argv` as the default value of the `sessionIdContext` option, other 1038 * APIs that create secure contexts have no default value. 1039 * 1040 * The `tls.createSecureContext()` method creates a `SecureContext` object. It is 1041 * usable as an argument to several `tls` APIs, such as {@link createServer} and `server.addContext()`, but has no public methods. 1042 * 1043 * A key is _required_ for ciphers that use certificates. Either `key` or`pfx` can be used to provide it. 1044 * 1045 * If the `ca` option is not given, then Node.js will default to using [Mozilla's publicly trusted list of 1046 * CAs](https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt). 1047 * @since v0.11.13 1048 */ 1049 function createSecureContext(options?: SecureContextOptions): SecureContext; 1050 /** 1051 * Returns an array with the names of the supported TLS ciphers. The names are 1052 * lower-case for historical reasons, but must be uppercased to be used in 1053 * the `ciphers` option of {@link createSecureContext}. 1054 * 1055 * Cipher names that start with `'tls_'` are for TLSv1.3, all the others are for 1056 * TLSv1.2 and below. 1057 * 1058 * ```js 1059 * console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...] 1060 * ``` 1061 * @since v0.10.2 1062 */ 1063 function getCiphers(): string[]; 1064 /** 1065 * The default curve name to use for ECDH key agreement in a tls server. 1066 * The default value is 'auto'. See tls.createSecureContext() for further 1067 * information. 1068 */ 1069 let DEFAULT_ECDH_CURVE: string; 1070 /** 1071 * The default value of the maxVersion option of 1072 * tls.createSecureContext(). It can be assigned any of the supported TLS 1073 * protocol versions, 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: 1074 * 'TLSv1.3', unless changed using CLI options. Using --tls-max-v1.2 sets 1075 * the default to 'TLSv1.2'. Using --tls-max-v1.3 sets the default to 1076 * 'TLSv1.3'. If multiple of the options are provided, the highest maximum 1077 * is used. 1078 */ 1079 let DEFAULT_MAX_VERSION: SecureVersion; 1080 /** 1081 * The default value of the minVersion option of tls.createSecureContext(). 1082 * It can be assigned any of the supported TLS protocol versions, 1083 * 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: 'TLSv1.2', unless 1084 * changed using CLI options. Using --tls-min-v1.0 sets the default to 1085 * 'TLSv1'. Using --tls-min-v1.1 sets the default to 'TLSv1.1'. Using 1086 * --tls-min-v1.3 sets the default to 'TLSv1.3'. If multiple of the options 1087 * are provided, the lowest minimum is used. 1088 */ 1089 let DEFAULT_MIN_VERSION: SecureVersion; 1090 /** 1091 * An immutable array of strings representing the root certificates (in PEM 1092 * format) used for verifying peer certificates. This is the default value 1093 * of the ca option to tls.createSecureContext(). 1094 */ 1095 const rootCertificates: readonly string[]; 1096 } 1097 declare module "node:tls" { 1098 export * from "tls"; 1099 }