Browse Source

Replace Express with Koa

pull/750/head
Daniil Isakov 3 years ago
parent
commit
32eabe5d4c
  1. 205
      src/lib/Server.js
  2. 37
      src/lib/Util.js
  3. 838
      src/package-lock.json
  4. 9
      src/package.json

205
src/lib/Server.js

@ -2,60 +2,53 @@
const path = require('path');
const bcrypt = require('bcryptjs');
const crypto = require('node:crypto');
const crypto = require('crypto');
const express = require('express');
const expressSession = require('express-session');
const debug = require('debug')('Server');
const Koa = require('koa');
const Router = require('@koa/router');
const session = require('koa-session');
const bodyParser = require('koa-bodyparser');
const serve = require('koa-static');
const Util = require('./Util');
const ServerError = require('./ServerError');
const WireGuard = require('../services/WireGuard');
const {
PORT,
WEBUI_HOST,
RELEASE,
PASSWORD,
PORT, WEBUI_HOST, RELEASE, PASSWORD,
} = require('../config');
module.exports = class Server {
constructor() {
// Express
this.app = express()
.disable('etag')
.use('/', express.static(path.join(__dirname, '..', 'www')))
.use(express.json())
.use(expressSession({
secret: crypto.randomBytes(256).toString('hex'),
resave: true,
saveUninitialized: true,
cookie: {
httpOnly: true,
},
}))
.get('/api/release', (Util.promisify(async () => {
return RELEASE;
})))
this.app = new Koa();
this.router = new Router();
this.app.keys = [crypto.randomBytes(256).toString('hex')];
this.app
.use(serve(path.join(__dirname, '..', 'www')))
.use(bodyParser())
.use(session(this.app))
.use(this.router.routes())
.use(this.router.allowedMethods());
this.router
.get('/api/release', async (ctx) => {
ctx.body = RELEASE;
})
// Authentication
.get('/api/session', Util.promisify(async (req) => {
.get('/api/session', async (ctx) => {
const requiresPassword = !!process.env.PASSWORD;
const authenticated = requiresPassword
? !!(req.session && req.session.authenticated)
: true;
const authenticated = requiresPassword ? !!(ctx.session && ctx.session.authenticated) : true;
return {
ctx.body = {
requiresPassword,
authenticated,
};
}))
.post('/api/session', Util.promisify(async (req) => {
const {
password,
} = req.body;
})
.post('/api/session', async (ctx) => {
const { password } = ctx.request.body;
if (typeof password !== 'string') {
throw new ServerError('Missing: Password', 401);
@ -65,53 +58,55 @@ module.exports = class Server {
throw new ServerError('Incorrect Password', 401);
}
req.session.authenticated = true;
req.session.save();
ctx.session.authenticated = true;
debug(`New Session: ${req.session.id}`);
}))
console.log(`New Session: ${ctx.session.id}`);
})
// WireGuard
.use((req, res, next) => {
.use(async (ctx, next) => {
if (!PASSWORD) {
return next();
}
if (req.session && req.session.authenticated) {
if (ctx.session && ctx.session.authenticated) {
return next();
}
if (req.path.startsWith('/api/') && req.headers['authorization']) {
if (bcrypt.compareSync(req.headers['authorization'], bcrypt.hashSync(PASSWORD, 10))) {
if (ctx.path.startsWith('/api/') && ctx.headers['authorization']) {
if (bcrypt.compareSync(ctx.headers['authorization'], bcrypt.hashSync(PASSWORD, 10))) {
return next();
}
return res.status(401).json({
ctx.status = 401;
ctx.body = {
error: 'Incorrect Password',
});
};
return;
}
return res.status(401).json({
ctx.status = 401;
ctx.body = {
error: 'Not Logged In',
});
};
})
.delete('/api/session', async (ctx) => {
const sessionId = ctx.session.id;
ctx.session = null;
console.log(`Deleted Session: ${sessionId}`);
})
.delete('/api/session', Util.promisify(async (req) => {
const sessionId = req.session.id;
req.session.destroy();
debug(`Deleted Session: ${sessionId}`);
}))
.get('/api/wireguard/client', Util.promisify(async (req) => {
return WireGuard.getClients();
}))
.get('/api/wireguard/client/:clientId/qrcode.svg', Util.promisify(async (req, res) => {
const { clientId } = req.params;
.get('/api/wireguard/client', async (ctx) => {
ctx.body = await WireGuard.getClients();
})
.get('/api/wireguard/client/:clientId/qrcode.svg', async (ctx) => {
const { clientId } = ctx.params;
const svg = await WireGuard.getClientQRCodeSVG({ clientId });
res.header('Content-Type', 'image/svg+xml');
res.send(svg);
}))
.get('/api/wireguard/client/:clientId/configuration', Util.promisify(async (req, res) => {
const { clientId } = req.params;
ctx.set('Content-Type', 'image/svg+xml');
ctx.body = svg;
})
.get('/api/wireguard/client/:clientId/configuration', async (ctx) => {
const { clientId } = ctx.params;
const client = await WireGuard.getClient({ clientId });
const config = await WireGuard.getClientConfiguration({ clientId });
const configName = client.name
@ -119,52 +114,56 @@ module.exports = class Server {
.replace(/(-{2,}|-$)/g, '-')
.replace(/-$/, '')
.substring(0, 32);
res.header('Content-Disposition', `attachment; filename="${configName || clientId}.conf"`);
res.header('Content-Type', 'text/plain');
res.send(config);
}))
.post('/api/wireguard/client', Util.promisify(async (req) => {
const { name } = req.body;
return WireGuard.createClient({ name });
}))
.delete('/api/wireguard/client/:clientId', Util.promisify(async (req) => {
const { clientId } = req.params;
return WireGuard.deleteClient({ clientId });
}))
.post('/api/wireguard/client/:clientId/enable', Util.promisify(async (req, res) => {
const { clientId } = req.params;
ctx.set('Content-Disposition', `attachment; filename="${configName || clientId}.conf"`);
ctx.set('Content-Type', 'text/plain');
ctx.body = config;
})
.post('/api/wireguard/client', async (ctx) => {
const { name } = ctx.request.body;
ctx.body = await WireGuard.createClient({ name });
})
.delete('/api/wireguard/client/:clientId', async (ctx) => {
const { clientId } = ctx.params;
ctx.body = await WireGuard.deleteClient({ clientId });
})
.post('/api/wireguard/client/:clientId/enable', async (ctx) => {
const { clientId } = ctx.params;
if (clientId === '__proto__' || clientId === 'constructor' || clientId === 'prototype') {
res.end(403);
ctx.status = 403;
return;
}
return WireGuard.enableClient({ clientId });
}))
.post('/api/wireguard/client/:clientId/disable', Util.promisify(async (req, res) => {
const { clientId } = req.params;
ctx.body = await WireGuard.enableClient({ clientId });
})
.post('/api/wireguard/client/:clientId/disable', async (ctx) => {
const { clientId } = ctx.params;
if (clientId === '__proto__' || clientId === 'constructor' || clientId === 'prototype') {
res.end(403);
ctx.status = 403;
return;
}
return WireGuard.disableClient({ clientId });
}))
.put('/api/wireguard/client/:clientId/name', Util.promisify(async (req, res) => {
const { clientId } = req.params;
ctx.body = await WireGuard.disableClient({ clientId });
})
.put('/api/wireguard/client/:clientId/name', async (ctx) => {
const { clientId } = ctx.params;
if (clientId === '__proto__' || clientId === 'constructor' || clientId === 'prototype') {
res.end(403);
ctx.status = 403;
return;
}
const { name } = req.body;
return WireGuard.updateClientName({ clientId, name });
}))
.put('/api/wireguard/client/:clientId/address', Util.promisify(async (req, res) => {
const { clientId } = req.params;
const { name } = ctx.request.body;
ctx.body = await WireGuard.updateClientName({ clientId, name });
})
.put('/api/wireguard/client/:clientId/address', async (ctx) => {
const { clientId } = ctx.params;
if (clientId === '__proto__' || clientId === 'constructor' || clientId === 'prototype') {
res.end(403);
ctx.status = 403;
return;
}
const { address } = req.body;
return WireGuard.updateClientAddress({ clientId, address });
}))
.listen(PORT, WEBUI_HOST, () => {
debug(`Listening on http://${WEBUI_HOST}:${PORT}`);
const { address } = ctx.request.body;
ctx.body = await WireGuard.updateClientAddress({ clientId, address });
});
this.app.listen(PORT, WEBUI_HOST, () => {
console.log(`Listening on http://${WEBUI_HOST}:${PORT}`);
});
}
};
};

37
src/lib/Util.js

@ -17,41 +17,6 @@ module.exports = class Util {
return true;
}
static promisify(fn) {
// eslint-disable-next-line func-names
return function(req, res) {
Promise.resolve().then(async () => fn(req, res))
.then((result) => {
if (res.headersSent) return;
if (typeof result === 'undefined') {
return res
.status(204)
.end();
}
return res
.status(200)
.json(result);
})
.catch((error) => {
if (typeof error === 'string') {
error = new Error(error);
}
// eslint-disable-next-line no-console
console.error(error);
return res
.status(error.statusCode || 500)
.json({
error: error.message || error.toString(),
stack: error.stack,
});
});
};
}
static async exec(cmd, {
log = true,
} = {}) {
@ -77,4 +42,4 @@ module.exports = class Util {
});
}
};
};

838
src/package-lock.json

File diff suppressed because it is too large

9
src/package.json

@ -13,10 +13,13 @@
"author": "Emile Nijssen",
"license": "GPL",
"dependencies": {
"@koa/router": "^12.0.1",
"bcryptjs": "^2.4.3",
"debug": "^4.3.4",
"express": "^4.18.2",
"express-session": "^1.17.3",
"koa": "^2.15.0",
"koa-bodyparser": "^4.4.1",
"koa-session": "^6.4.0",
"koa-static": "^5.0.0",
"qrcode": "^1.5.3",
"uuid": "^9.0.1"
},
@ -32,4 +35,4 @@
"engines": {
"node": "18"
}
}
}
Loading…
Cancel
Save