@aikidosec/firewall
Version:
Zen by Aikido is an embedded Web Application Firewall that autonomously protects Node.js apps against common and critical attacks
47 lines (46 loc) • 1.63 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.readBodyStream = readBodyStream;
const stream_1 = require("stream");
const getMaxBodySize_1 = require("../../helpers/getMaxBodySize");
const replaceRequestBody_1 = require("./replaceRequestBody");
async function readBodyStream(req, res, agent) {
let body = "";
let bodySize = 0;
const maxBodySize = (0, getMaxBodySize_1.getMaxBodySize)();
const stream = new stream_1.PassThrough();
try {
for await (const chunk of req) {
if (bodySize + chunk.length > maxBodySize) {
res.statusCode = 413;
res.end("This request was aborted by Aikido firewall because the body size exceeded the maximum allowed size. Use AIKIDO_MAX_BODY_SIZE_MB to increase the limit.", () => {
req.destroy();
});
agent.getInspectionStatistics().onAbortedRequest();
return {
success: false,
};
}
bodySize += chunk.length;
body += chunk.toString();
stream.push(chunk);
}
}
catch {
res.statusCode = 500;
res.end("Aikido firewall encountered an error while reading the request body.", () => {
req.destroy();
});
return {
success: false,
};
}
// End the stream
stream.push(null);
// Ensure the body stream can be read again by the application
(0, replaceRequestBody_1.replaceRequestBody)(req, stream);
return {
success: true,
body,
};
}