unsecured.js 1.3 KB

1234567891011121314151617181920212223242526272829303132
  1. import * as base64url from '../runtime/base64url.js';
  2. import { decoder } from '../lib/buffer_utils.js';
  3. import { JWTInvalid } from '../util/errors.js';
  4. import jwtPayload from '../lib/jwt_claims_set.js';
  5. import { ProduceJWT } from './produce.js';
  6. export class UnsecuredJWT extends ProduceJWT {
  7. encode() {
  8. const header = base64url.encode(JSON.stringify({ alg: 'none' }));
  9. const payload = base64url.encode(JSON.stringify(this._payload));
  10. return `${header}.${payload}.`;
  11. }
  12. static decode(jwt, options) {
  13. if (typeof jwt !== 'string') {
  14. throw new JWTInvalid('Unsecured JWT must be a string');
  15. }
  16. const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt.split('.');
  17. if (length !== 3 || signature !== '') {
  18. throw new JWTInvalid('Invalid Unsecured JWT');
  19. }
  20. let header;
  21. try {
  22. header = JSON.parse(decoder.decode(base64url.decode(encodedHeader)));
  23. if (header.alg !== 'none')
  24. throw new Error();
  25. }
  26. catch (_a) {
  27. throw new JWTInvalid('Invalid Unsecured JWT');
  28. }
  29. const payload = jwtPayload(header, base64url.decode(encodedPayload), options);
  30. return { payload, header };
  31. }
  32. }