From 605be1dd1512fa8926e0d85a14b4e0dbbd84adcb Mon Sep 17 00:00:00 2001 From: vbasiuk Date: Thu, 13 Jul 2023 14:16:57 +0300 Subject: [PATCH] fix iden3comm folder --- package-lock.json | 19 +++++++++++++++++++ package.json | 1 + src/iden3comm/errors.ts | 1 + src/iden3comm/handlers/auth.ts | 4 ++-- src/iden3comm/handlers/fetch.ts | 15 +++++++++------ src/iden3comm/packers/jws.ts | 2 +- src/iden3comm/packers/zkp.ts | 30 ++++++++++++++++++++---------- src/iden3comm/utils/did.ts | 6 +++--- 8 files changed, 56 insertions(+), 22 deletions(-) diff --git a/package-lock.json b/package-lock.json index b3f6d8e6..70870f12 100644 --- a/package-lock.json +++ b/package-lock.json @@ -42,6 +42,7 @@ "@microsoft/api-extractor": "^7.34.4", "@types/chai": "^4.3.4", "@types/chai-as-promised": "^7.1.5", + "@types/elliptic": "^6.4.14", "@types/jsonld": "^1.4.8", "@types/mocha": "^10.0.1", "@types/node": "^18.16.19", @@ -2609,6 +2610,15 @@ "@babel/types": "^7.20.7" } }, + "node_modules/@types/bn.js": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/@types/bn.js/-/bn.js-5.1.1.tgz", + "integrity": "sha512-qNrYbZqMx0uJAfKnKclPh+dTwK33KfLHYqtyODwd5HnXOjnkhc4qgn3BrK6RWyGZm5+sIFE7Q7Vz6QQtJB7w7g==", + "dev": true, + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/chai": { "version": "4.3.5", "resolved": "https://registry.npmjs.org/@types/chai/-/chai-4.3.5.tgz", @@ -2624,6 +2634,15 @@ "@types/chai": "*" } }, + "node_modules/@types/elliptic": { + "version": "6.4.14", + "resolved": "https://registry.npmjs.org/@types/elliptic/-/elliptic-6.4.14.tgz", + "integrity": "sha512-z4OBcDAU0GVwDTuwJzQCiL6188QvZMkvoERgcVjq0/mPM8jCfdwZ3x5zQEVoL9WCAru3aG5wl3Z5Ww5wBWn7ZQ==", + "dev": true, + "dependencies": { + "@types/bn.js": "*" + } + }, "node_modules/@types/eslint": { "version": "8.40.0", "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-8.40.0.tgz", diff --git a/package.json b/package.json index 864760ff..688e5c84 100644 --- a/package.json +++ b/package.json @@ -50,6 +50,7 @@ "@microsoft/api-extractor": "^7.34.4", "@types/chai": "^4.3.4", "@types/chai-as-promised": "^7.1.5", + "@types/elliptic": "^6.4.14", "@types/jsonld": "^1.4.8", "@types/mocha": "^10.0.1", "@types/node": "^18.16.19", diff --git a/src/iden3comm/errors.ts b/src/iden3comm/errors.ts index d3c54e53..074be88a 100644 --- a/src/iden3comm/errors.ts +++ b/src/iden3comm/errors.ts @@ -11,3 +11,4 @@ export const ErrSenderNotUsedTokenCreation = 'sender of message is not used for export const ErrPackedWithUnsupportedCircuit = 'message was packed with unsupported circuit'; export const ErrProofIsInvalid = 'message proof is invalid'; export const ErrStateVerificationFailed = 'message state verification failed'; +export const ErrNoProvingMethodAlg = 'unknown proving method algorithm'; diff --git a/src/iden3comm/handlers/auth.ts b/src/iden3comm/handlers/auth.ts index 541b58bc..dfdf5002 100644 --- a/src/iden3comm/handlers/auth.ts +++ b/src/iden3comm/handlers/auth.ts @@ -246,14 +246,14 @@ export class AuthHandler implements IAuthHandler { type: PROTOCOL_MESSAGE_TYPE.AUTHORIZATION_RESPONSE_MESSAGE_TYPE, thid: authRequest.thid ?? guid, body: { - message: authRequest.body.message, + message: authRequest?.body?.message, scope: [] }, from: userGenesisDID.string(), to: authRequest.from }; - for (const r of zkpRequestsWithCreds) { + for (const r of zkpRequestsWithCreds || []) { const zkpRes: ZeroKnowledgeProofResponse = await this._proofService.generateProof( r.req, userGenesisDID, diff --git a/src/iden3comm/handlers/fetch.ts b/src/iden3comm/handlers/fetch.ts index c2ee471a..0d78e4ba 100644 --- a/src/iden3comm/handlers/fetch.ts +++ b/src/iden3comm/handlers/fetch.ts @@ -97,8 +97,8 @@ export class FetchHandler implements IFetchHandler { } const credentials: W3CCredential[] = []; - for (let index = 0; index < offerMessage.body.credentials.length; index++) { - const credentialInfo = offerMessage.body.credentials[index]; + for (let index = 0; index < (offerMessage?.body?.credentials?.length ?? 0); index++) { + const credentialInfo = offerMessage?.body?.credentials[index]; const guid = uuid.v4(); const fetchRequest: MessageFetchRequestMessage = { @@ -107,7 +107,7 @@ export class FetchHandler implements IFetchHandler { type: PROTOCOL_MESSAGE_TYPE.CREDENTIAL_FETCH_REQUEST_MESSAGE_TYPE, thid: offerMessage.thid ?? guid, body: { - id: credentialInfo.id + id: credentialInfo?.id || '' }, from: did.string(), to: offerMessage.from @@ -119,6 +119,9 @@ export class FetchHandler implements IFetchHandler { ); let message: { body: { credential: W3CCredential } }; try { + if (!offerMessage?.body?.url) { + throw new Error(`could not fetch W3C credential, body url is missing`); + } const resp = await fetch(offerMessage.body.url, { method: 'post', headers: { @@ -127,13 +130,13 @@ export class FetchHandler implements IFetchHandler { body: token }); if (resp.status !== 200) { - throw new Error(`could not fetch W3C credential, ${credentialInfo.id}`); + throw new Error(`could not fetch W3C credential, ${credentialInfo?.id}`); } message = await resp.json(); credentials.push(message.body.credential); - } catch (e) { + } catch (e: any) { throw new Error( - `could not fetch W3C credential, ${credentialInfo.id}, error: ${e.message ?? e}` + `could not fetch W3C credential, ${credentialInfo?.id}, error: ${e.message ?? e}` ); } } diff --git a/src/iden3comm/packers/jws.ts b/src/iden3comm/packers/jws.ts index 2835415d..e6258406 100644 --- a/src/iden3comm/packers/jws.ts +++ b/src/iden3comm/packers/jws.ts @@ -64,7 +64,7 @@ export class JWSPacker implements IPacker { throw new Error('Missing sender DID'); } - const vmTypes: string[] = SUPPORTED_PUBLIC_KEY_TYPES[params.alg]; + const vmTypes: string[] = SUPPORTED_PUBLIC_KEY_TYPES[params.alg as keyof typeof SUPPORTED_PUBLIC_KEY_TYPES]; if (!vmTypes?.length) { throw new Error(`No supported verification methods for algorithm ${params.alg}`); } diff --git a/src/iden3comm/packers/zkp.ts b/src/iden3comm/packers/zkp.ts index adf78800..18e9bc3c 100644 --- a/src/iden3comm/packers/zkp.ts +++ b/src/iden3comm/packers/zkp.ts @@ -12,6 +12,7 @@ import { AuthV2PubSignals, CircuitId } from '../../circuits/index'; import { DID, Id } from '@iden3/js-iden3-core'; import { bytesToProtocolMessage } from '../utils/envelope'; import { + ErrNoProvingMethodAlg, ErrPackedWithUnsupportedCircuit, ErrProofIsInvalid, ErrSenderNotUsedTokenCreation, @@ -110,19 +111,28 @@ export class ZKPPacker implements IPacker { */ async pack(payload: Uint8Array, params: ZKPPackerParams): Promise { const provingMethod = await getProvingMethod(params.provingMethodAlg); - const { provingKey, wasm, dataPreparer } = this.provingParamsMap.get( + const provingParams = this.provingParamsMap.get( params.provingMethodAlg.toString() ); + if (!provingParams) { + throw new Error(ErrNoProvingMethodAlg); + } + const token = new Token( provingMethod, byteDecoder.decode(payload), - (hash: Uint8Array, circuitID: CircuitId) => { - return dataPreparer.prepare(hash, params.senderDID, params.profileNonce, circuitID); + (hash: Uint8Array, circuitID: string) => { + return provingParams?.dataPreparer?.prepare( + hash, + params.senderDID, + params.profileNonce, + CircuitId[circuitID as keyof typeof CircuitId] + ); } ); token.setHeader(Header.Type, MediaType.ZKPMessage); - const tokenStr = await token.prove(provingKey, wasm); + const tokenStr = await token.prove(provingParams.provingKey, provingParams.wasm); return byteEncoder.encode(tokenStr); } @@ -135,18 +145,18 @@ export class ZKPPacker implements IPacker { async unpack(envelope: Uint8Array): Promise { const token = await Token.parse(byteDecoder.decode(envelope)); const provingMethodAlg = new ProvingMethodAlg(token.alg, token.circuitId); - const { key: verificationKey, verificationFn } = this.verificationParamsMap.get( + const verificationParams = this.verificationParamsMap.get( provingMethodAlg.toString() ); - if (!verificationKey) { + if (!verificationParams?.key) { throw new Error(ErrPackedWithUnsupportedCircuit); } - const isValid = await token.verify(verificationKey); + const isValid = await token.verify(verificationParams?.key); if (!isValid) { throw new Error(ErrProofIsInvalid); } - const verificationResult = await verificationFn.verify( + const verificationResult = await verificationParams?.verificationFn?.verify( token.circuitId, token.zkProof.pub_signals ); @@ -170,7 +180,7 @@ export class ZKPPacker implements IPacker { const verifySender = (token: Token, msg: BasicMessage): void => { switch (token.circuitId) { case CircuitId.AuthV2: - if (!verifyAuthV2Sender(msg.from, token.zkProof.pub_signals)) { + if (!msg.from || !verifyAuthV2Sender(msg.from, token.zkProof.pub_signals)) { throw new Error(ErrSenderNotUsedTokenCreation); } break; @@ -183,7 +193,7 @@ const verifyAuthV2Sender = (from: string, pubSignals: Array): boolean => const authSignals = new AuthV2PubSignals(); const pubSig = authSignals.pubSignalsUnmarshal(byteEncoder.encode(JSON.stringify(pubSignals))); - return checkSender(from, pubSig.userID); + return pubSig.userID ? checkSender(from, pubSig.userID) : false; }; const checkSender = (from: string, id: Id): boolean => { diff --git a/src/iden3comm/utils/did.ts b/src/iden3comm/utils/did.ts index 58991286..5a021721 100644 --- a/src/iden3comm/utils/did.ts +++ b/src/iden3comm/utils/did.ts @@ -19,7 +19,7 @@ export const resolveDIDDocument = async ( const response = await fetch(`${UNIVERSAL_RESOLVER_URL}/${didUrl}`); const data = await response.json(); return data as DIDResolutionResult; - } catch (error) { + } catch (error: any) { throw new Error(`Can't resolve did document: ${error.message}`); } }; @@ -52,9 +52,9 @@ const secp256k1 = new elliptic.ec('secp256k1'); export const extractPublicKeyBytes = ( vm: VerificationMethod -): { publicKeyBytes: Uint8Array; kmsKeyType?: KmsKeyType } => { +): { publicKeyBytes: Uint8Array | null; kmsKeyType?: KmsKeyType } => { const isSupportedVmType = Object.keys(SUPPORTED_PUBLIC_KEY_TYPES).some((key) => - SUPPORTED_PUBLIC_KEY_TYPES[key].includes(vm.type) + SUPPORTED_PUBLIC_KEY_TYPES[key as keyof typeof SUPPORTED_PUBLIC_KEY_TYPES].includes(vm.type) ); if (vm.publicKeyBase58 && isSupportedVmType) { return { publicKeyBytes: base58ToBytes(vm.publicKeyBase58), kmsKeyType: KmsKeyType.Secp256k1 };