sign.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.GeneralSign = void 0;
  4. const sign_js_1 = require("../flattened/sign.js");
  5. const errors_js_1 = require("../../util/errors.js");
  6. class IndividualSignature {
  7. constructor(sig, key, options) {
  8. this.parent = sig;
  9. this.key = key;
  10. this.options = options;
  11. }
  12. setProtectedHeader(protectedHeader) {
  13. if (this.protectedHeader) {
  14. throw new TypeError('setProtectedHeader can only be called once');
  15. }
  16. this.protectedHeader = protectedHeader;
  17. return this;
  18. }
  19. setUnprotectedHeader(unprotectedHeader) {
  20. if (this.unprotectedHeader) {
  21. throw new TypeError('setUnprotectedHeader can only be called once');
  22. }
  23. this.unprotectedHeader = unprotectedHeader;
  24. return this;
  25. }
  26. addSignature(...args) {
  27. return this.parent.addSignature(...args);
  28. }
  29. sign(...args) {
  30. return this.parent.sign(...args);
  31. }
  32. done() {
  33. return this.parent;
  34. }
  35. }
  36. class GeneralSign {
  37. constructor(payload) {
  38. this._signatures = [];
  39. this._payload = payload;
  40. }
  41. addSignature(key, options) {
  42. const signature = new IndividualSignature(this, key, options);
  43. this._signatures.push(signature);
  44. return signature;
  45. }
  46. async sign() {
  47. if (!this._signatures.length) {
  48. throw new errors_js_1.JWSInvalid('at least one signature must be added');
  49. }
  50. const jws = {
  51. signatures: [],
  52. payload: '',
  53. };
  54. for (let i = 0; i < this._signatures.length; i++) {
  55. const signature = this._signatures[i];
  56. const flattened = new sign_js_1.FlattenedSign(this._payload);
  57. flattened.setProtectedHeader(signature.protectedHeader);
  58. flattened.setUnprotectedHeader(signature.unprotectedHeader);
  59. const { payload, ...rest } = await flattened.sign(signature.key, signature.options);
  60. if (i === 0) {
  61. jws.payload = payload;
  62. }
  63. else if (jws.payload !== payload) {
  64. throw new errors_js_1.JWSInvalid('inconsistent use of JWS Unencoded Payload (RFC7797)');
  65. }
  66. jws.signatures.push(rest);
  67. }
  68. return jws;
  69. }
  70. }
  71. exports.GeneralSign = GeneralSign;