@0xpolygonid/js-sdk 1.21.3 → 1.23.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 (78) hide show
  1. package/dist/browser/esm/index.js +1358 -270
  2. package/dist/browser/esm/index.js.map +1 -1
  3. package/dist/browser/umd/index.js +1363 -270
  4. package/dist/browser/umd/index.js.map +1 -1
  5. package/dist/node/cjs/iden3comm/constants.js +25 -1
  6. package/dist/node/cjs/iden3comm/handlers/auth.js +52 -8
  7. package/dist/node/cjs/iden3comm/handlers/common.js +13 -1
  8. package/dist/node/cjs/iden3comm/handlers/contract-request.js +5 -1
  9. package/dist/node/cjs/iden3comm/handlers/credential-proposal.js +14 -3
  10. package/dist/node/cjs/iden3comm/handlers/fetch.js +12 -2
  11. package/dist/node/cjs/iden3comm/handlers/message-handler.js +4 -0
  12. package/dist/node/cjs/iden3comm/handlers/payment.js +240 -28
  13. package/dist/node/cjs/iden3comm/handlers/revocation-status.js +4 -0
  14. package/dist/node/cjs/iden3comm/index.js +1 -0
  15. package/dist/node/cjs/iden3comm/packageManager.js +12 -0
  16. package/dist/node/cjs/iden3comm/packers/jws.js +21 -0
  17. package/dist/node/cjs/iden3comm/packers/plain.js +19 -0
  18. package/dist/node/cjs/iden3comm/packers/zkp.js +25 -0
  19. package/dist/node/cjs/iden3comm/types/index.js +1 -0
  20. package/dist/node/cjs/iden3comm/types/protocol/accept-profile.js +2 -0
  21. package/dist/node/cjs/iden3comm/utils/accept-profile.js +107 -0
  22. package/dist/node/cjs/iden3comm/utils/index.js +1 -0
  23. package/dist/node/cjs/storage/blockchain/abi/ERC20Permit.json +1 -0
  24. package/dist/node/cjs/storage/blockchain/erc20-permit-sig.js +46 -0
  25. package/dist/node/cjs/storage/blockchain/index.js +1 -0
  26. package/dist/node/cjs/verifiable/constants.js +28 -11
  27. package/dist/node/esm/iden3comm/constants.js +24 -0
  28. package/dist/node/esm/iden3comm/handlers/auth.js +55 -11
  29. package/dist/node/esm/iden3comm/handlers/common.js +11 -0
  30. package/dist/node/esm/iden3comm/handlers/contract-request.js +7 -3
  31. package/dist/node/esm/iden3comm/handlers/credential-proposal.js +15 -4
  32. package/dist/node/esm/iden3comm/handlers/fetch.js +12 -2
  33. package/dist/node/esm/iden3comm/handlers/message-handler.js +4 -0
  34. package/dist/node/esm/iden3comm/handlers/payment.js +240 -29
  35. package/dist/node/esm/iden3comm/handlers/revocation-status.js +4 -0
  36. package/dist/node/esm/iden3comm/index.js +1 -0
  37. package/dist/node/esm/iden3comm/packageManager.js +12 -0
  38. package/dist/node/esm/iden3comm/packers/jws.js +22 -1
  39. package/dist/node/esm/iden3comm/packers/plain.js +19 -0
  40. package/dist/node/esm/iden3comm/packers/zkp.js +26 -1
  41. package/dist/node/esm/iden3comm/types/index.js +1 -0
  42. package/dist/node/esm/iden3comm/types/protocol/accept-profile.js +1 -0
  43. package/dist/node/esm/iden3comm/utils/accept-profile.js +102 -0
  44. package/dist/node/esm/iden3comm/utils/index.js +1 -0
  45. package/dist/node/esm/storage/blockchain/abi/ERC20Permit.json +1 -0
  46. package/dist/node/esm/storage/blockchain/erc20-permit-sig.js +39 -0
  47. package/dist/node/esm/storage/blockchain/index.js +1 -0
  48. package/dist/node/esm/verifiable/constants.js +27 -10
  49. package/dist/types/iden3comm/constants.d.ts +16 -0
  50. package/dist/types/iden3comm/handlers/auth.d.ts +19 -7
  51. package/dist/types/iden3comm/handlers/common.d.ts +7 -1
  52. package/dist/types/iden3comm/handlers/contract-request.d.ts +2 -2
  53. package/dist/types/iden3comm/handlers/credential-proposal.d.ts +9 -4
  54. package/dist/types/iden3comm/handlers/fetch.d.ts +22 -6
  55. package/dist/types/iden3comm/handlers/message-handler.d.ts +6 -0
  56. package/dist/types/iden3comm/handlers/payment.d.ts +70 -10
  57. package/dist/types/iden3comm/handlers/revocation-status.d.ts +2 -2
  58. package/dist/types/iden3comm/index.d.ts +1 -0
  59. package/dist/types/iden3comm/packageManager.d.ts +4 -0
  60. package/dist/types/iden3comm/packers/jws.d.ts +5 -0
  61. package/dist/types/iden3comm/packers/plain.d.ts +4 -0
  62. package/dist/types/iden3comm/packers/zkp.d.ts +6 -0
  63. package/dist/types/iden3comm/types/index.d.ts +1 -0
  64. package/dist/types/iden3comm/types/packageManager.d.ts +14 -0
  65. package/dist/types/iden3comm/types/packer.d.ts +25 -0
  66. package/dist/types/iden3comm/types/protocol/accept-profile.d.ts +7 -0
  67. package/dist/types/iden3comm/types/protocol/auth.d.ts +1 -0
  68. package/dist/types/iden3comm/types/protocol/credentials.d.ts +6 -6
  69. package/dist/types/iden3comm/types/protocol/messages.d.ts +2 -2
  70. package/dist/types/iden3comm/types/protocol/payment.d.ts +87 -13
  71. package/dist/types/iden3comm/types/protocol/proof.d.ts +3 -3
  72. package/dist/types/iden3comm/types/protocol/revocation.d.ts +2 -2
  73. package/dist/types/iden3comm/utils/accept-profile.d.ts +3 -0
  74. package/dist/types/iden3comm/utils/index.d.ts +1 -0
  75. package/dist/types/storage/blockchain/erc20-permit-sig.d.ts +12 -0
  76. package/dist/types/storage/blockchain/index.d.ts +1 -0
  77. package/dist/types/verifiable/constants.d.ts +27 -11
  78. package/package.json +2 -2
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.getPermitSignature = void 0;
7
+ const ethers_1 = require("ethers");
8
+ const ERC20Permit_json_1 = __importDefault(require("./abi/ERC20Permit.json"));
9
+ /**
10
+ * @beta
11
+ * getPermitSignature is a function to create EIP712 Permit signature
12
+ * @param {Signer} signer - User who owns the tokens
13
+ * @param {string} tokenAddress - EIP-2612 contract address
14
+ * @param {string} spender - The contract address that will spend tokens
15
+ * @param {bigint} value - Amount of tokens to approve
16
+ * @param {number} deadline - Timestamp when the permit expires
17
+ * @returns {Promise<PaymentRequestMessage>}
18
+ */
19
+ async function getPermitSignature(signer, tokenAddress, spender, value, deadline) {
20
+ const erc20PermitContract = new ethers_1.Contract(tokenAddress, ERC20Permit_json_1.default, signer);
21
+ const nonce = await erc20PermitContract.nonces(await signer.getAddress());
22
+ const domainData = await erc20PermitContract.eip712Domain();
23
+ const domain = {
24
+ version: domainData[2],
25
+ chainId: domainData[3],
26
+ verifyingContract: tokenAddress
27
+ };
28
+ const types = {
29
+ Permit: [
30
+ { name: 'owner', type: 'address' },
31
+ { name: 'spender', type: 'address' },
32
+ { name: 'value', type: 'uint256' },
33
+ { name: 'nonce', type: 'uint256' },
34
+ { name: 'deadline', type: 'uint256' }
35
+ ]
36
+ };
37
+ const message = {
38
+ owner: await signer.getAddress(),
39
+ spender: spender,
40
+ value: value,
41
+ nonce: nonce,
42
+ deadline: deadline
43
+ };
44
+ return signer.signTypedData(domain, types, message);
45
+ }
46
+ exports.getPermitSignature = getPermitSignature;
@@ -17,3 +17,4 @@ Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./state"), exports);
18
18
  __exportStar(require("./onchain-zkp-verifier"), exports);
19
19
  __exportStar(require("./onchain-revocation"), exports);
20
+ __exportStar(require("./erc20-permit-sig"), exports);
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DisplayMethodType = exports.SupportedCurrencies = exports.PaymentType = exports.PaymentRequestDataType = exports.PaymentRequestType = exports.RefreshServiceType = exports.SubjectPosition = exports.MerklizedRootPosition = exports.ProofPurpose = exports.CredentialStatusType = exports.ProofType = exports.VerifiableConstants = void 0;
3
+ exports.DisplayMethodType = exports.PaymentFeatures = exports.SupportedCurrencies = exports.SupportedPaymentProofType = exports.PaymentType = exports.PaymentRequestDataType = exports.RefreshServiceType = exports.SubjectPosition = exports.MerklizedRootPosition = exports.ProofPurpose = exports.CredentialStatusType = exports.ProofType = exports.VerifiableConstants = void 0;
4
4
  /** Verifiable constants */
5
5
  exports.VerifiableConstants = Object.freeze({
6
6
  ERRORS: {
@@ -115,15 +115,6 @@ var RefreshServiceType;
115
115
  (function (RefreshServiceType) {
116
116
  RefreshServiceType["Iden3RefreshService2023"] = "Iden3RefreshService2023";
117
117
  })(RefreshServiceType = exports.RefreshServiceType || (exports.RefreshServiceType = {}));
118
- /**
119
- * PaymentRequestType type for payment requests
120
- * @beta
121
- * @enum {string}
122
- */
123
- var PaymentRequestType;
124
- (function (PaymentRequestType) {
125
- PaymentRequestType["PaymentRequest"] = "PaymentRequest";
126
- })(PaymentRequestType = exports.PaymentRequestType || (exports.PaymentRequestType = {}));
127
118
  /**
128
119
  * PaymentRequestDataType type for payment requests
129
120
  * @beta
@@ -132,6 +123,8 @@ var PaymentRequestType;
132
123
  var PaymentRequestDataType;
133
124
  (function (PaymentRequestDataType) {
134
125
  PaymentRequestDataType["Iden3PaymentRequestCryptoV1"] = "Iden3PaymentRequestCryptoV1";
126
+ PaymentRequestDataType["Iden3PaymentRailsRequestV1"] = "Iden3PaymentRailsRequestV1";
127
+ PaymentRequestDataType["Iden3PaymentRailsERC20RequestV1"] = "Iden3PaymentRailsERC20RequestV1";
135
128
  })(PaymentRequestDataType = exports.PaymentRequestDataType || (exports.PaymentRequestDataType = {}));
136
129
  /**
137
130
  * PaymentType type for payment responses
@@ -141,17 +134,41 @@ var PaymentRequestDataType;
141
134
  var PaymentType;
142
135
  (function (PaymentType) {
143
136
  PaymentType["Iden3PaymentCryptoV1"] = "Iden3PaymentCryptoV1";
137
+ PaymentType["Iden3PaymentRailsV1"] = "Iden3PaymentRailsV1";
138
+ PaymentType["Iden3PaymentRailsERC20V1"] = "Iden3PaymentRailsERC20V1";
144
139
  })(PaymentType = exports.PaymentType || (exports.PaymentType = {}));
140
+ /**
141
+ * SupportedPaymentProofType type for payment proofs
142
+ * @beta
143
+ * @enum {string}
144
+ */
145
+ var SupportedPaymentProofType;
146
+ (function (SupportedPaymentProofType) {
147
+ SupportedPaymentProofType["EthereumEip712Signature2021"] = "EthereumEip712Signature2021";
148
+ })(SupportedPaymentProofType = exports.SupportedPaymentProofType || (exports.SupportedPaymentProofType = {}));
145
149
  /**
146
150
  * Media types for Payment supported currencies
147
151
  * @beta
148
- * @enum {number}
152
+ * @enum {string}
149
153
  */
150
154
  var SupportedCurrencies;
151
155
  (function (SupportedCurrencies) {
152
156
  SupportedCurrencies["ETH"] = "ETH";
157
+ SupportedCurrencies["ETH_WEI"] = "ETHWEI";
158
+ SupportedCurrencies["ETH_GWEI"] = "ETHGWEI";
153
159
  SupportedCurrencies["MATIC"] = "MATIC";
160
+ SupportedCurrencies["USDT"] = "USDT";
161
+ SupportedCurrencies["USDC"] = "USDC";
154
162
  })(SupportedCurrencies = exports.SupportedCurrencies || (exports.SupportedCurrencies = {}));
163
+ /**
164
+ * Supported features for payment-request
165
+ * @beta
166
+ * @enum {string}
167
+ */
168
+ var PaymentFeatures;
169
+ (function (PaymentFeatures) {
170
+ PaymentFeatures["EIP_2612"] = "EIP-2612";
171
+ })(PaymentFeatures = exports.PaymentFeatures || (exports.PaymentFeatures = {}));
155
172
  /**
156
173
  * DisplayMethodType type for display method
157
174
  *
@@ -73,5 +73,29 @@ export const SUPPORTED_PUBLIC_KEY_TYPES = {
73
73
  'JsonWebKey2020'
74
74
  ]
75
75
  };
76
+ export var ProtocolVersion;
77
+ (function (ProtocolVersion) {
78
+ ProtocolVersion["V1"] = "iden3comm/v1";
79
+ })(ProtocolVersion || (ProtocolVersion = {}));
80
+ export var AcceptAuthCircuits;
81
+ (function (AcceptAuthCircuits) {
82
+ AcceptAuthCircuits["AuthV2"] = "authV2";
83
+ AcceptAuthCircuits["AuthV3"] = "authV3";
84
+ })(AcceptAuthCircuits || (AcceptAuthCircuits = {}));
85
+ export var AcceptJwzAlgorithms;
86
+ (function (AcceptJwzAlgorithms) {
87
+ AcceptJwzAlgorithms["Groth16"] = "groth16";
88
+ })(AcceptJwzAlgorithms || (AcceptJwzAlgorithms = {}));
89
+ export var AcceptJwsAlgorithms;
90
+ (function (AcceptJwsAlgorithms) {
91
+ AcceptJwsAlgorithms["ES256K"] = "ES256K";
92
+ AcceptJwsAlgorithms["ES256KR"] = "ES256K-R";
93
+ })(AcceptJwsAlgorithms || (AcceptJwsAlgorithms = {}));
94
+ export const defaultAcceptProfile = {
95
+ protocolVersion: ProtocolVersion.V1,
96
+ env: MediaType.ZKPMessage,
97
+ circuits: [AcceptAuthCircuits.AuthV2],
98
+ alg: [AcceptJwzAlgorithms.Groth16]
99
+ };
76
100
  export const DEFAULT_PROOF_VERIFY_DELAY = 1 * 60 * 60 * 1000; // 1 hour
77
101
  export const DEFAULT_AUTH_VERIFY_DELAY = 5 * 60 * 1000; // 5 minutes
@@ -1,21 +1,23 @@
1
- import { MediaType } from '../constants';
1
+ import { MediaType, ProtocolVersion } from '../constants';
2
2
  import { PROTOCOL_MESSAGE_TYPE } from '../constants';
3
- import { DID } from '@iden3/js-iden3-core';
3
+ import { DID, getUnixTimestamp } from '@iden3/js-iden3-core';
4
4
  import { proving } from '@iden3/js-jwz';
5
5
  import * as uuid from 'uuid';
6
6
  import { byteDecoder, byteEncoder } from '../../utils';
7
- import { processZeroKnowledgeProofRequests } from './common';
7
+ import { processZeroKnowledgeProofRequests, verifyExpiresTime } from './common';
8
8
  import { CircuitId } from '../../circuits';
9
9
  import { AbstractMessageHandler } from './message-handler';
10
+ import { parseAcceptProfile } from '../utils';
10
11
  /**
11
12
  * createAuthorizationRequest is a function to create protocol authorization request
12
13
  * @param {string} reason - reason to request proof
13
14
  * @param {string} sender - sender did
14
15
  * @param {string} callbackUrl - callback that user should use to send response
16
+ * @param {AuthorizationRequestCreateOptions} opts - authorization request options
15
17
  * @returns `Promise<AuthorizationRequestMessage>`
16
18
  */
17
- export function createAuthorizationRequest(reason, sender, callbackUrl) {
18
- return createAuthorizationRequestWithMessage(reason, '', sender, callbackUrl);
19
+ export function createAuthorizationRequest(reason, sender, callbackUrl, opts) {
20
+ return createAuthorizationRequestWithMessage(reason, '', sender, callbackUrl, opts);
19
21
  }
20
22
  /**
21
23
  * createAuthorizationRequestWithMessage is a function to create protocol authorization request with explicit message to sign
@@ -23,9 +25,10 @@ export function createAuthorizationRequest(reason, sender, callbackUrl) {
23
25
  * @param {string} message - message to sign in the response
24
26
  * @param {string} sender - sender did
25
27
  * @param {string} callbackUrl - callback that user should use to send response
28
+ * @param {AuthorizationRequestCreateOptions} opts - authorization request options
26
29
  * @returns `Promise<AuthorizationRequestMessage>`
27
30
  */
28
- export function createAuthorizationRequestWithMessage(reason, message, sender, callbackUrl) {
31
+ export function createAuthorizationRequestWithMessage(reason, message, sender, callbackUrl, opts) {
29
32
  const uuidv4 = uuid.v4();
30
33
  const request = {
31
34
  id: uuidv4,
@@ -34,11 +37,14 @@ export function createAuthorizationRequestWithMessage(reason, message, sender, c
34
37
  typ: MediaType.PlainMessage,
35
38
  type: PROTOCOL_MESSAGE_TYPE.AUTHORIZATION_REQUEST_MESSAGE_TYPE,
36
39
  body: {
40
+ accept: opts?.accept,
37
41
  reason: reason,
38
42
  message: message,
39
43
  callbackUrl: callbackUrl,
40
- scope: []
41
- }
44
+ scope: opts?.scope ?? []
45
+ },
46
+ created_time: getUnixTimestamp(new Date()),
47
+ expires_time: opts?.expires_time ? getUnixTimestamp(opts.expires_time) : undefined
42
48
  };
43
49
  return request;
44
50
  }
@@ -97,17 +103,18 @@ export class AuthHandler extends AbstractMessageHandler {
97
103
  }
98
104
  // override sender did if it's explicitly specified in the auth request
99
105
  const to = authRequest.to ? DID.parse(authRequest.to) : ctx.senderDid;
100
- const mediaType = ctx.mediaType || MediaType.ZKPMessage;
101
106
  const guid = uuid.v4();
102
107
  if (!authRequest.from) {
103
108
  throw new Error('auth request should contain from field');
104
109
  }
110
+ const responseType = PROTOCOL_MESSAGE_TYPE.AUTHORIZATION_RESPONSE_MESSAGE_TYPE;
111
+ const mediaType = this.getSupportedMediaTypeByProfile(ctx, responseType, authRequest.body.accept);
105
112
  const from = DID.parse(authRequest.from);
106
113
  const responseScope = await processZeroKnowledgeProofRequests(to, authRequest?.body.scope, from, this._proofService, { mediaType, supportedCircuits: this._supportedCircuits });
107
114
  return {
108
115
  id: guid,
109
- typ: ctx.mediaType,
110
- type: PROTOCOL_MESSAGE_TYPE.AUTHORIZATION_RESPONSE_MESSAGE_TYPE,
116
+ typ: mediaType,
117
+ type: responseType,
111
118
  thid: authRequest.thid ?? guid,
112
119
  body: {
113
120
  message: authRequest?.body?.message,
@@ -122,6 +129,9 @@ export class AuthHandler extends AbstractMessageHandler {
122
129
  */
123
130
  async handleAuthorizationRequest(did, request, opts) {
124
131
  const authRequest = await this.parseAuthorizationRequest(request);
132
+ if (!opts?.allowExpiredMessages) {
133
+ verifyExpiresTime(authRequest);
134
+ }
125
135
  if (!opts) {
126
136
  opts = {
127
137
  mediaType: MediaType.ZKPMessage
@@ -211,6 +221,9 @@ export class AuthHandler extends AbstractMessageHandler {
211
221
  * @inheritdoc IAuthHandler#handleAuthorizationResponse
212
222
  */
213
223
  async handleAuthorizationResponse(response, request, opts) {
224
+ if (!opts?.allowExpiredMessages) {
225
+ verifyExpiresTime(response);
226
+ }
214
227
  const authResp = (await this.handleAuthResponse(response, {
215
228
  request,
216
229
  acceptedStateTransitionDelay: opts?.acceptedStateTransitionDelay,
@@ -244,4 +257,35 @@ export class AuthHandler extends AbstractMessageHandler {
244
257
  }
245
258
  }
246
259
  }
260
+ getSupportedMediaTypeByProfile(ctx, responseType, profile) {
261
+ let mediaType;
262
+ if (profile?.length) {
263
+ const supportedMediaTypes = [];
264
+ for (const acceptProfile of profile) {
265
+ // 1. check protocol version
266
+ const { protocolVersion, env } = parseAcceptProfile(acceptProfile);
267
+ const responseTypeVersion = Number(responseType.split('/').at(-2));
268
+ if (protocolVersion !== ProtocolVersion.V1 ||
269
+ (protocolVersion === ProtocolVersion.V1 &&
270
+ (responseTypeVersion < 1 || responseTypeVersion >= 2))) {
271
+ continue;
272
+ }
273
+ // 2. check packer support
274
+ if (this._packerMgr.isProfileSupported(env, acceptProfile)) {
275
+ supportedMediaTypes.push(env);
276
+ }
277
+ }
278
+ if (!supportedMediaTypes.length) {
279
+ throw new Error('no packer with profile which meets `accept` header requirements');
280
+ }
281
+ mediaType = supportedMediaTypes[0];
282
+ if (ctx.mediaType && supportedMediaTypes.includes(ctx.mediaType)) {
283
+ mediaType = ctx.mediaType;
284
+ }
285
+ }
286
+ else {
287
+ mediaType = ctx.mediaType || MediaType.ZKPMessage;
288
+ }
289
+ return mediaType;
290
+ }
247
291
  }
@@ -1,5 +1,6 @@
1
1
  import { getRandomBytes } from '@iden3/js-crypto';
2
2
  import { mergeObjects } from '../../utils';
3
+ import { getUnixTimestamp } from '@iden3/js-iden3-core';
3
4
  /**
4
5
  * Groups the ZeroKnowledgeProofRequest objects based on their groupId.
5
6
  * Returns a Map where the key is the groupId and the value is an object containing the query and linkNonce.
@@ -79,3 +80,13 @@ export const processZeroKnowledgeProofRequests = async (to, requests, from, proo
79
80
  }
80
81
  return zkpResponses;
81
82
  };
83
+ /**
84
+ * Verifies that the expires_time field of a message is not in the past. Throws an error if it is.
85
+ *
86
+ * @param message - Basic message to verify.
87
+ */
88
+ export const verifyExpiresTime = (message) => {
89
+ if (message?.expires_time && message.expires_time < getUnixTimestamp(new Date())) {
90
+ throw new Error('Message expired');
91
+ }
92
+ };
@@ -1,8 +1,8 @@
1
1
  import { CircuitId } from '../../circuits/models';
2
2
  import { PROTOCOL_MESSAGE_TYPE } from '../constants';
3
- import { DID, ChainIds } from '@iden3/js-iden3-core';
3
+ import { DID, ChainIds, getUnixTimestamp } from '@iden3/js-iden3-core';
4
4
  import { FunctionSignatures } from '../../storage';
5
- import { processZeroKnowledgeProofRequests } from './common';
5
+ import { processZeroKnowledgeProofRequests, verifyExpiresTime } from './common';
6
6
  import { AbstractMessageHandler } from './message-handler';
7
7
  /**
8
8
  *
@@ -107,7 +107,8 @@ export class ContractRequestHandler extends AbstractMessageHandler {
107
107
  body: {
108
108
  transaction_data: request.body.transaction_data,
109
109
  scope: []
110
- }
110
+ },
111
+ created_time: getUnixTimestamp(new Date())
111
112
  };
112
113
  for (const [txHash, zkpResponses] of txHashToZkpResponseMap) {
113
114
  for (const zkpResponse of zkpResponses) {
@@ -131,6 +132,9 @@ export class ContractRequestHandler extends AbstractMessageHandler {
131
132
  */
132
133
  async handleContractInvokeRequest(did, request, opts) {
133
134
  const ciRequest = await this.parseContractInvokeRequest(request);
135
+ if (!opts.allowExpiredMessages) {
136
+ verifyExpiresTime(ciRequest);
137
+ }
134
138
  if (ciRequest.body.transaction_data.method_id !== FunctionSignatures.SubmitZKPResponseV1) {
135
139
  throw new Error(`please use handle method to work with other method ids`);
136
140
  }
@@ -1,9 +1,10 @@
1
1
  import { PROTOCOL_MESSAGE_TYPE, MediaType } from '../constants';
2
- import { DID } from '@iden3/js-iden3-core';
2
+ import { DID, getUnixTimestamp } from '@iden3/js-iden3-core';
3
3
  import * as uuid from 'uuid';
4
4
  import { proving } from '@iden3/js-jwz';
5
5
  import { byteEncoder } from '../../utils';
6
6
  import { AbstractMessageHandler } from './message-handler';
7
+ import { verifyExpiresTime } from './common';
7
8
  /**
8
9
  * @beta
9
10
  * createProposalRequest is a function to create protocol proposal-request protocol message
@@ -21,7 +22,9 @@ export function createProposalRequest(sender, receiver, opts) {
21
22
  to: receiver.string(),
22
23
  typ: MediaType.PlainMessage,
23
24
  type: PROTOCOL_MESSAGE_TYPE.PROPOSAL_REQUEST_MESSAGE_TYPE,
24
- body: opts
25
+ body: opts,
26
+ created_time: getUnixTimestamp(new Date()),
27
+ expires_time: opts?.expires_time ? getUnixTimestamp(opts.expires_time) : undefined
25
28
  };
26
29
  return request;
27
30
  }
@@ -33,7 +36,7 @@ export function createProposalRequest(sender, receiver, opts) {
33
36
  * @param {Proposal[]} proposals - proposals
34
37
  * @returns `Promise<ProposalRequestMessage>`
35
38
  */
36
- export function createProposal(sender, receiver, proposals) {
39
+ export function createProposal(sender, receiver, proposals, opts) {
37
40
  const uuidv4 = uuid.v4();
38
41
  const request = {
39
42
  id: uuidv4,
@@ -44,7 +47,9 @@ export function createProposal(sender, receiver, proposals) {
44
47
  type: PROTOCOL_MESSAGE_TYPE.PROPOSAL_MESSAGE_TYPE,
45
48
  body: {
46
49
  proposals: proposals || []
47
- }
50
+ },
51
+ created_time: getUnixTimestamp(new Date()),
52
+ expires_time: opts?.expires_time ? getUnixTimestamp(opts.expires_time) : undefined
48
53
  };
49
54
  return request;
50
55
  }
@@ -182,6 +187,9 @@ export class CredentialProposalHandler extends AbstractMessageHandler {
182
187
  if (!proposalRequest.from) {
183
188
  throw new Error(`failed request. empty 'from' field`);
184
189
  }
190
+ if (!opts?.allowExpiredMessages) {
191
+ verifyExpiresTime(proposalRequest);
192
+ }
185
193
  const senderDID = DID.parse(proposalRequest.from);
186
194
  const message = await this.handleProposalRequestMessage(proposalRequest);
187
195
  const response = byteEncoder.encode(JSON.stringify(message));
@@ -199,6 +207,9 @@ export class CredentialProposalHandler extends AbstractMessageHandler {
199
207
  * @inheritdoc ICredentialProposalHandler#handleProposal
200
208
  */
201
209
  async handleProposal(proposal, opts) {
210
+ if (!opts?.allowExpiredMessages) {
211
+ verifyExpiresTime(proposal);
212
+ }
202
213
  if (opts?.proposalRequest && opts.proposalRequest.from !== proposal.to) {
203
214
  throw new Error(`sender of the request is not a target of response - expected ${opts.proposalRequest.from}, given ${proposal.to}`);
204
215
  }
@@ -7,6 +7,7 @@ import { proving } from '@iden3/js-jwz';
7
7
  import { DID } from '@iden3/js-iden3-core';
8
8
  import * as uuid from 'uuid';
9
9
  import { AbstractMessageHandler } from './message-handler';
10
+ import { verifyExpiresTime } from './common';
10
11
  /**
11
12
  *
12
13
  * Allows to handle Credential offer protocol message and return fetched credential
@@ -121,6 +122,9 @@ export class FetchHandler extends AbstractMessageHandler {
121
122
  throw new Error(`jws packer options are required for ${MediaType.SignedMessage}`);
122
123
  }
123
124
  const offerMessage = await FetchHandler.unpackMessage(this._packerMgr, offer, PROTOCOL_MESSAGE_TYPE.CREDENTIAL_OFFER_MESSAGE_TYPE);
125
+ if (!opts?.allowExpiredMessages) {
126
+ verifyExpiresTime(offerMessage);
127
+ }
124
128
  const result = await this.handleOfferMessage(offerMessage, {
125
129
  mediaType: opts?.mediaType,
126
130
  headers: opts?.headers,
@@ -168,8 +172,11 @@ export class FetchHandler extends AbstractMessageHandler {
168
172
  /**
169
173
  * @inheritdoc IFetchHandler#handleCredentialFetchRequest
170
174
  */
171
- async handleCredentialFetchRequest(envelope) {
175
+ async handleCredentialFetchRequest(envelope, opts) {
172
176
  const msgRequest = await FetchHandler.unpackMessage(this._packerMgr, envelope, PROTOCOL_MESSAGE_TYPE.CREDENTIAL_FETCH_REQUEST_MESSAGE_TYPE);
177
+ if (!opts?.allowExpiredMessages) {
178
+ verifyExpiresTime(msgRequest);
179
+ }
173
180
  const request = await this.handleFetchRequest(msgRequest);
174
181
  return this._packerMgr.pack(MediaType.PlainMessage, byteEncoder.encode(JSON.stringify(request)), {});
175
182
  }
@@ -186,8 +193,11 @@ export class FetchHandler extends AbstractMessageHandler {
186
193
  /**
187
194
  * @inheritdoc IFetchHandler#handleIssuanceResponseMessage
188
195
  */
189
- async handleIssuanceResponseMessage(envelop) {
196
+ async handleIssuanceResponseMessage(envelop, opts) {
190
197
  const issuanceMsg = await FetchHandler.unpackMessage(this._packerMgr, envelop, PROTOCOL_MESSAGE_TYPE.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE);
198
+ if (!opts?.allowExpiredMessages) {
199
+ verifyExpiresTime(issuanceMsg);
200
+ }
191
201
  await this.handleIssuanceResponseMsg(issuanceMsg);
192
202
  return Uint8Array.from([]);
193
203
  }
@@ -1,5 +1,6 @@
1
1
  import { MediaType } from '../constants';
2
2
  import { proving } from '@iden3/js-jwz';
3
+ import { verifyExpiresTime } from './common';
3
4
  /**
4
5
  * Base implementation of protocol message handler
5
6
  *
@@ -14,6 +15,9 @@ export class AbstractMessageHandler {
14
15
  return messageHandler;
15
16
  }
16
17
  async handle(message, context) {
18
+ if (!context.allowExpiredMessages) {
19
+ verifyExpiresTime(message);
20
+ }
17
21
  if (this.nextMessageHandler)
18
22
  return this.nextMessageHandler.handle(message, context);
19
23
  return Promise.reject('Message handler not provided or message not supported');