@0xpolygonid/js-sdk 1.14.1 → 1.15.2

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 (38) hide show
  1. package/README.md +0 -4
  2. package/dist/browser/esm/index.js +3490 -3457
  3. package/dist/browser/esm/index.js.map +1 -1
  4. package/dist/browser/umd/index.js +3503 -3470
  5. package/dist/browser/umd/index.js.map +1 -1
  6. package/dist/node/cjs/iden3comm/constants.js +3 -1
  7. package/dist/node/cjs/iden3comm/handlers/credential-proposal.js +11 -8
  8. package/dist/node/cjs/iden3comm/handlers/message-handler.js +14 -3
  9. package/dist/node/cjs/iden3comm/packers/zkp.js +23 -16
  10. package/dist/node/cjs/iden3comm/types/index.js +1 -0
  11. package/dist/node/cjs/iden3comm/types/models.js +2 -0
  12. package/dist/node/cjs/iden3comm/types/protocol/credentials.js +8 -0
  13. package/dist/node/cjs/identity/identity-wallet.js +4 -1
  14. package/dist/node/cjs/proof/proof-service.js +16 -15
  15. package/dist/node/cjs/proof/verifiers/pub-signals-verifier.js +4 -5
  16. package/dist/node/esm/iden3comm/constants.js +2 -0
  17. package/dist/node/esm/iden3comm/handlers/credential-proposal.js +7 -4
  18. package/dist/node/esm/iden3comm/handlers/message-handler.js +14 -3
  19. package/dist/node/esm/iden3comm/packers/zkp.js +24 -17
  20. package/dist/node/esm/iden3comm/types/index.js +1 -0
  21. package/dist/node/esm/iden3comm/types/models.js +1 -0
  22. package/dist/node/esm/iden3comm/types/protocol/credentials.js +7 -1
  23. package/dist/node/esm/identity/identity-wallet.js +4 -1
  24. package/dist/node/esm/proof/proof-service.js +18 -17
  25. package/dist/node/esm/proof/verifiers/pub-signals-verifier.js +4 -5
  26. package/dist/types/iden3comm/constants.d.ts +2 -0
  27. package/dist/types/iden3comm/handlers/auth.d.ts +3 -5
  28. package/dist/types/iden3comm/handlers/message-handler.d.ts +2 -0
  29. package/dist/types/iden3comm/packers/zkp.d.ts +6 -5
  30. package/dist/types/iden3comm/types/index.d.ts +1 -0
  31. package/dist/types/iden3comm/types/models.d.ts +6 -0
  32. package/dist/types/iden3comm/types/packer.d.ts +2 -1
  33. package/dist/types/iden3comm/types/protocol/auth.d.ts +0 -2
  34. package/dist/types/iden3comm/types/protocol/credentials.d.ts +7 -0
  35. package/dist/types/identity/identity-wallet.d.ts +8 -0
  36. package/dist/types/proof/proof-service.d.ts +2 -2
  37. package/dist/types/proof/verifiers/pub-signals-verifier.d.ts +1 -1
  38. package/package.json +4 -4
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SUPPORTED_PUBLIC_KEY_TYPES = exports.MediaType = exports.PROTOCOL_MESSAGE_TYPE = void 0;
3
+ exports.DEFAULT_AUTH_VERIFY_DELAY = exports.DEFAULT_PROOF_VERIFY_DELAY = exports.SUPPORTED_PUBLIC_KEY_TYPES = exports.MediaType = exports.PROTOCOL_MESSAGE_TYPE = void 0;
4
4
  const IDEN3_PROTOCOL = 'https://iden3-communication.io/';
5
5
  /**
6
6
  * Constants for Iden3 protocol
@@ -74,3 +74,5 @@ exports.SUPPORTED_PUBLIC_KEY_TYPES = {
74
74
  'JsonWebKey2020'
75
75
  ]
76
76
  };
77
+ exports.DEFAULT_PROOF_VERIFY_DELAY = 1 * 60 * 60 * 1000; // 1 hour
78
+ exports.DEFAULT_AUTH_VERIFY_DELAY = 5 * 60 * 1000; // 5 minutes
@@ -25,7 +25,6 @@ var __importStar = (this && this.__importStar) || function (mod) {
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
26
  exports.CredentialProposalHandler = exports.createProposal = exports.createProposalRequest = void 0;
27
27
  const constants_1 = require("../constants");
28
- const constants_2 = require("../constants");
29
28
  const js_iden3_core_1 = require("@iden3/js-iden3-core");
30
29
  const uuid = __importStar(require("uuid"));
31
30
  const js_jwz_1 = require("@iden3/js-jwz");
@@ -46,7 +45,7 @@ function createProposalRequest(sender, receiver, opts) {
46
45
  thid: uuidv4,
47
46
  from: sender.string(),
48
47
  to: receiver.string(),
49
- typ: constants_2.MediaType.PlainMessage,
48
+ typ: constants_1.MediaType.PlainMessage,
50
49
  type: constants_1.PROTOCOL_MESSAGE_TYPE.PROPOSAL_REQUEST_MESSAGE_TYPE,
51
50
  body: opts
52
51
  };
@@ -68,7 +67,7 @@ function createProposal(sender, receiver, proposals) {
68
67
  thid: uuidv4,
69
68
  from: sender.string(),
70
69
  to: receiver.string(),
71
- typ: constants_2.MediaType.PlainMessage,
70
+ typ: constants_1.MediaType.PlainMessage,
72
71
  type: constants_1.PROTOCOL_MESSAGE_TYPE.PROPOSAL_MESSAGE_TYPE,
73
72
  body: {
74
73
  proposals: proposals || []
@@ -129,7 +128,6 @@ class CredentialProposalHandler extends message_handler_1.AbstractMessageHandler
129
128
  if (!proposalRequest.body?.credentials?.length) {
130
129
  throw new Error(`failed request. no 'credentials' in body`);
131
130
  }
132
- const senderDID = js_iden3_core_1.DID.parse(proposalRequest.from);
133
131
  let credOfferMessage = undefined;
134
132
  let proposalMessage = undefined;
135
133
  for (let i = 0; i < proposalRequest.body.credentials.length; i++) {
@@ -137,7 +135,12 @@ class CredentialProposalHandler extends message_handler_1.AbstractMessageHandler
137
135
  // check if there is credentials in the wallet
138
136
  let credsFromWallet = [];
139
137
  try {
140
- credsFromWallet = await this._identityWallet.findOwnedCredentialsByDID(senderDID, {
138
+ credsFromWallet = await this._identityWallet.credentialWallet.findByQuery({
139
+ credentialSubject: {
140
+ id: {
141
+ $eq: proposalRequest.from
142
+ }
143
+ },
141
144
  type: cred.type,
142
145
  context: cred.context
143
146
  });
@@ -198,9 +201,9 @@ class CredentialProposalHandler extends message_handler_1.AbstractMessageHandler
198
201
  async handleProposalRequest(request,
199
202
  //eslint-disable-next-line @typescript-eslint/no-unused-vars
200
203
  opts) {
201
- if (this._params.packerParams.mediaType === constants_2.MediaType.SignedMessage &&
204
+ if (this._params.packerParams.mediaType === constants_1.MediaType.SignedMessage &&
202
205
  !this._params.packerParams.packerOptions) {
203
- throw new Error(`jws packer options are required for ${constants_2.MediaType.SignedMessage}`);
206
+ throw new Error(`jws packer options are required for ${constants_1.MediaType.SignedMessage}`);
204
207
  }
205
208
  const proposalRequest = await this.parseProposalRequest(request);
206
209
  if (!proposalRequest.from) {
@@ -209,7 +212,7 @@ class CredentialProposalHandler extends message_handler_1.AbstractMessageHandler
209
212
  const senderDID = js_iden3_core_1.DID.parse(proposalRequest.from);
210
213
  const message = await this.handleProposalRequestMessage(proposalRequest);
211
214
  const response = utils_1.byteEncoder.encode(JSON.stringify(message));
212
- const packerOpts = this._params.packerParams.mediaType === constants_2.MediaType.SignedMessage
215
+ const packerOpts = this._params.packerParams.mediaType === constants_1.MediaType.SignedMessage
213
216
  ? this._params.packerParams.packerOptions
214
217
  : {
215
218
  provingMethodAlg: js_jwz_1.proving.provingMethodGroth16AuthV2Instance.methodAlg
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MessageHandler = exports.AbstractMessageHandler = void 0;
4
+ const constants_1 = require("../constants");
5
+ const js_jwz_1 = require("@iden3/js-jwz");
4
6
  /**
5
7
  * Base implementation of protocol message handler
6
8
  *
@@ -87,10 +89,19 @@ class MessageHandler {
87
89
  return Promise.reject(new Error('Message handler not provided'));
88
90
  }
89
91
  const response = await this.messageHandler.handle(message, context);
90
- if (response) {
91
- return this._params.packageManager.packMessage(unpackedMediaType, response, {});
92
+ if (!response) {
93
+ return null;
92
94
  }
93
- return null;
95
+ let packerParams = {};
96
+ const senderDID = context?.senderDID;
97
+ if (unpackedMediaType === constants_1.MediaType.ZKPMessage && senderDID) {
98
+ packerParams = {
99
+ senderDID,
100
+ provingMethodAlg: js_jwz_1.proving.provingMethodGroth16AuthV2Instance.methodAlg
101
+ };
102
+ return this._params.packageManager.packMessage(unpackedMediaType, response, packerParams);
103
+ }
104
+ return this._params.packageManager.packMessage(constants_1.MediaType.PlainMessage, response, packerParams);
94
105
  }
95
106
  }
96
107
  exports.MessageHandler = MessageHandler;
@@ -8,6 +8,7 @@ const envelope_1 = require("../utils/envelope");
8
8
  const errors_1 = require("../errors");
9
9
  const constants_1 = require("../constants");
10
10
  const utils_1 = require("../../utils");
11
+ const constants_2 = require("../constants");
11
12
  const { getProvingMethod } = js_jwz_1.proving;
12
13
  /**
13
14
  * Handler to
@@ -57,8 +58,8 @@ class VerificationHandlerFunc {
57
58
  * @param {Array<string>} pubSignals - signals that must contain user id and state
58
59
  * @returns `Promise<boolean>`
59
60
  */
60
- verify(id, pubSignals) {
61
- return this.stateVerificationFunc(id, pubSignals);
61
+ verify(id, pubSignals, opts) {
62
+ return this.stateVerificationFunc(id, pubSignals, opts);
62
63
  }
63
64
  }
64
65
  exports.VerificationHandlerFunc = VerificationHandlerFunc;
@@ -75,9 +76,12 @@ class ZKPPacker {
75
76
  * @param {Map<string, ProvingParams>} provingParamsMap - string is derived by JSON.parse(ProvingMethodAlg)
76
77
  * @param {Map<string, VerificationParams>} verificationParamsMap - string is derived by JSON.parse(ProvingMethodAlg)
77
78
  */
78
- constructor(provingParamsMap, verificationParamsMap) {
79
+ constructor(provingParamsMap, verificationParamsMap, _opts = {
80
+ acceptedStateTransitionDelay: constants_2.DEFAULT_AUTH_VERIFY_DELAY
81
+ }) {
79
82
  this.provingParamsMap = provingParamsMap;
80
83
  this.verificationParamsMap = verificationParamsMap;
84
+ this._opts = _opts;
81
85
  }
82
86
  /**
83
87
  * Packs a basic message using the specified parameters.
@@ -125,7 +129,7 @@ class ZKPPacker {
125
129
  if (!isValid) {
126
130
  throw new Error(errors_1.ErrProofIsInvalid);
127
131
  }
128
- const verificationResult = await verificationParams?.verificationFn?.verify(token.circuitId, token.zkProof.pub_signals);
132
+ const verificationResult = await verificationParams?.verificationFn?.verify(token.circuitId, token.zkProof.pub_signals, this._opts);
129
133
  if (!verificationResult) {
130
134
  throw new Error(errors_1.ErrStateVerificationFailed);
131
135
  }
@@ -139,23 +143,26 @@ class ZKPPacker {
139
143
  }
140
144
  }
141
145
  exports.ZKPPacker = ZKPPacker;
142
- const verifySender = (token, msg) => {
146
+ const verifySender = async (token, msg) => {
143
147
  switch (token.circuitId) {
144
148
  case index_1.CircuitId.AuthV2:
145
- if (!msg.from || !verifyAuthV2Sender(msg.from, token.zkProof.pub_signals)) {
146
- throw new Error(errors_1.ErrSenderNotUsedTokenCreation);
149
+ {
150
+ if (!msg.from) {
151
+ throw new Error(errors_1.ErrSenderNotUsedTokenCreation);
152
+ }
153
+ const authSignals = new index_1.AuthV2PubSignals().pubSignalsUnmarshal(utils_1.byteEncoder.encode(JSON.stringify(token.zkProof.pub_signals)));
154
+ const did = js_iden3_core_1.DID.parseFromId(authSignals.userID);
155
+ const msgHash = await token.getMessageHash();
156
+ const challenge = js_iden3_core_1.BytesHelper.bytesToInt(msgHash.reverse());
157
+ if (challenge !== authSignals.challenge) {
158
+ throw new Error(errors_1.ErrSenderNotUsedTokenCreation);
159
+ }
160
+ if (msg.from !== did.string()) {
161
+ throw new Error(errors_1.ErrSenderNotUsedTokenCreation);
162
+ }
147
163
  }
148
164
  break;
149
165
  default:
150
166
  throw new Error(errors_1.ErrUnknownCircuitID);
151
167
  }
152
168
  };
153
- const verifyAuthV2Sender = (from, pubSignals) => {
154
- const authSignals = new index_1.AuthV2PubSignals();
155
- const pubSig = authSignals.pubSignalsUnmarshal(utils_1.byteEncoder.encode(JSON.stringify(pubSignals)));
156
- return pubSig.userID ? checkSender(from, pubSig.userID) : false;
157
- };
158
- const checkSender = (from, id) => {
159
- const did = js_iden3_core_1.DID.parseFromId(id);
160
- return from === did.string();
161
- };
@@ -23,4 +23,5 @@ __exportStar(require("./protocol/contract-request"), exports);
23
23
  __exportStar(require("./protocol/proposal-request"), exports);
24
24
  __exportStar(require("./protocol/payment"), exports);
25
25
  __exportStar(require("./packer"), exports);
26
+ __exportStar(require("./models"), exports);
26
27
  __exportStar(require("./packageManager"), exports);
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,2 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CredentialOfferStatus = void 0;
4
+ /** CredentialOfferStatus is list of possible statuses for credential offer message */
5
+ var CredentialOfferStatus;
6
+ (function (CredentialOfferStatus) {
7
+ CredentialOfferStatus["Pending"] = "pending";
8
+ CredentialOfferStatus["Completed"] = "completed";
9
+ CredentialOfferStatus["Rejected"] = "rejected";
10
+ })(CredentialOfferStatus = exports.CredentialOfferStatus || (exports.CredentialOfferStatus = {}));
@@ -68,6 +68,9 @@ class IdentityWallet {
68
68
  this._inputsGenerator = new proof_1.InputGenerator(this, _credentialWallet, _storage.states);
69
69
  this._transactionService = new blockchain_1.TransactionService(_storage.states.getRpcProvider());
70
70
  }
71
+ get credentialWallet() {
72
+ return this._credentialWallet;
73
+ }
71
74
  getCredentialStatusPublisherRegistry(_opts) {
72
75
  if (!_opts?.credentialStatusPublisherRegistry) {
73
76
  const registry = new credential_status_publisher_1.CredentialStatusPublisherRegistry();
@@ -387,7 +390,7 @@ class IdentityWallet {
387
390
  req.revocationOpts.nonce =
388
391
  typeof req.revocationOpts.nonce === 'number'
389
392
  ? req.revocationOpts.nonce
390
- : Math.round(Math.random() * 10000);
393
+ : new DataView((0, js_crypto_1.getRandomBytes)(16).buffer).getUint32(0, false);
391
394
  req.subjectPosition = req.subjectPosition ?? verifiable_1.SubjectPosition.Index;
392
395
  try {
393
396
  credential = this._credentialWallet.createCredential(issuerDID, req, jsonSchema);
@@ -2,12 +2,12 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ProofService = void 0;
4
4
  const js_iden3_core_1 = require("@iden3/js-iden3-core");
5
- const js_merkletree_1 = require("@iden3/js-merkletree");
6
5
  const circuits_1 = require("../circuits");
7
6
  const verifiable_1 = require("../verifiable");
8
7
  const common_1 = require("./common");
9
8
  const prover_1 = require("./provers/prover");
10
9
  const js_jsonld_merklization_1 = require("@iden3/js-jsonld-merklization");
10
+ const iden3comm_1 = require("../iden3comm");
11
11
  const schema_processor_1 = require("../schema-processor");
12
12
  const encoding_1 = require("../utils/encoding");
13
13
  const inputs_generator_1 = require("./provers/inputs-generator");
@@ -200,10 +200,6 @@ class ProofService {
200
200
  const { nonce: authProfileNonce, genesisDID } = await this._identityWallet.getGenesisDIDMetadata(did);
201
201
  const challenge = js_iden3_core_1.BytesHelper.bytesToInt(hash.reverse());
202
202
  const authPrepared = await this._inputsGenerator.prepareAuthBJJCredential(genesisDID);
203
- const authClaimData = await this._inputsGenerator.newCircuitClaimData({
204
- credential: authPrepared.credential,
205
- credentialCoreClaim: authPrepared.coreClaim
206
- });
207
203
  const signature = await this._identityWallet.signChallenge(challenge, authPrepared.credential);
208
204
  const id = js_iden3_core_1.DID.idFromDID(genesisDID);
209
205
  const stateProof = await this._stateStorage.getGISTProof(id.bigInt());
@@ -211,25 +207,25 @@ class ProofService {
211
207
  const authInputs = new circuits_1.AuthV2Inputs();
212
208
  authInputs.genesisID = id;
213
209
  authInputs.profileNonce = BigInt(authProfileNonce);
214
- authInputs.authClaim = authClaimData.claim;
215
- authInputs.authClaimIncMtp = authClaimData.proof;
210
+ authInputs.authClaim = authPrepared.coreClaim;
211
+ authInputs.authClaimIncMtp = authPrepared.incProof.proof;
216
212
  authInputs.authClaimNonRevMtp = authPrepared.nonRevProof.proof;
217
- authInputs.treeState = authClaimData.treeState;
213
+ authInputs.treeState = authPrepared.incProof.treeState;
218
214
  authInputs.signature = signature;
219
215
  authInputs.challenge = challenge;
220
216
  authInputs.gistProof = gistProof;
221
217
  return authInputs.inputsMarshal();
222
218
  }
223
- async verifyState(circuitId, pubSignals) {
219
+ async verifyState(circuitId, pubSignals, opts = {
220
+ acceptedStateTransitionDelay: iden3comm_1.PROTOCOL_CONSTANTS.DEFAULT_AUTH_VERIFY_DELAY
221
+ }) {
224
222
  if (circuitId !== circuits_1.CircuitId.AuthV2) {
225
223
  throw new Error(`CircuitId is not supported ${circuitId}`);
226
224
  }
227
- const gistRoot = js_merkletree_1.Hash.fromString(pubSignals[2]).bigInt();
228
- const userId = BigInt(pubSignals[0]);
225
+ const authV2PubSignals = new circuits_1.AuthV2PubSignals().pubSignalsUnmarshal(encoding_1.byteEncoder.encode(JSON.stringify(pubSignals)));
226
+ const gistRoot = authV2PubSignals.GISTRoot.bigInt();
227
+ const userId = authV2PubSignals.userID.bigInt();
229
228
  const globalStateInfo = await this._stateStorage.getGISTRootInfo(gistRoot, userId);
230
- if (globalStateInfo.createdAtTimestamp === 0n) {
231
- throw new Error(`gist state doesn't exists in contract`);
232
- }
233
229
  if (globalStateInfo.root !== gistRoot) {
234
230
  throw new Error(`gist info contains invalid state`);
235
231
  }
@@ -237,7 +233,12 @@ class ProofService {
237
233
  if (globalStateInfo.replacedAtTimestamp === 0n) {
238
234
  throw new Error(`state was replaced, but replaced time unknown`);
239
235
  }
240
- return false;
236
+ const timeDiff = Date.now() -
237
+ (0, js_iden3_core_1.getDateFromUnixTimestamp)(Number(globalStateInfo.replacedAtTimestamp)).getTime();
238
+ if (timeDiff >
239
+ (opts?.acceptedStateTransitionDelay ?? iden3comm_1.PROTOCOL_CONSTANTS.DEFAULT_AUTH_VERIFY_DELAY)) {
240
+ throw new Error('global state is outdated');
241
+ }
241
242
  }
242
243
  return true;
243
244
  }
@@ -16,10 +16,9 @@ const query_1 = require("./query");
16
16
  const common_2 = require("../common");
17
17
  const circuits_1 = require("../../circuits");
18
18
  const query_hash_1 = require("./query-hash");
19
+ const iden3comm_1 = require("../../iden3comm");
19
20
  exports.userStateError = new Error(`user state is not valid`);
20
21
  const zeroInt = 0n;
21
- const defaultProofVerifyOpts = 1 * 60 * 60 * 1000; // 1 hour
22
- const defaultAuthVerifyOpts = 5 * 60 * 1000; // 5 minutes
23
22
  /**
24
23
  * PubSignalsVerifier provides verify method
25
24
  * @public
@@ -221,7 +220,7 @@ class PubSignalsVerifier {
221
220
  // no query verification
222
221
  // verify state
223
222
  const gist = await this.checkGlobalState(authV2PubSignals.GISTRoot, this.userId);
224
- let acceptedStateTransitionDelay = defaultAuthVerifyOpts;
223
+ let acceptedStateTransitionDelay = iden3comm_1.PROTOCOL_CONSTANTS.DEFAULT_AUTH_VERIFY_DELAY;
225
224
  if (opts?.acceptedStateTransitionDelay) {
226
225
  acceptedStateTransitionDelay = opts.acceptedStateTransitionDelay;
227
226
  }
@@ -308,7 +307,7 @@ class PubSignalsVerifier {
308
307
  };
309
308
  this.checkRevocationState = async (issuerID, issuerClaimNonRevState, opts) => {
310
309
  const issuerNonRevStateResolved = await this.checkRevocationStateForId(issuerID, issuerClaimNonRevState);
311
- const acceptedStateTransitionDelay = opts?.acceptedStateTransitionDelay ?? defaultProofVerifyOpts;
310
+ const acceptedStateTransitionDelay = opts?.acceptedStateTransitionDelay ?? iden3comm_1.PROTOCOL_CONSTANTS.DEFAULT_PROOF_VERIFY_DELAY;
312
311
  if (!issuerNonRevStateResolved.latest) {
313
312
  const timeDiff = Date.now() -
314
313
  (0, js_iden3_core_1.getDateFromUnixTimestamp)(Number(issuerNonRevStateResolved.transitionTimestamp)).getTime();
@@ -392,7 +391,7 @@ class PubSignalsVerifier {
392
391
  catch (e) {
393
392
  const stateNotExistErr = (e?.errorArgs ?? [])[0];
394
393
  const errMsg = stateNotExistErr || e.message;
395
- if (errMsg === 'State does not exist') {
394
+ if (errMsg.includes('State does not exist')) {
396
395
  if (isGenesis) {
397
396
  return {
398
397
  latest: true,
@@ -71,3 +71,5 @@ export const SUPPORTED_PUBLIC_KEY_TYPES = {
71
71
  'JsonWebKey2020'
72
72
  ]
73
73
  };
74
+ export const DEFAULT_PROOF_VERIFY_DELAY = 1 * 60 * 60 * 1000; // 1 hour
75
+ export const DEFAULT_AUTH_VERIFY_DELAY = 5 * 60 * 1000; // 5 minutes
@@ -1,5 +1,4 @@
1
- import { PROTOCOL_MESSAGE_TYPE } from '../constants';
2
- import { MediaType } from '../constants';
1
+ import { PROTOCOL_MESSAGE_TYPE, MediaType } from '../constants';
3
2
  import { DID } from '@iden3/js-iden3-core';
4
3
  import * as uuid from 'uuid';
5
4
  import { proving } from '@iden3/js-jwz';
@@ -101,7 +100,6 @@ export class CredentialProposalHandler extends AbstractMessageHandler {
101
100
  if (!proposalRequest.body?.credentials?.length) {
102
101
  throw new Error(`failed request. no 'credentials' in body`);
103
102
  }
104
- const senderDID = DID.parse(proposalRequest.from);
105
103
  let credOfferMessage = undefined;
106
104
  let proposalMessage = undefined;
107
105
  for (let i = 0; i < proposalRequest.body.credentials.length; i++) {
@@ -109,7 +107,12 @@ export class CredentialProposalHandler extends AbstractMessageHandler {
109
107
  // check if there is credentials in the wallet
110
108
  let credsFromWallet = [];
111
109
  try {
112
- credsFromWallet = await this._identityWallet.findOwnedCredentialsByDID(senderDID, {
110
+ credsFromWallet = await this._identityWallet.credentialWallet.findByQuery({
111
+ credentialSubject: {
112
+ id: {
113
+ $eq: proposalRequest.from
114
+ }
115
+ },
113
116
  type: cred.type,
114
117
  context: cred.context
115
118
  });
@@ -1,3 +1,5 @@
1
+ import { MediaType } from '../constants';
2
+ import { proving } from '@iden3/js-jwz';
1
3
  /**
2
4
  * Base implementation of protocol message handler
3
5
  *
@@ -83,9 +85,18 @@ export class MessageHandler {
83
85
  return Promise.reject(new Error('Message handler not provided'));
84
86
  }
85
87
  const response = await this.messageHandler.handle(message, context);
86
- if (response) {
87
- return this._params.packageManager.packMessage(unpackedMediaType, response, {});
88
+ if (!response) {
89
+ return null;
88
90
  }
89
- return null;
91
+ let packerParams = {};
92
+ const senderDID = context?.senderDID;
93
+ if (unpackedMediaType === MediaType.ZKPMessage && senderDID) {
94
+ packerParams = {
95
+ senderDID,
96
+ provingMethodAlg: proving.provingMethodGroth16AuthV2Instance.methodAlg
97
+ };
98
+ return this._params.packageManager.packMessage(unpackedMediaType, response, packerParams);
99
+ }
100
+ return this._params.packageManager.packMessage(MediaType.PlainMessage, response, packerParams);
90
101
  }
91
102
  }
@@ -1,10 +1,11 @@
1
1
  import { Token, Header, ProvingMethodAlg, proving } from '@iden3/js-jwz';
2
2
  import { AuthV2PubSignals, CircuitId } from '../../circuits/index';
3
- import { DID } from '@iden3/js-iden3-core';
3
+ import { BytesHelper, DID } from '@iden3/js-iden3-core';
4
4
  import { bytesToProtocolMessage } from '../utils/envelope';
5
5
  import { ErrNoProvingMethodAlg, ErrPackedWithUnsupportedCircuit, ErrProofIsInvalid, ErrSenderNotUsedTokenCreation, ErrStateVerificationFailed, ErrUnknownCircuitID } from '../errors';
6
6
  import { MediaType } from '../constants';
7
7
  import { byteDecoder, byteEncoder } from '../../utils';
8
+ import { DEFAULT_AUTH_VERIFY_DELAY } from '../constants';
8
9
  const { getProvingMethod } = proving;
9
10
  /**
10
11
  * Handler to
@@ -53,8 +54,8 @@ export class VerificationHandlerFunc {
53
54
  * @param {Array<string>} pubSignals - signals that must contain user id and state
54
55
  * @returns `Promise<boolean>`
55
56
  */
56
- verify(id, pubSignals) {
57
- return this.stateVerificationFunc(id, pubSignals);
57
+ verify(id, pubSignals, opts) {
58
+ return this.stateVerificationFunc(id, pubSignals, opts);
58
59
  }
59
60
  }
60
61
  /**
@@ -70,9 +71,12 @@ export class ZKPPacker {
70
71
  * @param {Map<string, ProvingParams>} provingParamsMap - string is derived by JSON.parse(ProvingMethodAlg)
71
72
  * @param {Map<string, VerificationParams>} verificationParamsMap - string is derived by JSON.parse(ProvingMethodAlg)
72
73
  */
73
- constructor(provingParamsMap, verificationParamsMap) {
74
+ constructor(provingParamsMap, verificationParamsMap, _opts = {
75
+ acceptedStateTransitionDelay: DEFAULT_AUTH_VERIFY_DELAY
76
+ }) {
74
77
  this.provingParamsMap = provingParamsMap;
75
78
  this.verificationParamsMap = verificationParamsMap;
79
+ this._opts = _opts;
76
80
  }
77
81
  /**
78
82
  * Packs a basic message using the specified parameters.
@@ -120,7 +124,7 @@ export class ZKPPacker {
120
124
  if (!isValid) {
121
125
  throw new Error(ErrProofIsInvalid);
122
126
  }
123
- const verificationResult = await verificationParams?.verificationFn?.verify(token.circuitId, token.zkProof.pub_signals);
127
+ const verificationResult = await verificationParams?.verificationFn?.verify(token.circuitId, token.zkProof.pub_signals, this._opts);
124
128
  if (!verificationResult) {
125
129
  throw new Error(ErrStateVerificationFailed);
126
130
  }
@@ -133,23 +137,26 @@ export class ZKPPacker {
133
137
  return MediaType.ZKPMessage;
134
138
  }
135
139
  }
136
- const verifySender = (token, msg) => {
140
+ const verifySender = async (token, msg) => {
137
141
  switch (token.circuitId) {
138
142
  case CircuitId.AuthV2:
139
- if (!msg.from || !verifyAuthV2Sender(msg.from, token.zkProof.pub_signals)) {
140
- throw new Error(ErrSenderNotUsedTokenCreation);
143
+ {
144
+ if (!msg.from) {
145
+ throw new Error(ErrSenderNotUsedTokenCreation);
146
+ }
147
+ const authSignals = new AuthV2PubSignals().pubSignalsUnmarshal(byteEncoder.encode(JSON.stringify(token.zkProof.pub_signals)));
148
+ const did = DID.parseFromId(authSignals.userID);
149
+ const msgHash = await token.getMessageHash();
150
+ const challenge = BytesHelper.bytesToInt(msgHash.reverse());
151
+ if (challenge !== authSignals.challenge) {
152
+ throw new Error(ErrSenderNotUsedTokenCreation);
153
+ }
154
+ if (msg.from !== did.string()) {
155
+ throw new Error(ErrSenderNotUsedTokenCreation);
156
+ }
141
157
  }
142
158
  break;
143
159
  default:
144
160
  throw new Error(ErrUnknownCircuitID);
145
161
  }
146
162
  };
147
- const verifyAuthV2Sender = (from, pubSignals) => {
148
- const authSignals = new AuthV2PubSignals();
149
- const pubSig = authSignals.pubSignalsUnmarshal(byteEncoder.encode(JSON.stringify(pubSignals)));
150
- return pubSig.userID ? checkSender(from, pubSig.userID) : false;
151
- };
152
- const checkSender = (from, id) => {
153
- const did = DID.parseFromId(id);
154
- return from === did.string();
155
- };
@@ -7,4 +7,5 @@ export * from './protocol/contract-request';
7
7
  export * from './protocol/proposal-request';
8
8
  export * from './protocol/payment';
9
9
  export * from './packer';
10
+ export * from './models';
10
11
  export * from './packageManager';
@@ -0,0 +1 @@
1
+ export {};
@@ -1 +1,7 @@
1
- export {};
1
+ /** CredentialOfferStatus is list of possible statuses for credential offer message */
2
+ export var CredentialOfferStatus;
3
+ (function (CredentialOfferStatus) {
4
+ CredentialOfferStatus["Pending"] = "pending";
5
+ CredentialOfferStatus["Completed"] = "completed";
6
+ CredentialOfferStatus["Rejected"] = "rejected";
7
+ })(CredentialOfferStatus || (CredentialOfferStatus = {}));
@@ -42,6 +42,9 @@ export class IdentityWallet {
42
42
  this._inputsGenerator = new InputGenerator(this, _credentialWallet, _storage.states);
43
43
  this._transactionService = new TransactionService(_storage.states.getRpcProvider());
44
44
  }
45
+ get credentialWallet() {
46
+ return this._credentialWallet;
47
+ }
45
48
  getCredentialStatusPublisherRegistry(_opts) {
46
49
  if (!_opts?.credentialStatusPublisherRegistry) {
47
50
  const registry = new CredentialStatusPublisherRegistry();
@@ -361,7 +364,7 @@ export class IdentityWallet {
361
364
  req.revocationOpts.nonce =
362
365
  typeof req.revocationOpts.nonce === 'number'
363
366
  ? req.revocationOpts.nonce
364
- : Math.round(Math.random() * 10000);
367
+ : new DataView(getRandomBytes(16).buffer).getUint32(0, false);
365
368
  req.subjectPosition = req.subjectPosition ?? SubjectPosition.Index;
366
369
  try {
367
370
  credential = this._credentialWallet.createCredential(issuerDID, req, jsonSchema);
@@ -1,10 +1,10 @@
1
- import { BytesHelper, DID, MerklizedRootPosition } from '@iden3/js-iden3-core';
2
- import { Hash } from '@iden3/js-merkletree';
3
- import { AuthV2Inputs, CircuitId, Operators, Query, ValueProof } from '../circuits';
1
+ import { BytesHelper, DID, MerklizedRootPosition, getDateFromUnixTimestamp } from '@iden3/js-iden3-core';
2
+ import { AuthV2Inputs, AuthV2PubSignals, CircuitId, Operators, Query, ValueProof } from '../circuits';
4
3
  import { createVerifiablePresentation } from '../verifiable';
5
4
  import { parseCredentialSubject, parseQueryMetadata, toGISTProof, transformQueryValueToBigInts } from './common';
6
5
  import { NativeProver } from './provers/prover';
7
6
  import { getDocumentLoader } from '@iden3/js-jsonld-merklization';
7
+ import { PROTOCOL_CONSTANTS } from '../iden3comm';
8
8
  import { cacheLoader } from '../schema-processor';
9
9
  import { byteDecoder, byteEncoder } from '../utils/encoding';
10
10
  import { InputGenerator } from './provers/inputs-generator';
@@ -197,10 +197,6 @@ export class ProofService {
197
197
  const { nonce: authProfileNonce, genesisDID } = await this._identityWallet.getGenesisDIDMetadata(did);
198
198
  const challenge = BytesHelper.bytesToInt(hash.reverse());
199
199
  const authPrepared = await this._inputsGenerator.prepareAuthBJJCredential(genesisDID);
200
- const authClaimData = await this._inputsGenerator.newCircuitClaimData({
201
- credential: authPrepared.credential,
202
- credentialCoreClaim: authPrepared.coreClaim
203
- });
204
200
  const signature = await this._identityWallet.signChallenge(challenge, authPrepared.credential);
205
201
  const id = DID.idFromDID(genesisDID);
206
202
  const stateProof = await this._stateStorage.getGISTProof(id.bigInt());
@@ -208,25 +204,25 @@ export class ProofService {
208
204
  const authInputs = new AuthV2Inputs();
209
205
  authInputs.genesisID = id;
210
206
  authInputs.profileNonce = BigInt(authProfileNonce);
211
- authInputs.authClaim = authClaimData.claim;
212
- authInputs.authClaimIncMtp = authClaimData.proof;
207
+ authInputs.authClaim = authPrepared.coreClaim;
208
+ authInputs.authClaimIncMtp = authPrepared.incProof.proof;
213
209
  authInputs.authClaimNonRevMtp = authPrepared.nonRevProof.proof;
214
- authInputs.treeState = authClaimData.treeState;
210
+ authInputs.treeState = authPrepared.incProof.treeState;
215
211
  authInputs.signature = signature;
216
212
  authInputs.challenge = challenge;
217
213
  authInputs.gistProof = gistProof;
218
214
  return authInputs.inputsMarshal();
219
215
  }
220
- async verifyState(circuitId, pubSignals) {
216
+ async verifyState(circuitId, pubSignals, opts = {
217
+ acceptedStateTransitionDelay: PROTOCOL_CONSTANTS.DEFAULT_AUTH_VERIFY_DELAY
218
+ }) {
221
219
  if (circuitId !== CircuitId.AuthV2) {
222
220
  throw new Error(`CircuitId is not supported ${circuitId}`);
223
221
  }
224
- const gistRoot = Hash.fromString(pubSignals[2]).bigInt();
225
- const userId = BigInt(pubSignals[0]);
222
+ const authV2PubSignals = new AuthV2PubSignals().pubSignalsUnmarshal(byteEncoder.encode(JSON.stringify(pubSignals)));
223
+ const gistRoot = authV2PubSignals.GISTRoot.bigInt();
224
+ const userId = authV2PubSignals.userID.bigInt();
226
225
  const globalStateInfo = await this._stateStorage.getGISTRootInfo(gistRoot, userId);
227
- if (globalStateInfo.createdAtTimestamp === 0n) {
228
- throw new Error(`gist state doesn't exists in contract`);
229
- }
230
226
  if (globalStateInfo.root !== gistRoot) {
231
227
  throw new Error(`gist info contains invalid state`);
232
228
  }
@@ -234,7 +230,12 @@ export class ProofService {
234
230
  if (globalStateInfo.replacedAtTimestamp === 0n) {
235
231
  throw new Error(`state was replaced, but replaced time unknown`);
236
232
  }
237
- return false;
233
+ const timeDiff = Date.now() -
234
+ getDateFromUnixTimestamp(Number(globalStateInfo.replacedAtTimestamp)).getTime();
235
+ if (timeDiff >
236
+ (opts?.acceptedStateTransitionDelay ?? PROTOCOL_CONSTANTS.DEFAULT_AUTH_VERIFY_DELAY)) {
237
+ throw new Error('global state is outdated');
238
+ }
238
239
  }
239
240
  return true;
240
241
  }