|
| 1 | +import * as fs from 'fs'; |
| 2 | +import * as https from 'https'; |
| 3 | +import { NestApplicationOptions } from '@nestjs/common'; |
1 | 4 | import { AxiosRequestConfig } from 'axios'; |
| 5 | +import { ClientOptions } from 'ws'; |
2 | 6 |
|
3 | | -export const basicAuth = (username: string, password: string) => { |
| 7 | +interface Certificates { |
| 8 | + key: string; |
| 9 | + cert: string; |
| 10 | + ca: string; |
| 11 | +} |
| 12 | + |
| 13 | +const getCertificates = (): Certificates | undefined => { |
| 14 | + let key, cert, ca; |
| 15 | + if ( |
| 16 | + process.env['TLS_KEY'] === undefined || |
| 17 | + process.env['TLS_CERT'] === undefined || |
| 18 | + process.env['TLS_CA'] === undefined |
| 19 | + ) { |
| 20 | + return undefined; |
| 21 | + } |
| 22 | + try { |
| 23 | + key = fs.readFileSync(process.env['TLS_KEY']).toString(); |
| 24 | + cert = fs.readFileSync(process.env['TLS_CERT']).toString(); |
| 25 | + ca = fs.readFileSync(process.env['TLS_CA']).toString(); |
| 26 | + } catch (error) { |
| 27 | + console.error(`Error reading certificates: ${error}`); |
| 28 | + process.exit(-1); |
| 29 | + } |
| 30 | + return { key, cert, ca }; |
| 31 | +}; |
| 32 | + |
| 33 | +export const getWebsocketOptions = (username: string, password: string): ClientOptions => { |
| 34 | + const requestOptions: ClientOptions = {}; |
| 35 | + if (username && username !== '' && password && password !== '') { |
| 36 | + requestOptions.headers = { |
| 37 | + Authorization: `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`, |
| 38 | + }; |
| 39 | + } |
| 40 | + const certs = getCertificates(); |
| 41 | + if (certs) { |
| 42 | + requestOptions.ca = certs.ca; |
| 43 | + requestOptions.cert = certs.cert; |
| 44 | + requestOptions.key = certs.key; |
| 45 | + } |
| 46 | + return requestOptions; |
| 47 | +}; |
| 48 | + |
| 49 | +export const getHttpRequestOptions = (username: string, password: string) => { |
4 | 50 | const requestOptions: AxiosRequestConfig = {}; |
5 | 51 | if (username !== '' && password !== '') { |
6 | 52 | requestOptions.auth = { |
7 | 53 | username: username, |
8 | 54 | password: password, |
9 | 55 | }; |
10 | 56 | } |
| 57 | + const certs = getCertificates(); |
| 58 | + if (certs) { |
| 59 | + requestOptions.httpsAgent = new https.Agent({ ...certs, requestCert: true }); |
| 60 | + } |
11 | 61 | return requestOptions; |
12 | 62 | }; |
| 63 | + |
| 64 | +export const getNestOptions = (): NestApplicationOptions => { |
| 65 | + const options: NestApplicationOptions = {}; |
| 66 | + const certs = getCertificates(); |
| 67 | + if (certs) { |
| 68 | + options.httpsOptions = certs; |
| 69 | + } |
| 70 | + return options; |
| 71 | +}; |
0 commit comments