@aikidosec/firewall
Version:
Zen by Aikido is an embedded Web Application Firewall that autonomously protects Node.js apps against common and critical attacks
64 lines (63 loc) • 2.43 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.FunctionsFramework = void 0;
exports.createCloudFunctionWrapper = createCloudFunctionWrapper;
const AgentSingleton_1 = require("../agent/AgentSingleton");
const Context_1 = require("../agent/Context");
const wrapExport_1 = require("../agent/hooks/wrapExport");
function createCloudFunctionWrapper(fn) {
const agent = (0, AgentSingleton_1.getInstance)();
let lastFlushStatsAt = undefined;
const flushEveryMS = 10 * 60 * 1000;
return async (req, res) => {
return await (0, Context_1.runWithContext)({
method: req.method,
remoteAddress: req.ip,
body: req.body ? req.body : undefined,
url: req.protocol + "://" + req.get("host") + req.originalUrl,
headers: req.headers,
query: req.query,
/* c8 ignore next */
cookies: req.cookies ? req.cookies : {},
routeParams: {},
source: "cloud-function/http",
route: undefined,
}, async () => {
try {
return await fn(req, res);
}
finally {
const context = (0, Context_1.getContext)();
if (agent && context) {
const stats = agent.getInspectionStatistics();
stats.onRequest();
if (lastFlushStatsAt === undefined ||
lastFlushStatsAt + flushEveryMS < performance.now()) {
await agent.flushStats(1000);
lastFlushStatsAt = performance.now();
}
}
}
});
};
}
class FunctionsFramework {
wrap(hooks) {
hooks
.addPackage("@google-cloud/functions-framework")
.withVersion("^4.0.0 || ^3.0.0")
.onRequire((exports, pkgInfo) => {
(0, wrapExport_1.wrapExport)(exports, "http", pkgInfo, {
kind: undefined,
modifyArgs: (args) => {
if (args.length === 2 && typeof args[1] === "function") {
const httpFunction = args[1];
args[1] = createCloudFunctionWrapper(httpFunction);
}
return args;
},
});
});
}
}
exports.FunctionsFramework = FunctionsFramework;