@0xpolygonid/js-sdk 1.10.4 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/README.md +11 -0
  2. package/dist/browser/esm/index.js +8360 -17398
  3. package/dist/browser/esm/index.js.map +1 -1
  4. package/dist/browser/umd/index.js +8381 -17414
  5. package/dist/browser/umd/index.js.map +1 -1
  6. package/dist/node/cjs/blockchain/index.js +17 -0
  7. package/dist/node/cjs/blockchain/transaction-service.js +55 -0
  8. package/dist/node/cjs/credentials/credential-wallet.js +1 -1
  9. package/dist/node/cjs/credentials/status/reverse-sparse-merkle-tree.js +5 -1
  10. package/dist/node/cjs/iden3comm/handlers/auth.js +62 -27
  11. package/dist/node/cjs/iden3comm/handlers/common.js +4 -4
  12. package/dist/node/cjs/iden3comm/handlers/contract-request.js +34 -15
  13. package/dist/node/cjs/iden3comm/handlers/credential-proposal.js +33 -14
  14. package/dist/node/cjs/iden3comm/handlers/fetch.js +65 -34
  15. package/dist/node/cjs/iden3comm/handlers/index.js +1 -0
  16. package/dist/node/cjs/iden3comm/handlers/message-handler.js +96 -0
  17. package/dist/node/cjs/iden3comm/handlers/revocation-status.js +58 -30
  18. package/dist/node/cjs/iden3comm/packageManager.js +16 -0
  19. package/dist/node/cjs/iden3comm/packers/jws.js +63 -49
  20. package/dist/node/cjs/iden3comm/packers/plain.js +13 -3
  21. package/dist/node/cjs/iden3comm/packers/zkp.js +9 -0
  22. package/dist/node/cjs/iden3comm/utils/did.js +11 -11
  23. package/dist/node/cjs/identity/identity-wallet.js +228 -43
  24. package/dist/node/cjs/index.js +1 -0
  25. package/dist/node/cjs/kms/key-providers/bjj-provider.js +9 -0
  26. package/dist/node/cjs/kms/key-providers/ed25519-provider.js +13 -1
  27. package/dist/node/cjs/kms/key-providers/index.js +1 -1
  28. package/dist/node/cjs/kms/key-providers/{sec256k1-provider.js → secp256k1-provider.js} +37 -26
  29. package/dist/node/cjs/kms/kms.js +15 -0
  30. package/dist/node/cjs/proof/proof-service.js +3 -33
  31. package/dist/node/cjs/proof/provers/inputs-generator.js +2 -7
  32. package/dist/node/cjs/storage/blockchain/onchain-revocation.js +4 -12
  33. package/dist/node/cjs/storage/blockchain/onchain-zkp-verifier.js +3 -10
  34. package/dist/node/cjs/storage/blockchain/state.js +39 -10
  35. package/dist/node/cjs/utils/did-helper.js +36 -2
  36. package/dist/node/cjs/verifiable/constants.js +2 -1
  37. package/dist/node/esm/blockchain/index.js +1 -0
  38. package/dist/node/esm/blockchain/transaction-service.js +51 -0
  39. package/dist/node/esm/credentials/credential-wallet.js +1 -1
  40. package/dist/node/esm/credentials/status/reverse-sparse-merkle-tree.js +6 -2
  41. package/dist/node/esm/iden3comm/handlers/auth.js +62 -27
  42. package/dist/node/esm/iden3comm/handlers/common.js +4 -4
  43. package/dist/node/esm/iden3comm/handlers/contract-request.js +34 -15
  44. package/dist/node/esm/iden3comm/handlers/credential-proposal.js +33 -14
  45. package/dist/node/esm/iden3comm/handlers/fetch.js +65 -34
  46. package/dist/node/esm/iden3comm/handlers/index.js +1 -0
  47. package/dist/node/esm/iden3comm/handlers/message-handler.js +91 -0
  48. package/dist/node/esm/iden3comm/handlers/revocation-status.js +58 -30
  49. package/dist/node/esm/iden3comm/packageManager.js +16 -0
  50. package/dist/node/esm/iden3comm/packers/jws.js +63 -49
  51. package/dist/node/esm/iden3comm/packers/plain.js +13 -3
  52. package/dist/node/esm/iden3comm/packers/zkp.js +9 -0
  53. package/dist/node/esm/iden3comm/utils/did.js +11 -8
  54. package/dist/node/esm/identity/identity-wallet.js +230 -45
  55. package/dist/node/esm/index.js +1 -0
  56. package/dist/node/esm/kms/key-providers/bjj-provider.js +10 -1
  57. package/dist/node/esm/kms/key-providers/ed25519-provider.js +13 -1
  58. package/dist/node/esm/kms/key-providers/index.js +1 -1
  59. package/dist/node/esm/kms/key-providers/secp256k1-provider.js +85 -0
  60. package/dist/node/esm/kms/kms.js +15 -0
  61. package/dist/node/esm/proof/proof-service.js +4 -34
  62. package/dist/node/esm/proof/provers/inputs-generator.js +3 -8
  63. package/dist/node/esm/storage/blockchain/onchain-revocation.js +4 -12
  64. package/dist/node/esm/storage/blockchain/onchain-zkp-verifier.js +3 -10
  65. package/dist/node/esm/storage/blockchain/state.js +39 -10
  66. package/dist/node/esm/utils/did-helper.js +33 -1
  67. package/dist/node/esm/verifiable/constants.js +2 -1
  68. package/dist/types/blockchain/index.d.ts +1 -0
  69. package/dist/types/blockchain/transaction-service.d.ts +80 -0
  70. package/dist/types/iden3comm/handlers/auth.d.ts +17 -2
  71. package/dist/types/iden3comm/handlers/common.d.ts +2 -2
  72. package/dist/types/iden3comm/handlers/contract-request.d.ts +10 -2
  73. package/dist/types/iden3comm/handlers/credential-proposal.d.ts +5 -2
  74. package/dist/types/iden3comm/handlers/fetch.d.ts +15 -6
  75. package/dist/types/iden3comm/handlers/index.d.ts +1 -0
  76. package/dist/types/iden3comm/handlers/message-handler.d.ts +83 -0
  77. package/dist/types/iden3comm/handlers/revocation-status.d.ts +18 -2
  78. package/dist/types/iden3comm/packageManager.d.ts +10 -0
  79. package/dist/types/iden3comm/packers/jws.d.ts +9 -0
  80. package/dist/types/iden3comm/packers/plain.d.ts +10 -2
  81. package/dist/types/iden3comm/packers/zkp.d.ts +7 -0
  82. package/dist/types/iden3comm/types/packageManager.d.ts +10 -0
  83. package/dist/types/iden3comm/types/packer.d.ts +24 -2
  84. package/dist/types/iden3comm/types/protocol/auth.d.ts +5 -15
  85. package/dist/types/iden3comm/types/protocol/contract-request.d.ts +2 -6
  86. package/dist/types/iden3comm/types/protocol/credentials.d.ts +7 -44
  87. package/dist/types/iden3comm/types/protocol/messages.d.ts +2 -9
  88. package/dist/types/iden3comm/types/protocol/proof.d.ts +3 -16
  89. package/dist/types/iden3comm/types/protocol/revocation.d.ts +3 -16
  90. package/dist/types/identity/identity-wallet.d.ts +80 -7
  91. package/dist/types/index.d.ts +1 -0
  92. package/dist/types/kms/key-providers/bjj-provider.d.ts +1 -0
  93. package/dist/types/kms/key-providers/ed25519-provider.d.ts +8 -0
  94. package/dist/types/kms/key-providers/index.d.ts +1 -1
  95. package/dist/types/kms/key-providers/{sec256k1-provider.d.ts → secp256k1-provider.d.ts} +15 -9
  96. package/dist/types/kms/kms.d.ts +18 -0
  97. package/dist/types/proof/proof-service.d.ts +2 -2
  98. package/dist/types/storage/blockchain/onchain-revocation.d.ts +1 -0
  99. package/dist/types/storage/blockchain/state.d.ts +7 -2
  100. package/dist/types/storage/interfaces/state.d.ts +26 -2
  101. package/dist/types/utils/did-helper.d.ts +9 -1
  102. package/dist/types/verifiable/constants.d.ts +1 -0
  103. package/package.json +10 -12
  104. package/LICENSE +0 -691
  105. package/dist/node/esm/kms/key-providers/sec256k1-provider.js +0 -71
@@ -6,6 +6,7 @@ import { byteDecoder, byteEncoder } from '../../utils';
6
6
  import { proving } from '@iden3/js-jwz';
7
7
  import { DID } from '@iden3/js-iden3-core';
8
8
  import * as uuid from 'uuid';
9
+ import { AbstractMessageHandler } from './message-handler';
9
10
  /**
10
11
  *
11
12
  * Allows to handle Credential offer protocol message and return fetched credential
@@ -15,41 +16,43 @@ import * as uuid from 'uuid';
15
16
  * @class FetchHandler
16
17
  * @implements implements IFetchHandler interface
17
18
  */
18
- export class FetchHandler {
19
+ export class FetchHandler extends AbstractMessageHandler {
19
20
  /**
20
- * Creates an instance of FetchHandler.
21
- * @param {IPackageManager} _packerMgr - package manager to unpack message envelope
21
+ * Constructs a new instance of the FetchHandler class.
22
+ *
23
+ * @param _packerMgr The package manager used for packing and unpacking data.
24
+ * @param opts Optional configuration options for the FetchHandler.
25
+ * @param opts.credentialWallet The credential wallet used for managing credentials.
22
26
  */
23
27
  constructor(_packerMgr, opts) {
28
+ super();
24
29
  this._packerMgr = _packerMgr;
25
30
  this.opts = opts;
26
31
  }
27
- /**
28
- * Handles only messages with credentials/1.0/offer type
29
- *
30
- * @param {
31
- * offer: Uint8Array; offer - raw offer message
32
- * opts
33
- * }) options how to fetch credential
34
- * @returns `Promise<W3CCredential[]>`
35
- */
36
- async handleCredentialOffer(offer, opts) {
37
- if (!opts) {
38
- opts = {
39
- mediaType: MediaType.ZKPMessage
40
- };
32
+ async handle(message, ctx) {
33
+ switch (message.type) {
34
+ case PROTOCOL_MESSAGE_TYPE.CREDENTIAL_OFFER_MESSAGE_TYPE:
35
+ await this.handleOfferMessage(message, ctx);
36
+ return null;
37
+ case PROTOCOL_MESSAGE_TYPE.CREDENTIAL_FETCH_REQUEST_MESSAGE_TYPE:
38
+ return this.handleFetchRequest(message);
39
+ case PROTOCOL_MESSAGE_TYPE.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE:
40
+ return this.handleIssuanceResponseMsg(message);
41
+ default:
42
+ return super.handle(message, ctx);
41
43
  }
42
- if (opts.mediaType === MediaType.SignedMessage && !opts.packerOptions) {
43
- throw new Error(`jws packer options are required for ${MediaType.SignedMessage}`);
44
+ }
45
+ async handleOfferMessage(offerMessage, ctx) {
46
+ if (!ctx.mediaType) {
47
+ ctx.mediaType = MediaType.ZKPMessage;
44
48
  }
45
- const offerMessage = await FetchHandler.unpackMessage(this._packerMgr, offer, PROTOCOL_MESSAGE_TYPE.CREDENTIAL_OFFER_MESSAGE_TYPE);
46
49
  const credentials = [];
47
50
  for (let index = 0; index < offerMessage.body.credentials.length; index++) {
48
51
  const credentialInfo = offerMessage.body.credentials[index];
49
52
  const guid = uuid.v4();
50
53
  const fetchRequest = {
51
54
  id: guid,
52
- typ: opts.mediaType,
55
+ typ: ctx.mediaType,
53
56
  type: PROTOCOL_MESSAGE_TYPE.CREDENTIAL_FETCH_REQUEST_MESSAGE_TYPE,
54
57
  thid: offerMessage.thid ?? guid,
55
58
  body: {
@@ -59,13 +62,13 @@ export class FetchHandler {
59
62
  to: offerMessage.from
60
63
  };
61
64
  const msgBytes = byteEncoder.encode(JSON.stringify(fetchRequest));
62
- const packerOpts = opts.mediaType === MediaType.SignedMessage
63
- ? opts.packerOptions
65
+ const packerOpts = ctx.mediaType === MediaType.SignedMessage
66
+ ? ctx.packerOptions
64
67
  : {
65
68
  provingMethodAlg: proving.provingMethodGroth16AuthV2Instance.methodAlg
66
69
  };
67
70
  const senderDID = DID.parse(offerMessage.to);
68
- const token = byteDecoder.decode(await this._packerMgr.pack(opts.mediaType, msgBytes, {
71
+ const token = byteDecoder.decode(await this._packerMgr.pack(ctx.mediaType, msgBytes, {
69
72
  senderDID,
70
73
  ...packerOpts
71
74
  }));
@@ -78,7 +81,7 @@ export class FetchHandler {
78
81
  method: 'post',
79
82
  headers: {
80
83
  'Content-Type': 'application/x-www-form-urlencoded',
81
- ...(opts.headers ?? {})
84
+ ...ctx.headers
82
85
  },
83
86
  body: token
84
87
  });
@@ -95,10 +98,26 @@ export class FetchHandler {
95
98
  return credentials;
96
99
  }
97
100
  /**
98
- * @inheritdoc IFetchHandler#handleCredentialFetchRequest
101
+ * Handles only messages with credentials/1.0/offer type
102
+ *
103
+ * @param {
104
+ * offer: Uint8Array; offer - raw offer message
105
+ * opts
106
+ * }) options how to fetch credential
107
+ * @returns `Promise<W3CCredential[]>`
99
108
  */
100
- async handleCredentialFetchRequest(envelope) {
101
- const msgRequest = await FetchHandler.unpackMessage(this._packerMgr, envelope, PROTOCOL_MESSAGE_TYPE.CREDENTIAL_FETCH_REQUEST_MESSAGE_TYPE);
109
+ async handleCredentialOffer(offer, opts) {
110
+ if (opts?.mediaType === MediaType.SignedMessage && !opts.packerOptions) {
111
+ throw new Error(`jws packer options are required for ${MediaType.SignedMessage}`);
112
+ }
113
+ const offerMessage = await FetchHandler.unpackMessage(this._packerMgr, offer, PROTOCOL_MESSAGE_TYPE.CREDENTIAL_OFFER_MESSAGE_TYPE);
114
+ return this.handleOfferMessage(offerMessage, {
115
+ mediaType: opts?.mediaType,
116
+ headers: opts?.headers,
117
+ packerOptions: opts?.packerOptions
118
+ });
119
+ }
120
+ async handleFetchRequest(msgRequest) {
102
121
  if (!msgRequest.to) {
103
122
  throw new Error("failed request. empty 'to' field");
104
123
  }
@@ -122,7 +141,7 @@ export class FetchHandler {
122
141
  if (userToVerifyDID.string() !== userDID.string()) {
123
142
  throw new Error('credential subject is not a sender DID');
124
143
  }
125
- return this._packerMgr.pack(MediaType.PlainMessage, byteEncoder.encode(JSON.stringify({
144
+ return {
126
145
  id: uuid.v4(),
127
146
  type: PROTOCOL_MESSAGE_TYPE.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE,
128
147
  typ: msgRequest.typ ?? MediaType.PlainMessage,
@@ -130,13 +149,17 @@ export class FetchHandler {
130
149
  body: { credential: cred },
131
150
  from: msgRequest.to,
132
151
  to: msgRequest.from
133
- })), {});
152
+ };
134
153
  }
135
154
  /**
136
- * @inheritdoc IFetchHandler#handleIssuanceResponseMessage
155
+ * @inheritdoc IFetchHandler#handleCredentialFetchRequest
137
156
  */
138
- async handleIssuanceResponseMessage(envelop) {
139
- const issuanceMsg = await FetchHandler.unpackMessage(this._packerMgr, envelop, PROTOCOL_MESSAGE_TYPE.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE);
157
+ async handleCredentialFetchRequest(envelope) {
158
+ const msgRequest = await FetchHandler.unpackMessage(this._packerMgr, envelope, PROTOCOL_MESSAGE_TYPE.CREDENTIAL_FETCH_REQUEST_MESSAGE_TYPE);
159
+ const request = await this.handleFetchRequest(msgRequest);
160
+ return this._packerMgr.pack(MediaType.PlainMessage, byteEncoder.encode(JSON.stringify(request)), {});
161
+ }
162
+ async handleIssuanceResponseMsg(issuanceMsg) {
140
163
  if (!this.opts?.credentialWallet) {
141
164
  throw new Error('please provide credential wallet in options');
142
165
  }
@@ -144,7 +167,15 @@ export class FetchHandler {
144
167
  throw new Error('credential is missing in issuance response message');
145
168
  }
146
169
  await this.opts.credentialWallet.save(W3CCredential.fromJSON(issuanceMsg.body.credential));
147
- return Promise.resolve(Uint8Array.from([]));
170
+ return null;
171
+ }
172
+ /**
173
+ * @inheritdoc IFetchHandler#handleIssuanceResponseMessage
174
+ */
175
+ async handleIssuanceResponseMessage(envelop) {
176
+ const issuanceMsg = await FetchHandler.unpackMessage(this._packerMgr, envelop, PROTOCOL_MESSAGE_TYPE.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE);
177
+ await this.handleIssuanceResponseMsg(issuanceMsg);
178
+ return Uint8Array.from([]);
148
179
  }
149
180
  /**
150
181
  * @inheritdoc IFetchHandler#unpackMessage
@@ -5,3 +5,4 @@ export * from './refresh';
5
5
  export * from './revocation-status';
6
6
  export * from './common';
7
7
  export * from './credential-proposal';
8
+ export * from './message-handler';
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Base implementation of protocol message handler
3
+ *
4
+ * @export
5
+ * @abstract
6
+ * @class AbstractMessageHandler
7
+ * @implements {IProtocolMessageHandler}
8
+ */
9
+ export class AbstractMessageHandler {
10
+ setNext(messageHandler) {
11
+ this.nextMessageHandler = messageHandler;
12
+ return messageHandler;
13
+ }
14
+ async handle(message, context) {
15
+ if (this.nextMessageHandler)
16
+ return this.nextMessageHandler.handle(message, context);
17
+ return Promise.reject('Message handler not provided or message not supported');
18
+ }
19
+ }
20
+ /**
21
+ * Protocol message handler entry point
22
+ */
23
+ export class MessageHandler {
24
+ /**
25
+ * Creates an instance of MessageHandler.
26
+ * @param {{
27
+ * messageHandlers: AbstractMessageHandler[];
28
+ * packageManager: IPackageManager;
29
+ * }} _params
30
+ * @memberof MessageHandler
31
+ */
32
+ constructor(_params) {
33
+ this._params = _params;
34
+ this.registerHandlers(_params.messageHandlers);
35
+ }
36
+ /**
37
+ * Registers a list of message handlers and sets up the chain of responsibility.
38
+ *
39
+ * This method takes an array of `AbstractMessageHandler` instances and sets up a chain of responsibility
40
+ * where each handler is linked to the next one in the array. The first handler in the array becomes the
41
+ * main message handler for the `MessageHandler` class.
42
+ *
43
+ * @param {AbstractMessageHandler[]} handlersList - An array of `AbstractMessageHandler` instances to be registered.
44
+ * @returns {void}
45
+ */
46
+ registerHandlers(handlersList) {
47
+ if (!handlersList.length)
48
+ return;
49
+ const [firstMessageHandler, ...restHandlersList] = handlersList;
50
+ const tempHandler = firstMessageHandler;
51
+ for (const currentHandler of restHandlersList) {
52
+ let lastHandler = tempHandler;
53
+ while (lastHandler.nextMessageHandler) {
54
+ lastHandler = lastHandler.nextMessageHandler;
55
+ }
56
+ lastHandler.setNext(currentHandler);
57
+ }
58
+ if (!this.messageHandler) {
59
+ this.messageHandler = firstMessageHandler;
60
+ }
61
+ else {
62
+ this.messageHandler.setNext(firstMessageHandler);
63
+ }
64
+ }
65
+ /**
66
+ * Handles a message by unpacking it, passing it to the registered message handler, and packing the response.
67
+ *
68
+ * This method takes a Uint8Array of message bytes and a context object that contains information specific to the
69
+ * type of message being handled (e.g. AuthMessageHandlerOptions, ContractMessageHandlerOptions, etc.).
70
+ *
71
+ * The method first unpacks the message using the provided package manager, then passes the unpacked message and
72
+ * context to the registered message handler. If the message handler returns a response, the method packs the
73
+ * response using the package manager and returns it. If the message handler does not return a response, the
74
+ * method returns null.
75
+ *
76
+ * @param bytes - A Uint8Array of message bytes to be handled.
77
+ * @param context - An object containing information specific to the type of message being handled.
78
+ * @returns A Promise that resolves to a Uint8Array of the packed response, or null if no response was generated.
79
+ */
80
+ async handleMessage(bytes, context) {
81
+ const { unpackedMediaType, unpackedMessage: message } = await this._params.packageManager.unpack(bytes);
82
+ if (!this.messageHandler) {
83
+ return Promise.reject(new Error('Message handler not provided'));
84
+ }
85
+ const response = await this.messageHandler.handle(message, context);
86
+ if (response) {
87
+ return this._params.packageManager.packMessage(unpackedMediaType, response, {});
88
+ }
89
+ return null;
90
+ }
91
+ }
@@ -4,6 +4,7 @@ import { DID } from '@iden3/js-iden3-core';
4
4
  import * as uuid from 'uuid';
5
5
  import { byteEncoder } from '../../utils';
6
6
  import { proving } from '@iden3/js-jwz';
7
+ import { AbstractMessageHandler } from './message-handler';
7
8
  /**
8
9
  *
9
10
  * Allows to process RevocationStatusRequest protocol message
@@ -12,7 +13,7 @@ import { proving } from '@iden3/js-jwz';
12
13
  * @class RevocationStatusHandler
13
14
  * @implements implements IRevocationStatusHandler interface
14
15
  */
15
- export class RevocationStatusHandler {
16
+ export class RevocationStatusHandler extends AbstractMessageHandler {
16
17
  /**
17
18
  * Creates an instance of RevocationStatusHandler.
18
19
  * @param {IPackageManager} _packerMgr - package manager to unpack message envelope
@@ -20,33 +21,25 @@ export class RevocationStatusHandler {
20
21
  *
21
22
  */
22
23
  constructor(_packerMgr, _identityWallet) {
24
+ super();
23
25
  this._packerMgr = _packerMgr;
24
26
  this._identityWallet = _identityWallet;
25
27
  }
26
- /**
27
- * @inheritdoc IRevocationStatusHandler#parseRevocationStatusRequest
28
- */
29
- async parseRevocationStatusRequest(request) {
30
- const { unpackedMessage: message } = await this._packerMgr.unpack(request);
31
- const ciRequest = message;
32
- if (message.type !== PROTOCOL_MESSAGE_TYPE.REVOCATION_STATUS_REQUEST_MESSAGE_TYPE) {
33
- throw new Error('Invalid media type');
28
+ handle(message, context) {
29
+ if (!context.did) {
30
+ throw new Error('DID is required');
34
31
  }
35
- return ciRequest;
36
- }
37
- /**
38
- * @inheritdoc IRevocationStatusHandler#handleRevocationStatusRequest
39
- */
40
- async handleRevocationStatusRequest(did, request, opts) {
41
- if (!opts) {
42
- opts = {
43
- mediaType: MediaType.PlainMessage
44
- };
32
+ if (!context.mediaType) {
33
+ throw new Error('mediaType is required');
45
34
  }
46
- if (opts.mediaType === MediaType.SignedMessage && !opts.packerOptions) {
47
- throw new Error(`jws packer options are required for ${MediaType.SignedMessage}`);
35
+ switch (message.type) {
36
+ case PROTOCOL_MESSAGE_TYPE.REVOCATION_STATUS_REQUEST_MESSAGE_TYPE:
37
+ return this.handleRevocationStatusRequestMessage(message, context);
38
+ default:
39
+ return super.handle(message, context);
48
40
  }
49
- const rsRequest = await this.parseRevocationStatusRequest(request);
41
+ }
42
+ async handleRevocationStatusRequestMessage(rsRequest, context) {
50
43
  if (!rsRequest.to) {
51
44
  throw new Error(`failed request. empty 'to' field`);
52
45
  }
@@ -57,7 +50,7 @@ export class RevocationStatusHandler {
57
50
  throw new Error(`failed request. empty 'revocation_nonce' field`);
58
51
  }
59
52
  const issuerDID = DID.parse(rsRequest.to);
60
- const mtpWithTreeState = await this._identityWallet.generateNonRevocationMtpWithNonce(issuerDID, BigInt(rsRequest.body.revocation_nonce), opts?.treeState);
53
+ const mtpWithTreeState = await this._identityWallet.generateNonRevocationMtpWithNonce(issuerDID, BigInt(rsRequest.body.revocation_nonce), context.treeState);
61
54
  const treeState = mtpWithTreeState.treeState;
62
55
  const revStatus = {
63
56
  issuer: {
@@ -68,12 +61,6 @@ export class RevocationStatusHandler {
68
61
  },
69
62
  mtp: mtpWithTreeState.proof
70
63
  };
71
- const packerOpts = opts.mediaType === MediaType.SignedMessage
72
- ? opts.packerOptions
73
- : {
74
- provingMethodAlg: proving.provingMethodGroth16AuthV2Instance.methodAlg
75
- };
76
- const senderDID = DID.parse(rsRequest.to);
77
64
  const guid = uuid.v4();
78
65
  const response = {
79
66
  id: guid,
@@ -81,9 +68,50 @@ export class RevocationStatusHandler {
81
68
  type: PROTOCOL_MESSAGE_TYPE.REVOCATION_STATUS_RESPONSE_MESSAGE_TYPE,
82
69
  thid: rsRequest.thid ?? guid,
83
70
  body: revStatus,
84
- from: did.string(),
71
+ from: context.did.string(),
85
72
  to: rsRequest.from
86
73
  };
74
+ return response;
75
+ }
76
+ /**
77
+ * @inheritdoc IRevocationStatusHandler#parseRevocationStatusRequest
78
+ */
79
+ async parseRevocationStatusRequest(request) {
80
+ const { unpackedMessage: message } = await this._packerMgr.unpack(request);
81
+ const ciRequest = message;
82
+ if (message.type !== PROTOCOL_MESSAGE_TYPE.REVOCATION_STATUS_REQUEST_MESSAGE_TYPE) {
83
+ throw new Error('Invalid media type');
84
+ }
85
+ return ciRequest;
86
+ }
87
+ /**
88
+ * @inheritdoc IRevocationStatusHandler#handleRevocationStatusRequest
89
+ */
90
+ async handleRevocationStatusRequest(did, request, opts) {
91
+ if (!opts) {
92
+ opts = {
93
+ mediaType: MediaType.PlainMessage
94
+ };
95
+ }
96
+ if (opts.mediaType === MediaType.SignedMessage && !opts.packerOptions) {
97
+ throw new Error(`jws packer options are required for ${MediaType.SignedMessage}`);
98
+ }
99
+ const rsRequest = await this.parseRevocationStatusRequest(request);
100
+ const response = await this.handleRevocationStatusRequestMessage(rsRequest, {
101
+ did,
102
+ mediaType: opts.mediaType,
103
+ packerOptions: opts.packerOptions,
104
+ treeState: opts.treeState
105
+ });
106
+ const packerOpts = opts.mediaType === MediaType.SignedMessage
107
+ ? opts.packerOptions
108
+ : {
109
+ provingMethodAlg: proving.provingMethodGroth16AuthV2Instance.methodAlg
110
+ };
111
+ if (!rsRequest.to) {
112
+ throw new Error(`failed request. empty 'to' field`);
113
+ }
114
+ const senderDID = DID.parse(rsRequest.to);
87
115
  return this._packerMgr.pack(opts.mediaType, byteEncoder.encode(JSON.stringify(response)), {
88
116
  senderDID,
89
117
  ...packerOpts
@@ -29,6 +29,22 @@ export class PackageManager {
29
29
  }
30
30
  return await p.pack(payload, params);
31
31
  }
32
+ /**
33
+ * Packs a protocol message using the specified media type and packer parameters.
34
+ *
35
+ * @param mediaType - The media type to use for packing the message.
36
+ * @param protocolMessage - The protocol message to pack.
37
+ * @param params - The packer parameters.
38
+ * @returns A promise that resolves to the packed message as a Uint8Array.
39
+ * @throws An error if the packer for the specified media type is not found.
40
+ */
41
+ packMessage(mediaType, protocolMessage, params) {
42
+ const p = this.packers.get(mediaType);
43
+ if (!p) {
44
+ throw new Error(`packer for media type ${mediaType} not found`);
45
+ }
46
+ return p.packMessage(protocolMessage, params);
47
+ }
32
48
  /** {@inheritDoc IPackageManager.unpack} */
33
49
  async unpack(envelope) {
34
50
  const decodedStr = byteDecoder.decode(envelope);
@@ -3,6 +3,7 @@ import { extractPublicKeyBytes, resolveVerificationMethods } from '../utils/did'
3
3
  import { keyPath } from '../../kms/';
4
4
  import { verifyJWS } from 'did-jwt';
5
5
  import { parse } from 'did-resolver';
6
+ import { bytesToBase64url } from '../../utils/encoding';
6
7
  import { byteDecoder, byteEncoder, bytesToHex, decodeBase64url, encodeBase64url } from '../../utils';
7
8
  /**
8
9
  * Packer that can pack message to JWZ token,
@@ -23,6 +24,16 @@ export class JWSPacker {
23
24
  this._kms = _kms;
24
25
  this._documentResolver = _documentResolver;
25
26
  }
27
+ /**
28
+ * Packs the given payload and returns a promise that resolves to the packed data.
29
+ *
30
+ * @param {Uint8Array} payload - The payload to be packed.
31
+ * @param {PackerParams} param - The packing parameters.
32
+ * @returns `Promise<Uint8Array>`
33
+ */
34
+ packMessage(msg, param) {
35
+ return this.packInternal(msg, param);
36
+ }
26
37
  /**
27
38
  * creates JSON Web Signature token
28
39
  *
@@ -31,56 +42,8 @@ export class JWSPacker {
31
42
  * @returns `Promise<Uint8Array>`
32
43
  */
33
44
  async pack(payload, params) {
34
- if (!params.alg) {
35
- throw new Error('Missing algorithm');
36
- }
37
45
  const message = JSON.parse(byteDecoder.decode(payload));
38
- const from = message.from ?? '';
39
- if (!from) {
40
- throw new Error('Missing sender DID');
41
- }
42
- const vmTypes = SUPPORTED_PUBLIC_KEY_TYPES[params.alg];
43
- if (!vmTypes?.length) {
44
- throw new Error(`No supported verification methods for algorithm ${params.alg}`);
45
- }
46
- const didDocument = params.didDocument ?? (await this.resolveDidDoc(from));
47
- const vms = resolveVerificationMethods(didDocument);
48
- if (!vms.length) {
49
- throw new Error(`No verification methods defined in the DID document of ${didDocument.id}`);
50
- }
51
- // try to find a managed signing key that matches keyRef
52
- const vm = params.kid ? vms.find((vm) => vm.id === params.kid) : vms[0];
53
- if (!vm) {
54
- throw new Error(`No key found with id ${params.kid} in DID document of ${didDocument.id}`);
55
- }
56
- const { publicKeyBytes, kmsKeyType } = extractPublicKeyBytes(vm);
57
- if (!publicKeyBytes && !kmsKeyType) {
58
- if ((vm.blockchainAccountId || vm.ethereumAddress) && !params.signer) {
59
- throw new Error(`No signer provided for ${vm.blockchainAccountId || vm.ethereumAddress}`);
60
- }
61
- }
62
- const kid = vm.id;
63
- const headerObj = { alg: params.alg, kid, typ: MediaType.SignedMessage };
64
- const header = encodeBase64url(JSON.stringify(headerObj));
65
- const msg = encodeBase64url(JSON.stringify(message));
66
- const signingInput = `${header}.${msg}`;
67
- const signingInputBytes = byteEncoder.encode(signingInput);
68
- let signatureBase64;
69
- if (params.signer) {
70
- const signerFn = params.signer(vm, signingInputBytes);
71
- signatureBase64 = (await signerFn(signingInput)).toString();
72
- }
73
- else {
74
- if (!publicKeyBytes) {
75
- throw new Error('No public key found');
76
- }
77
- if (!kmsKeyType) {
78
- throw new Error('No KMS key type found');
79
- }
80
- const signatureBytes = await this._kms.sign({ type: kmsKeyType, id: keyPath(kmsKeyType, bytesToHex(publicKeyBytes)) }, signingInputBytes);
81
- signatureBase64 = byteDecoder.decode(signatureBytes);
82
- }
83
- return byteEncoder.encode(`${signingInput}.${signatureBase64}`);
46
+ return this.packInternal(message, params);
84
47
  }
85
48
  /**
86
49
  * validate envelope which is jwz token
@@ -134,4 +97,55 @@ export class JWSPacker {
134
97
  }
135
98
  return didDocument;
136
99
  }
100
+ async packInternal(message, params) {
101
+ if (!params.alg) {
102
+ throw new Error('Missing algorithm');
103
+ }
104
+ const from = message.from ?? '';
105
+ if (!from) {
106
+ throw new Error('Missing sender DID');
107
+ }
108
+ const vmTypes = SUPPORTED_PUBLIC_KEY_TYPES[params.alg];
109
+ if (!vmTypes?.length) {
110
+ throw new Error(`No supported verification methods for algorithm ${params.alg}`);
111
+ }
112
+ const didDocument = params.didDocument ?? (await this.resolveDidDoc(from));
113
+ const vms = resolveVerificationMethods(didDocument);
114
+ if (!vms.length) {
115
+ throw new Error(`No verification methods defined in the DID document of ${didDocument.id}`);
116
+ }
117
+ // try to find a managed signing key that matches keyRef
118
+ const vm = params.kid ? vms.find((vm) => vm.id === params.kid) : vms[0];
119
+ if (!vm) {
120
+ throw new Error(`No key found with id ${params.kid} in DID document of ${didDocument.id}`);
121
+ }
122
+ const { publicKeyBytes, kmsKeyType } = extractPublicKeyBytes(vm);
123
+ if (!publicKeyBytes && !kmsKeyType) {
124
+ if ((vm.blockchainAccountId || vm.ethereumAddress) && !params.signer) {
125
+ throw new Error(`No signer provided for ${vm.blockchainAccountId || vm.ethereumAddress}`);
126
+ }
127
+ }
128
+ const kid = vm.id;
129
+ const headerObj = { alg: params.alg, kid, typ: MediaType.SignedMessage };
130
+ const header = encodeBase64url(JSON.stringify(headerObj));
131
+ const msg = encodeBase64url(JSON.stringify(message));
132
+ const signingInput = `${header}.${msg}`;
133
+ const signingInputBytes = byteEncoder.encode(signingInput);
134
+ let signatureBase64;
135
+ if (params.signer) {
136
+ const signature = await params.signer(vm, signingInputBytes);
137
+ signatureBase64 = bytesToBase64url(signature);
138
+ }
139
+ else {
140
+ if (!publicKeyBytes) {
141
+ throw new Error('No public key found');
142
+ }
143
+ if (!kmsKeyType) {
144
+ throw new Error('No KMS key type found');
145
+ }
146
+ const signatureBytes = await this._kms.sign({ type: kmsKeyType, id: keyPath(kmsKeyType, bytesToHex(publicKeyBytes)) }, signingInputBytes, { alg: params.alg });
147
+ signatureBase64 = bytesToBase64url(signatureBytes);
148
+ }
149
+ return byteEncoder.encode(`${signingInput}.${signatureBase64}`);
150
+ }
137
151
  }
@@ -8,6 +8,18 @@ import { byteDecoder, byteEncoder } from '../../utils';
8
8
  * @implements implements IPacker interface
9
9
  */
10
10
  export class PlainPacker {
11
+ /**
12
+ * Packs a basic message using the specified parameters.
13
+ *
14
+ * @param msg - The basic message to pack.
15
+ * @param param - The packer parameters.
16
+ * @returns A promise that resolves to a Uint8Array representing the packed message.
17
+ * @throws An error if the method is not implemented.
18
+ */
19
+ packMessage(msg) {
20
+ msg.typ = MediaType.PlainMessage;
21
+ return Promise.resolve(byteEncoder.encode(JSON.stringify(msg)));
22
+ }
11
23
  /**
12
24
  * Pack returns packed message to transport envelope
13
25
  *
@@ -15,9 +27,7 @@ export class PlainPacker {
15
27
  * @param {PlainPackerParams} _params - not used here
16
28
  * @returns `Promise<Uint8Array>`
17
29
  */
18
- //
19
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
20
- async pack(payload, _params) {
30
+ async pack(payload) {
21
31
  const msg = JSON.parse(byteDecoder.decode(payload));
22
32
  msg.typ = MediaType.PlainMessage;
23
33
  return Promise.resolve(byteEncoder.encode(JSON.stringify(msg)));
@@ -74,6 +74,15 @@ export class ZKPPacker {
74
74
  this.provingParamsMap = provingParamsMap;
75
75
  this.verificationParamsMap = verificationParamsMap;
76
76
  }
77
+ /**
78
+ * Packs a basic message using the specified parameters.
79
+ * @param msg - The basic message to pack.
80
+ * @param param - The parameters for the ZKPPacker.
81
+ * @returns A promise that resolves to a Uint8Array representing the packed message.
82
+ */
83
+ packMessage(msg, param) {
84
+ return this.pack(byteEncoder.encode(JSON.stringify(msg)), param);
85
+ }
77
86
  /**
78
87
  * creates JSON Web Zeroknowledge token
79
88
  *
@@ -1,5 +1,5 @@
1
1
  import { SUPPORTED_PUBLIC_KEY_TYPES } from '../constants';
2
- import elliptic from 'elliptic';
2
+ import { secp256k1 as sec } from '@noble/curves/secp256k1';
3
3
  import { KmsKeyType } from '../../kms';
4
4
  import { base58ToBytes, base64UrlToBytes, bytesToHex, hexToBytes } from '../../utils';
5
5
  const DIDAuthenticationSection = 'authentication';
@@ -23,7 +23,6 @@ export const resolveVerificationMethods = (didDocument) => {
23
23
  }
24
24
  return sortedVerificationMethods;
25
25
  };
26
- const secp256k1 = new elliptic.ec('secp256k1');
27
26
  export const extractPublicKeyBytes = (vm) => {
28
27
  const isSupportedVmType = Object.keys(SUPPORTED_PUBLIC_KEY_TYPES).some((key) => SUPPORTED_PUBLIC_KEY_TYPES[key].includes(vm.type));
29
28
  if (vm.publicKeyBase58 && isSupportedVmType) {
@@ -42,13 +41,17 @@ export const extractPublicKeyBytes = (vm) => {
42
41
  vm.publicKeyJwk.crv === 'secp256k1' &&
43
42
  vm.publicKeyJwk.x &&
44
43
  vm.publicKeyJwk.y) {
44
+ const [xHex, yHex] = [
45
+ base64UrlToBytes(vm.publicKeyJwk.x),
46
+ base64UrlToBytes(vm.publicKeyJwk.y)
47
+ ].map(bytesToHex);
48
+ const x = xHex.includes('0x') ? BigInt(xHex) : BigInt(`0x${xHex}`);
49
+ const y = yHex.includes('0x') ? BigInt(yHex) : BigInt(`0x${yHex}`);
45
50
  return {
46
- publicKeyBytes: hexToBytes(secp256k1
47
- .keyFromPublic({
48
- x: bytesToHex(base64UrlToBytes(vm.publicKeyJwk.x)),
49
- y: bytesToHex(base64UrlToBytes(vm.publicKeyJwk.y))
50
- })
51
- .getPublic('hex')),
51
+ publicKeyBytes: sec.ProjectivePoint.fromAffine({
52
+ x,
53
+ y
54
+ }).toRawBytes(false),
52
55
  kmsKeyType: KmsKeyType.Secp256k1
53
56
  };
54
57
  }