unsecured.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import * as b64u from '../util/base64url.js';
  2. import { decoder } from '../lib/buffer_utils.js';
  3. import { JWTInvalid } from '../util/errors.js';
  4. import { validateClaimsSet, JWTClaimsBuilder } from '../lib/jwt_claims_set.js';
  5. export class UnsecuredJWT {
  6. #jwt;
  7. constructor(payload = {}) {
  8. this.#jwt = new JWTClaimsBuilder(payload);
  9. }
  10. encode() {
  11. const header = b64u.encode(JSON.stringify({ alg: 'none' }));
  12. const payload = b64u.encode(this.#jwt.data());
  13. return `${header}.${payload}.`;
  14. }
  15. setIssuer(issuer) {
  16. this.#jwt.iss = issuer;
  17. return this;
  18. }
  19. setSubject(subject) {
  20. this.#jwt.sub = subject;
  21. return this;
  22. }
  23. setAudience(audience) {
  24. this.#jwt.aud = audience;
  25. return this;
  26. }
  27. setJti(jwtId) {
  28. this.#jwt.jti = jwtId;
  29. return this;
  30. }
  31. setNotBefore(input) {
  32. this.#jwt.nbf = input;
  33. return this;
  34. }
  35. setExpirationTime(input) {
  36. this.#jwt.exp = input;
  37. return this;
  38. }
  39. setIssuedAt(input) {
  40. this.#jwt.iat = input;
  41. return this;
  42. }
  43. static decode(jwt, options) {
  44. if (typeof jwt !== 'string') {
  45. throw new JWTInvalid('Unsecured JWT must be a string');
  46. }
  47. const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt.split('.');
  48. if (length !== 3 || signature !== '') {
  49. throw new JWTInvalid('Invalid Unsecured JWT');
  50. }
  51. let header;
  52. try {
  53. header = JSON.parse(decoder.decode(b64u.decode(encodedHeader)));
  54. if (header.alg !== 'none')
  55. throw new Error();
  56. }
  57. catch {
  58. throw new JWTInvalid('Invalid Unsecured JWT');
  59. }
  60. const payload = validateClaimsSet(header, b64u.decode(encodedPayload), options);
  61. return { payload, header };
  62. }
  63. }