Skip to content

Commit

Permalink
feat: Add connection object to IncomingMessage
Browse files Browse the repository at this point in the history
  • Loading branch information
yvele committed Dec 9, 2016
1 parent 868f2ce commit 57eaf49
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 2 deletions.
23 changes: 23 additions & 0 deletions src/createIncomingMessage.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,28 @@ import EventEmitter from "events";

const NOOP = () => {};

function removePortFromAddress(address) {
return address
? address.replace(/:[0-9]*$/, "")
: address;
}

/**
* Create a fake connection object
*
* @param {Object} context Azure context object for a single HTTP request.
* @returns {object} Connection object
*/
function createConnectionObject(context) {
const req = context.bindings.req;
const xForwardedFor = req.headers ? req.headers["x-forwarded-for"] : undefined;

return {
encrypted : req.originalUrl && req.originalUrl.toLowerCase().startsWith("https"),
remoteAddress : removePortFromAddress(xForwardedFor)
};
}

/**
* @private
*/
Expand All @@ -24,6 +46,7 @@ class IncomingMessage extends EventEmitter {
this._readableState = { pipesCount: 0 }; // To make unpipe happy
this.resume = NOOP;
this.socket = { destroy: NOOP };
this.connection = createConnectionObject(context);

// Extra content
this.context = { log: context.log.bind(context) };
Expand Down
35 changes: 33 additions & 2 deletions test/createIncomingMessage.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,46 @@ describe("createIncomingMessage", () => {
it("Should work", () => {

const context = {
bindings : { req: { originalUrl: "http://foo.com/bar" } },
log : () => {}
bindings : {
req : {
originalUrl : "https://foo.com/bar",
headers : { "x-forwarded-for": "192.168.0.1:57996" }
}
},
log : () => {}
};

const incomingMessag = createIncomingMessage(context);

incomingMessag.resume();
incomingMessag.socket.destroy();
incomingMessag.url.should.eql("https://foo.com/bar");
incomingMessag.connection.should.eql({
encrypted : true,
remoteAddress : "192.168.0.1"
});
});

it("Should work with no headers", () => {

const context = {
bindings : {
req : {
originalUrl : "http://foo.com/bar"
}
},
log : () => {}
};

const incomingMessag = createIncomingMessage(context);

incomingMessag.resume();
incomingMessag.socket.destroy();
incomingMessag.url.should.eql("http://foo.com/bar");
incomingMessag.connection.should.eql({
encrypted : false,
remoteAddress : undefined
});
});

});

0 comments on commit 57eaf49

Please sign in to comment.