@aikidosec/firewall
Version:
Zen by Aikido is an embedded Application Firewall that autonomously protects Node.js apps against common and critical attacks, provides rate limiting, detects malicious traffic (including bots), and more.
68 lines (67 loc) • 2.84 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.wrapOnHeaders = wrapOnHeaders;
exports.wrapOnResponseStart = wrapOnResponseStart;
const parseHeaders_1 = require("./parseHeaders");
const isRedirectStatusCode_1 = require("../../helpers/isRedirectStatusCode");
const onRedirect_1 = require("./onRedirect");
/**
* Wrap the onHeaders function and check if the response is a redirect. If yes, determine the destination URL and call onRedirect.
* This is the undici v6 / legacy handler API
*/
function wrapOnHeaders(orig, requestContext, context) {
// @ts-expect-error We return undefined if there is no original function, that's fine because the onHeaders function is optional
return function onHeaders() {
const args = Array.from(arguments);
if (args.length > 1) {
const statusCode = args[0];
if ((0, isRedirectStatusCode_1.isRedirectStatusCode)(statusCode)) {
try {
// Get redirect location
const headers = (0, parseHeaders_1.parseHeaders)(args[1]);
if (typeof headers.location === "string") {
const destinationUrl = new URL(headers.location);
(0, onRedirect_1.onRedirect)(destinationUrl, requestContext, context);
}
}
catch {
// Ignore, log later if we have log levels
}
}
}
if (orig) {
return orig.apply(
// @ts-expect-error We don't know the type of this
this,
// @ts-expect-error Arguments are not typed
arguments);
}
};
}
/**
* Wrap the onResponseStart function (undici v7 / Node.js v26+ handler API) and check if the response is a redirect.
* Headers are passed as a plain object with lowercase keys instead of a Buffer array.
*/
function wrapOnResponseStart(orig, requestContext, context) {
return function onResponseStart(_controller, statusCode, headers) {
if ((0, isRedirectStatusCode_1.isRedirectStatusCode)(statusCode)) {
try {
const location = headers === null || headers === void 0 ? void 0 : headers.location;
if (typeof location === "string") {
const destinationUrl = new URL(location);
(0, onRedirect_1.onRedirect)(destinationUrl, requestContext, context);
}
}
catch {
// Ignore, log later if we have log levels
}
}
if (orig) {
return orig.apply(
// @ts-expect-error We don't know the type of this
this,
// @ts-expect-error Arguments are not typed
arguments);
}
};
}