diff --git a/package.json b/package.json index 9329c98..3dc956a 100644 --- a/package.json +++ b/package.json @@ -14,6 +14,7 @@ "bluebird": "^3.5.0", "elliptic": "^6.4.0", "jsonwebtoken": "^7.4.1", - "jwk-to-pem": "^1.2.6" + "jwk-to-pem": "^1.2.6", + "ms": "^2.0.0" } } diff --git a/rest.js b/rest.js index 9384e23..6c96ea1 100644 --- a/rest.js +++ b/rest.js @@ -8,6 +8,22 @@ function makeB64UrlSafe(b64) { return b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=*$/, ''); } +function timespan(duration, max) { + var timestamp = Math.floor(Date.now() / 1000); + + if (typeof duration === 'string') { + duration = Math.floor(require('ms')(duration) / 1000); + } + if (typeof duration !== 'number') { + return timestamp; + } + + if (max && timestamp+duration > max) { + return max - timestamp; + } + return duration; +} + module.exports.create = function (bigconf, deps, app) { var Jwks = { restful: {} }; var Grants = { restful: {} }; @@ -445,16 +461,18 @@ module.exports.create = function (bigconf, deps, app) { kid: jwk.kid } }; + var accessOpts = {expiresIn: timespan(req.body.exp || '1d', token_info.exp)}; + var refreshOpts = {expiresIn: timespan(req.body.refresh_exp, token_info.exp)}; var jwt = require('jsonwebtoken'); var result = {}; result.scope = token_info.scope; - result.access_token = jwt.sign(payload, pem, Object.assign({expiresIn: req.body.exp || '1d'}, opts)); + result.access_token = jwt.sign(payload, pem, Object.assign(accessOpts, opts)); if (req.body.refresh_token) { if (token_info.refresh_token) { result.refresh_token = token_info.refresh_token; } else { - result.refresh_token = jwt.sign(payload, pem, Object.assign({expiresIn: req.body.refresh_exp}, opts)); + result.refresh_token = jwt.sign(payload, pem, Object.assign(refreshOpts, opts)); } } return result;