DiscordTickets/src/http.js

181 lines
5.0 KiB
JavaScript
Raw Normal View History

2023-02-01 23:19:48 +02:00
const fastify = require('fastify')({ trustProxy: process.env.HTTP_TRUST_PROXY === 'true' });
2022-05-06 23:17:53 +03:00
const oauth = require('@fastify/oauth2');
const { randomBytes } = require('crypto');
2022-05-06 02:12:38 +03:00
const { short } = require('leeks.js');
2022-05-06 02:01:19 +03:00
const { join } = require('path');
2022-07-18 15:34:29 +03:00
const { files } = require('node-dir');
2022-10-04 23:23:01 +03:00
const { PermissionsBitField } = require('discord.js');
2022-05-06 02:01:19 +03:00
process.env.ORIGIN = process.env.HTTP_EXTERNAL;
2022-09-06 22:30:28 +03:00
2022-09-06 22:46:18 +03:00
module.exports = async client => {
2022-05-06 23:17:53 +03:00
// oauth2 plugin
fastify.states = new Map();
2022-05-06 23:17:53 +03:00
fastify.register(oauth, {
2022-09-07 23:24:16 +03:00
callbackUri: `${process.env.HTTP_EXTERNAL}/auth/callback`,
checkStateFunction: (state, callback) => {
if (fastify.states.has(state)) {
callback();
return;
}
callback(new Error('Invalid state'));
},
2022-05-06 23:17:53 +03:00
credentials: {
auth: oauth.DISCORD_CONFIGURATION,
client: {
id: client.user.id,
secret: process.env.DISCORD_SECRET,
},
},
generateStateFunction: req => {
const state = randomBytes(12).toString('hex');
fastify.states.set(state, req.query.r);
return state;
},
2022-05-06 23:17:53 +03:00
name: 'discord',
scope: ['applications.commands.permissions.update', 'guilds', 'identify'],
2022-05-06 23:17:53 +03:00
startRedirectPath: '/auth/login',
});
// cookies plugin
fastify.register(require('@fastify/cookie'));
// jwt plugin
fastify.register(require('@fastify/jwt'), {
cookie: {
cookieName: 'token',
signed: false,
},
2022-07-16 01:19:42 +03:00
secret: process.env.ENCRYPTION_KEY,
2022-05-06 23:17:53 +03:00
});
// auth
fastify.decorate('authenticate', async (req, res) => {
try {
const data = await req.jwtVerify();
2023-03-13 00:21:21 +02:00
if (data.expiresAt < Date.now()) throw 'expired';
if (data.createdAt < new Date(process.env.INVALIDATE_TOKENS).getTime()) throw 'expired';
} catch (error) {
return res.code(401).send({
error: 'Unauthorised',
message: error === 'expired' ? 'Your token has expired; please re-authenticate.' : 'You are not authenticated.',
statusCode: 401,
});
2022-05-06 23:17:53 +03:00
}
});
2022-05-07 20:28:38 +03:00
fastify.decorate('isAdmin', async (req, res) => {
try {
2023-03-13 00:21:21 +02:00
const userId = req.user.id;
2022-05-07 20:28:38 +03:00
const guildId = req.params.guild;
const guild = client.guilds.cache.get(guildId);
2022-07-16 01:19:42 +03:00
if (!guild) {
return res.code(404).send({
error: 'Not Found',
message: 'The requested resource could not be found.',
statusCode: 404,
2022-05-07 20:28:38 +03:00
2022-07-16 01:19:42 +03:00
});
}
const guildMember = await guild.members.fetch(userId);
2022-10-04 23:23:01 +03:00
const isAdmin = guildMember?.permissions.has(PermissionsBitField.Flags.ManageGuild) || client.supers.includes(userId);
2022-07-18 23:53:17 +03:00
if (!isAdmin) {
2022-07-16 01:19:42 +03:00
return res.code(403).send({
error: 'Forbidden',
message: 'You are not permitted for this action.',
statusCode: 403,
2022-05-07 20:28:38 +03:00
});
}
} catch (err) {
res.send(err);
}
});
2022-07-18 23:53:17 +03:00
// body processing
fastify.addHook('preHandler', (req, res, done) => {
if (req.body && typeof req.body === 'object') {
for (const prop in req.body) {
if (typeof req.body[prop] === 'string') {
req.body[prop] = req.body[prop].trim();
}
}
}
done();
});
2022-05-06 23:17:53 +03:00
// logging
2022-05-06 02:12:38 +03:00
fastify.addHook('onResponse', (req, res, done) => {
done();
const status = (res.statusCode >= 500
? '&4'
: res.statusCode >= 400
? '&6'
: res.statusCode >= 300
? '&3'
: res.statusCode >= 200
? '&2'
: '&f') + res.statusCode;
2022-09-04 21:55:32 +03:00
let responseTime = res.getResponseTime().toFixed(2);
2023-05-24 18:24:19 +03:00
responseTime = (responseTime >= 100
2022-05-06 02:12:38 +03:00
? '&c'
2023-05-24 18:24:19 +03:00
: responseTime >= 10
2022-05-06 02:12:38 +03:00
? '&e'
2022-09-04 21:55:32 +03:00
: '&a') + responseTime + 'ms';
const level = req.routerPath === '/status'
? 'debug'
: req.routerPath === '/*'
? 'verbose'
: 'info';
2022-09-08 00:15:46 +03:00
client.log[level].http(short(`${req.id} ${req.ip} ${req.method} ${req.routerPath ?? '*'} &m-+>&r ${status}&b in ${responseTime}`));
2022-09-07 23:24:16 +03:00
if (!req.routerPath) client.log.verbose.http(`${req.id} ${req.method} ${req.url}`);
2022-05-06 23:17:53 +03:00
done();
2022-05-06 02:12:38 +03:00
});
2022-09-07 23:24:16 +03:00
fastify.addHook('onError', async (req, res, err) => client.log.error.http(req.id, err));
2022-05-06 23:17:53 +03:00
// route loading
2022-05-06 02:01:19 +03:00
const dir = join(__dirname, '/routes');
2022-07-18 15:34:29 +03:00
files(dir, {
exclude: /^\./,
match: /.js$/,
sync: true,
}).forEach(file => {
const path = file
.substring(0, file.length - 3) // remove `.js`
.substring(dir.length) // remove higher directories
2022-08-26 01:35:17 +03:00
.replace(/\\/g, '/') // replace `\` with `/` because Windows is stupid
2022-07-18 15:34:29 +03:00
.replace(/\[(\w+)\]/gi, ':$1') // convert [] to :
.replace('/index', '') || '/'; // remove index
const route = require(file);
2022-09-06 22:46:18 +03:00
2022-07-18 15:34:29 +03:00
Object.keys(route).forEach(method => fastify.route({
config: { client },
method: method.toUpperCase(),
path,
...route[method](fastify),
})); // register route
});
2022-05-06 02:01:19 +03:00
2022-09-06 22:30:28 +03:00
const { handler } = await import('@discord-tickets/settings/build/handler.js');
2023-03-11 01:47:43 +02:00
// https://stackoverflow.com/questions/72317071/how-to-set-up-fastify-correctly-so-that-sveltekit-works-fine
fastify.all('/*', {}, (req, res) => handler(req.raw, res.raw, () => { }));
2022-09-07 23:24:16 +03:00
// start the fastify server
2023-01-31 14:53:22 +02:00
fastify.listen({
2023-02-01 23:19:48 +02:00
host: process.env.HTTP_HOST,
port: process.env.HTTP_PORT,
2023-01-31 14:53:22 +02:00
}, (err, addr) => {
2022-09-07 23:24:16 +03:00
if (err) client.log.error.http(err);
else client.log.success.http(`Listening at ${addr}`);
2022-07-18 15:34:29 +03:00
});
2023-03-11 01:47:43 +02:00
process.on('sveltekit:error', ({
error,
errorId,
}) => {
client.log.error.http(`SvelteKit ${errorId} ${error}`);
});
2023-03-13 00:21:21 +02:00
};