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