thumbprint.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.calculateJwkThumbprintUri = exports.calculateJwkThumbprint = void 0;
  4. const digest_js_1 = require("../runtime/digest.js");
  5. const base64url_js_1 = require("../runtime/base64url.js");
  6. const errors_js_1 = require("../util/errors.js");
  7. const buffer_utils_js_1 = require("../lib/buffer_utils.js");
  8. const is_object_js_1 = require("../lib/is_object.js");
  9. const check = (value, description) => {
  10. if (typeof value !== 'string' || !value) {
  11. throw new errors_js_1.JWKInvalid(`${description} missing or invalid`);
  12. }
  13. };
  14. async function calculateJwkThumbprint(jwk, digestAlgorithm) {
  15. if (!(0, is_object_js_1.default)(jwk)) {
  16. throw new TypeError('JWK must be an object');
  17. }
  18. digestAlgorithm !== null && digestAlgorithm !== void 0 ? digestAlgorithm : (digestAlgorithm = 'sha256');
  19. if (digestAlgorithm !== 'sha256' &&
  20. digestAlgorithm !== 'sha384' &&
  21. digestAlgorithm !== 'sha512') {
  22. throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');
  23. }
  24. let components;
  25. switch (jwk.kty) {
  26. case 'EC':
  27. check(jwk.crv, '"crv" (Curve) Parameter');
  28. check(jwk.x, '"x" (X Coordinate) Parameter');
  29. check(jwk.y, '"y" (Y Coordinate) Parameter');
  30. components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y };
  31. break;
  32. case 'OKP':
  33. check(jwk.crv, '"crv" (Subtype of Key Pair) Parameter');
  34. check(jwk.x, '"x" (Public Key) Parameter');
  35. components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x };
  36. break;
  37. case 'RSA':
  38. check(jwk.e, '"e" (Exponent) Parameter');
  39. check(jwk.n, '"n" (Modulus) Parameter');
  40. components = { e: jwk.e, kty: jwk.kty, n: jwk.n };
  41. break;
  42. case 'oct':
  43. check(jwk.k, '"k" (Key Value) Parameter');
  44. components = { k: jwk.k, kty: jwk.kty };
  45. break;
  46. default:
  47. throw new errors_js_1.JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported');
  48. }
  49. const data = buffer_utils_js_1.encoder.encode(JSON.stringify(components));
  50. return (0, base64url_js_1.encode)(await (0, digest_js_1.default)(digestAlgorithm, data));
  51. }
  52. exports.calculateJwkThumbprint = calculateJwkThumbprint;
  53. async function calculateJwkThumbprintUri(jwk, digestAlgorithm) {
  54. digestAlgorithm !== null && digestAlgorithm !== void 0 ? digestAlgorithm : (digestAlgorithm = 'sha256');
  55. const thumbprint = await calculateJwkThumbprint(jwk, digestAlgorithm);
  56. return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`;
  57. }
  58. exports.calculateJwkThumbprintUri = calculateJwkThumbprintUri;