@aikidosec/firewall
Version:
Zen by Aikido is an embedded Web Application Firewall that autonomously protects Node.js apps against common and critical attacks
35 lines (34 loc) • 1.38 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.addKoaMiddleware = addKoaMiddleware;
const shouldBlockRequest_1 = require("./shouldBlockRequest");
const escapeHTML_1 = require("../helpers/escapeHTML");
/**
* Calling this function will setup rate limiting and user blocking for the provided Express app.
* Attacks will still be blocked by Zen if you do not call this function.
* Execute this function as early as possible in your Express app, but after the middleware that sets the user.
*/
function addKoaMiddleware(app) {
app.use(async (ctx, next) => {
const result = (0, shouldBlockRequest_1.shouldBlockRequest)();
if (result.block) {
if (result.type === "ratelimited") {
let message = "You are rate limited by Zen.";
if (result.trigger === "ip" && result.ip) {
message += ` (Your IP: ${(0, escapeHTML_1.escapeHTML)(result.ip)})`;
}
ctx.type = "text/plain";
ctx.body = message;
ctx.status = 429;
return;
}
if (result.type === "blocked") {
ctx.type = "text/plain";
ctx.body = "You are blocked by Zen.";
ctx.status = 403;
return;
}
}
await next();
});
}