Skip to content

Commit f260d73

Browse files
committed
fix: abstracting uWebsocket server creation to its own protected method
[ci skip]
1 parent 953efbc commit f260d73

1 file changed

Lines changed: 25 additions & 14 deletions

File tree

src/websockets/WebSocketServer.ts

Lines changed: 25 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -127,20 +127,7 @@ class WebSocketServer {
127127
}): Promise<void> {
128128
this.logger.info(`Starting ${this.constructor.name}`);
129129
this.connectionCallback = connectionCallback;
130-
const tmpDir = await this.fs.promises.mkdtemp(
131-
path.join(basePath, 'polykey-'),
132-
);
133-
// TODO: The key file needs to be in the encrypted format
134-
const keyFile = path.join(tmpDir, 'keyFile.pem');
135-
const certFile = path.join(tmpDir, 'certFile.pem');
136-
await this.fs.promises.writeFile(keyFile, tlsConfig.keyPrivatePem);
137-
await this.fs.promises.writeFile(certFile, tlsConfig.certChainPem);
138-
this.server = uWebsocket.SSLApp({
139-
key_file_name: keyFile,
140-
cert_file_name: certFile,
141-
});
142-
await this.fs.promises.rm(keyFile);
143-
await this.fs.promises.rm(certFile);
130+
await this.setupServer(basePath, tlsConfig);
144131
this.server.ws('/*', {
145132
sendPingsAutomatically: true,
146133
idleTimeout: this.idleTimeout,
@@ -206,6 +193,30 @@ class WebSocketServer {
206193
return uWebsocket.us_socket_local_port(this.listenSocket);
207194
}
208195

196+
/**
197+
* This creates the pem files and starts the server with them. It ensures that
198+
* files are cleaned up to the best of its ability.
199+
*/
200+
protected async setupServer(basePath: string, tlsConfig: TLSConfig) {
201+
const tmpDir = await this.fs.promises.mkdtemp(
202+
path.join(basePath, 'polykey-'),
203+
);
204+
// TODO: The key file needs to be in the encrypted format
205+
const keyFile = path.join(tmpDir, 'keyFile.pem');
206+
const certFile = path.join(tmpDir, 'certFile.pem');
207+
try {
208+
await this.fs.promises.writeFile(keyFile, tlsConfig.keyPrivatePem);
209+
await this.fs.promises.writeFile(certFile, tlsConfig.certChainPem);
210+
this.server = uWebsocket.SSLApp({
211+
key_file_name: keyFile,
212+
cert_file_name: certFile,
213+
});
214+
} finally {
215+
await this.fs.promises.rm(keyFile);
216+
await this.fs.promises.rm(certFile);
217+
}
218+
}
219+
209220
/**
210221
* Applies default upgrade behaviour and creates a UserData object we can
211222
* mutate for the Context

0 commit comments

Comments
 (0)