diff --git a/API.md b/API.md index f55afff..eec1212 100644 --- a/API.md +++ b/API.md @@ -158,13 +158,19 @@ Request(requestOptions, function (error, response, body) { }); ``` -**Hawk** utilized the [**SNTP**](https://github.com/hueniverse/sntp) module for time sync management. By default, the local -machine time is used. To automatically retrieve and synchronize the clock within the application, use the SNTP 'start()' method. +## Time Sync + +**Hawk** can utilize the [`@hapi/sntp`](https://github.com/outmoded/sntp) module for time sync management. +By default, the local machine time is used. +To automatically retrieve and synchronize the clock within the application, add `@hapi/sntp` to your application and initialize it at the top level: ```js -Hawk.sntp.start(); -``` +const Sntp = require('@hapi/sntp'); +const Hawk = require('hawk'); +Sntp.start(); +Hawk.utils.setTimeFunction(Sntp.now) +``` ## Protocol Example diff --git a/lib/index.js b/lib/index.js index e61925c..97ee3ca 100755 --- a/lib/index.js +++ b/lib/index.js @@ -1,8 +1,6 @@ 'use strict'; -exports.sntp = require('@hapi/sntp'); - exports.server = require('./server'); exports.client = require('./client'); diff --git a/lib/utils.js b/lib/utils.js index 9c26cd8..11ff55a 100755 --- a/lib/utils.js +++ b/lib/utils.js @@ -1,7 +1,6 @@ 'use strict'; const Boom = require('@hapi/boom'); -const Sntp = require('@hapi/sntp'); const internals = {}; @@ -93,9 +92,20 @@ exports.parseRequest = function (req, options) { }; +let _now = Date.now; + + +// override the `now` function, e.g., to use sntp + +exports.setTimeFunction = function (fn) { + + _now = fn; +}; + + exports.now = function (localtimeOffsetMsec) { - return Sntp.now() + (localtimeOffsetMsec || 0); + return _now() + (localtimeOffsetMsec || 0); }; diff --git a/package.json b/package.json index 394ad6a..d0fad29 100755 --- a/package.json +++ b/package.json @@ -17,8 +17,7 @@ "@hapi/b64": "5.x.x", "@hapi/boom": "9.x.x", "@hapi/cryptiles": "5.x.x", - "@hapi/hoek": "9.x.x", - "@hapi/sntp": "4.x.x" + "@hapi/hoek": "9.x.x" }, "devDependencies": { "@hapi/code": "8.x.x", diff --git a/test/utils.js b/test/utils.js index 410cafd..252b35b 100755 --- a/test/utils.js +++ b/test/utils.js @@ -10,7 +10,7 @@ const Package = require('../package.json'); const internals = {}; -const { describe, it } = exports.lab = Lab.script(); +const { describe, it, after } = exports.lab = Lab.script(); const expect = Code.expect; @@ -119,6 +119,20 @@ describe('Utils', () => { }); }); + describe('setTimeFunction()', () => { + + after(() => { + + Hawk.utils.setTimeFunction(Date.now); + }); + + it('creates the value that now() will return', () => { + + Hawk.utils.setTimeFunction(() => 269323200000); + expect(Hawk.utils.now()).to.equal(269323200000); + }); + }); + describe('unauthorized()', () => { it('returns a hawk 401', () => {