Created
February 25, 2016 20:01
-
-
Save tstachl/20e51a0871e34ab4bacf to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function base64UrlDecode(str) { | |
str = (str + '===').slice(0, str.length + (str.length % 4)); | |
return new Buffer(str.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); | |
} | |
function readSecret() { | |
return process.env.DESK_SHARED_KEY; | |
} | |
module.exports = { | |
parse: function(request, max_age) { | |
max_age = (max_age || 3600) * 1000; | |
var encodedSignature = request.split('.')[0] | |
, encodedEnvelope = request.split('.')[1] | |
, envelope = JSON.parse(base64UrlDecode(encoded_envelope)) | |
, algorithm = envelope.algorithm | |
, hex = crypto.createHmac('sha256', readSecret()).update(encoded_envelope).digest('base64') | |
, decodedSignature = base64UrlDecode(encodedSignature) | |
if (algorithm !== 'HMACSHA256') { | |
throw Error('Invalid request. (Unsupported algorithm.)'); | |
} | |
if (Date.parse(envelope.issuedAt) + max_age) < Date.now()) { | |
throw Error('Invalid request. (Too old.)'); | |
} | |
if (decodedSignature !== hex) { | |
throw Error('Invalid request. (Invalid signature.)'); | |
} | |
return envelope; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment