@0xpolygonid/js-sdk 1.10.0 → 1.10.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.
@@ -62889,7 +62889,11 @@ const PROTOCOL_MESSAGE_TYPE = Object.freeze({
62889
62889
  // ContractInvokeRequestMessageType is type for request of contract invoke request
62890
62890
  CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE: IDEN3_PROTOCOL + 'proofs/1.0/contract-invoke-request',
62891
62891
  // CredentialOnchainOfferMessageType is type of message with credential onchain offering
62892
- CREDENTIAL_ONCHAIN_OFFER_MESSAGE_TYPE: IDEN3_PROTOCOL + 'credentials/1.0/onchain-offer'
62892
+ CREDENTIAL_ONCHAIN_OFFER_MESSAGE_TYPE: IDEN3_PROTOCOL + 'credentials/1.0/onchain-offer',
62893
+ // ProposalRequestMessageType is type for proposal-request message
62894
+ PROPOSAL_REQUEST_MESSAGE_TYPE: IDEN3_PROTOCOL + 'credentials/0.1/proposal-request',
62895
+ // ProposalMessageType is type for proposal message
62896
+ PROPOSAL_MESSAGE_TYPE: IDEN3_PROTOCOL + 'credentials/0.1/proposal'
62893
62897
  });
62894
62898
  /**
62895
62899
  * Media types for iden3 comm communication protocol
@@ -66990,5 +66994,184 @@ class RevocationStatusHandler {
66990
66994
  }
66991
66995
  }
66992
66996
 
66993
- export { AbstractPrivateKeyStore, AgentResolver, AtomicQueryMTPV2Inputs, AtomicQueryMTPV2OnChainInputs, AtomicQueryMTPV2OnChainPubSignals, AtomicQueryMTPV2PubSignals, AtomicQuerySigV2Inputs, AtomicQuerySigV2OnChainCircuitInputs, AtomicQuerySigV2OnChainInputs, AtomicQuerySigV2OnChainPubSignals, AtomicQuerySigV2PubSignals, AtomicQueryV3Inputs, AtomicQueryV3OnChainInputs, AtomicQueryV3OnChainPubSignals, AtomicQueryV3PubSignals, AuthHandler, AuthV2Inputs, AuthV2PubSignals, BJJSignatureProof2021, BaseConfig, BjjProvider, BrowserDataSource, CircuitClaim, CircuitError, CircuitId, CircuitStorage, ContractRequestHandler, CredentialStatusPublisherRegistry, CredentialStatusResolverRegistry, CredentialStatusType, CredentialStorage, CredentialWallet, DIDDocumentJSONSchema, DataPrepareHandlerFunc, Ed25519Provider, ErrorEmptyAuthClaimNonRevProof, ErrorEmptyAuthClaimProof, ErrorEmptyChallengeSignature, ErrorEmptyClaimNonRevProof, ErrorEmptyClaimProof, ErrorEmptyClaimSignature, ErrorEmptyIssuerAuthClaimNonRevProof, ErrorEmptyIssuerAuthClaimProof, ErrorUserStateInRelayClaimProof, EthStateStorage, FSCircuitStorage, FetchHandler, FilterQuery, Iden3OnchainSmtCredentialStatusPublisher, Iden3SmtRhsCredentialStatusPublisher, Iden3SparseMerkleTreeProof, IdentityStorage, IdentityWallet, InMemoryDataSource, InMemoryMerkleTreeStorage, InMemoryPrivateKeyStore, IndexedDBDataSource, IndexedDBPrivateKeyStore, InputGenerator, IssuerResolver, JSON_SCHEMA_VALIDATORS_REGISTRY, JWSPacker, JsonSchemaValidator, KMS, KmsKeyType, LDParser, LinkedMultiQueryInputs, LinkedMultiQueryPubSignals, LocalStoragePrivateKeyStore, MerkleTreeIndexedDBStorage, MerkleTreeLocalStorage, MerkleTreeType, MerklizedRootPosition, MessageBus, NativeProver, OnChainResolver, OnChainRevocationStorage, OnChainZKPVerifier, Operators, constants as PROTOCOL_CONSTANTS, PackageManager, Parser, PlainPacker, ProofNode, ProofPurpose, ProofService, ProofType, PubSignalsVerifier, Query, QueryOperators, RHSResolver, RefreshHandler, RefreshServiceType, RevocationStatusHandler, SDK_EVENTS, Scalar, SearchError, Sec256k1Provider, StandardJSONCredentialsQueryFilter, StateTransitionInputs, StateTransitionPubSignals, SubjectPosition, ValueProof, Vector, VerifiableConstants, VerificationHandlerFunc, W3CCredential, XSDNS, ZKPPacker, availableTypesOperators, base58ToBytes$1 as base58ToBytes, base64ToBytes$1 as base64ToBytes, base64UrlToBytes, bigIntArrayToStringArray, bigIntCompare, buildFieldPath, buildTreeState, buildVerifierId, byteDecoder, byteEncoder, bytesToBase58$1 as bytesToBase58, bytesToBase64, bytesToBase64url$1 as bytesToBase64url, bytesToHex$2 as bytesToHex, cacheLoader, calculateCoreSchemaHash, calculateQueryHashV2, calculateQueryHashV3, checkCircuitOperator, checkCircuitQueriesLength, checkDataInField, checkQueryRequest, circuitValidator, comparatorOptions, createAuthorizationRequest, createAuthorizationRequestWithMessage, createSchemaHash, createVerifiablePresentation, credentialSubjectKey, dataFillsSlot, decodeBase64url$1 as decodeBase64url, defaultEthConnectionConfig, defaultMTLevels, defaultMTLevelsClaim, defaultMTLevelsOnChain, defaultValueArraySize, defineMerklizedRootPosition, encodeBase64url, existenceToInt, extractProof, extractPublicKeyBytes, factoryComparer, fieldToByteArray, fieldValueFromVerifiablePresentation, fillCoreClaimSlot, fillSlot, findCredentialType, findValue, generateProfileDID, getFieldSlotIndex, getKMSIdByAuthCredential, getNodeAuxValue, getNodesRepresentation, getOperatorNameByValue, getProperties, getSerializationAttrFromContext, getSerializationAttrFromParsedContext, getUserDIDFromCredential, hexToBytes$2 as hexToBytes, isGenesisState, isGenesisStateId, isIssuerGenesis, isValidOperation, keyPath, mergeObjects, parseCoreClaimSlots, parseCredentialSubject, parseQueriesMetadata, parseQueryMetadata, parseSerializationAttr, prepareCircuitArrayValues, prepareSiblingsStr, processZeroKnowledgeProofRequests, pushHashesToRHS, resolveDIDDocumentAuth, resolvePath, resolveVerificationMethods, strMTHex, stringByPath, subjectPositionIndex, swapEndianness, toClaimNonRevStatus, toGISTProof, toRevocationStatus, transformQueryValueToBigInts, userStateError, validateDIDDocumentAuth, validateDisclosureNativeSDSupport, validateDisclosureV2Circuit, validateEmptyCredentialSubjectNoopNativeSupport, validateEmptyCredentialSubjectV2Circuit, validateOperators, validateTreeState, verifyFieldValueInclusionNativeExistsSupport, verifyFieldValueInclusionV2, witnessBuilder };
66997
+ /**
66998
+ * @beta
66999
+ * createProposalRequest is a function to create protocol proposal-request protocol message
67000
+ * @param {DID} sender - sender did
67001
+ * @param {DID} receiver - receiver did
67002
+ * @param {ProposalRequestCreationOptions} opts - creation options
67003
+ * @returns `Promise<ProposalRequestMessage>`
67004
+ */
67005
+ function createProposalRequest(sender, receiver, opts) {
67006
+ const uuidv4 = v4();
67007
+ const request = {
67008
+ id: uuidv4,
67009
+ thid: uuidv4,
67010
+ from: sender.string(),
67011
+ to: receiver.string(),
67012
+ typ: MediaType.PlainMessage,
67013
+ type: PROTOCOL_MESSAGE_TYPE.PROPOSAL_REQUEST_MESSAGE_TYPE,
67014
+ body: opts
67015
+ };
67016
+ return request;
67017
+ }
67018
+ /**
67019
+ * @beta
67020
+ * createProposal is a function to create protocol proposal protocol message
67021
+ * @param {DID} sender - sender did
67022
+ * @param {DID} receiver - receiver did
67023
+ * @param {Proposal[]} proposals - proposals
67024
+ * @returns `Promise<ProposalRequestMessage>`
67025
+ */
67026
+ function createProposal(sender, receiver, proposals) {
67027
+ const uuidv4 = v4();
67028
+ const request = {
67029
+ id: uuidv4,
67030
+ thid: uuidv4,
67031
+ from: sender.string(),
67032
+ to: receiver.string(),
67033
+ typ: MediaType.PlainMessage,
67034
+ type: PROTOCOL_MESSAGE_TYPE.PROPOSAL_MESSAGE_TYPE,
67035
+ body: {
67036
+ proposals: proposals || []
67037
+ }
67038
+ };
67039
+ return request;
67040
+ }
67041
+ /**
67042
+ *
67043
+ * Allows to process ProposalRequest protocol message
67044
+ * @beta
67045
+ * @class CredentialProposalHandler
67046
+ * @implements implements ICredentialProposalHandler interface
67047
+ */
67048
+ class CredentialProposalHandler {
67049
+ /**
67050
+ * @beta Creates an instance of CredentialProposalHandler.
67051
+ * @param {IPackageManager} _packerMgr - package manager to unpack message envelope
67052
+ * @param {IIdentityWallet} _identityWallet - identity wallet
67053
+ * @param {CredentialProposalHandlerParams} _params - credential proposal handler params
67054
+ *
67055
+ */
67056
+ constructor(_packerMgr, _identityWallet, _params) {
67057
+ this._packerMgr = _packerMgr;
67058
+ this._identityWallet = _identityWallet;
67059
+ this._params = _params;
67060
+ }
67061
+ /**
67062
+ * @inheritdoc ICredentialProposalHandler#parseProposalRequest
67063
+ */
67064
+ async parseProposalRequest(request) {
67065
+ const { unpackedMessage: message } = await this._packerMgr.unpack(request);
67066
+ const proposalRequest = message;
67067
+ if (message.type !== PROTOCOL_MESSAGE_TYPE.PROPOSAL_REQUEST_MESSAGE_TYPE) {
67068
+ throw new Error('Invalid media type');
67069
+ }
67070
+ return proposalRequest;
67071
+ }
67072
+ /**
67073
+ * @inheritdoc ICredentialProposalHandler#handleProposalRequest
67074
+ */
67075
+ async handleProposalRequest(request,
67076
+ //eslint-disable-next-line @typescript-eslint/no-unused-vars
67077
+ opts) {
67078
+ if (this._params.packerParams.mediaType === MediaType.SignedMessage &&
67079
+ !this._params.packerParams.packerOptions) {
67080
+ throw new Error(`jws packer options are required for ${MediaType.SignedMessage}`);
67081
+ }
67082
+ const proposalRequest = await this.parseProposalRequest(request);
67083
+ if (!proposalRequest.to) {
67084
+ throw new Error(`failed request. empty 'to' field`);
67085
+ }
67086
+ if (!proposalRequest.from) {
67087
+ throw new Error(`failed request. empty 'from' field`);
67088
+ }
67089
+ if (!proposalRequest.body?.credentials?.length) {
67090
+ throw new Error(`failed request. no 'credentials' in body`);
67091
+ }
67092
+ const senderDID = DID.parse(proposalRequest.from);
67093
+ let credOfferMessage = undefined;
67094
+ let proposalMessage = undefined;
67095
+ for (let i = 0; i < proposalRequest.body.credentials.length; i++) {
67096
+ const cred = proposalRequest.body.credentials[i];
67097
+ // check if there is credentials in the wallet
67098
+ let credsFromWallet = [];
67099
+ try {
67100
+ credsFromWallet = await this._identityWallet.findOwnedCredentialsByDID(senderDID, {
67101
+ type: cred.type,
67102
+ context: cred.context
67103
+ });
67104
+ }
67105
+ catch (e) {
67106
+ if (e.message !== 'no credential satisfied query') {
67107
+ throw e;
67108
+ }
67109
+ }
67110
+ if (credsFromWallet.length) {
67111
+ const guid = v4();
67112
+ if (!credOfferMessage) {
67113
+ credOfferMessage = {
67114
+ id: guid,
67115
+ typ: this._params.packerParams.mediaType,
67116
+ type: PROTOCOL_MESSAGE_TYPE.CREDENTIAL_OFFER_MESSAGE_TYPE,
67117
+ thid: proposalRequest.thid ?? guid,
67118
+ body: {
67119
+ url: this._params.agentUrl,
67120
+ credentials: []
67121
+ },
67122
+ from: proposalRequest.to,
67123
+ to: proposalRequest.from
67124
+ };
67125
+ }
67126
+ credOfferMessage.body.credentials.push(...credsFromWallet.map((c) => ({
67127
+ id: c.id,
67128
+ description: ''
67129
+ })));
67130
+ continue;
67131
+ }
67132
+ // credential not found in the wallet, prepare proposal protocol message
67133
+ const proposal = await this._params.proposalResolverFn(cred.context, cred.type);
67134
+ if (!proposal) {
67135
+ throw new Error(`can't resolve Proposal for type: ${cred.type}, context: ${cred.context}`);
67136
+ }
67137
+ if (!proposalMessage) {
67138
+ const guid = v4();
67139
+ proposalMessage = {
67140
+ id: guid,
67141
+ typ: this._params.packerParams.mediaType,
67142
+ type: PROTOCOL_MESSAGE_TYPE.PROPOSAL_MESSAGE_TYPE,
67143
+ thid: proposalRequest.thid ?? guid,
67144
+ body: {
67145
+ proposals: []
67146
+ },
67147
+ from: proposalRequest.to,
67148
+ to: proposalRequest.from
67149
+ };
67150
+ }
67151
+ proposalMessage.body?.proposals.push(proposal);
67152
+ }
67153
+ // if there is credentials in the wallet, return offer protocol message, otherwise proposal
67154
+ const response = byteEncoder.encode(JSON.stringify(proposalMessage ?? credOfferMessage));
67155
+ const packerOpts = this._params.packerParams.mediaType === MediaType.SignedMessage
67156
+ ? this._params.packerParams.packerOptions
67157
+ : {
67158
+ provingMethodAlg: proving.provingMethodGroth16AuthV2Instance.methodAlg
67159
+ };
67160
+ return this._packerMgr.pack(this._params.packerParams.mediaType, response, {
67161
+ senderDID,
67162
+ ...packerOpts
67163
+ });
67164
+ }
67165
+ /**
67166
+ * @inheritdoc ICredentialProposalHandler#handleProposal
67167
+ */
67168
+ async handleProposal(proposal, opts) {
67169
+ if (opts?.proposalRequest && opts.proposalRequest.from !== proposal.to) {
67170
+ throw new Error(`sender of the request is not a target of response - expected ${opts.proposalRequest.from}, given ${proposal.to}`);
67171
+ }
67172
+ return { proposal };
67173
+ }
67174
+ }
67175
+
67176
+ export { AbstractPrivateKeyStore, AgentResolver, AtomicQueryMTPV2Inputs, AtomicQueryMTPV2OnChainInputs, AtomicQueryMTPV2OnChainPubSignals, AtomicQueryMTPV2PubSignals, AtomicQuerySigV2Inputs, AtomicQuerySigV2OnChainCircuitInputs, AtomicQuerySigV2OnChainInputs, AtomicQuerySigV2OnChainPubSignals, AtomicQuerySigV2PubSignals, AtomicQueryV3Inputs, AtomicQueryV3OnChainInputs, AtomicQueryV3OnChainPubSignals, AtomicQueryV3PubSignals, AuthHandler, AuthV2Inputs, AuthV2PubSignals, BJJSignatureProof2021, BaseConfig, BjjProvider, BrowserDataSource, CircuitClaim, CircuitError, CircuitId, CircuitStorage, ContractRequestHandler, CredentialProposalHandler, CredentialStatusPublisherRegistry, CredentialStatusResolverRegistry, CredentialStatusType, CredentialStorage, CredentialWallet, DIDDocumentJSONSchema, DataPrepareHandlerFunc, Ed25519Provider, ErrorEmptyAuthClaimNonRevProof, ErrorEmptyAuthClaimProof, ErrorEmptyChallengeSignature, ErrorEmptyClaimNonRevProof, ErrorEmptyClaimProof, ErrorEmptyClaimSignature, ErrorEmptyIssuerAuthClaimNonRevProof, ErrorEmptyIssuerAuthClaimProof, ErrorUserStateInRelayClaimProof, EthStateStorage, FSCircuitStorage, FetchHandler, FilterQuery, Iden3OnchainSmtCredentialStatusPublisher, Iden3SmtRhsCredentialStatusPublisher, Iden3SparseMerkleTreeProof, IdentityStorage, IdentityWallet, InMemoryDataSource, InMemoryMerkleTreeStorage, InMemoryPrivateKeyStore, IndexedDBDataSource, IndexedDBPrivateKeyStore, InputGenerator, IssuerResolver, JSON_SCHEMA_VALIDATORS_REGISTRY, JWSPacker, JsonSchemaValidator, KMS, KmsKeyType, LDParser, LinkedMultiQueryInputs, LinkedMultiQueryPubSignals, LocalStoragePrivateKeyStore, MerkleTreeIndexedDBStorage, MerkleTreeLocalStorage, MerkleTreeType, MerklizedRootPosition, MessageBus, NativeProver, OnChainResolver, OnChainRevocationStorage, OnChainZKPVerifier, Operators, constants as PROTOCOL_CONSTANTS, PackageManager, Parser, PlainPacker, ProofNode, ProofPurpose, ProofService, ProofType, PubSignalsVerifier, Query, QueryOperators, RHSResolver, RefreshHandler, RefreshServiceType, RevocationStatusHandler, SDK_EVENTS, Scalar, SearchError, Sec256k1Provider, StandardJSONCredentialsQueryFilter, StateTransitionInputs, StateTransitionPubSignals, SubjectPosition, ValueProof, Vector, VerifiableConstants, VerificationHandlerFunc, W3CCredential, XSDNS, ZKPPacker, availableTypesOperators, base58ToBytes$1 as base58ToBytes, base64ToBytes$1 as base64ToBytes, base64UrlToBytes, bigIntArrayToStringArray, bigIntCompare, buildFieldPath, buildTreeState, buildVerifierId, byteDecoder, byteEncoder, bytesToBase58$1 as bytesToBase58, bytesToBase64, bytesToBase64url$1 as bytesToBase64url, bytesToHex$2 as bytesToHex, cacheLoader, calculateCoreSchemaHash, calculateQueryHashV2, calculateQueryHashV3, checkCircuitOperator, checkCircuitQueriesLength, checkDataInField, checkQueryRequest, circuitValidator, comparatorOptions, createAuthorizationRequest, createAuthorizationRequestWithMessage, createProposal, createProposalRequest, createSchemaHash, createVerifiablePresentation, credentialSubjectKey, dataFillsSlot, decodeBase64url$1 as decodeBase64url, defaultEthConnectionConfig, defaultMTLevels, defaultMTLevelsClaim, defaultMTLevelsOnChain, defaultValueArraySize, defineMerklizedRootPosition, encodeBase64url, existenceToInt, extractProof, extractPublicKeyBytes, factoryComparer, fieldToByteArray, fieldValueFromVerifiablePresentation, fillCoreClaimSlot, fillSlot, findCredentialType, findValue, generateProfileDID, getFieldSlotIndex, getKMSIdByAuthCredential, getNodeAuxValue, getNodesRepresentation, getOperatorNameByValue, getProperties, getSerializationAttrFromContext, getSerializationAttrFromParsedContext, getUserDIDFromCredential, hexToBytes$2 as hexToBytes, isGenesisState, isGenesisStateId, isIssuerGenesis, isValidOperation, keyPath, mergeObjects, parseCoreClaimSlots, parseCredentialSubject, parseQueriesMetadata, parseQueryMetadata, parseSerializationAttr, prepareCircuitArrayValues, prepareSiblingsStr, processZeroKnowledgeProofRequests, pushHashesToRHS, resolveDIDDocumentAuth, resolvePath, resolveVerificationMethods, strMTHex, stringByPath, subjectPositionIndex, swapEndianness, toClaimNonRevStatus, toGISTProof, toRevocationStatus, transformQueryValueToBigInts, userStateError, validateDIDDocumentAuth, validateDisclosureNativeSDSupport, validateDisclosureV2Circuit, validateEmptyCredentialSubjectNoopNativeSupport, validateEmptyCredentialSubjectV2Circuit, validateOperators, validateTreeState, verifyFieldValueInclusionNativeExistsSupport, verifyFieldValueInclusionV2, witnessBuilder };
66994
67177
  //# sourceMappingURL=index.js.map