@web5/credentials
Version:
Verifiable Credentials
284 lines • 13.3 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.VerifiablePresentation = exports.DEFAULT_VP_TYPE = void 0;
var crypto_1 = require("@web5/crypto");
var jwt_js_1 = require("./jwt.js");
var validators_js_1 = require("./validators.js");
var verifiable_credential_js_1 = require("./verifiable-credential.js");
/** The default type for a Verifiable Presentation. */
exports.DEFAULT_VP_TYPE = 'VerifiablePresentation';
/**
* `VerifiablePresentation` is a tamper-evident presentation encoded in such a way that authorship of the data
* can be trusted after a process of cryptographic verification.
* [W3C Verifiable Presentation Data Model](https://www.w3.org/TR/vc-data-model/#presentations).
*
* It provides functionalities to sign, verify, and create presentations, offering a concise API to
* work with JWT representations of verifiable presentations and ensuring that the signatures
* and claims within those JWTs can be validated.
*
* @property vpDataModel The [vpDataModel] instance representing the core data model of a verifiable presentation.
*/
var VerifiablePresentation = /** @class */ (function () {
function VerifiablePresentation(vpDataModel) {
this.vpDataModel = vpDataModel;
}
Object.defineProperty(VerifiablePresentation.prototype, "type", {
/** The type of the Verifiable Presentation. */
get: function () {
return this.vpDataModel.type[this.vpDataModel.type.length - 1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(VerifiablePresentation.prototype, "holder", {
/** The holder of the Verifiable Presentation. */
get: function () {
return this.vpDataModel.holder.toString();
},
enumerable: false,
configurable: true
});
Object.defineProperty(VerifiablePresentation.prototype, "verifiableCredential", {
/** The verifiable credentials contained in the Verifiable Presentation. */
get: function () {
return this.vpDataModel.verifiableCredential;
},
enumerable: false,
configurable: true
});
/**
* Signs the verifiable presentation and returns it as a signed JWT.
*
* @example
* ```ts
* const vpJwt = verifiablePresentation.sign({ did: myDid });
* ```
*
* @param options - The sign options used to sign the presentation.
* @returns The JWT representing the signed verifiable presentation.
*/
VerifiablePresentation.prototype.sign = function (options) {
return __awaiter(this, void 0, void 0, function () {
var vpJwt;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, jwt_js_1.Jwt.sign({
signerDid: options.did,
payload: {
vp: this.vpDataModel,
iss: options.did.uri,
sub: options.did.uri,
jti: this.vpDataModel.id,
iat: Math.floor(Date.now() / 1000)
}
})];
case 1:
vpJwt = _a.sent();
return [2 /*return*/, vpJwt];
}
});
});
};
/**
* Converts the current object to its JSON representation.
*
* @returns The JSON representation of the object.
*/
VerifiablePresentation.prototype.toString = function () {
return JSON.stringify(this.vpDataModel);
};
/**
* Create a [VerifiablePresentation] based on the provided parameters.
*
* @example
* ```ts
* const vp = await VerifiablePresentation.create({
* type: 'PresentationSubmission',
* holder: 'did:ex:holder',
* vcJwts: vcJwts,
* additionalData: { 'arbitrary': 'data' }
* })
* ```
*
* @param options - The options to use when creating the Verifiable Presentation.
* @returns A [VerifiablePresentation] instance.
*/
VerifiablePresentation.create = function (options) {
return __awaiter(this, void 0, void 0, function () {
var type, holder, vcJwts, additionalData, jsonData, vpDataModel;
return __generator(this, function (_a) {
type = options.type, holder = options.holder, vcJwts = options.vcJwts, additionalData = options.additionalData;
if (additionalData) {
jsonData = JSON.parse(JSON.stringify(additionalData));
if (typeof jsonData !== 'object') {
throw new Error('Expected data to be parseable into a JSON object');
}
}
if (!holder) {
throw new Error('Holder must be defined');
}
if (typeof holder !== 'string') {
throw new Error('Holder must be of type string');
}
vpDataModel = __assign({ '@context': [verifiable_credential_js_1.DEFAULT_VC_CONTEXT], type: Array.isArray(type)
? __spreadArray([exports.DEFAULT_VP_TYPE], type, true) : (type ? [exports.DEFAULT_VP_TYPE, type] : [exports.DEFAULT_VP_TYPE]), id: "urn:uuid:".concat(crypto_1.CryptoUtils.randomUuid()), holder: holder, verifiableCredential: vcJwts }, additionalData);
validatePayload(vpDataModel);
return [2 /*return*/, new VerifiablePresentation(vpDataModel)];
});
});
};
/**
* Verifies the integrity and authenticity of a Verifiable Presentation (VP) encoded as a JSON Web Token (JWT).
*
* This function performs several crucial validation steps to ensure the trustworthiness of the provided VP:
* - 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.
*
* @example
* ```ts
* try {
* VerifiablePresentation.verify({ vpJwt: signedVpJwt })
* console.log("VC Verification successful!")
* } catch (e: Error) {
* console.log("VC Verification failed: ${e.message}")
* }
* ```
*
* @param vpJwt The Verifiable Presentation 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.
*/
VerifiablePresentation.verify = function (_a) {
return __awaiter(this, arguments, void 0, function (_b) {
var payload, vp, _i, _c, vcJwt;
var vpJwt = _b.vpJwt;
return __generator(this, function (_d) {
switch (_d.label) {
case 0: return [4 /*yield*/, jwt_js_1.Jwt.verify({ jwt: vpJwt })];
case 1:
payload = (_d.sent()).payload;
vp = payload['vp'];
if (!vp) {
throw new Error('vp property missing.');
}
validatePayload(vp);
_i = 0, _c = vp.verifiableCredential;
_d.label = 2;
case 2:
if (!(_i < _c.length)) return [3 /*break*/, 5];
vcJwt = _c[_i];
return [4 /*yield*/, verifiable_credential_js_1.VerifiableCredential.verify({ vcJwt: vcJwt })];
case 3:
_d.sent();
_d.label = 4;
case 4:
_i++;
return [3 /*break*/, 2];
case 5: return [2 /*return*/, {
/** The issuer of the VP */
issuer: payload.iss,
/** The subject of the VP. */
subject: payload.sub,
/** The VP data model object. */
vp: payload['vp']
}];
}
});
});
};
/**
* Parses a JWT into a [VerifiablePresentation] instance.
*
* @example
* ```ts
* const vp = VerifiablePresentation.parseJwt({ vpJwt: signedVpJwt })
* ```
*
* @param vpJwt The verifiable presentation JWT as a [String].
* @returns A [VerifiablePresentation] instance derived from the JWT.
*/
VerifiablePresentation.parseJwt = function (_a) {
var vpJwt = _a.vpJwt;
var parsedJwt = jwt_js_1.Jwt.parse({ jwt: vpJwt });
var vpDataModel = parsedJwt.decoded.payload['vp'];
if (!vpDataModel) {
throw Error('Jwt payload missing vp property');
}
return new VerifiablePresentation(vpDataModel);
};
return VerifiablePresentation;
}());
exports.VerifiablePresentation = VerifiablePresentation;
/**
* Validates the structure and integrity of a Verifiable Presentation payload.
*
* @param vp - The Verifiable Presentaation object to validate.
* @throws Error if any validation check fails.
*/
function validatePayload(vp) {
validators_js_1.SsiValidator.validateContext(vp['@context']);
validators_js_1.SsiValidator.validateVpType(vp.type);
}
//# sourceMappingURL=verifiable-presentation.js.map