Skip to content

Instantly share code, notes, and snippets.

@tstachl
Created February 25, 2016 20:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tstachl/20e51a0871e34ab4bacf to your computer and use it in GitHub Desktop.
Save tstachl/20e51a0871e34ab4bacf to your computer and use it in GitHub Desktop.
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