How can I get the buffer of the raw request body in Hapijs?
Asked Answered
A

2

5

It's okay with using body-parser + expressjs. But my problem is: how can I get the buffer of the raw request body in Hapijs?

The thing I am talking to is like the buf param in this function of body-parser npm package: verify(req,res, buf, encoding)

I need it for this function in messenger-platform-samples example:

function verifyRequestSignature(req, res, buf) {
  var signature = req.headers["x-hub-signature"];
  if (!signature) {
    console.error("Couldn't validate the signature.");
  } else {
    var elements = signature.split('=');
    var method = elements[0];
    var signatureHash = elements[1];
    var expectedHash = crypto.createHmac('sha1', APP_SECRET)
                             .update(buf)
                             .digest('hex');
    if (signatureHash != expectedHash) {
      throw new Error("Couldn't validate the request signature.");
    }
  }
}

EDIT: I need to use this in my middle ware using server.ext(), like this:

server.ext({
  type: 'onRequest',
  method: (request, reply) => {
    var signature = request.headers["x-hub-signature"];

    if (!signature) {
      console.error("Couldn't validate the signature.");
    } else {
      var elements = signature.split('=');
      var method = elements[0];
      var signatureHash = elements[1];

      var expectedHash = crypto.createHmac('sha1', APP_SECRET)
                              .update(request.payload)
                              .digest('hex');

      if (signatureHash != expectedHash) {
        throw new Error("Couldn't validate the request signature.");
      }
      return reply.continue();
    }
  }
});
Arrowroot answered 5/3, 2017 at 4:24 Comment(0)
A
9

In [email protected]:

This is how you can get the raw buffer and the raw headers:

'use strict';

const Hapi = require('hapi');

const server = new Hapi.Server();
server.connection({
    host: 'localhost',
    port: 8000
});

server.route({
    method: 'POST',
    path:'/',
    handler: function (request, reply) {
        console.log(request.payload);
        console.log(request.raw.req.headers);
        return reply('hello world');
    },
    config: {
        payload: {
            output: 'data',
            parse: false
        }
    }
});

server.start((err) => {
    if (err) throw err;
    console.log('Server running at:', server.info.uri);
});

Running example:

$ curl -X POST 'http://localhost:8000/' -d name=nehaljwani --trace-ascii /dev/stdout
Note: Unnecessary use of -X or --request, POST is already inferred.
== Info:   Trying 127.0.0.1...
== Info: TCP_NODELAY set
== Info: Connected to localhost (127.0.0.1) port 8000 (#0)
=> Send header, 148 bytes (0x94)
0000: POST / HTTP/1.1
0011: Host: localhost:8000
0027: User-Agent: curl/7.51.0
0040: Accept: */*
004d: Content-Length: 15
0061: Content-Type: application/x-www-form-urlencoded
0092:
=> Send data, 15 bytes (0xf)
0000: name=nehaljwani
== Info: upload completely sent off: 15 out of 15 bytes
<= Recv header, 17 bytes (0x11)
0000: HTTP/1.1 200 OK
<= Recv header, 40 bytes (0x28)
0000: content-type: text/html; charset=utf-8
<= Recv header, 25 bytes (0x19)
0000: cache-control: no-cache
<= Recv header, 20 bytes (0x14)
0000: content-length: 11
<= Recv header, 23 bytes (0x17)
0000: vary: accept-encoding
<= Recv header, 37 bytes (0x25)
0000: Date: Sun, 05 Mar 2017 07:51:14 GMT
<= Recv header, 24 bytes (0x18)
0000: Connection: keep-alive
<= Recv header, 2 bytes (0x2)
0000:
<= Recv data, 11 bytes (0xb)
0000: hello world
== Info: Curl_http_done: called premature == 0
== Info: Connection #0 to host localhost left intact
hello world

Server output:

Server running at: http://localhost:8000
<Buffer 6e 61 6d 65 3d 6e 65 68 61 6c 6a 77 61 6e 69>
{ host: 'localhost:8000',
  'user-agent': 'curl/7.51.0',
  accept: '*/*',
  'content-length': '15',
  'content-type': 'application/x-www-form-urlencoded' }

To access the raw buffer, you will have to move it to route-prequisites. So the config for the route will look something like:

config: {
    pre: [
        {
            method: (request, reply) => {
                //signature verification steps
                return reply.continue();
            }
        }
    ],
    payload: {
        output: 'data',
        parse: false
    }
}
Agma answered 5/3, 2017 at 7:53 Comment(6)
Thank you so much. But in my handler, I need to use request.payload, so then I have to parse it myself?Arrowroot
@TrieuDang Unfortunately, yes. Because if you set parse to true, then I couldn't find any way to fetch the raw buffer. It seems to be engulfed :)Agma
But there's another problem now, that I want to use this buffer in a middle ware, not a handler. I am using server.ext() to define my middle ware, so how can I get this buffer?Arrowroot
@TrieuDang No, you won't be able to access the raw buffer in .ext. But you will be able to access it in route-prerequites . Read: hapijs.com/api/16.1.0#route-prerequisitesAgma
Thank you so much. There is a solution in my mind now. I will try it. But if you receive another notification from this question, please come back to help me haha :DArrowroot
Done. Thank sir!Arrowroot
S
1

I know this question is kinda old now, but I was facing the same problem recently and I found a solution that does not require me to give up automatic data parsing.

In a onRequest hook in a Plugin (you could do it directly on the request you are interested in), I have this code:

server.ext('onRequest', (request, h) => {
      const dataChunks: Buffer[] = [];

      request.raw.req.on('data', (chunk) => {
        dataChunks.push(chunk);
      });

      request.raw.req.on('end', () => {
        request.plugins['MyPlugin'] = {
          rawBody: Buffer.concat(dataChunks),
        };
      });

      return h.continue;
    });

And later on, in the preHandler hook, I can access the raw Buffer however I see fit from the request.plugins['MyPlugin'].rawBody property.

Sitology answered 10/3, 2022 at 20:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.