fetch_jwks.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. const http = require("http");
  4. const https = require("https");
  5. const events_1 = require("events");
  6. const errors_js_1 = require("../util/errors.js");
  7. const buffer_utils_js_1 = require("../lib/buffer_utils.js");
  8. const fetchJwks = async (url, timeout, options) => {
  9. let get;
  10. switch (url.protocol) {
  11. case 'https:':
  12. get = https.get;
  13. break;
  14. case 'http:':
  15. get = http.get;
  16. break;
  17. default:
  18. throw new TypeError('Unsupported URL protocol.');
  19. }
  20. const { agent, headers } = options;
  21. const req = get(url.href, {
  22. agent,
  23. timeout,
  24. headers,
  25. });
  26. const [response] = (await Promise.race([(0, events_1.once)(req, 'response'), (0, events_1.once)(req, 'timeout')]));
  27. if (!response) {
  28. req.destroy();
  29. throw new errors_js_1.JWKSTimeout();
  30. }
  31. if (response.statusCode !== 200) {
  32. throw new errors_js_1.JOSEError('Expected 200 OK from the JSON Web Key Set HTTP response');
  33. }
  34. const parts = [];
  35. for await (const part of response) {
  36. parts.push(part);
  37. }
  38. try {
  39. return JSON.parse(buffer_utils_js_1.decoder.decode((0, buffer_utils_js_1.concat)(...parts)));
  40. }
  41. catch {
  42. throw new errors_js_1.JOSEError('Failed to parse the JSON Web Key Set HTTP response as JSON');
  43. }
  44. };
  45. exports.default = fetchJwks;