From 5553c2550dbccd954c5a1800979cdbb9f328d9f4 Mon Sep 17 00:00:00 2001 From: Nigelk Date: Tue, 14 Nov 2017 20:02:22 +0100 Subject: [PATCH] feat(opts): add opts param to verify, invalidate & cache functions --- index.js | 19 ++++++++++--------- package.json | 2 +- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/index.js b/index.js index 3740fb0..3cf0127 100644 --- a/index.js +++ b/index.js @@ -6,12 +6,12 @@ var d = exports.defaults = { var items = {}; -function cache(key) { - if(!items[key] || !d.cache) { +function cache(key, opts) { + if(!items[key] || !(opts && opts.cache || d.cache)) { if(Object.keys(items).length > 500) { items = {}; } - items[key] = crypto.createHmac('sha512', d.secret).update(key).digest('base64'); + items[key] = crypto.createHmac('sha512', opts && opts.secret || d.secret).update(key).digest('base64'); } return items[key]; } @@ -20,16 +20,17 @@ exports.INVALID = 0; exports.VALID = 1; exports.EXPIRING = 2; -exports.verify = function(data, hash) { +exports.verify = function(data, hash, opts) { if(typeof data !== 'string' || typeof hash !== 'string' ) { return false; } - var epoch = Math.floor(new Date().getTime() / 1000 / d.timeStep); // e.g. http://tools.ietf.org/html/rfc6238 + + var epoch = Math.floor(new Date().getTime() / 1000 / (opts && opts.timeStep || d.timeStep)); // e.g. http://tools.ietf.org/html/rfc6238 // allow data to be empty, always take into account the time - if (hash === cache(data + epoch) || hash === cache(data + (epoch + 1))) { + if (hash === cache(data + epoch, opts) || hash === cache(data + (epoch + 1), opts)) { return exports.VALID; // truthy, valid and current } - if (hash === cache(data + (epoch - 1))) { + if (hash === cache(data + (epoch - 1), opts)) { return exports.EXPIRING; // truthy, expired but still valid } return exports.INVALID; @@ -46,9 +47,9 @@ exports.generate = function(data, opts) { return crypto.createHmac('sha512', secret).update(data + epoch).digest('base64'); }; -exports.invalidate = function(data, hash) { +exports.invalidate = function(data, hash, opts) { var isValidHash = exports.verify(data, hash), - epoch = Math.floor(new Date().getTime() / 1000 / d.timeStep); + epoch = Math.floor(new Date().getTime() / 1000 / (opts && opts.timeStep || d.timeStep)); if (!isValidHash) { throw 'invalid hash'; diff --git a/package.json b/package.json index d4b43ac..3ac9ca7 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "token", - "version": "0.1.0", + "version": "0.2.0", "description": "HMAC token generation and verification with time-based limitation on validity", "author": "Mikito Takada ", "main": "index.js",