decode_jwt.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.decodeJwt = void 0;
  4. const base64url_js_1 = require("./base64url.js");
  5. const buffer_utils_js_1 = require("../lib/buffer_utils.js");
  6. const is_object_js_1 = require("../lib/is_object.js");
  7. const errors_js_1 = require("./errors.js");
  8. function decodeJwt(jwt) {
  9. if (typeof jwt !== 'string')
  10. throw new errors_js_1.JWTInvalid('JWTs must use Compact JWS serialization, JWT must be a string');
  11. const { 1: payload, length } = jwt.split('.');
  12. if (length === 5)
  13. throw new errors_js_1.JWTInvalid('Only JWTs using Compact JWS serialization can be decoded');
  14. if (length !== 3)
  15. throw new errors_js_1.JWTInvalid('Invalid JWT');
  16. if (!payload)
  17. throw new errors_js_1.JWTInvalid('JWTs must contain a payload');
  18. let decoded;
  19. try {
  20. decoded = (0, base64url_js_1.decode)(payload);
  21. }
  22. catch {
  23. throw new errors_js_1.JWTInvalid('Failed to base64url decode the payload');
  24. }
  25. let result;
  26. try {
  27. result = JSON.parse(buffer_utils_js_1.decoder.decode(decoded));
  28. }
  29. catch {
  30. throw new errors_js_1.JWTInvalid('Failed to parse the decoded payload as JSON');
  31. }
  32. if (!(0, is_object_js_1.default)(result))
  33. throw new errors_js_1.JWTInvalid('Invalid JWT Claims Set');
  34. return result;
  35. }
  36. exports.decodeJwt = decodeJwt;