From 714da70209f95efcaa939405f062f6ea2eb930da Mon Sep 17 00:00:00 2001 From: Derrick Hammer Date: Tue, 18 Apr 2023 20:43:37 -0400 Subject: [PATCH] *refactor ssl support --- src/modules/relay.ts | 2 +- src/modules/ssl.ts | 45 +++++++++++++++++++++++++++++--------------- 2 files changed, 31 insertions(+), 16 deletions(-) diff --git a/src/modules/relay.ts b/src/modules/relay.ts index 53cdf82..a0f26fd 100644 --- a/src/modules/relay.ts +++ b/src/modules/relay.ts @@ -20,7 +20,7 @@ export async function start() { const dht = getSwarm(); let sslOptions: boolean | http2.SecureServerOptions = false; - if (getSslManager().enabled) { + if (getSslManager().ready) { sslOptions = { SNICallback: () => getSslManager().context, } as http2.SecureServerOptions; diff --git a/src/modules/ssl.ts b/src/modules/ssl.ts index a4f2da4..79a0d02 100644 --- a/src/modules/ssl.ts +++ b/src/modules/ssl.ts @@ -6,37 +6,47 @@ import config from "../config.js"; export type SSLManagerRenewHandler = (domain: string) => Promise; export class SSLManager { - private _context?: tls.SecureContext; private _key?: Buffer; - private _cert?: Buffer; private _domain: string; - private _renewHandler?: SSLManagerRenewHandler; constructor(domain: string) { this._domain = domain; } + private _context?: tls.SecureContext; + get context(): tls.SecureContext { return this._context as tls.SecureContext; } + private _cert?: Buffer; + + set cert(cert: Buffer) { + this._cert = cert; + this._maybeUpdateContext(); + } + + private _renewHandler?: SSLManagerRenewHandler; + + get renewHandler(): SSLManagerRenewHandler { + return this._renewHandler as any; + } + + set renewHandler(value: SSLManagerRenewHandler) { + this._renewHandler = value; + } + set privateKey(key: Buffer) { this._key = key; this._maybeUpdateContext(); } - set cert(cert: Buffer) { - this._cert = cert; - this._maybeUpdateContext(); + get enabled() { + return config.bool("core.ssl"); } - private _maybeUpdateContext() { - if (b4a.isBuffer(this._cert) && b4a.isBuffer(this._key)) { - this._context = tls.createSecureContext({ - cert: this._cert, - key: this._key, - }); - } + get ready() { + return this.enabled && this.renewHandler; } public async renew(): Promise { @@ -50,8 +60,13 @@ export class SSLManager { return result; } - get enabled() { - return config.bool("core.ssl") && this._renewHandler; + private _maybeUpdateContext() { + if (b4a.isBuffer(this._cert) && b4a.isBuffer(this._key)) { + this._context = tls.createSecureContext({ + cert: this._cert, + key: this._key, + }); + } } }