@sphereon/ssi-sdk.vc-status-list
Version:
Sphereon SSI-SDK plugin for Status List management, like StatusList2021.
979 lines (966 loc) • 39.2 kB
JavaScript
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var index_exports = {};
__export(index_exports, {
Status2021: () => Status2021,
StatusOAuth: () => StatusOAuth,
checkStatusForCredential: () => checkStatusForCredential,
checkStatusIndexFromStatusListCredential: () => checkStatusIndexFromStatusListCredential,
createNewStatusList: () => createNewStatusList,
fetchStatusListCredential: () => fetchStatusListCredential,
simpleCheckStatusFromStatusListUrl: () => simpleCheckStatusFromStatusListUrl,
statusList2021ToVerifiableCredential: () => statusList2021ToVerifiableCredential,
statusListCredentialToDetails: () => statusListCredentialToDetails,
statusPluginStatusFunction: () => statusPluginStatusFunction,
updateStatusIndexFromStatusListCredential: () => updateStatusIndexFromStatusListCredential,
updateStatusListIndexFromEncodedList: () => updateStatusListIndexFromEncodedList,
vcLibCheckStatusFunction: () => vcLibCheckStatusFunction
});
module.exports = __toCommonJS(index_exports);
// src/types/index.ts
var StatusOAuth = /* @__PURE__ */ function(StatusOAuth2) {
StatusOAuth2[StatusOAuth2["Valid"] = 0] = "Valid";
StatusOAuth2[StatusOAuth2["Invalid"] = 1] = "Invalid";
StatusOAuth2[StatusOAuth2["Suspended"] = 2] = "Suspended";
return StatusOAuth2;
}({});
var Status2021 = /* @__PURE__ */ function(Status20212) {
Status20212[Status20212["Valid"] = 0] = "Valid";
Status20212[Status20212["Invalid"] = 1] = "Invalid";
return Status20212;
}({});
// src/functions.ts
var import_ssi_types6 = require("@sphereon/ssi-types");
var import_vc_status_list2 = require("@sphereon/vc-status-list");
// src/utils.ts
var import_ssi_types = require("@sphereon/ssi-types");
var import_jwt_decode = require("jwt-decode");
function getAssertedStatusListType(type) {
const assertedType = type ?? import_ssi_types.StatusListType.StatusList2021;
if (![
import_ssi_types.StatusListType.StatusList2021,
import_ssi_types.StatusListType.OAuthStatusList
].includes(assertedType)) {
throw Error(`StatusList type ${assertedType} is not supported (yet)`);
}
return assertedType;
}
__name(getAssertedStatusListType, "getAssertedStatusListType");
function getAssertedValue(name, value) {
if (value === void 0 || value === null) {
throw Error(`Missing required ${name} value`);
}
return value;
}
__name(getAssertedValue, "getAssertedValue");
function getAssertedValues(args) {
const type = getAssertedStatusListType(args?.type);
const id = getAssertedValue("id", args.id);
const issuer = getAssertedValue("issuer", args.issuer);
return {
id,
issuer,
type
};
}
__name(getAssertedValues, "getAssertedValues");
function getAssertedProperty(propertyName, obj) {
if (!(propertyName in obj)) {
throw Error(`The input object does not contain required property: ${propertyName}`);
}
return getAssertedValue(propertyName, obj[propertyName]);
}
__name(getAssertedProperty, "getAssertedProperty");
var ValidProofTypeMap = /* @__PURE__ */ new Map([
[
import_ssi_types.StatusListType.StatusList2021,
[
"jwt",
"lds",
"EthereumEip712Signature2021"
]
],
[
import_ssi_types.StatusListType.OAuthStatusList,
[
"jwt",
"cbor"
]
]
]);
function assertValidProofType(type, proofFormat) {
const validProofTypes = ValidProofTypeMap.get(type);
if (!validProofTypes?.includes(proofFormat)) {
throw Error(`Invalid proof format '${proofFormat}' for status list type ${type}`);
}
}
__name(assertValidProofType, "assertValidProofType");
function determineStatusListType(credential) {
const proofFormat = determineProofFormat(credential);
switch (proofFormat) {
case "jwt":
const payload = (0, import_jwt_decode.jwtDecode)(credential);
const keys = Object.keys(payload);
if (keys.includes("status_list")) {
return import_ssi_types.StatusListType.OAuthStatusList;
} else if (keys.includes("vc")) {
return import_ssi_types.StatusListType.StatusList2021;
}
break;
case "lds":
const uniform = import_ssi_types.CredentialMapper.toUniformCredential(credential);
const type = uniform.type.find((t) => {
return Object.values(import_ssi_types.StatusListType).some((statusType) => t.includes(statusType));
});
if (!type) {
throw new Error("Invalid status list credential type");
}
return type.replace("Credential", "");
case "cbor":
return import_ssi_types.StatusListType.OAuthStatusList;
}
throw new Error("Cannot determine status list type from credential payload");
}
__name(determineStatusListType, "determineStatusListType");
function determineProofFormat(credential) {
const type = import_ssi_types.CredentialMapper.detectDocumentType(credential);
switch (type) {
case import_ssi_types.DocumentFormat.JWT:
return "jwt";
case import_ssi_types.DocumentFormat.MSO_MDOC:
return "cbor";
case import_ssi_types.DocumentFormat.JSONLD:
return "lds";
default:
throw Error("Cannot determine credential payload type");
}
}
__name(determineProofFormat, "determineProofFormat");
// src/impl/StatusList2021.ts
var import_ssi_types2 = require("@sphereon/ssi-types");
var import_vc_status_list = require("@sphereon/vc-status-list");
var DEFAULT_LIST_LENGTH = 25e4;
var DEFAULT_PROOF_FORMAT = "lds";
var StatusList2021Implementation = class {
static {
__name(this, "StatusList2021Implementation");
}
async createNewStatusList(args, context) {
const length = args?.length ?? DEFAULT_LIST_LENGTH;
const proofFormat = args?.proofFormat ?? DEFAULT_PROOF_FORMAT;
assertValidProofType(import_ssi_types2.StatusListType.StatusList2021, proofFormat);
const veramoProofFormat = proofFormat;
const { issuer, id } = args;
const correlationId = getAssertedValue("correlationId", args.correlationId);
const list = new import_vc_status_list.StatusList({
length
});
const encodedList = await list.encode();
const statusPurpose = "revocation";
const statusListCredential = await this.createVerifiableCredential({
...args,
encodedList,
proofFormat: veramoProofFormat
}, context);
return {
encodedList,
statusListCredential,
statusList2021: {
statusPurpose,
indexingDirection: "rightToLeft"
},
length,
type: import_ssi_types2.StatusListType.StatusList2021,
proofFormat,
id,
correlationId,
issuer,
statuslistContentType: this.buildContentType(proofFormat)
};
}
async updateStatusListIndex(args, context) {
const credential = args.statusListCredential;
const uniform = import_ssi_types2.CredentialMapper.toUniformCredential(credential);
const { issuer, credentialSubject } = uniform;
const id = getAssertedValue("id", uniform.id);
const origEncodedList = getAssertedProperty("encodedList", credentialSubject);
const index = typeof args.statusListIndex === "number" ? args.statusListIndex : parseInt(args.statusListIndex);
const statusList = await import_vc_status_list.StatusList.decode({
encodedList: origEncodedList
});
statusList.setStatus(index, args.value != 0);
const encodedList = await statusList.encode();
const proofFormat = import_ssi_types2.CredentialMapper.detectDocumentType(credential) === import_ssi_types2.DocumentFormat.JWT ? "jwt" : "lds";
const updatedCredential = await this.createVerifiableCredential({
...args,
id,
issuer,
encodedList,
proofFormat
}, context);
return {
statusListCredential: updatedCredential,
encodedList,
statusList2021: {
..."statusPurpose" in credentialSubject ? {
statusPurpose: credentialSubject.statusPurpose
} : {},
indexingDirection: "rightToLeft"
},
length: statusList.length - 1,
type: import_ssi_types2.StatusListType.StatusList2021,
proofFormat,
id,
issuer,
statuslistContentType: this.buildContentType(proofFormat)
};
}
async updateStatusListFromEncodedList(args, context) {
if (!args.statusList2021) {
throw new Error("statusList2021 options required for type StatusList2021");
}
const proofFormat = args?.proofFormat ?? DEFAULT_PROOF_FORMAT;
assertValidProofType(import_ssi_types2.StatusListType.StatusList2021, proofFormat);
const veramoProofFormat = proofFormat;
const { issuer, id } = getAssertedValues(args);
const statusList = await import_vc_status_list.StatusList.decode({
encodedList: args.encodedList
});
const index = typeof args.statusListIndex === "number" ? args.statusListIndex : parseInt(args.statusListIndex);
statusList.setStatus(index, args.value);
const newEncodedList = await statusList.encode();
const credential = await this.createVerifiableCredential({
id,
issuer,
encodedList: newEncodedList,
proofFormat: veramoProofFormat,
keyRef: args.keyRef
}, context);
return {
type: import_ssi_types2.StatusListType.StatusList2021,
statusListCredential: credential,
encodedList: newEncodedList,
statusList2021: {
statusPurpose: args.statusList2021.statusPurpose,
indexingDirection: "rightToLeft"
},
length: statusList.length,
proofFormat: args.proofFormat ?? "lds",
id,
issuer,
statuslistContentType: this.buildContentType(proofFormat)
};
}
async checkStatusIndex(args) {
const uniform = import_ssi_types2.CredentialMapper.toUniformCredential(args.statusListCredential);
const { credentialSubject } = uniform;
const encodedList = getAssertedProperty("encodedList", credentialSubject);
const statusList = await import_vc_status_list.StatusList.decode({
encodedList
});
const status = statusList.getStatus(typeof args.statusListIndex === "number" ? args.statusListIndex : parseInt(args.statusListIndex));
return status ? Status2021.Invalid : Status2021.Valid;
}
async toStatusListDetails(args) {
const { statusListPayload } = args;
const uniform = import_ssi_types2.CredentialMapper.toUniformCredential(statusListPayload);
const { issuer, credentialSubject } = uniform;
const id = getAssertedValue("id", uniform.id);
const encodedList = getAssertedProperty("encodedList", credentialSubject);
const proofFormat = import_ssi_types2.CredentialMapper.detectDocumentType(statusListPayload) === import_ssi_types2.DocumentFormat.JWT ? "jwt" : "lds";
const statusPurpose = getAssertedProperty("statusPurpose", credentialSubject);
const list = await import_vc_status_list.StatusList.decode({
encodedList
});
return {
id,
encodedList,
issuer,
type: import_ssi_types2.StatusListType.StatusList2021,
proofFormat,
length: list.length,
statusListCredential: statusListPayload,
statuslistContentType: this.buildContentType(proofFormat),
statusList2021: {
indexingDirection: "rightToLeft",
statusPurpose
},
...args.correlationId && {
correlationId: args.correlationId
},
...args.driverType && {
driverType: args.driverType
}
};
}
async createVerifiableCredential(args, context) {
const identifier = await context.agent.identifierManagedGet({
identifier: typeof args.issuer === "string" ? args.issuer : args.issuer.id,
vmRelationship: "assertionMethod",
offlineWhenNoDIDRegistered: true
});
const credential = {
"@context": [
"https://www.w3.org/2018/credentials/v1",
"https://w3id.org/vc/status-list/2021/v1"
],
id: args.id,
issuer: args.issuer,
type: [
"VerifiableCredential",
"StatusList2021Credential"
],
credentialSubject: {
id: args.id,
type: "StatusList2021",
statusPurpose: "revocation",
encodedList: args.encodedList
}
};
const verifiableCredential = await context.agent.createVerifiableCredential({
credential,
keyRef: args.keyRef ?? identifier.kmsKeyRef,
proofFormat: args.proofFormat,
fetchRemoteContexts: true
});
return import_ssi_types2.CredentialMapper.toWrappedVerifiableCredential(verifiableCredential).original;
}
buildContentType(proofFormat) {
switch (proofFormat) {
case "jwt":
return `application/statuslist+jwt`;
case "cbor":
return `application/statuslist+cwt`;
case "lds":
return "application/statuslist+ld+json";
default:
throw Error(`Unsupported content type '${proofFormat}' for status lists`);
}
}
};
// src/impl/OAuthStatusList.ts
var import_ssi_types4 = require("@sphereon/ssi-types");
var import_jwt_status_list3 = require("@sd-jwt/jwt-status-list");
// src/impl/encoding/jwt.ts
var import_ssi_types3 = require("@sphereon/ssi-types");
var import_jwt_status_list = require("@sd-jwt/jwt-status-list");
var import_base64url = __toESM(require("base64url"), 1);
// src/impl/encoding/common.ts
var resolveIdentifier = /* @__PURE__ */ __name(async (context, issuer, keyRef) => {
return await context.agent.identifierManagedGet({
identifier: issuer,
vmRelationship: "assertionMethod",
offlineWhenNoDIDRegistered: true,
...keyRef && {
kmsKeyRef: keyRef
}
});
}, "resolveIdentifier");
// src/impl/encoding/jwt.ts
var import_ssi_sdk_ext = require("@sphereon/ssi-sdk-ext.identifier-resolution");
var STATUS_LIST_JWT_TYP = "statuslist+jwt";
var createSignedJwt = /* @__PURE__ */ __name(async (context, statusList, issuerString, id, expiresAt, keyRef) => {
const identifier = await resolveIdentifier(context, issuerString, keyRef);
const resolution = await (0, import_ssi_sdk_ext.ensureManagedIdentifierResult)(identifier, context);
const payload = {
iss: issuerString,
sub: id,
iat: Math.floor(Date.now() / 1e3),
...expiresAt && {
exp: Math.floor(expiresAt.getTime() / 1e3)
}
};
const header = {
alg: getSigningAlgo(resolution.key.type),
typ: STATUS_LIST_JWT_TYP
};
const values = (0, import_jwt_status_list.createHeaderAndPayload)(statusList, payload, header);
const signedJwt = await context.agent.jwtCreateJwsCompactSignature({
issuer: {
...identifier,
noIssPayloadUpdate: false
},
protectedHeader: values.header,
payload: values.payload
});
return {
statusListCredential: signedJwt.jwt,
encodedList: values.payload.status_list.lst
};
}, "createSignedJwt");
var decodeStatusListJWT = /* @__PURE__ */ __name((jwt) => {
const [, payloadBase64] = jwt.split(".");
const payload = JSON.parse(import_base64url.default.decode(payloadBase64));
if (!payload.iss || !payload.sub || !payload.status_list) {
throw new Error("Missing required fields in JWT payload");
}
const statusList = import_jwt_status_list.StatusList.decompressStatusList(payload.status_list.lst, payload.status_list.bits);
return {
issuer: payload.iss,
id: payload.sub,
statusList,
exp: payload.exp,
ttl: payload.ttl,
iat: payload.iat
};
}, "decodeStatusListJWT");
var getSigningAlgo = /* @__PURE__ */ __name((type) => {
switch (type) {
case "Ed25519":
return import_ssi_types3.JoseSignatureAlgorithm.EdDSA;
case "Secp256k1":
return import_ssi_types3.JoseSignatureAlgorithm.ES256K;
case "Secp256r1":
return import_ssi_types3.JoseSignatureAlgorithm.ES256;
case "RSA":
return import_ssi_types3.JoseSignatureAlgorithm.RS256;
default:
throw Error("Key type not yet supported");
}
}, "getSigningAlgo");
// src/impl/encoding/cbor.ts
var import_jwt_status_list2 = require("@sd-jwt/jwt-status-list");
var import_pako = require("pako");
var import_kmp_mdoc_core = __toESM(require("@sphereon/kmp-mdoc-core"), 1);
var import_base64url2 = __toESM(require("base64url"), 1);
var { com, kotlin } = import_kmp_mdoc_core.default;
var CborByteString = com.sphereon.cbor.CborByteString;
var CborUInt = com.sphereon.cbor.CborUInt;
var CborString = com.sphereon.cbor.CborString;
var decompressRawStatusList = import_jwt_status_list2.StatusList.decodeStatusList.bind(import_jwt_status_list2.StatusList);
var CWT_CLAIMS = {
SUBJECT: 2,
ISSUER: 1,
ISSUED_AT: 6,
EXPIRATION: 4,
TIME_TO_LIVE: 65534,
STATUS_LIST: 65533
};
var createSignedCbor = /* @__PURE__ */ __name(async (context, statusList, issuerString, id, expiresAt, keyRef) => {
const identifier = await resolveIdentifier(context, issuerString, keyRef);
const encodeStatusList = statusList.encodeStatusList();
const compressedList = (0, import_pako.deflate)(encodeStatusList, {
level: 9
});
const compressedBytes = new Int8Array(compressedList);
const statusListMap = new com.sphereon.cbor.CborMap(kotlin.collections.KtMutableMap.fromJsMap(/* @__PURE__ */ new Map([
[
new com.sphereon.cbor.CborString("bits"),
new com.sphereon.cbor.CborUInt(com.sphereon.kmp.LongKMP.fromNumber(statusList.getBitsPerStatus()))
],
[
new com.sphereon.cbor.CborString("lst"),
new com.sphereon.cbor.CborByteString(compressedBytes)
]
])));
const protectedHeader = new com.sphereon.cbor.CborMap(kotlin.collections.KtMutableMap.fromJsMap(/* @__PURE__ */ new Map([
[
new com.sphereon.cbor.CborUInt(com.sphereon.kmp.LongKMP.fromNumber(16)),
new com.sphereon.cbor.CborString("statuslist+cwt")
]
])));
const protectedHeaderEncoded = com.sphereon.cbor.Cbor.encode(protectedHeader);
const claimsMap = buildClaimsMap(id, issuerString, statusListMap, expiresAt);
const claimsEncoded = com.sphereon.cbor.Cbor.encode(claimsMap);
const signedCWT = await context.agent.keyManagerSign({
keyRef: identifier.kmsKeyRef,
data: import_base64url2.default.encode(Buffer.from(claimsEncoded)),
encoding: void 0
});
const protectedHeaderEncodedInt8 = new Int8Array(protectedHeaderEncoded);
const claimsEncodedInt8 = new Int8Array(claimsEncoded);
const signatureBytes = import_base64url2.default.decode(signedCWT);
const signatureInt8 = new Int8Array(Buffer.from(signatureBytes));
const cwtArrayElements = [
new CborByteString(protectedHeaderEncodedInt8),
new CborByteString(claimsEncodedInt8),
new CborByteString(signatureInt8)
];
const cwtArray = new com.sphereon.cbor.CborArray(kotlin.collections.KtMutableList.fromJsArray(cwtArrayElements));
const cwtEncoded = com.sphereon.cbor.Cbor.encode(cwtArray);
const cwtBuffer = Buffer.from(cwtEncoded);
return {
statusListCredential: import_base64url2.default.encode(cwtBuffer),
encodedList: import_base64url2.default.encode(compressedList)
};
}, "createSignedCbor");
function buildClaimsMap(id, issuerString, statusListMap, expiresAt) {
const ttl = 65535;
const claimsEntries = [
[
new CborUInt(com.sphereon.kmp.LongKMP.fromNumber(CWT_CLAIMS.SUBJECT)),
new com.sphereon.cbor.CborString(id)
],
[
new CborUInt(com.sphereon.kmp.LongKMP.fromNumber(CWT_CLAIMS.ISSUER)),
new com.sphereon.cbor.CborString(issuerString)
],
[
new CborUInt(com.sphereon.kmp.LongKMP.fromNumber(CWT_CLAIMS.ISSUED_AT)),
new CborUInt(com.sphereon.kmp.LongKMP.fromNumber(Math.floor(Date.now() / 1e3)))
]
];
if (expiresAt) {
claimsEntries.push([
new com.sphereon.cbor.CborUInt(com.sphereon.kmp.LongKMP.fromNumber(CWT_CLAIMS.EXPIRATION)),
new com.sphereon.cbor.CborUInt(com.sphereon.kmp.LongKMP.fromNumber(Math.floor(expiresAt.getTime() / 1e3)))
]);
}
if (ttl) {
claimsEntries.push([
new com.sphereon.cbor.CborUInt(com.sphereon.kmp.LongKMP.fromNumber(CWT_CLAIMS.TIME_TO_LIVE)),
new com.sphereon.cbor.CborUInt(com.sphereon.kmp.LongKMP.fromNumber(ttl))
]);
}
claimsEntries.push([
new com.sphereon.cbor.CborUInt(com.sphereon.kmp.LongKMP.fromNumber(CWT_CLAIMS.STATUS_LIST)),
statusListMap
]);
const claimsMap = new com.sphereon.cbor.CborMap(kotlin.collections.KtMutableMap.fromJsMap(new Map(claimsEntries)));
return claimsMap;
}
__name(buildClaimsMap, "buildClaimsMap");
var getCborValueFromMap = /* @__PURE__ */ __name((map, key) => {
const value = getCborOptionalValueFromMap(map, key);
if (value === void 0) {
throw new Error(`Required claim ${key} not found`);
}
return value;
}, "getCborValueFromMap");
var getCborOptionalValueFromMap = /* @__PURE__ */ __name((map, key) => {
const value = map.get(new CborUInt(com.sphereon.kmp.LongKMP.fromNumber(key)));
if (!value) {
return void 0;
}
return value.value;
}, "getCborOptionalValueFromMap");
var decodeStatusListCWT = /* @__PURE__ */ __name((cwt) => {
const encodedCbor = import_base64url2.default.toBuffer(cwt);
const encodedCborArray = new Int8Array(encodedCbor);
const decodedCbor = com.sphereon.cbor.Cbor.decode(encodedCborArray);
if (!(decodedCbor instanceof com.sphereon.cbor.CborArray)) {
throw new Error("Invalid CWT format: Expected a CBOR array");
}
const [, payload] = decodedCbor.value.asJsArrayView();
if (!(payload instanceof com.sphereon.cbor.CborByteString)) {
throw new Error("Invalid payload format: Expected a CBOR ByteString");
}
const claims = com.sphereon.cbor.Cbor.decode(payload.value);
if (!(claims instanceof com.sphereon.cbor.CborMap)) {
throw new Error("Invalid claims format: Expected a CBOR map");
}
const claimsMap = claims.value.asJsMapView();
const statusListMap = claimsMap.get(new CborUInt(com.sphereon.kmp.LongKMP.fromNumber(65533))).value.asJsMapView();
const bits = Number(statusListMap.get(new CborString("bits")).value);
const decoded = new Uint8Array(statusListMap.get(new CborString("lst")).value);
const uint8Array = (0, import_pako.inflate)(decoded);
const rawStatusList = decompressRawStatusList(uint8Array, bits);
const statusList = new import_jwt_status_list2.StatusList(rawStatusList, bits);
return {
issuer: getCborValueFromMap(claimsMap, CWT_CLAIMS.ISSUER),
id: getCborValueFromMap(claimsMap, CWT_CLAIMS.SUBJECT),
statusList,
iat: Number(getCborValueFromMap(claimsMap, CWT_CLAIMS.ISSUED_AT)),
exp: getCborOptionalValueFromMap(claimsMap, CWT_CLAIMS.EXPIRATION),
ttl: getCborOptionalValueFromMap(claimsMap, CWT_CLAIMS.TIME_TO_LIVE)
};
}, "decodeStatusListCWT");
// src/impl/OAuthStatusList.ts
var DEFAULT_BITS_PER_STATUS = 1;
var DEFAULT_LIST_LENGTH2 = 25e4;
var DEFAULT_PROOF_FORMAT2 = "jwt";
var OAuthStatusListImplementation = class {
static {
__name(this, "OAuthStatusListImplementation");
}
async createNewStatusList(args, context) {
if (!args.oauthStatusList) {
throw new Error("OAuthStatusList options are required for type OAuthStatusList");
}
const proofFormat = args?.proofFormat ?? DEFAULT_PROOF_FORMAT2;
const { issuer, id, oauthStatusList, keyRef } = args;
const { bitsPerStatus, expiresAt } = oauthStatusList;
const length = args.length ?? DEFAULT_LIST_LENGTH2;
const issuerString = typeof issuer === "string" ? issuer : issuer.id;
const correlationId = getAssertedValue("correlationId", args.correlationId);
const statusList = new import_jwt_status_list3.StatusList(new Array(length).fill(0), bitsPerStatus ?? DEFAULT_BITS_PER_STATUS);
const encodedList = statusList.compressStatusList();
const { statusListCredential } = await this.createSignedStatusList(proofFormat, context, statusList, issuerString, id, expiresAt, keyRef);
return {
encodedList,
statusListCredential,
oauthStatusList: {
bitsPerStatus
},
length,
type: import_ssi_types4.StatusListType.OAuthStatusList,
proofFormat,
id,
correlationId,
issuer,
statuslistContentType: this.buildContentType(proofFormat)
};
}
async updateStatusListIndex(args, context) {
const { statusListCredential, value, expiresAt, keyRef } = args;
if (typeof statusListCredential !== "string") {
return Promise.reject("statusListCredential in neither JWT nor CWT");
}
const proofFormat = determineProofFormat(statusListCredential);
const decoded = proofFormat === "jwt" ? decodeStatusListJWT(statusListCredential) : decodeStatusListCWT(statusListCredential);
const { statusList, issuer, id } = decoded;
const index = typeof args.statusListIndex === "number" ? args.statusListIndex : parseInt(args.statusListIndex);
if (index < 0 || index >= statusList.statusList.length) {
throw new Error("Status list index out of bounds");
}
statusList.setStatus(index, value);
const { statusListCredential: signedCredential, encodedList } = await this.createSignedStatusList(proofFormat, context, statusList, issuer, id, expiresAt, keyRef);
return {
statusListCredential: signedCredential,
encodedList,
oauthStatusList: {
bitsPerStatus: statusList.getBitsPerStatus()
},
length: statusList.statusList.length,
type: import_ssi_types4.StatusListType.OAuthStatusList,
proofFormat,
id,
issuer,
statuslistContentType: this.buildContentType(proofFormat)
};
}
// FIXME: This still assumes only two values (boolean), whilst this list supports 8 bits max
async updateStatusListFromEncodedList(args, context) {
if (!args.oauthStatusList) {
throw new Error("OAuthStatusList options are required for type OAuthStatusList");
}
const { proofFormat, oauthStatusList, keyRef } = args;
const { bitsPerStatus, expiresAt } = oauthStatusList;
const { issuer, id } = getAssertedValues(args);
const issuerString = typeof issuer === "string" ? issuer : issuer.id;
const listToUpdate = import_jwt_status_list3.StatusList.decompressStatusList(args.encodedList, bitsPerStatus ?? DEFAULT_BITS_PER_STATUS);
const index = typeof args.statusListIndex === "number" ? args.statusListIndex : parseInt(args.statusListIndex);
listToUpdate.setStatus(index, args.value ? 1 : 0);
const { statusListCredential, encodedList } = await this.createSignedStatusList(proofFormat ?? DEFAULT_PROOF_FORMAT2, context, listToUpdate, issuerString, id, expiresAt, keyRef);
return {
encodedList,
statusListCredential,
oauthStatusList: {
bitsPerStatus,
expiresAt
},
length: listToUpdate.statusList.length,
type: import_ssi_types4.StatusListType.OAuthStatusList,
proofFormat: proofFormat ?? DEFAULT_PROOF_FORMAT2,
id,
issuer,
statuslistContentType: this.buildContentType(proofFormat)
};
}
buildContentType(proofFormat) {
return `application/statuslist+${proofFormat === "cbor" ? "cwt" : "jwt"}`;
}
async checkStatusIndex(args) {
const { statusListCredential, statusListIndex } = args;
if (typeof statusListCredential !== "string") {
return Promise.reject("statusListCredential in neither JWT nor CWT");
}
const proofFormat = determineProofFormat(statusListCredential);
const { statusList } = proofFormat === "jwt" ? decodeStatusListJWT(statusListCredential) : decodeStatusListCWT(statusListCredential);
const index = typeof statusListIndex === "number" ? statusListIndex : parseInt(statusListIndex);
if (index < 0 || index >= statusList.statusList.length) {
throw new Error("Status list index out of bounds");
}
return statusList.getStatus(index);
}
async toStatusListDetails(args) {
const { statusListPayload } = args;
const proofFormat = determineProofFormat(statusListPayload);
const decoded = proofFormat === "jwt" ? decodeStatusListJWT(statusListPayload) : decodeStatusListCWT(statusListPayload);
const { statusList, issuer, id, exp } = decoded;
return {
id,
encodedList: statusList.compressStatusList(),
issuer,
type: import_ssi_types4.StatusListType.OAuthStatusList,
proofFormat,
length: statusList.statusList.length,
statusListCredential: statusListPayload,
statuslistContentType: this.buildContentType(proofFormat),
oauthStatusList: {
bitsPerStatus: statusList.getBitsPerStatus(),
...exp && {
expiresAt: new Date(exp * 1e3)
}
},
...args.correlationId && {
correlationId: args.correlationId
},
...args.driverType && {
driverType: args.driverType
}
};
}
async createSignedStatusList(proofFormat, context, statusList, issuerString, id, expiresAt, keyRef) {
switch (proofFormat) {
case "jwt": {
return await createSignedJwt(context, statusList, issuerString, id, expiresAt, keyRef);
}
case "cbor": {
return await createSignedCbor(context, statusList, issuerString, id, expiresAt, keyRef);
}
default:
throw new Error(`Invalid proof format '${proofFormat}' for OAuthStatusList`);
}
}
};
// src/impl/StatusListFactory.ts
var import_ssi_types5 = require("@sphereon/ssi-types");
var StatusListFactory = class _StatusListFactory {
static {
__name(this, "StatusListFactory");
}
static instance;
implementations;
constructor() {
this.implementations = /* @__PURE__ */ new Map();
this.implementations.set(import_ssi_types5.StatusListType.StatusList2021, new StatusList2021Implementation());
this.implementations.set(import_ssi_types5.StatusListType.OAuthStatusList, new OAuthStatusListImplementation());
}
static getInstance() {
if (!_StatusListFactory.instance) {
_StatusListFactory.instance = new _StatusListFactory();
}
return _StatusListFactory.instance;
}
getByType(type) {
const statusList = this.implementations.get(type);
if (!statusList) {
throw new Error(`No implementation found for status list type: ${type}`);
}
return statusList;
}
};
function getStatusListImplementation(type) {
return StatusListFactory.getInstance().getByType(type);
}
__name(getStatusListImplementation, "getStatusListImplementation");
// src/functions.ts
async function fetchStatusListCredential(args) {
const url = getAssertedValue("statusListCredential", args.statusListCredential);
try {
const response = await fetch(url);
if (!response.ok) {
throw Error(`Fetching status list ${url} resulted in an error: ${response.status} : ${response.statusText}`);
}
const responseAsText = await response.text();
if (responseAsText.trim().startsWith("{")) {
return JSON.parse(responseAsText);
}
return responseAsText;
} catch (error) {
console.error(`Fetching status list ${url} resulted in an unexpected error: ${error instanceof Error ? error.message : JSON.stringify(error)}`);
throw error;
}
}
__name(fetchStatusListCredential, "fetchStatusListCredential");
function statusPluginStatusFunction(args) {
return async (credential, didDoc) => {
const result = await checkStatusForCredential({
...args,
documentLoader: args.documentLoader,
credential,
errorUnknownListType: args.errorUnknownListType
});
return {
revoked: !result.verified || result.error,
...result.error && {
error: result.error
}
};
};
}
__name(statusPluginStatusFunction, "statusPluginStatusFunction");
function vcLibCheckStatusFunction(args) {
const { mandatoryCredentialStatus, verifyStatusListCredential, verifyMatchingIssuers, errorUnknownListType } = args;
return (args2) => {
return checkStatusForCredential({
...args2,
mandatoryCredentialStatus,
verifyStatusListCredential,
verifyMatchingIssuers,
errorUnknownListType
});
};
}
__name(vcLibCheckStatusFunction, "vcLibCheckStatusFunction");
async function checkStatusForCredential(args) {
const verifyStatusListCredential = args.verifyStatusListCredential ?? true;
const verifyMatchingIssuers = args.verifyMatchingIssuers ?? true;
const uniform = import_ssi_types6.CredentialMapper.toUniformCredential(args.credential);
if (!("credentialStatus" in uniform) || !uniform.credentialStatus) {
if (args.mandatoryCredentialStatus) {
const error = "No credential status object found in the Verifiable Credential and it is mandatory";
console.log(error);
return {
verified: false,
error
};
}
return {
verified: true
};
}
if ("credentialStatus" in uniform && uniform.credentialStatus) {
if (uniform.credentialStatus.type === "StatusList2021Entry") {
return (0, import_vc_status_list2.checkStatus)({
...args,
verifyStatusListCredential,
verifyMatchingIssuers
});
} else if (args?.errorUnknownListType) {
const error = `Credential status type ${uniform.credentialStatus.type} is not supported, and check status has been configured to not allow for that`;
console.log(error);
return {
verified: false,
error
};
} else {
console.log(`Skipped verification of status type ${uniform.credentialStatus.type} as we do not support it (yet)`);
}
}
return {
verified: true
};
}
__name(checkStatusForCredential, "checkStatusForCredential");
async function simpleCheckStatusFromStatusListUrl(args) {
return checkStatusIndexFromStatusListCredential({
...args,
statusListCredential: await fetchStatusListCredential(args)
});
}
__name(simpleCheckStatusFromStatusListUrl, "simpleCheckStatusFromStatusListUrl");
async function checkStatusIndexFromStatusListCredential(args) {
const statusListType = determineStatusListType(args.statusListCredential);
const implementation = getStatusListImplementation(statusListType);
return implementation.checkStatusIndex(args);
}
__name(checkStatusIndexFromStatusListCredential, "checkStatusIndexFromStatusListCredential");
async function createNewStatusList(args, context) {
const { type } = getAssertedValues(args);
const implementation = getStatusListImplementation(type);
return implementation.createNewStatusList(args, context);
}
__name(createNewStatusList, "createNewStatusList");
async function updateStatusIndexFromStatusListCredential(args, context) {
const credential = getAssertedValue("statusListCredential", args.statusListCredential);
const statusListType = determineStatusListType(credential);
const implementation = getStatusListImplementation(statusListType);
return implementation.updateStatusListIndex(args, context);
}
__name(updateStatusIndexFromStatusListCredential, "updateStatusIndexFromStatusListCredential");
async function statusListCredentialToDetails(args) {
const credential = getAssertedValue("statusListCredential", args.statusListCredential);
let statusListType;
const documentFormat = import_ssi_types6.CredentialMapper.detectDocumentType(credential);
if (documentFormat === import_ssi_types6.DocumentFormat.JWT) {
const [header] = credential.split(".");
const decodedHeader = JSON.parse(Buffer.from(header, "base64").toString());
if (decodedHeader.typ === "statuslist+jwt") {
statusListType = import_ssi_types6.StatusListType.OAuthStatusList;
}
} else if (documentFormat === import_ssi_types6.DocumentFormat.MSO_MDOC) {
statusListType = import_ssi_types6.StatusListType.OAuthStatusList;
}
if (!statusListType) {
const uniform = import_ssi_types6.CredentialMapper.toUniformCredential(credential);
const type = uniform.type.find((t) => t.includes("StatusList2021") || t.includes("OAuth2StatusList"));
if (!type) {
throw new Error("Invalid status list credential type");
}
statusListType = type.replace("Credential", "");
}
const implementation = getStatusListImplementation(statusListType);
return await implementation.toStatusListDetails({
statusListPayload: credential,
correlationId: args.correlationId,
driverType: args.driverType
});
}
__name(statusListCredentialToDetails, "statusListCredentialToDetails");
async function updateStatusListIndexFromEncodedList(args, context) {
const { type } = getAssertedValue("type", args);
const implementation = getStatusListImplementation(type);
return implementation.updateStatusListFromEncodedList(args, context);
}
__name(updateStatusListIndexFromEncodedList, "updateStatusListIndexFromEncodedList");
async function statusList2021ToVerifiableCredential(args, context) {
const { issuer, id, type } = getAssertedValues(args);
const identifier = await context.agent.identifierManagedGet({
identifier: typeof issuer === "string" ? issuer : issuer.id,
vmRelationship: "assertionMethod",
offlineWhenNoDIDRegistered: true
});
const proofFormat = args?.proofFormat ?? "lds";
assertValidProofType(import_ssi_types6.StatusListType.StatusList2021, proofFormat);
const veramoProofFormat = proofFormat;
const encodedList = getAssertedValue("encodedList", args.encodedList);
const statusPurpose = getAssertedValue("statusPurpose", args.statusPurpose);
const credential = {
"@context": [
"https://www.w3.org/2018/credentials/v1",
"https://w3id.org/vc/status-list/2021/v1"
],
id,
issuer,
// issuanceDate: "2021-03-10T04:24:12.164Z",
type: [
"VerifiableCredential",
`${type}Credential`
],
credentialSubject: {
id,
type,
statusPurpose,
encodedList
}
};
const verifiableCredential = await context.agent.createVerifiableCredential({
credential,
keyRef: identifier.kmsKeyRef,
proofFormat: veramoProofFormat,
fetchRemoteContexts: true
});
return import_ssi_types6.CredentialMapper.toWrappedVerifiableCredential(verifiableCredential).original;
}
__name(statusList2021ToVerifiableCredential, "statusList2021ToVerifiableCredential");
//# sourceMappingURL=index.cjs.map