b9c04ec56707076743730df4c9eaf441d39f8b6cd79f2934480d84c9438f3404706d56da9cf5d97d1ff2c8c8b418b600b842271329b5d6a7ba62be326ae32f 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245
  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/v24.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. type SecureVersion = "TLSv1.3" | "TLSv1.2" | "TLSv1.1" | "TLSv1";
  801. interface SecureContextOptions {
  802. /**
  803. * If set, this will be called when a client opens a connection using the ALPN extension.
  804. * One argument will be passed to the callback: an object containing `servername` and `protocols` fields,
  805. * respectively containing the server name from the SNI extension (if any) and an array of
  806. * ALPN protocol name strings. The callback must return either one of the strings listed in `protocols`,
  807. * which will be returned to the client as the selected ALPN protocol, or `undefined`,
  808. * to reject the connection with a fatal alert. If a string is returned that does not match one of
  809. * the client's ALPN protocols, an error will be thrown.
  810. * This option cannot be used with the `ALPNProtocols` option, and setting both options will throw an error.
  811. */
  812. ALPNCallback?: ((arg: { servername: string; protocols: string[] }) => string | undefined) | undefined;
  813. /**
  814. * Treat intermediate (non-self-signed)
  815. * certificates in the trust CA certificate list as trusted.
  816. * @since v22.9.0, v20.18.0
  817. */
  818. allowPartialTrustChain?: boolean | undefined;
  819. /**
  820. * Optionally override the trusted CA certificates. Default is to trust
  821. * the well-known CAs curated by Mozilla. Mozilla's CAs are completely
  822. * replaced when CAs are explicitly specified using this option.
  823. */
  824. ca?: string | Buffer | Array<string | Buffer> | undefined;
  825. /**
  826. * Cert chains in PEM format. One cert chain should be provided per
  827. * private key. Each cert chain should consist of the PEM formatted
  828. * certificate for a provided private key, followed by the PEM
  829. * formatted intermediate certificates (if any), in order, and not
  830. * including the root CA (the root CA must be pre-known to the peer,
  831. * see ca). When providing multiple cert chains, they do not have to
  832. * be in the same order as their private keys in key. If the
  833. * intermediate certificates are not provided, the peer will not be
  834. * able to validate the certificate, and the handshake will fail.
  835. */
  836. cert?: string | Buffer | Array<string | Buffer> | undefined;
  837. /**
  838. * Colon-separated list of supported signature algorithms. The list
  839. * can contain digest algorithms (SHA256, MD5 etc.), public key
  840. * algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g
  841. * 'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512).
  842. */
  843. sigalgs?: string | undefined;
  844. /**
  845. * Cipher suite specification, replacing the default. For more
  846. * information, see modifying the default cipher suite. Permitted
  847. * ciphers can be obtained via tls.getCiphers(). Cipher names must be
  848. * uppercased in order for OpenSSL to accept them.
  849. */
  850. ciphers?: string | undefined;
  851. /**
  852. * Name of an OpenSSL engine which can provide the client certificate.
  853. * @deprecated
  854. */
  855. clientCertEngine?: string | undefined;
  856. /**
  857. * PEM formatted CRLs (Certificate Revocation Lists).
  858. */
  859. crl?: string | Buffer | Array<string | Buffer> | undefined;
  860. /**
  861. * `'auto'` or custom Diffie-Hellman parameters, required for non-ECDHE perfect forward secrecy.
  862. * If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available.
  863. * ECDHE-based perfect forward secrecy will still be available.
  864. */
  865. dhparam?: string | Buffer | undefined;
  866. /**
  867. * A string describing a named curve or a colon separated list of curve
  868. * NIDs or names, for example P-521:P-384:P-256, to use for ECDH key
  869. * agreement. Set to auto to select the curve automatically. Use
  870. * crypto.getCurves() to obtain a list of available curve names. On
  871. * recent releases, openssl ecparam -list_curves will also display the
  872. * name and description of each available elliptic curve. Default:
  873. * tls.DEFAULT_ECDH_CURVE.
  874. */
  875. ecdhCurve?: string | undefined;
  876. /**
  877. * Attempt to use the server's cipher suite preferences instead of the
  878. * client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be
  879. * set in secureOptions
  880. */
  881. honorCipherOrder?: boolean | undefined;
  882. /**
  883. * Private keys in PEM format. PEM allows the option of private keys
  884. * being encrypted. Encrypted keys will be decrypted with
  885. * options.passphrase. Multiple keys using different algorithms can be
  886. * provided either as an array of unencrypted key strings or buffers,
  887. * or an array of objects in the form {pem: <string|buffer>[,
  888. * passphrase: <string>]}. The object form can only occur in an array.
  889. * object.passphrase is optional. Encrypted keys will be decrypted with
  890. * object.passphrase if provided, or options.passphrase if it is not.
  891. */
  892. key?: string | Buffer | Array<string | Buffer | KeyObject> | undefined;
  893. /**
  894. * Name of an OpenSSL engine to get private key from. Should be used
  895. * together with privateKeyIdentifier.
  896. * @deprecated
  897. */
  898. privateKeyEngine?: string | undefined;
  899. /**
  900. * Identifier of a private key managed by an OpenSSL engine. Should be
  901. * used together with privateKeyEngine. Should not be set together with
  902. * key, because both options define a private key in different ways.
  903. * @deprecated
  904. */
  905. privateKeyIdentifier?: string | undefined;
  906. /**
  907. * Optionally set the maximum TLS version to allow. One
  908. * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the
  909. * `secureProtocol` option, use one or the other.
  910. * **Default:** `'TLSv1.3'`, unless changed using CLI options. Using
  911. * `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to
  912. * `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used.
  913. */
  914. maxVersion?: SecureVersion | undefined;
  915. /**
  916. * Optionally set the minimum TLS version to allow. One
  917. * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the
  918. * `secureProtocol` option, use one or the other. It is not recommended to use
  919. * less than TLSv1.2, but it may be required for interoperability.
  920. * **Default:** `'TLSv1.2'`, unless changed using CLI options. Using
  921. * `--tls-v1.0` sets the default to `'TLSv1'`. Using `--tls-v1.1` sets the default to
  922. * `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to
  923. * 'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used.
  924. */
  925. minVersion?: SecureVersion | undefined;
  926. /**
  927. * Shared passphrase used for a single private key and/or a PFX.
  928. */
  929. passphrase?: string | undefined;
  930. /**
  931. * PFX or PKCS12 encoded private key and certificate chain. pfx is an
  932. * alternative to providing key and cert individually. PFX is usually
  933. * encrypted, if it is, passphrase will be used to decrypt it. Multiple
  934. * PFX can be provided either as an array of unencrypted PFX buffers,
  935. * or an array of objects in the form {buf: <string|buffer>[,
  936. * passphrase: <string>]}. The object form can only occur in an array.
  937. * object.passphrase is optional. Encrypted PFX will be decrypted with
  938. * object.passphrase if provided, or options.passphrase if it is not.
  939. */
  940. pfx?: string | Buffer | Array<string | Buffer | PxfObject> | undefined;
  941. /**
  942. * Optionally affect the OpenSSL protocol behavior, which is not
  943. * usually necessary. This should be used carefully if at all! Value is
  944. * a numeric bitmask of the SSL_OP_* options from OpenSSL Options
  945. */
  946. secureOptions?: number | undefined; // Value is a numeric bitmask of the `SSL_OP_*` options
  947. /**
  948. * Legacy mechanism to select the TLS protocol version to use, it does
  949. * not support independent control of the minimum and maximum version,
  950. * and does not support limiting the protocol to TLSv1.3. Use
  951. * minVersion and maxVersion instead. The possible values are listed as
  952. * SSL_METHODS, use the function names as strings. For example, use
  953. * 'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow
  954. * any TLS protocol version up to TLSv1.3. It is not recommended to use
  955. * TLS versions less than 1.2, but it may be required for
  956. * interoperability. Default: none, see minVersion.
  957. */
  958. secureProtocol?: string | undefined;
  959. /**
  960. * Opaque identifier used by servers to ensure session state is not
  961. * shared between applications. Unused by clients.
  962. */
  963. sessionIdContext?: string | undefined;
  964. /**
  965. * 48-bytes of cryptographically strong pseudo-random data.
  966. * See Session Resumption for more information.
  967. */
  968. ticketKeys?: Buffer | undefined;
  969. /**
  970. * The number of seconds after which a TLS session created by the
  971. * server will no longer be resumable. See Session Resumption for more
  972. * information. Default: 300.
  973. */
  974. sessionTimeout?: number | undefined;
  975. }
  976. interface SecureContext {
  977. context: any;
  978. }
  979. /**
  980. * Verifies the certificate `cert` is issued to `hostname`.
  981. *
  982. * Returns [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object, populating it with `reason`, `host`, and `cert` on
  983. * failure. On success, returns [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type).
  984. *
  985. * This function is intended to be used in combination with the`checkServerIdentity` option that can be passed to {@link connect} and as
  986. * such operates on a `certificate object`. For other purposes, consider using `x509.checkHost()` instead.
  987. *
  988. * This function can be overwritten by providing an alternative function as the `options.checkServerIdentity` option that is passed to `tls.connect()`. The
  989. * overwriting function can call `tls.checkServerIdentity()` of course, to augment
  990. * the checks done with additional verification.
  991. *
  992. * This function is only called if the certificate passed all other checks, such as
  993. * being issued by trusted CA (`options.ca`).
  994. *
  995. * Earlier versions of Node.js incorrectly accepted certificates for a given`hostname` if a matching `uniformResourceIdentifier` subject alternative name
  996. * 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
  997. * a custom `options.checkServerIdentity` function that implements the desired behavior.
  998. * @since v0.8.4
  999. * @param hostname The host name or IP address to verify the certificate against.
  1000. * @param cert A `certificate object` representing the peer's certificate.
  1001. */
  1002. function checkServerIdentity(hostname: string, cert: PeerCertificate): Error | undefined;
  1003. /**
  1004. * Creates a new {@link Server}. The `secureConnectionListener`, if provided, is
  1005. * automatically set as a listener for the `'secureConnection'` event.
  1006. *
  1007. * The `ticketKeys` options is automatically shared between `node:cluster` module
  1008. * workers.
  1009. *
  1010. * The following illustrates a simple echo server:
  1011. *
  1012. * ```js
  1013. * import tls from 'node:tls';
  1014. * import fs from 'node:fs';
  1015. *
  1016. * const options = {
  1017. * key: fs.readFileSync('server-key.pem'),
  1018. * cert: fs.readFileSync('server-cert.pem'),
  1019. *
  1020. * // This is necessary only if using client certificate authentication.
  1021. * requestCert: true,
  1022. *
  1023. * // This is necessary only if the client uses a self-signed certificate.
  1024. * ca: [ fs.readFileSync('client-cert.pem') ],
  1025. * };
  1026. *
  1027. * const server = tls.createServer(options, (socket) => {
  1028. * console.log('server connected',
  1029. * socket.authorized ? 'authorized' : 'unauthorized');
  1030. * socket.write('welcome!\n');
  1031. * socket.setEncoding('utf8');
  1032. * socket.pipe(socket);
  1033. * });
  1034. * server.listen(8000, () => {
  1035. * console.log('server bound');
  1036. * });
  1037. * ```
  1038. *
  1039. * The server can be tested by connecting to it using the example client from {@link connect}.
  1040. * @since v0.3.2
  1041. */
  1042. function createServer(secureConnectionListener?: (socket: TLSSocket) => void): Server;
  1043. function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server;
  1044. /**
  1045. * The `callback` function, if specified, will be added as a listener for the `'secureConnect'` event.
  1046. *
  1047. * `tls.connect()` returns a {@link TLSSocket} object.
  1048. *
  1049. * Unlike the `https` API, `tls.connect()` does not enable the
  1050. * SNI (Server Name Indication) extension by default, which may cause some
  1051. * servers to return an incorrect certificate or reject the connection
  1052. * altogether. To enable SNI, set the `servername` option in addition
  1053. * to `host`.
  1054. *
  1055. * The following illustrates a client for the echo server example from {@link createServer}:
  1056. *
  1057. * ```js
  1058. * // Assumes an echo server that is listening on port 8000.
  1059. * import tls from 'node:tls';
  1060. * import fs from 'node:fs';
  1061. *
  1062. * const options = {
  1063. * // Necessary only if the server requires client certificate authentication.
  1064. * key: fs.readFileSync('client-key.pem'),
  1065. * cert: fs.readFileSync('client-cert.pem'),
  1066. *
  1067. * // Necessary only if the server uses a self-signed certificate.
  1068. * ca: [ fs.readFileSync('server-cert.pem') ],
  1069. *
  1070. * // Necessary only if the server's cert isn't for "localhost".
  1071. * checkServerIdentity: () => { return null; },
  1072. * };
  1073. *
  1074. * const socket = tls.connect(8000, options, () => {
  1075. * console.log('client connected',
  1076. * socket.authorized ? 'authorized' : 'unauthorized');
  1077. * process.stdin.pipe(socket);
  1078. * process.stdin.resume();
  1079. * });
  1080. * socket.setEncoding('utf8');
  1081. * socket.on('data', (data) => {
  1082. * console.log(data);
  1083. * });
  1084. * socket.on('end', () => {
  1085. * console.log('server ends connection');
  1086. * });
  1087. * ```
  1088. * @since v0.11.3
  1089. */
  1090. function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket;
  1091. function connect(
  1092. port: number,
  1093. host?: string,
  1094. options?: ConnectionOptions,
  1095. secureConnectListener?: () => void,
  1096. ): TLSSocket;
  1097. function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket;
  1098. /**
  1099. * `{@link createServer}` sets the default value of the `honorCipherOrder` option
  1100. * to `true`, other APIs that create secure contexts leave it unset.
  1101. *
  1102. * `{@link createServer}` uses a 128 bit truncated SHA1 hash value generated
  1103. * from `process.argv` as the default value of the `sessionIdContext` option, other
  1104. * APIs that create secure contexts have no default value.
  1105. *
  1106. * The `tls.createSecureContext()` method creates a `SecureContext` object. It is
  1107. * usable as an argument to several `tls` APIs, such as `server.addContext()`,
  1108. * but has no public methods. The {@link Server} constructor and the {@link createServer} method do not support the `secureContext` option.
  1109. *
  1110. * A key is _required_ for ciphers that use certificates. Either `key` or `pfx` can be used to provide it.
  1111. *
  1112. * If the `ca` option is not given, then Node.js will default to using [Mozilla's publicly trusted list of
  1113. * CAs](https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt).
  1114. *
  1115. * Custom DHE parameters are discouraged in favor of the new `dhparam: 'auto' `option. When set to `'auto'`, well-known DHE parameters of sufficient strength
  1116. * will be selected automatically. Otherwise, if necessary, `openssl dhparam` can
  1117. * be used to create custom parameters. The key length must be greater than or
  1118. * equal to 1024 bits or else an error will be thrown. Although 1024 bits is
  1119. * permissible, use 2048 bits or larger for stronger security.
  1120. * @since v0.11.13
  1121. */
  1122. function createSecureContext(options?: SecureContextOptions): SecureContext;
  1123. /**
  1124. * Returns an array containing the CA certificates from various sources, depending on `type`:
  1125. *
  1126. * * `"default"`: return the CA certificates that will be used by the Node.js TLS clients by default.
  1127. * * When `--use-bundled-ca` is enabled (default), or `--use-openssl-ca` is not enabled,
  1128. * this would include CA certificates from the bundled Mozilla CA store.
  1129. * * When `--use-system-ca` is enabled, this would also include certificates from the system's
  1130. * trusted store.
  1131. * * When `NODE_EXTRA_CA_CERTS` is used, this would also include certificates loaded from the specified
  1132. * file.
  1133. * * `"system"`: return the CA certificates that are loaded from the system's trusted store, according
  1134. * to rules set by `--use-system-ca`. This can be used to get the certificates from the system
  1135. * when `--use-system-ca` is not enabled.
  1136. * * `"bundled"`: return the CA certificates from the bundled Mozilla CA store. This would be the same
  1137. * as `tls.rootCertificates`.
  1138. * * `"extra"`: return the CA certificates loaded from `NODE_EXTRA_CA_CERTS`. It's an empty array if
  1139. * `NODE_EXTRA_CA_CERTS` is not set.
  1140. * @since v22.15.0
  1141. * @param type The type of CA certificates that will be returned. Valid values
  1142. * are `"default"`, `"system"`, `"bundled"` and `"extra"`.
  1143. * **Default:** `"default"`.
  1144. * @returns An array of PEM-encoded certificates. The array may contain duplicates
  1145. * if the same certificate is repeatedly stored in multiple sources.
  1146. */
  1147. function getCACertificates(type?: "default" | "system" | "bundled" | "extra"): string[];
  1148. /**
  1149. * Returns an array with the names of the supported TLS ciphers. The names are
  1150. * lower-case for historical reasons, but must be uppercased to be used in
  1151. * the `ciphers` option of `{@link createSecureContext}`.
  1152. *
  1153. * Not all supported ciphers are enabled by default. See
  1154. * [Modifying the default TLS cipher suite](https://nodejs.org/docs/latest-v24.x/api/tls.html#modifying-the-default-tls-cipher-suite).
  1155. *
  1156. * Cipher names that start with `'tls_'` are for TLSv1.3, all the others are for
  1157. * TLSv1.2 and below.
  1158. *
  1159. * ```js
  1160. * console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...]
  1161. * ```
  1162. * @since v0.10.2
  1163. */
  1164. function getCiphers(): string[];
  1165. /**
  1166. * Sets the default CA certificates used by Node.js TLS clients. If the provided
  1167. * certificates are parsed successfully, they will become the default CA
  1168. * certificate list returned by {@link getCACertificates} and used
  1169. * by subsequent TLS connections that don't specify their own CA certificates.
  1170. * The certificates will be deduplicated before being set as the default.
  1171. *
  1172. * This function only affects the current Node.js thread. Previous
  1173. * sessions cached by the HTTPS agent won't be affected by this change, so
  1174. * this method should be called before any unwanted cachable TLS connections are
  1175. * made.
  1176. *
  1177. * To use system CA certificates as the default:
  1178. *
  1179. * ```js
  1180. * import tls from 'node:tls';
  1181. * tls.setDefaultCACertificates(tls.getCACertificates('system'));
  1182. * ```
  1183. *
  1184. * This function completely replaces the default CA certificate list. To add additional
  1185. * certificates to the existing defaults, get the current certificates and append to them:
  1186. *
  1187. * ```js
  1188. * import tls from 'node:tls';
  1189. * const currentCerts = tls.getCACertificates('default');
  1190. * const additionalCerts = ['-----BEGIN CERTIFICATE-----\n...'];
  1191. * tls.setDefaultCACertificates([...currentCerts, ...additionalCerts]);
  1192. * ```
  1193. * @since v24.5.0
  1194. * @param certs An array of CA certificates in PEM format.
  1195. */
  1196. function setDefaultCACertificates(certs: ReadonlyArray<string | NodeJS.ArrayBufferView>): void;
  1197. /**
  1198. * The default curve name to use for ECDH key agreement in a tls server.
  1199. * The default value is `'auto'`. See `{@link createSecureContext()}` for further
  1200. * information.
  1201. * @since v0.11.13
  1202. */
  1203. let DEFAULT_ECDH_CURVE: string;
  1204. /**
  1205. * The default value of the `maxVersion` option of `{@link createSecureContext()}`.
  1206. * It can be assigned any of the supported TLS protocol versions,
  1207. * `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. **Default:** `'TLSv1.3'`, unless
  1208. * changed using CLI options. Using `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using
  1209. * `--tls-max-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options
  1210. * are provided, the highest maximum is used.
  1211. * @since v11.4.0
  1212. */
  1213. let DEFAULT_MAX_VERSION: SecureVersion;
  1214. /**
  1215. * The default value of the `minVersion` option of `{@link createSecureContext()}`.
  1216. * It can be assigned any of the supported TLS protocol versions,
  1217. * `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. **Default:** `'TLSv1.2'`, unless
  1218. * changed using CLI options. Using `--tls-min-v1.0` sets the default to
  1219. * `'TLSv1'`. Using `--tls-min-v1.1` sets the default to `'TLSv1.1'`. Using
  1220. * `--tls-min-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options
  1221. * are provided, the lowest minimum is used.
  1222. * @since v11.4.0
  1223. */
  1224. let DEFAULT_MIN_VERSION: SecureVersion;
  1225. /**
  1226. * The default value of the `ciphers` option of `{@link createSecureContext()}`.
  1227. * It can be assigned any of the supported OpenSSL ciphers.
  1228. * Defaults to the content of `crypto.constants.defaultCoreCipherList`, unless
  1229. * changed using CLI options using `--tls-default-ciphers`.
  1230. * @since v19.8.0
  1231. */
  1232. let DEFAULT_CIPHERS: string;
  1233. /**
  1234. * An immutable array of strings representing the root certificates (in PEM format)
  1235. * from the bundled Mozilla CA store as supplied by the current Node.js version.
  1236. *
  1237. * The bundled CA store, as supplied by Node.js, is a snapshot of Mozilla CA store
  1238. * that is fixed at release time. It is identical on all supported platforms.
  1239. * @since v12.3.0
  1240. */
  1241. const rootCertificates: readonly string[];
  1242. }
  1243. declare module "node:tls" {
  1244. export * from "tls";
  1245. }