diff --git a/index.js b/index.js index eb94b4b..461abb2 100644 --- a/index.js +++ b/index.js @@ -114,7 +114,7 @@ function sign_object (obj, key, key_info = null) { * * @param {string} str string to verify * @param {string|(Object)=>string} key used key - * @param {number} timeout timeout (optional) + * @param {number|(Object)=>number} timeout timeout (optional) * @returns {any} returns object if successful, else null */ function verify_signature_get_info (str, key, timeout = 0) { @@ -129,9 +129,10 @@ function verify_signature_get_info (str, key, timeout = 0) { if (token !== verify_token) return null; const time = Date.now () - json.iat; - if (timeout !== 0 && time > timeout) - return null; - return json; + const num_timeout = typeof timeout === 'number' ? timeout : timeout (json); + if (num_timeout === 0 || time <= num_timeout) + return json; + return null; } /** @@ -139,7 +140,7 @@ function verify_signature_get_info (str, key, timeout = 0) { * * @param {string} str string to verify * @param {string|(Object)=>string} key used key - * @param {number} timeout timeout (optional) + * @param {number|(Object)=>number} timeout timeout (optional) * @returns {any} returns object if successful, else null */ function verify_signature (str, key, timeout = 0) { diff --git a/package.json b/package.json index 864d38c..6f01913 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@sapphirecode/crypto-helper", - "version": "1.2.0", + "version": "1.2.1", "main": "index.js", "author": { "name": "Timo Hocker", diff --git a/test/spec/index.js b/test/spec/index.js index f216f50..100fbc2 100644 --- a/test/spec/index.js +++ b/test/spec/index.js @@ -174,6 +174,14 @@ describe ('crypto helper', () => { .toEqual (dec); }); + it ('should verify signature using function retrieved timeout 0', () => { + const obj = { foo: 'bar' }; + const str = crypto.sign_object (obj, 'baz'); + const dec = crypto.verify_signature (str, 'baz', () => 0); + expect (obj) + .toEqual (dec); + }); + it ('should reject tampered signatures', () => { const obj = { foo: 'bar' }; const str = crypto.sign_object (obj, 'baz'); @@ -254,6 +262,27 @@ describe ('crypto helper', () => { .uninstall (); }); + it ('should verify signature using function retrieved timeout', () => { + jasmine.clock () + .install (); + const base_time = (new Date); + jasmine.clock () + .mockDate (base_time); + + const obj = { foo: 'bar' }; + const str = crypto.sign_object (obj, 'baz', { to: 100 }); + + jasmine.clock () + .tick (50); + + const dec = crypto.verify_signature (str, 'baz', (info) => info.to); + expect (obj) + .toEqual (dec); + + jasmine.clock () + .uninstall (); + }); + it ('verify_signature on almost timed out packet', () => { jasmine.clock () .install ();