diff --git a/lib/helpers.js b/lib/helpers.js index f685bf74..5c7ac2be 100644 --- a/lib/helpers.js +++ b/lib/helpers.js @@ -44,13 +44,33 @@ export function assertCredentialContext({context}) { } /** - * Checks to see if a VC has a V1 context. + * Turns the first context in a VC into a numbered version. * * @param {object} options - Options. * @param {object} options.credential - A VC. * - * @returns {boolean} If the VC has a V1 context. + * @returns {number} A number representing the version. */ -export function hasV1CredentialContext({credential}) { - return credential?.['@context']?.[0] === CREDENTIALS_CONTEXT_V1_URL; +function getContextVersion({credential} = {}) { + const firstContext = credential?.['@context']?.[0]; + if(firstContext === CREDENTIALS_CONTEXT_V1_URL) { + return 1.0; + } + if(firstContext === CREDENTIALS_CONTEXT_V2_URL) { + return 2.0; + } + return 0; +} + +/** + * Checks if a VC is using a specific context version. + * + * @param {object} options - Options. + * @param {object} options.credential - A VC. + * @param {number} options.version - A VC Context version + * + * @returns {boolean} If the first context matches the version. + */ +export function checkContextVersion({credential, version}) { + return getContextVersion({credential}) === version; } diff --git a/lib/index.js b/lib/index.js index f3aec728..7d5c4d28 100644 --- a/lib/index.js +++ b/lib/index.js @@ -36,9 +36,9 @@ */ import { assertCredentialContext, + checkContextVersion, CREDENTIALS_CONTEXT_V1_URL, CREDENTIALS_CONTEXT_V2_URL, - hasV1CredentialContext } from './helpers.js'; import {documentLoader as _documentLoader} from './documentLoader.js'; import {CredentialIssuancePurpose} from './CredentialIssuancePurpose.js'; @@ -134,7 +134,10 @@ export async function issue({ if(!credential) { throw new TypeError('"credential" parameter is required for issuing.'); } - if(hasV1CredentialContext({credential}) && !credential.issuanceDate) { + if(checkContextVersion({ + credential, + version: 1.0 + }) && !credential.issuanceDate) { const now = (new Date()).toJSON(); credential.issuanceDate = `${now.slice(0, now.length - 5)}Z`; } @@ -604,7 +607,7 @@ export function _checkCredential({ if(!credential.issuer) { throw new Error('"issuer" property is required.'); } - if(hasV1CredentialContext({credential})) { + if(checkContextVersion({credential, version: 1.0})) { // check issued is a date if(!credential.issuanceDate) { throw new Error('"issuanceDate" property is required.');