decode_protected_header.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334
  1. import { decode as base64url } from './base64url.js';
  2. import { decoder } from '../lib/buffer_utils.js';
  3. import isObject from '../lib/is_object.js';
  4. export function decodeProtectedHeader(token) {
  5. let protectedB64u;
  6. if (typeof token === 'string') {
  7. const parts = token.split('.');
  8. if (parts.length === 3 || parts.length === 5) {
  9. ;
  10. [protectedB64u] = parts;
  11. }
  12. }
  13. else if (typeof token === 'object' && token) {
  14. if ('protected' in token) {
  15. protectedB64u = token.protected;
  16. }
  17. else {
  18. throw new TypeError('Token does not contain a Protected Header');
  19. }
  20. }
  21. try {
  22. if (typeof protectedB64u !== 'string' || !protectedB64u) {
  23. throw new Error();
  24. }
  25. const result = JSON.parse(decoder.decode(base64url(protectedB64u)));
  26. if (!isObject(result)) {
  27. throw new Error();
  28. }
  29. return result;
  30. }
  31. catch (_a) {
  32. throw new TypeError('Invalid Token or Protected Header formatting');
  33. }
  34. }