@0xpolygonid/js-sdk 1.21.3 → 1.24.1

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 (114) hide show
  1. package/dist/browser/esm/index.js +4378 -545
  2. package/dist/browser/esm/index.js.map +1 -1
  3. package/dist/browser/umd/index.js +4388 -545
  4. package/dist/browser/umd/index.js.map +1 -1
  5. package/dist/node/cjs/credentials/credential-wallet.js +11 -78
  6. package/dist/node/cjs/credentials/index.js +1 -0
  7. package/dist/node/cjs/credentials/status/did-resolver-revocation.js +21 -0
  8. package/dist/node/cjs/iden3comm/constants.js +25 -1
  9. package/dist/node/cjs/iden3comm/handlers/auth.js +52 -8
  10. package/dist/node/cjs/iden3comm/handlers/common.js +13 -1
  11. package/dist/node/cjs/iden3comm/handlers/contract-request.js +5 -1
  12. package/dist/node/cjs/iden3comm/handlers/credential-proposal.js +14 -3
  13. package/dist/node/cjs/iden3comm/handlers/fetch.js +44 -2
  14. package/dist/node/cjs/iden3comm/handlers/message-handler.js +4 -0
  15. package/dist/node/cjs/iden3comm/handlers/payment.js +265 -28
  16. package/dist/node/cjs/iden3comm/handlers/revocation-status.js +4 -0
  17. package/dist/node/cjs/iden3comm/index.js +1 -0
  18. package/dist/node/cjs/iden3comm/packageManager.js +12 -0
  19. package/dist/node/cjs/iden3comm/packers/jws.js +21 -0
  20. package/dist/node/cjs/iden3comm/packers/plain.js +19 -0
  21. package/dist/node/cjs/iden3comm/packers/zkp.js +25 -0
  22. package/dist/node/cjs/iden3comm/types/index.js +1 -0
  23. package/dist/node/cjs/iden3comm/types/protocol/accept-profile.js +2 -0
  24. package/dist/node/cjs/iden3comm/utils/accept-profile.js +107 -0
  25. package/dist/node/cjs/iden3comm/utils/index.js +1 -0
  26. package/dist/node/cjs/storage/blockchain/abi/ERC20.json +1 -0
  27. package/dist/node/cjs/storage/blockchain/abi/ERC20Permit.json +1 -0
  28. package/dist/node/cjs/storage/blockchain/did-resolver-readonly-storage.js +72 -0
  29. package/dist/node/cjs/storage/blockchain/erc20-helper.js +59 -0
  30. package/dist/node/cjs/storage/blockchain/index.js +3 -0
  31. package/dist/node/cjs/storage/blockchain/onchain-issuer-adapter/non-merklized/version/v0.0.1/onchain-non-merklized-issuer-adapter.js +245 -0
  32. package/dist/node/cjs/storage/blockchain/onchain-issuer.js +82 -0
  33. package/dist/node/cjs/storage/blockchain/onchain-zkp-verifier.js +38 -34
  34. package/dist/node/cjs/storage/interfaces/index.js +1 -0
  35. package/dist/node/cjs/storage/interfaces/onchain-issuer.js +2 -0
  36. package/dist/node/cjs/utils/did-helper.js +3 -3
  37. package/dist/node/cjs/verifiable/constants.js +29 -11
  38. package/dist/node/cjs/verifiable/credential.js +86 -0
  39. package/dist/node/esm/credentials/credential-wallet.js +12 -79
  40. package/dist/node/esm/credentials/index.js +1 -0
  41. package/dist/node/esm/credentials/status/did-resolver-revocation.js +17 -0
  42. package/dist/node/esm/iden3comm/constants.js +24 -0
  43. package/dist/node/esm/iden3comm/handlers/auth.js +55 -11
  44. package/dist/node/esm/iden3comm/handlers/common.js +11 -0
  45. package/dist/node/esm/iden3comm/handlers/contract-request.js +7 -3
  46. package/dist/node/esm/iden3comm/handlers/credential-proposal.js +15 -4
  47. package/dist/node/esm/iden3comm/handlers/fetch.js +44 -2
  48. package/dist/node/esm/iden3comm/handlers/message-handler.js +4 -0
  49. package/dist/node/esm/iden3comm/handlers/payment.js +264 -29
  50. package/dist/node/esm/iden3comm/handlers/revocation-status.js +4 -0
  51. package/dist/node/esm/iden3comm/index.js +1 -0
  52. package/dist/node/esm/iden3comm/packageManager.js +12 -0
  53. package/dist/node/esm/iden3comm/packers/jws.js +22 -1
  54. package/dist/node/esm/iden3comm/packers/plain.js +19 -0
  55. package/dist/node/esm/iden3comm/packers/zkp.js +26 -1
  56. package/dist/node/esm/iden3comm/types/index.js +1 -0
  57. package/dist/node/esm/iden3comm/types/protocol/accept-profile.js +1 -0
  58. package/dist/node/esm/iden3comm/utils/accept-profile.js +102 -0
  59. package/dist/node/esm/iden3comm/utils/index.js +1 -0
  60. package/dist/node/esm/storage/blockchain/abi/ERC20.json +1 -0
  61. package/dist/node/esm/storage/blockchain/abi/ERC20Permit.json +1 -0
  62. package/dist/node/esm/storage/blockchain/did-resolver-readonly-storage.js +68 -0
  63. package/dist/node/esm/storage/blockchain/erc20-helper.js +51 -0
  64. package/dist/node/esm/storage/blockchain/index.js +3 -0
  65. package/dist/node/esm/storage/blockchain/onchain-issuer-adapter/non-merklized/version/v0.0.1/onchain-non-merklized-issuer-adapter.js +241 -0
  66. package/dist/node/esm/storage/blockchain/onchain-issuer.js +78 -0
  67. package/dist/node/esm/storage/blockchain/onchain-zkp-verifier.js +38 -34
  68. package/dist/node/esm/storage/interfaces/index.js +1 -0
  69. package/dist/node/esm/storage/interfaces/onchain-issuer.js +1 -0
  70. package/dist/node/esm/utils/did-helper.js +3 -3
  71. package/dist/node/esm/verifiable/constants.js +28 -10
  72. package/dist/node/esm/verifiable/credential.js +88 -2
  73. package/dist/types/credentials/credential-wallet.d.ts +0 -6
  74. package/dist/types/credentials/index.d.ts +1 -0
  75. package/dist/types/credentials/models.d.ts +8 -0
  76. package/dist/types/credentials/status/did-resolver-revocation.d.ts +7 -0
  77. package/dist/types/iden3comm/constants.d.ts +16 -0
  78. package/dist/types/iden3comm/handlers/auth.d.ts +19 -7
  79. package/dist/types/iden3comm/handlers/common.d.ts +7 -1
  80. package/dist/types/iden3comm/handlers/contract-request.d.ts +2 -2
  81. package/dist/types/iden3comm/handlers/credential-proposal.d.ts +9 -4
  82. package/dist/types/iden3comm/handlers/fetch.d.ts +30 -6
  83. package/dist/types/iden3comm/handlers/message-handler.d.ts +6 -0
  84. package/dist/types/iden3comm/handlers/payment.d.ts +71 -10
  85. package/dist/types/iden3comm/handlers/revocation-status.d.ts +2 -2
  86. package/dist/types/iden3comm/index.d.ts +1 -0
  87. package/dist/types/iden3comm/packageManager.d.ts +4 -0
  88. package/dist/types/iden3comm/packers/jws.d.ts +5 -0
  89. package/dist/types/iden3comm/packers/plain.d.ts +4 -0
  90. package/dist/types/iden3comm/packers/zkp.d.ts +6 -0
  91. package/dist/types/iden3comm/types/index.d.ts +1 -0
  92. package/dist/types/iden3comm/types/packageManager.d.ts +14 -0
  93. package/dist/types/iden3comm/types/packer.d.ts +25 -0
  94. package/dist/types/iden3comm/types/protocol/accept-profile.d.ts +7 -0
  95. package/dist/types/iden3comm/types/protocol/auth.d.ts +1 -0
  96. package/dist/types/iden3comm/types/protocol/credentials.d.ts +6 -6
  97. package/dist/types/iden3comm/types/protocol/messages.d.ts +2 -2
  98. package/dist/types/iden3comm/types/protocol/payment.d.ts +87 -13
  99. package/dist/types/iden3comm/types/protocol/proof.d.ts +3 -3
  100. package/dist/types/iden3comm/types/protocol/revocation.d.ts +2 -2
  101. package/dist/types/iden3comm/utils/accept-profile.d.ts +3 -0
  102. package/dist/types/iden3comm/utils/index.d.ts +1 -0
  103. package/dist/types/storage/blockchain/did-resolver-readonly-storage.d.ts +16 -0
  104. package/dist/types/storage/blockchain/erc20-helper.d.ts +19 -0
  105. package/dist/types/storage/blockchain/index.d.ts +3 -0
  106. package/dist/types/storage/blockchain/onchain-issuer-adapter/non-merklized/version/v0.0.1/onchain-non-merklized-issuer-adapter.d.ts +66 -0
  107. package/dist/types/storage/blockchain/onchain-issuer.d.ts +40 -0
  108. package/dist/types/storage/blockchain/onchain-zkp-verifier.d.ts +11 -12
  109. package/dist/types/storage/entities/state.d.ts +2 -0
  110. package/dist/types/storage/interfaces/index.d.ts +1 -0
  111. package/dist/types/storage/interfaces/onchain-issuer.d.ts +12 -0
  112. package/dist/types/verifiable/constants.d.ts +28 -11
  113. package/dist/types/verifiable/credential.d.ts +15 -2
  114. package/package.json +3 -2
@@ -23,7 +23,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
23
23
  return result;
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.PaymentHandler = exports.createPayment = exports.createPaymentRequest = void 0;
26
+ exports.PaymentHandler = exports.createPayment = exports.convertPaymentAmount = exports.verifyEIP712TypedData = exports.createPaymentRequest = void 0;
27
27
  const constants_1 = require("../constants");
28
28
  const constants_2 = require("../constants");
29
29
  const js_iden3_core_1 = require("@iden3/js-iden3-core");
@@ -32,6 +32,8 @@ const js_jwz_1 = require("@iden3/js-jwz");
32
32
  const utils_1 = require("../../utils");
33
33
  const message_handler_1 = require("./message-handler");
34
34
  const verifiable_1 = require("../../verifiable");
35
+ const ethers_1 = require("ethers");
36
+ const common_1 = require("./common");
35
37
  /**
36
38
  * @beta
37
39
  * createPaymentRequest is a function to create protocol payment-request message
@@ -41,7 +43,7 @@ const verifiable_1 = require("../../verifiable");
41
43
  * @param {PaymentRequestInfo[]} payments - payments
42
44
  * @returns `PaymentRequestMessage`
43
45
  */
44
- function createPaymentRequest(sender, receiver, agent, payments) {
46
+ function createPaymentRequest(sender, receiver, agent, payments, opts) {
45
47
  const uuidv4 = uuid.v4();
46
48
  const request = {
47
49
  id: uuidv4,
@@ -53,20 +55,85 @@ function createPaymentRequest(sender, receiver, agent, payments) {
53
55
  body: {
54
56
  agent,
55
57
  payments
56
- }
58
+ },
59
+ created_time: (0, js_iden3_core_1.getUnixTimestamp)(new Date()),
60
+ expires_time: opts?.expires_time ? (0, js_iden3_core_1.getUnixTimestamp)(opts.expires_time) : undefined
57
61
  };
58
62
  return request;
59
63
  }
60
64
  exports.createPaymentRequest = createPaymentRequest;
65
+ async function verifyEIP712TypedData(data, resolver) {
66
+ const convertedAmount = await convertPaymentAmount(data.amount, data.currency);
67
+ const paymentData = data.type === verifiable_1.PaymentRequestDataType.Iden3PaymentRailsRequestV1
68
+ ? {
69
+ recipient: data.recipient,
70
+ amount: convertedAmount,
71
+ expirationDate: (0, js_iden3_core_1.getUnixTimestamp)(new Date(data.expirationDate)),
72
+ nonce: data.nonce,
73
+ metadata: '0x'
74
+ }
75
+ : {
76
+ tokenAddress: data.tokenAddress,
77
+ recipient: data.recipient,
78
+ amount: convertedAmount,
79
+ expirationDate: (0, js_iden3_core_1.getUnixTimestamp)(new Date(data.expirationDate)),
80
+ nonce: data.nonce,
81
+ metadata: '0x'
82
+ };
83
+ const proof = Array.isArray(data.proof) ? data.proof[0] : data.proof;
84
+ const typesFetchResult = await fetch(proof.eip712.types);
85
+ const types = await typesFetchResult.json();
86
+ delete types.EIP712Domain;
87
+ const recovered = ethers_1.ethers.verifyTypedData(proof.eip712.domain, types, paymentData, proof.proofValue);
88
+ const { didDocument } = await resolver.resolve(proof.verificationMethod);
89
+ if (didDocument?.verificationMethod) {
90
+ for (const verificationMethod of didDocument.verificationMethod) {
91
+ if (verificationMethod.blockchainAccountId?.split(':').slice(-1)[0].toLowerCase() ===
92
+ recovered.toLowerCase()) {
93
+ return recovered;
94
+ }
95
+ }
96
+ }
97
+ else {
98
+ throw new Error('failed request. issuer DIDDocument does not contain any verificationMethods');
99
+ }
100
+ throw new Error(`failed request. no matching verificationMethod`);
101
+ }
102
+ exports.verifyEIP712TypedData = verifyEIP712TypedData;
103
+ async function convertPaymentAmount(amount, currency) {
104
+ let convertedAmount = 0n;
105
+ switch (currency) {
106
+ case verifiable_1.SupportedCurrencies.ETH:
107
+ case verifiable_1.SupportedCurrencies.POL:
108
+ case verifiable_1.SupportedCurrencies.MATIC:
109
+ convertedAmount = (0, ethers_1.parseEther)(amount.toString());
110
+ break;
111
+ case verifiable_1.SupportedCurrencies.ETH_WEI:
112
+ convertedAmount = (0, ethers_1.parseUnits)(amount.toString(), 'wei');
113
+ break;
114
+ case verifiable_1.SupportedCurrencies.ETH_GWEI:
115
+ convertedAmount = (0, ethers_1.parseUnits)(amount.toString(), 'gwei');
116
+ break;
117
+ case verifiable_1.SupportedCurrencies.USDC:
118
+ case verifiable_1.SupportedCurrencies.USDT: {
119
+ convertedAmount = (0, ethers_1.parseUnits)(amount.toString(), 6);
120
+ break;
121
+ }
122
+ default:
123
+ throw new Error(`failed request. unsupported currency ${currency}`);
124
+ }
125
+ return convertedAmount;
126
+ }
127
+ exports.convertPaymentAmount = convertPaymentAmount;
61
128
  /**
62
129
  * @beta
63
130
  * createPayment is a function to create protocol payment message
64
131
  * @param {DID} sender - sender did
65
132
  * @param {DID} receiver - receiver did
66
- * @param {PaymentInfo[]} payments - payments
133
+ * @param {PaymentMessageBody} body - payments
67
134
  * @returns `PaymentMessage`
68
135
  */
69
- function createPayment(sender, receiver, payments) {
136
+ function createPayment(sender, receiver, payments, opts) {
70
137
  const uuidv4 = uuid.v4();
71
138
  const request = {
72
139
  id: uuidv4,
@@ -77,7 +144,9 @@ function createPayment(sender, receiver, payments) {
77
144
  type: constants_1.PROTOCOL_MESSAGE_TYPE.PAYMENT_MESSAGE_TYPE,
78
145
  body: {
79
146
  payments
80
- }
147
+ },
148
+ created_time: (0, js_iden3_core_1.getUnixTimestamp)(new Date()),
149
+ expires_time: opts?.expires_time ? (0, js_iden3_core_1.getUnixTimestamp)(opts.expires_time) : undefined
81
150
  };
82
151
  return request;
83
152
  }
@@ -140,21 +209,28 @@ class PaymentHandler extends message_handler_1.AbstractMessageHandler {
140
209
  const receiverDID = js_iden3_core_1.DID.parse(paymentRequest.from);
141
210
  const payments = [];
142
211
  for (let i = 0; i < paymentRequest.body.payments.length; i++) {
143
- const paymentReq = paymentRequest.body.payments[i];
144
- if (paymentReq.type !== verifiable_1.PaymentRequestType.PaymentRequest) {
145
- throw new Error(`failed request. not supported '${paymentReq.type}' payment type `);
212
+ const { data } = paymentRequest.body.payments[i];
213
+ const selectedPayment = Array.isArray(data)
214
+ ? data.find((p) => {
215
+ return p.type === verifiable_1.PaymentRequestDataType.Iden3PaymentRequestCryptoV1
216
+ ? p.id === ctx.nonce
217
+ : p.nonce === ctx.nonce;
218
+ })
219
+ : data;
220
+ if (!selectedPayment) {
221
+ throw new Error(`failed request. no payment in request for nonce ${ctx.nonce}`);
146
222
  }
147
- if (paymentReq.data.type !== verifiable_1.PaymentRequestDataType.Iden3PaymentRequestCryptoV1) {
148
- throw new Error(`failed request. not supported '${paymentReq.data.type}' payment type `);
223
+ switch (selectedPayment.type) {
224
+ case verifiable_1.PaymentRequestDataType.Iden3PaymentRequestCryptoV1:
225
+ payments.push(await this.handleIden3PaymentRequestCryptoV1(selectedPayment, ctx.paymentHandler));
226
+ break;
227
+ case verifiable_1.PaymentRequestDataType.Iden3PaymentRailsRequestV1:
228
+ payments.push(await this.handleIden3PaymentRailsRequestV1(selectedPayment, ctx.paymentHandler));
229
+ break;
230
+ case verifiable_1.PaymentRequestDataType.Iden3PaymentRailsERC20RequestV1:
231
+ payments.push(await this.handleIden3PaymentRailsERC20RequestV1(selectedPayment, ctx.paymentHandler, ctx.erc20TokenApproveHandler));
232
+ break;
149
233
  }
150
- const txId = await ctx.paymentHandler(paymentReq.data);
151
- payments.push({
152
- id: paymentReq.data.id,
153
- type: verifiable_1.PaymentType.Iden3PaymentCryptoV1,
154
- paymentData: {
155
- txId
156
- }
157
- });
158
234
  }
159
235
  const paymentMessage = createPayment(senderDID, receiverDID, payments);
160
236
  const response = await this.packMessage(paymentMessage, senderDID);
@@ -187,6 +263,9 @@ class PaymentHandler extends message_handler_1.AbstractMessageHandler {
187
263
  if (!paymentRequest.to) {
188
264
  throw new Error(`failed request. empty 'to' field`);
189
265
  }
266
+ if (!opts?.allowExpiredMessages) {
267
+ (0, common_1.verifyExpiresTime)(paymentRequest);
268
+ }
190
269
  const agentMessage = await this.handlePaymentRequestMessage(paymentRequest, opts);
191
270
  if (!agentMessage) {
192
271
  return null;
@@ -197,24 +276,121 @@ class PaymentHandler extends message_handler_1.AbstractMessageHandler {
197
276
  /**
198
277
  * @inheritdoc IPaymentHandler#handlePayment
199
278
  */
200
- async handlePayment(payment, opts) {
201
- if (opts.paymentRequest.from !== payment.to) {
202
- throw new Error(`sender of the request is not a target of response - expected ${opts.paymentRequest.from}, given ${payment.to}`);
279
+ async handlePayment(payment, params) {
280
+ if (!params?.allowExpiredMessages) {
281
+ (0, common_1.verifyExpiresTime)(payment);
282
+ }
283
+ if (params.paymentRequest.from !== payment.to) {
284
+ throw new Error(`sender of the request is not a target of response - expected ${params.paymentRequest.from}, given ${payment.to}`);
203
285
  }
204
286
  if (!payment.body.payments.length) {
205
287
  throw new Error(`failed request. empty 'payments' field in body`);
206
288
  }
289
+ if (!params.paymentValidationHandler) {
290
+ throw new Error(`please provide payment validation handler in options`);
291
+ }
207
292
  for (let i = 0; i < payment.body.payments.length; i++) {
208
293
  const p = payment.body.payments[i];
209
- const paymentRequestData = opts.paymentRequest.body.payments.find((r) => r.data.id === p.id);
210
- if (!paymentRequestData) {
211
- throw new Error(`can't find payment request for payment id ${p.id}`);
294
+ const nonce = p.type === verifiable_1.PaymentType.Iden3PaymentCryptoV1 ? p.id : p.nonce;
295
+ const requestDataArr = params.paymentRequest.body.payments
296
+ .map((r) => (Array.isArray(r.data) ? r.data : [r.data]))
297
+ .flat();
298
+ const requestData = requestDataArr.find((r) => r.type === verifiable_1.PaymentRequestDataType.Iden3PaymentRequestCryptoV1
299
+ ? r.id === nonce
300
+ : r.nonce === nonce);
301
+ if (!requestData) {
302
+ throw new Error(`can't find payment request for payment ${p.type === verifiable_1.PaymentType.Iden3PaymentCryptoV1 ? 'id' : 'nonce'} ${nonce}`);
212
303
  }
213
- if (!opts.paymentValidationHandler) {
214
- throw new Error(`please provide payment validation handler in options`);
304
+ await params.paymentValidationHandler(p.paymentData.txId, requestData);
305
+ }
306
+ }
307
+ /**
308
+ * @inheritdoc IPaymentHandler#createPaymentRailsV1
309
+ */
310
+ async createPaymentRailsV1(sender, receiver, agent, signer, payments) {
311
+ const paymentRequestInfo = [];
312
+ for (let i = 0; i < payments.length; i++) {
313
+ const { credentials, description } = payments[i];
314
+ const dataArr = [];
315
+ for (let j = 0; j < payments[i].chains.length; j++) {
316
+ const { features, nonce, amount, currency, chainId, expirationDate, type } = payments[i].chains[j];
317
+ const multiChainConfig = this._params.multiChainPaymentConfig?.find((c) => c.chainId === chainId);
318
+ if (!multiChainConfig) {
319
+ throw new Error(`failed request. no config for chain ${chainId}`);
320
+ }
321
+ const { recipient, paymentContract, erc20TokenAddressArr } = multiChainConfig;
322
+ const tokenAddress = erc20TokenAddressArr.find((t) => t.symbol === currency)?.address;
323
+ if (type === verifiable_1.PaymentRequestDataType.Iden3PaymentRailsERC20RequestV1 && !tokenAddress) {
324
+ throw new Error(`failed request. no token address for currency ${currency}`);
325
+ }
326
+ const expirationDateRequired = expirationDate ?? new Date(new Date().setHours(new Date().getHours() + 1));
327
+ const typeUrl = `https://schema.iden3.io/core/json/${type}.json`;
328
+ const typesFetchResult = await fetch(typeUrl);
329
+ const types = await typesFetchResult.json();
330
+ delete types.EIP712Domain;
331
+ const convertedAmount = await convertPaymentAmount(amount, currency);
332
+ const paymentData = type === verifiable_1.PaymentRequestDataType.Iden3PaymentRailsRequestV1
333
+ ? {
334
+ recipient,
335
+ amount: convertedAmount,
336
+ expirationDate: (0, js_iden3_core_1.getUnixTimestamp)(expirationDateRequired),
337
+ nonce,
338
+ metadata: '0x'
339
+ }
340
+ : {
341
+ tokenAddress,
342
+ recipient,
343
+ amount: convertedAmount,
344
+ expirationDate: (0, js_iden3_core_1.getUnixTimestamp)(expirationDateRequired),
345
+ nonce,
346
+ metadata: '0x'
347
+ };
348
+ const domain = {
349
+ name: 'MCPayment',
350
+ version: '1.0.0',
351
+ chainId,
352
+ verifyingContract: paymentContract
353
+ };
354
+ const signature = await signer.signTypedData(domain, types, paymentData);
355
+ const proof = [
356
+ {
357
+ type: verifiable_1.SupportedPaymentProofType.EthereumEip712Signature2021,
358
+ proofPurpose: 'assertionMethod',
359
+ proofValue: signature,
360
+ verificationMethod: `did:pkh:eip155:${chainId}:${await signer.getAddress()}`,
361
+ created: new Date().toISOString(),
362
+ eip712: {
363
+ types: typeUrl,
364
+ primaryType: 'Iden3PaymentRailsRequestV1',
365
+ domain
366
+ }
367
+ }
368
+ ];
369
+ const d = {
370
+ type: verifiable_1.PaymentRequestDataType.Iden3PaymentRailsRequestV1,
371
+ '@context': [
372
+ `https://schema.iden3.io/core/jsonld/payment.jsonld#${type}`,
373
+ 'https://w3id.org/security/suites/eip712sig-2021/v1'
374
+ ],
375
+ recipient,
376
+ amount: amount.toString(),
377
+ currency,
378
+ expirationDate: expirationDateRequired.toISOString(),
379
+ nonce: nonce.toString(),
380
+ metadata: '0x',
381
+ proof
382
+ };
383
+ dataArr.push(type === verifiable_1.PaymentRequestDataType.Iden3PaymentRailsRequestV1
384
+ ? d
385
+ : { ...d, type, tokenAddress: tokenAddress || '', features: features || [] });
215
386
  }
216
- await opts.paymentValidationHandler(p.paymentData.txId, paymentRequestData.data);
387
+ paymentRequestInfo.push({
388
+ data: dataArr,
389
+ credentials,
390
+ description
391
+ });
217
392
  }
393
+ return createPaymentRequest(sender, receiver, agent, paymentRequestInfo);
218
394
  }
219
395
  async packMessage(message, senderDID) {
220
396
  const responseEncoded = utils_1.byteEncoder.encode(JSON.stringify(message));
@@ -228,5 +404,66 @@ class PaymentHandler extends message_handler_1.AbstractMessageHandler {
228
404
  ...packerOpts
229
405
  });
230
406
  }
407
+ async handleIden3PaymentRequestCryptoV1(data, paymentHandler) {
408
+ if (data.expiration && new Date(data.expiration) < new Date()) {
409
+ throw new Error(`failed request. expired request`);
410
+ }
411
+ const txId = await paymentHandler(data);
412
+ return {
413
+ id: data.id,
414
+ '@context': 'https://schema.iden3.io/core/jsonld/payment.jsonld#Iden3PaymentCryptoV1',
415
+ type: verifiable_1.PaymentType.Iden3PaymentCryptoV1,
416
+ paymentData: {
417
+ txId
418
+ }
419
+ };
420
+ }
421
+ async handleIden3PaymentRailsRequestV1(data, paymentHandler) {
422
+ if (data.expirationDate && new Date(data.expirationDate) < new Date()) {
423
+ throw new Error(`failed request. expired request`);
424
+ }
425
+ const signer = await verifyEIP712TypedData(data, this._params.documentResolver);
426
+ if (this._params.allowedSigners && !this._params.allowedSigners.includes(signer)) {
427
+ throw new Error(`failed request. signer is not in the allowed signers list`);
428
+ }
429
+ const txId = await paymentHandler(data);
430
+ const proof = Array.isArray(data.proof) ? data.proof[0] : data.proof;
431
+ return {
432
+ nonce: data.nonce,
433
+ type: verifiable_1.PaymentType.Iden3PaymentRailsV1,
434
+ '@context': 'https://schema.iden3.io/core/jsonld/payment.jsonld#Iden3PaymentRailsV1',
435
+ paymentData: {
436
+ txId,
437
+ chainId: proof.eip712.domain.chainId
438
+ }
439
+ };
440
+ }
441
+ async handleIden3PaymentRailsERC20RequestV1(data, paymentHandler, approveHandler) {
442
+ if (data.expirationDate && new Date(data.expirationDate) < new Date()) {
443
+ throw new Error(`failed request. expired request`);
444
+ }
445
+ const signer = await verifyEIP712TypedData(data, this._params.documentResolver);
446
+ if (this._params.allowedSigners && !this._params.allowedSigners.includes(signer)) {
447
+ throw new Error(`failed request. signer is not in the allowed signers list`);
448
+ }
449
+ if (!data.features?.includes(verifiable_1.PaymentFeatures.EIP_2612) && !approveHandler) {
450
+ throw new Error(`please provide erc20TokenApproveHandler in context for ERC-20 payment type`);
451
+ }
452
+ if (approveHandler) {
453
+ await approveHandler(data);
454
+ }
455
+ const txId = await paymentHandler(data);
456
+ const proof = Array.isArray(data.proof) ? data.proof[0] : data.proof;
457
+ return {
458
+ nonce: data.nonce,
459
+ type: verifiable_1.PaymentType.Iden3PaymentRailsERC20V1,
460
+ '@context': 'https://schema.iden3.io/core/jsonld/payment.jsonld#Iden3PaymentRailsERC20V1',
461
+ paymentData: {
462
+ txId,
463
+ chainId: proof.eip712.domain.chainId,
464
+ tokenAddress: data.tokenAddress
465
+ }
466
+ };
467
+ }
231
468
  }
232
469
  exports.PaymentHandler = PaymentHandler;
@@ -31,6 +31,7 @@ const uuid = __importStar(require("uuid"));
31
31
  const utils_1 = require("../../utils");
32
32
  const js_jwz_1 = require("@iden3/js-jwz");
33
33
  const message_handler_1 = require("./message-handler");
34
+ const common_1 = require("./common");
34
35
  /**
35
36
  *
36
37
  * Allows to process RevocationStatusRequest protocol message
@@ -123,6 +124,9 @@ class RevocationStatusHandler extends message_handler_1.AbstractMessageHandler {
123
124
  throw new Error(`jws packer options are required for ${constants_2.MediaType.SignedMessage}`);
124
125
  }
125
126
  const rsRequest = await this.parseRevocationStatusRequest(request);
127
+ if (!opts.allowExpiredMessages) {
128
+ (0, common_1.verifyExpiresTime)(rsRequest);
129
+ }
126
130
  const response = await this.handleRevocationStatusRequestMessage(rsRequest, {
127
131
  senderDid: did,
128
132
  mediaType: opts.mediaType,
@@ -32,5 +32,6 @@ __exportStar(require("./packers"), exports);
32
32
  __exportStar(require("./types"), exports);
33
33
  __exportStar(require("./handlers"), exports);
34
34
  __exportStar(require("./utils/did"), exports);
35
+ __exportStar(require("./utils/accept-profile"), exports);
35
36
  const PROTOCOL_CONSTANTS = __importStar(require("./constants"));
36
37
  exports.PROTOCOL_CONSTANTS = PROTOCOL_CONSTANTS;
@@ -18,6 +18,18 @@ class PackageManager {
18
18
  constructor() {
19
19
  this.packers = new Map();
20
20
  }
21
+ /** {@inheritDoc IPackageManager.isProfileSupported} */
22
+ isProfileSupported(mediaType, profile) {
23
+ const p = this.packers.get(mediaType);
24
+ if (!p) {
25
+ return false;
26
+ }
27
+ return p.isProfileSupported(profile);
28
+ }
29
+ /** {@inheritDoc IPackageManager.getSupportedMediaTypes} */
30
+ getSupportedMediaTypes() {
31
+ return [...this.packers.keys()];
32
+ }
21
33
  /** {@inheritDoc IPackageManager.registerPackers} */
22
34
  registerPackers(packers) {
23
35
  packers.forEach((p) => {
@@ -8,6 +8,7 @@ const did_jwt_1 = require("did-jwt");
8
8
  const did_resolver_1 = require("did-resolver");
9
9
  const encoding_1 = require("../../utils/encoding");
10
10
  const utils_1 = require("../../utils");
11
+ const utils_2 = require("../utils");
11
12
  /**
12
13
  * Packer that can pack message to JWZ token,
13
14
  * and unpack and validate JWZ envelope
@@ -86,6 +87,26 @@ class JWSPacker {
86
87
  mediaType() {
87
88
  return constants_1.MediaType.SignedMessage;
88
89
  }
90
+ /** {@inheritDoc IPacker.getSupportedProfiles} */
91
+ getSupportedProfiles() {
92
+ return [`env=${this.mediaType()}&alg=${this.getSupportedAlgorithms().join(',')}`];
93
+ }
94
+ /** {@inheritDoc IPacker.isProfileSupported} */
95
+ isProfileSupported(profile) {
96
+ const { env, circuits, alg } = (0, utils_2.parseAcceptProfile)(profile);
97
+ if (env !== this.mediaType()) {
98
+ return false;
99
+ }
100
+ if (circuits) {
101
+ throw new Error(`Circuits are not supported for ${env} media type`);
102
+ }
103
+ const supportedAlgArr = this.getSupportedAlgorithms();
104
+ const algSupported = !alg?.length || alg.some((a) => supportedAlgArr.includes(a));
105
+ return algSupported;
106
+ }
107
+ getSupportedAlgorithms() {
108
+ return [constants_1.AcceptJwsAlgorithms.ES256K, constants_1.AcceptJwsAlgorithms.ES256KR];
109
+ }
89
110
  async resolveDidDoc(from) {
90
111
  let didDocument;
91
112
  try {
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PlainPacker = void 0;
4
4
  const constants_1 = require("../constants");
5
5
  const utils_1 = require("../../utils");
6
+ const utils_2 = require("../utils");
6
7
  /**
7
8
  * Plain packer just serializes bytes to JSON and adds media type
8
9
  *
@@ -52,5 +53,23 @@ class PlainPacker {
52
53
  mediaType() {
53
54
  return constants_1.MediaType.PlainMessage;
54
55
  }
56
+ /** {@inheritDoc IPacker.getSupportedProfiles} */
57
+ getSupportedProfiles() {
58
+ return [`env=${this.mediaType()}`];
59
+ }
60
+ /** {@inheritDoc IPacker.isProfileSupported} */
61
+ isProfileSupported(profile) {
62
+ const { env, circuits, alg } = (0, utils_2.parseAcceptProfile)(profile);
63
+ if (env !== this.mediaType()) {
64
+ return false;
65
+ }
66
+ if (circuits) {
67
+ throw new Error(`Circuits are not supported for ${env} media type`);
68
+ }
69
+ if (alg) {
70
+ throw new Error(`Algorithms are not supported for ${env} media type`);
71
+ }
72
+ return true;
73
+ }
55
74
  }
56
75
  exports.PlainPacker = PlainPacker;
@@ -9,6 +9,7 @@ const errors_1 = require("../errors");
9
9
  const constants_1 = require("../constants");
10
10
  const utils_1 = require("../../utils");
11
11
  const constants_2 = require("../constants");
12
+ const utils_2 = require("../utils");
12
13
  const { getProvingMethod } = js_jwz_1.proving;
13
14
  /**
14
15
  * Handler to
@@ -141,6 +142,30 @@ class ZKPPacker {
141
142
  mediaType() {
142
143
  return constants_1.MediaType.ZKPMessage;
143
144
  }
145
+ /** {@inheritDoc IPacker.getSupportedProfiles} */
146
+ getSupportedProfiles() {
147
+ return [
148
+ `env=${this.mediaType()}&alg=${this.getSupportedAlgorithms().join(',')}&circuitIds=${this.getSupportedCircuitIds().join(',')}`
149
+ ];
150
+ }
151
+ /** {@inheritDoc IPacker.isProfileSupported} */
152
+ isProfileSupported(profile) {
153
+ const { env, circuits, alg } = (0, utils_2.parseAcceptProfile)(profile);
154
+ if (env !== this.mediaType()) {
155
+ return false;
156
+ }
157
+ const supportedCircuitIds = this.getSupportedCircuitIds();
158
+ const circuitIdSupported = !circuits?.length || circuits.some((c) => supportedCircuitIds.includes(c));
159
+ const supportedAlgArr = this.getSupportedAlgorithms();
160
+ const algSupported = !alg?.length || alg.some((a) => supportedAlgArr.includes(a));
161
+ return algSupported && circuitIdSupported;
162
+ }
163
+ getSupportedAlgorithms() {
164
+ return [constants_1.AcceptJwzAlgorithms.Groth16];
165
+ }
166
+ getSupportedCircuitIds() {
167
+ return [constants_1.AcceptAuthCircuits.AuthV2];
168
+ }
144
169
  }
145
170
  exports.ZKPPacker = ZKPPacker;
146
171
  const verifySender = async (token, msg) => {
@@ -22,6 +22,7 @@ __exportStar(require("./protocol/revocation"), exports);
22
22
  __exportStar(require("./protocol/contract-request"), exports);
23
23
  __exportStar(require("./protocol/proposal-request"), exports);
24
24
  __exportStar(require("./protocol/payment"), exports);
25
+ __exportStar(require("./protocol/accept-profile"), exports);
25
26
  __exportStar(require("./packer"), exports);
26
27
  __exportStar(require("./models"), exports);
27
28
  __exportStar(require("./packageManager"), exports);
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,107 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseAcceptProfile = exports.buildAccept = void 0;
4
+ const constants_1 = require("../constants");
5
+ function isProtocolVersion(value) {
6
+ return Object.values(constants_1.ProtocolVersion).includes(value);
7
+ }
8
+ function isMediaType(value) {
9
+ return Object.values(constants_1.MediaType).includes(value);
10
+ }
11
+ function isAcceptAuthCircuits(value) {
12
+ return Object.values(constants_1.AcceptAuthCircuits).includes(value);
13
+ }
14
+ function isAcceptJwsAlgorithms(value) {
15
+ return Object.values(constants_1.AcceptJwsAlgorithms).includes(value);
16
+ }
17
+ function isAcceptJwzAlgorithms(value) {
18
+ return Object.values(constants_1.AcceptJwzAlgorithms).includes(value);
19
+ }
20
+ const buildAccept = (profiles) => {
21
+ const result = [];
22
+ for (const profile of profiles) {
23
+ let accept = `${profile.protocolVersion};env=${profile.env}`;
24
+ if (profile.circuits?.length) {
25
+ accept += `;circuitId=${profile.circuits.join(',')}`;
26
+ }
27
+ if (profile.alg?.length) {
28
+ accept += `;alg=${profile.alg.join(',')}`;
29
+ }
30
+ result.push(accept);
31
+ }
32
+ return result;
33
+ };
34
+ exports.buildAccept = buildAccept;
35
+ const parseAcceptProfile = (profile) => {
36
+ const params = profile.split(';');
37
+ if (params.length < 2) {
38
+ throw new Error('Invalid accept profile');
39
+ }
40
+ const protocolVersion = params[0].trim();
41
+ if (!isProtocolVersion(protocolVersion)) {
42
+ throw new Error(`Protocol version '${protocolVersion}' not supported`);
43
+ }
44
+ const envParam = params[1].split('=');
45
+ if (envParam.length !== 2) {
46
+ throw new Error(`Invalid accept profile 'env' parameter`);
47
+ }
48
+ const env = params[1].split('=')[1].trim();
49
+ if (!isMediaType(env)) {
50
+ throw new Error(`Envelop '${env}' not supported`);
51
+ }
52
+ const circuitsIndex = params.findIndex((i) => i.includes('circuitId='));
53
+ if (env !== constants_1.MediaType.ZKPMessage && circuitsIndex > 0) {
54
+ throw new Error(`Circuits not supported for env '${env}'`);
55
+ }
56
+ let circuits = undefined;
57
+ if (circuitsIndex > 0) {
58
+ circuits = params[circuitsIndex]
59
+ .split('=')[1]
60
+ .split(',')
61
+ .map((i) => i.trim())
62
+ .map((i) => {
63
+ if (!isAcceptAuthCircuits(i)) {
64
+ throw new Error(`Circuit '${i}' not supported`);
65
+ }
66
+ return i;
67
+ });
68
+ }
69
+ const algIndex = params.findIndex((i) => i.includes('alg='));
70
+ let alg = undefined;
71
+ if (algIndex > 0) {
72
+ if (env === constants_1.MediaType.ZKPMessage) {
73
+ alg = params[algIndex]
74
+ .split('=')[1]
75
+ .split(',')
76
+ .map((i) => {
77
+ i = i.trim();
78
+ if (!isAcceptJwzAlgorithms(i)) {
79
+ throw new Error(`Algorithm '${i}' not supported for '${env}'`);
80
+ }
81
+ return i;
82
+ });
83
+ }
84
+ else if (env === constants_1.MediaType.SignedMessage) {
85
+ alg = params[algIndex]
86
+ .split('=')[1]
87
+ .split(',')
88
+ .map((i) => {
89
+ i = i.trim();
90
+ if (!isAcceptJwsAlgorithms(i)) {
91
+ throw new Error(`Algorithm '${i}' not supported for '${env}'`);
92
+ }
93
+ return i;
94
+ });
95
+ }
96
+ else {
97
+ throw new Error(`Algorithm not supported for '${env}'`);
98
+ }
99
+ }
100
+ return {
101
+ protocolVersion,
102
+ env,
103
+ circuits,
104
+ alg
105
+ };
106
+ };
107
+ exports.parseAcceptProfile = parseAcceptProfile;
@@ -17,3 +17,4 @@ Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./envelope"), exports);
18
18
  __exportStar(require("./message"), exports);
19
19
  __exportStar(require("./did"), exports);
20
+ __exportStar(require("./accept-profile"), exports);