Browse Source

Fixup koa (#792)

pull/794/head
Philip H 3 years ago
committed by GitHub
parent
commit
62265fa061
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 204
      src/lib/Server.js
  2. 836
      src/package-lock.json
  3. 7
      src/package.json

204
src/lib/Server.js

@ -2,13 +2,16 @@
const path = require('path');
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 Util = require('./Util');
const ServerError = require('./ServerError');
const WireGuard = require('../services/WireGuard');
@ -23,44 +26,48 @@ const {
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(async (ctx, next) => {
try {
await next();
} catch (err) {
ctx.status = err.statusCode || err.status || 500;
ctx.body = { error: err.message };
ctx.app.emit('error', err, ctx);
}
})
.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;
})
.get('/api/lang', (Util.promisify(async () => {
return LANG;
})))
// 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);
@ -70,53 +77,58 @@ module.exports = class Server {
throw new ServerError('Incorrect Password', 401);
}
req.session.authenticated = true;
req.session.save();
ctx.session.authenticated = true;
ctx.session.save();
debug(`New Session: ${req.session.id}`);
}))
debug(`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', Util.promisify(async (req) => {
const sessionId = req.session.id;
.delete('/api/session', async (ctx) => {
const sessionId = ctx.session.id;
req.session.destroy();
ctx.session = null;
ctx.status = 204;
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
@ -124,52 +136,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, () => {
debug(`Listening on http://${WEBUI_HOST}:${PORT}`);
});
}
};

836
src/package-lock.json

File diff suppressed because it is too large

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

Loading…
Cancel
Save