Skip to content

Commit

Permalink
Add extensible ServerConfiguration in server interface
Browse files Browse the repository at this point in the history
nisargjhaveri committed Sep 1, 2024

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
1 parent 5db8c3d commit 2236b44
Showing 2 changed files with 16 additions and 10 deletions.
4 changes: 3 additions & 1 deletion src/server/command.ts
Original file line number Diff line number Diff line change
@@ -61,6 +61,8 @@ export const commandServer = {

const listenOptions = { port: args.port, host: args.host };

new Server(listenOptions, httpsOptions, args.password).start();
new Server(listenOptions, httpsOptions, {
password: args.password
}).start();
}
} as CommandModule;
22 changes: 13 additions & 9 deletions src/server/server.ts
Original file line number Diff line number Diff line change
@@ -18,27 +18,31 @@ declare module 'express-session' {
}
}

export type ServerConfiguration = {
password?: string;
}

export class Server {
private listenOptions: net.ListenOptions;
private httpsOptions: https.ServerOptions;
private password: string|undefined;
private httpsOptions: https.ServerOptions|undefined;
private serverConfig: ServerConfiguration|undefined;

private serverAddress: net.AddressInfo;
private server: (http.Server|https.Server) & stoppable.WithStop;

private wsKeepaliveInterval: NodeJS.Timer = undefined;

constructor(listenOptions: net.ListenOptions, httpsOptions?: https.ServerOptions, password?: string) {
constructor(listenOptions: net.ListenOptions, httpsOptions?: https.ServerOptions, serverConfig?: ServerConfiguration) {
this.listenOptions = listenOptions;
this.httpsOptions = httpsOptions;
this.password = password
this.serverConfig = serverConfig
}

private get loginSupported() {
return !!this.password;
return !!this.serverConfig?.password;
}

private loginRequried(req: Request) {
private loginRequired(req: Request) {
return this.loginSupported && !req.session.userId;
}

@@ -67,13 +71,13 @@ export class Server {
res.json({
result: "OK",
loginSupported: this.loginSupported,
loginRequired: this.loginRequried(req)
loginRequired: this.loginRequired(req)
});
res.end();
});

app.post('/login', (req, res) => {
if (!this.loginSupported || req.body.password === this.password) {
if (!this.loginSupported || req.body.password === this.serverConfig.password) {
req.session.regenerate(() => {
req.session.userId = "user";

@@ -110,7 +114,7 @@ export class Server {
server.on('upgrade', (request: any, socket: net.Socket, head) => {
// This function is not defined on purpose. Implement it with your own logic.
sessionParser(request, {} as any, () => {
if (this.loginRequried(request)) {
if (this.loginRequired(request)) {
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
socket.destroy();
return;

0 comments on commit 2236b44

Please sign in to comment.