Browse Source

Merge pull request #750 from oplexz/feat-koa

Replace Express with Koa
pull/792/head
Peter Lewis 3 years ago
committed by GitHub
parent
commit
a94a79df42
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 210
      src/lib/Server.js
  2. 35
      src/lib/Util.js
  3. 836
      src/package-lock.json
  4. 7
      src/package.json

210
src/lib/Server.js

@ -2,60 +2,64 @@
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 Koa = require('koa');
const Router = require('@koa/router');
const session = require('koa-session');
const bodyParser = require('koa-bodyparser');
const serve = require('koa-static');
const express = require('express');
const expressSession = require('express-session');
const debug = require('debug')('Server'); const debug = require('debug')('Server');
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(async (ctx, next) => {
resave: true, try {
saveUninitialized: true, await next();
cookie: { } catch (err) {
httpOnly: true, ctx.status = err.statusCode || err.status || 500;
}, ctx.body = { error: err.message };
})) ctx.app.emit('error', err, ctx);
}
.get('/api/release', (Util.promisify(async () => { })
return RELEASE; .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 // 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 +69,59 @@ 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}`); ctx.status = 204;
}))
debug(`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', Util.promisify(async (req) => { .delete('/api/session', async (ctx) => {
const sessionId = req.session.id; const sessionId = ctx.session.id;
req.session.destroy(); ctx.session = null;
ctx.status = 204;
debug(`Deleted Session: ${sessionId}`); debug(`Deleted Session: ${sessionId}`);
})) })
.get('/api/wireguard/client', Util.promisify(async (req) => { .get('/api/wireguard/client', async (ctx) => {
return WireGuard.getClients(); ctx.body = await WireGuard.getClients();
})) })
.get('/api/wireguard/client/:clientId/qrcode.svg', Util.promisify(async (req, res) => { .get('/api/wireguard/client/:clientId/qrcode.svg', async (ctx) => {
const { clientId } = req.params; const { clientId } = ctx.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 +129,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, () => {
debug(`Listening on http://${WEBUI_HOST}:${PORT}`);
});
} }
}; };

35
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,
} = {}) { } = {}) {

836
src/package-lock.json

File diff suppressed because it is too large

7
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"
}, },

Loading…
Cancel
Save