@aikidosec/firewall
Version:
Zen by Aikido is an embedded Web Application Firewall that autonomously protects Node.js apps against common and critical attacks
42 lines (41 loc) • 1.62 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.wrapNewInstance = wrapNewInstance;
const AgentSingleton_1 = require("../AgentSingleton");
const wrapDefaultOrNamed_1 = require("./wrapDefaultOrNamed");
/**
* Intercepts the creation of a new instance of a class, to wrap it's methods and properties.
*/
function wrapNewInstance(subject, className, pkgInfo, interceptor) {
const agent = (0, AgentSingleton_1.getInstance)();
if (!agent) {
throw new Error("Can not wrap new instance if agent is not initialized");
}
try {
return (0, wrapDefaultOrNamed_1.wrapDefaultOrNamed)(subject, className, function wrap(original) {
return function wrap() {
// eslint-disable-next-line prefer-rest-params
const args = Array.from(arguments);
// @ts-expect-error It's a constructor
const newInstance = new original(...args);
try {
const returnVal = interceptor(newInstance);
if (returnVal) {
return returnVal;
}
}
catch (error) {
if (error instanceof Error) {
agent.onFailedToWrapMethod(pkgInfo.name, className || "default export", error);
}
}
return newInstance;
};
});
}
catch (error) {
if (error instanceof Error) {
agent.onFailedToWrapMethod(pkgInfo.name, className || "default export", error);
}
}
}