UNPKG

spigot-anti-piracy-backend

Version:
84 lines (83 loc) 2.99 kB
#!/usr/bin/env node "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.app = void 0; const fs_1 = require("fs"); const path_1 = require("path"); const Koa = require("koa"); const bodyParser = require("koa-bodyparser"); const Router = require("@koa/router"); const winston_1 = require("winston"); exports.app = new Koa(); exports.app.proxy = Boolean(process.env.PROXY) || false; const router = new Router(); const logger = winston_1.createLogger({ format: winston_1.format.combine(winston_1.format.timestamp(), winston_1.format.splat(), winston_1.format.json()), }); logger.add(new winston_1.transports.File({ filename: process.env.LOG_FILE || path_1.join(__dirname, 'request.log'), maxFiles: 5, maxsize: 5000000, tailable: true, })); if (process.env.NODE_ENV !== 'test') { logger.add(new winston_1.transports.Console({ format: winston_1.format.simple(), })); } router.post('/', async (ctx, next) => { const body = ctx.request.body; if (!ctx.request.body || (!body.user_id && !body.userId)) { return (ctx.status = 400); } await handleAuthRequest(ctx); next(); }); async function handleAuthRequest(ctx) { const request = ctx.request; const body = request.body; const userId = body.user_id || body.userId; const ip = request.ip; const blacklisted = await isUserBlacklisted(userId); const response = { blacklisted, }; if (blacklisted) { ctx.status = 401; } logger.info('request from %s for user %s --> blacklisted %s', ip, userId, blacklisted, { blacklisted, ip, plugin: body.plugin, port: request.headers['bukkit-server-port'] || body.port, userId, }); ctx.set('Content-Type', 'application/json'); ctx.body = JSON.stringify(response); } async function isUserBlacklisted(userId) { const bannedFileLocation = process.env.BLACKLISTED_USERS_FILE || path_1.join(__dirname, 'banned_users.txt'); try { const bannedUsersFile = await fs_1.promises.readFile(bannedFileLocation, 'utf-8'); if (!bannedUsersFile) { return false; } const bannedUsers = bannedUsersFile.toString().match(/[^\r\n]+/g) || []; return bannedUsers.includes(userId); } catch { return false; } } exports.app.use(bodyParser()); exports.app.use(router.routes()); exports.app.use(router.allowedMethods()); const server = exports.app.listen(process.env.PORT || 3000, () => { const loggerFileLocation = process.env.LOG_FILE || path_1.join(__dirname, 'request.log'); const bannedFileLocation = process.env.BLACKLISTED_USERS_FILE || path_1.join(__dirname, 'banned_users.txt'); logger.info('Spigot Anti Piracy Backend listening at http://%s:%s', server.address().address, server.address().port); logger.info('Logging to %s', loggerFileLocation); logger.info('Using %s for blacklisted users', bannedFileLocation); });