@web5/credentials
Version:
Verifiable Credentials
343 lines • 19.4 kB
JavaScript
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.VerifiableCredential = exports.DEFAULT_VC_TYPE = exports.DEFAULT_VC_CONTEXT = void 0;
var crypto_1 = require("@web5/crypto");
var jwt_js_1 = require("./jwt.js");
var validators_js_1 = require("./validators.js");
var utils_js_1 = require("./utils.js");
var status_list_credential_js_1 = require("./status-list-credential.js");
/** The default Verifiable Credential context. */
exports.DEFAULT_VC_CONTEXT = 'https://www.w3.org/2018/credentials/v1';
/** The default Verifiable Credential type. */
exports.DEFAULT_VC_TYPE = 'VerifiableCredential';
/**
* `VerifiableCredential` represents a digitally verifiable credential according to the
* [W3C Verifiable Credentials Data Model](https://www.w3.org/TR/vc-data-model/).
*
* It provides functionalities to sign, verify, and create credentials, offering a concise API to
* work with JWT representations of verifiable credentials and ensuring that the signatures
* and claims within those JWTs can be validated.
*
* @property vcDataModel The [VcDataModel] instance representing the core data model of a verifiable credential.
*/
var VerifiableCredential = /** @class */ (function () {
function VerifiableCredential(vcDataModel) {
this.vcDataModel = vcDataModel;
}
Object.defineProperty(VerifiableCredential.prototype, "type", {
/** The type of the credential. */
get: function () {
return this.vcDataModel.type[this.vcDataModel.type.length - 1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(VerifiableCredential.prototype, "issuer", {
/** The issuer of the credential. */
get: function () {
return this.vcDataModel.issuer.toString();
},
enumerable: false,
configurable: true
});
Object.defineProperty(VerifiableCredential.prototype, "subject", {
/** The subject of the credential. */
get: function () {
if (Array.isArray(this.vcDataModel.credentialSubject)) {
return this.vcDataModel.credentialSubject[0].id;
}
else {
return this.vcDataModel.credentialSubject.id;
}
},
enumerable: false,
configurable: true
});
/**
* Signs the verifiable credential and returns it as a signed JWT.
*
* @example
* ```ts
* const vcJwt = verifiableCredential.sign({ did: myDid });
* ```
*
* @param options - The sign options used to sign the credential.
* @returns The JWT representing the signed verifiable credential.
*/
VerifiableCredential.prototype.sign = function (options) {
return __awaiter(this, void 0, void 0, function () {
var vcJwt;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, jwt_js_1.Jwt.sign({
signerDid: options.did,
payload: __assign({ vc: this.vcDataModel, nbf: Math.floor(new Date(this.vcDataModel.issuanceDate).getTime() / 1000), jti: this.vcDataModel.id, iss: options.did.uri, sub: this.subject, iat: Math.floor(Date.now() / 1000) }, (this.vcDataModel.expirationDate && {
exp: Math.floor(new Date(this.vcDataModel.expirationDate).getTime() / 1000),
}))
})];
case 1:
vcJwt = _a.sent();
return [2 /*return*/, vcJwt];
}
});
});
};
/**
* Converts the current object to its JSON representation.
*
* @returns The JSON representation of the object.
*/
VerifiableCredential.prototype.toString = function () {
return JSON.stringify(this.vcDataModel);
};
/**
* Create a [VerifiableCredential] based on the provided parameters.
*
* @example
* ```ts
* const vc = await VerifiableCredential.create({
* type: 'StreetCredibility',
* issuer: 'did:ex:issuer',
* subject: 'did:ex:subject',
* data: { 'arbitrary': 'data' }
* })
* ```
*
* @param options - The options to use when creating the Verifiable Credential.
* @returns A [VerifiableCredential] instance.
*/
VerifiableCredential.create = function (options) {
return __awaiter(this, void 0, void 0, function () {
var type, issuer, subject, data, issuanceDate, expirationDate, credentialStatus, credentialSchema, evidence, jsonData, credentialSubject, contexts, vcDataModel;
return __generator(this, function (_a) {
type = options.type, issuer = options.issuer, subject = options.subject, data = options.data, issuanceDate = options.issuanceDate, expirationDate = options.expirationDate, credentialStatus = options.credentialStatus, credentialSchema = options.credentialSchema, evidence = options.evidence;
jsonData = JSON.parse(JSON.stringify(data));
if (typeof jsonData !== 'object') {
throw new Error('Expected data to be parseable into a JSON object');
}
if (!issuer || !subject) {
throw new Error('Issuer and subject must be defined');
}
if (typeof issuer !== 'string' || typeof subject !== 'string') {
throw new Error('Issuer and subject must be of type string');
}
credentialSubject = __assign({ id: subject }, jsonData);
contexts = [exports.DEFAULT_VC_CONTEXT];
if (credentialStatus !== null) {
contexts.push(status_list_credential_js_1.DEFAULT_STATUS_LIST_VC_CONTEXT);
}
vcDataModel = __assign(__assign(__assign(__assign({ '@context': contexts, type: Array.isArray(type)
? __spreadArray([exports.DEFAULT_VC_TYPE], type, true) : (type ? [exports.DEFAULT_VC_TYPE, type] : [exports.DEFAULT_VC_TYPE]), id: "urn:uuid:".concat(crypto_1.CryptoUtils.randomUuid()), issuer: issuer, issuanceDate: issuanceDate || (0, utils_js_1.getCurrentXmlSchema112Timestamp)(), credentialSubject: credentialSubject }, (expirationDate && { expirationDate: expirationDate })), (credentialStatus && { credentialStatus: credentialStatus })), (credentialSchema && { credentialSchema: credentialSchema })), (evidence && { evidence: evidence }));
validatePayload(vcDataModel);
return [2 /*return*/, new VerifiableCredential(vcDataModel)];
});
});
};
/**
* Verifies the integrity and authenticity of a Verifiable Credential (VC) encoded as a JSON Web Token (JWT).
*
* This function performs several crucial validation steps to ensure the trustworthiness of the provided VC:
* - Parses and validates the structure of the JWT.
* - Ensures the presence of critical header elements `alg` and `kid` in the JWT header.
* - Resolves the Decentralized Identifier (DID) and retrieves the associated DID Document.
* - Validates the DID and establishes a set of valid verification method IDs.
* - Identifies the correct Verification Method from the DID Document based on the `kid` parameter.
* - Verifies the JWT's signature using the public key associated with the Verification Method.
*
* If any of these steps fail, the function will throw a [Error] with a message indicating the nature of the failure:
* - exp MUST represent the expirationDate property, encoded as a UNIX timestamp (NumericDate).
* - iss MUST represent the issuer property of a verifiable credential or the holder property of a verifiable presentation.
* - nbf MUST represent issuanceDate, encoded as a UNIX timestamp (NumericDate).
* - jti MUST represent the id property of the verifiable credential or verifiable presentation.
* - sub MUST represent the id property contained in the credentialSubject.
*
* Once the verifications are successful, when recreating the VC data model object, this function will:
* - If exp is present, the UNIX timestamp MUST be converted to an [XMLSCHEMA11-2] date-time, and MUST be used to set the value of the expirationDate property of credentialSubject of the new JSON object.
* - If iss is present, the value MUST be used to set the issuer property of the new credential JSON object or the holder property of the new presentation JSON object.
* - If nbf is present, the UNIX timestamp MUST be converted to an [XMLSCHEMA11-2] date-time, and MUST be used to set the value of the issuanceDate property of the new JSON object.
* - If sub is present, the value MUST be used to set the value of the id property of credentialSubject of the new credential JSON object.
* - If jti is present, the value MUST be used to set the value of the id property of the new JSON object.
*
* @example
* ```ts
* try {
* VerifiableCredential.verify({ vcJwt: signedVcJwt })
* console.log("VC Verification successful!")
* } catch (e: Error) {
* console.log("VC Verification failed: ${e.message}")
* }
* ```
* @param param - The parameters for the verification process.
* @param param.vcJwt The Verifiable Credential in JWT format as a [string].
* @throws Error if the verification fails at any step, providing a message with failure details.
* @throws Error if critical JWT header elements are absent.
*/
VerifiableCredential.verify = function (_a) {
return __awaiter(this, arguments, void 0, function (_b) {
var payload, exp, iss, nbf, jti, sub, vc, vcTyped;
var vcJwt = _b.vcJwt;
return __generator(this, function (_c) {
switch (_c.label) {
case 0: return [4 /*yield*/, jwt_js_1.Jwt.verify({ jwt: vcJwt })];
case 1:
payload = (_c.sent()).payload;
exp = payload.exp, iss = payload.iss, nbf = payload.nbf, jti = payload.jti, sub = payload.sub, vc = payload.vc;
if (!vc) {
throw new Error('vc property missing.');
}
vcTyped = payload['vc'];
// exp MUST represent the expirationDate property, encoded as a UNIX timestamp (NumericDate).
if (exp && vcTyped.expirationDate && exp !== Math.floor(new Date(vcTyped.expirationDate).getTime() / 1000)) {
throw new Error('Verification failed: exp claim does not match expirationDate');
}
// If exp is present, the UNIX timestamp MUST be converted to an [XMLSCHEMA11-2] date-time, and MUST be used to set the value of the expirationDate property of credentialSubject of the new JSON object.
if (exp) {
vcTyped.expirationDate = (0, utils_js_1.getXmlSchema112Timestamp)(exp);
}
if (!iss)
throw new Error('Verification failed: iss claim is required');
// iss MUST represent the issuer property of a verifiable credential or the holder property of a verifiable presentation.
if (iss !== vcTyped.issuer) {
throw new Error('Verification failed: iss claim does not match expected issuer');
}
// nbf cannot represent time in the future
if (nbf && nbf > Math.floor(Date.now() / 1000)) {
throw new Error('Verification failed: nbf claim is in the future');
}
// nbf MUST represent issuanceDate, encoded as a UNIX timestamp (NumericDate).
if (nbf && vcTyped.issuanceDate && nbf !== Math.floor(new Date(vcTyped.issuanceDate).getTime() / 1000)) {
throw new Error('Verification failed: nbf claim does not match issuanceDate');
}
// If nbf is present, the UNIX timestamp MUST be converted to an [XMLSCHEMA11-2] date-time, and MUST be used to set the value of the issuanceDate property of the new JSON object.
if (nbf) {
vcTyped.issuanceDate = (0, utils_js_1.getXmlSchema112Timestamp)(nbf);
}
// sub MUST represent the id property contained in the credentialSubject.
if (sub && !Array.isArray(vcTyped.credentialSubject) && sub !== vcTyped.credentialSubject.id) {
throw new Error('Verification failed: sub claim does not match credentialSubject.id');
}
// If sub is present, the value MUST be used to set the value of the id property of credentialSubject of the new credential JSON object.
if (sub && !Array.isArray(vcTyped.credentialSubject)) {
vcTyped.credentialSubject.id = sub;
}
// jti MUST represent the id property of the verifiable credential or verifiable presentation.
if (jti && jti !== vcTyped.id) {
throw new Error('Verification failed: jti claim does not match id');
}
if (jti) {
vcTyped.id = jti;
}
validatePayload(vcTyped);
if (!vcTyped.credentialSchema) return [3 /*break*/, 3];
return [4 /*yield*/, validators_js_1.SsiValidator.validateCredentialSchema(vcTyped)];
case 2:
_c.sent();
_c.label = 3;
case 3: return [2 /*return*/, {
/** The issuer of the VC. */
issuer: payload.iss,
/** The subject of the VC. */
subject: payload.sub,
/** The VC data model object. */
vc: vcTyped
}];
}
});
});
};
/**
* Parses a JWT into a [VerifiableCredential] instance.
*
* @example
* ```ts
* const vc = VerifiableCredential.parseJwt({ vcJwt: signedVcJwt })
* ```
*
* @param vcJwt The verifiable credential JWT as a [String].
* @returns A [VerifiableCredential] instance derived from the JWT.
*/
VerifiableCredential.parseJwt = function (_a) {
var vcJwt = _a.vcJwt;
var parsedJwt = jwt_js_1.Jwt.parse({ jwt: vcJwt });
var vcDataModel = parsedJwt.decoded.payload['vc'];
if (!vcDataModel) {
throw Error('Jwt payload missing vc property');
}
validatePayload(vcDataModel);
return new VerifiableCredential(vcDataModel);
};
return VerifiableCredential;
}());
exports.VerifiableCredential = VerifiableCredential;
/**
* Validates the structure and integrity of a Verifiable Credential payload.
*
* @param vc - The Verifiable Credential object to validate.
* @throws Error if any validation check fails.
*/
function validatePayload(vc) {
validators_js_1.SsiValidator.validateContext(vc['@context']);
validators_js_1.SsiValidator.validateVcType(vc.type);
validators_js_1.SsiValidator.validateCredentialSubject(vc.credentialSubject);
if (vc.issuanceDate)
validators_js_1.SsiValidator.validateTimestamp(vc.issuanceDate);
if (vc.expirationDate)
validators_js_1.SsiValidator.validateTimestamp(vc.expirationDate);
}
//# sourceMappingURL=verifiable-credential.js.map
;