From 74b9e7be4874e8af5f7e87050f3ed0293398af1f Mon Sep 17 00:00:00 2001 From: Chris Bygrave Date: Wed, 3 May 2023 09:59:01 +0100 Subject: [PATCH] Pass certs on the websocket Signed-off-by: Chris Bygrave --- src/event-stream/event-stream.service.ts | 6 ++---- src/utils.ts | 17 +++++++++++++++++ 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/src/event-stream/event-stream.service.ts b/src/event-stream/event-stream.service.ts index 3a6d10d..85655b4 100644 --- a/src/event-stream/event-stream.service.ts +++ b/src/event-stream/event-stream.service.ts @@ -22,7 +22,7 @@ import WebSocket from 'ws'; import { FFRequestIDHeader } from '../request-context/constants'; import { Context } from '../request-context/request-context.decorator'; import { IAbiMethod } from '../tokens/tokens.interfaces'; -import { getHttpRequestOptions } from '../utils'; +import { getHttpRequestOptions, getWebsocketOptions } from '../utils'; import { Event, EventBatch, @@ -58,9 +58,7 @@ export class EventStreamSocket { this.disconnectDetected = false; this.closeRequested = false; - const auth = - this.username && this.password ? { auth: `${this.username}:${this.password}` } : undefined; - this.ws = new WebSocket(this.url, auth); + this.ws = new WebSocket(this.url, getWebsocketOptions(this.username, this.password)); this.ws .on('open', () => { if (this.disconnectDetected) { diff --git a/src/utils.ts b/src/utils.ts index 4faa0ce..2aa5db6 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -2,6 +2,7 @@ import * as fs from 'fs'; import * as https from 'https'; import { NestApplicationOptions } from '@nestjs/common'; import { AxiosRequestConfig } from 'axios'; +import { ClientOptions } from 'ws'; interface Certificates { key: string; @@ -29,6 +30,22 @@ const getCertificates = (): Certificates | undefined => { return { key, cert, ca }; }; +export const getWebsocketOptions = (username: string, password: string): ClientOptions => { + const requestOptions: ClientOptions = {}; + if (username && username !== '' && password && password !== '') { + requestOptions.headers = { + Authorization: `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`, + }; + } + const certs = getCertificates(); + if (certs) { + requestOptions.ca = certs.ca; + requestOptions.cert = certs.cert; + requestOptions.key = certs.key; + } + return requestOptions; +}; + export const getHttpRequestOptions = (username: string, password: string) => { const requestOptions: AxiosRequestConfig = {}; if (username !== '' && password !== '') {