prepare.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. const VError = require('verror');
  2. module.exports = function (dependencies) {
  3. const { sign, decode, resolve } = dependencies;
  4. function prepareToken(options) {
  5. let keyData;
  6. try {
  7. keyData = resolve(options.key);
  8. } catch (err) {
  9. throw new VError(err, 'Failed loading token key');
  10. }
  11. try {
  12. const token = sign.bind(null, {}, keyData, {
  13. algorithm: 'ES256',
  14. issuer: options.teamId,
  15. header: { kid: options.keyId },
  16. });
  17. return {
  18. generation: 0,
  19. current: token(),
  20. iat: null,
  21. regenerate(generation) {
  22. if (generation === this.generation) {
  23. this.generation += 1;
  24. this.current = token();
  25. this.iat = null;
  26. }
  27. },
  28. isExpired(validSeconds) {
  29. if (this.iat == null) {
  30. const decoded = decode(this.current);
  31. this.iat = decoded.iat;
  32. }
  33. return Math.floor(Date.now() / 1000) - this.iat >= validSeconds;
  34. },
  35. };
  36. } catch (err) {
  37. throw new VError(err, 'Failed to generate token');
  38. }
  39. }
  40. return prepareToken;
  41. };