UNPKG

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