@sphereon/ssi-types
Version:
SSI Common Types
1,320 lines (1,306 loc) • 71.9 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, {
ActionType: () => ActionType,
BasicEventEmitter: () => BasicEventEmitter,
CredentialMapper: () => CredentialMapper,
CredentialRole: () => CredentialRole,
DefaultActionSubType: () => DefaultActionSubType,
DocumentFormat: () => DocumentFormat,
EventManager: () => EventManager,
ICoseCurve: () => ICoseCurve,
ICoseKeyOperation: () => ICoseKeyOperation,
ICoseKeyType: () => ICoseKeyType,
ICoseSignatureAlgorithm: () => ICoseSignatureAlgorithm,
IProofPurpose: () => IProofPurpose,
IProofType: () => IProofType,
InitiatorType: () => InitiatorType,
JWT_PROOF_TYPE_2020: () => JWT_PROOF_TYPE_2020,
JoseCurve: () => JoseCurve,
JoseKeyOperation: () => JoseKeyOperation,
JoseSignatureAlgorithm: () => JoseSignatureAlgorithm,
JwkKeyType: () => JwkKeyType,
LogLevel: () => LogLevel,
LogMethod: () => LogMethod,
Loggers: () => Loggers,
LoggingEventType: () => LoggingEventType,
ObjectUtils: () => ObjectUtils,
OriginalType: () => OriginalType,
SimpleLogger: () => SimpleLogger,
SimpleRecordLogger: () => SimpleRecordLogger,
StatusListCredentialIdMode: () => StatusListCredentialIdMode,
StatusListDriverType: () => StatusListDriverType,
StatusListType: () => StatusListType,
SubSystem: () => SubSystem,
System: () => System,
SystemCorrelationIdType: () => SystemCorrelationIdType,
VCDM_CREDENTIAL_CONTEXT_V1: () => VCDM_CREDENTIAL_CONTEXT_V1,
VCDM_CREDENTIAL_CONTEXT_V2: () => VCDM_CREDENTIAL_CONTEXT_V2,
VCDM_CREDENTIAL_CONTEXT_VERSIONS: () => VCDM_CREDENTIAL_CONTEXT_VERSIONS,
addVcdmContextIfNeeded: () => addVcdmContextIfNeeded,
decodeMdocDeviceResponse: () => decodeMdocDeviceResponse,
decodeMdocIssuerSigned: () => decodeMdocIssuerSigned,
decodeSdJwtVc: () => decodeSdJwtVc,
decodeSdJwtVcAsync: () => decodeSdJwtVcAsync,
defaultHasher: () => defaultHasher,
encodeMdocIssuerSigned: () => encodeMdocIssuerSigned,
getMdocDecodedPayload: () => getMdocDecodedPayload,
isLanguageValueObject: () => isLanguageValueObject,
isLanguageValueObjects: () => isLanguageValueObjects,
isVcdm1Credential: () => isVcdm1Credential,
isVcdm2Credential: () => isVcdm2Credential,
isWrappedMdocCredential: () => isWrappedMdocCredential,
isWrappedMdocPresentation: () => isWrappedMdocPresentation,
isWrappedSdJwtVerifiableCredential: () => isWrappedSdJwtVerifiableCredential,
isWrappedSdJwtVerifiablePresentation: () => isWrappedSdJwtVerifiablePresentation,
isWrappedW3CVerifiableCredential: () => isWrappedW3CVerifiableCredential,
isWrappedW3CVerifiablePresentation: () => isWrappedW3CVerifiablePresentation,
logOptions: () => logOptions,
mapLanguageValue: () => mapLanguageValue,
mapLanguageValues: () => mapLanguageValues,
mdocDecodedCredentialToUniformCredential: () => mdocDecodedCredentialToUniformCredential,
parseDid: () => parseDid,
sdJwtDecodedCredentialToUniformCredential: () => sdJwtDecodedCredentialToUniformCredential,
sha256: () => sha2562,
shaHasher: () => shaHasher,
toLanguageValueObject: () => toLanguageValueObject,
toLanguageValueObjects: () => toLanguageValueObjects
});
module.exports = __toCommonJS(index_exports);
// src/logging/index.ts
var import_debug = __toESM(require("debug"), 1);
var import_events = require("events");
var LogLevel = /* @__PURE__ */ (function(LogLevel2) {
LogLevel2[LogLevel2["TRACE"] = 0] = "TRACE";
LogLevel2[LogLevel2["DEBUG"] = 1] = "DEBUG";
LogLevel2[LogLevel2["INFO"] = 2] = "INFO";
LogLevel2[LogLevel2["WARNING"] = 3] = "WARNING";
LogLevel2[LogLevel2["ERROR"] = 4] = "ERROR";
return LogLevel2;
})({});
var LoggingEventType = /* @__PURE__ */ (function(LoggingEventType2) {
LoggingEventType2["AUDIT"] = "audit";
LoggingEventType2["ACTIVITY"] = "activity";
LoggingEventType2["GENERAL"] = "general";
return LoggingEventType2;
})({});
var LogMethod = /* @__PURE__ */ (function(LogMethod2) {
LogMethod2[LogMethod2["DEBUG_PKG"] = 0] = "DEBUG_PKG";
LogMethod2[LogMethod2["CONSOLE"] = 1] = "CONSOLE";
LogMethod2[LogMethod2["EVENT"] = 2] = "EVENT";
return LogMethod2;
})({});
function logOptions(opts) {
return {
namespace: opts?.namespace ?? "sphereon",
eventName: opts?.eventName ?? "sphereon:default",
defaultLogLevel: opts?.defaultLogLevel ?? 2,
methods: opts?.methods ?? [
0,
2
]
};
}
__name(logOptions, "logOptions");
var Loggers = class _Loggers {
static {
__name(this, "Loggers");
}
static DEFAULT_KEY = "__DEFAULT__";
static DEFAULT = new _Loggers({
defaultLogLevel: 2,
methods: [
0,
2
]
});
namespaceOptions = /* @__PURE__ */ new Map();
loggers = /* @__PURE__ */ new WeakMap();
constructor(defaultOptions) {
this.defaultOptions(logOptions(defaultOptions));
}
options(namespace, options) {
this.namespaceOptions.set(namespace, logOptions({
...options,
namespace
}));
return this;
}
defaultOptions(options) {
this.options(_Loggers.DEFAULT_KEY, options);
return this;
}
register(namespace, logger2) {
return this.get(namespace, logger2);
}
get(namespace, registerLogger) {
const options = this.namespaceOptions.get(namespace) ?? registerLogger?.options ?? this.namespaceOptions.get(_Loggers.DEFAULT_KEY);
if (!options) {
throw Error(`No logging options found for namespace ${namespace}`);
}
this.namespaceOptions.set(namespace, options);
let logger2 = this.loggers.get(options);
if (!logger2) {
logger2 = registerLogger ?? new SimpleLogger(options);
this.loggers.set(options, logger2);
}
return logger2;
}
};
var SimpleLogger = class {
static {
__name(this, "SimpleLogger");
}
_eventEmitter = new import_events.EventEmitter({
captureRejections: true
});
_options;
constructor(opts) {
this._options = logOptions(opts);
}
get eventEmitter() {
return this._eventEmitter;
}
get options() {
return this._options;
}
trace(value, ...args) {
this.logImpl(0, value, ...args);
}
debug(value, ...args) {
this.logImpl(1, value, ...args);
}
info(value, ...args) {
this.logImpl(2, value, ...args);
}
warning(value, ...args) {
this.logImpl(3, value, ...args);
}
error(value, ...args) {
this.logImpl(4, value, ...args);
}
logl(level, value, ...args) {
this.logImpl(level, value, ...args);
}
logImpl(level, value, ...args) {
const date = (/* @__PURE__ */ new Date()).toISOString();
const filteredArgs = args?.filter((v) => v) ?? [];
const arg = filteredArgs.length === 0 || filteredArgs[0] == void 0 ? void 0 : filteredArgs;
function toLogValue(options) {
if (typeof value === "string") {
return `${date}-(${options.namespace}) ${value}`;
} else if (typeof value === "object") {
value["namespace"] = options.namespace;
value["time"] = date;
}
return value;
}
__name(toLogValue, "toLogValue");
const logValue = toLogValue(this.options);
const logArgs = [
logValue
];
if (arg) {
logArgs.push(args);
}
let debugPkgEnabled = false;
if (debugPkgEnabled) {
const debugPkgDebugger = import_debug.default.default(this._options.namespace);
debugPkgEnabled = debugPkgDebugger.enabled;
if (debugPkgEnabled) {
if (arg) {
debugPkgDebugger(`${date}- ${value},`, ...arg);
} else {
debugPkgDebugger(`${date}- ${value}`);
}
}
}
if (this.options.methods.includes(1) && !debugPkgEnabled) {
const [value2, args2] = logArgs;
let logMethod = console.info;
switch (level) {
case 0:
logMethod = console.trace;
break;
case 1:
logMethod = console.debug;
break;
case 2:
logMethod = console.info;
break;
case 3:
logMethod = console.warn;
break;
case 4:
logMethod = console.error;
break;
}
if (args2) {
logMethod(value2 + ",", ...args2);
} else {
logMethod(value2);
}
}
if (this.options.methods.includes(2)) {
this._eventEmitter.emit(this.options.eventName, {
data: value.toString(),
timestamp: new Date(date),
level,
type: "general",
diagnosticData: logArgs
});
}
}
log(value, ...args) {
this.logImpl(this.options.defaultLogLevel, value, ...args);
}
};
var SimpleRecordLogger = class extends SimpleLogger {
static {
__name(this, "SimpleRecordLogger");
}
constructor(opts) {
super(opts);
}
};
// src/types/datastore.ts
var CredentialRole = /* @__PURE__ */ (function(CredentialRole2) {
CredentialRole2["ISSUER"] = "ISSUER";
CredentialRole2["VERIFIER"] = "VERIFIER";
CredentialRole2["HOLDER"] = "HOLDER";
CredentialRole2["FEDERATION_TRUST_ANCHOR"] = "FEDERATION_TRUST_ANCHOR";
return CredentialRole2;
})({});
// src/events/index.ts
var import_events2 = require("events");
var System = /* @__PURE__ */ (function(System2) {
System2["GENERAL"] = "general";
System2["KMS"] = "kms";
System2["IDENTITY"] = "identity";
System2["OID4VCI"] = "oid4vci";
System2["OID4VP"] = "oid4vp";
System2["SIOPv2"] = "siopv2";
System2["PE"] = "PE";
System2["CREDENTIALS"] = "credentials";
System2["WEB3"] = "web3";
System2["PROFILE"] = "profile";
System2["CONTACT"] = "contact";
return System2;
})({});
var SubSystem = /* @__PURE__ */ (function(SubSystem2) {
SubSystem2["KEY"] = "key";
SubSystem2["DID_PROVIDER"] = "did_provider";
SubSystem2["DID_RESOLVER"] = "did_resolver";
SubSystem2["OID4VP_OP"] = "oid4vp_op";
SubSystem2["OID4VCI_CLIENT"] = "oid4vci_client";
SubSystem2["SIOPv2_OP"] = "siopv2_op";
SubSystem2["CONTACT_MANAGER"] = "contact_manager";
SubSystem2["VC_ISSUER"] = "vc_issuer";
SubSystem2["VC_VERIFIER"] = "vc_verifier";
SubSystem2["VC_PERSISTENCE"] = "vc_persistence";
SubSystem2["TRANSPORT"] = "transport";
SubSystem2["PROFILE"] = "profile";
SubSystem2["API"] = "api";
return SubSystem2;
})({});
var ActionType = /* @__PURE__ */ (function(ActionType2) {
ActionType2["CREATE"] = "create";
ActionType2["READ"] = "read";
ActionType2["UPDATE"] = "update";
ActionType2["DELETE"] = "delete";
ActionType2["EXECUTE"] = "execute";
return ActionType2;
})({});
var DefaultActionSubType = /* @__PURE__ */ (function(DefaultActionSubType2) {
DefaultActionSubType2["KEY_GENERATION"] = "Key generation";
DefaultActionSubType2["KEY_IMPORT"] = "Key import";
DefaultActionSubType2["KEY_PERSISTENCE"] = "Key persistence";
DefaultActionSubType2["KEY_REMOVAL"] = "Key removal";
DefaultActionSubType2["DID_CREATION"] = "DID creation";
DefaultActionSubType2["DID_RESOLUTION"] = "DID resolution";
DefaultActionSubType2["DID_SERVICE_UPDATE"] = "DID service update";
DefaultActionSubType2["VC_ISSUE"] = "VC issue";
DefaultActionSubType2["VC_VERIFY"] = "VC verify";
DefaultActionSubType2["VC_SHARE"] = "VC share";
DefaultActionSubType2["VC_DELETE"] = "VC delete";
DefaultActionSubType2["VC_ISSUE_DECLINE"] = "VC issue decline";
DefaultActionSubType2["VC_SHARE_DECLINE"] = "VC share decline";
return DefaultActionSubType2;
})({});
var InitiatorType = /* @__PURE__ */ (function(InitiatorType2) {
InitiatorType2["USER"] = "user";
InitiatorType2["SYSTEM"] = "system";
InitiatorType2["EXTERNAL"] = "external";
return InitiatorType2;
})({});
var SystemCorrelationIdType = /* @__PURE__ */ (function(SystemCorrelationIdType2) {
SystemCorrelationIdType2["DID"] = "did";
SystemCorrelationIdType2["URL"] = "url";
SystemCorrelationIdType2["EMAIL"] = "email";
SystemCorrelationIdType2["HOSTNAME"] = "hostname";
SystemCorrelationIdType2["PHONE"] = "phone";
SystemCorrelationIdType2["USER"] = "user";
return SystemCorrelationIdType2;
})({});
var EventManager = class _EventManager {
static {
__name(this, "EventManager");
}
static INSTANCE = new _EventManager();
_emitters = /* @__PURE__ */ new Map();
constructor() {
}
static instance() {
return _EventManager.INSTANCE;
}
register(name, emitter, opts) {
this._emitters.set(name, {
emitter,
enabled: opts?.disabled !== true
});
return emitter;
}
get(name, opts) {
const { emitter, enabled } = this._emitters.get(name) ?? {};
if (!emitter) {
throw Error(`No emitter registered with name ${name}`);
} else if (opts?.onlyEnabled && !enabled) {
throw Error(`Emitter with name ${name} is not enabled`);
}
return emitter;
}
getOrCreate(name, opts) {
if (this.has(name)) {
return this.get(name, opts);
}
return this.register(name, new BasicEventEmitter());
}
has(name) {
return this._emitters.has(name);
}
emitters(filter) {
const all = Array.from(new Set(this._emitters.values()));
return this.emittersImpl(all, filter).map((e) => e.emitter);
}
hasEventName(eventName) {
return this.eventNames().includes(eventName);
}
eventNames() {
return Array.from(new Set(this.emitters().flatMap((emitter) => emitter.eventNames())));
}
emitBasic(event, ...args) {
return this.emit(event.eventName, event, args);
}
emit(eventName, event, ...args) {
if ("id" in event && "system" in event && !event.eventName) {
event.eventName = eventName;
}
Loggers.DEFAULT.options("sphereon:events", {
methods: [
LogMethod.CONSOLE
],
defaultLogLevel: LogLevel.INFO
}).get("sphereon:events").log(`Emitting '${eventName.toString()}' event`, event);
const emitters = this.emitters({
eventName
});
emitters.flatMap((emitter) => emitter.emit(eventName, event, args));
}
listenerCount(eventName) {
const emitters = this.emitters({
eventName
});
return emitters.map((emitter) => emitter.listenerCount(eventName)).reduce((previous, current) => current + previous);
}
listeners(filter) {
const emitters = filter?.emitterName ? [
this.get(filter.emitterName, filter)
] : this.emitters(filter);
return Array.from(new Set(this.emittersImpl(emitters.map((emitter) => {
return {
emitter,
enabled: true
};
}), filter).flatMap((emitter) => emitter.emitter.listeners(filter.eventName))));
}
emittersImpl(all, filter) {
const { eventName } = filter ?? {};
if (!eventName) {
return all;
}
const filtered = all.filter((emitter) => emitter.emitter.eventNames().includes(eventName) && (emitter.enabled || filter?.onlyEnabled !== true));
return Array.from(new Set(filtered));
}
};
var BasicEventEmitter = class extends import_events2.EventEmitter {
static {
__name(this, "BasicEventEmitter");
}
addListener(eventName, listener) {
return super.addListener(eventName, listener);
}
once(eventName, listener) {
return super.once(eventName, listener);
}
emit(eventName, event, ...args) {
return super.emit(eventName, ...args);
}
};
// src/utils/object.ts
var BASE64_REGEX = /^[-A-Za-z0-9+_/]*={0,3}$/g;
var ObjectUtils = class _ObjectUtils {
static {
__name(this, "ObjectUtils");
}
static asArray(value) {
return Array.isArray(value) ? value : [
value
];
}
static isObject(value) {
return typeof value === "object" || Object.prototype.toString.call(value) === "[object Object]";
}
static isUrlAbsolute(url) {
const isAbsoluteRegex = /^([A-Za-z][A-Za-z0-9+-.]*|_):[^\s]*$/;
_ObjectUtils.isString(url) && isAbsoluteRegex.test(url);
}
static isString(value) {
return typeof value === "string" || Object.prototype.toString.call(value) === "[object String]";
}
static isBase64(value) {
if (!_ObjectUtils.isString(value)) {
return false;
}
return value.match(BASE64_REGEX) !== null;
}
};
// src/utils/hasher.ts
var import_sha2 = require("@noble/hashes/sha2");
var u8a = __toESM(require("uint8arrays"), 1);
var { fromString } = u8a;
var supportedAlgorithms = [
"sha256",
"sha384",
"sha512"
];
var shaHasher = /* @__PURE__ */ __name((data, algorithm) => {
const sanitizedAlgorithm = algorithm.toLowerCase().replace(/[-_]/g, "");
if (!supportedAlgorithms.includes(sanitizedAlgorithm)) {
throw new Error(`Unsupported hashing algorithm ${algorithm}`);
}
const hasher = sanitizedAlgorithm === "sha384" ? import_sha2.sha384 : sanitizedAlgorithm === "sha512" ? import_sha2.sha512 : import_sha2.sha256;
return hasher(typeof data === "string" ? fromString(data) : new Uint8Array(data));
}, "shaHasher");
var defaultHasher = shaHasher;
// src/utils/vc.ts
function isWrappedW3CVerifiableCredential(vc) {
return vc.format === "jwt_vc" || vc.format === "ldp_vc";
}
__name(isWrappedW3CVerifiableCredential, "isWrappedW3CVerifiableCredential");
function isWrappedW3CVerifiablePresentation(vp) {
return vp.format === "jwt_vp" || vp.format === "ldp_vp";
}
__name(isWrappedW3CVerifiablePresentation, "isWrappedW3CVerifiablePresentation");
var StatusListType = /* @__PURE__ */ (function(StatusListType2) {
StatusListType2["StatusList2021"] = "StatusList2021";
StatusListType2["OAuthStatusList"] = "OAuthStatusList";
StatusListType2["BitstringStatusList"] = "BitstringStatusList";
return StatusListType2;
})({});
function isVcdmCredential(credential, vcdmType) {
if (!credential || typeof credential !== "object") {
return false;
} else if (!("@context" in credential && Array.isArray(credential["@context"]))) {
return false;
}
return credential["@context"].includes(vcdmType);
}
__name(isVcdmCredential, "isVcdmCredential");
function isVcdm1Credential(credential) {
return isVcdmCredential(credential, VCDM_CREDENTIAL_CONTEXT_V1);
}
__name(isVcdm1Credential, "isVcdm1Credential");
function isVcdm2Credential(credential) {
return isVcdmCredential(credential, VCDM_CREDENTIAL_CONTEXT_V2);
}
__name(isVcdm2Credential, "isVcdm2Credential");
function addVcdmContextIfNeeded(context, defaultValue = VCDM_CREDENTIAL_CONTEXT_V2) {
const newContext = [
...context ?? []
];
const vcdmContext = context?.find((val) => VCDM_CREDENTIAL_CONTEXT_VERSIONS.includes(val));
if (!vcdmContext) {
newContext.unshift(defaultValue);
}
return newContext;
}
__name(addVcdmContextIfNeeded, "addVcdmContextIfNeeded");
var VCDM_CREDENTIAL_CONTEXT_V1 = "https://www.w3.org/2018/credentials/v1";
var VCDM_CREDENTIAL_CONTEXT_V2 = "https://www.w3.org/ns/credentials/v2";
var VCDM_CREDENTIAL_CONTEXT_VERSIONS = [
VCDM_CREDENTIAL_CONTEXT_V2,
VCDM_CREDENTIAL_CONTEXT_V1
];
// src/utils/did.ts
var IProofPurpose = /* @__PURE__ */ (function(IProofPurpose2) {
IProofPurpose2["verificationMethod"] = "verificationMethod";
IProofPurpose2["assertionMethod"] = "assertionMethod";
IProofPurpose2["authentication"] = "authentication";
IProofPurpose2["keyAgreement"] = "keyAgreement";
IProofPurpose2["contractAgreement"] = "contactAgreement";
IProofPurpose2["capabilityInvocation"] = "capabilityInvocation";
IProofPurpose2["capabilityDelegation"] = "capabilityDelegation";
return IProofPurpose2;
})({});
var IProofType = /* @__PURE__ */ (function(IProofType2) {
IProofType2["Ed25519Signature2018"] = "Ed25519Signature2018";
IProofType2["Ed25519Signature2020"] = "Ed25519Signature2020";
IProofType2["EcdsaSecp256k1Signature2019"] = "EcdsaSecp256k1Signature2019";
IProofType2["EcdsaSecp256k1RecoverySignature2020"] = "EcdsaSecp256k1RecoverySignature2020";
IProofType2["JsonWebSignature2020"] = "JsonWebSignature2020";
IProofType2["RsaSignature2018"] = "RsaSignature2018";
IProofType2["GpgSignature2020"] = "GpgSignature2020";
IProofType2["JcsEd25519Signature2020"] = "JcsEd25519Signature2020";
IProofType2["BbsBlsSignatureProof2020"] = "BbsBlsSignatureProof2020";
IProofType2["BbsBlsBoundSignatureProof2020"] = "BbsBlsBoundSignatureProof2020";
IProofType2["JwtProof2020"] = "JwtProof2020";
IProofType2["SdJwtProof2024"] = "SdJwtProof2024";
IProofType2["MdocProof2024"] = "MsoMdocProof2024";
return IProofType2;
})({});
var parseDid = /* @__PURE__ */ __name((did) => {
const parsedDid = parse(did);
if (parsedDid === null) {
throw new Error("invalid did");
}
return parsedDid;
}, "parseDid");
var parse = /* @__PURE__ */ __name((didUrl) => {
const PCT_ENCODED = "(?:%[0-9a-fA-F]{2})";
const ID_CHAR = `(?:[a-zA-Z0-9._-]|${PCT_ENCODED})`;
const METHOD = "([a-z0-9]+)";
const METHOD_ID = `((?:${ID_CHAR}*:)*(${ID_CHAR}+))`;
const PARAM_CHAR = "[a-zA-Z0-9_.:%-]";
const PARAM = `;${PARAM_CHAR}+=${PARAM_CHAR}*`;
const PARAMS = `((${PARAM})*)`;
const PATH = `(/[^#?]*)?`;
const QUERY = `([?][^#]*)?`;
const FRAGMENT = `(#.*)?`;
const DID_MATCHER = new RegExp(`^did:${METHOD}:${METHOD_ID}${PARAMS}${PATH}${QUERY}${FRAGMENT}$`);
if (didUrl === "" || !didUrl) return null;
const sections = didUrl.match(DID_MATCHER);
if (sections) {
const parts = {
did: `did:${sections[1]}:${sections[2]}`,
method: sections[1],
id: sections[2],
didUrl
};
if (sections[4]) {
const params = sections[4].slice(1).split(";");
parts.params = {};
for (const p of params) {
const kv = p.split("=");
parts.params[kv[0]] = kv[1];
}
}
if (sections[6]) parts.path = sections[6];
if (sections[7]) parts.query = sections[7].slice(1);
if (sections[8]) parts.fragment = sections[8].slice(1);
return parts;
}
return null;
}, "parse");
// src/utils/mdoc.ts
var import_kmp_mdoc_core = __toESM(require("@sphereon/kmp-mdoc-core"), 1);
var { com } = import_kmp_mdoc_core.default;
function isWrappedMdocCredential(vc) {
return vc.format === "mso_mdoc";
}
__name(isWrappedMdocCredential, "isWrappedMdocCredential");
function isWrappedMdocPresentation(vp) {
return vp.format === "mso_mdoc";
}
__name(isWrappedMdocPresentation, "isWrappedMdocPresentation");
function getMdocDecodedPayload(mdoc) {
const mdocJson = mdoc.toJson();
if (!mdocJson.issuerSigned.nameSpaces) {
throw Error(`Cannot access Issuer Signed items from the Mdoc`);
}
const issuerSignedJson = mdoc.issuerSigned.toJsonDTO();
const namespaces = issuerSignedJson.nameSpaces;
const decodedPayload = {};
for (const [namespace, items] of Object.entries(namespaces)) {
decodedPayload[namespace] = items.reduce((acc, item) => ({
...acc,
[item.key]: item.value.value
}), {});
}
return decodedPayload;
}
__name(getMdocDecodedPayload, "getMdocDecodedPayload");
function decodeMdocIssuerSigned(oid4vpIssuerSigned) {
const issuerSigned = com.sphereon.mdoc.data.device.IssuerSignedCbor.Static.cborDecode(com.sphereon.kmp.decodeFrom(oid4vpIssuerSigned, com.sphereon.kmp.Encoding.BASE64URL));
const holderMdoc = issuerSigned.toDocument();
return holderMdoc;
}
__name(decodeMdocIssuerSigned, "decodeMdocIssuerSigned");
function encodeMdocIssuerSigned(issuerSigned, encoding = "base64url") {
return com.sphereon.kmp.encodeTo(issuerSigned.cborEncode(), com.sphereon.kmp.Encoding.BASE64URL);
}
__name(encodeMdocIssuerSigned, "encodeMdocIssuerSigned");
function decodeMdocDeviceResponse(vpToken) {
const deviceResponse = com.sphereon.mdoc.data.device.DeviceResponseCbor.Static.cborDecode(com.sphereon.kmp.decodeFrom(vpToken, com.sphereon.kmp.Encoding.BASE64URL));
return deviceResponse;
}
__name(decodeMdocDeviceResponse, "decodeMdocDeviceResponse");
var mdocDecodedCredentialToUniformCredential = /* @__PURE__ */ __name((decoded, opts) => {
const document = decoded.toJson();
const json = document.toJsonDTO();
const type = "Personal Identification Data";
const MSO = document.MSO;
if (!MSO || !json.issuerSigned?.nameSpaces) {
throw Error(`Cannot access Mobile Security Object or Issuer Signed items from the Mdoc`);
}
const nameSpaces = json.issuerSigned.nameSpaces;
if (!("eu.europa.ec.eudi.pid.1" in nameSpaces)) {
throw Error(`Only PID supported at present`);
}
const items = nameSpaces["eu.europa.ec.eudi.pid.1"];
if (!items || items.length === 0) {
throw Error(`No issuer signed items were found`);
}
const credentialSubject = items.reduce((acc, item) => {
if (Array.isArray(item.value)) {
acc[item.key] = item.value.map((val) => val.value).join(", ");
} else {
acc[item.key] = item.value.value;
}
return acc;
}, {});
const validFrom = MSO.validityInfo.validFrom;
const validUntil = MSO.validityInfo.validUntil;
const docType = MSO.docType;
const expirationDate = validUntil;
let issuanceDateStr = validFrom;
const issuanceDate = issuanceDateStr;
if (!issuanceDate) {
throw Error(`JWT issuance date is required but was not present`);
}
const credential = {
type: [
docType
],
"@context": [],
credentialSubject: {
type,
...credentialSubject
},
issuanceDate,
expirationDate,
proof: {
type: IProofType.MdocProof2024,
created: issuanceDate,
proofPurpose: IProofPurpose.authentication,
verificationMethod: json.issuerSigned.issuerAuth.payload,
mso_mdoc: com.sphereon.kmp.encodeTo(decoded.cborEncode(), com.sphereon.kmp.Encoding.BASE64URL)
}
};
return credential;
}, "mdocDecodedCredentialToUniformCredential");
// src/utils/sd-jwt.ts
var import_decode = require("@sd-jwt/decode");
function decodeSdJwtVc(compactSdJwtVc, hasher) {
const { jwt, disclosures, kbJwt } = (0, import_decode.decodeSdJwtSync)(compactSdJwtVc, hasher);
const signedPayload = jwt.payload;
const decodedPayload = (0, import_decode.getClaimsSync)(signedPayload, disclosures, hasher);
const compactKeyBindingJwt = kbJwt ? compactSdJwtVc.split("~").pop() : void 0;
const type = decodedPayload.vct ? "dc+sd-jwt" : "vc+sd-jwt";
return {
compactSdJwtVc,
type,
decodedPayload,
disclosures: disclosures.map((d) => {
const decoded = d.key ? [
d.salt,
d.key,
d.value
] : [
d.salt,
d.value
];
if (!d._digest) throw new Error("Implementation error: digest not present in disclosure");
return {
decoded,
digest: d._digest,
encoded: d.encode()
};
}),
signedPayload,
...compactKeyBindingJwt && kbJwt && {
kbJwt: {
header: kbJwt.header,
compact: compactKeyBindingJwt,
payload: kbJwt.payload
}
}
};
}
__name(decodeSdJwtVc, "decodeSdJwtVc");
async function decodeSdJwtVcAsync(compactSdJwtVc, hasher) {
const { jwt, disclosures, kbJwt } = await (0, import_decode.decodeSdJwt)(compactSdJwtVc, hasher);
const signedPayload = jwt.payload;
const decodedPayload = await (0, import_decode.getClaims)(signedPayload, disclosures, hasher);
const compactKeyBindingJwt = kbJwt ? compactSdJwtVc.split("~").pop() : void 0;
const type = decodedPayload.vct ? "dc+sd-jwt" : "vc+sd-jwt";
return {
compactSdJwtVc,
type,
decodedPayload,
disclosures: disclosures.map((d) => {
const decoded = d.key ? [
d.salt,
d.key,
d.value
] : [
d.salt,
d.value
];
if (!d._digest) throw new Error("Implementation error: digest not present in disclosure");
return {
decoded,
digest: d._digest,
encoded: d.encode()
};
}),
signedPayload,
...compactKeyBindingJwt && kbJwt && {
kbJwt: {
header: kbJwt.header,
payload: kbJwt.payload,
compact: compactKeyBindingJwt
}
}
};
}
__name(decodeSdJwtVcAsync, "decodeSdJwtVcAsync");
var sdJwtDecodedCredentialToUniformCredential = /* @__PURE__ */ __name((decoded, opts) => {
const { decodedPayload } = decoded;
const { exp, nbf, iss, iat, vct, cnf, status, jti, validUntil, validFrom } = decodedPayload;
let credentialSubject = decodedPayload.credentialSubject;
let issuer = iss ?? decodedPayload.issuer;
if (typeof issuer === "object" && "id" in issuer && typeof issuer.id === "string") {
issuer = issuer.id;
}
const subId = decodedPayload.sub ?? (typeof credentialSubject == "object" && "id" in credentialSubject ? credentialSubject.id : void 0);
const maxSkewInMS = opts?.maxTimeSkewInMS ?? 1500;
const expirationDate = validUntil ?? jwtDateToISOString({
jwtClaim: exp,
claimName: "exp"
});
let issuanceDateStr = validFrom ?? jwtDateToISOString({
jwtClaim: iat,
claimName: "iat"
});
let nbfDateAsStr;
if (nbf) {
nbfDateAsStr = jwtDateToISOString({
jwtClaim: nbf,
claimName: "nbf"
});
if (issuanceDateStr && nbfDateAsStr && issuanceDateStr !== nbfDateAsStr) {
const diff = Math.abs(new Date(nbfDateAsStr).getTime() - new Date(issuanceDateStr).getTime());
if (!maxSkewInMS || diff > maxSkewInMS) {
throw Error(`Inconsistent issuance dates between JWT claim (${nbfDateAsStr}) and VC value (${iss})`);
}
}
issuanceDateStr = nbfDateAsStr;
}
const issuanceDate = issuanceDateStr;
if (!issuanceDate) {
throw Error(`JWT issuance date is required but was not present`);
}
const excludedFields = /* @__PURE__ */ new Set([
"vct",
"cnf",
"iss",
"iat",
"exp",
"nbf",
"jti",
"sub"
]);
if (!credentialSubject) {
credentialSubject = Object.entries(decodedPayload).reduce((acc, [key, value]) => {
if (!excludedFields.has(key) && value !== void 0 && value !== "" && !(typeof value === "object" && value !== null && Object.keys(value).length === 0)) {
acc[key] = value;
}
return acc;
}, {});
}
const sdJwtVc = decodedPayload.vct && !decodedPayload.type;
const credential = {
...{
type: sdJwtVc ? [
vct
] : decodedPayload.type
},
...{
"@context": sdJwtVc ? [] : decodedPayload["@context"]
},
credentialSubject: {
...credentialSubject,
id: subId ?? jti
},
...issuanceDate && (sdJwtVc ? {
issuanceDate
} : {
validFrom: issuanceDateStr
}),
...expirationDate && (sdJwtVc ? {
expirationDate
} : {
validUntil: expirationDate
}),
issuer,
...cnf && {
cnf
},
...status && {
status
},
proof: {
type: IProofType.SdJwtProof2024,
created: nbfDateAsStr ?? issuanceDate,
proofPurpose: IProofPurpose.authentication,
verificationMethod: iss,
jwt: decoded.compactSdJwtVc
}
};
return credential;
}, "sdJwtDecodedCredentialToUniformCredential");
var jwtDateToISOString = /* @__PURE__ */ __name(({ jwtClaim, claimName, isRequired = false }) => {
if (jwtClaim) {
const claim = parseInt(jwtClaim.toString());
return new Date(claim * (claim < 9999999999 ? 1e3 : 1)).toISOString().replace(/\.000Z/, "Z");
} else if (isRequired) {
throw Error(`JWT claim ${claimName} is required but was not present`);
}
return void 0;
}, "jwtDateToISOString");
// src/utils/jose.ts
var JwkKeyType = /* @__PURE__ */ (function(JwkKeyType2) {
JwkKeyType2["EC"] = "EC";
JwkKeyType2["RSA"] = "RSA";
JwkKeyType2["oct"] = "oct";
JwkKeyType2["OKP"] = "OKP";
return JwkKeyType2;
})({});
var JoseSignatureAlgorithm = /* @__PURE__ */ (function(JoseSignatureAlgorithm2) {
JoseSignatureAlgorithm2["RS256"] = "RS256";
JoseSignatureAlgorithm2["RS384"] = "RS384";
JoseSignatureAlgorithm2["RS512"] = "RS512";
JoseSignatureAlgorithm2["ES256"] = "ES256";
JoseSignatureAlgorithm2["ES256K"] = "ES256K";
JoseSignatureAlgorithm2["ES384"] = "ES384";
JoseSignatureAlgorithm2["ES512"] = "ES512";
JoseSignatureAlgorithm2["EdDSA"] = "EdDSA";
JoseSignatureAlgorithm2["HS256"] = "HS256";
JoseSignatureAlgorithm2["HS384"] = "HS384";
JoseSignatureAlgorithm2["HS512"] = "HS512";
JoseSignatureAlgorithm2["PS256"] = "PS256";
JoseSignatureAlgorithm2["PS384"] = "PS384";
JoseSignatureAlgorithm2["PS512"] = "PS512";
JoseSignatureAlgorithm2["none"] = "none";
return JoseSignatureAlgorithm2;
})({});
var JoseKeyOperation = /* @__PURE__ */ (function(JoseKeyOperation2) {
JoseKeyOperation2["SIGN"] = "sign";
JoseKeyOperation2["VERIFY"] = "verify";
JoseKeyOperation2["ENCRYPT"] = "encrypt";
JoseKeyOperation2["DECRYPT"] = "decrypt";
JoseKeyOperation2["WRAP_KEY"] = "wrapKey";
JoseKeyOperation2["UNWRAP_KEY"] = "unwrapKey";
JoseKeyOperation2["DERIVE_KEY"] = "deriveKey";
JoseKeyOperation2["DERIVE_BITS"] = "deriveBits";
return JoseKeyOperation2;
})({});
var JoseCurve = /* @__PURE__ */ (function(JoseCurve2) {
JoseCurve2["P_256"] = "P-256";
JoseCurve2["P_384"] = "P-384";
JoseCurve2["P_521"] = "P-521";
JoseCurve2["X25519"] = "X25519";
JoseCurve2["X448"] = "X448";
JoseCurve2["EdDSA"] = "EdDSA";
JoseCurve2["Ed25519"] = "Ed25519";
JoseCurve2["Ed448"] = "Ed448";
JoseCurve2["secp256k1"] = "secp256k1";
return JoseCurve2;
})({});
// src/utils/cose.ts
var ICoseKeyType = /* @__PURE__ */ (function(ICoseKeyType2) {
ICoseKeyType2[ICoseKeyType2["OKP"] = 1] = "OKP";
ICoseKeyType2[ICoseKeyType2["EC2"] = 2] = "EC2";
ICoseKeyType2[ICoseKeyType2["RSA"] = 3] = "RSA";
ICoseKeyType2[ICoseKeyType2["Symmetric"] = 4] = "Symmetric";
ICoseKeyType2[ICoseKeyType2["Reserved"] = 0] = "Reserved";
return ICoseKeyType2;
})({});
var ICoseSignatureAlgorithm = /* @__PURE__ */ (function(ICoseSignatureAlgorithm2) {
ICoseSignatureAlgorithm2[ICoseSignatureAlgorithm2["ES256"] = -7] = "ES256";
ICoseSignatureAlgorithm2[ICoseSignatureAlgorithm2["ES256K"] = -47] = "ES256K";
ICoseSignatureAlgorithm2[ICoseSignatureAlgorithm2["ES384"] = -35] = "ES384";
ICoseSignatureAlgorithm2[ICoseSignatureAlgorithm2["ES512"] = -36] = "ES512";
ICoseSignatureAlgorithm2[ICoseSignatureAlgorithm2["EdDSA"] = -8] = "EdDSA";
ICoseSignatureAlgorithm2[ICoseSignatureAlgorithm2["HS256_64"] = 4] = "HS256_64";
ICoseSignatureAlgorithm2[ICoseSignatureAlgorithm2["HS256"] = 5] = "HS256";
ICoseSignatureAlgorithm2[ICoseSignatureAlgorithm2["HS384"] = 6] = "HS384";
ICoseSignatureAlgorithm2[ICoseSignatureAlgorithm2["HS512"] = 7] = "HS512";
ICoseSignatureAlgorithm2[ICoseSignatureAlgorithm2["PS256"] = -37] = "PS256";
ICoseSignatureAlgorithm2[ICoseSignatureAlgorithm2["PS384"] = -38] = "PS384";
ICoseSignatureAlgorithm2[ICoseSignatureAlgorithm2["PS512"] = -39] = "PS512";
return ICoseSignatureAlgorithm2;
})({});
var ICoseKeyOperation = /* @__PURE__ */ (function(ICoseKeyOperation2) {
ICoseKeyOperation2[ICoseKeyOperation2["SIGN"] = 1] = "SIGN";
ICoseKeyOperation2[ICoseKeyOperation2["VERIFY"] = 2] = "VERIFY";
ICoseKeyOperation2[ICoseKeyOperation2["ENCRYPT"] = 3] = "ENCRYPT";
ICoseKeyOperation2[ICoseKeyOperation2["DECRYPT"] = 4] = "DECRYPT";
ICoseKeyOperation2[ICoseKeyOperation2["WRAP_KEY"] = 5] = "WRAP_KEY";
ICoseKeyOperation2[ICoseKeyOperation2["UNWRAP_KEY"] = 6] = "UNWRAP_KEY";
ICoseKeyOperation2[ICoseKeyOperation2["DERIVE_KEY"] = 7] = "DERIVE_KEY";
ICoseKeyOperation2[ICoseKeyOperation2["DERIVE_BITS"] = 8] = "DERIVE_BITS";
ICoseKeyOperation2[ICoseKeyOperation2["MAC_CREATE"] = 9] = "MAC_CREATE";
ICoseKeyOperation2[ICoseKeyOperation2["MAC_VERIFY"] = 10] = "MAC_VERIFY";
return ICoseKeyOperation2;
})({});
var ICoseCurve = /* @__PURE__ */ (function(ICoseCurve2) {
ICoseCurve2[ICoseCurve2["P_256"] = 1] = "P_256";
ICoseCurve2[ICoseCurve2["P_384"] = 2] = "P_384";
ICoseCurve2[ICoseCurve2["P_521"] = 3] = "P_521";
ICoseCurve2[ICoseCurve2["X25519"] = 4] = "X25519";
ICoseCurve2[ICoseCurve2["X448"] = 5] = "X448";
ICoseCurve2[ICoseCurve2["Ed25519"] = 6] = "Ed25519";
ICoseCurve2[ICoseCurve2["Ed448"] = 7] = "Ed448";
ICoseCurve2[ICoseCurve2["secp256k1"] = -1] = "secp256k1";
return ICoseCurve2;
})({});
// src/mapper/credential-constraints.ts
var StatusListCredentialIdMode = /* @__PURE__ */ (function(StatusListCredentialIdMode2) {
StatusListCredentialIdMode2["ISSUANCE"] = "ISSUANCE";
StatusListCredentialIdMode2["NEVER"] = "NEVER";
return StatusListCredentialIdMode2;
})({});
var StatusListDriverType = /* @__PURE__ */ (function(StatusListDriverType2) {
StatusListDriverType2["AGENT_TYPEORM"] = "agent_typeorm";
return StatusListDriverType2;
})({});
// src/mapper/credential-mapper.ts
var import_jwt_decode = require("jwt-decode");
var sha2562 = /* @__PURE__ */ __name((data) => {
return defaultHasher(data, "sha256");
}, "sha256");
var CredentialMapper = class _CredentialMapper {
static {
__name(this, "CredentialMapper");
}
/**
* Decodes a compact SD-JWT vc to it's decoded variant. This method can be used when the hasher implementation used is Async, and therefore not suitable for usage
* with the other decode methods.
*/
static decodeSdJwtVcAsync(compactSdJwtVc, hasher) {
return decodeSdJwtVcAsync(compactSdJwtVc, hasher ?? sha2562);
}
/**
* Decodes a Verifiable Presentation to a uniform format.
*
* When decoding SD-JWT credentials, a hasher implementation must be provided. The hasher implementation must be sync. When using
* an async hasher implementation, use the decodeSdJwtVcAsync method instead and you can provide the decoded payload to methods
* instead of the compact SD-JWT.
*
* @param presentation
* @param hasher Hasher implementation to use for SD-JWT decoding.
*/
static decodeVerifiablePresentation(presentation, hasher) {
if (_CredentialMapper.isJwtEncoded(presentation)) {
const payload = (0, import_jwt_decode.jwtDecode)(presentation);
const header = (0, import_jwt_decode.jwtDecode)(presentation, {
header: true
});
payload.vp.proof = {
type: IProofType.JwtProof2020,
created: payload.nbf,
proofPurpose: IProofPurpose.authentication,
verificationMethod: header["kid"] ?? payload.iss,
jwt: presentation
};
return payload;
} else if (_CredentialMapper.isJwtDecodedPresentation(presentation)) {
return presentation;
} else if (_CredentialMapper.isSdJwtEncoded(presentation)) {
return decodeSdJwtVc(presentation, hasher ?? sha2562);
} else if (_CredentialMapper.isSdJwtDecodedCredential(presentation)) {
return presentation;
} else if (_CredentialMapper.isMsoMdocOid4VPEncoded(presentation)) {
return presentation;
} else if (_CredentialMapper.isMsoMdocDecodedPresentation(presentation)) {
return presentation;
} else if (_CredentialMapper.isJsonLdAsString(presentation)) {
return JSON.parse(presentation);
} else {
return presentation;
}
}
/**
* Decodes a Verifiable Credential to a uniform format.
*
* When decoding SD-JWT credentials, a hasher implementation must be provided. The hasher implementation must be sync. When using
* an async hasher implementation, use the decodeSdJwtVcAsync method instead and you can provide the decoded payload to methods
* instead of the compact SD-JWT.
*
* @param credential
* @param hasher Hasher implementation to use for SD-JWT decoding
*/
static decodeVerifiableCredential(credential, hasher) {
if (_CredentialMapper.isJwtEncoded(credential)) {
const payload = (0, import_jwt_decode.jwtDecode)(credential);
const header = (0, import_jwt_decode.jwtDecode)(credential, {
header: true
});
payload.vc = payload.vc ?? {};
payload.vc.proof = {
type: IProofType.JwtProof2020,
created: payload.nbf,
proofPurpose: IProofPurpose.authentication,
verificationMethod: header["kid"] ?? payload.iss,
jwt: credential
};
return payload;
} else if (_CredentialMapper.isJwtDecodedCredential(credential)) {
return credential;
} else if (_CredentialMapper.isJsonLdAsString(credential)) {
return JSON.parse(credential);
} else if (_CredentialMapper.isSdJwtEncoded(credential)) {
return decodeSdJwtVc(credential, hasher ?? sha2562);
} else if (_CredentialMapper.isSdJwtDecodedCredential(credential)) {
return credential;
} else {
return credential;
}
}
/**
* Converts a presentation to a wrapped presentation.
*
* When decoding SD-JWT credentials, a hasher implementation must be provided. The hasher implementation must be sync. When using
* an async hasher implementation, use the decodeSdJwtVcAsync method instead and you can provide the decoded payload to methods
* instead of the compact SD-JWT.
*
* @param originalPresentation
* @param opts
*/
static toWrappedVerifiablePresentation(originalPresentation, opts) {
if (_CredentialMapper.isMsoMdocDecodedPresentation(originalPresentation) || _CredentialMapper.isMsoMdocOid4VPEncoded(originalPresentation)) {
let deviceResponse;
let originalType;
if (_CredentialMapper.isMsoMdocOid4VPEncoded(originalPresentation)) {
deviceResponse = decodeMdocDeviceResponse(originalPresentation);
originalType = "mso_mdoc-encoded";
} else {
deviceResponse = originalPresentation;
originalType = "mso_mdoc-decoded";
}
const mdocCredentials = deviceResponse.documents?.map((doc) => _CredentialMapper.toWrappedVerifiableCredential(doc, opts));
if (!mdocCredentials || mdocCredentials.length === 0) {
throw new Error("could not extract any mdoc credentials from mdoc device response");
}
return {
type: originalType,
format: "mso_mdoc",
original: originalPresentation,
presentation: deviceResponse,
decoded: deviceResponse,
vcs: mdocCredentials
};
}
if (_CredentialMapper.isSdJwtDecodedCredential(originalPresentation) || _CredentialMapper.isSdJwtEncoded(originalPresentation)) {
let decodedPresentation;
if (_CredentialMapper.isSdJwtEncoded(originalPresentation)) {
decodedPresentation = decodeSdJwtVc(originalPresentation, opts?.hasher ?? sha2562);
} else {
decodedPresentation = originalPresentation;
}
return {
type: _CredentialMapper.isSdJwtDecodedCredential(originalPresentation) ? "sd-jwt-vc-decoded" : "sd-jwt-vc-encoded",
format: "dc+sd-jwt",
original: originalPresentation,
presentation: decodedPresentation,
decoded: decodedPresentation.decodedPayload,
// NOTE: we also include the SD-JWT VC as the VC, as the SD-JWT acts as both the VC and the VP
vcs: [
_CredentialMapper.toWrappedVerifiableCredential(originalPresentation, opts)
]
};
}
const proof = _CredentialMapper.getFirstProof(originalPresentation);
const original = typeof originalPresentation !== "string" && _CredentialMapper.hasJWTProofType(originalPresentation) ? proof?.jwt : originalPresentation;
if (!original) {
throw Error("Could not determine original presentation, probably it was a converted JWT presentation, that is now missing the JWT value in the proof");
}
const decoded = _CredentialMapper.decodeVerifiablePresentation(original);
const isJwtEncoded = _CredentialMapper.isJwtEncoded(original);
const isJwtDecoded = _CredentialMapper.isJwtDecodedPresentation(original);
const type = isJwtEncoded ? "jwt-encoded" : isJwtDecoded ? "jwt-decoded" : "json-ld";
const format = isJwtDecoded || isJwtEncoded ? "jwt_vp" : "ldp_vp";
let vp;
if (isJwtEncoded || isJwtDecoded) {
vp = _CredentialMapper.jwtDecodedPresentationToUniformPresentation(decoded, false, opts);
} else {
vp = decoded;
}
if (!vp) {
throw Error(`VP key not found`);
}
const noVCs = !("verifiableCredential" in vp) || !vp.verifiableCredential || vp.verifiableCredential.length === 0;
if (noVCs) {
console.warn(`Presentation without verifiable credentials. That is rare! `);
}
const vcs = noVCs ? [] : _CredentialMapper.toWrappedVerifiableCredentials(vp.verifiableCredential ?? [], opts);
const presentation = {
...vp,
verifiableCredential: vcs
};
return {
type,
format,
original,
decoded,
presentation,
vcs
};
}
/**
* Converts a list of credentials to a list of wrapped credentials.
*
* When decoding SD-JWT credentials, a hasher implementation must be provided. The hasher implementation must be sync. When using
* an async hasher implementation, use the decodeSdJwtVcAsync method instead and you can provide the decoded payload to methods
* instead of the compact SD-JWT.
*
* @param hasher Hasher implementation to use for SD-JWT decoding
*/
static toWrappedVerifiableCredentials(verifiableCredentials, opts) {
return verifiableCredentials.map((vc) => _CredentialMapper.toWrappedVerifiableCredential(vc, opts));
}
/**
* Converts a credential to a wrapped credential.
*
* When decoding SD-JWT credentials, a hasher implementation must be provided. The hasher implementation must be sync. When using
* an async hasher implementation, use the decodeSdJwtVcAsync method instead and you can provide the decoded payload to methods
* instead of the compact SD-JWT.
*
* @param hasher Hasher implementation to use for SD-JWT decoding
*/
static toWrappedVerifiableCredential(verifiableCredential, opts) {
if (_CredentialMapper.isMsoMdocDecodedCredential(verifiableCredential) || _CredentialMapper.isMsoMdocOid4VPEncoded(verifiableCredential)) {
let mdoc;
if (_CredentialMapper.isMsoMdocOid4VPEncoded(verifiableCredential)) {
mdoc = decodeMdocIssuerSigned(verifiableCredential);
} else {
mdoc = verifiableCredential;
}
return {
type: _CredentialMapper.isMsoMdocDecodedCredential(verifiableCredential) ? "mso_mdoc-decoded" : "mso_mdoc-encoded",
format: "mso_mdoc",
original: verifiableCredential,
credential: mdoc,
decoded: getMdocDecodedPayload(mdoc)
};
}
if (_CredentialMapper.isSdJwtDecodedCredential(verifiableCredential) || _CredentialMapper.isSdJwtEncoded(verifiableCredential)) {
let decodedCredential;
if (_CredentialMapper.isSdJwtEncoded(verifiableCredential)) {
const hasher = opts?.hasher ?? sha2562;
decodedCredential = decodeSdJwtVc(verifiableCredential, hasher);
} else {
decodedCredential = verifiableCredential;
}
return {
type: _CredentialMapper.isSdJwtDecodedCredential(verifiableCredential) ? "sd-jwt-vc-decoded" : "sd-jwt-vc-encoded",
format: "dc+sd-jwt",
original: verifiableCredential,
credential: decodedCredential,
decoded: decodedCredential.decodedPayload
};
}
const proof = _CredentialMapper.getFirstProof(verifiableCredential);
const original = _CredentialMapper.hasJWTProofType(verifiableCredential) && proof ? proof.jwt ?? verifiableCredential : verifiableCredential;
if (!original) {
throw Error("Could not determine original credential, probably it was a converted JWT credential, that is now missing the JWT value in the proof");
}
const decoded = _CredentialMapper.decodeVerifiableCredential(original);
const isJwtEncoded = _CredentialMapper.isJwtEncoded(original);
const isJwtDecoded = _CredentialMapper.isJwtDecodedCredential(original);
const type = isJwtEncoded ? "jwt-encoded" : isJwtDecoded ? "jwt-decoded" : "json-ld";
const credential = isJwtEncoded || isJwtDecoded ? _CredentialMapper.jwtDecodedCredentialToUniformCredential(decoded, opts) : decoded;
const format = isJwtEncoded || isJwtDecoded ? "jwt_vc" : "ldp_vc";
return {
original,
decoded,
format,
type,
credential
};
}
static isJwtEncoded(original) {
return ObjectUtils.isString(original) && original.startsWith("ey") && !original.includes("~");
}
static isSdJwtEncoded(original) {
return ObjectUtils.isString(original) && original.startsWith("ey") && original.includes("~");
}
static isMsoMdocOid4VPEncoded(original) {
return ObjectUtils.isString(original) && !original.startsWith("ey") && ObjectUtils.isBase64(original);
}
static isW3cCredential(credential) {
return typeof credential === "object" && "@context" in credential && (credential.type?.includes("VerifiableCredential") || false);
}
static isCredential(original) {
try {
if (_CredentialMapper.isJwtEncoded(original)) {
const vc = _CredentialMapper.toUniformCredential(original);
return _CredentialMapper.isW3cCredential(vc);
} else if (_CredentialMapper.isSdJwtEncoded(original)) {
return true;
} else if (_CredentialMapper.isMsoMdocDecodedCredential(original)) {
return true;
} else if (_CredentialMapper.isMsoMdocOid4VPEncoded(original)) {
return true;
}
return _CredentialMapper.isW3cCredential(o