jwt.js 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. var __defProp = Object.defineProperty;
  2. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  3. var __getOwnPropNames = Object.getOwnPropertyNames;
  4. var __hasOwnProp = Object.prototype.hasOwnProperty;
  5. var __export = (target, all) => {
  6. for (var name in all)
  7. __defProp(target, name, { get: all[name], enumerable: true });
  8. };
  9. var __copyProps = (to, from, except, desc) => {
  10. if (from && typeof from === "object" || typeof from === "function") {
  11. for (let key of __getOwnPropNames(from))
  12. if (!__hasOwnProp.call(to, key) && key !== except)
  13. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  14. }
  15. return to;
  16. };
  17. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  18. var jwt_exports = {};
  19. __export(jwt_exports, {
  20. decode: () => decode,
  21. decodeHeader: () => decodeHeader,
  22. isTokenHeader: () => isTokenHeader,
  23. sign: () => sign,
  24. verify: () => verify,
  25. verifyWithJwks: () => verifyWithJwks
  26. });
  27. module.exports = __toCommonJS(jwt_exports);
  28. var import_encode = require("../../utils/encode");
  29. var import_jwa = require("./jwa");
  30. var import_jws = require("./jws");
  31. var import_types = require("./types");
  32. var import_utf8 = require("./utf8");
  33. const encodeJwtPart = (part) => (0, import_encode.encodeBase64Url)(import_utf8.utf8Encoder.encode(JSON.stringify(part)).buffer).replace(/=/g, "");
  34. const encodeSignaturePart = (buf) => (0, import_encode.encodeBase64Url)(buf).replace(/=/g, "");
  35. const decodeJwtPart = (part) => JSON.parse(import_utf8.utf8Decoder.decode((0, import_encode.decodeBase64Url)(part)));
  36. function isTokenHeader(obj) {
  37. if (typeof obj === "object" && obj !== null) {
  38. const objWithAlg = obj;
  39. return "alg" in objWithAlg && Object.values(import_jwa.AlgorithmTypes).includes(objWithAlg.alg) && (!("typ" in objWithAlg) || objWithAlg.typ === "JWT");
  40. }
  41. return false;
  42. }
  43. const sign = async (payload, privateKey, alg = "HS256") => {
  44. const encodedPayload = encodeJwtPart(payload);
  45. let encodedHeader;
  46. if (typeof privateKey === "object" && "alg" in privateKey) {
  47. alg = privateKey.alg;
  48. encodedHeader = encodeJwtPart({ alg, typ: "JWT", kid: privateKey.kid });
  49. } else {
  50. encodedHeader = encodeJwtPart({ alg, typ: "JWT" });
  51. }
  52. const partialToken = `${encodedHeader}.${encodedPayload}`;
  53. const signaturePart = await (0, import_jws.signing)(privateKey, alg, import_utf8.utf8Encoder.encode(partialToken));
  54. const signature = encodeSignaturePart(signaturePart);
  55. return `${partialToken}.${signature}`;
  56. };
  57. const verify = async (token, publicKey, algOrOptions) => {
  58. if (!algOrOptions) {
  59. throw new import_types.JwtAlgorithmRequired();
  60. }
  61. const {
  62. alg,
  63. iss,
  64. nbf = true,
  65. exp = true,
  66. iat = true,
  67. aud
  68. } = typeof algOrOptions === "string" ? { alg: algOrOptions } : algOrOptions;
  69. if (!alg) {
  70. throw new import_types.JwtAlgorithmRequired();
  71. }
  72. const tokenParts = token.split(".");
  73. if (tokenParts.length !== 3) {
  74. throw new import_types.JwtTokenInvalid(token);
  75. }
  76. const { header, payload } = decode(token);
  77. if (!isTokenHeader(header)) {
  78. throw new import_types.JwtHeaderInvalid(header);
  79. }
  80. if (header.alg !== alg) {
  81. throw new import_types.JwtAlgorithmMismatch(alg, header.alg);
  82. }
  83. const now = Math.floor(Date.now() / 1e3);
  84. if (nbf && payload.nbf && payload.nbf > now) {
  85. throw new import_types.JwtTokenNotBefore(token);
  86. }
  87. if (exp && payload.exp && payload.exp <= now) {
  88. throw new import_types.JwtTokenExpired(token);
  89. }
  90. if (iat && payload.iat && now < payload.iat) {
  91. throw new import_types.JwtTokenIssuedAt(now, payload.iat);
  92. }
  93. if (iss) {
  94. if (!payload.iss) {
  95. throw new import_types.JwtTokenIssuer(iss, null);
  96. }
  97. if (typeof iss === "string" && payload.iss !== iss) {
  98. throw new import_types.JwtTokenIssuer(iss, payload.iss);
  99. }
  100. if (iss instanceof RegExp && !iss.test(payload.iss)) {
  101. throw new import_types.JwtTokenIssuer(iss, payload.iss);
  102. }
  103. }
  104. if (aud) {
  105. if (!payload.aud) {
  106. throw new import_types.JwtPayloadRequiresAud(payload);
  107. }
  108. const audiences = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
  109. const matched = audiences.some(
  110. (payloadAud) => aud instanceof RegExp ? aud.test(payloadAud) : typeof aud === "string" ? payloadAud === aud : Array.isArray(aud) && aud.includes(payloadAud)
  111. );
  112. if (!matched) {
  113. throw new import_types.JwtTokenAudience(aud, payload.aud);
  114. }
  115. }
  116. const headerPayload = token.substring(0, token.lastIndexOf("."));
  117. const verified = await (0, import_jws.verifying)(
  118. publicKey,
  119. alg,
  120. (0, import_encode.decodeBase64Url)(tokenParts[2]),
  121. import_utf8.utf8Encoder.encode(headerPayload)
  122. );
  123. if (!verified) {
  124. throw new import_types.JwtTokenSignatureMismatched(token);
  125. }
  126. return payload;
  127. };
  128. const symmetricAlgorithms = [
  129. import_jwa.AlgorithmTypes.HS256,
  130. import_jwa.AlgorithmTypes.HS384,
  131. import_jwa.AlgorithmTypes.HS512
  132. ];
  133. const verifyWithJwks = async (token, options, init) => {
  134. const verifyOpts = options.verification || {};
  135. const header = decodeHeader(token);
  136. if (!isTokenHeader(header)) {
  137. throw new import_types.JwtHeaderInvalid(header);
  138. }
  139. if (!header.kid) {
  140. throw new import_types.JwtHeaderRequiresKid(header);
  141. }
  142. if (symmetricAlgorithms.includes(header.alg)) {
  143. throw new import_types.JwtSymmetricAlgorithmNotAllowed(header.alg);
  144. }
  145. if (!options.allowedAlgorithms.includes(header.alg)) {
  146. throw new import_types.JwtAlgorithmNotAllowed(header.alg, options.allowedAlgorithms);
  147. }
  148. let verifyKeys = options.keys ? [...options.keys] : void 0;
  149. if (options.jwks_uri) {
  150. const response = await fetch(options.jwks_uri, init);
  151. if (!response.ok) {
  152. throw new Error(`failed to fetch JWKS from ${options.jwks_uri}`);
  153. }
  154. const data = await response.json();
  155. if (!data.keys) {
  156. throw new Error('invalid JWKS response. "keys" field is missing');
  157. }
  158. if (!Array.isArray(data.keys)) {
  159. throw new Error('invalid JWKS response. "keys" field is not an array');
  160. }
  161. verifyKeys ??= [];
  162. verifyKeys.push(...data.keys);
  163. } else if (!verifyKeys) {
  164. throw new Error('verifyWithJwks requires options for either "keys" or "jwks_uri" or both');
  165. }
  166. const matchingKey = verifyKeys.find((key) => key.kid === header.kid);
  167. if (!matchingKey) {
  168. throw new import_types.JwtTokenInvalid(token);
  169. }
  170. if (matchingKey.alg && matchingKey.alg !== header.alg) {
  171. throw new import_types.JwtAlgorithmMismatch(matchingKey.alg, header.alg);
  172. }
  173. return await verify(token, matchingKey, {
  174. alg: header.alg,
  175. ...verifyOpts
  176. });
  177. };
  178. const decode = (token) => {
  179. const parts = token.split(".");
  180. if (parts.length !== 3) {
  181. throw new import_types.JwtTokenInvalid(token);
  182. }
  183. try {
  184. const header = decodeJwtPart(parts[0]);
  185. const payload = decodeJwtPart(parts[1]);
  186. return {
  187. header,
  188. payload
  189. };
  190. } catch {
  191. throw new import_types.JwtTokenInvalid(token);
  192. }
  193. };
  194. const decodeHeader = (token) => {
  195. const parts = token.split(".");
  196. if (parts.length !== 3) {
  197. throw new import_types.JwtTokenInvalid(token);
  198. }
  199. try {
  200. return decodeJwtPart(parts[0]);
  201. } catch {
  202. throw new import_types.JwtTokenInvalid(token);
  203. }
  204. };
  205. // Annotate the CommonJS export names for ESM import in node:
  206. 0 && (module.exports = {
  207. decode,
  208. decodeHeader,
  209. isTokenHeader,
  210. sign,
  211. verify,
  212. verifyWithJwks
  213. });