jwt_claims_set.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. import { JWTClaimValidationFailed, JWTExpired, JWTInvalid } from '../util/errors.js';
  2. import { encoder, decoder } from './buffer_utils.js';
  3. import { isObject } from './type_checks.js';
  4. const epoch = (date) => Math.floor(date.getTime() / 1000);
  5. const minute = 60;
  6. const hour = minute * 60;
  7. const day = hour * 24;
  8. const week = day * 7;
  9. const year = day * 365.25;
  10. const REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;
  11. export function secs(str) {
  12. const matched = REGEX.exec(str);
  13. if (!matched || (matched[4] && matched[1])) {
  14. throw new TypeError('Invalid time period format');
  15. }
  16. const value = parseFloat(matched[2]);
  17. const unit = matched[3].toLowerCase();
  18. let numericDate;
  19. switch (unit) {
  20. case 'sec':
  21. case 'secs':
  22. case 'second':
  23. case 'seconds':
  24. case 's':
  25. numericDate = Math.round(value);
  26. break;
  27. case 'minute':
  28. case 'minutes':
  29. case 'min':
  30. case 'mins':
  31. case 'm':
  32. numericDate = Math.round(value * minute);
  33. break;
  34. case 'hour':
  35. case 'hours':
  36. case 'hr':
  37. case 'hrs':
  38. case 'h':
  39. numericDate = Math.round(value * hour);
  40. break;
  41. case 'day':
  42. case 'days':
  43. case 'd':
  44. numericDate = Math.round(value * day);
  45. break;
  46. case 'week':
  47. case 'weeks':
  48. case 'w':
  49. numericDate = Math.round(value * week);
  50. break;
  51. default:
  52. numericDate = Math.round(value * year);
  53. break;
  54. }
  55. if (matched[1] === '-' || matched[4] === 'ago') {
  56. return -numericDate;
  57. }
  58. return numericDate;
  59. }
  60. function validateInput(label, input) {
  61. if (!Number.isFinite(input)) {
  62. throw new TypeError(`Invalid ${label} input`);
  63. }
  64. return input;
  65. }
  66. const normalizeTyp = (value) => {
  67. if (value.includes('/')) {
  68. return value.toLowerCase();
  69. }
  70. return `application/${value.toLowerCase()}`;
  71. };
  72. const checkAudiencePresence = (audPayload, audOption) => {
  73. if (typeof audPayload === 'string') {
  74. return audOption.includes(audPayload);
  75. }
  76. if (Array.isArray(audPayload)) {
  77. return audOption.some(Set.prototype.has.bind(new Set(audPayload)));
  78. }
  79. return false;
  80. };
  81. export function validateClaimsSet(protectedHeader, encodedPayload, options = {}) {
  82. let payload;
  83. try {
  84. payload = JSON.parse(decoder.decode(encodedPayload));
  85. }
  86. catch {
  87. }
  88. if (!isObject(payload)) {
  89. throw new JWTInvalid('JWT Claims Set must be a top-level JSON object');
  90. }
  91. const { typ } = options;
  92. if (typ &&
  93. (typeof protectedHeader.typ !== 'string' ||
  94. normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) {
  95. throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, 'typ', 'check_failed');
  96. }
  97. const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;
  98. const presenceCheck = [...requiredClaims];
  99. if (maxTokenAge !== undefined)
  100. presenceCheck.push('iat');
  101. if (audience !== undefined)
  102. presenceCheck.push('aud');
  103. if (subject !== undefined)
  104. presenceCheck.push('sub');
  105. if (issuer !== undefined)
  106. presenceCheck.push('iss');
  107. for (const claim of new Set(presenceCheck.reverse())) {
  108. if (!(claim in payload)) {
  109. throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, 'missing');
  110. }
  111. }
  112. if (issuer &&
  113. !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) {
  114. throw new JWTClaimValidationFailed('unexpected "iss" claim value', payload, 'iss', 'check_failed');
  115. }
  116. if (subject && payload.sub !== subject) {
  117. throw new JWTClaimValidationFailed('unexpected "sub" claim value', payload, 'sub', 'check_failed');
  118. }
  119. if (audience &&
  120. !checkAudiencePresence(payload.aud, typeof audience === 'string' ? [audience] : audience)) {
  121. throw new JWTClaimValidationFailed('unexpected "aud" claim value', payload, 'aud', 'check_failed');
  122. }
  123. let tolerance;
  124. switch (typeof options.clockTolerance) {
  125. case 'string':
  126. tolerance = secs(options.clockTolerance);
  127. break;
  128. case 'number':
  129. tolerance = options.clockTolerance;
  130. break;
  131. case 'undefined':
  132. tolerance = 0;
  133. break;
  134. default:
  135. throw new TypeError('Invalid clockTolerance option type');
  136. }
  137. const { currentDate } = options;
  138. const now = epoch(currentDate || new Date());
  139. if ((payload.iat !== undefined || maxTokenAge) && typeof payload.iat !== 'number') {
  140. throw new JWTClaimValidationFailed('"iat" claim must be a number', payload, 'iat', 'invalid');
  141. }
  142. if (payload.nbf !== undefined) {
  143. if (typeof payload.nbf !== 'number') {
  144. throw new JWTClaimValidationFailed('"nbf" claim must be a number', payload, 'nbf', 'invalid');
  145. }
  146. if (payload.nbf > now + tolerance) {
  147. throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, 'nbf', 'check_failed');
  148. }
  149. }
  150. if (payload.exp !== undefined) {
  151. if (typeof payload.exp !== 'number') {
  152. throw new JWTClaimValidationFailed('"exp" claim must be a number', payload, 'exp', 'invalid');
  153. }
  154. if (payload.exp <= now - tolerance) {
  155. throw new JWTExpired('"exp" claim timestamp check failed', payload, 'exp', 'check_failed');
  156. }
  157. }
  158. if (maxTokenAge) {
  159. const age = now - payload.iat;
  160. const max = typeof maxTokenAge === 'number' ? maxTokenAge : secs(maxTokenAge);
  161. if (age - tolerance > max) {
  162. throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, 'iat', 'check_failed');
  163. }
  164. if (age < 0 - tolerance) {
  165. throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, 'iat', 'check_failed');
  166. }
  167. }
  168. return payload;
  169. }
  170. export class JWTClaimsBuilder {
  171. #payload;
  172. constructor(payload) {
  173. if (!isObject(payload)) {
  174. throw new TypeError('JWT Claims Set MUST be an object');
  175. }
  176. this.#payload = structuredClone(payload);
  177. }
  178. data() {
  179. return encoder.encode(JSON.stringify(this.#payload));
  180. }
  181. get iss() {
  182. return this.#payload.iss;
  183. }
  184. set iss(value) {
  185. this.#payload.iss = value;
  186. }
  187. get sub() {
  188. return this.#payload.sub;
  189. }
  190. set sub(value) {
  191. this.#payload.sub = value;
  192. }
  193. get aud() {
  194. return this.#payload.aud;
  195. }
  196. set aud(value) {
  197. this.#payload.aud = value;
  198. }
  199. set jti(value) {
  200. this.#payload.jti = value;
  201. }
  202. set nbf(value) {
  203. if (typeof value === 'number') {
  204. this.#payload.nbf = validateInput('setNotBefore', value);
  205. }
  206. else if (value instanceof Date) {
  207. this.#payload.nbf = validateInput('setNotBefore', epoch(value));
  208. }
  209. else {
  210. this.#payload.nbf = epoch(new Date()) + secs(value);
  211. }
  212. }
  213. set exp(value) {
  214. if (typeof value === 'number') {
  215. this.#payload.exp = validateInput('setExpirationTime', value);
  216. }
  217. else if (value instanceof Date) {
  218. this.#payload.exp = validateInput('setExpirationTime', epoch(value));
  219. }
  220. else {
  221. this.#payload.exp = epoch(new Date()) + secs(value);
  222. }
  223. }
  224. set iat(value) {
  225. if (value === undefined) {
  226. this.#payload.iat = epoch(new Date());
  227. }
  228. else if (value instanceof Date) {
  229. this.#payload.iat = validateInput('setIssuedAt', epoch(value));
  230. }
  231. else if (typeof value === 'string') {
  232. this.#payload.iat = validateInput('setIssuedAt', epoch(new Date()) + secs(value));
  233. }
  234. else {
  235. this.#payload.iat = validateInput('setIssuedAt', value);
  236. }
  237. }
  238. }