UNPKG

offline-token-generator

Version:
91 lines 3.27 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var aes_js_1 = require("aes-js"); var js_sha512_1 = require("js-sha512"); var OfflineTokenGenerator = /** @class */ (function () { function OfflineTokenGenerator(key, aesBits, ttl, tolerance, timeGen) { if (ttl === void 0) { ttl = 5; } if (tolerance === void 0) { tolerance = 0; } if (timeGen === void 0) { timeGen = { getTime: function () { return new Date().getTime(); } }; } this.key = key; this.aesBits = aesBits; this.ttl = ttl; this.tolerance = tolerance; this.timeGen = timeGen; if (tolerance < 0) { throw new Error("tolerance must be >= 0"); } if (ttl < 1) { throw new Error("ttl must be >= 1"); } if (aesBits != 128 && aesBits != 192 && aesBits != 256) { throw new Error("aesBits must be 128 or 192 or 256"); } } OfflineTokenGenerator.prototype.getCurrentTime = function (tol) { if (tol > this.tolerance) { return -1; } var t = Math.floor(this.timeGen.getTime() / 1000); t -= (t % this.ttl); while (tol > 0) { t -= this.ttl; tol--; } return t; }; OfflineTokenGenerator.prototype.getKey = function (tol) { var t = this.getCurrentTime(tol); if (t == -1) { return null; } var hash = js_sha512_1.sha384.digest(t + "//" + this.key + "//" + this.aesBits + "//" + this.ttl + "//" + this.tolerance); return [hash.slice(0, this.aesBits / 8), hash.slice(32, 48)]; }; OfflineTokenGenerator.prototype.generate = function (value) { var envelope = [ Math.random(), value ]; var hash = this.getKey(0); var aesPass = hash[0]; var aesIV = hash[1]; var content = JSON.stringify(envelope); var padding = ''; while ((content.length + padding.length) % 16 > 0) { padding += ' '; } content = content + padding; return aes_js_1.utils.hex.fromBytes(new aes_js_1.ModeOfOperation.cbc(aesPass, aesIV).encrypt(aes_js_1.utils.utf8.toBytes(content))); }; OfflineTokenGenerator.prototype.doRead = function (tol, crypto) { var hash = this.getKey(tol); if (hash == null) { return null; } var aesPass = hash[0]; var aesIV = hash[1]; try { return JSON.parse(aes_js_1.utils.utf8.fromBytes(new aes_js_1.ModeOfOperation.cbc(aesPass, aesIV).decrypt(aes_js_1.utils.hex.toBytes(crypto)))); } catch (e) { return this.doRead(tol + 1, crypto); } }; OfflineTokenGenerator.prototype.read = function (crypto) { var json = this.doRead(0, crypto); if (json == null) { throw new Error("Expired token!"); } return json[1]; }; return OfflineTokenGenerator; }()); exports.OfflineTokenGenerator = OfflineTokenGenerator; //# sourceMappingURL=index.js.map