File size: 1,693 Bytes
66adc5d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
import * as fs from "fs";
import { setGlobalDispatcher, Agent } from "undici";
/**
* Load client certificates for mutual TLS authentication. This function must be called before any HTTP requests are made.
* This is a global setting that affects all HTTP requests made by the application using the native fetch API.
*
* @param clientCertPath Path to client certificate
* @param clientKeyPath Path to client key
* @param caCertPath Path to CA certificate [optional]
* @param clientKeyPassword Password for client key [optional]
* @param rejectUnauthorized Reject unauthorized certificates.
* Only use for testing/development, not recommended in production environments [optional]
*
* @returns void
*
* @example
* ```typescript
* loadClientCertificates("cert.pem", "key.pem", "ca.pem", "password", false);
* ```
*
* @see
* [Undici Agent](https://undici.nodejs.org/#/docs/api/Agent)
* @see
* [Undici Dispatcher](https://undici.nodejs.org/#/docs/api/Dispatcher)
* @see
* [NodeJS Native Fetch API](https://nodejs.org/docs/latest-v19.x/api/globals.html#fetch)
*/
export function loadClientCertificates(
clientCertPath: string,
clientKeyPath: string,
caCertPath?: string,
clientKeyPassword?: string,
rejectUnauthorized?: boolean
): void {
const clientCert = fs.readFileSync(clientCertPath);
const clientKey = fs.readFileSync(clientKeyPath);
const caCert = caCertPath ? fs.readFileSync(caCertPath) : undefined;
const agent = new Agent({
connect: {
cert: clientCert,
key: clientKey,
ca: caCert,
passphrase: clientKeyPassword,
rejectUnauthorized: rejectUnauthorized,
},
});
setGlobalDispatcher(agent);
}
|