'use strict'; var PromiseA = require('bluebird'); var crypto = require('crypto'); module.exports.create = function (bigconf, deps, app) { var Jwks = { restful: {} }; function attachModels(req, res, next) { return req.getSiteStore().then(function (models) { req.Models = models; next(); }); } Jwks.thumbprint = function (jwk) { // To produce a thumbprint we need to create a JSON string with only the required keys for // the key type, with the keys sorted lexicographically and no white space. We then need // run it through a SHA-256 and encode the result in url safe base64. // https://stackoverflow.com/questions/42588786/how-to-fingerprint-a-jwk var keys; if (jwk.kty === 'EC') { keys = ['crv', 'x', 'y']; } else if (jwk.kty === 'RSA') { keys = ['e', 'n']; } else { return PromiseA.reject(new Error('invalid JWK key type ' + jwk.kty)); } keys.push('kty'); keys.sort(); var missing = keys.filter(function (name) { return !jwk.hasOwnProperty(name); }); if (missing.length > 0) { return PromiseA.reject(new Error('JWK of type '+jwk.kty+' missing fields ' + missing)); } // I'm not 100% sure this behavior is guaranteed by a real standard, but when we use an array // as the replacer argument the keys are always in the order they appeared in the array. var jwkStr = JSON.stringify(jwk, keys); var hash = crypto.createHash('sha256').update(jwkStr).digest('base64'); return PromiseA.resolve(hash.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+/g, '')); }; Jwks.restful.get = function (req, res) { var promise = req.Models.IssuerOauth3OrgJwks.find({ kid: req.params.kid }, { limit: 1 }).then(function (jwkArr) { var jwk = jwkArr[0]; // We need to sanitize the key to make sure we don't deliver any private keys fields if // we were given a key we could use to sign tokens on behalf of the user. var whitelist = [ 'kty', 'alg', 'kid', 'use' ]; if (jwk.kty === 'EC') { whitelist = whitelist.concat([ 'crv', 'x', 'y' ]); } else if (jwk.kty === 'RSA') { whitelist = whitelist.concat([ 'e', 'n' ]); } var result = {}; whitelist.forEach(function (key) { result[key] = jwk[key]; }); return result; }); app.handlePromise(req, res, promise, "[issuer@oauth3.org] retrieve JWK"); }; Jwks.restful.saveNew = function (req, res) { var jwk = req.body; var promise = Jwks.thumbprint(jwk).then(function (kid) { if (jwk.kid && jwk.kid !== kid) { throw new Error('provided kid "'+jwk.kid+'" does not match calculated "'+kid+'"'); } jwk.kid = kid; return req.Models.IssuerOauth3OrgJwks.upsert(req.params.sub, jwk); }).then(function () { return { success: true }; }); app.handlePromise(req, res, promise, "[issuer@oauth3.org] create JWK"); }; app.use( '/jwks', attachModels); app.get( '/jwks/:kid.json', Jwks.restful.get); app.post( '/jwks/:sub', Jwks.restful.saveNew); };