diff --git a/lib/tunnel-client-manager.js b/lib/tunnel-client-manager.js index 1b099a4..4d40c7f 100644 --- a/lib/tunnel-client-manager.js +++ b/lib/tunnel-client-manager.js @@ -27,6 +27,22 @@ module.exports.create = function (deps, config) { return fs.writeFileAsync(tokensPath, JSON.stringify(tokens), 'utf8'); }); } + , _makeKey: function (token) { + // We use a stripped down version of the token contents so that if the token is + // re-issued the nonce and the iat and any other less important things are different + // we don't save essentially duplicate tokens multiple times. + var parsed = JSON.parse((new Buffer(token.split('.')[1], 'base64')).toString()); + var stripped = {}; + ['aud', 'iss', 'domains'].forEach(function (key) { + if (parsed[key]) { + stripped[key] = parsed[key]; + } + }); + stripped.domains.sort(); + + var hash = require('crypto').createHash('sha256'); + return hash.update(JSON.stringify(stripped)).digest('hex'); + } , all: function () { var tokens = storage._read(); @@ -34,15 +50,19 @@ module.exports.create = function (deps, config) { return tokens[key]; })); } - , save: function (result) { - var tokens = storage._read(); - tokens[result.jwt] = result; - storage._write(tokens); + , save: function (token) { + return PromiseA.resolve().then(function () { + var curTokens = storage._read(); + curTokens[storage._makeKey(token)] = token; + return storage._write(curTokens); + }); } - , del: function (id) { - var tokens = storage._read(); - delete tokens[id]; - storage._write(tokens); + , del: function (token) { + return PromiseA.resolve().then(function () { + var curTokens = storage._read(); + delete curTokens[storage._makeKey(token)]; + return storage._write(curTokens); + }); } };