remote.js 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. import { JOSEError, JWKSNoMatchingKey, JWKSTimeout } from '../util/errors.js';
  2. import { createLocalJWKSet } from './local.js';
  3. import { isObject } from '../lib/type_checks.js';
  4. function isCloudflareWorkers() {
  5. return (typeof WebSocketPair !== 'undefined' ||
  6. (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') ||
  7. (typeof EdgeRuntime !== 'undefined' && EdgeRuntime === 'vercel'));
  8. }
  9. let USER_AGENT;
  10. if (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) {
  11. const NAME = 'jose';
  12. const VERSION = 'v6.2.2';
  13. USER_AGENT = `${NAME}/${VERSION}`;
  14. }
  15. export const customFetch = Symbol();
  16. async function fetchJwks(url, headers, signal, fetchImpl = fetch) {
  17. const response = await fetchImpl(url, {
  18. method: 'GET',
  19. signal,
  20. redirect: 'manual',
  21. headers,
  22. }).catch((err) => {
  23. if (err.name === 'TimeoutError') {
  24. throw new JWKSTimeout();
  25. }
  26. throw err;
  27. });
  28. if (response.status !== 200) {
  29. throw new JOSEError('Expected 200 OK from the JSON Web Key Set HTTP response');
  30. }
  31. try {
  32. return await response.json();
  33. }
  34. catch {
  35. throw new JOSEError('Failed to parse the JSON Web Key Set HTTP response as JSON');
  36. }
  37. }
  38. export const jwksCache = Symbol();
  39. function isFreshJwksCache(input, cacheMaxAge) {
  40. if (typeof input !== 'object' || input === null) {
  41. return false;
  42. }
  43. if (!('uat' in input) || typeof input.uat !== 'number' || Date.now() - input.uat >= cacheMaxAge) {
  44. return false;
  45. }
  46. if (!('jwks' in input) ||
  47. !isObject(input.jwks) ||
  48. !Array.isArray(input.jwks.keys) ||
  49. !Array.prototype.every.call(input.jwks.keys, isObject)) {
  50. return false;
  51. }
  52. return true;
  53. }
  54. class RemoteJWKSet {
  55. #url;
  56. #timeoutDuration;
  57. #cooldownDuration;
  58. #cacheMaxAge;
  59. #jwksTimestamp;
  60. #pendingFetch;
  61. #headers;
  62. #customFetch;
  63. #local;
  64. #cache;
  65. constructor(url, options) {
  66. if (!(url instanceof URL)) {
  67. throw new TypeError('url must be an instance of URL');
  68. }
  69. this.#url = new URL(url.href);
  70. this.#timeoutDuration =
  71. typeof options?.timeoutDuration === 'number' ? options?.timeoutDuration : 5000;
  72. this.#cooldownDuration =
  73. typeof options?.cooldownDuration === 'number' ? options?.cooldownDuration : 30000;
  74. this.#cacheMaxAge = typeof options?.cacheMaxAge === 'number' ? options?.cacheMaxAge : 600000;
  75. this.#headers = new Headers(options?.headers);
  76. if (USER_AGENT && !this.#headers.has('User-Agent')) {
  77. this.#headers.set('User-Agent', USER_AGENT);
  78. }
  79. if (!this.#headers.has('accept')) {
  80. this.#headers.set('accept', 'application/json');
  81. this.#headers.append('accept', 'application/jwk-set+json');
  82. }
  83. this.#customFetch = options?.[customFetch];
  84. if (options?.[jwksCache] !== undefined) {
  85. this.#cache = options?.[jwksCache];
  86. if (isFreshJwksCache(options?.[jwksCache], this.#cacheMaxAge)) {
  87. this.#jwksTimestamp = this.#cache.uat;
  88. this.#local = createLocalJWKSet(this.#cache.jwks);
  89. }
  90. }
  91. }
  92. pendingFetch() {
  93. return !!this.#pendingFetch;
  94. }
  95. coolingDown() {
  96. return typeof this.#jwksTimestamp === 'number'
  97. ? Date.now() < this.#jwksTimestamp + this.#cooldownDuration
  98. : false;
  99. }
  100. fresh() {
  101. return typeof this.#jwksTimestamp === 'number'
  102. ? Date.now() < this.#jwksTimestamp + this.#cacheMaxAge
  103. : false;
  104. }
  105. jwks() {
  106. return this.#local?.jwks();
  107. }
  108. async getKey(protectedHeader, token) {
  109. if (!this.#local || !this.fresh()) {
  110. await this.reload();
  111. }
  112. try {
  113. return await this.#local(protectedHeader, token);
  114. }
  115. catch (err) {
  116. if (err instanceof JWKSNoMatchingKey) {
  117. if (this.coolingDown() === false) {
  118. await this.reload();
  119. return this.#local(protectedHeader, token);
  120. }
  121. }
  122. throw err;
  123. }
  124. }
  125. async reload() {
  126. if (this.#pendingFetch && isCloudflareWorkers()) {
  127. this.#pendingFetch = undefined;
  128. }
  129. this.#pendingFetch ||= fetchJwks(this.#url.href, this.#headers, AbortSignal.timeout(this.#timeoutDuration), this.#customFetch)
  130. .then((json) => {
  131. this.#local = createLocalJWKSet(json);
  132. if (this.#cache) {
  133. this.#cache.uat = Date.now();
  134. this.#cache.jwks = json;
  135. }
  136. this.#jwksTimestamp = Date.now();
  137. this.#pendingFetch = undefined;
  138. })
  139. .catch((err) => {
  140. this.#pendingFetch = undefined;
  141. throw err;
  142. });
  143. await this.#pendingFetch;
  144. }
  145. }
  146. export function createRemoteJWKSet(url, options) {
  147. const set = new RemoteJWKSet(url, options);
  148. const remoteJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);
  149. Object.defineProperties(remoteJWKSet, {
  150. coolingDown: {
  151. get: () => set.coolingDown(),
  152. enumerable: true,
  153. configurable: false,
  154. },
  155. fresh: {
  156. get: () => set.fresh(),
  157. enumerable: true,
  158. configurable: false,
  159. },
  160. reload: {
  161. value: () => set.reload(),
  162. enumerable: true,
  163. configurable: false,
  164. writable: false,
  165. },
  166. reloading: {
  167. get: () => set.pendingFetch(),
  168. enumerable: true,
  169. configurable: false,
  170. },
  171. jwks: {
  172. value: () => set.jwks(),
  173. enumerable: true,
  174. configurable: false,
  175. writable: false,
  176. },
  177. });
  178. return remoteJWKSet;
  179. }