diff --git a/lib/routes.js b/lib/routes.js index 6c6e3d47..2c338699 100644 --- a/lib/routes.js +++ b/lib/routes.js @@ -14,6 +14,8 @@ module.exports = { const STALE_TICKER = 3 * 60 * 1000 const STALE_BALANCE = 3 * 60 * 1000 +const CLOCK_SKEW = 60 * 1000 +const REQUEST_TTL = 3 * 60 * 1000 const pids = {} const reboots = {} @@ -301,7 +303,13 @@ function cacheAndRespond (req, res, _body, _status) { const body = _body || {} return updateCachedAction(req, body, status) - // .then(() => res.status(status).json(body)) + .then(() => res.status(status).json(body)) +} + +function pruneIdempotents () { + const sql = "delete from idempotents where created < now() - interval '24 hours'" + + return db.none(sql) } function httpError (msg, code) { @@ -312,6 +320,18 @@ function httpError (msg, code) { return err } +function filterOldRequests (req, res, next) { + const deviceTime = getDeviceTime(req) + const delta = Date.now() - deviceTime + + if (delta > CLOCK_SKEW) { + logger.error('Clock skew with lamassu-machine too high [%ss], adjust lamassu-machine clock', (delta / 1000).toFixed(2)) + } + + if (delta > REQUEST_TTL) return res.status(408).end() + next() +} + function init (opts) { plugins = opts.plugins @@ -319,6 +339,7 @@ function init (opts) { const app = opts.app const localApp = opts.localApp + app.use(filterOldRequests) app.post('*', cacheAction) app.post('/pair', pair) @@ -373,6 +394,8 @@ function init (opts) { .catch(logger.error) }) + setInterval(pruneIdempotents, 60000) + return app } diff --git a/todo.txt b/todo.txt index b8ac027b..e76b8375 100644 --- a/todo.txt +++ b/todo.txt @@ -117,4 +117,6 @@ v finish idempotency for all calls ------------- -test pending action (action needs to take a while so we can test) +- test pending action (action needs to take a while so we can test) +- defaults and validation +- tweak install script