From 5e1d13749d1c3d919fa4193286aafd00f7fcf009 Mon Sep 17 00:00:00 2001 From: yago Date: Sun, 12 Jul 2015 16:50:07 +0200 Subject: [PATCH] WebHook request bot token can be anywhere on the URL request. Tests --- src/telegram.js | 23 +++++++++++++++++------ test/index.js | 28 +++++++++++++++++++++++++++- 2 files changed, 44 insertions(+), 7 deletions(-) diff --git a/src/telegram.js b/src/telegram.js index 61a4c19..7c464b7 100644 --- a/src/telegram.js +++ b/src/telegram.js @@ -74,24 +74,35 @@ TelegramBot.prototype._configureWebHook = function (port, host, key, cert) { TelegramBot.prototype._requestListener = function (req, res) { var self = this; - var url = '/bot'+this.token; - if (req.url === url && req.method === 'POST') { + var regex = new RegExp(this.token); + + debug('WebHook request URL:', req.url); + debug('WebHook request headers: %j', req.headers); + // If there isn't token on URL + if (!regex.test(req.url)) { + debug('WebHook request unauthorized'); + res.statusCode = 401; + res.end(); + } else if (req.method === 'POST') { var fullBody = ''; req.on('data', function (chunk) { fullBody += chunk.toString(); }); req.on('end', function () { try { + debug('WebHook request fullBody', fullBody); var data = JSON.parse(fullBody); self.offset = data.update_id; self.emit('message', data.message); } catch (error) { - console.error(error); + debug(error); } - res.end('OK :P\n'); + res.end('OK'); }); - } else { - res.end('OK\n'); + } else { // Authorized but not a POST + debug('WebHook request isn\'t a POST'); + res.statusCode = 418; // I'm a teabot! + res.end(); } }; diff --git a/test/index.js b/test/index.js index 4bf5ad1..be00311 100644 --- a/test/index.js +++ b/test/index.js @@ -31,7 +31,7 @@ describe('Telegram', function () { }); }); - describe('#emit', function () { + describe('#Polling', function () { it('should emit a `message` on polling', function (done) { var bot = new Telegram(TOKEN); bot.on('message', function (msg) { @@ -50,6 +50,32 @@ describe('Telegram', function () { }; bot._polling(); }); + }); + + describe('#WebHook', function () { + it('should reject request if same token not provided', function (done) { + var bot = new Telegram(TOKEN, {webHook: true}); + request({ + url: 'http://localhost:8443/NOT_REAL_TOKEN', + method: 'POST' + }, function (error, response, body) { + response.statusCode.should.not.be.equal(200); + bot._webServer.close(); + done(); + }); + }); + + it('should reject request if authorized but not a POST', function (done) { + var bot = new Telegram(TOKEN, {webHook: true}); + request({ + url: 'http://localhost:8443/bot'+TOKEN, + method: 'GET' + }, function (error, response, body) { + response.statusCode.should.not.be.equal(200); + bot._webServer.close(); + done(); + }); + }); it('should emit a `message` on HTTP WebHook', function (done) { var bot = new Telegram(TOKEN, {webHook: true});