d61dca9b566f03dc5200026f69af63fd76e5d4645c73418f34b68c208a3cb524a5d776eb8a43552c9654f89625dbece24693fa8a7d8ca19123a3ececcc1ea0 58 KB

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