UNPKG

@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.

78 lines (77 loc) 2.54 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RawBody = void 0; const Context_1 = require("../agent/Context"); const wrapExport_1 = require("../agent/hooks/wrapExport"); /** * This helps detect attacks in frameworks that parse the body lazily inside handlers * rather than using middleware before the handler is invoked. * * Note: We only support promise-based usage of raw-body, callbacks are not supported yet. */ class RawBody { looksLikeJson(str) { return str.includes('"'); } tryUpdateContextBody(buffer) { if (!(buffer instanceof Buffer)) { return; } const context = (0, Context_1.getContext)(); if (!context) { return; } const str = new TextDecoder("utf-8").decode(buffer); if (!this.looksLikeJson(str)) { return; } try { const parsed = JSON.parse(str); // We expect the body to be read once per request, so it's fine to overwrite it (0, Context_1.updateContext)(context, "rawBody", parsed); } catch { // Not valid JSON, ignore } } onBodyParsed(_, returnValue) { if (returnValue instanceof Promise) { // Update context after the promise resolves, it won't change the original promise returnValue .then((buffer) => { this.tryUpdateContextBody(buffer); }) .catch(() => { // Ignore errors }); } return returnValue; } wrap(hooks) { hooks .addPackage("raw-body") .withVersion("^2.0.0 || ^3.0.0") .onRequire((exports, pkgInfo) => { return (0, wrapExport_1.wrapExport)(exports, undefined, pkgInfo, { kind: undefined, modifyReturnValue: (args, returnValue) => { return this.onBodyParsed(args, returnValue); }, }); }) .addFileInstrumentation({ path: "index.js", functions: [ { nodeType: "FunctionDeclaration", name: "getRawBody", operationKind: undefined, modifyReturnValue: (args, returnValue) => { return this.onBodyParsed(args, returnValue); }, }, ], }); } } exports.RawBody = RawBody;