Socket
Socket
Sign inDemoInstall

@unumid/server-sdk

Package Overview
Dependencies
Maintainers
1
Versions
88
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@unumid/server-sdk - npm Package Compare versions

Comparing version 3.18.1 to 3.19.0

build/issuer/revokeAllCredentials.d.ts

1

build/config.d.ts
declare const configData: {
nodeEnv: string;
SaaSUrl: string;
debug: boolean;
logLevel: string;

@@ -5,0 +6,0 @@ };

@@ -13,8 +13,29 @@ "use strict";

dotenv_1.default.config();
/**
* Get saas url based on the provide UNUM_ENV env var.
* @param env
*/
function getSaasUrl(env) {
switch (env) {
case 'local':
return 'http://localhost:3030/';
case 'dev':
return 'https://api.dev-unum.id/';
case 'sandbox':
return 'https://api.sandbox-unum.id/';
case 'production':
return 'https://api.unum.id/';
default:
return 'http://localhost:3030/';
}
}
// defaults to sandbox if not provided
var env = process.env.UNUM_ENV || 'sandbox';
var configData = {
nodeEnv: process.env.NODE_ENV || 'sandbox',
SaaSUrl: process.env.SAAS_URL || 'https://api.sandbox-unumid.org/',
logLevel: process.env.LOG_LEVEL || 'debug' // Winston defaults to info if not set
nodeEnv: env,
SaaSUrl: process.env.UNUM_SAAS_URL || getSaasUrl(env),
debug: process.env.DEBUG === 'true' || false,
logLevel: process.env.LOG_LEVEL || 'info' // Winston defaults to info if not set however being explicit here
};
exports.configData = configData;
//# sourceMappingURL=config.js.map

8

build/index.d.ts

@@ -12,3 +12,2 @@ import { registerVerifier } from './verifier/registerVerifier';

import { CredentialSubject, Presentation, Proof, Credential } from '@unumid/types';
import { checkCredentialStatus } from './verifier/checkCredentialStatus';
import { CustError } from './utils/error';

@@ -19,3 +18,8 @@ import { createProof, createProofPb } from './utils/createProof';

import { getVersionedRequest } from './verifier/getVersionedRequest';
export { registerIssuer, issueCredential, issueCredentials, updateCredentialStatus, registerVerifier, sendEmail, sendRequest, sendSms, verifyPresentation, checkCredentialStatus, getRequest, getVersionedRequest, UnumDto, RegisteredVerifier, VerifiedStatus, Presentation, RegisteredIssuer, CredentialSubject, DecryptedPresentation, CredentialStatusInfo, CustError, Proof, Credential, CredentialInfo, extractCredentialInfo, createProof, createProofPb, convertCredentialSubject };
import { verifySubjectCredentialRequests } from './issuer/verifySubjectCredentialRequests';
import { verifySignedDid } from './utils/verifyDidDocument';
import { revokeAllCredentials } from './issuer/revokeAllCredentials';
import { updateCredentialStatuses } from './issuer/updateCredentialStatuses';
import { checkCredentialStatuses } from './verifier/checkCredentialStatuses';
export { registerIssuer, issueCredential, issueCredentials, updateCredentialStatus, updateCredentialStatuses, verifySubjectCredentialRequests, revokeAllCredentials, registerVerifier, sendEmail, sendRequest, sendSms, verifyPresentation, checkCredentialStatuses, getRequest, getVersionedRequest, UnumDto, RegisteredVerifier, VerifiedStatus, Presentation, RegisteredIssuer, CredentialSubject, DecryptedPresentation, CredentialStatusInfo, CustError, Proof, Credential, CredentialInfo, extractCredentialInfo, verifySignedDid, createProof, createProofPb, convertCredentialSubject };
//# sourceMappingURL=index.d.ts.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.convertCredentialSubject = exports.createProofPb = exports.createProof = exports.extractCredentialInfo = exports.CustError = exports.getVersionedRequest = exports.getRequest = exports.checkCredentialStatus = exports.verifyPresentation = exports.sendSms = exports.sendRequest = exports.sendEmail = exports.registerVerifier = exports.updateCredentialStatus = exports.issueCredentials = exports.issueCredential = exports.registerIssuer = void 0;
exports.convertCredentialSubject = exports.createProofPb = exports.createProof = exports.verifySignedDid = exports.extractCredentialInfo = exports.CustError = exports.getVersionedRequest = exports.getRequest = exports.checkCredentialStatuses = exports.verifyPresentation = exports.sendSms = exports.sendRequest = exports.sendEmail = exports.registerVerifier = exports.revokeAllCredentials = exports.verifySubjectCredentialRequests = exports.updateCredentialStatuses = exports.updateCredentialStatus = exports.issueCredentials = exports.issueCredential = exports.registerIssuer = void 0;
var registerVerifier_1 = require("./verifier/registerVerifier");

@@ -23,4 +23,2 @@ Object.defineProperty(exports, "registerVerifier", { enumerable: true, get: function () { return registerVerifier_1.registerVerifier; } });

Object.defineProperty(exports, "extractCredentialInfo", { enumerable: true, get: function () { return extractCredentialInfo_1.extractCredentialInfo; } });
var checkCredentialStatus_1 = require("./verifier/checkCredentialStatus");
Object.defineProperty(exports, "checkCredentialStatus", { enumerable: true, get: function () { return checkCredentialStatus_1.checkCredentialStatus; } });
var error_1 = require("./utils/error");

@@ -37,2 +35,12 @@ Object.defineProperty(exports, "CustError", { enumerable: true, get: function () { return error_1.CustError; } });

Object.defineProperty(exports, "getVersionedRequest", { enumerable: true, get: function () { return getVersionedRequest_1.getVersionedRequest; } });
var verifySubjectCredentialRequests_1 = require("./issuer/verifySubjectCredentialRequests");
Object.defineProperty(exports, "verifySubjectCredentialRequests", { enumerable: true, get: function () { return verifySubjectCredentialRequests_1.verifySubjectCredentialRequests; } });
var verifyDidDocument_1 = require("./utils/verifyDidDocument");
Object.defineProperty(exports, "verifySignedDid", { enumerable: true, get: function () { return verifyDidDocument_1.verifySignedDid; } });
var revokeAllCredentials_1 = require("./issuer/revokeAllCredentials");
Object.defineProperty(exports, "revokeAllCredentials", { enumerable: true, get: function () { return revokeAllCredentials_1.revokeAllCredentials; } });
var updateCredentialStatuses_1 = require("./issuer/updateCredentialStatuses");
Object.defineProperty(exports, "updateCredentialStatuses", { enumerable: true, get: function () { return updateCredentialStatuses_1.updateCredentialStatuses; } });
var checkCredentialStatuses_1 = require("./verifier/checkCredentialStatuses");
Object.defineProperty(exports, "checkCredentialStatuses", { enumerable: true, get: function () { return checkCredentialStatuses_1.checkCredentialStatuses; } });
//# sourceMappingURL=index.js.map

@@ -252,3 +252,3 @@ "use strict";

exports.issueCredentials = function (authorization, issuer, subjectDid, credentialDataList, signingPrivateKey, expirationDate) { return __awaiter(void 0, void 0, void 0, function () {
var publicKeyInfos, creds, i, type, credData, credSubject, credentialVersionPairs, _loop_1, _i, versionList_2, version, latestVersion, resultantCredentials;
var publicKeyInfoResponse, publicKeyInfos, creds, i, type, credData, credSubject, credentialVersionPairs, _loop_1, _i, versionList_2, version, latestVersion, resultantCredentials;
return __generator(this, function (_a) {

@@ -261,5 +261,7 @@ switch (_a.label) {

validateInputs(issuer, subjectDid, credentialDataList, signingPrivateKey, expirationDate);
return [4 /*yield*/, didHelper_1.getDidDocPublicKeys(authorization, subjectDid)];
return [4 /*yield*/, didHelper_1.getDidDocPublicKeys(authorization, subjectDid, 'RSA')];
case 1:
publicKeyInfos = _a.sent();
publicKeyInfoResponse = _a.sent();
publicKeyInfos = publicKeyInfoResponse.body;
authorization = publicKeyInfoResponse.authToken;
creds = [];

@@ -322,3 +324,3 @@ for (i = 0; i < credentialDataList.length; i++) {

exports.issueCredential = function (authorization, type, issuer, credentialSubject, signingPrivateKey, expirationDate) { return __awaiter(void 0, void 0, void 0, function () {
var subjectDid, publicKeyInfos, error_2;
var subjectDid, publicKeyInfoResponse, publicKeyInfos, error_2;
return __generator(this, function (_a) {

@@ -333,5 +335,7 @@ switch (_a.label) {

subjectDid = credentialSubject.id;
return [4 /*yield*/, didHelper_1.getDidDocPublicKeys(authorization, subjectDid)];
return [4 /*yield*/, didHelper_1.getDidDocPublicKeys(authorization, subjectDid, 'RSA')];
case 1:
publicKeyInfos = _a.sent();
publicKeyInfoResponse = _a.sent();
publicKeyInfos = publicKeyInfoResponse.body;
authorization = publicKeyInfoResponse.authToken;
return [2 /*return*/, issueCredentialHelperDeprecated(authorization, type, issuer, credentialSubject, signingPrivateKey, publicKeyInfos, expirationDate)];

@@ -338,0 +342,0 @@ case 2:

import { RegisteredIssuer, UnumDto } from '../types';
import { VersionInfo } from '@unumid/types';
/**

@@ -7,3 +8,3 @@ * Handles registering an Issuer with UnumID's SaaS.

*/
export declare const registerIssuer: (customerUuid: string, apiKey: string) => Promise<UnumDto<RegisteredIssuer>>;
export declare const registerIssuer: (customerUuid: string, apiKey: string, url: string, versionInfo?: VersionInfo[]) => Promise<UnumDto<RegisteredIssuer>>;
//# sourceMappingURL=registerIssuer.d.ts.map

@@ -49,2 +49,3 @@ "use strict";

var networkRequestHelper_1 = require("../utils/networkRequestHelper");
var validateVersionInfo_1 = require("../utils/validateVersionInfo");
/**

@@ -81,3 +82,3 @@ * Creates an object to encapsulate key information after key pair creation.

*/
var validateInParams = function (customerUuid, apiKey) {
var validateInParams = function (customerUuid, apiKey, url, versionInfo) {
if (!customerUuid) {

@@ -89,2 +90,6 @@ throw new error_1.CustError(400, 'Invalid Issuer: customerUuid is required.');

}
if (!url) {
throw new error_1.CustError(400, 'Invalid Issuer: url is required.');
}
validateVersionInfo_1.validateVersionInfo(versionInfo);
};

@@ -96,50 +101,57 @@ /**

*/
exports.registerIssuer = function (customerUuid, apiKey) { return __awaiter(void 0, void 0, void 0, function () {
var kpSet, issuerOpt, restData, restResp, authToken, issuerResp, error_2;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 3, , 4]);
validateInParams(customerUuid, apiKey);
return [4 /*yield*/, createKeyPairs_1.createKeyPairSet()];
case 1:
kpSet = _a.sent();
issuerOpt = {
customerUuid: customerUuid,
publicKeyInfo: constructKeyObjs(kpSet)
};
restData = {
method: 'POST',
baseUrl: config_1.configData.SaaSUrl,
endPoint: 'issuer',
header: { Authorization: 'Bearer ' + apiKey },
data: issuerOpt
};
return [4 /*yield*/, networkRequestHelper_1.makeNetworkRequest(restData)];
case 2:
restResp = _a.sent();
authToken = networkRequestHelper_1.handleAuthTokenHeader(restResp);
issuerResp = {
authToken: authToken,
body: {
uuid: restResp.body.uuid,
customerUuid: restResp.body.customerUuid,
did: restResp.body.did,
name: restResp.body.name,
createdAt: restResp.body.createdAt,
updatedAt: restResp.body.updatedAt,
isAuthorized: restResp.body.isAuthorized,
keys: kpSet,
apiKey: apiKey
}
};
return [2 /*return*/, issuerResp];
case 3:
error_2 = _a.sent();
logger_1.default.error("Error registering an Issuer with UnumID SaaS. " + error_2);
throw error_2;
case 4: return [2 /*return*/];
}
exports.registerIssuer = function (customerUuid, apiKey, url, versionInfo) {
if (versionInfo === void 0) { versionInfo = [{ target: { version: '1.0.0' }, sdkVersion: '3.0.0' }]; }
return __awaiter(void 0, void 0, void 0, function () {
var kpSet, issuerOpt, restData, restResp, authToken, issuerResp, error_2;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 3, , 4]);
validateInParams(customerUuid, apiKey, url, versionInfo);
return [4 /*yield*/, createKeyPairs_1.createKeyPairSet()];
case 1:
kpSet = _a.sent();
issuerOpt = {
customerUuid: customerUuid,
publicKeyInfo: constructKeyObjs(kpSet),
url: url,
versionInfo: versionInfo
};
restData = {
method: 'POST',
baseUrl: config_1.configData.SaaSUrl,
endPoint: 'issuer',
header: { Authorization: 'Bearer ' + apiKey },
data: issuerOpt
};
return [4 /*yield*/, networkRequestHelper_1.makeNetworkRequest(restData)];
case 2:
restResp = _a.sent();
authToken = networkRequestHelper_1.handleAuthTokenHeader(restResp);
issuerResp = {
authToken: authToken,
body: {
uuid: restResp.body.uuid,
customerUuid: restResp.body.customerUuid,
did: restResp.body.did,
name: restResp.body.name,
createdAt: restResp.body.createdAt,
updatedAt: restResp.body.updatedAt,
isAuthorized: restResp.body.isAuthorized,
keys: kpSet,
apiKey: apiKey,
url: restResp.body.url,
versionInfo: restResp.body.versionInfo
}
};
return [2 /*return*/, issuerResp];
case 3:
error_2 = _a.sent();
logger_1.default.error("Error registering an Issuer with UnumID SaaS. " + error_2);
throw error_2;
case 4: return [2 /*return*/];
}
});
});
}); };
};
//# sourceMappingURL=registerIssuer.js.map

@@ -74,3 +74,3 @@ "use strict";

return __awaiter(void 0, void 0, void 0, function () {
var restData, response, authToken, revokedCredential, error_2;
var restData, response, authToken, result, error_2;
return __generator(this, function (_a) {

@@ -85,3 +85,3 @@ switch (_a.label) {

baseUrl: config_1.configData.SaaSUrl,
endPoint: 'credentialStatus/' + credentialId,
endPoint: 'credentialStatus/?credentialId=' + credentialId,
header: { Authorization: authorization },

@@ -94,7 +94,7 @@ data: { status: status }

authToken = networkRequestHelper_1.handleAuthTokenHeader(response, authorization);
revokedCredential = {
result = {
authToken: authToken,
body: undefined
};
return [2 /*return*/, revokedCredential];
return [2 /*return*/, result];
case 2:

@@ -101,0 +101,0 @@ error_2 = _a.sent();

@@ -27,5 +27,6 @@ "use strict";

// Printing this info here instead of in ./config to prevent a circular dependency.
logger.debug("Server SDK SaaS URL: " + config_1.configData.SaaSUrl);
logger.debug("Server SDK Log Level: " + config_1.configData.logLevel);
logger.debug("Server SDK v3 SaaS URL: " + config_1.configData.SaaSUrl);
logger.debug("Server SDK v3 Log Level: " + config_1.configData.logLevel);
logger.debug("Server SDK v3 Debug: " + config_1.configData.debug);
exports.default = logger;
//# sourceMappingURL=logger.js.map

@@ -136,3 +136,3 @@ import { CredentialStatusOptions, Issuer, CredentialSubject, Verifier, CredentialRequest, Presentation, KeyPair, PublicKeyInfo, JSONObj, PresentationPb, CredentialRequestPb } from '@unumid/types';

*/
export interface VerifiedStatus {
export interface VerifiedStatus{
isVerified: boolean;

@@ -142,2 +142,22 @@ message?: string;

// /**
// * A type to convey why a presentation can not be verified.
// * While this would normally be served by throwing an exception we want to pass back the auth token returned
// * by calls to the SaaS via the UnumDto type.
// */
// export interface VerifiedStatus<T = any> {
// isVerified: boolean;
// message?: string;
// metadata?: T;
// }
// /**
// * Interface to encapsulate the subject did attributed to a verifySubjectCredentialRequests call.
// * This is useful for customers to use as reference to then issues the credentials.
// * Note: the verification method ensures the same subject did is used for all requests.
// */
// export interface SubjectCredentialRequestsVerifiedMetadata {
// subjectDid: string
// }
/**

@@ -144,0 +164,0 @@ * A type came about need to convey that a credential presentation can not be verified.

import { DidDocument, DidKeyType, PublicKeyInfo } from '@unumid/types';
import { CustError } from './error';
import { RESTResponse } from '../types';
import { RESTResponse, UnumDto } from '../types';
/**

@@ -10,11 +10,11 @@ * Get a Did document from the did and url provided.

*/
export declare const getDIDDoc: (baseUrl: string, authorization: string, did: string) => Promise<RESTResponse<DidDocument> | CustError>;
export declare const getDIDDoc: (baseUrl: string, authorization: string, did: string) => Promise<RESTResponse<DidDocument | PublicKeyInfo> | CustError>;
/**
* Helper to get a key from a Did document.
* Note: Per convention, Did documents have secp256r1 keys for signing / verification and only holder DID Documents have RSA keys.
* Helper to return the keys in the DID document which corresponds to the type specified.
* Note: the can be multiple keys of same type on the same DID document.
* @param didDocument DiDDocument
* @param type DidKeyType
*/
export declare const getKeyFromDIDDoc: (didDocument: DidDocument, type: DidKeyType) => PublicKeyInfo[];
export declare const getDidDocPublicKeys: (authorization: string, subjectDid: string) => Promise<PublicKeyInfo[]>;
export declare const getKeysFromDIDDoc: (didDocument: DidDocument, type: DidKeyType) => PublicKeyInfo[];
export declare const getDidDocPublicKeys: (authorization: string, subjectDid: string, type: DidKeyType) => Promise<UnumDto<PublicKeyInfo[]>>;
//# sourceMappingURL=didHelper.d.ts.map

@@ -42,3 +42,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.getDidDocPublicKeys = exports.getKeyFromDIDDoc = exports.getDIDDoc = void 0;
exports.getDidDocPublicKeys = exports.getKeysFromDIDDoc = exports.getDIDDoc = void 0;
var error_1 = require("./error");

@@ -63,3 +63,3 @@ var logger_1 = __importDefault(require("../logger"));

baseUrl: baseUrl,
endPoint: 'didDocument/' + did,
endPoint: 'didDocument/' + encodeURIComponent(did),
header: { Authorization: authorization }

@@ -75,3 +75,3 @@ };

logger_1.default.error("Error getting did document " + did + " from " + baseUrl, error_2);
return [2 /*return*/, (error_2)];
throw error_2;
case 3: return [2 /*return*/];

@@ -82,13 +82,17 @@ }

/**
* Helper to get a key from a Did document.
* Note: Per convention, Did documents have secp256r1 keys for signing / verification and only holder DID Documents have RSA keys.
* Helper to return the keys in the DID document which corresponds to the type specified.
* Note: the can be multiple keys of same type on the same DID document.
* @param didDocument DiDDocument
* @param type DidKeyType
*/
exports.getKeyFromDIDDoc = function (didDocument, type) {
// return the key in the DID document which corresponds to the type specified.
return didDocument.publicKey.filter(function (publicKeyInfo) { return publicKeyInfo.type === type; });
exports.getKeysFromDIDDoc = function (didDocument, type) {
var publicKeyInfos = didDocument.publicKey.filter(function (publicKeyInfo) { return publicKeyInfo.type === type; });
if (publicKeyInfos.length === 0) {
logger_1.default.error("DidDoc " + didDocument.id + " has no " + type + " public keys");
throw new error_1.CustError(500, "DidDoc " + didDocument.id + " has no " + type + " public keys");
}
return publicKeyInfos;
};
exports.getDidDocPublicKeys = function (authorization, subjectDid) { return __awaiter(void 0, void 0, void 0, function () {
var didDocResponse, publicKeyInfos;
exports.getDidDocPublicKeys = function (authorization, subjectDid, type) { return __awaiter(void 0, void 0, void 0, function () {
var didDocResponse, didKeyId, publicKeyInfoList, didDoc, authToken;
return __generator(this, function (_a) {

@@ -103,7 +107,29 @@ switch (_a.label) {

}
publicKeyInfos = exports.getKeyFromDIDDoc(didDocResponse.body, 'RSA');
if (publicKeyInfos.length === 0) {
throw new error_1.CustError(404, 'Public key not found for the DID');
didKeyId = subjectDid.split('#')[1];
if (!didKeyId) return [3 /*break*/, 3];
return [4 /*yield*/, didDocResponse.body];
case 2:
/**
* If making a request to the Did Document service with a did and did fragment, only a single PublicKeyInfo object is returned.
* Putting in array for uniform handling with the case no fragment is included, in which case all the matching keys will need to be tried until one works.
*/
publicKeyInfoList = [_a.sent()];
return [3 /*break*/, 5];
case 3: return [4 /*yield*/, didDocResponse.body];
case 4:
didDoc = _a.sent();
// get subject's encryption public key info from its DID document
publicKeyInfoList = exports.getKeysFromDIDDoc(didDoc, type);
_a.label = 5;
case 5:
// // get subject's public key info from its DID document
// const publicKeyInfos = getKeysFromDIDDoc(didDocResponse.body, 'RSA');
if (publicKeyInfoList.length === 0) {
throw new error_1.CustError(404, type + " public keys not found for the DID " + subjectDid);
}
return [2 /*return*/, publicKeyInfos];
authToken = networkRequestHelper_1.handleAuthTokenHeader(didDocResponse, authorization);
return [2 /*return*/, {
authToken: authToken,
body: publicKeyInfoList
}];
}

@@ -110,0 +136,0 @@ });

@@ -16,2 +16,8 @@ import { PresentationRequestDto, PresentationRequestRepoDto } from '@unumid/types';

export declare function extractPresentationRequest(presentationRequestResponse: PresentationRequestRepoDto): PresentationRequestDto;
/**
* Helper to handle converting the stringified date attributes to real Date objects so the proto serializer doesn't complain when going into a byte array for the signature check.
* @param presentationRequestDto
* @returns
*/
export declare function handleConvertingPresentationRequestDateAttributes(presentationRequestDto: PresentationRequestDto): PresentationRequestDto;
//# sourceMappingURL=getPresentationRequest.d.ts.map

@@ -53,3 +53,4 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.extractPresentationRequest = exports.getPresentationRequest = void 0;
exports.handleConvertingPresentationRequestDateAttributes = exports.extractPresentationRequest = exports.getPresentationRequest = void 0;
var lodash_1 = require("lodash");
var config_1 = require("../config");

@@ -100,7 +101,7 @@ var logger_1 = __importDefault(require("../logger"));

function extractPresentationRequest(presentationRequestResponse) {
// export function extractPresentationRequest (presentationRequestDto: PresentationRequestDto): PresentationRequestDto {
try {
var presentationRequestDto = presentationRequestResponse.presentationRequests['3.0.0'];
// need to convert the times to Date objects for proto handling
var result = __assign(__assign({}, presentationRequestDto), { presentationRequest: __assign(__assign({}, presentationRequestDto.presentationRequest), { createdAt: presentationRequestDto.presentationRequest.createdAt ? new Date(presentationRequestDto.presentationRequest.createdAt) : undefined, updatedAt: presentationRequestDto.presentationRequest.updatedAt ? new Date(presentationRequestDto.presentationRequest.updatedAt) : undefined, expiresAt: presentationRequestDto.presentationRequest.expiresAt ? new Date(presentationRequestDto.presentationRequest.expiresAt) : undefined }) });
return result;
return handleConvertingPresentationRequestDateAttributes(presentationRequestDto);
}

@@ -112,2 +113,30 @@ catch (e) {

exports.extractPresentationRequest = extractPresentationRequest;
/**
* Helper to handle converting the stringified date attributes to real Date objects so the proto serializer doesn't complain when going into a byte array for the signature check.
* @param presentationRequestDto
* @returns
*/
function handleConvertingPresentationRequestDateAttributes(presentationRequestDto) {
var result = __assign(__assign({}, presentationRequestDto), { presentationRequest: __assign(__assign({}, presentationRequestDto.presentationRequest), { createdAt: handleAttributeDateType(presentationRequestDto.presentationRequest.createdAt), updatedAt: handleAttributeDateType(presentationRequestDto.presentationRequest.updatedAt), expiresAt: handleAttributeDateType(presentationRequestDto.presentationRequest.expiresAt) }) });
return result;
}
exports.handleConvertingPresentationRequestDateAttributes = handleConvertingPresentationRequestDateAttributes;
/**
* Helper to make the date attribute handling a little easier to follow than a complicate ternary.
* @param input
* @returns
*/
function handleAttributeDateType(input) {
if (!input) {
return undefined;
}
if (lodash_1.isDate(input)) {
return input;
}
if (lodash_1.isString(input)) {
return new Date(input);
}
logger_1.default.error('PresentationRequest date attribute value is not a string, undefined or Date. This should never happen.');
return undefined;
}
//# sourceMappingURL=getPresentationRequest.js.map

@@ -49,2 +49,3 @@ "use strict";

var networkRequestHelper_1 = require("../utils/networkRequestHelper");
var validateVersionInfo_1 = require("../utils/validateVersionInfo");
/**

@@ -81,3 +82,3 @@ * Creates an object to encapsulate key information after key pair creation.

*/
var validateInParams = function (customerUuid, url, apiKey) {
var validateInParams = function (customerUuid, url, apiKey, versionInfo) {
if (!customerUuid) {

@@ -92,2 +93,3 @@ throw new __1.CustError(400, 'Invalid Verifier Options: customerUuid is required.');

}
validateVersionInfo_1.validateVersionInfo(versionInfo);
};

@@ -102,3 +104,3 @@ /**

exports.registerVerifier = function (customerUuid, url, apiKey, versionInfo) {
if (versionInfo === void 0) { versionInfo = [{ target: { version: '1.0.0' }, sdkVersion: '2.0.0' }]; }
if (versionInfo === void 0) { versionInfo = [{ target: { version: '1.0.0' }, sdkVersion: '3.0.0' }]; }
return __awaiter(void 0, void 0, void 0, function () {

@@ -110,3 +112,3 @@ var kpSet, verifierOpt, restData, restResp, authToken, verifierResp, error_1;

_a.trys.push([0, 3, , 4]);
validateInParams(customerUuid, url, apiKey);
validateInParams(customerUuid, url, apiKey, versionInfo);
return [4 /*yield*/, createKeyPairs_1.createKeyPairSet()];

@@ -113,0 +115,0 @@ case 1:

import { PresentationRequestPostDto as PresentationRequestPostDtoDeprecatedV2, UnsignedPresentationRequest as UnsignedPresentationRequestDeprecatedV2, SignedPresentationRequest as SignedPresentationRequestDeprecatedV2 } from '@unumid/types-v2';
import { CredentialRequest, PresentationRequestPostDto, UnsignedPresentationRequestPb, PresentationRequestPb, CredentialRequestPb } from '@unumid/types';
import { CredentialRequest, UnsignedPresentationRequestPb, PresentationRequestPb, CredentialRequestPb, PresentationRequestDto } from '@unumid/types';
import { SendRequestReqBody, UnumDto } from '../types';

@@ -30,3 +30,3 @@ /**

*/
export declare const sendRequest: (authorization: string, verifier: string, credentialRequests: CredentialRequestPb[] | CredentialRequest[], eccPrivateKey: string, holderAppUuid: string, expirationDate?: Date | undefined, metadata?: Record<string, unknown> | undefined) => Promise<UnumDto<PresentationRequestPostDto>>;
export declare const sendRequest: (authorization: string, verifier: string, credentialRequests: CredentialRequestPb[] | CredentialRequest[], eccPrivateKey: string, holderAppUuid: string, expirationDate?: Date | undefined, metadata?: Record<string, unknown> | undefined) => Promise<UnumDto<PresentationRequestDto>>;
/**

@@ -40,3 +40,3 @@ * Handler for sending a PresentationRequest to UnumID's SaaS.

*/
export declare const sendRequestV3: (authorization: string, verifier: string, credentialRequests: CredentialRequestPb[], eccPrivateKey: string, holderAppUuid: string, id: string, expirationDate?: Date | undefined, metadata?: any) => Promise<UnumDto<PresentationRequestPostDto>>;
export declare const sendRequestV3: (authorization: string, verifier: string, credentialRequests: CredentialRequestPb[], eccPrivateKey: string, holderAppUuid: string, id: string, expirationDate?: Date | undefined, metadata?: any) => Promise<UnumDto<PresentationRequestDto>>;
/**

@@ -43,0 +43,0 @@ * Handler for sending a PresentationRequest to UnumID's SaaS.

@@ -283,14 +283,7 @@ "use strict";

exports.sendRequest = function (authorization, verifier, credentialRequests, eccPrivateKey, holderAppUuid, expirationDate, metadata) { return __awaiter(void 0, void 0, void 0, function () {
var id, responseV2, response;
var id, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
id = helpers_1.getUUID();
return [4 /*yield*/, exports.sendRequestDeprecated(authorization, verifier, credentialRequests, eccPrivateKey, holderAppUuid, id, expirationDate, metadata)];
case 1:
responseV2 = _a.sent();
authorization = responseV2.authToken ? responseV2.authToken : authorization;
response = exports.sendRequestV3(authorization, verifier, credentialRequests, eccPrivateKey, holderAppUuid, id, expirationDate, metadata);
return [2 /*return*/, response];
}
id = helpers_1.getUUID();
response = exports.sendRequestV3(authorization, verifier, credentialRequests, eccPrivateKey, holderAppUuid, id, expirationDate, metadata);
return [2 /*return*/, response];
});

@@ -297,0 +290,0 @@ }); };

@@ -1,2 +0,2 @@

import { ProofPb } from '@unumid/types';
import { Proof, ProofPb } from '@unumid/types';
/**

@@ -7,2 +7,7 @@ * Helper to validate a proof has the required attributes.

export declare const validateProof: (proof: ProofPb) => ProofPb;
/**
* Helper to validate a proof has the required attributes.
* @param proof ProofPb
*/
export declare const validateProofDeprecated: (proof: Proof) => Proof;
//# sourceMappingURL=validateProof.d.ts.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateProof = void 0;
exports.validateProofDeprecated = exports.validateProof = void 0;
var error_1 = require("../utils/error");

@@ -31,2 +31,25 @@ /**

};
/**
* Helper to validate a proof has the required attributes.
* @param proof ProofPb
*/
exports.validateProofDeprecated = function (proof) {
var created = proof.created, signatureValue = proof.signatureValue, type = proof.type, verificationMethod = proof.verificationMethod, proofPurpose = proof.proofPurpose;
if (!created) {
throw new error_1.CustError(400, 'Invalid Presentation: proof.created is required.');
}
if (!signatureValue) {
throw new error_1.CustError(400, 'Invalid Presentation: proof.signatureValue is required.');
}
if (!type) {
throw new error_1.CustError(400, 'Invalid Presentation: proof.type is required.');
}
if (!verificationMethod) {
throw new error_1.CustError(400, 'Invalid Presentation: proof.verificationMethod is required.');
}
if (!proofPurpose) {
throw new error_1.CustError(400, 'Invalid Presentation: proof.proofPurpose is required.');
}
return proof;
};
//# sourceMappingURL=validateProof.js.map

@@ -8,3 +8,3 @@ import { UnumDto } from '../types';

*/
export declare const verifyCredential: (credential: CredentialPb, authorization: string) => Promise<UnumDto<boolean>>;
export declare const verifyCredential: (authorization: string, credential: CredentialPb) => Promise<UnumDto<boolean>>;
//# sourceMappingURL=verifyCredential.d.ts.map

@@ -45,7 +45,5 @@ "use strict";

var lodash_1 = require("lodash");
var config_1 = require("../config");
var logger_1 = __importDefault(require("../logger"));
var types_1 = require("@unumid/types");
var didHelper_1 = require("../utils/didHelper");
var networkRequestHelper_1 = require("../utils/networkRequestHelper");
var verify_1 = require("../utils/verify");

@@ -58,4 +56,4 @@ var __1 = require("..");

*/
exports.verifyCredential = function (credential, authorization) { return __awaiter(void 0, void 0, void 0, function () {
var proof, didDocumentResponse, authToken, publicKeyObject, data, bytes, isVerified, result, result;
exports.verifyCredential = function (authorization, credential) { return __awaiter(void 0, void 0, void 0, function () {
var proof, publicKeyInfoResponse, publicKeyInfoList, authToken, data, bytes, isVerified, _i, publicKeyInfoList_1, publicKeyInfo, publicKey, encoding, result, result;
return __generator(this, function (_a) {

@@ -68,14 +66,19 @@ switch (_a.label) {

}
return [4 /*yield*/, didHelper_1.getDIDDoc(config_1.configData.SaaSUrl, authorization, proof.verificationMethod)];
return [4 /*yield*/, didHelper_1.getDidDocPublicKeys(authorization, proof.verificationMethod, 'secp256r1')];
case 1:
didDocumentResponse = _a.sent();
if (didDocumentResponse instanceof Error) {
throw didDocumentResponse;
}
authToken = networkRequestHelper_1.handleAuthTokenHeader(didDocumentResponse, authorization);
publicKeyObject = didHelper_1.getKeyFromDIDDoc(didDocumentResponse.body, 'secp256r1');
publicKeyInfoResponse = _a.sent();
publicKeyInfoList = publicKeyInfoResponse.body;
authToken = publicKeyInfoResponse.authToken;
data = lodash_1.omit(credential, 'proof');
try {
bytes = types_1.UnsignedCredentialPb.encode(data).finish();
isVerified = verify_1.doVerify(proof.signatureValue, bytes, publicKeyObject[0].publicKey, publicKeyObject[0].encoding);
isVerified = false;
// check all the public keys to see if any work, stop if one does
for (_i = 0, publicKeyInfoList_1 = publicKeyInfoList; _i < publicKeyInfoList_1.length; _i++) {
publicKeyInfo = publicKeyInfoList_1[_i];
publicKey = publicKeyInfo.publicKey, encoding = publicKeyInfo.encoding;
isVerified = verify_1.doVerify(proof.signatureValue, bytes, publicKey, encoding);
if (isVerified)
break;
}
result = {

@@ -82,0 +85,0 @@ authToken: authToken,

@@ -10,7 +10,7 @@ import { UnumDto, VerifiedStatus } from '../types';

* Handler for when a user does not agree to share the information in the credential request.
* @param authorization
* @param authToken
* @param noPresentation
* @param verifier
*/
export declare const verifyNoPresentationHelper: (authorization: string, noPresentation: PresentationPb, verifier: string, requestUuid: string) => Promise<UnumDto<VerifiedStatus>>;
export declare const verifyNoPresentationHelper: (authToken: string, noPresentation: PresentationPb, verifier: string, requestUuid: string) => Promise<UnumDto<VerifiedStatus>>;
//# sourceMappingURL=verifyNoPresentationHelper.d.ts.map

@@ -45,3 +45,2 @@ "use strict";

var validateProof_1 = require("./validateProof");
var config_1 = require("../config");
var requireAuth_1 = require("../requireAuth");

@@ -51,3 +50,2 @@ var logger_1 = __importDefault(require("../logger"));

var helpers_1 = require("../utils/helpers");
var networkRequestHelper_1 = require("../utils/networkRequestHelper");
var verify_1 = require("../utils/verify");

@@ -89,13 +87,13 @@ var types_1 = require("@unumid/types");

* Handler for when a user does not agree to share the information in the credential request.
* @param authorization
* @param authToken
* @param noPresentation
* @param verifier
*/
exports.verifyNoPresentationHelper = function (authorization, noPresentation, verifier, requestUuid) { return __awaiter(void 0, void 0, void 0, function () {
var _a, verificationMethod, signatureValue, verifierDid, message_1, authToken_1, result_1, didDocumentResponse, authToken, publicKeyInfos, _b, publicKey, encoding, unsignedNoPresentation, bytes, isVerified, message, result, e_1;
return __generator(this, function (_c) {
switch (_c.label) {
exports.verifyNoPresentationHelper = function (authToken, noPresentation, verifier, requestUuid) { return __awaiter(void 0, void 0, void 0, function () {
var _a, verificationMethod, signatureValue, verifierDid, message_1, result_1, publicKeyInfoResponse, publicKeyInfoList, unsignedNoPresentation, bytes, isVerified, _i, publicKeyInfoList_1, publicKeyInfo, publicKey, encoding, message, result, e_1;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_c.trys.push([0, 5, , 6]);
requireAuth_1.requireAuth(authorization);
_b.trys.push([0, 5, , 6]);
requireAuth_1.requireAuth(authToken);
noPresentation = exports.validateNoPresentationParams(noPresentation);

@@ -108,7 +106,8 @@ if (!noPresentation.proof) {

message_1 = "The presentation was meant for verifier, " + verifierDid + ", not the provided verifier, " + verifier + ".";
return [4 /*yield*/, sendPresentationVerifiedReceipt_1.sendPresentationVerifiedReceipt(authorization, verifier, noPresentation.proof.verificationMethod, 'declined', false, noPresentation.presentationRequestId, requestUuid, message_1)];
return [4 /*yield*/, sendPresentationVerifiedReceipt_1.sendPresentationVerifiedReceipt(authToken, verifier, noPresentation.proof.verificationMethod, 'declined', false, noPresentation.presentationRequestId, requestUuid, message_1)];
case 1:
authToken_1 = _c.sent();
// send PresentationVerified receipt
authToken = _b.sent();
result_1 = {
authToken: authToken_1,
authToken: authToken,
body: {

@@ -120,18 +119,23 @@ isVerified: false,

return [2 /*return*/, result_1];
case 2: return [4 /*yield*/, didHelper_1.getDIDDoc(config_1.configData.SaaSUrl, authorization, verificationMethod)];
case 2: return [4 /*yield*/, didHelper_1.getDidDocPublicKeys(authToken, verificationMethod, 'secp256r1')];
case 3:
didDocumentResponse = _c.sent();
if (didDocumentResponse instanceof Error) {
throw didDocumentResponse;
}
authToken = networkRequestHelper_1.handleAuthTokenHeader(didDocumentResponse, authorization);
publicKeyInfos = didHelper_1.getKeyFromDIDDoc(didDocumentResponse.body, 'secp256r1');
_b = publicKeyInfos[0], publicKey = _b.publicKey, encoding = _b.encoding;
publicKeyInfoResponse = _b.sent();
publicKeyInfoList = publicKeyInfoResponse.body;
authToken = publicKeyInfoResponse.authToken;
unsignedNoPresentation = lodash_1.omit(noPresentation, 'proof');
bytes = types_1.UnsignedPresentationPb.encode(unsignedNoPresentation).finish();
isVerified = verify_1.doVerify(signatureValue, bytes, publicKey, encoding);
isVerified = false;
// check all the public keys to see if any work, stop if one does
for (_i = 0, publicKeyInfoList_1 = publicKeyInfoList; _i < publicKeyInfoList_1.length; _i++) {
publicKeyInfo = publicKeyInfoList_1[_i];
publicKey = publicKeyInfo.publicKey, encoding = publicKeyInfo.encoding;
// verify the signature
isVerified = verify_1.doVerify(signatureValue, bytes, publicKey, encoding);
if (isVerified)
break;
}
message = isVerified ? undefined : 'Presentation signature can not be verified.';
return [4 /*yield*/, sendPresentationVerifiedReceipt_1.sendPresentationVerifiedReceipt(authToken, verifier, noPresentation.proof.verificationMethod, 'declined', isVerified, noPresentation.presentationRequestId, requestUuid, message)];
case 4:
authToken = _c.sent();
authToken = _b.sent();
result = {

@@ -146,3 +150,3 @@ authToken: authToken,

case 5:
e_1 = _c.sent();
e_1 = _b.sent();
logger_1.default.error("Error handling a declined presentation verification. Error " + e_1);

@@ -149,0 +153,0 @@ throw e_1;

import { DecryptedPresentation, UnumDto } from '../types';
import { PresentationRequestDto, EncryptedData } from '@unumid/types';
/**
* Handler to send information regarding the user agreeing to share a credential Presentation.
* Handler for verifying a provided encrypted Presentation.
* @param authorization: string

@@ -6,0 +6,0 @@ * @param encryptedPresentation: EncryptedData

@@ -165,5 +165,5 @@ "use strict";

return __awaiter(this, void 0, void 0, function () {
var _a, verificationMethod, signatureValue, didDocumentResponse, authToken, publicKeyInfos, _b, publicKey, encoding, unsignedPresentationRequest, bytes, isVerified, result_1, result;
return __generator(this, function (_c) {
switch (_c.label) {
var _a, verificationMethod, signatureValue, publicKeyInfoResponse, publicKeyInfoList, authToken, unsignedPresentationRequest, bytes, isVerified, _i, publicKeyInfoList_1, publicKeyInfo, publicKey, encoding, result_1, result;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:

@@ -174,14 +174,19 @@ if (!presentationRequest.proof) {

_a = presentationRequest.proof, verificationMethod = _a.verificationMethod, signatureValue = _a.signatureValue;
return [4 /*yield*/, didHelper_1.getDIDDoc(config_1.configData.SaaSUrl, authorization, verificationMethod)];
return [4 /*yield*/, didHelper_1.getDidDocPublicKeys(authorization, verificationMethod, 'secp256r1')];
case 1:
didDocumentResponse = _c.sent();
if (didDocumentResponse instanceof Error) {
throw didDocumentResponse;
}
authToken = networkRequestHelper_1.handleAuthTokenHeader(didDocumentResponse, authorization);
publicKeyInfos = didHelper_1.getKeyFromDIDDoc(didDocumentResponse.body, 'secp256r1');
_b = publicKeyInfos[0], publicKey = _b.publicKey, encoding = _b.encoding;
publicKeyInfoResponse = _b.sent();
publicKeyInfoList = publicKeyInfoResponse.body;
authToken = publicKeyInfoResponse.authToken;
unsignedPresentationRequest = lodash_1.omit(presentationRequest, 'proof');
bytes = types_1.UnsignedPresentationRequestPb.encode(unsignedPresentationRequest).finish();
isVerified = verify_1.doVerify(signatureValue, bytes, publicKey, encoding);
isVerified = false;
// check all the public keys to see if any work, stop if one does
for (_i = 0, publicKeyInfoList_1 = publicKeyInfoList; _i < publicKeyInfoList_1.length; _i++) {
publicKeyInfo = publicKeyInfoList_1[_i];
publicKey = publicKeyInfo.publicKey, encoding = publicKeyInfo.encoding;
// verify the signature
isVerified = verify_1.doVerify(signatureValue, bytes, publicKey, encoding);
if (isVerified)
break;
}
if (!isVerified) {

@@ -209,3 +214,3 @@ result_1 = {

/**
* Handler to send information regarding the user agreeing to share a credential Presentation.
* Handler for verifying a provided encrypted Presentation.
* @param authorization: string

@@ -220,3 +225,3 @@ * @param encryptedPresentation: EncryptedData

case 0:
_a.trys.push([0, 9, , 10]);
_a.trys.push([0, 10, , 11]);
requireAuth_1.requireAuth(authorization);

@@ -237,3 +242,3 @@ if (!encryptedPresentation) {

presentation = types_1.PresentationPb.decode(presentationBytes);
if (process.env.NODE_ENV === 'debug') {
if (config_1.configData.debug) {
logger_1.default.debug("Decrypted Presentation: " + JSON.stringify(presentation));

@@ -249,4 +254,8 @@ }

presentationRequest = getPresentationRequest_1.extractPresentationRequest(presentationRequestResponse.body);
_a.label = 2;
return [3 /*break*/, 3];
case 2:
// need to convert the string date attributes to to Date objects for proto handling
presentationRequest = getPresentationRequest_1.handleConvertingPresentationRequestDateAttributes(presentationRequest);
_a.label = 3;
case 3:
// verify the presentation request uuid match

@@ -256,11 +265,11 @@ if (presentationRequest.presentationRequest.id !== presentation.presentationRequestId) {

}
if (!presentationRequest.presentationRequest) return [3 /*break*/, 5];
if (!presentationRequest.presentationRequest) return [3 /*break*/, 6];
presentationRequestPb = validatePresentationRequest(presentationRequest.presentationRequest);
return [4 /*yield*/, verifyPresentationRequest(authorization, presentationRequestPb)];
case 3:
case 4:
requestVerificationResult = _a.sent();
authorization = requestVerificationResult.authToken;
if (!!requestVerificationResult.body.isVerified) return [3 /*break*/, 5];
if (!!requestVerificationResult.body.isVerified) return [3 /*break*/, 6];
return [4 /*yield*/, handlePresentationVerificationReceipt(requestVerificationResult.authToken, presentation, verifierDid, requestVerificationResult.body.message, presentationRequest.presentationRequest.uuid)];
case 4:
case 5:
authToken = _a.sent();

@@ -273,6 +282,6 @@ type = isDeclinedPresentation(presentation) ? 'DeclinedPresentation' : 'VerifiablePresentation';

return [2 /*return*/, result_2];
case 5:
if (!isDeclinedPresentation(presentation)) return [3 /*break*/, 7];
case 6:
if (!isDeclinedPresentation(presentation)) return [3 /*break*/, 8];
return [4 /*yield*/, verifyNoPresentationHelper_1.verifyNoPresentationHelper(authorization, presentation, verifierDid, presentationRequest.presentationRequest.uuid)];
case 6:
case 7:
verificationResult_1 = _a.sent();

@@ -284,6 +293,6 @@ result_3 = {

return [2 /*return*/, result_3];
case 7:
case 8:
credentialRequests = presentationRequest.presentationRequest.credentialRequests;
return [4 /*yield*/, verifyPresentationHelper_1.verifyPresentationHelper(authorization, presentation, verifierDid, credentialRequests, presentationRequest.presentationRequest.uuid)];
case 8:
case 9:
verificationResult = _a.sent();

@@ -295,3 +304,3 @@ result = {

return [2 /*return*/, result];
case 9:
case 10:
error_2 = _a.sent();

@@ -308,3 +317,3 @@ if (error_2 instanceof library_crypto_1.CryptoError) {

throw error_2;
case 10: return [2 /*return*/];
case 11: return [2 /*return*/];
}

@@ -311,0 +320,0 @@ });

@@ -44,3 +44,2 @@ "use strict";

var lodash_1 = require("lodash");
var config_1 = require("../config");
var types_1 = require("@unumid/types");

@@ -51,3 +50,2 @@ var validateProof_1 = require("./validateProof");

var isCredentialExpired_1 = require("./isCredentialExpired");
var checkCredentialStatus_1 = require("./checkCredentialStatus");
var logger_1 = __importDefault(require("../logger"));

@@ -58,6 +56,7 @@ var library_crypto_1 = require("@unumid/library-crypto");

var didHelper_1 = require("../utils/didHelper");
var networkRequestHelper_1 = require("../utils/networkRequestHelper");
var verify_1 = require("../utils/verify");
var convertCredentialSubject_1 = require("../utils/convertCredentialSubject");
var sendPresentationVerifiedReceipt_1 = require("./sendPresentationVerifiedReceipt");
var checkCredentialStatuses_1 = require("./checkCredentialStatuses");
var getCredentialStatusFromMap_1 = require("../utils/getCredentialStatusFromMap");
/**

@@ -75,8 +74,6 @@ * Validates the attributes for a credential from UnumId's Saas

}
var totCred = credentials.length;
for (var i = 0; i < totCred; i++) {
var credPosStr = '[' + i + ']';
for (var i = 0; i < credentials.length; i++) {
var credential = credentials[i];
// Validate the existence of elements in Credential object
var invalidMsg = "Invalid verifiableCredential" + credPosStr + ":";
var invalidMsg = "Invalid verifiableCredential[" + i + "]:";
if (!credential.context) {

@@ -265,7 +262,7 @@ retObj.valid = false;

exports.verifyPresentationHelper = function (authorization, presentation, verifier, credentialRequests, requestUuid) { return __awaiter(void 0, void 0, void 0, function () {
var data, proof, subject, credentialTypes, credentialIds, issuers, message, authToken_1, result_1, didDocumentResponse, authToken, pubKeyObj, result_2, isPresentationVerified, bytes, e_1, message, authToken_2, result_3, message, authToken_3, result_4, areCredentialsValid, credentialInvalidMessage, _i, _a, credential, isExpired, isStatusValidResponse, isStatusValid, isVerifiedResponse, isVerified_1, authToken_4, result_5, isVerified, result, error_2;
return __generator(this, function (_b) {
switch (_b.label) {
var data, proof, subject, credentialTypes, credentialIds, issuers, message, authToken_1, result_1, publicKeyInfoResponse, publicKeyInfoList, authToken, isPresentationVerified, bytes, _i, publicKeyInfoList_1, publicKeyInfo, publicKey, encoding, e_1, message, result_2, message, result_3, areCredentialsValid, credentialInvalidMessage, presentationCredentialIds, isStatusValidResponse, _a, _b, credential, isExpired, isStatusValid, isVerifiedResponse, isVerified_1, result_4, isVerified, result, error_2;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
_b.trys.push([0, 18, , 19]);
_c.trys.push([0, 18, , 19]);
requireAuth_1.requireAuth(authorization);

@@ -289,3 +286,3 @@ if (!presentation) {

case 1:
authToken_1 = _b.sent();
authToken_1 = _c.sent();
result_1 = {

@@ -304,30 +301,24 @@ authToken: authToken_1,

}
return [4 /*yield*/, didHelper_1.getDIDDoc(config_1.configData.SaaSUrl, authorization, proof.verificationMethod)];
return [4 /*yield*/, didHelper_1.getDidDocPublicKeys(authorization, proof.verificationMethod, 'secp256r1')];
case 3:
didDocumentResponse = _b.sent();
if (didDocumentResponse instanceof Error) {
throw didDocumentResponse;
}
authToken = networkRequestHelper_1.handleAuthTokenHeader(didDocumentResponse, authorization);
pubKeyObj = didHelper_1.getKeyFromDIDDoc(didDocumentResponse.body, 'secp256r1');
if (pubKeyObj.length === 0) {
result_2 = {
authToken: authToken,
body: {
isVerified: false,
message: 'Public key not found for the DID associated with the proof.verificationMethod'
}
};
return [2 /*return*/, result_2];
}
publicKeyInfoResponse = _c.sent();
publicKeyInfoList = publicKeyInfoResponse.body;
authToken = publicKeyInfoResponse.authToken;
isPresentationVerified = false;
_b.label = 4;
_c.label = 4;
case 4:
_b.trys.push([4, 5, , 7]);
_c.trys.push([4, 5, , 7]);
bytes = types_1.UnsignedPresentationPb.encode(data).finish();
// verify the signature
isPresentationVerified = verify_1.doVerify(proof.signatureValue, bytes, pubKeyObj[0].publicKey, pubKeyObj[0].encoding);
// check all the public keys to see if any work, stop if one does
for (_i = 0, publicKeyInfoList_1 = publicKeyInfoList; _i < publicKeyInfoList_1.length; _i++) {
publicKeyInfo = publicKeyInfoList_1[_i];
publicKey = publicKeyInfo.publicKey, encoding = publicKeyInfo.encoding;
// verify the signature
isPresentationVerified = verify_1.doVerify(proof.signatureValue, bytes, publicKey, encoding);
if (isPresentationVerified)
break;
}
return [3 /*break*/, 7];
case 5:
e_1 = _b.sent();
e_1 = _c.sent();
if (e_1 instanceof library_crypto_1.CryptoError) {

@@ -340,7 +331,8 @@ logger_1.default.error("CryptoError verifying presentation " + JSON.stringify(presentation) + " signature", e_1);

message = "Exception verifying presentation signature. " + e_1.message;
return [4 /*yield*/, sendPresentationVerifiedReceipt_1.sendPresentationVerifiedReceipt(authorization, verifier, proof.verificationMethod, 'approved', false, presentation.presentationRequestId, requestUuid, message, issuers, credentialTypes, credentialIds)];
return [4 /*yield*/, sendPresentationVerifiedReceipt_1.sendPresentationVerifiedReceipt(authToken, verifier, proof.verificationMethod, 'approved', false, presentation.presentationRequestId, requestUuid, message, issuers, credentialTypes, credentialIds)];
case 6:
authToken_2 = _b.sent();
result_3 = {
authToken: authToken_2,
// send PresentationVerified receipt
authToken = _c.sent();
result_2 = {
authToken: authToken,
body: {

@@ -351,11 +343,12 @@ isVerified: false,

};
return [2 /*return*/, result_3];
return [2 /*return*/, result_2];
case 7:
if (!!isPresentationVerified) return [3 /*break*/, 9];
message = 'Presentation signature can not be verified';
return [4 /*yield*/, sendPresentationVerifiedReceipt_1.sendPresentationVerifiedReceipt(authorization, verifier, proof.verificationMethod, 'approved', false, presentation.presentationRequestId, requestUuid, message, issuers, credentialTypes, credentialIds)];
return [4 /*yield*/, sendPresentationVerifiedReceipt_1.sendPresentationVerifiedReceipt(authToken, verifier, proof.verificationMethod, 'approved', false, presentation.presentationRequestId, requestUuid, message, issuers, credentialTypes, credentialIds)];
case 8:
authToken_3 = _b.sent();
result_4 = {
authToken: authToken_3,
// send PresentationVerified receipt
authToken = _c.sent();
result_3 = {
authToken: authToken,
body: {

@@ -366,11 +359,16 @@ isVerified: false,

};
return [2 /*return*/, result_4];
return [2 /*return*/, result_3];
case 9:
areCredentialsValid = true;
credentialInvalidMessage = void 0;
_i = 0, _a = presentation.verifiableCredential;
_b.label = 10;
presentationCredentialIds = presentation.verifiableCredential.map(function (credential) { return credential.id; });
return [4 /*yield*/, checkCredentialStatuses_1.checkCredentialStatuses(authToken, presentationCredentialIds)];
case 10:
if (!(_i < _a.length)) return [3 /*break*/, 14];
credential = _a[_i];
isStatusValidResponse = _c.sent();
authToken = isStatusValidResponse.authToken;
_a = 0, _b = presentation.verifiableCredential;
_c.label = 11;
case 11:
if (!(_a < _b.length)) return [3 /*break*/, 14];
credential = _b[_a];
isExpired = isCredentialExpired_1.isCredentialExpired(credential);

@@ -382,6 +380,3 @@ if (isExpired) {

}
return [4 /*yield*/, checkCredentialStatus_1.checkCredentialStatus(authToken, credential.id)];
case 11:
isStatusValidResponse = _b.sent();
isStatusValid = isStatusValidResponse.body.status === 'valid';
isStatusValid = getCredentialStatusFromMap_1.getCredentialStatusFromMap(credential.id, isStatusValidResponse.body);
authToken = isStatusValidResponse.authToken;

@@ -393,5 +388,5 @@ if (!isStatusValid) {

}
return [4 /*yield*/, verifyCredential_1.verifyCredential(credential, authToken)];
return [4 /*yield*/, verifyCredential_1.verifyCredential(authToken, credential)];
case 12:
isVerifiedResponse = _b.sent();
isVerifiedResponse = _c.sent();
isVerified_1 = isVerifiedResponse.body;

@@ -404,13 +399,14 @@ authToken = isVerifiedResponse.authToken;

}
_b.label = 13;
_c.label = 13;
case 13:
_i++;
return [3 /*break*/, 10];
_a++;
return [3 /*break*/, 11];
case 14:
if (!!areCredentialsValid) return [3 /*break*/, 16];
return [4 /*yield*/, sendPresentationVerifiedReceipt_1.sendPresentationVerifiedReceipt(authorization, verifier, proof.verificationMethod, 'approved', false, presentation.presentationRequestId, requestUuid, credentialInvalidMessage, issuers, credentialTypes, credentialIds)];
return [4 /*yield*/, sendPresentationVerifiedReceipt_1.sendPresentationVerifiedReceipt(authToken, verifier, proof.verificationMethod, 'approved', false, presentation.presentationRequestId, requestUuid, credentialInvalidMessage, issuers, credentialTypes, credentialIds)];
case 15:
authToken_4 = _b.sent();
result_5 = {
authToken: authToken_4,
// send PresentationVerified receipt
authToken = _c.sent();
result_4 = {
authToken: authToken,
body: {

@@ -421,3 +417,3 @@ isVerified: false,

};
return [2 /*return*/, result_5];
return [2 /*return*/, result_4];
case 16:

@@ -427,3 +423,3 @@ isVerified = isPresentationVerified && areCredentialsValid;

case 17:
authToken = _b.sent();
authToken = _c.sent();
result = {

@@ -437,3 +433,3 @@ authToken: authToken,

case 18:
error_2 = _b.sent();
error_2 = _c.sent();
logger_1.default.error('Error verifying Presentation.', error_2);

@@ -440,0 +436,0 @@ throw error_2;

@@ -1,1 +0,1 @@

window.searchData = {"kinds":{"64":"Function","128":"Class","256":"Interface","512":"Constructor","1024":"Property","65536":"Type literal"},"rows":[{"id":0,"kind":64,"name":"registerIssuer","url":"modules.html#registerissuer","classes":"tsd-kind-function"},{"id":1,"kind":64,"name":"issueCredential","url":"modules.html#issuecredential","classes":"tsd-kind-function"},{"id":2,"kind":64,"name":"issueCredentials","url":"modules.html#issuecredentials","classes":"tsd-kind-function"},{"id":3,"kind":64,"name":"updateCredentialStatus","url":"modules.html#updatecredentialstatus","classes":"tsd-kind-function"},{"id":4,"kind":64,"name":"registerVerifier","url":"modules.html#registerverifier","classes":"tsd-kind-function"},{"id":5,"kind":64,"name":"sendEmail","url":"modules.html#sendemail","classes":"tsd-kind-function"},{"id":6,"kind":64,"name":"sendRequest","url":"modules.html#sendrequest","classes":"tsd-kind-function"},{"id":7,"kind":64,"name":"sendSms","url":"modules.html#sendsms","classes":"tsd-kind-function"},{"id":8,"kind":64,"name":"verifyPresentation","url":"modules.html#verifypresentation","classes":"tsd-kind-function"},{"id":9,"kind":64,"name":"checkCredentialStatus","url":"modules.html#checkcredentialstatus","classes":"tsd-kind-function"},{"id":10,"kind":64,"name":"getRequest","url":"modules.html#getrequest","classes":"tsd-kind-function"},{"id":11,"kind":64,"name":"getVersionedRequest","url":"modules.html#getversionedrequest","classes":"tsd-kind-function"},{"id":12,"kind":256,"name":"UnumDto","url":"interfaces/unumdto.html","classes":"tsd-kind-interface tsd-has-type-parameter"},{"id":13,"kind":1024,"name":"authToken","url":"interfaces/unumdto.html#authtoken","classes":"tsd-kind-property tsd-parent-kind-interface","parent":"UnumDto"},{"id":14,"kind":1024,"name":"body","url":"interfaces/unumdto.html#body","classes":"tsd-kind-property tsd-parent-kind-interface","parent":"UnumDto"},{"id":15,"kind":256,"name":"RegisteredVerifier","url":"interfaces/registeredverifier.html","classes":"tsd-kind-interface"},{"id":16,"kind":1024,"name":"keys","url":"interfaces/registeredverifier.html#keys","classes":"tsd-kind-property tsd-parent-kind-interface","parent":"RegisteredVerifier"},{"id":17,"kind":256,"name":"VerifiedStatus","url":"interfaces/verifiedstatus.html","classes":"tsd-kind-interface"},{"id":18,"kind":1024,"name":"isVerified","url":"interfaces/verifiedstatus.html#isverified","classes":"tsd-kind-property tsd-parent-kind-interface","parent":"VerifiedStatus"},{"id":19,"kind":1024,"name":"message","url":"interfaces/verifiedstatus.html#message","classes":"tsd-kind-property tsd-parent-kind-interface","parent":"VerifiedStatus"},{"id":20,"kind":256,"name":"RegisteredIssuer","url":"interfaces/registeredissuer.html","classes":"tsd-kind-interface"},{"id":21,"kind":1024,"name":"keys","url":"interfaces/registeredissuer.html#keys","classes":"tsd-kind-property tsd-parent-kind-interface","parent":"RegisteredIssuer"},{"id":22,"kind":256,"name":"DecryptedPresentation","url":"interfaces/decryptedpresentation.html","classes":"tsd-kind-interface"},{"id":23,"kind":1024,"name":"type","url":"interfaces/decryptedpresentation.html#type","classes":"tsd-kind-property tsd-parent-kind-interface","parent":"DecryptedPresentation"},{"id":24,"kind":1024,"name":"presentation","url":"interfaces/decryptedpresentation.html#presentation","classes":"tsd-kind-property tsd-parent-kind-interface","parent":"DecryptedPresentation"},{"id":25,"kind":1024,"name":"isVerified","url":"interfaces/decryptedpresentation.html#isverified","classes":"tsd-kind-property tsd-parent-kind-interface tsd-is-inherited","parent":"DecryptedPresentation"},{"id":26,"kind":1024,"name":"message","url":"interfaces/decryptedpresentation.html#message","classes":"tsd-kind-property tsd-parent-kind-interface tsd-is-inherited","parent":"DecryptedPresentation"},{"id":27,"kind":256,"name":"CredentialStatusInfo","url":"interfaces/credentialstatusinfo.html","classes":"tsd-kind-interface"},{"id":28,"kind":1024,"name":"createdAt","url":"interfaces/credentialstatusinfo.html#createdat","classes":"tsd-kind-property tsd-parent-kind-interface","parent":"CredentialStatusInfo"},{"id":29,"kind":1024,"name":"updatedAt","url":"interfaces/credentialstatusinfo.html#updatedat","classes":"tsd-kind-property tsd-parent-kind-interface","parent":"CredentialStatusInfo"},{"id":30,"kind":1024,"name":"credentialId","url":"interfaces/credentialstatusinfo.html#credentialid","classes":"tsd-kind-property tsd-parent-kind-interface","parent":"CredentialStatusInfo"},{"id":31,"kind":1024,"name":"status","url":"interfaces/credentialstatusinfo.html#status","classes":"tsd-kind-property tsd-parent-kind-interface","parent":"CredentialStatusInfo"},{"id":32,"kind":128,"name":"CustError","url":"classes/custerror.html","classes":"tsd-kind-class"},{"id":33,"kind":65536,"name":"__type","url":"classes/custerror.html#__type","classes":"tsd-kind-type-literal tsd-parent-kind-class","parent":"CustError"},{"id":34,"kind":512,"name":"constructor","url":"classes/custerror.html#constructor","classes":"tsd-kind-constructor tsd-parent-kind-class tsd-is-overwrite","parent":"CustError"},{"id":35,"kind":1024,"name":"code","url":"classes/custerror.html#code","classes":"tsd-kind-property tsd-parent-kind-class","parent":"CustError"},{"id":36,"kind":256,"name":"CredentialInfo","url":"interfaces/credentialinfo.html","classes":"tsd-kind-interface"},{"id":37,"kind":1024,"name":"credentialTypes","url":"interfaces/credentialinfo.html#credentialtypes","classes":"tsd-kind-property tsd-parent-kind-interface","parent":"CredentialInfo"},{"id":38,"kind":1024,"name":"subjectDid","url":"interfaces/credentialinfo.html#subjectdid","classes":"tsd-kind-property tsd-parent-kind-interface","parent":"CredentialInfo"},{"id":39,"kind":64,"name":"extractCredentialInfo","url":"modules.html#extractcredentialinfo","classes":"tsd-kind-function"},{"id":40,"kind":64,"name":"createProof","url":"modules.html#createproof","classes":"tsd-kind-function"},{"id":41,"kind":64,"name":"createProofPb","url":"modules.html#createproofpb","classes":"tsd-kind-function"},{"id":42,"kind":64,"name":"convertCredentialSubject","url":"modules.html#convertcredentialsubject","classes":"tsd-kind-function"}],"index":{"version":"2.3.9","fields":["name","parent"],"fieldVectors":[["name/0",[0,33.787]],["parent/0",[]],["name/1",[1,33.787]],["parent/1",[]],["name/2",[2,33.787]],["parent/2",[]],["name/3",[3,33.787]],["parent/3",[]],["name/4",[4,33.787]],["parent/4",[]],["name/5",[5,33.787]],["parent/5",[]],["name/6",[6,33.787]],["parent/6",[]],["name/7",[7,33.787]],["parent/7",[]],["name/8",[8,33.787]],["parent/8",[]],["name/9",[9,33.787]],["parent/9",[]],["name/10",[10,33.787]],["parent/10",[]],["name/11",[11,33.787]],["parent/11",[]],["name/12",[12,25.314]],["parent/12",[]],["name/13",[13,33.787]],["parent/13",[12,1.669]],["name/14",[14,33.787]],["parent/14",[12,1.669]],["name/15",[15,28.679]],["parent/15",[]],["name/16",[16,28.679]],["parent/16",[15,1.891]],["name/17",[17,25.314]],["parent/17",[]],["name/18",[18,28.679]],["parent/18",[17,1.669]],["name/19",[19,28.679]],["parent/19",[17,1.669]],["name/20",[20,28.679]],["parent/20",[]],["name/21",[16,28.679]],["parent/21",[20,1.891]],["name/22",[21,20.794]],["parent/22",[]],["name/23",[22,33.787]],["parent/23",[21,1.371]],["name/24",[23,33.787]],["parent/24",[21,1.371]],["name/25",[18,28.679]],["parent/25",[21,1.371]],["name/26",[19,28.679]],["parent/26",[21,1.371]],["name/27",[24,20.794]],["parent/27",[]],["name/28",[25,33.787]],["parent/28",[24,1.371]],["name/29",[26,33.787]],["parent/29",[24,1.371]],["name/30",[27,33.787]],["parent/30",[24,1.371]],["name/31",[28,33.787]],["parent/31",[24,1.371]],["name/32",[29,22.801]],["parent/32",[]],["name/33",[30,33.787]],["parent/33",[29,1.503]],["name/34",[31,33.787]],["parent/34",[29,1.503]],["name/35",[32,33.787]],["parent/35",[29,1.503]],["name/36",[33,25.314]],["parent/36",[]],["name/37",[34,33.787]],["parent/37",[33,1.669]],["name/38",[35,33.787]],["parent/38",[33,1.669]],["name/39",[36,33.787]],["parent/39",[]],["name/40",[37,33.787]],["parent/40",[]],["name/41",[38,33.787]],["parent/41",[]],["name/42",[39,33.787]],["parent/42",[]]],"invertedIndex":[["__type",{"_index":30,"name":{"33":{}},"parent":{}}],["authtoken",{"_index":13,"name":{"13":{}},"parent":{}}],["body",{"_index":14,"name":{"14":{}},"parent":{}}],["checkcredentialstatus",{"_index":9,"name":{"9":{}},"parent":{}}],["code",{"_index":32,"name":{"35":{}},"parent":{}}],["constructor",{"_index":31,"name":{"34":{}},"parent":{}}],["convertcredentialsubject",{"_index":39,"name":{"42":{}},"parent":{}}],["createdat",{"_index":25,"name":{"28":{}},"parent":{}}],["createproof",{"_index":37,"name":{"40":{}},"parent":{}}],["createproofpb",{"_index":38,"name":{"41":{}},"parent":{}}],["credentialid",{"_index":27,"name":{"30":{}},"parent":{}}],["credentialinfo",{"_index":33,"name":{"36":{}},"parent":{"37":{},"38":{}}}],["credentialstatusinfo",{"_index":24,"name":{"27":{}},"parent":{"28":{},"29":{},"30":{},"31":{}}}],["credentialtypes",{"_index":34,"name":{"37":{}},"parent":{}}],["custerror",{"_index":29,"name":{"32":{}},"parent":{"33":{},"34":{},"35":{}}}],["decryptedpresentation",{"_index":21,"name":{"22":{}},"parent":{"23":{},"24":{},"25":{},"26":{}}}],["extractcredentialinfo",{"_index":36,"name":{"39":{}},"parent":{}}],["getrequest",{"_index":10,"name":{"10":{}},"parent":{}}],["getversionedrequest",{"_index":11,"name":{"11":{}},"parent":{}}],["issuecredential",{"_index":1,"name":{"1":{}},"parent":{}}],["issuecredentials",{"_index":2,"name":{"2":{}},"parent":{}}],["isverified",{"_index":18,"name":{"18":{},"25":{}},"parent":{}}],["keys",{"_index":16,"name":{"16":{},"21":{}},"parent":{}}],["message",{"_index":19,"name":{"19":{},"26":{}},"parent":{}}],["presentation",{"_index":23,"name":{"24":{}},"parent":{}}],["registeredissuer",{"_index":20,"name":{"20":{}},"parent":{"21":{}}}],["registeredverifier",{"_index":15,"name":{"15":{}},"parent":{"16":{}}}],["registerissuer",{"_index":0,"name":{"0":{}},"parent":{}}],["registerverifier",{"_index":4,"name":{"4":{}},"parent":{}}],["sendemail",{"_index":5,"name":{"5":{}},"parent":{}}],["sendrequest",{"_index":6,"name":{"6":{}},"parent":{}}],["sendsms",{"_index":7,"name":{"7":{}},"parent":{}}],["status",{"_index":28,"name":{"31":{}},"parent":{}}],["subjectdid",{"_index":35,"name":{"38":{}},"parent":{}}],["type",{"_index":22,"name":{"23":{}},"parent":{}}],["unumdto",{"_index":12,"name":{"12":{}},"parent":{"13":{},"14":{}}}],["updatecredentialstatus",{"_index":3,"name":{"3":{}},"parent":{}}],["updatedat",{"_index":26,"name":{"29":{}},"parent":{}}],["verifiedstatus",{"_index":17,"name":{"17":{}},"parent":{"18":{},"19":{}}}],["verifypresentation",{"_index":8,"name":{"8":{}},"parent":{}}]],"pipeline":[]}}
window.searchData = {"kinds":{"64":"Function","128":"Class","256":"Interface","512":"Constructor","1024":"Property","65536":"Type literal"},"rows":[{"id":0,"kind":64,"name":"registerIssuer","url":"modules.html#registerissuer","classes":"tsd-kind-function"},{"id":1,"kind":64,"name":"issueCredential","url":"modules.html#issuecredential","classes":"tsd-kind-function"},{"id":2,"kind":64,"name":"issueCredentials","url":"modules.html#issuecredentials","classes":"tsd-kind-function"},{"id":3,"kind":64,"name":"updateCredentialStatus","url":"modules.html#updatecredentialstatus","classes":"tsd-kind-function"},{"id":4,"kind":64,"name":"updateCredentialStatuses","url":"modules.html#updatecredentialstatuses","classes":"tsd-kind-function"},{"id":5,"kind":64,"name":"verifySubjectCredentialRequests","url":"modules.html#verifysubjectcredentialrequests","classes":"tsd-kind-function"},{"id":6,"kind":64,"name":"revokeAllCredentials","url":"modules.html#revokeallcredentials","classes":"tsd-kind-function"},{"id":7,"kind":64,"name":"registerVerifier","url":"modules.html#registerverifier","classes":"tsd-kind-function"},{"id":8,"kind":64,"name":"sendEmail","url":"modules.html#sendemail","classes":"tsd-kind-function"},{"id":9,"kind":64,"name":"sendRequest","url":"modules.html#sendrequest","classes":"tsd-kind-function"},{"id":10,"kind":64,"name":"sendSms","url":"modules.html#sendsms","classes":"tsd-kind-function"},{"id":11,"kind":64,"name":"verifyPresentation","url":"modules.html#verifypresentation","classes":"tsd-kind-function"},{"id":12,"kind":64,"name":"checkCredentialStatuses","url":"modules.html#checkcredentialstatuses","classes":"tsd-kind-function"},{"id":13,"kind":64,"name":"getRequest","url":"modules.html#getrequest","classes":"tsd-kind-function"},{"id":14,"kind":64,"name":"getVersionedRequest","url":"modules.html#getversionedrequest","classes":"tsd-kind-function"},{"id":15,"kind":256,"name":"UnumDto","url":"interfaces/unumdto.html","classes":"tsd-kind-interface tsd-has-type-parameter"},{"id":16,"kind":1024,"name":"authToken","url":"interfaces/unumdto.html#authtoken","classes":"tsd-kind-property tsd-parent-kind-interface","parent":"UnumDto"},{"id":17,"kind":1024,"name":"body","url":"interfaces/unumdto.html#body","classes":"tsd-kind-property tsd-parent-kind-interface","parent":"UnumDto"},{"id":18,"kind":256,"name":"RegisteredVerifier","url":"interfaces/registeredverifier.html","classes":"tsd-kind-interface"},{"id":19,"kind":1024,"name":"keys","url":"interfaces/registeredverifier.html#keys","classes":"tsd-kind-property tsd-parent-kind-interface","parent":"RegisteredVerifier"},{"id":20,"kind":256,"name":"VerifiedStatus","url":"interfaces/verifiedstatus.html","classes":"tsd-kind-interface"},{"id":21,"kind":1024,"name":"isVerified","url":"interfaces/verifiedstatus.html#isverified","classes":"tsd-kind-property tsd-parent-kind-interface","parent":"VerifiedStatus"},{"id":22,"kind":1024,"name":"message","url":"interfaces/verifiedstatus.html#message","classes":"tsd-kind-property tsd-parent-kind-interface","parent":"VerifiedStatus"},{"id":23,"kind":256,"name":"RegisteredIssuer","url":"interfaces/registeredissuer.html","classes":"tsd-kind-interface"},{"id":24,"kind":1024,"name":"keys","url":"interfaces/registeredissuer.html#keys","classes":"tsd-kind-property tsd-parent-kind-interface","parent":"RegisteredIssuer"},{"id":25,"kind":256,"name":"DecryptedPresentation","url":"interfaces/decryptedpresentation.html","classes":"tsd-kind-interface"},{"id":26,"kind":1024,"name":"type","url":"interfaces/decryptedpresentation.html#type","classes":"tsd-kind-property tsd-parent-kind-interface","parent":"DecryptedPresentation"},{"id":27,"kind":1024,"name":"presentation","url":"interfaces/decryptedpresentation.html#presentation","classes":"tsd-kind-property tsd-parent-kind-interface","parent":"DecryptedPresentation"},{"id":28,"kind":1024,"name":"isVerified","url":"interfaces/decryptedpresentation.html#isverified","classes":"tsd-kind-property tsd-parent-kind-interface tsd-is-inherited","parent":"DecryptedPresentation"},{"id":29,"kind":1024,"name":"message","url":"interfaces/decryptedpresentation.html#message","classes":"tsd-kind-property tsd-parent-kind-interface tsd-is-inherited","parent":"DecryptedPresentation"},{"id":30,"kind":256,"name":"CredentialStatusInfo","url":"interfaces/credentialstatusinfo.html","classes":"tsd-kind-interface"},{"id":31,"kind":1024,"name":"createdAt","url":"interfaces/credentialstatusinfo.html#createdat","classes":"tsd-kind-property tsd-parent-kind-interface","parent":"CredentialStatusInfo"},{"id":32,"kind":1024,"name":"updatedAt","url":"interfaces/credentialstatusinfo.html#updatedat","classes":"tsd-kind-property tsd-parent-kind-interface","parent":"CredentialStatusInfo"},{"id":33,"kind":1024,"name":"credentialId","url":"interfaces/credentialstatusinfo.html#credentialid","classes":"tsd-kind-property tsd-parent-kind-interface","parent":"CredentialStatusInfo"},{"id":34,"kind":1024,"name":"status","url":"interfaces/credentialstatusinfo.html#status","classes":"tsd-kind-property tsd-parent-kind-interface","parent":"CredentialStatusInfo"},{"id":35,"kind":128,"name":"CustError","url":"classes/custerror.html","classes":"tsd-kind-class"},{"id":36,"kind":65536,"name":"__type","url":"classes/custerror.html#__type","classes":"tsd-kind-type-literal tsd-parent-kind-class","parent":"CustError"},{"id":37,"kind":512,"name":"constructor","url":"classes/custerror.html#constructor","classes":"tsd-kind-constructor tsd-parent-kind-class tsd-is-overwrite","parent":"CustError"},{"id":38,"kind":1024,"name":"code","url":"classes/custerror.html#code","classes":"tsd-kind-property tsd-parent-kind-class","parent":"CustError"},{"id":39,"kind":256,"name":"CredentialInfo","url":"interfaces/credentialinfo.html","classes":"tsd-kind-interface"},{"id":40,"kind":1024,"name":"credentialTypes","url":"interfaces/credentialinfo.html#credentialtypes","classes":"tsd-kind-property tsd-parent-kind-interface","parent":"CredentialInfo"},{"id":41,"kind":1024,"name":"subjectDid","url":"interfaces/credentialinfo.html#subjectdid","classes":"tsd-kind-property tsd-parent-kind-interface","parent":"CredentialInfo"},{"id":42,"kind":64,"name":"extractCredentialInfo","url":"modules.html#extractcredentialinfo","classes":"tsd-kind-function"},{"id":43,"kind":64,"name":"verifySignedDid","url":"modules.html#verifysigneddid","classes":"tsd-kind-function"},{"id":44,"kind":64,"name":"createProof","url":"modules.html#createproof","classes":"tsd-kind-function"},{"id":45,"kind":64,"name":"createProofPb","url":"modules.html#createproofpb","classes":"tsd-kind-function"},{"id":46,"kind":64,"name":"convertCredentialSubject","url":"modules.html#convertcredentialsubject","classes":"tsd-kind-function"}],"index":{"version":"2.3.9","fields":["name","parent"],"fieldVectors":[["name/0",[0,34.657]],["parent/0",[]],["name/1",[1,34.657]],["parent/1",[]],["name/2",[2,34.657]],["parent/2",[]],["name/3",[3,34.657]],["parent/3",[]],["name/4",[4,34.657]],["parent/4",[]],["name/5",[5,34.657]],["parent/5",[]],["name/6",[6,34.657]],["parent/6",[]],["name/7",[7,34.657]],["parent/7",[]],["name/8",[8,34.657]],["parent/8",[]],["name/9",[9,34.657]],["parent/9",[]],["name/10",[10,34.657]],["parent/10",[]],["name/11",[11,34.657]],["parent/11",[]],["name/12",[12,34.657]],["parent/12",[]],["name/13",[13,34.657]],["parent/13",[]],["name/14",[14,34.657]],["parent/14",[]],["name/15",[15,26.184]],["parent/15",[]],["name/16",[16,34.657]],["parent/16",[15,1.634]],["name/17",[17,34.657]],["parent/17",[15,1.634]],["name/18",[18,29.549]],["parent/18",[]],["name/19",[19,29.549]],["parent/19",[18,1.844]],["name/20",[20,26.184]],["parent/20",[]],["name/21",[21,29.549]],["parent/21",[20,1.634]],["name/22",[22,29.549]],["parent/22",[20,1.634]],["name/23",[23,29.549]],["parent/23",[]],["name/24",[19,29.549]],["parent/24",[23,1.844]],["name/25",[24,21.665]],["parent/25",[]],["name/26",[25,34.657]],["parent/26",[24,1.352]],["name/27",[26,34.657]],["parent/27",[24,1.352]],["name/28",[21,29.549]],["parent/28",[24,1.352]],["name/29",[22,29.549]],["parent/29",[24,1.352]],["name/30",[27,21.665]],["parent/30",[]],["name/31",[28,34.657]],["parent/31",[27,1.352]],["name/32",[29,34.657]],["parent/32",[27,1.352]],["name/33",[30,34.657]],["parent/33",[27,1.352]],["name/34",[31,34.657]],["parent/34",[27,1.352]],["name/35",[32,23.671]],["parent/35",[]],["name/36",[33,34.657]],["parent/36",[32,1.477]],["name/37",[34,34.657]],["parent/37",[32,1.477]],["name/38",[35,34.657]],["parent/38",[32,1.477]],["name/39",[36,26.184]],["parent/39",[]],["name/40",[37,34.657]],["parent/40",[36,1.634]],["name/41",[38,34.657]],["parent/41",[36,1.634]],["name/42",[39,34.657]],["parent/42",[]],["name/43",[40,34.657]],["parent/43",[]],["name/44",[41,34.657]],["parent/44",[]],["name/45",[42,34.657]],["parent/45",[]],["name/46",[43,34.657]],["parent/46",[]]],"invertedIndex":[["__type",{"_index":33,"name":{"36":{}},"parent":{}}],["authtoken",{"_index":16,"name":{"16":{}},"parent":{}}],["body",{"_index":17,"name":{"17":{}},"parent":{}}],["checkcredentialstatuses",{"_index":12,"name":{"12":{}},"parent":{}}],["code",{"_index":35,"name":{"38":{}},"parent":{}}],["constructor",{"_index":34,"name":{"37":{}},"parent":{}}],["convertcredentialsubject",{"_index":43,"name":{"46":{}},"parent":{}}],["createdat",{"_index":28,"name":{"31":{}},"parent":{}}],["createproof",{"_index":41,"name":{"44":{}},"parent":{}}],["createproofpb",{"_index":42,"name":{"45":{}},"parent":{}}],["credentialid",{"_index":30,"name":{"33":{}},"parent":{}}],["credentialinfo",{"_index":36,"name":{"39":{}},"parent":{"40":{},"41":{}}}],["credentialstatusinfo",{"_index":27,"name":{"30":{}},"parent":{"31":{},"32":{},"33":{},"34":{}}}],["credentialtypes",{"_index":37,"name":{"40":{}},"parent":{}}],["custerror",{"_index":32,"name":{"35":{}},"parent":{"36":{},"37":{},"38":{}}}],["decryptedpresentation",{"_index":24,"name":{"25":{}},"parent":{"26":{},"27":{},"28":{},"29":{}}}],["extractcredentialinfo",{"_index":39,"name":{"42":{}},"parent":{}}],["getrequest",{"_index":13,"name":{"13":{}},"parent":{}}],["getversionedrequest",{"_index":14,"name":{"14":{}},"parent":{}}],["issuecredential",{"_index":1,"name":{"1":{}},"parent":{}}],["issuecredentials",{"_index":2,"name":{"2":{}},"parent":{}}],["isverified",{"_index":21,"name":{"21":{},"28":{}},"parent":{}}],["keys",{"_index":19,"name":{"19":{},"24":{}},"parent":{}}],["message",{"_index":22,"name":{"22":{},"29":{}},"parent":{}}],["presentation",{"_index":26,"name":{"27":{}},"parent":{}}],["registeredissuer",{"_index":23,"name":{"23":{}},"parent":{"24":{}}}],["registeredverifier",{"_index":18,"name":{"18":{}},"parent":{"19":{}}}],["registerissuer",{"_index":0,"name":{"0":{}},"parent":{}}],["registerverifier",{"_index":7,"name":{"7":{}},"parent":{}}],["revokeallcredentials",{"_index":6,"name":{"6":{}},"parent":{}}],["sendemail",{"_index":8,"name":{"8":{}},"parent":{}}],["sendrequest",{"_index":9,"name":{"9":{}},"parent":{}}],["sendsms",{"_index":10,"name":{"10":{}},"parent":{}}],["status",{"_index":31,"name":{"34":{}},"parent":{}}],["subjectdid",{"_index":38,"name":{"41":{}},"parent":{}}],["type",{"_index":25,"name":{"26":{}},"parent":{}}],["unumdto",{"_index":15,"name":{"15":{}},"parent":{"16":{},"17":{}}}],["updatecredentialstatus",{"_index":3,"name":{"3":{}},"parent":{}}],["updatecredentialstatuses",{"_index":4,"name":{"4":{}},"parent":{}}],["updatedat",{"_index":29,"name":{"32":{}},"parent":{}}],["verifiedstatus",{"_index":20,"name":{"20":{}},"parent":{"21":{},"22":{}}}],["verifypresentation",{"_index":11,"name":{"11":{}},"parent":{}}],["verifysigneddid",{"_index":40,"name":{"43":{}},"parent":{}}],["verifysubjectcredentialrequests",{"_index":5,"name":{"5":{}},"parent":{}}]],"pipeline":[]}}
{
"name": "@unumid/server-sdk",
"version": "3.18.1",
"version": "3.19.0",
"main": "build/index.js",

@@ -47,3 +47,3 @@ "repository": "git@github.com:UnumID/Server-SDK-TypeScript.git",

"@unumid/library-crypto": "https://github.com/UnumID/Library-Crypto-TypeScript.git#1.7.0",
"@unumid/types": "https://github.com/UnumID/types.git#3.17.1",
"@unumid/types": "https://github.com/UnumID/types.git#3.34.0",
"@unumid/types-v2": "npm:@unumid/types@2.1.3",

@@ -50,0 +50,0 @@ "dotenv": "^8.2.0",

# Unum ID Typescript Server-SDK
This SDK combines the functionality of an [**Issuer**](https://docs.unum.id/terminology#issuer) and [**Verifier**](https://docs.unum.id/terminology#verifier) entities to work with UnumID's SaaS. For necessary account creation and API keys please email admin@unum.id.
This SDK combines the functionality of an [**Issuer**](https://docs.unumid.co/terminology#issuer) and [**Verifier**](https://docs.unumid.co/terminology#verifier) entities to work with UnumID's SaaS. For necessary account creation and API keys please email admin@unumid.co.
## Documentation
High level technical documentation can be found [here](https://docs.unum.id/server-sdk) which is served via [Docusaurus](https://github.com/UnumID/UnumID.github.io). More detailed generated from source documentation can be found [here](https://docs.unum.id/Server-SDK-Typescript/index.html) which is served via repo specific Github pages via the /docs folder of the main branch.
High level technical documentation can be found [here](https://docs.unumid.co/server-sdk) which is served via [Docusaurus](https://github.com/UnumID/UnumID.github.io). More detailed generated from source documentation can be found [here](https://docs.unumid.co/Server-SDK-Typescript/index.html) which is served via repo specific Github pages via the /docs folder of the main branch.
## Distribution

@@ -19,14 +19,22 @@

## Logging
Logs level defaults to Info. One can set to debug for more information via the environment variable LOG_LEVEL, i.e. LOG_LEVEL=debug. We are using standard NPM log levels. More details on the various log levels [here](https://github.com/winstonjs/winston#logging-levels).
## Environment Variables
The following environment variables are required to be set to use the SDK properly.
- `UNUM_ENV`
- `LOG_LEVEL`
- `DEBUG`
### UNUM_ENV
One needs to provide the SDK the with an environment variable to denote its run time environment, i.e. `production`. For the Typescript SDK this done via the `UNUM_ENV` environment variable. The three relevant values are: `production`, `sandbox`, `dev`. You need to use one of these exactly in order for the SDK to communicate with Unum ID's SaaS. The default value if nothing is supplied is `sandbox`.
The logs default to stdout so can be aggregated using any log provider you would like from disk.
### LOG_LEVEL
The default logs level is `info`. You can change this to `debug` for more information (set the environment variable `LOG_LEVEL = debug`). The logs default to `stdout`, so you can easily aggregate them from disk using the log provider of your choice.
## Debugging
The `NODE_ENV` environment variable defaults to `sandbox`. However while debugging one can use the `debug` environment setting. This enables logging of decrypted presentations at the `debug` level. Due to presentations containing sensitive information it is not advised to use in a production environment.
We use standard NPM log levels. Learn more about these [here](https://github.com/winstonjs/winston#logging-levels).
### DEBUG
The `DEBUG` environment variable defaults to `false`. Setting to `true` enables logging of decrypted presentations at the `debug` level. Due to presentations containing potentially sensitive information it is *not* advised to use in a production environment. Note: the `LOG_LEVEL` envirnoment variable also needs to be set to at least `debug` level in order to be visible.
In order to generate the Typedoc documentation from the source code run the `createTypedocs.sh` script.
## Versioning
Information regarding the suggested versioning strategy can be found [here](https://docs.unum.id/deployment-overview#versioning-strategy).
Information regarding the suggested versioning strategy can be found [here](https://docs.unumid.co/deployment-overview#versioning-strategy).
Breaking versions of this SDK will be denoted as such with an incremented major version. However all versions of the SDK will be fully backwards compatible with the other Unum ID SDKs. If there is a need to referencing an older version of the SDK within your applications for other applications specific backwards compatibility we recommend this syntax for simplicity:

@@ -65,3 +73,3 @@ `@unumid/server-sdk-v2": "npm:@unumid/server-sdk@2.1.4`.

Response Body: [**RegisteredIssuer**](https://docs.unum.id/Server-SDK-Typescript/interfaces/registeredissuer.html)
Response Body: [**RegisteredIssuer**](https://docs.unumid.co/Server-SDK-Typescript/interfaces/registeredissuer.html)
```typescript title="RegisteredIssuer"

@@ -81,4 +89,4 @@ {

"encryption": {
"privateKey": string, // you use this to encrypt credentials you send to subjects
"publicKey": string, // subjects use this to decrypt credentials they receive from you
"privateKey": string, // not used
"publicKey": string, // not used; but part of the issuer did doc
}

@@ -89,3 +97,3 @@ }

### issueCredential
### issueCredentials
Issue a credential to a Subject, also known as a User.

@@ -111,5 +119,5 @@

Response Body: [**Credential**](https://docs.unum.id/Server-SDK-Typescript/interfaces/credential.html)
Response Body: [**Credential**](https://docs.unumid.co/Server-SDK-Typescript/interfaces/credential.html)
```typescript title="Credential"
{
{[
"@context": ["https://www.w3.org/2018/credentials/v1"], // for conformance with W3C Verifiable Credential spec

@@ -130,3 +138,3 @@ "credentialStatus": {

"proof": Proof // cryptographic proof created by signing credential with your issuer signing private key. Can be used to verify credential.
}
]}
```

@@ -137,3 +145,3 @@

You need to provide the credential `id` (created when you issued the credential) and a [CredentialStatusOptions](https://docs.unum.id/types/modules.html#credentialstatusoptions) `status`. Currently the only valid status are: verified and revoked.
You need to provide the credential `id` (created when you issued the credential) and a [CredentialStatusOptions](https://docs.unumid.co/types/modules.html#credentialstatusoptions) `status`. Currently the only valid status are: verified and revoked.

@@ -157,2 +165,60 @@ ```typescript

### revokeAllCredentials
Revoke all issued credentials to a particular DID.
You need to provide your issuer's `did` and `signingPrivateKey` also the target `subjectDid`. Only credentials issued by the associated issuer are revoked from the subject. The signing private key is necessary for the request signature to be created within the sdk. The signature is necessary to be verified by the SaaS prior to revoking all the credentials.
Parameters
```typescript
{
"issuerDid": string // did of the issuer of credential you would like to revoke
"signingPrivateKey": string // issuer's signing private key
"subjectDid": string // did of target subject whom to revoke all the credentials issued by the issuer
}
```
Response Body: **Empty**. If unsuccessful and exception will be thrown.
```typescript
{}
```
### verifySubjectCredentialRequest
Verify a Subject's request for credentials.
You need to provide the your issuer's `did` along with the SubjectCredentialRequest array from your `/credentialRequest` [endpoint](https://gist.github.com/UnumIDAdmin/d76d9fe46e459e529d7f7b6f9319a0b6).
Each request is cryptographically signed by the subject's private key. This function verifies the signatures are valid. Furthermore, it validates that all requests are from the same subject and that requested Issuer requirements are met. After which, your application code will need to evaluate wether it can issue the requested credentials. An example implementation can be found [here](https://github.com/UnumID/demo-issuer-server/blob/main/src/services/api/credentialRequest/credentialRequest.class.ts).
The main use case of this to allow bootstrapping users that just installed the Unum ID Wallet with credentials necessary to use across the network, i.e for instant sign ups with a partner.
_Note_: Despite this having "verify" in its name, this function only serves Issuers in determining whether a subject's request for credentials is valid. It is up to you application logic to determine whether you have the data relating to the the subject to issue the requested credentials.
```typescript
export type SubjectCredentialRequest = {
type: string; // the string matching the desire credential type
issuers: string[]; //list of acceptable issuer DIDs that have issued the credential
required: boolean; // to denote wether this particular credential is required. Defaults behavior resolves this to true.
proof: Proof; // proof signed by the subject
}
```
Parameters
```typescript
{
"authorization": string // auth token
"issuerDid": string // the did of your issuer
"credentialRequests: SubjectCredentialRequest[] // array of credential requests signed by the Subject
}
```
Response Body: [**SubjectCredentialRequestVerifiedStatus**].
```typescript
export interface SubjectCredentialRequestVerifiedStatus {
subjectDid: string; // returns the subject DID that made and signed all the requests
isVerified: boolean; // returns true if all requests are verified and validation requirements are met
message?: string; // (optional) only populated iff isVerified is false
}
```
## Verifier

@@ -173,3 +239,3 @@ The Verifier functionality is used by a customer acting as a verifier. Most importantly, it allows customers to send PresentationRequests to the UnumID mobile SDK and to verify the encrypted Presentation responses.

Response body: [**RegisteredVerifier**](https://docs.unum.id/Server-SDK-Typescript/interfaces/registeredverifier.html)
Response body: [**RegisteredVerifier**](https://docs.unumid.co/Server-SDK-Typescript/interfaces/registeredverifier.html)
```typescript title="RegisteredVerifier"

@@ -202,3 +268,3 @@ {

To request credentials, you need to populate one or more [CredentialRequest](https://docs.unum.id/types/interfaces/credentialrequest.html) objects, defined in the UnumID generic [types](https://github.com/UnumID/types/blob/00ba819e661e2856ba9909923ac6f083b9a15e85/index.d.ts#L113-L117) project and shown below.
To request credentials, you need to populate one or more [CredentialRequest](https://docs.unumid.co/types/interfaces/credentialrequest.html) objects, defined in the UnumID generic [types](https://github.com/UnumID/types/blob/00ba819e661e2856ba9909923ac6f083b9a15e85/index.d.ts#L113-L117) project and shown below.

@@ -224,3 +290,3 @@ ```typescript

Response Body: [**PresentationRequestPostDto**](https://docs.unum.id/types/interfaces/presentationrequestpostdto.html)
Response Body: [**PresentationRequestPostDto**](https://docs.unumid.co/types/interfaces/presentationrequestpostdto.html)
```typescript title="PresentationRequestPostDto"

@@ -264,3 +330,3 @@ {

You need to be able to receive presentations from users and pass them to this function. To do this, you need to create a `/presentation` endpoint that conforms to our [OpenAPI specification](https://unumid.postman.co/workspace/Unum-ID-Team-Workspace~48b1f312-a6e6-4bcc-86a0-aa4bc37df9b4/api/09ad0ccd-c614-4d54-a1b4-ff9ae85b8449?version=c217a461-fc05-4476-a792-6c9163f2a198&tab=define). The Unum ID cloud sends encrypted presentations to this endpoint, which should pass those presentations to the `verifyPresentation` function to be decrypted and verified.
You need to be able to receive presentations from users and pass them to this function. To do this, you need to create a `/presentation` endpoint that conforms to our [OpenAPI specification](https://gist.github.com/UnumIDAdmin/2bffdf092594196beba48ce7738b60fa). The Unum ID cloud sends encrypted presentations to this endpoint, which should pass those presentations to the `verifyPresentation` function to be decrypted and verified.

@@ -289,3 +355,3 @@ You need to provide:

Response Body: [**DecryptedPresentation**](https://docs.unum.id/Server-SDK-Typescript/interfaces/decryptedpresentation.html)
Response Body: [**DecryptedPresentation**](https://docs.unumid.co/Server-SDK-Typescript/interfaces/decryptedpresentation.html)
```typescript title="DecryptedPresentation"

@@ -324,3 +390,3 @@ {

### sendEmail
Use to send a deep link to a user by email. A templated message will be delivered from no-reply@unum.id. You can of course use your own email sending service if you prefer.
Use to send a deep link to a user by email. A templated message will be delivered from no-reply@unumid.co. You can of course use your own email sending service if you prefer.

@@ -348,6 +414,6 @@ To request (a presentation of) credentials from a user, you first create the request object and receive a deep link that references it. The user need to receive this deep link, which will open the correct app on their phone and prompt them to share the credentials. Email is one convenient channel, though keep in mind that the user will need to click the link from their phone for the deep link to work.

### checkCredentialStatus
Used to check the status of a credential.
### checkCredentialStatuses
Used to check the status of individual credentials.
The `status` attribute of the response is of type [CredentialStatusOptions](https://docs.unum.id/types/modules.html#credentialstatusoptions). Currently the only valid status are: verified and revoked.
The `status` attribute of the response's [CredentialStatusInfo](https://docs.unumid.co/types/interfaces/credentialstatusinfo.html) is of type [CredentialStatusOptions](https://docs.unumid.co/types/modules.html#credentialstatusoptions). Currently the only valid status are: verified and revoked.

@@ -358,17 +424,23 @@ ```typescript

```typescript
export type CredentialStatusInfo {
"createdAt": Date; // the time the credential was recorded as created in the UnumID SaaS db
"updatedAt": Date; // the time the credential was recorded as updated in the UnumID SaaS db
"credentialId": string; // the did (aka id) of the credential this status is in regard to
"status": CredentialStatusOptions; // a string literal type that currently only consists of 'valid' and 'revoked'
}
```
Parameters
```typescript
{
"credentialId": string, // the id of the credential in question
"credentialIds": string[], // the array of ids of the credentials in question
}
```
Response Body: **CredentialStatusInfo**. If unsuccessful and exception will be thrown.
Response Body: **CredentialIdToStatusMap**. If unsuccessful and exception will be thrown.
```typescript
{
"createdAt": Date; // the time the credential was recorded as created in the UnumID SaaS db
"updatedAt": Date; // the time the credential was recorded as updated in the UnumID SaaS db
"credentialId": string; // the did (aka id) of the credential this status is in regard to
"status": CredentialStatusOptions; // a string literal type that currently only consists of 'valid' and 'revoked'
[credentialId: string]: CredentialStatusInfo;
}
```

@@ -9,8 +9,31 @@ /*

/**
* Get saas url based on the provide UNUM_ENV env var.
* @param env
*/
function getSaasUrl (env: string) {
switch (env) {
case 'local':
return 'http://localhost:3030/';
case 'dev':
return 'https://api.dev-unum.id/';
case 'sandbox':
return 'https://api.sandbox-unum.id/';
case 'production':
return 'https://api.unum.id/';
default:
return 'http://localhost:3030/';
}
}
// defaults to sandbox if not provided
const env = process.env.UNUM_ENV || 'sandbox';
const configData = {
nodeEnv: process.env.NODE_ENV || 'sandbox',
SaaSUrl: process.env.SAAS_URL || 'https://api.sandbox-unumid.org/',
logLevel: process.env.LOG_LEVEL || 'debug' // Winston defaults to info if not set
nodeEnv: env,
SaaSUrl: process.env.UNUM_SAAS_URL || getSaasUrl(env),
debug: process.env.DEBUG === 'true' || false,
logLevel: process.env.LOG_LEVEL || 'info' // Winston defaults to info if not set however being explicit here
};
export { configData };

@@ -12,3 +12,2 @@ import { registerVerifier } from './verifier/registerVerifier';

import { CredentialSubject, Presentation, Proof, Credential } from '@unumid/types';
import { checkCredentialStatus } from './verifier/checkCredentialStatus';
import { CustError } from './utils/error';

@@ -19,2 +18,7 @@ import { createProof, createProofPb } from './utils/createProof';

import { getVersionedRequest } from './verifier/getVersionedRequest';
import { verifySubjectCredentialRequests } from './issuer/verifySubjectCredentialRequests';
import { verifySignedDid } from './utils/verifyDidDocument';
import { revokeAllCredentials } from './issuer/revokeAllCredentials';
import { updateCredentialStatuses } from './issuer/updateCredentialStatuses';
import { checkCredentialStatuses } from './verifier/checkCredentialStatuses';

@@ -27,2 +31,5 @@ export {

updateCredentialStatus,
updateCredentialStatuses,
verifySubjectCredentialRequests,
revokeAllCredentials,
// Verifier Functions

@@ -34,3 +41,3 @@ registerVerifier,

verifyPresentation,
checkCredentialStatus,
checkCredentialStatuses,
getRequest,

@@ -54,2 +61,3 @@ getVersionedRequest,

extractCredentialInfo,
verifySignedDid,
createProof,

@@ -56,0 +64,0 @@ createProofPb,

@@ -234,3 +234,5 @@ import { configData } from '../config';

// Get target Subject's DID document public keys for encrypting all the credentials issued.
const publicKeyInfos = await getDidDocPublicKeys(authorization, subjectDid);
const publicKeyInfoResponse: UnumDto<PublicKeyInfo[]> = await getDidDocPublicKeys(authorization, subjectDid, 'RSA');
const publicKeyInfos = publicKeyInfoResponse.body;
authorization = publicKeyInfoResponse.authToken;

@@ -294,4 +296,7 @@ // loop through the types and credential data lists inputted to create CredentialPairs of each supported version for each

const subjectDid = credentialSubject.id;
const publicKeyInfos = await getDidDocPublicKeys(authorization, subjectDid);
const publicKeyInfoResponse: UnumDto<PublicKeyInfo[]> = await getDidDocPublicKeys(authorization, subjectDid, 'RSA');
const publicKeyInfos = publicKeyInfoResponse.body;
authorization = publicKeyInfoResponse.authToken;
return issueCredentialHelperDeprecated(authorization, type, issuer, credentialSubject, signingPrivateKey, publicKeyInfos, expirationDate);

@@ -298,0 +303,0 @@ } catch (error) {

@@ -5,3 +5,3 @@ import { configData } from '../config';

import logger from '../logger';
import { DidKeyType, IssuerOptions, JSONObj, KeyPair, PublicKeyInfo } from '@unumid/types';
import { DidKeyType, IssuerOptions, JSONObj, KeyPair, PublicKeyInfo, VersionInfo } from '@unumid/types';
import { getUUID } from '../utils/helpers';

@@ -11,2 +11,3 @@ import { CustError } from '../utils/error';

import { handleAuthTokenHeader, makeNetworkRequest } from '../utils/networkRequestHelper';
import { validateVersionInfo } from '../utils/validateVersionInfo';

@@ -47,3 +48,3 @@ /**

*/
const validateInParams = (customerUuid: string, apiKey: string) => {
const validateInParams = (customerUuid: string, apiKey: string, url: string, versionInfo: VersionInfo[]) => {
if (!customerUuid) {

@@ -56,2 +57,8 @@ throw new CustError(400, 'Invalid Issuer: customerUuid is required.');

}
if (!url) {
throw new CustError(400, 'Invalid Issuer: url is required.');
}
validateVersionInfo(versionInfo);
};

@@ -64,5 +71,5 @@

*/
export const registerIssuer = async (customerUuid: string, apiKey: string): Promise<UnumDto<RegisteredIssuer>> => {
export const registerIssuer = async (customerUuid: string, apiKey: string, url:string, versionInfo: VersionInfo[] = [{ target: { version: '1.0.0' }, sdkVersion: '3.0.0' }]): Promise<UnumDto<RegisteredIssuer>> => {
try {
validateInParams(customerUuid, apiKey);
validateInParams(customerUuid, apiKey, url, versionInfo);

@@ -72,4 +79,7 @@ const kpSet: KeyPairSet = await createKeyPairSet();

customerUuid,
publicKeyInfo: constructKeyObjs(kpSet)
publicKeyInfo: constructKeyObjs(kpSet),
url,
versionInfo
};
const restData: RESTData = {

@@ -98,3 +108,5 @@ method: 'POST',

keys: kpSet,
apiKey
apiKey,
url: restResp.body.url,
versionInfo: restResp.body.versionInfo
}

@@ -101,0 +113,0 @@ };

@@ -42,3 +42,3 @@ import { configData } from '../config';

baseUrl: configData.SaaSUrl,
endPoint: 'credentialStatus/' + credentialId,
endPoint: 'credentialStatus/?credentialId=' + credentialId,
header: { Authorization: authorization },

@@ -53,3 +53,3 @@ data: { status }

const revokedCredential: UnumDto<undefined> = {
const result: UnumDto<undefined> = {
authToken,

@@ -59,3 +59,3 @@ body: undefined

return revokedCredential;
return result;
} catch (error) {

@@ -62,0 +62,0 @@ logger.error(`Error revoking a credential with UnumID SaaS. ${error}`);

@@ -37,5 +37,6 @@ import { createLogger, format, transports } from 'winston';

// Printing this info here instead of in ./config to prevent a circular dependency.
logger.debug(`Server SDK SaaS URL: ${configData.SaaSUrl}`);
logger.debug(`Server SDK Log Level: ${configData.logLevel}`);
logger.debug(`Server SDK v3 SaaS URL: ${configData.SaaSUrl}`);
logger.debug(`Server SDK v3 Log Level: ${configData.logLevel}`);
logger.debug(`Server SDK v3 Debug: ${configData.debug}`);
export default logger;

@@ -136,3 +136,3 @@ import { CredentialStatusOptions, Issuer, CredentialSubject, Verifier, CredentialRequest, Presentation, KeyPair, PublicKeyInfo, JSONObj, PresentationPb, CredentialRequestPb } from '@unumid/types';

*/
export interface VerifiedStatus {
export interface VerifiedStatus{
isVerified: boolean;

@@ -142,2 +142,22 @@ message?: string;

// /**
// * A type to convey why a presentation can not be verified.
// * While this would normally be served by throwing an exception we want to pass back the auth token returned
// * by calls to the SaaS via the UnumDto type.
// */
// export interface VerifiedStatus<T = any> {
// isVerified: boolean;
// message?: string;
// metadata?: T;
// }
// /**
// * Interface to encapsulate the subject did attributed to a verifySubjectCredentialRequests call.
// * This is useful for customers to use as reference to then issues the credentials.
// * Note: the verification method ensures the same subject did is used for all requests.
// */
// export interface SubjectCredentialRequestsVerifiedMetadata {
// subjectDid: string
// }
/**

@@ -144,0 +164,0 @@ * A type came about need to convey that a credential presentation can not be verified.

@@ -5,4 +5,4 @@ import { CredentialSubject, DidDocument, DidKeyType, PublicKeyInfo, Credential, CredentialPb } from '@unumid/types';

import logger from '../logger';
import { makeNetworkRequest } from './networkRequestHelper';
import { RESTData, RESTResponse } from '../types';
import { handleAuthTokenHeader, makeNetworkRequest } from './networkRequestHelper';
import { RESTData, RESTResponse, UnumDto } from '../types';
import { convertCredentialSubject } from './convertCredentialSubject';

@@ -17,3 +17,3 @@ import { configData } from '../config';

*/
export const getDIDDoc = async (baseUrl: string, authorization: string, did: string): Promise<RESTResponse<DidDocument> | CustError> => {
export const getDIDDoc = async (baseUrl: string, authorization: string, did: string): Promise<RESTResponse<DidDocument | PublicKeyInfo> | CustError> => {
try {

@@ -23,3 +23,3 @@ const restData: RESTData = {

baseUrl: baseUrl,
endPoint: 'didDocument/' + did,
endPoint: 'didDocument/' + encodeURIComponent(did),
header: { Authorization: authorization }

@@ -34,3 +34,3 @@ };

logger.error(`Error getting did document ${did} from ${baseUrl}`, error);
return (error);
throw error;
}

@@ -40,13 +40,19 @@ };

/**
* Helper to get a key from a Did document.
* Note: Per convention, Did documents have secp256r1 keys for signing / verification and only holder DID Documents have RSA keys.
* Helper to return the keys in the DID document which corresponds to the type specified.
* Note: the can be multiple keys of same type on the same DID document.
* @param didDocument DiDDocument
* @param type DidKeyType
*/
export const getKeyFromDIDDoc = (didDocument: DidDocument, type: DidKeyType): PublicKeyInfo[] => {
// return the key in the DID document which corresponds to the type specified.
return didDocument.publicKey.filter(publicKeyInfo => publicKeyInfo.type === type);
export const getKeysFromDIDDoc = (didDocument: DidDocument, type: DidKeyType): PublicKeyInfo[] => {
const publicKeyInfos = didDocument.publicKey.filter(publicKeyInfo => publicKeyInfo.type === type);
if (publicKeyInfos.length === 0) {
logger.error(`DidDoc ${didDocument.id} has no ${type} public keys`);
throw new CustError(500, `DidDoc ${didDocument.id} has no ${type} public keys`);
}
return publicKeyInfos;
};
export const getDidDocPublicKeys = async (authorization: string, subjectDid: string): Promise<PublicKeyInfo[]> => {
export const getDidDocPublicKeys = async (authorization: string, subjectDid: string, type: DidKeyType): Promise<UnumDto<PublicKeyInfo[]>> => {
// resolve the subject's DID

@@ -56,2 +62,3 @@ const didDocResponse = await getDIDDoc(configData.SaaSUrl, authorization, subjectDid);

logger.debug(`DidDoc repsonse: ${didDocResponse}`);
if (didDocResponse instanceof Error) {

@@ -61,10 +68,32 @@ throw didDocResponse;

// get subject's public key info from its DID document
const publicKeyInfos = getKeyFromDIDDoc(didDocResponse.body, 'RSA');
// const did = subjectDid.split('#')[0];
const didKeyId = subjectDid.split('#')[1];
if (publicKeyInfos.length === 0) {
throw new CustError(404, 'Public key not found for the DID');
let publicKeyInfoList: PublicKeyInfo[];
if (didKeyId) {
/**
* If making a request to the Did Document service with a did and did fragment, only a single PublicKeyInfo object is returned.
* Putting in array for uniform handling with the case no fragment is included, in which case all the matching keys will need to be tried until one works.
*/
publicKeyInfoList = [await didDocResponse.body as PublicKeyInfo];
} else {
const didDoc = await didDocResponse.body as DidDocument;
// get subject's encryption public key info from its DID document
publicKeyInfoList = getKeysFromDIDDoc(didDoc, type);
}
return publicKeyInfos;
// // get subject's public key info from its DID document
// const publicKeyInfos = getKeysFromDIDDoc(didDocResponse.body, 'RSA');
if (publicKeyInfoList.length === 0) {
throw new CustError(404, `${type} public keys not found for the DID ${subjectDid}`);
}
const authToken: string = handleAuthTokenHeader(didDocResponse, authorization);
return {
authToken,
body: publicKeyInfoList
};
};
import { JSONObj, PresentationRequestDto, PresentationRequestDtoPb, WithVersion, PresentationRequestRepoDto } from '@unumid/types';
import { isDate, isString } from 'lodash';
import { configData } from '../config';

@@ -38,2 +39,3 @@ import logger from '../logger';

export function extractPresentationRequest (presentationRequestResponse: PresentationRequestRepoDto): PresentationRequestDto {
// export function extractPresentationRequest (presentationRequestDto: PresentationRequestDto): PresentationRequestDto {
try {

@@ -43,13 +45,3 @@ const presentationRequestDto = presentationRequestResponse.presentationRequests['3.0.0'];

// need to convert the times to Date objects for proto handling
const result = {
...presentationRequestDto,
presentationRequest: {
...presentationRequestDto.presentationRequest,
createdAt: presentationRequestDto.presentationRequest.createdAt ? new Date(presentationRequestDto.presentationRequest.createdAt) : undefined as any as Date, // Despite this ugliness, rather check for presence and handle the undefined directly while not dealing with a whole new type
updatedAt: presentationRequestDto.presentationRequest.updatedAt ? new Date(presentationRequestDto.presentationRequest.updatedAt) : undefined as any as Date,
expiresAt: presentationRequestDto.presentationRequest.expiresAt ? new Date(presentationRequestDto.presentationRequest.expiresAt) : undefined as any as Date
}
};
return result;
return handleConvertingPresentationRequestDateAttributes(presentationRequestDto);
} catch (e) {

@@ -59,1 +51,42 @@ throw new CustError(500, `Error handling presentation request from Saas: Error ${e}`);

}
/**
* Helper to handle converting the stringified date attributes to real Date objects so the proto serializer doesn't complain when going into a byte array for the signature check.
* @param presentationRequestDto
* @returns
*/
export function handleConvertingPresentationRequestDateAttributes (presentationRequestDto: PresentationRequestDto): PresentationRequestDto {
const result = {
...presentationRequestDto,
presentationRequest: {
...presentationRequestDto.presentationRequest,
createdAt: handleAttributeDateType(presentationRequestDto.presentationRequest.createdAt) as Date, // Despite this ugliness, rather check for presence and handle the undefined directly while not dealing with a whole new type
updatedAt: handleAttributeDateType(presentationRequestDto.presentationRequest.updatedAt) as Date,
expiresAt: handleAttributeDateType(presentationRequestDto.presentationRequest.expiresAt) as Date
}
};
return result;
}
/**
* Helper to make the date attribute handling a little easier to follow than a complicate ternary.
* @param input
* @returns
*/
function handleAttributeDateType (input: any): Date | undefined {
if (!input) {
return undefined;
}
if (isDate(input)) {
return input;
}
if (isString(input)) {
return new Date(input);
}
logger.error('PresentationRequest date attribute value is not a string, undefined or Date. This should never happen.');
return undefined;
}

@@ -9,2 +9,3 @@ import { configData } from '../config';

import { makeNetworkRequest, handleAuthTokenHeader } from '../utils/networkRequestHelper';
import { validateVersionInfo } from '../utils/validateVersionInfo';

@@ -45,3 +46,3 @@ /**

*/
const validateInParams = (customerUuid: string, url: string, apiKey: string): void => {
const validateInParams = (customerUuid: string, url: string, apiKey: string, versionInfo: VersionInfo[]): void => {
if (!customerUuid) {

@@ -58,2 +59,4 @@ throw new CustError(400, 'Invalid Verifier Options: customerUuid is required.');

}
validateVersionInfo(versionInfo);
};

@@ -68,5 +71,5 @@

*/
export const registerVerifier = async (customerUuid: string, url: string, apiKey: string, versionInfo: VersionInfo[] = [{ target: { version: '1.0.0' }, sdkVersion: '2.0.0' }]): Promise<UnumDto<RegisteredVerifier>> => {
export const registerVerifier = async (customerUuid: string, url: string, apiKey: string, versionInfo: VersionInfo[] = [{ target: { version: '1.0.0' }, sdkVersion: '3.0.0' }]): Promise<UnumDto<RegisteredVerifier>> => {
try {
validateInParams(customerUuid, url, apiKey);
validateInParams(customerUuid, url, apiKey, versionInfo);

@@ -73,0 +76,0 @@ const kpSet: KeyPairSet = await createKeyPairSet();

@@ -5,3 +5,3 @@ import { configData } from '../config';

import { PresentationRequestPostDto as PresentationRequestPostDtoDeprecatedV2, UnsignedPresentationRequest as UnsignedPresentationRequestDeprecatedV2, SignedPresentationRequest as SignedPresentationRequestDeprecatedV2, Proof } from '@unumid/types-v2';
import { CredentialRequest, PresentationRequestPostDto, UnsignedPresentationRequestPb, PresentationRequestPb, ProofPb, SignedPresentationRequest, CredentialRequestPb, JSONObj } from '@unumid/types';
import { CredentialRequest, PresentationRequestPostDto, UnsignedPresentationRequestPb, PresentationRequestPb, ProofPb, SignedPresentationRequest, CredentialRequestPb, JSONObj, PresentationRequestDto } from '@unumid/types';

@@ -324,9 +324,9 @@ import { RESTData, SendRequestReqBody, UnumDto } from '../types';

metadata?: Record<string, unknown>
): Promise<UnumDto<PresentationRequestPostDto>> => {
): Promise<UnumDto<PresentationRequestDto>> => {
// create an indentifier that ties together these related requests of different versions.
const id = getUUID();
// create and send a v2 presentation request for backwards compatibility
const responseV2 = await sendRequestDeprecated(authorization, verifier, credentialRequests, eccPrivateKey, holderAppUuid, id, expirationDate, metadata);
authorization = responseV2.authToken ? responseV2.authToken : authorization;
// // create and send a v2 presentation request for backwards compatibility
// const responseV2 = await sendRequestDeprecated(authorization, verifier, credentialRequests, eccPrivateKey, holderAppUuid, id, expirationDate, metadata);
// authorization = responseV2.authToken ? responseV2.authToken : authorization;

@@ -354,3 +354,3 @@ const response = sendRequestV3(authorization, verifier, credentialRequests, eccPrivateKey, holderAppUuid, id, expirationDate, metadata);

metadata?: any
): Promise<UnumDto<PresentationRequestPostDto>> => {
): Promise<UnumDto<PresentationRequestDto>> => {
try {

@@ -378,7 +378,7 @@ requireAuth(authorization);

const restResp = await makeNetworkRequest<PresentationRequestPostDto>(restData);
const restResp = await makeNetworkRequest<PresentationRequestDto>(restData);
const authToken: string = handleAuthTokenHeader(restResp, authorization);
const presentationRequestResponse: UnumDto<PresentationRequestPostDto> = { body: { ...restResp.body }, authToken };
const presentationRequestResponse: UnumDto<PresentationRequestDto> = { body: { ...restResp.body }, authToken };

@@ -385,0 +385,0 @@ return presentationRequestResponse;

@@ -1,2 +0,2 @@

import { ProofPb } from '@unumid/types';
import { Proof, ProofPb } from '@unumid/types';
import { CustError } from '../utils/error';

@@ -41,1 +41,37 @@

};
/**
* Helper to validate a proof has the required attributes.
* @param proof ProofPb
*/
export const validateProofDeprecated = (proof: Proof): Proof => {
const {
created,
signatureValue,
type,
verificationMethod,
proofPurpose
} = proof;
if (!created) {
throw new CustError(400, 'Invalid Presentation: proof.created is required.');
}
if (!signatureValue) {
throw new CustError(400, 'Invalid Presentation: proof.signatureValue is required.');
}
if (!type) {
throw new CustError(400, 'Invalid Presentation: proof.type is required.');
}
if (!verificationMethod) {
throw new CustError(400, 'Invalid Presentation: proof.verificationMethod is required.');
}
if (!proofPurpose) {
throw new CustError(400, 'Invalid Presentation: proof.proofPurpose is required.');
}
return proof;
};

@@ -6,7 +6,5 @@

import { UnumDto } from '../types';
import { configData } from '../config';
import logger from '../logger';
import { CredentialPb, Proof, UnsignedCredentialPb } from '@unumid/types';
import { getDIDDoc, getKeyFromDIDDoc } from '../utils/didHelper';
import { handleAuthTokenHeader } from '../utils/networkRequestHelper';
import { CredentialPb, PublicKeyInfo, UnsignedCredentialPb } from '@unumid/types';
import { getDidDocPublicKeys } from '../utils/didHelper';
import { doVerify } from '../utils/verify';

@@ -20,3 +18,3 @@ import { CustError } from '..';

*/
export const verifyCredential = async (credential: CredentialPb, authorization: string): Promise<UnumDto<boolean>> => {
export const verifyCredential = async (authorization: string, credential: CredentialPb): Promise<UnumDto<boolean>> => {
const { proof } = credential;

@@ -28,11 +26,7 @@

const didDocumentResponse = await getDIDDoc(configData.SaaSUrl, authorization, proof.verificationMethod);
// grab all 'secp256r1' keys from the DID document
const publicKeyInfoResponse: UnumDto<PublicKeyInfo[]> = await getDidDocPublicKeys(authorization, proof.verificationMethod, 'secp256r1');
const publicKeyInfoList: PublicKeyInfo[] = publicKeyInfoResponse.body;
const authToken = publicKeyInfoResponse.authToken;
if (didDocumentResponse instanceof Error) {
throw didDocumentResponse;
}
const authToken: string = handleAuthTokenHeader(didDocumentResponse, authorization);
const publicKeyObject = getKeyFromDIDDoc(didDocumentResponse.body, 'secp256r1');
const data: UnsignedCredentialPb = omit(credential, 'proof');

@@ -42,4 +36,13 @@

const bytes = UnsignedCredentialPb.encode(data).finish();
const isVerified: boolean = doVerify(proof.signatureValue, bytes, publicKeyObject[0].publicKey, publicKeyObject[0].encoding);
let isVerified = false;
// check all the public keys to see if any work, stop if one does
for (const publicKeyInfo of publicKeyInfoList) {
const { publicKey, encoding } = publicKeyInfo;
isVerified = doVerify(proof.signatureValue, bytes, publicKey, encoding);
if (isVerified) break;
}
const result: UnumDto<boolean> = {

@@ -46,0 +49,0 @@ authToken,

@@ -6,3 +6,2 @@

import { validateProof } from './validateProof';
import { configData } from '../config';
import { requireAuth } from '../requireAuth';

@@ -12,6 +11,5 @@ import logger from '../logger';

import { isArrayEmpty, isArrayNotEmpty } from '../utils/helpers';
import { handleAuthTokenHeader } from '../utils/networkRequestHelper';
import { doVerify } from '../utils/verify';
import { PresentationPb, UnsignedPresentationPb } from '@unumid/types';
import { getDIDDoc, getKeyFromDIDDoc } from '../utils/didHelper';
import { PresentationPb, PublicKeyInfo, UnsignedPresentationPb } from '@unumid/types';
import { getDidDocPublicKeys } from '../utils/didHelper';
import { sendPresentationVerifiedReceipt } from './sendPresentationVerifiedReceipt';

@@ -67,9 +65,9 @@

* Handler for when a user does not agree to share the information in the credential request.
* @param authorization
* @param authToken
* @param noPresentation
* @param verifier
*/
export const verifyNoPresentationHelper = async (authorization: string, noPresentation: PresentationPb, verifier: string, requestUuid: string): Promise<UnumDto<VerifiedStatus>> => {
export const verifyNoPresentationHelper = async (authToken: string, noPresentation: PresentationPb, verifier: string, requestUuid: string): Promise<UnumDto<VerifiedStatus>> => {
try {
requireAuth(authorization);
requireAuth(authToken);

@@ -89,3 +87,3 @@ noPresentation = validateNoPresentationParams(noPresentation);

// send PresentationVerified receipt
const authToken = await sendPresentationVerifiedReceipt(authorization, verifier, noPresentation.proof.verificationMethod, 'declined', false, noPresentation.presentationRequestId, requestUuid, message);
authToken = await sendPresentationVerifiedReceipt(authToken, verifier, noPresentation.proof.verificationMethod, 'declined', false, noPresentation.presentationRequestId, requestUuid, message);

@@ -102,13 +100,7 @@ const result: UnumDto<VerifiedStatus> = {

const didDocumentResponse = await getDIDDoc(configData.SaaSUrl, authorization as string, verificationMethod);
// grab all 'secp256r1' keys from the DID document
const publicKeyInfoResponse: UnumDto<PublicKeyInfo[]> = await getDidDocPublicKeys(authToken, verificationMethod, 'secp256r1');
const publicKeyInfoList: PublicKeyInfo[] = publicKeyInfoResponse.body;
authToken = publicKeyInfoResponse.authToken;
if (didDocumentResponse instanceof Error) {
throw didDocumentResponse;
}
let authToken: string = handleAuthTokenHeader(didDocumentResponse, authorization);
const publicKeyInfos = getKeyFromDIDDoc(didDocumentResponse.body, 'secp256r1');
const { publicKey, encoding } = publicKeyInfos[0];
// remove the proof attribute

@@ -120,5 +112,13 @@ const unsignedNoPresentation: UnsignedPresentationPb = omit(noPresentation, 'proof');

// verify the signature
const isVerified = doVerify(signatureValue, bytes, publicKey, encoding);
let isVerified = false;
// check all the public keys to see if any work, stop if one does
for (const publicKeyInfo of publicKeyInfoList) {
const { publicKey, encoding } = publicKeyInfo;
// verify the signature
isVerified = doVerify(signatureValue, bytes, publicKey, encoding);
if (isVerified) break;
}
const message = isVerified ? undefined : 'Presentation signature can not be verified.'; // the receipt reason, only populated if not verified

@@ -125,0 +125,0 @@

import { DecryptedPresentation, UnumDto, VerifiedStatus } from '../types';
import { Presentation, CredentialRequest, PresentationRequestDto, EncryptedData, PresentationRequest, PresentationPb, PresentationRequestPb, ProofPb, UnsignedPresentationRequestPb, JSONObj, CredentialRequestPb, WithVersion } from '@unumid/types';
import { Presentation, CredentialRequest, PresentationRequestDto, EncryptedData, PresentationRequest, PresentationPb, PresentationRequestPb, ProofPb, UnsignedPresentationRequestPb, WithVersion, PublicKeyInfo } from '@unumid/types';
import { requireAuth } from '../requireAuth';
import { CryptoError, decrypt, decryptBytes } from '@unumid/library-crypto';
import { CryptoError, decryptBytes } from '@unumid/library-crypto';
import logger from '../logger';

@@ -12,3 +12,3 @@ import { verifyNoPresentationHelper } from './verifyNoPresentationHelper';

import { omit } from 'lodash';
import { getDIDDoc, getKeyFromDIDDoc } from '../utils/didHelper';
import { getDidDocPublicKeys } from '../utils/didHelper';
import { configData } from '../config';

@@ -20,3 +20,3 @@ import { doVerify } from '../utils/verify';

import { sendPresentationVerifiedReceipt } from './sendPresentationVerifiedReceipt';
import { extractPresentationRequest, getPresentationRequest } from './getPresentationRequest';
import { extractPresentationRequest, getPresentationRequest, handleConvertingPresentationRequestDateAttributes } from './getPresentationRequest';

@@ -151,13 +151,7 @@ function isDeclinedPresentation (presentation: Presentation | PresentationPb): presentation is Presentation {

const didDocumentResponse = await getDIDDoc(configData.SaaSUrl, authorization as string, verificationMethod);
// grab all 'secp256r1' keys from the DID document
const publicKeyInfoResponse: UnumDto<PublicKeyInfo[]> = await getDidDocPublicKeys(authorization, verificationMethod, 'secp256r1');
const publicKeyInfoList: PublicKeyInfo[] = publicKeyInfoResponse.body;
const authToken = publicKeyInfoResponse.authToken;
if (didDocumentResponse instanceof Error) {
throw didDocumentResponse;
}
const authToken: string = handleAuthTokenHeader(didDocumentResponse, authorization);
const publicKeyInfos = getKeyFromDIDDoc(didDocumentResponse.body, 'secp256r1');
const { publicKey, encoding } = publicKeyInfos[0];
const unsignedPresentationRequest: UnsignedPresentationRequestPb = omit(presentationRequest, 'proof');

@@ -168,5 +162,13 @@

// verify the byte array
const isVerified = doVerify(signatureValue, bytes, publicKey, encoding);
let isVerified = false;
// check all the public keys to see if any work, stop if one does
for (const publicKeyInfo of publicKeyInfoList) {
const { publicKey, encoding } = publicKeyInfo;
// verify the signature
isVerified = doVerify(signatureValue, bytes, publicKey, encoding);
if (isVerified) break;
}
if (!isVerified) {

@@ -193,3 +195,3 @@ const result: UnumDto<VerifiedStatus> = {

/**
* Handler to send information regarding the user agreeing to share a credential Presentation.
* Handler for verifying a provided encrypted Presentation.
* @param authorization: string

@@ -223,3 +225,3 @@ * @param encryptedPresentation: EncryptedData

if (process.env.NODE_ENV === 'debug') {
if (configData.debug) {
logger.debug(`Decrypted Presentation: ${JSON.stringify(presentation)}`);

@@ -237,2 +239,5 @@ }

presentationRequest = extractPresentationRequest(presentationRequestResponse.body);
} else {
// need to convert the string date attributes to to Date objects for proto handling
presentationRequest = handleConvertingPresentationRequestDateAttributes(presentationRequest);
}

@@ -250,3 +255,3 @@

const requestVerificationResult = await verifyPresentationRequest(authorization, presentationRequestPb);
const requestVerificationResult: UnumDto<VerifiedStatus> = await verifyPresentationRequest(authorization, presentationRequestPb);
authorization = requestVerificationResult.authToken;

@@ -253,0 +258,0 @@

import { omit } from 'lodash';
import { configData } from '../config';
import { CredentialStatusInfo, UnumDto, VerifiedStatus } from '../types';
import { CredentialRequest, PublicKeyInfo, JSONObj, PresentationPb, CredentialPb, ProofPb, UnsignedPresentationPb, CredentialSubject, WithVersion } from '@unumid/types';
import { UnumDto, VerifiedStatus } from '../types';
import { CredentialRequest, PublicKeyInfo, JSONObj, PresentationPb, CredentialPb, ProofPb, UnsignedPresentationPb, CredentialSubject, CredentialIdToStatusMap } from '@unumid/types';
import { validateProof } from './validateProof';

@@ -10,3 +9,2 @@ import { requireAuth } from '../requireAuth';

import { isCredentialExpired } from './isCredentialExpired';
import { checkCredentialStatus } from './checkCredentialStatus';
import logger from '../logger';

@@ -16,7 +14,8 @@ import { CryptoError } from '@unumid/library-crypto';

import { CustError } from '../utils/error';
import { getDIDDoc, getKeyFromDIDDoc } from '../utils/didHelper';
import { handleAuthTokenHeader } from '../utils/networkRequestHelper';
import { getDidDocPublicKeys } from '../utils/didHelper';
import { doVerify } from '../utils/verify';
import { convertCredentialSubject } from '../utils/convertCredentialSubject';
import { sendPresentationVerifiedReceipt } from './sendPresentationVerifiedReceipt';
import { checkCredentialStatuses } from './checkCredentialStatuses';
import { getCredentialStatusFromMap } from '../utils/getCredentialStatusFromMap';

@@ -38,9 +37,7 @@ /**

const totCred = credentials.length;
for (let i = 0; i < totCred; i++) {
const credPosStr = '[' + i + ']';
for (let i = 0; i < credentials.length; i++) {
const credential = credentials[i];
// Validate the existence of elements in Credential object
const invalidMsg = `Invalid verifiableCredential${credPosStr}:`;
const invalidMsg = `Invalid verifiableCredential[${i}]:`;
if (!credential.context) {

@@ -305,22 +302,7 @@ retObj.valid = false;

// proof.verificationMethod is the subject's did
const didDocumentResponse = await getDIDDoc(configData.SaaSUrl, authorization as string, proof.verificationMethod);
// grab all 'secp256r1' keys from the DID document
const publicKeyInfoResponse: UnumDto<PublicKeyInfo[]> = await getDidDocPublicKeys(authorization, proof.verificationMethod, 'secp256r1');
const publicKeyInfoList: PublicKeyInfo[] = publicKeyInfoResponse.body;
let authToken = publicKeyInfoResponse.authToken;
if (didDocumentResponse instanceof Error) {
throw didDocumentResponse;
}
let authToken: string = handleAuthTokenHeader(didDocumentResponse, authorization); // Note: going to use authToken instead of authorization for subsequent requests in case saas rolls to token.
const pubKeyObj: PublicKeyInfo[] = getKeyFromDIDDoc(didDocumentResponse.body, 'secp256r1');
if (pubKeyObj.length === 0) {
const result: UnumDto<VerifiedStatus> = {
authToken,
body: {
isVerified: false,
message: 'Public key not found for the DID associated with the proof.verificationMethod'
}
};
return result;
}
// Verify the data given. As of now only one secp256r1 public key is expected.

@@ -334,4 +316,10 @@ // In future, there is a possibility that, more than one secp256r1 public key can be there for a given DID.

// verify the signature
isPresentationVerified = doVerify(proof.signatureValue, bytes, pubKeyObj[0].publicKey, pubKeyObj[0].encoding);
// check all the public keys to see if any work, stop if one does
for (const publicKeyInfo of publicKeyInfoList) {
const { publicKey, encoding } = publicKeyInfo;
// verify the signature
isPresentationVerified = doVerify(proof.signatureValue, bytes, publicKey, encoding);
if (isPresentationVerified) break;
}
} catch (e) {

@@ -347,3 +335,3 @@ if (e instanceof CryptoError) {

// send PresentationVerified receipt
const authToken = await sendPresentationVerifiedReceipt(authorization, verifier, proof.verificationMethod, 'approved', false, presentation.presentationRequestId, requestUuid, message, issuers, credentialTypes, credentialIds);
authToken = await sendPresentationVerifiedReceipt(authToken, verifier, proof.verificationMethod, 'approved', false, presentation.presentationRequestId, requestUuid, message, issuers, credentialTypes, credentialIds);

@@ -365,3 +353,3 @@ // need to return the UnumDto with the (potentially) updated authToken

// send PresentationVerified receipt
const authToken = await sendPresentationVerifiedReceipt(authorization, verifier, proof.verificationMethod, 'approved', false, presentation.presentationRequestId, requestUuid, message, issuers, credentialTypes, credentialIds);
authToken = await sendPresentationVerifiedReceipt(authToken, verifier, proof.verificationMethod, 'approved', false, presentation.presentationRequestId, requestUuid, message, issuers, credentialTypes, credentialIds);

@@ -381,2 +369,7 @@ const result: UnumDto<VerifiedStatus> = {

// get all the presentation's credentialIds to make one batched call for their statuses to the saas
const presentationCredentialIds = presentation.verifiableCredential.map(credential => credential.id);
const isStatusValidResponse: UnumDto<CredentialIdToStatusMap> = await checkCredentialStatuses(authToken, presentationCredentialIds);
authToken = isStatusValidResponse.authToken;
for (const credential of presentation.verifiableCredential) {

@@ -391,4 +384,3 @@ const isExpired = isCredentialExpired(credential);

const isStatusValidResponse: UnumDto<CredentialStatusInfo> = await checkCredentialStatus(authToken, credential.id);
const isStatusValid = isStatusValidResponse.body.status === 'valid';
const isStatusValid = getCredentialStatusFromMap(credential.id, isStatusValidResponse.body);
authToken = isStatusValidResponse.authToken;

@@ -402,3 +394,3 @@

const isVerifiedResponse: UnumDto<boolean> = await verifyCredential(credential, authToken);
const isVerifiedResponse: UnumDto<boolean> = await verifyCredential(authToken, credential);
const isVerified = isVerifiedResponse.body;

@@ -416,3 +408,3 @@ authToken = isVerifiedResponse.authToken;

// send PresentationVerified receipt
const authToken = await sendPresentationVerifiedReceipt(authorization, verifier, proof.verificationMethod, 'approved', false, presentation.presentationRequestId, requestUuid, credentialInvalidMessage, issuers, credentialTypes, credentialIds);
authToken = await sendPresentationVerifiedReceipt(authToken, verifier, proof.verificationMethod, 'approved', false, presentation.presentationRequestId, requestUuid, credentialInvalidMessage, issuers, credentialTypes, credentialIds);

@@ -419,0 +411,0 @@ const result: UnumDto<VerifiedStatus> = {

@@ -8,3 +8,3 @@ import { configData } from '../../src/config';

import * as createKeyPairs from '../../src/utils/createKeyPairs';
import { getDIDDoc, getDidDocPublicKeys } from '../../src/utils/didHelper';
import { getDidDocPublicKeys } from '../../src/utils/didHelper';
import { doEncrypt, doEncryptPb } from '../../src/utils/encrypt';

@@ -18,3 +18,2 @@ import { makeNetworkRequest } from '../../src/utils/networkRequestHelper';

...actual,
getDIDDoc: jest.fn(),
getDidDocPublicKeys: jest.fn()

@@ -54,3 +53,2 @@ };

const mockMakeNetworkRequest = makeNetworkRequest as jest.Mock;
const mockGetDIDDoc = getDIDDoc as jest.Mock;
const mockGetDidDocKeys = getDidDocPublicKeys as jest.Mock;

@@ -83,5 +81,4 @@ const mockDoEncrypt = doEncrypt as jest.Mock;

const headers = { 'x-auth-token': dummyAuthToken };
mockGetDIDDoc.mockResolvedValue({ body: dummyDidDoc, headers });
mockMakeNetworkRequest.mockResolvedValue({ body: { success: true }, headers });
mockGetDidDocKeys.mockResolvedValue(dummyDidDoc.publicKey);
mockGetDidDocKeys.mockResolvedValue({ authToken: dummyAuthToken, body: [dummyDidDoc.publicKey] });

@@ -106,4 +103,4 @@ responseDto = await callIssueCred(credentialSubject, type, issuer, expirationDate, eccPrivateKey, authHeader);

it('encrypts the credential for each public key', () => {
expect(mockDoEncrypt).toBeCalledTimes(4);
expect(mockDoEncryptPb).toBeCalledTimes(4);
expect(mockDoEncrypt).toBeCalledTimes(1);
expect(mockDoEncryptPb).toBeCalledTimes(1);
});

@@ -134,9 +131,2 @@

it('does not return an auth token if the SaaS does not return an auth token', async () => {
mockMakeNetworkRequest.mockResolvedValue({ body: { success: true } });
responseDto = await callIssueCred(credentialSubject, type, issuer, expirationDate, eccPrivateKey, dummyAdminKey);
responseAuthToken = responseDto.authToken;
expect(responseAuthToken).toBeUndefined();
});
it('type array starts with and contains only one `VerifiableCredential` string despite type of the credential options including the preceeding string', async () => {

@@ -146,3 +136,2 @@ mockMakeNetworkRequest.mockResolvedValue({ body: { success: true } });

const headers = { 'x-auth-token': dummyAuthToken };
mockGetDIDDoc.mockResolvedValue({ body: dummyDidDoc, headers });

@@ -271,5 +260,5 @@ responseDto = await callIssueCred(credentialSubject, type, issuer, expirationDate, eccPrivateKey, dummyAdminKey);

const headers = { 'x-auth-token': dummyAuthToken };
mockGetDIDDoc.mockResolvedValue({ body: dummyDidDoc, headers });
// mockGetDIDDoc.mockResolvedValue({ body: dummyDidDoc, headers });
mockMakeNetworkRequest.mockResolvedValue({ body: { success: true }, headers });
mockGetDidDocKeys.mockResolvedValue(dummyDidDoc.publicKey);
mockGetDidDocKeys.mockResolvedValue({ authToken: dummyAuthToken, body: [dummyDidDoc.publicKey] });

@@ -294,4 +283,4 @@ responseDto = await callIssueCreds(issuer, credentialSubject.id, credentialData, expirationDate, eccPrivateKey, authHeader);

it('encrypts the credential for each public key', () => {
expect(mockDoEncrypt).toBeCalledTimes(8);
expect(mockDoEncryptPb).toBeCalledTimes(8);
expect(mockDoEncrypt).toBeCalledTimes(2);
expect(mockDoEncryptPb).toBeCalledTimes(2);
});

@@ -338,3 +327,3 @@

const headers = { 'x-auth-token': dummyAuthToken };
mockGetDIDDoc.mockResolvedValue({ body: dummyDidDoc, headers });
// mockGetDIDDoc.mockResolvedValue({ body: dummyDidDoc, headers });

@@ -341,0 +330,0 @@ responseDto = await callIssueCreds(issuer, credentialSubject.id, credentialData, expirationDate, eccPrivateKey, authHeader);

import { Issuer, DidDocument, UnsignedCredential, Credential, CredentialSubject } from '@unumid/types';
import { Issuer, DidDocument, UnsignedCredential, Credential, CredentialSubject, SubjectCredentialRequest, CredentialRequestPb, SignedDidDocument, SubjectCredentialRequests } from '@unumid/types';
import { CredentialRequest, UnsignedSubjectCredentialRequests } from '@unumid/types/build/protos/credential';
import { configData } from '../../src/config';
import { RESTResponse } from '../../src/types';
import { createKeyPairSet } from '../../src/utils/createKeyPairs';
import { createProof } from '../../src/utils/createProof';
import { createProof, createProofPb } from '../../src/utils/createProof';
import { getUUID } from '../../src/utils/helpers';

@@ -41,2 +42,49 @@

export const dummyCredentialRequest = {
type: 'DummyCredential',
issuers: [dummyIssuerDid],
required: true
};
export const dummySubjectCredentialRequest = {
type: 'DummyCredential',
issuers: [dummyIssuerDid],
required: true
};
export const makeDummySubjectCredentialRequests = async (requests: CredentialRequest[], subjectPrivateKey: string, subjectDid: string): Promise<SubjectCredentialRequests> => {
// create UnsignedSubjectCredentialRequests
const unsignedSubjectCredentialRequests: UnsignedSubjectCredentialRequests = {
credentialRequests: requests
};
// convert the protobuf to a byte array
const bytes: Uint8Array = UnsignedSubjectCredentialRequests.encode(unsignedSubjectCredentialRequests).finish();
const proof = await createProofPb(bytes, subjectPrivateKey, subjectDid, undefined);
return {
...unsignedSubjectCredentialRequests,
proof: proof
};
};
// export const makeDummySubjectCredentialRequest = async (request: CredentialRequestPb, subjectPrivateKey: string, subjectDid: string): Promise<SubjectCredentialRequest> => {
// // convert the protobuf to a byte array
// const bytes: Uint8Array = CredentialRequestPb.encode(request).finish();
// const proof = await createProofPb(bytes, subjectPrivateKey, subjectDid, undefined);
// return {
// ...dummyCredentialRequest,
// proof: proof
// };
// };
export const makeDummySignedDidDocument = async (didDoc: DidDocument, subjectPrivateKey: string, subjectDid: string): Promise<SignedDidDocument> => {
const proof = await createProof(didDoc, subjectPrivateKey, subjectDid, 'pem');
return {
...didDoc,
proof
};
};
export const makeDummyIssuerResponse = (options: DummyVerifierResponseOptions = {}): RESTResponse<Issuer> => {

@@ -50,3 +98,4 @@ const authToken = options.authToken || dummyAuthToken;

export const makeDummyDidDocument = async (options: Partial<DidDocument> = {}): Promise<DidDocument> => {
export const makeDummyDidDocument = async (options: Partial<DidDocument> = {}, signingPrivateKey?: string, signginPublicKey?: string): Promise<DidDocument> => {
// export const makeDummyDidDocument = async (options: Partial<DidDocument> = {}, signingPrivateKey?: string, signginPublicKey?: string): Promise<DidDocument> => {
const id = options.id || `did:unum:${getUUID()}`;

@@ -67,3 +116,4 @@ const now = new Date();

id: getUUID(),
publicKey: keypairs.signing.publicKey,
publicKey: signginPublicKey || keypairs.signing.publicKey,
// publicKey: keypairs.signing.publicKey,
encoding: 'pem',

@@ -77,3 +127,4 @@ type: 'secp256r1',

id: getUUID(),
publicKey: keypairs.encryption.publicKey,
publicKey: signingPrivateKey || keypairs.encryption.publicKey,
// publicKey: keypairs.encryption.publicKey,
encoding: 'pem',

@@ -80,0 +131,0 @@ type: 'RSA',

@@ -7,2 +7,3 @@ import { JSONObj, RegisteredIssuer, UnumDto } from '../../src/types';

import { makeNetworkRequest } from '../../src/utils/networkRequestHelper';
import { VersionInfo } from '@unumid/types';

@@ -66,6 +67,7 @@ jest.mock('../../src/utils/networkRequestHelper', () => ({

const customerUuid = '5e46f1ba-4c82-471d-bbc7-251924a90532';
const url = 'dummy.com';
it('returns a CustError with a descriptive error message if customerUuid is missing', async () => {
try {
await registerIssuer('', dummyIssuerApiKey);
await registerIssuer('', dummyIssuerApiKey, url);
fail();

@@ -81,3 +83,3 @@ } catch (e) {

try {
await registerIssuer(customerUuid, '');
await registerIssuer(customerUuid, '', url);
fail();

@@ -90,2 +92,62 @@ } catch (e) {

});
it('returns a CustError with a descriptive error message if url is missing', async () => {
try {
await registerIssuer(customerUuid, dummyIssuerApiKey, undefined);
fail();
} catch (e) {
expect(e).toEqual(new CustError(400, 'Invalid Issuer: url is required.'));
expect(e.code).toEqual(400);
expect(e.message).toEqual('Invalid Issuer: url is required.');
}
});
it('returns a CustError with a descriptive error message if versionInfo target is missing', async () => {
// const badVersionInfo: VersionInfo[] = [{ target: { version: '1.0.x' }, sdkVersion: '3.0.0' }];
const badVersionInfo: VersionInfo[] = [{ sdkVersion: '3.0.0' }];
try {
await registerIssuer(customerUuid, dummyIssuerApiKey, url, badVersionInfo);
fail();
} catch (e) {
expect(e).toEqual(new CustError(400, '\'versionInfo[0].target\' must be defined.'));
expect(e.code).toEqual(400);
expect(e.message).toEqual('\'versionInfo[0].target\' must be defined.');
}
});
it('returns a CustError with a descriptive error message if versionInfo url or version is missing', async () => {
const badVersionInfo: VersionInfo[] = [{ target: { hat: '1.0.x' }, sdkVersion: '3.0.0' }];
try {
await registerIssuer(customerUuid, dummyIssuerApiKey, url, badVersionInfo);
fail();
} catch (e) {
expect(e).toEqual(new CustError(400, '\'versionInfo[0].target.version\' or \'versionInfo[0].target.url\' must be defined.'));
expect(e.code).toEqual(400);
expect(e.message).toEqual('\'versionInfo[0].target.version\' or \'versionInfo[0].target.url\' must be defined.');
}
});
it('returns a CustError with a descriptive error message if versionInfo version is not in semver notation', async () => {
const badVersionInfo: VersionInfo[] = [{ target: { version: '1.0.x' }, sdkVersion: '3.0.0' }];
try {
await registerIssuer(customerUuid, dummyIssuerApiKey, url, badVersionInfo);
fail();
} catch (e) {
expect(e).toEqual(new CustError(400, '\'versionInfo[0].target.version\' must be valid semver notation.'));
expect(e.code).toEqual(400);
expect(e.message).toEqual('\'versionInfo[0].target.version\' must be valid semver notation.');
}
});
it('returns a CustError with a descriptive error message if versionInfo sdkVersion is not in semver notation', async () => {
const badVersionInfo: VersionInfo[] = [{ target: { version: '1.0.0' }, sdkVersion: '3.0.x' }];
try {
await registerIssuer(customerUuid, dummyIssuerApiKey, url, badVersionInfo);
fail();
} catch (e) {
expect(e).toEqual(new CustError(400, '\'versionInfo[0].sdkVersion\' must be valid semver notation.'));
expect(e.code).toEqual(400);
expect(e.message).toEqual('\'versionInfo[0].sdkVersion\' must be valid semver notation.');
}
});
});

@@ -96,2 +158,3 @@

const customerUuid = '5e46f1ba-4c82-471d-bbc7-251924a90532';
const url = 'dummy.com';

@@ -101,3 +164,3 @@ it('Response code should be 403 when uuid is not valid', async () => {

try {
await registerIssuer('123', dummyIssuerApiKey);
await registerIssuer('123', dummyIssuerApiKey, url);
} catch (e) {

@@ -112,3 +175,3 @@ expect(e.code).toBe(403);

try {
await registerIssuer(customerUuid, 'abc');
await registerIssuer(customerUuid, 'abc', url);
} catch (e) {

@@ -115,0 +178,0 @@ expect(e.code).toBe(403);

@@ -25,3 +25,3 @@ import { dummyAuthToken, dummyAdminKey } from './mocks';

mockMakeNetworkRequest.mockResolvedValue({ body: { success: true }, headers });
response = await updateCredentialStatus(credentialId, authHeader);
response = await updateCredentialStatus(authHeader, credentialId);
responseAuthToken = response.authToken;

@@ -28,0 +28,0 @@ });

import { DidDocument } from '@unumid/types';
import { getKeyFromDIDDoc } from '../../src/utils/didHelper';
import { getKeysFromDIDDoc } from '../../src/utils/didHelper';

@@ -38,3 +38,3 @@ describe('getKeyFromDidDoc', () => {

const result = getKeyFromDIDDoc(didDoc, 'secp256r1');
const result = getKeysFromDIDDoc(didDoc, 'secp256r1');
expect(result.length).toEqual(1);

@@ -41,0 +41,0 @@ expect(result[0].id).toEqual('5a586f0f-6936-426c-bc68-adeb4f0e7d5d');

@@ -54,5 +54,5 @@ import * as restHlpr from '../../src/utils/networkRequestHelper';

it('Status code should be 401 when authKey is not passed', () => {
expect(didDocResponse.code).toBe(401);
});
// it('Status code should be 401 when authKey is not passed', () => {
// expect(didDocResponse.code).toBe(401);
// });
});
import * as cryptoLib from '@unumid/library-crypto';
import { PublicKeyInfo, EncryptedData, KeyPair, UnsignedCredentialPb } from '@unumid/types';
import { getDIDDoc, getKeyFromDIDDoc } from '../../src/utils/didHelper';
import { getDIDDoc, getKeysFromDIDDoc } from '../../src/utils/didHelper';
import { doEncrypt } from '../../src/utils/encrypt';

@@ -27,3 +27,3 @@ import { doVerify, doVerifyDeprecated } from '../../src/utils/verify';

const didDocResponse = await getDIDDoc(baseUrl, authHeader, did);
publicKeyObj = getKeyFromDIDDoc(didDocResponse.body, 'RSA');
publicKeyObj = getKeysFromDIDDoc(didDocResponse.body, 'RSA');
});

@@ -30,0 +30,0 @@

@@ -119,2 +119,51 @@ import {

});
it('returns a CustError with a descriptive error message if versionInfo target is missing', async () => {
// const badVersionInfo: VersionInfo[] = [{ target: { version: '1.0.x' }, sdkVersion: '3.0.0' }];
const badVersionInfo: VersionInfo[] = [{ sdkVersion: '3.0.0' }];
try {
await registerVerifier(customerUuid, url, dummyVerifierApiKey, badVersionInfo);
fail();
} catch (e) {
expect(e).toEqual(new CustError(400, '\'versionInfo[0].target\' must be defined.'));
expect(e.code).toEqual(400);
expect(e.message).toEqual('\'versionInfo[0].target\' must be defined.');
}
});
it('returns a CustError with a descriptive error message if versionInfo url or version is missing', async () => {
const badVersionInfo: VersionInfo[] = [{ target: { hat: '1.0.x' }, sdkVersion: '3.0.0' }];
try {
await registerVerifier(customerUuid, url, dummyVerifierApiKey, badVersionInfo);
fail();
} catch (e) {
expect(e).toEqual(new CustError(400, '\'versionInfo[0].target.version\' or \'versionInfo[0].target.url\' must be defined.'));
expect(e.code).toEqual(400);
expect(e.message).toEqual('\'versionInfo[0].target.version\' or \'versionInfo[0].target.url\' must be defined.');
}
});
it('returns a CustError with a descriptive error message if versionInfo version is not in semver notation', async () => {
const badVersionInfo: VersionInfo[] = [{ target: { version: '1.0.x' }, sdkVersion: '3.0.0' }];
try {
await registerVerifier(customerUuid, url, dummyVerifierApiKey, badVersionInfo);
fail();
} catch (e) {
expect(e).toEqual(new CustError(400, '\'versionInfo[0].target.version\' must be valid semver notation.'));
expect(e.code).toEqual(400);
expect(e.message).toEqual('\'versionInfo[0].target.version\' must be valid semver notation.');
}
});
it('returns a CustError with a descriptive error message if versionInfo sdkVersion is not in semver notation', async () => {
const badVersionInfo: VersionInfo[] = [{ target: { version: '1.0.0' }, sdkVersion: '3.0.x' }];
try {
await registerVerifier(customerUuid, url, dummyVerifierApiKey, badVersionInfo);
fail();
} catch (e) {
expect(e).toEqual(new CustError(400, '\'versionInfo[0].sdkVersion\' must be valid semver notation.'));
expect(e.code).toEqual(400);
expect(e.message).toEqual('\'versionInfo[0].sdkVersion\' must be valid semver notation.');
}
});
});

@@ -121,0 +170,0 @@

@@ -1,5 +0,5 @@

import { CredentialPb, CredentialRequestPb, UnsignedCredentialPb } from '@unumid/types';
import { CredentialPb, UnsignedCredentialPb } from '@unumid/types';
import { UnumDto } from '../../src/types';
import { getDIDDoc } from '../../src/utils/didHelper';
import { getDidDocPublicKeys } from '../../src/utils/didHelper';
import { doVerify } from '../../src/utils/verify';

@@ -14,3 +14,3 @@ import { verifyCredential } from '../../src/verifier/verifyCredential';

...actual,
getDIDDoc: jest.fn()
getDidDocPublicKeys: jest.fn()
};

@@ -27,3 +27,3 @@ });

const mockGetDIDDoc = getDIDDoc as jest.Mock;
const mockGetDidDocKeys = getDidDocPublicKeys as jest.Mock;
const mockDoVerify = doVerify as jest.Mock;

@@ -49,6 +49,6 @@

const dummyDidDoc = await makeDummyDidDocument({ id: credential.issuer });
mockGetDIDDoc.mockResolvedValue({ body: dummyDidDoc });
mockGetDidDocKeys.mockResolvedValue({ authToken: authHeader, body: [dummyDidDoc.publicKey] });
mockDoVerify.mockReturnValueOnce(true);
isVerified = await verifyCredential(credential, authHeader);
isVerified = await verifyCredential(authHeader, credential);
});

@@ -61,3 +61,3 @@

it('gets the did document', () => {
expect(mockGetDIDDoc).toBeCalled();
expect(mockGetDidDocKeys).toBeCalled();
});

@@ -103,3 +103,3 @@

mockDoVerify.mockReturnValueOnce(false);
const isInvalidVerified = await verifyCredential(invalidCredential, authHeader);
const isInvalidVerified = await verifyCredential(authHeader, invalidCredential);
expect(isInvalidVerified.body).toBe(false);

@@ -140,3 +140,3 @@ });

mockDoVerify.mockReturnValueOnce(false);
const isInvalidVerified = await verifyCredential(invalidCredential, authHeader);
const isInvalidVerified = await verifyCredential(authHeader, invalidCredential);
expect(isInvalidVerified.body).toBe(false);

@@ -177,5 +177,5 @@ });

mockDoVerify.mockReturnValueOnce(false);
const isInvalidVerified = await verifyCredential(validCredential, authHeader);
const isInvalidVerified = await verifyCredential(authHeader, validCredential);
expect(isInvalidVerified.body).toBe(false);
});
});
import { omit } from 'lodash';
import { VerifiedStatus, UnumDto } from '../../src/types';
import { dummyAuthToken, dummyVerifierDid, makeDummyDidDocument, makeDummyPresentation } from './mocks';
import { dummyAuthToken, makeDummyDidDocument, makeDummyPresentation } from './mocks';
import { verifyNoPresentationHelper as verifyNoPresentation } from '../../src/verifier/verifyNoPresentationHelper';
import { getDIDDoc } from '../../src/utils/didHelper';
import { getDidDocPublicKeys } from '../../src/utils/didHelper';
import { makeNetworkRequest } from '../../src/utils/networkRequestHelper';

@@ -15,3 +15,3 @@ import { doVerify } from '../../src/utils/verify';

...actual,
getDIDDoc: jest.fn()
getDidDocPublicKeys: jest.fn()
};

@@ -33,3 +33,3 @@ });

const mockGetDIDDoc = getDIDDoc as jest.Mock;
const mockGetDidDocKeys = getDidDocPublicKeys as jest.Mock;
const mockDoVerify = doVerify as jest.Mock;

@@ -81,3 +81,3 @@ const mockMakeNetworkRequest = makeNetworkRequest as jest.Mock;

const headers = { 'x-auth-token': dummyAuthToken };
mockGetDIDDoc.mockResolvedValue({ body: dummyDidDoc, headers });
mockGetDidDocKeys.mockResolvedValue({ body: [dummyDidDoc.publicKey], authToken: dummyAuthToken });
mockMakeNetworkRequest.mockResolvedValue({ body: { success: true }, headers });

@@ -101,3 +101,3 @@ });

it('gets the holder did', () => {
expect(mockGetDIDDoc).toBeCalled();
expect(mockGetDidDocKeys).toBeCalled();
});

@@ -121,3 +121,3 @@

mockMakeNetworkRequest.mockResolvedValueOnce(dummyApiResponse);
mockGetDIDDoc.mockResolvedValue({ body: dummySubjectDidDoc });
mockGetDidDocKeys.mockResolvedValue({ body: [dummySubjectDidDoc.publicKey], authToken: dummyAuthToken });
const dummyNoPresentationLocal = await makeDummyPresentation({ context: [], type: ['NoPresentation', 'NoPresentation'], verifiableCredential: [] });

@@ -124,0 +124,0 @@ response = await callVerifyNoPresentation(dummyNoPresentationLocal, verifier, authHeader);

@@ -1,13 +0,10 @@

import { Presentation, VerifiedStatus, UnumDto, CustError } from '../../src/index';
import { UnumDto, CustError, checkCredentialStatuses } from '../../src/index';
import { verifyCredential } from '../../src/verifier/verifyCredential';
import { isCredentialExpired } from '../../src/verifier/isCredentialExpired';
import { checkCredentialStatus } from '../../src/verifier/checkCredentialStatus';
import { dummyAuthToken, dummyIssuerDid, dummyRsaPrivateKey, dummyRsaPublicKey, dummyVerifierDid, makeDummyCredential, makeDummyDidDocument, makeDummyPresentation, makeDummyPresentationRequestResponse, makeDummyUnsignedCredential, makeDummyUnsignedPresentation, makeDummyUnsignedPresentationRequest } from './mocks';
import { encrypt, encryptBytes } from '@unumid/library-crypto';
import { omit } from 'lodash';
import { dummyAuthToken, dummyRsaPrivateKey, dummyRsaPublicKey, makeDummyCredential, makeDummyDidDocument, makeDummyPresentation, makeDummyPresentationRequestResponse, makeDummyUnsignedCredential, makeDummyUnsignedPresentation, makeDummyUnsignedPresentationRequest } from './mocks';
import { encryptBytes } from '@unumid/library-crypto';
import { DecryptedPresentation } from '../../src/types';
import { verifyPresentation } from '../../src/verifier/verifyPresentation';
import { verifyNoPresentationHelper } from '../../src/verifier/verifyNoPresentationHelper';
import { JSONObj, PresentationPb, PresentationRequestDto, PresentationRequestRepoDto } from '@unumid/types';
import { getDIDDoc } from '../../src/utils/didHelper';
import { JSONObj, PresentationPb, PresentationRequestRepoDto } from '@unumid/types';
import { getDidDocPublicKeys } from '../../src/utils/didHelper';
import { getUUID } from '../../src/utils/helpers';

@@ -18,2 +15,3 @@ import { makeNetworkRequest } from '../../src/utils/networkRequestHelper';

import { extractPresentationRequest, getPresentationRequest } from '../../src/verifier/getPresentationRequest';
import { getCredentialStatusFromMap } from '../../src/utils/getCredentialStatusFromMap';

@@ -32,3 +30,3 @@ jest.mock('../../src/verifier/getPresentationRequest', () => {

...actual,
getDIDDoc: jest.fn()
getDidDocPublicKeys: jest.fn()
};

@@ -52,8 +50,10 @@ });

jest.mock('../../src/verifier/isCredentialExpired');
jest.mock('../../src/verifier/checkCredentialStatus');
jest.mock('../../src/verifier/checkCredentialStatuses');
jest.mock('../../src/utils/getCredentialStatusFromMap');
const mockVerifyCredential = verifyCredential as jest.Mock;
const mockIsCredentialExpired = isCredentialExpired as jest.Mock;
const mockCheckCredentialStatus = checkCredentialStatus as jest.Mock;
const mockGetDIDDoc = getDIDDoc as jest.Mock;
const mockCheckCredentialStatuses = checkCredentialStatuses as jest.Mock;
const mockGetCredentialStatusFromMap = getCredentialStatusFromMap as jest.Mock;
const mockGetDidDocKeys = getDidDocPublicKeys as jest.Mock;
const mockGetPresentationRequest = getPresentationRequest as jest.Mock;

@@ -194,3 +194,3 @@ const mockDoVerify = doVerify as jest.Mock;

const dummyResponseHeaders = { 'x-auth-token': dummyAuthToken };
mockGetDIDDoc.mockResolvedValue({ body: dummySubjectDidDoc, headers: dummyResponseHeaders });
mockGetDidDocKeys.mockResolvedValue({ body: [dummySubjectDidDoc.publicKey], authToken: dummyAuthToken });
mockGetPresentationRequest.mockResolvedValue({ body: presentationRequestDtoResponse, headers: dummyResponseHeaders });

@@ -200,3 +200,4 @@ mockDoVerify.mockReturnValueOnce(true);

mockIsCredentialExpired.mockReturnValue(false);
mockCheckCredentialStatus.mockReturnValue({ authToken: dummyAuthToken, body: { status: 'valid' } });
mockCheckCredentialStatuses.mockReturnValue({ authToken: dummyAuthToken, body: { credentialId: { status: 'valid' } } });
mockGetCredentialStatusFromMap.mockReturnValue({ status: 'valid' });
mockMakeNetworkRequest.mockResolvedValue({ body: { success: true }, headers: dummyResponseHeaders });

@@ -208,3 +209,3 @@ response = await callVerifyEncryptedPresentation(context, type, verifiableCredentials, presentationRequestId, proof, verifier, authHeader, presentationRequestDto);

it('gets the subject did document', () => {
expect(mockGetDIDDoc).toBeCalled();
expect(mockGetDidDocKeys).toBeCalled();
});

@@ -222,3 +223,3 @@

verifiableCredentials.forEach((vc) => {
expect(mockVerifyCredential).toBeCalledWith(vc, authHeader);
expect(mockVerifyCredential).toBeCalledWith(authHeader, vc);
});

@@ -235,3 +236,3 @@ });

verifiableCredentials.forEach((vc) => {
expect(mockCheckCredentialStatus).toBeCalledWith(authHeader, vc.id);
expect(mockCheckCredentialStatuses).toBeCalledWith(authHeader, [vc.id]);
});

@@ -268,3 +269,3 @@ });

const dummyResponseHeaders = { 'x-auth-token': dummyAuthToken };
mockGetDIDDoc.mockResolvedValue({ body: dummySubjectDidDoc, headers: dummyResponseHeaders });
mockGetDidDocKeys.mockResolvedValue({ body: [dummySubjectDidDoc.publicKey], authToken: dummyAuthToken });
mockGetPresentationRequest.mockResolvedValue({ body: presentationRequestDtoResponse, headers: dummyResponseHeaders });

@@ -274,3 +275,4 @@ mockDoVerify.mockReturnValueOnce(true);

mockIsCredentialExpired.mockReturnValue(false);
mockCheckCredentialStatus.mockReturnValue({ authToken: dummyAuthToken, body: { status: 'valid' } });
mockCheckCredentialStatuses.mockReturnValue({ authToken: dummyAuthToken, body: { credentialId: { status: 'valid' } } });
mockGetCredentialStatusFromMap.mockReturnValue({ status: 'valid' });
mockMakeNetworkRequest.mockResolvedValue({ body: { success: true }, headers: dummyResponseHeaders });

@@ -282,3 +284,3 @@ response = await callVerifyEncryptedPresentation(context, type, verifiableCredentials, presentationRequestId, proof, verifier, authHeader);

it('gets the subject did document', () => {
expect(mockGetDIDDoc).toBeCalled();
expect(mockGetDidDocKeys).toBeCalled();
});

@@ -296,3 +298,3 @@

verifiableCredentials.forEach((vc) => {
expect(mockVerifyCredential).toBeCalledWith(vc, authHeader);
expect(mockVerifyCredential).toBeCalledWith(authHeader, vc);
});

@@ -309,3 +311,3 @@ });

verifiableCredentials.forEach((vc) => {
expect(mockCheckCredentialStatus).toBeCalledWith(authHeader, vc.id);
expect(mockCheckCredentialStatuses).toBeCalledWith(authHeader, [vc.id]);
});

@@ -329,4 +331,3 @@ });

const dummyResponseHeaders = { 'x-auth-token': dummyAuthToken };
mockGetDIDDoc.mockResolvedValueOnce({ body: dummySubjectDidDoc, headers: dummyResponseHeaders });
mockGetDIDDoc.mockResolvedValueOnce({ body: dummySubjectDidDoc, headers: dummyResponseHeaders });
mockGetDidDocKeys.mockResolvedValue({ body: [dummySubjectDidDoc.publicKey], headers: dummyResponseHeaders });
mockGetPresentationRequest.mockResolvedValueOnce({ body: presentationRequestDtoResponse, headers: dummyResponseHeaders });

@@ -336,3 +337,4 @@ mockDoVerify.mockReturnValueOnce(false);

mockIsCredentialExpired.mockReturnValue(true);
mockCheckCredentialStatus.mockReturnValue({ authToken: dummyAuthToken, body: false });
mockCheckCredentialStatuses.mockReturnValue({ authToken: dummyAuthToken, body: { credentialId: { status: 'valid' } } });
mockGetCredentialStatusFromMap.mockReturnValue({ status: 'valid' });
verifiableCredentials[0].proof.verificationMethod = proof.verificationMethod;

@@ -348,3 +350,3 @@ response = await callVerifyEncryptedPresentation(context, type, verifiableCredentials, presentationRequestId, proof, verifier, authHeader, presentationRequestDto);

it('gets the subject did document', () => {
expect(mockGetDIDDoc).toBeCalled();
expect(mockGetDidDocKeys).toBeCalled();
});

@@ -361,16 +363,18 @@

it('returns a 404 status code if the did document has no public keys', async () => {
const dummyDidDocWithoutKeys = {
// ...await makeDummyDidDocument(),
publicKey: []
};
const dummyResponseHeaders = { 'x-auth-token': dummyAuthToken };
mockGetDIDDoc.mockResolvedValueOnce({ body: dummyDidDocWithoutKeys, headers: dummyResponseHeaders });
const response = await callVerifyEncryptedPresentation(context, type, verifiableCredentials, presentationRequestId, proof, verifier, authHeader, presentationRequestDto);
expect(response.body.isVerified).toBe(false);
expect(response.body.message).toBe('Public key not found for the DID associated with the proof.verificationMethod');
});
// it('returns a 404 status code if the did document has no public keys', async () => {
// const dummyDidDocWithoutKeys = {
// // ...await makeDummyDidDocument(),
// publicKey: []
// };
// const dummyResponseHeaders = { 'x-auth-token': dummyAuthToken };
// mockGetDidDocKeys.mockResolvedValue({ body: [], authToken: dummyAuthToken });
// const response = await callVerifyEncryptedPresentation(context, type, verifiableCredentials, presentationRequestId, proof, verifier, authHeader, presentationRequestDto);
// expect(response.body.isVerified).toBe(false);
// expect(response.body.message).toBe('Public key not found for the DID associated with the proof.verificationMethod');
// });
it('returns a 404 status code if the did document is not found', async () => {
mockGetDIDDoc.mockResolvedValueOnce(new CustError(404, 'DID Document not found.'));
mockGetDidDocKeys.mockImplementation(() => {
throw new CustError(404, 'DID Document not found.');
});

@@ -445,3 +449,3 @@ try {

const headers = { 'x-auth-token': dummyAuthToken };
mockGetDIDDoc.mockResolvedValue({ body: dummyDidDoc, headers });
mockGetDidDocKeys.mockResolvedValue({ body: [dummyDidDoc.publicKey], authToken: dummyAuthToken });
mockGetPresentationRequest.mockResolvedValueOnce({ body: presentationRequestDtoResponse, headers: headers });

@@ -479,3 +483,3 @@ mockMakeNetworkRequest.mockResolvedValue({ body: { success: true }, headers });

const dummyResponseHeaders = { 'x-auth-token': dummyAuthToken };
mockGetDIDDoc.mockResolvedValue({ body: dummySubjectDidDoc, headers: dummyResponseHeaders });
mockGetDidDocKeys.mockResolvedValue({ body: [dummySubjectDidDoc.publicKey], authToken: dummyAuthToken });
mockGetPresentationRequest.mockResolvedValueOnce({ body: presentationRequestDtoResponse, headers: dummyResponseHeaders });

@@ -485,3 +489,4 @@ mockDoVerify.mockReturnValueOnce(true);

mockIsCredentialExpired.mockReturnValue(false);
mockCheckCredentialStatus.mockReturnValue({ authToken: dummyAuthToken, body: { status: 'valid' } });
mockCheckCredentialStatuses.mockReturnValue({ authToken: dummyAuthToken, body: { credentialId: { status: 'valid' } } });
mockGetCredentialStatusFromMap.mockReturnValue({ status: 'valid' });
mockMakeNetworkRequest.mockResolvedValue({ body: { success: true }, headers: dummyResponseHeaders });

@@ -551,3 +556,3 @@ });

const headers = { 'x-auth-token': dummyAuthToken };
mockGetDIDDoc.mockResolvedValue({ body: dummyDidDoc, headers });
mockGetDidDocKeys.mockResolvedValue({ body: [dummyDidDoc.publicKey], authToken: dummyAuthToken });
mockGetPresentationRequest.mockResolvedValueOnce({ body: presentationRequestDtoResponse, headers: headers });

@@ -566,3 +571,3 @@ // mockMakeNetworkRequest.mockImplementation(() => { throw new Error('test'); });

const headers = { 'x-auth-token': dummyAuthToken };
mockGetDIDDoc.mockResolvedValue({ body: dummyDidDoc, headers });
mockGetDidDocKeys.mockResolvedValue({ body: [dummyDidDoc.publicKey], authToken: dummyAuthToken });
mockMakeNetworkRequest.mockImplementation(() => { throw new Error('test'); });

@@ -569,0 +574,0 @@ mockDoVerify.mockReturnValueOnce(false);

@@ -1,8 +0,7 @@

import { verifyNoPresentationHelper } from '../../src/verifier/verifyNoPresentationHelper';
import { getUUID } from '../../src/utils/helpers';
import { PresentationPb, JSONObj, Presentation } from '@unumid/types';
import { checkCredentialStatus, UnumDto, VerifiedStatus, CustError, verifyPresentation } from '../../src';
import { getDIDDoc } from '../../src/utils/didHelper';
import { PresentationPb, JSONObj } from '@unumid/types';
import { UnumDto, VerifiedStatus, CustError, checkCredentialStatuses } from '../../src';
import { getDidDocPublicKeys } from '../../src/utils/didHelper';
import { makeNetworkRequest } from '../../src/utils/networkRequestHelper';
import { getCredentialStatusFromMap } from '../../src/utils/getCredentialStatusFromMap';
import { doVerify } from '../../src/utils/verify';

@@ -13,3 +12,2 @@ import { isCredentialExpired } from '../../src/verifier/isCredentialExpired';

import { makeDummyPresentation, makeDummyUnsignedCredential, makeDummyCredential, dummyCredentialRequest, makeDummyUnsignedPresentationRequest, makeDummyPresentationRequestResponse, makeDummyUnsignedPresentation, makeDummyDidDocument, dummyAuthToken, dummyIssuerDid } from './mocks';
import { encryptBytes } from '@unumid/library-crypto';

@@ -20,3 +18,3 @@ jest.mock('../../src/utils/didHelper', () => {

...actual,
getDIDDoc: jest.fn()
getDidDocPublicKeys: jest.fn()
};

@@ -40,8 +38,10 @@ });

jest.mock('../../src/verifier/isCredentialExpired');
jest.mock('../../src/verifier/checkCredentialStatus');
jest.mock('../../src/verifier/checkCredentialStatuses');
jest.mock('../../src/utils/getCredentialStatusFromMap');
const mockVerifyCredential = verifyCredential as jest.Mock;
const mockIsCredentialExpired = isCredentialExpired as jest.Mock;
const mockCheckCredentialStatus = checkCredentialStatus as jest.Mock;
const mockGetDIDDoc = getDIDDoc as jest.Mock;
const mockCheckCredentialStatuses = checkCredentialStatuses as jest.Mock;
const mockGetCredentialStatusFromMap = getCredentialStatusFromMap as jest.Mock;
const mockGetDidDocKeys = getDidDocPublicKeys as jest.Mock;
const mockDoVerify = doVerify as jest.Mock;

@@ -166,7 +166,8 @@ const mockMakeNetworkRequest = makeNetworkRequest as jest.Mock;

const dummyResponseHeaders = { 'x-auth-token': dummyAuthToken };
mockGetDIDDoc.mockResolvedValueOnce({ body: dummySubjectDidDoc, headers: dummyResponseHeaders });
mockGetDidDocKeys.mockResolvedValue({ authToken: dummyAuthToken, body: [dummySubjectDidDoc.publicKey] });
mockDoVerify.mockResolvedValue(true);
mockVerifyCredential.mockResolvedValue({ authToken: dummyAuthToken, body: true });
mockIsCredentialExpired.mockReturnValue(false);
mockCheckCredentialStatus.mockReturnValue({ authToken: dummyAuthToken, body: { status: 'valid' } });
mockCheckCredentialStatuses.mockReturnValue({ authToken: dummyAuthToken, body: { credentialId: { status: 'valid' } } });
mockGetCredentialStatusFromMap.mockReturnValue({ status: 'valid' });
mockMakeNetworkRequest.mockResolvedValue({ body: { success: true }, headers: dummyResponseHeaders });

@@ -182,3 +183,3 @@ response = await callVerifyPresentation(context, type, verifiableCredential, presentationRequestId, proof, verifier, authHeader, credentialRequests);

it('gets the subject did document', () => {
expect(mockGetDIDDoc).toBeCalled();
expect(mockGetDidDocKeys).toBeCalled();
});

@@ -192,3 +193,3 @@

verifiableCredential.forEach((vc) => {
expect(mockVerifyCredential).toBeCalledWith(vc, authHeader);
expect(mockVerifyCredential).toBeCalledWith(authHeader, vc);
});

@@ -205,3 +206,3 @@ });

verifiableCredential.forEach((vc) => {
expect(mockCheckCredentialStatus).toBeCalledWith(authHeader, vc.id);
expect(mockCheckCredentialStatuses).toBeCalledWith(authHeader, [vc.id]);
});

@@ -223,4 +224,5 @@ });

mockMakeNetworkRequest.mockResolvedValueOnce(dummyApiResponse);
mockGetDIDDoc.mockResolvedValue({ body: dummySubjectDidDoc, authToken: undefined });
mockCheckCredentialStatus.mockReturnValue({ authToken: undefined, body: { status: 'valid' } });
mockGetDidDocKeys.mockResolvedValue({ authToken: undefined, body: [dummySubjectDidDoc.publicKey] });
mockCheckCredentialStatuses.mockReturnValue({ authToken: dummyAuthToken, body: { credentialId: { status: 'valid' } } });
mockGetCredentialStatusFromMap.mockReturnValue({ status: 'valid' });
mockVerifyCredential.mockResolvedValue({ authToken: undefined, body: true });

@@ -243,7 +245,8 @@ mockDoVerify.mockReturnValueOnce(true);

const dummyResponseHeaders = { 'x-auth-token': dummyAuthToken };
mockGetDIDDoc.mockResolvedValueOnce({ body: dummySubjectDidDoc, headers: dummyResponseHeaders });
mockGetDidDocKeys.mockResolvedValue({ authToken: dummyAuthToken, body: [dummySubjectDidDoc.publicKey] });
mockDoVerify.mockResolvedValue(true);
mockVerifyCredential.mockResolvedValue({ authToken: dummyAuthToken, body: true });
mockIsCredentialExpired.mockReturnValue(false);
mockCheckCredentialStatus.mockReturnValue({ authToken: dummyAuthToken, body: { status: 'valid' } });
mockCheckCredentialStatuses.mockReturnValue({ authToken: dummyAuthToken, body: { credentialId: { status: 'valid' } } });
mockGetCredentialStatusFromMap.mockReturnValue({ status: 'valid' });
mockMakeNetworkRequest.mockResolvedValue({ body: { success: true }, headers: dummyResponseHeaders });

@@ -259,3 +262,3 @@ response = await callVerifyPresentation(context, type, verifiableCredential, presentationRequestId, proof, verifier, authHeader, credentialRequests);

it('gets the subject did document', () => {
expect(mockGetDIDDoc).toBeCalled();
expect(mockGetDidDocKeys).toBeCalled();
});

@@ -269,3 +272,3 @@

verifiableCredential.forEach((vc) => {
expect(mockVerifyCredential).toBeCalledWith(vc, authHeader);
expect(mockVerifyCredential).toBeCalledWith(authHeader, vc);
});

@@ -282,3 +285,3 @@ });

verifiableCredential.forEach((vc) => {
expect(mockCheckCredentialStatus).toBeCalledWith(authHeader, vc.id);
expect(mockCheckCredentialStatuses).toBeCalledWith(authHeader, [vc.id]);
});

@@ -300,4 +303,5 @@ });

mockMakeNetworkRequest.mockResolvedValueOnce(dummyApiResponse);
mockGetDIDDoc.mockResolvedValue({ body: dummySubjectDidDoc, authToken: undefined });
mockCheckCredentialStatus.mockReturnValue({ authToken: undefined, body: { status: 'valid' } });
mockGetDidDocKeys.mockResolvedValue({ authToken: undefined, body: [dummySubjectDidDoc.publicKey] });
mockCheckCredentialStatuses.mockReturnValue({ authToken: dummyAuthToken, body: { credentialId: { status: 'valid' } } });
mockGetCredentialStatusFromMap.mockReturnValue({ status: 'valid' });
mockVerifyCredential.mockResolvedValue({ authToken: undefined, body: true });

@@ -322,3 +326,4 @@ mockDoVerify.mockReturnValueOnce(true);

mockIsCredentialExpired.mockReturnValue(true);
mockCheckCredentialStatus.mockReturnValue({ authToken: dummyAuthToken, body: { status: 'revoked' } });
mockCheckCredentialStatuses.mockReturnValue({ authToken: dummyAuthToken, body: { credentialId: { status: 'valid' } } });
mockGetCredentialStatusFromMap.mockReturnValue({ status: 'valid' });
verifiableCredential[0].proof.verificationMethod = proof.verificationMethod;

@@ -334,6 +339,6 @@ });

const dummyResponseHeaders = { 'x-auth-token': dummyAuthToken };
mockGetDIDDoc.mockResolvedValue({ body: dummySubjectDidDoc, headers: dummyResponseHeaders });
mockGetDidDocKeys.mockResolvedValue({ authToken: dummyAuthToken, body: [dummySubjectDidDoc.publicKey] });
response = await callVerifyPresentationManual(context, type, verifiableCredential, presentationRequestId, proof, verifier, authHeader, credentialRequests);
verStatus = response.body.isVerified;
expect(mockGetDIDDoc).toBeCalled();
expect(mockGetDidDocKeys).toBeCalled();
});

@@ -356,10 +361,20 @@

const dummyResponseHeaders = { 'x-auth-token': dummyAuthToken };
mockGetDIDDoc.mockResolvedValue({ body: dummyDidDocWithoutKeys, headers: dummyResponseHeaders });
const response = await callVerifyPresentation(context, type, verifiableCredential, presentationRequestId, proof, verifier, authHeader, credentialRequests);
expect(response.body.isVerified).toBe(false);
expect(response.body.message).toBe('Public key not found for the DID associated with the proof.verificationMethod');
// mockGetDidDocKeys.mockResolvedValue({ authToken: dummyAuthToken, body: [] });
mockGetDidDocKeys.mockImplementation(() => {
throw new CustError(404, 'Public key not found for the DID associated with the proof.verificationMethod');
});
try {
const response = await callVerifyPresentation(context, type, verifiableCredential, presentationRequestId, proof, verifier, authHeader, credentialRequests);
} catch (e) {
expect(e.message).toBe('Public key not found for the DID associated with the proof.verificationMethod');
}
// expect(response.body.isVerified).toBe(false);
// expect(response.body.message).toBe('Exception verifying presentation signature. Public key not found for the DID associated with the proof.verificationMethod');
});
it('returns a 404 status code if the did document is not found', async () => {
mockGetDIDDoc.mockResolvedValue(new CustError(404, 'DID Document not found.'));
mockGetDidDocKeys.mockImplementation(() => {
throw new CustError(404, 'DID Document not found.');
});

@@ -380,3 +395,3 @@ try {

const dummyResponseHeaders = { 'x-auth-token': dummyAuthToken };
mockGetDIDDoc.mockResolvedValueOnce({ body: dummyDidDocWithoutKeys, headers: dummyResponseHeaders });
mockGetDidDocKeys.mockResolvedValue({ authToken: dummyAuthToken, body: [] });

@@ -630,7 +645,8 @@ const response = await verifyPresentationHelper(authHeader, presentation, 'fakeVerifierDid', credentialRequests);

const dummyResponseHeaders = { 'x-auth-token': dummyAuthToken };
mockGetDIDDoc.mockResolvedValueOnce({ body: dummySubjectDidDoc, headers: dummyResponseHeaders });
mockGetDidDocKeys.mockResolvedValue({ authToken: dummyAuthToken, body: [dummySubjectDidDoc.publicKey] });
mockDoVerify.mockResolvedValue(true);
mockVerifyCredential.mockResolvedValue({ authToken: dummyAuthToken, body: true });
mockIsCredentialExpired.mockReturnValue(false);
mockCheckCredentialStatus.mockReturnValue({ authToken: dummyAuthToken, body: { status: 'valid' } });
mockCheckCredentialStatuses.mockReturnValue({ authToken: dummyAuthToken, body: { credentialId: { status: 'valid' } } });
mockGetCredentialStatusFromMap.mockReturnValue({ status: 'valid' });
mockMakeNetworkRequest.mockResolvedValue({ body: { success: true }, headers: dummyResponseHeaders });

@@ -637,0 +653,0 @@ });

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc