Skip to content

Instantly share code, notes, and snippets.

@aldigjo
Last active January 12, 2023 19:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aldigjo/41a20d8fced39d4c47e7ac088f0c35c0 to your computer and use it in GitHub Desktop.
Save aldigjo/41a20d8fced39d4c47e7ac088f0c35c0 to your computer and use it in GitHub Desktop.
verify 712
import { Caip10Link } from "@ceramicnetwork/stream-caip10-link";
import { recoverTypedSignature, SignTypedDataVersion } from "@metamask/eth-sig-util";
import { decodeJWT, verifyJWS } from "did-jwt";
import { getResolver } from "@ceramicnetwork/3id-did-resolver";
import { Resolver } from 'did-resolver';
const JWT_REGEX = /^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/
async retrieveDidDocument(did: string) {
const threeidresolver = getResolver(ceramicHttpClient)
const resolver = new Resolver(threeidresolver);
const doc = await resolver.resolve(did);
return doc;
}
async verifyVc(vc: string) {
return vc.match(JWT_REGEX) ? this.verifyJwtVc(vc) : this.verify712Vc(vc)
}
async verifyJwtVc(vc: string) {
const decoded = decodeJWT(vc).payload as VC
if(!decoded || !decoded?.issuer) throw new Error("Decoding JWT");
const issuer = (typeof decoded.issuer === 'string') ? decoded.issuer : decoded.issuer.id
const doc = await retrieveDidDocument(issuer);
if(!doc.didDocument || !doc.didDocument.verificationMethod) throw new Error("Could not fetch did doc");
const verified = await verifyJWS(vc, doc.didDocument?.verificationMethod!)
return verified ? true : false
}
async verify712Vc(vc: string) {
try {
const TypedData = JSON.parse(vc);
if(!TypedData.proof || !TypedData.proof.proofValue) throw new Missing712ProofException();
if(
!TypedData.proof.eip712Domain ||
!TypedData.proof.eip712Domain.messageSchema ||
!TypedData.proof.eip712Domain.domain
) throw new Missing712DomainException();
const { proof, ...signingInput } = TypedData;
const { proofValue, eip712Domain, ...verifyInputProof} = proof;
const verificationMessage = {
...signingInput,
proof: verifyInputProof
};
const objectToVerify = {
message: verificationMessage,
domain: eip712Domain.domain,
types: eip712Domain.messageSchema,
primaryType: eip712Domain.primaryType
};
const recovered = recoverTypedSignature({data: objectToVerify, signature: proofValue, version: SignTypedDataVersion.V4});
// Get did from address using CAIP 10
// const { did } = await Caip10Link.fromAccount(this.ceramicHttpClient, ethAddress + ACOUNTID_SUFFIX);
if(did === signingInput.issuer.id){
return TypedData;
} else {
throw new SignatureMismatchException(did, signingInput.issuer.id);
}
} catch (e: any) {
console.log(e);
throw e;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment