@web5/credentials
Version:
Verifiable Credentials
212 lines • 11.1 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 };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Jwt = void 0;
var common_1 = require("@web5/common");
var crypto_1 = require("@web5/crypto");
var dids_1 = require("@web5/dids");
var crypto = new crypto_1.LocalKeyManager();
/**
* Class for handling Compact JSON Web Tokens (JWTs).
* This class provides methods to create, verify, and decode JWTs using various cryptographic algorithms.
* More information on JWTs can be found [here](https://datatracker.ietf.org/doc/html/rfc7519)
*/
var Jwt = /** @class */ (function () {
function Jwt() {
}
/**
* Creates a signed JWT.
*
* @example
* ```ts
* const jwt = await Jwt.sign({ signerDid: myDid, payload: myPayload });
* ```
*
* @param options - Parameters for JWT creation including signer DID and payload.
* @returns The compact JWT as a string.
*/
Jwt.sign = function (options) {
return __awaiter(this, void 0, void 0, function () {
var signerDid, payload, signer, vmId, header, base64UrlEncodedHeader, base64UrlEncodedPayload, toSign, toSignBytes, signatureBytes, base64UrlEncodedSignature;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
signerDid = options.signerDid, payload = options.payload;
return [4 /*yield*/, signerDid.getSigner()];
case 1:
signer = _a.sent();
vmId = signer.keyId;
if (vmId.charAt(0) === '#') {
vmId = "".concat(signerDid.uri).concat(vmId);
}
header = __assign({ alg: signer.algorithm, kid: vmId }, options.header);
base64UrlEncodedHeader = common_1.Convert.object(header).toBase64Url();
base64UrlEncodedPayload = common_1.Convert.object(payload).toBase64Url();
toSign = "".concat(base64UrlEncodedHeader, ".").concat(base64UrlEncodedPayload);
toSignBytes = common_1.Convert.string(toSign).toUint8Array();
return [4 /*yield*/, signer.sign({ data: toSignBytes })];
case 2:
signatureBytes = _a.sent();
base64UrlEncodedSignature = common_1.Convert.uint8Array(signatureBytes).toBase64Url();
return [2 /*return*/, "".concat(toSign, ".").concat(base64UrlEncodedSignature)];
}
});
});
};
/**
* Verifies a JWT.
*
* @example
* ```ts
* const verifiedJwt = await Jwt.verify({ jwt: myJwt });
* ```
*
* @param options - Parameters for JWT verification
* @returns Verified JWT information including signer DID, header, and payload.
*/
Jwt.verify = function (options) {
return __awaiter(this, void 0, void 0, function () {
var _a, decodedJwt, encodedJwt, dereferenceResult, verificationMethod, publicKeyJwk, signedData, signedDataBytes, signatureBytes, isSignatureValid;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_a = Jwt.parse({ jwt: options.jwt }), decodedJwt = _a.decoded, encodedJwt = _a.encoded;
if (decodedJwt.payload.exp && Math.floor(Date.now() / 1000) > decodedJwt.payload.exp) {
throw new Error("Verification failed: JWT is expired");
}
return [4 /*yield*/, Jwt.didResolver.dereference(decodedJwt.header.kid)];
case 1:
dereferenceResult = _b.sent();
if (dereferenceResult.dereferencingMetadata.error) {
throw new Error("Failed to resolve ".concat(decodedJwt.header.kid));
}
verificationMethod = dereferenceResult.contentStream;
if (!verificationMethod || !dids_1.utils.isDidVerificationMethod(verificationMethod)) { // ensure that appropriate verification method was found
throw new Error('Verification failed: Expected kid in JWT header to dereference a DID Document Verification Method');
}
publicKeyJwk = verificationMethod.publicKeyJwk;
if (!publicKeyJwk) { // ensure that Verification Method includes public key as a JWK.
throw new Error('Verification failed: Expected kid in JWT header to dereference to a DID Document Verification Method with publicKeyJwk');
}
if (publicKeyJwk.alg && (publicKeyJwk.alg !== decodedJwt.header.alg)) {
throw new Error('Verification failed: Expected alg in JWT header to match DID Document Verification Method alg');
}
signedData = "".concat(encodedJwt.header, ".").concat(encodedJwt.payload);
signedDataBytes = common_1.Convert.string(signedData).toUint8Array();
signatureBytes = common_1.Convert.base64Url(encodedJwt.signature).toUint8Array();
return [4 /*yield*/, crypto.verify({
key: publicKeyJwk,
signature: signatureBytes,
data: signedDataBytes,
})];
case 2:
isSignatureValid = _b.sent();
if (!isSignatureValid) {
throw new Error('Signature verification failed: Integrity mismatch');
}
return [2 /*return*/, decodedJwt];
}
});
});
};
/**
* Parses a JWT without verifying its signature.
*
* @example
* ```ts
* const { encoded: encodedJwt, decoded: decodedJwt } = Jwt.parse({ jwt: myJwt });
* ```
*
* @param options - Parameters for JWT decoding, including the JWT string.
* @returns both encoded and decoded JWT parts
*/
Jwt.parse = function (options) {
var splitJwt = options.jwt.split('.');
if (splitJwt.length !== 3) {
throw new Error("Verification failed: Malformed JWT. expected 3 parts. got ".concat(splitJwt.length));
}
var base64urlEncodedJwtHeader = splitJwt[0], base64urlEncodedJwtPayload = splitJwt[1], base64urlEncodedSignature = splitJwt[2];
var jwtHeader;
var jwtPayload;
try {
jwtHeader = common_1.Convert.base64Url(base64urlEncodedJwtHeader).toObject();
}
catch (e) {
throw new Error('Verification failed: Malformed JWT. Invalid base64url encoding for JWT header');
}
if (!jwtHeader.alg || !jwtHeader.kid) { // ensure that JWT header has required properties
throw new Error('Verification failed: Expected JWT header to contain alg and kid');
}
// TODO: validate optional payload fields: https://datatracker.ietf.org/doc/html/rfc7519#section-4.1
try {
jwtPayload = common_1.Convert.base64Url(base64urlEncodedJwtPayload).toObject();
}
catch (e) {
throw new Error('Verification failed: Malformed JWT. Invalid base64url encoding for JWT payload');
}
return {
decoded: {
header: jwtHeader,
payload: jwtPayload,
},
encoded: {
header: base64urlEncodedJwtHeader,
payload: base64urlEncodedJwtPayload,
signature: base64urlEncodedSignature
}
};
};
/**
* DID Resolver instance for resolving decentralized identifiers.
*/
Jwt.didResolver = new dids_1.UniversalResolver({ didResolvers: [dids_1.DidDht, dids_1.DidIon, dids_1.DidKey, dids_1.DidJwk, dids_1.DidWeb] });
return Jwt;
}());
exports.Jwt = Jwt;
//# sourceMappingURL=jwt.js.map