@sphereon/ssi-types 0.33.0 → 0.33.1-feature.jose.vcdm.55

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/dist/index.cjs +1619 -0
  2. package/dist/index.cjs.map +1 -0
  3. package/dist/index.d.cts +1580 -0
  4. package/dist/index.d.ts +1580 -6
  5. package/dist/index.js +1587 -24
  6. package/dist/index.js.map +1 -1
  7. package/package.json +23 -14
  8. package/src/index.ts +3 -2
  9. package/src/logging/index.ts +6 -4
  10. package/src/mapper/credential-constraints.ts +19 -1
  11. package/src/mapper/credential-mapper.ts +66 -23
  12. package/src/mapper/index.ts +1 -0
  13. package/src/types/cose.ts +4 -4
  14. package/src/types/did.ts +0 -87
  15. package/src/types/index.ts +14 -13
  16. package/src/types/mso_mdoc.ts +10 -138
  17. package/src/types/sd-jwt-vc.ts +4 -178
  18. package/src/types/status-list.ts +2 -3
  19. package/src/types/vc.ts +3 -29
  20. package/src/types/w3c-vc.ts +3 -22
  21. package/src/utils/did.ts +92 -0
  22. package/src/utils/hasher.ts +5 -2
  23. package/src/utils/index.ts +4 -0
  24. package/src/utils/mdoc.ts +139 -0
  25. package/src/utils/sd-jwt.ts +179 -0
  26. package/src/utils/vc.ts +9 -0
  27. package/dist/events/index.d.ts +0 -116
  28. package/dist/events/index.d.ts.map +0 -1
  29. package/dist/events/index.js +0 -165
  30. package/dist/events/index.js.map +0 -1
  31. package/dist/index.d.ts.map +0 -1
  32. package/dist/logging/index.d.ts +0 -73
  33. package/dist/logging/index.d.ts.map +0 -1
  34. package/dist/logging/index.js +0 -186
  35. package/dist/logging/index.js.map +0 -1
  36. package/dist/mapper/credential-constraints.d.ts +0 -16
  37. package/dist/mapper/credential-constraints.d.ts.map +0 -1
  38. package/dist/mapper/credential-constraints.js +0 -3
  39. package/dist/mapper/credential-constraints.js.map +0 -1
  40. package/dist/mapper/credential-mapper.d.ts +0 -124
  41. package/dist/mapper/credential-mapper.d.ts.map +0 -1
  42. package/dist/mapper/credential-mapper.js +0 -774
  43. package/dist/mapper/credential-mapper.js.map +0 -1
  44. package/dist/mapper/index.d.ts +0 -3
  45. package/dist/mapper/index.d.ts.map +0 -1
  46. package/dist/mapper/index.js +0 -19
  47. package/dist/mapper/index.js.map +0 -1
  48. package/dist/mapper/jsonld-language-values.d.ts +0 -18
  49. package/dist/mapper/jsonld-language-values.d.ts.map +0 -1
  50. package/dist/mapper/jsonld-language-values.js +0 -79
  51. package/dist/mapper/jsonld-language-values.js.map +0 -1
  52. package/dist/types/cose.d.ts +0 -77
  53. package/dist/types/cose.d.ts.map +0 -1
  54. package/dist/types/cose.js +0 -51
  55. package/dist/types/cose.js.map +0 -1
  56. package/dist/types/dcql.d.ts +0 -33
  57. package/dist/types/dcql.d.ts.map +0 -1
  58. package/dist/types/dcql.js +0 -4
  59. package/dist/types/dcql.js.map +0 -1
  60. package/dist/types/did.d.ts +0 -186
  61. package/dist/types/did.d.ts.map +0 -1
  62. package/dist/types/did.js +0 -78
  63. package/dist/types/did.js.map +0 -1
  64. package/dist/types/generic.d.ts +0 -44
  65. package/dist/types/generic.d.ts.map +0 -1
  66. package/dist/types/generic.js +0 -3
  67. package/dist/types/generic.js.map +0 -1
  68. package/dist/types/index.d.ts +0 -14
  69. package/dist/types/index.d.ts.map +0 -1
  70. package/dist/types/index.js +0 -30
  71. package/dist/types/index.js.map +0 -1
  72. package/dist/types/jose.d.ts +0 -89
  73. package/dist/types/jose.d.ts.map +0 -1
  74. package/dist/types/jose.js +0 -55
  75. package/dist/types/jose.js.map +0 -1
  76. package/dist/types/metadata-types.d.ts +0 -5
  77. package/dist/types/metadata-types.d.ts.map +0 -1
  78. package/dist/types/metadata-types.js +0 -3
  79. package/dist/types/metadata-types.js.map +0 -1
  80. package/dist/types/mso_mdoc.d.ts +0 -94
  81. package/dist/types/mso_mdoc.d.ts.map +0 -1
  82. package/dist/types/mso_mdoc.js +0 -121
  83. package/dist/types/mso_mdoc.js.map +0 -1
  84. package/dist/types/pex.d.ts +0 -36
  85. package/dist/types/pex.d.ts.map +0 -1
  86. package/dist/types/pex.js +0 -3
  87. package/dist/types/pex.js.map +0 -1
  88. package/dist/types/sd-jwt-type-metadata.d.ts +0 -191
  89. package/dist/types/sd-jwt-type-metadata.d.ts.map +0 -1
  90. package/dist/types/sd-jwt-type-metadata.js +0 -3
  91. package/dist/types/sd-jwt-type-metadata.js.map +0 -1
  92. package/dist/types/sd-jwt-vc.d.ts +0 -196
  93. package/dist/types/sd-jwt-vc.d.ts.map +0 -1
  94. package/dist/types/sd-jwt-vc.js +0 -142
  95. package/dist/types/sd-jwt-vc.js.map +0 -1
  96. package/dist/types/status-list.d.ts +0 -10
  97. package/dist/types/status-list.d.ts.map +0 -1
  98. package/dist/types/status-list.js +0 -9
  99. package/dist/types/status-list.js.map +0 -1
  100. package/dist/types/vc.d.ts +0 -28
  101. package/dist/types/vc.d.ts.map +0 -1
  102. package/dist/types/vc.js +0 -28
  103. package/dist/types/vc.js.map +0 -1
  104. package/dist/types/w3c-vc.d.ts +0 -243
  105. package/dist/types/w3c-vc.d.ts.map +0 -1
  106. package/dist/types/w3c-vc.js +0 -26
  107. package/dist/types/w3c-vc.js.map +0 -1
  108. package/dist/utils/hasher.d.ts +0 -4
  109. package/dist/utils/hasher.d.ts.map +0 -1
  110. package/dist/utils/hasher.js +0 -40
  111. package/dist/utils/hasher.js.map +0 -1
  112. package/dist/utils/index.d.ts +0 -3
  113. package/dist/utils/index.d.ts.map +0 -1
  114. package/dist/utils/index.js +0 -19
  115. package/dist/utils/index.js.map +0 -1
  116. package/dist/utils/object.d.ts +0 -8
  117. package/dist/utils/object.d.ts.map +0 -1
  118. package/dist/utils/object.js +0 -28
  119. package/dist/utils/object.js.map +0 -1
package/dist/index.cjs ADDED
@@ -0,0 +1,1619 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+
31
+ // src/index.ts
32
+ var index_exports = {};
33
+ __export(index_exports, {
34
+ ActionType: () => ActionType,
35
+ BasicEventEmitter: () => BasicEventEmitter,
36
+ CredentialMapper: () => CredentialMapper,
37
+ DefaultActionSubType: () => DefaultActionSubType,
38
+ DocumentFormat: () => DocumentFormat,
39
+ EventManager: () => EventManager,
40
+ IProofPurpose: () => IProofPurpose,
41
+ IProofType: () => IProofType,
42
+ InitiatorType: () => InitiatorType,
43
+ JWT_PROOF_TYPE_2020: () => JWT_PROOF_TYPE_2020,
44
+ LogLevel: () => LogLevel,
45
+ LogMethod: () => LogMethod,
46
+ Loggers: () => Loggers,
47
+ LoggingEventType: () => LoggingEventType,
48
+ ObjectUtils: () => ObjectUtils,
49
+ OriginalType: () => OriginalType,
50
+ SimpleLogger: () => SimpleLogger,
51
+ SimpleRecordLogger: () => SimpleRecordLogger,
52
+ StatusListCredentialIdMode: () => StatusListCredentialIdMode,
53
+ StatusListDriverType: () => StatusListDriverType,
54
+ SubSystem: () => SubSystem,
55
+ System: () => System,
56
+ SystemCorrelationIdType: () => SystemCorrelationIdType,
57
+ decodeMdocDeviceResponse: () => decodeMdocDeviceResponse,
58
+ decodeMdocIssuerSigned: () => decodeMdocIssuerSigned,
59
+ decodeSdJwtVc: () => decodeSdJwtVc,
60
+ decodeSdJwtVcAsync: () => decodeSdJwtVcAsync,
61
+ defaultHasher: () => defaultHasher,
62
+ encodeMdocIssuerSigned: () => encodeMdocIssuerSigned,
63
+ getMdocDecodedPayload: () => getMdocDecodedPayload,
64
+ isLanguageValueObject: () => isLanguageValueObject,
65
+ isLanguageValueObjects: () => isLanguageValueObjects,
66
+ isWrappedMdocCredential: () => isWrappedMdocCredential,
67
+ isWrappedMdocPresentation: () => isWrappedMdocPresentation,
68
+ isWrappedSdJwtVerifiableCredential: () => isWrappedSdJwtVerifiableCredential,
69
+ isWrappedSdJwtVerifiablePresentation: () => isWrappedSdJwtVerifiablePresentation,
70
+ isWrappedW3CVerifiableCredential: () => isWrappedW3CVerifiableCredential,
71
+ isWrappedW3CVerifiablePresentation: () => isWrappedW3CVerifiablePresentation,
72
+ logOptions: () => logOptions,
73
+ mapLanguageValue: () => mapLanguageValue,
74
+ mapLanguageValues: () => mapLanguageValues,
75
+ mdocDecodedCredentialToUniformCredential: () => mdocDecodedCredentialToUniformCredential,
76
+ parseDid: () => parseDid,
77
+ sdJwtDecodedCredentialToUniformCredential: () => sdJwtDecodedCredentialToUniformCredential,
78
+ sha256: () => sha2562,
79
+ shaHasher: () => shaHasher,
80
+ toLanguageValueObject: () => toLanguageValueObject,
81
+ toLanguageValueObjects: () => toLanguageValueObjects
82
+ });
83
+ module.exports = __toCommonJS(index_exports);
84
+
85
+ // src/logging/index.ts
86
+ var import_debug = __toESM(require("debug"), 1);
87
+ var import_events = require("events");
88
+ var LogLevel = /* @__PURE__ */ function(LogLevel2) {
89
+ LogLevel2[LogLevel2["TRACE"] = 0] = "TRACE";
90
+ LogLevel2[LogLevel2["DEBUG"] = 1] = "DEBUG";
91
+ LogLevel2[LogLevel2["INFO"] = 2] = "INFO";
92
+ LogLevel2[LogLevel2["WARNING"] = 3] = "WARNING";
93
+ LogLevel2[LogLevel2["ERROR"] = 4] = "ERROR";
94
+ return LogLevel2;
95
+ }({});
96
+ var LoggingEventType = /* @__PURE__ */ function(LoggingEventType2) {
97
+ LoggingEventType2["AUDIT"] = "audit";
98
+ LoggingEventType2["ACTIVITY"] = "activity";
99
+ LoggingEventType2["GENERAL"] = "general";
100
+ return LoggingEventType2;
101
+ }({});
102
+ var LogMethod = /* @__PURE__ */ function(LogMethod2) {
103
+ LogMethod2[LogMethod2["DEBUG_PKG"] = 0] = "DEBUG_PKG";
104
+ LogMethod2[LogMethod2["CONSOLE"] = 1] = "CONSOLE";
105
+ LogMethod2[LogMethod2["EVENT"] = 2] = "EVENT";
106
+ return LogMethod2;
107
+ }({});
108
+ function logOptions(opts) {
109
+ return {
110
+ namespace: opts?.namespace ?? "sphereon",
111
+ eventName: opts?.eventName ?? "sphereon:default",
112
+ defaultLogLevel: opts?.defaultLogLevel ?? 2,
113
+ methods: opts?.methods ?? [
114
+ 0,
115
+ 2
116
+ ]
117
+ };
118
+ }
119
+ __name(logOptions, "logOptions");
120
+ var Loggers = class _Loggers {
121
+ static {
122
+ __name(this, "Loggers");
123
+ }
124
+ static DEFAULT_KEY = "__DEFAULT__";
125
+ static DEFAULT = new _Loggers({
126
+ defaultLogLevel: 2,
127
+ methods: [
128
+ 0,
129
+ 2
130
+ ]
131
+ });
132
+ namespaceOptions = /* @__PURE__ */ new Map();
133
+ loggers = /* @__PURE__ */ new WeakMap();
134
+ constructor(defaultOptions) {
135
+ this.defaultOptions(logOptions(defaultOptions));
136
+ }
137
+ options(namespace, options) {
138
+ this.namespaceOptions.set(namespace, logOptions({
139
+ ...options,
140
+ namespace
141
+ }));
142
+ return this;
143
+ }
144
+ defaultOptions(options) {
145
+ this.options(_Loggers.DEFAULT_KEY, options);
146
+ return this;
147
+ }
148
+ register(namespace, logger2) {
149
+ return this.get(namespace, logger2);
150
+ }
151
+ get(namespace, registerLogger) {
152
+ const options = this.namespaceOptions.get(namespace) ?? registerLogger?.options ?? this.namespaceOptions.get(_Loggers.DEFAULT_KEY);
153
+ if (!options) {
154
+ throw Error(`No logging options found for namespace ${namespace}`);
155
+ }
156
+ this.namespaceOptions.set(namespace, options);
157
+ let logger2 = this.loggers.get(options);
158
+ if (!logger2) {
159
+ logger2 = registerLogger ?? new SimpleLogger(options);
160
+ this.loggers.set(options, logger2);
161
+ }
162
+ return logger2;
163
+ }
164
+ };
165
+ var SimpleLogger = class {
166
+ static {
167
+ __name(this, "SimpleLogger");
168
+ }
169
+ _eventEmitter = new import_events.EventEmitter({
170
+ captureRejections: true
171
+ });
172
+ _options;
173
+ constructor(opts) {
174
+ this._options = logOptions(opts);
175
+ }
176
+ get eventEmitter() {
177
+ return this._eventEmitter;
178
+ }
179
+ get options() {
180
+ return this._options;
181
+ }
182
+ trace(value, ...args) {
183
+ this.logImpl(0, value, ...args);
184
+ }
185
+ debug(value, ...args) {
186
+ this.logImpl(1, value, ...args);
187
+ }
188
+ info(value, ...args) {
189
+ this.logImpl(2, value, ...args);
190
+ }
191
+ warning(value, ...args) {
192
+ this.logImpl(3, value, ...args);
193
+ }
194
+ error(value, ...args) {
195
+ this.logImpl(4, value, ...args);
196
+ }
197
+ logl(level, value, ...args) {
198
+ this.logImpl(level, value, ...args);
199
+ }
200
+ logImpl(level, value, ...args) {
201
+ const date = (/* @__PURE__ */ new Date()).toISOString();
202
+ const filteredArgs = args?.filter((v) => v) ?? [];
203
+ const arg = filteredArgs.length === 0 || filteredArgs[0] == void 0 ? void 0 : filteredArgs;
204
+ function toLogValue(options) {
205
+ if (typeof value === "string") {
206
+ return `${date}-(${options.namespace}) ${value}`;
207
+ } else if (typeof value === "object") {
208
+ value["namespace"] = options.namespace;
209
+ value["time"] = date;
210
+ }
211
+ return value;
212
+ }
213
+ __name(toLogValue, "toLogValue");
214
+ const logValue = toLogValue(this.options);
215
+ const logArgs = [
216
+ logValue
217
+ ];
218
+ if (arg) {
219
+ logArgs.push(args);
220
+ }
221
+ let debugPkgEnabled = false;
222
+ if (debugPkgEnabled) {
223
+ const debugPkgDebugger = import_debug.default.default(this._options.namespace);
224
+ debugPkgEnabled = debugPkgDebugger.enabled;
225
+ if (debugPkgEnabled) {
226
+ if (arg) {
227
+ debugPkgDebugger(`${date}- ${value},`, ...arg);
228
+ } else {
229
+ debugPkgDebugger(`${date}- ${value}`);
230
+ }
231
+ }
232
+ }
233
+ if (this.options.methods.includes(1) && !debugPkgEnabled) {
234
+ const [value2, args2] = logArgs;
235
+ let logMethod = console.info;
236
+ switch (level) {
237
+ case 0:
238
+ logMethod = console.trace;
239
+ break;
240
+ case 1:
241
+ logMethod = console.debug;
242
+ break;
243
+ case 2:
244
+ logMethod = console.info;
245
+ break;
246
+ case 3:
247
+ logMethod = console.warn;
248
+ break;
249
+ case 4:
250
+ logMethod = console.error;
251
+ break;
252
+ }
253
+ if (args2) {
254
+ logMethod(value2 + ",", ...args2);
255
+ } else {
256
+ logMethod(value2);
257
+ }
258
+ }
259
+ if (this.options.methods.includes(2)) {
260
+ this._eventEmitter.emit(this.options.eventName, {
261
+ data: value.toString(),
262
+ timestamp: new Date(date),
263
+ level,
264
+ type: "general",
265
+ diagnosticData: logArgs
266
+ });
267
+ }
268
+ }
269
+ log(value, ...args) {
270
+ this.logImpl(this.options.defaultLogLevel, value, ...args);
271
+ }
272
+ };
273
+ var SimpleRecordLogger = class extends SimpleLogger {
274
+ static {
275
+ __name(this, "SimpleRecordLogger");
276
+ }
277
+ constructor(opts) {
278
+ super(opts);
279
+ }
280
+ };
281
+
282
+ // src/events/index.ts
283
+ var import_events2 = require("events");
284
+ var System = /* @__PURE__ */ function(System2) {
285
+ System2["GENERAL"] = "general";
286
+ System2["KMS"] = "kms";
287
+ System2["IDENTITY"] = "identity";
288
+ System2["OID4VCI"] = "oid4vci";
289
+ System2["OID4VP"] = "oid4vp";
290
+ System2["SIOPv2"] = "siopv2";
291
+ System2["PE"] = "PE";
292
+ System2["CREDENTIALS"] = "credentials";
293
+ System2["WEB3"] = "web3";
294
+ System2["PROFILE"] = "profile";
295
+ System2["CONTACT"] = "contact";
296
+ return System2;
297
+ }({});
298
+ var SubSystem = /* @__PURE__ */ function(SubSystem2) {
299
+ SubSystem2["KEY"] = "key";
300
+ SubSystem2["DID_PROVIDER"] = "did_provider";
301
+ SubSystem2["DID_RESOLVER"] = "did_resolver";
302
+ SubSystem2["OID4VP_OP"] = "oid4vp_op";
303
+ SubSystem2["OID4VCI_CLIENT"] = "oid4vci_client";
304
+ SubSystem2["SIOPv2_OP"] = "siopv2_op";
305
+ SubSystem2["CONTACT_MANAGER"] = "contact_manager";
306
+ SubSystem2["VC_ISSUER"] = "vc_issuer";
307
+ SubSystem2["VC_VERIFIER"] = "vc_verifier";
308
+ SubSystem2["VC_PERSISTENCE"] = "vc_persistence";
309
+ SubSystem2["TRANSPORT"] = "transport";
310
+ SubSystem2["PROFILE"] = "profile";
311
+ SubSystem2["API"] = "api";
312
+ return SubSystem2;
313
+ }({});
314
+ var ActionType = /* @__PURE__ */ function(ActionType2) {
315
+ ActionType2["CREATE"] = "create";
316
+ ActionType2["READ"] = "read";
317
+ ActionType2["UPDATE"] = "update";
318
+ ActionType2["DELETE"] = "delete";
319
+ ActionType2["EXECUTE"] = "execute";
320
+ return ActionType2;
321
+ }({});
322
+ var DefaultActionSubType = /* @__PURE__ */ function(DefaultActionSubType2) {
323
+ DefaultActionSubType2["KEY_GENERATION"] = "Key generation";
324
+ DefaultActionSubType2["KEY_IMPORT"] = "Key import";
325
+ DefaultActionSubType2["KEY_PERSISTENCE"] = "Key persistence";
326
+ DefaultActionSubType2["KEY_REMOVAL"] = "Key removal";
327
+ DefaultActionSubType2["DID_CREATION"] = "DID creation";
328
+ DefaultActionSubType2["DID_RESOLUTION"] = "DID resolution";
329
+ DefaultActionSubType2["DID_SERVICE_UPDATE"] = "DID service update";
330
+ DefaultActionSubType2["VC_ISSUE"] = "VC issue";
331
+ DefaultActionSubType2["VC_VERIFY"] = "VC verify";
332
+ DefaultActionSubType2["VC_SHARE"] = "VC share";
333
+ DefaultActionSubType2["VC_DELETE"] = "VC delete";
334
+ DefaultActionSubType2["VC_ISSUE_DECLINE"] = "VC issue decline";
335
+ DefaultActionSubType2["VC_SHARE_DECLINE"] = "VC share decline";
336
+ return DefaultActionSubType2;
337
+ }({});
338
+ var InitiatorType = /* @__PURE__ */ function(InitiatorType2) {
339
+ InitiatorType2["USER"] = "user";
340
+ InitiatorType2["SYSTEM"] = "system";
341
+ InitiatorType2["EXTERNAL"] = "external";
342
+ return InitiatorType2;
343
+ }({});
344
+ var SystemCorrelationIdType = /* @__PURE__ */ function(SystemCorrelationIdType2) {
345
+ SystemCorrelationIdType2["DID"] = "did";
346
+ SystemCorrelationIdType2["URL"] = "url";
347
+ SystemCorrelationIdType2["EMAIL"] = "email";
348
+ SystemCorrelationIdType2["HOSTNAME"] = "hostname";
349
+ SystemCorrelationIdType2["PHONE"] = "phone";
350
+ SystemCorrelationIdType2["USER"] = "user";
351
+ return SystemCorrelationIdType2;
352
+ }({});
353
+ var EventManager = class _EventManager {
354
+ static {
355
+ __name(this, "EventManager");
356
+ }
357
+ static INSTANCE = new _EventManager();
358
+ _emitters = /* @__PURE__ */ new Map();
359
+ constructor() {
360
+ }
361
+ static instance() {
362
+ return _EventManager.INSTANCE;
363
+ }
364
+ register(name, emitter, opts) {
365
+ this._emitters.set(name, {
366
+ emitter,
367
+ enabled: opts?.disabled !== true
368
+ });
369
+ return emitter;
370
+ }
371
+ get(name, opts) {
372
+ const { emitter, enabled } = this._emitters.get(name) ?? {};
373
+ if (!emitter) {
374
+ throw Error(`No emitter registered with name ${name}`);
375
+ } else if (opts?.onlyEnabled && !enabled) {
376
+ throw Error(`Emitter with name ${name} is not enabled`);
377
+ }
378
+ return emitter;
379
+ }
380
+ getOrCreate(name, opts) {
381
+ if (this.has(name)) {
382
+ return this.get(name, opts);
383
+ }
384
+ return this.register(name, new BasicEventEmitter());
385
+ }
386
+ has(name) {
387
+ return this._emitters.has(name);
388
+ }
389
+ emitters(filter) {
390
+ const all = Array.from(new Set(this._emitters.values()));
391
+ return this.emittersImpl(all, filter).map((e) => e.emitter);
392
+ }
393
+ hasEventName(eventName) {
394
+ return this.eventNames().includes(eventName);
395
+ }
396
+ eventNames() {
397
+ return Array.from(new Set(this.emitters().flatMap((emitter) => emitter.eventNames())));
398
+ }
399
+ emitBasic(event, ...args) {
400
+ return this.emit(event.eventName, event, args);
401
+ }
402
+ emit(eventName, event, ...args) {
403
+ if ("id" in event && "system" in event && !event.eventName) {
404
+ event.eventName = eventName;
405
+ }
406
+ Loggers.DEFAULT.options("sphereon:events", {
407
+ methods: [
408
+ LogMethod.CONSOLE
409
+ ],
410
+ defaultLogLevel: LogLevel.INFO
411
+ }).get("sphereon:events").log(`Emitting '${eventName.toString()}' event`, event);
412
+ const emitters = this.emitters({
413
+ eventName
414
+ });
415
+ emitters.flatMap((emitter) => emitter.emit(eventName, event, args));
416
+ }
417
+ listenerCount(eventName) {
418
+ const emitters = this.emitters({
419
+ eventName
420
+ });
421
+ return emitters.map((emitter) => emitter.listenerCount(eventName)).reduce((previous, current) => current + previous);
422
+ }
423
+ listeners(filter) {
424
+ const emitters = filter?.emitterName ? [
425
+ this.get(filter.emitterName, filter)
426
+ ] : this.emitters(filter);
427
+ return Array.from(new Set(this.emittersImpl(emitters.map((emitter) => {
428
+ return {
429
+ emitter,
430
+ enabled: true
431
+ };
432
+ }), filter).flatMap((emitter) => emitter.emitter.listeners(filter.eventName))));
433
+ }
434
+ emittersImpl(all, filter) {
435
+ const { eventName } = filter ?? {};
436
+ if (!eventName) {
437
+ return all;
438
+ }
439
+ const filtered = all.filter((emitter) => emitter.emitter.eventNames().includes(eventName) && (emitter.enabled || filter?.onlyEnabled !== true));
440
+ return Array.from(new Set(filtered));
441
+ }
442
+ };
443
+ var BasicEventEmitter = class extends import_events2.EventEmitter {
444
+ static {
445
+ __name(this, "BasicEventEmitter");
446
+ }
447
+ addListener(eventName, listener) {
448
+ return super.addListener(eventName, listener);
449
+ }
450
+ once(eventName, listener) {
451
+ return super.once(eventName, listener);
452
+ }
453
+ emit(eventName, event, ...args) {
454
+ return super.emit(eventName, ...args);
455
+ }
456
+ };
457
+
458
+ // src/utils/object.ts
459
+ var BASE64_REGEX = /^[-A-Za-z0-9+_/]*={0,3}$/g;
460
+ var ObjectUtils = class _ObjectUtils {
461
+ static {
462
+ __name(this, "ObjectUtils");
463
+ }
464
+ static asArray(value) {
465
+ return Array.isArray(value) ? value : [
466
+ value
467
+ ];
468
+ }
469
+ static isObject(value) {
470
+ return typeof value === "object" || Object.prototype.toString.call(value) === "[object Object]";
471
+ }
472
+ static isUrlAbsolute(url) {
473
+ const isAbsoluteRegex = /^([A-Za-z][A-Za-z0-9+-.]*|_):[^\s]*$/;
474
+ _ObjectUtils.isString(url) && isAbsoluteRegex.test(url);
475
+ }
476
+ static isString(value) {
477
+ return typeof value === "string" || Object.prototype.toString.call(value) === "[object String]";
478
+ }
479
+ static isBase64(value) {
480
+ if (!_ObjectUtils.isString(value)) {
481
+ return false;
482
+ }
483
+ return value.match(BASE64_REGEX) !== null;
484
+ }
485
+ };
486
+
487
+ // src/utils/hasher.ts
488
+ var import_sha2 = require("@noble/hashes/sha2");
489
+ var u8a = __toESM(require("uint8arrays"), 1);
490
+ var { fromString } = u8a;
491
+ var supportedAlgorithms = [
492
+ "sha256",
493
+ "sha384",
494
+ "sha512"
495
+ ];
496
+ var shaHasher = /* @__PURE__ */ __name((data, algorithm) => {
497
+ const sanitizedAlgorithm = algorithm.toLowerCase().replace(/[-_]/g, "");
498
+ if (!supportedAlgorithms.includes(sanitizedAlgorithm)) {
499
+ throw new Error(`Unsupported hashing algorithm ${algorithm}`);
500
+ }
501
+ const hasher = sanitizedAlgorithm === "sha384" ? import_sha2.sha384 : sanitizedAlgorithm === "sha512" ? import_sha2.sha512 : import_sha2.sha256;
502
+ return hasher(typeof data === "string" ? fromString(data) : new Uint8Array(data));
503
+ }, "shaHasher");
504
+ var defaultHasher = shaHasher;
505
+
506
+ // src/utils/vc.ts
507
+ function isWrappedW3CVerifiableCredential(vc) {
508
+ return vc.format === "jwt_vc" || vc.format === "ldp_vc";
509
+ }
510
+ __name(isWrappedW3CVerifiableCredential, "isWrappedW3CVerifiableCredential");
511
+ function isWrappedW3CVerifiablePresentation(vp) {
512
+ return vp.format === "jwt_vp" || vp.format === "ldp_vp";
513
+ }
514
+ __name(isWrappedW3CVerifiablePresentation, "isWrappedW3CVerifiablePresentation");
515
+
516
+ // src/utils/did.ts
517
+ var IProofPurpose = /* @__PURE__ */ function(IProofPurpose2) {
518
+ IProofPurpose2["verificationMethod"] = "verificationMethod";
519
+ IProofPurpose2["assertionMethod"] = "assertionMethod";
520
+ IProofPurpose2["authentication"] = "authentication";
521
+ IProofPurpose2["keyAgreement"] = "keyAgreement";
522
+ IProofPurpose2["contractAgreement"] = "contactAgreement";
523
+ IProofPurpose2["capabilityInvocation"] = "capabilityInvocation";
524
+ IProofPurpose2["capabilityDelegation"] = "capabilityDelegation";
525
+ return IProofPurpose2;
526
+ }({});
527
+ var IProofType = /* @__PURE__ */ function(IProofType2) {
528
+ IProofType2["Ed25519Signature2018"] = "Ed25519Signature2018";
529
+ IProofType2["Ed25519Signature2020"] = "Ed25519Signature2020";
530
+ IProofType2["EcdsaSecp256k1Signature2019"] = "EcdsaSecp256k1Signature2019";
531
+ IProofType2["EcdsaSecp256k1RecoverySignature2020"] = "EcdsaSecp256k1RecoverySignature2020";
532
+ IProofType2["JsonWebSignature2020"] = "JsonWebSignature2020";
533
+ IProofType2["RsaSignature2018"] = "RsaSignature2018";
534
+ IProofType2["GpgSignature2020"] = "GpgSignature2020";
535
+ IProofType2["JcsEd25519Signature2020"] = "JcsEd25519Signature2020";
536
+ IProofType2["BbsBlsSignatureProof2020"] = "BbsBlsSignatureProof2020";
537
+ IProofType2["BbsBlsBoundSignatureProof2020"] = "BbsBlsBoundSignatureProof2020";
538
+ IProofType2["JwtProof2020"] = "JwtProof2020";
539
+ IProofType2["SdJwtProof2024"] = "SdJwtProof2024";
540
+ IProofType2["MdocProof2024"] = "MsoMdocProof2024";
541
+ return IProofType2;
542
+ }({});
543
+ var parseDid = /* @__PURE__ */ __name((did) => {
544
+ const parsedDid = parse(did);
545
+ if (parsedDid === null) {
546
+ throw new Error("invalid did");
547
+ }
548
+ return parsedDid;
549
+ }, "parseDid");
550
+ var parse = /* @__PURE__ */ __name((didUrl) => {
551
+ const PCT_ENCODED = "(?:%[0-9a-fA-F]{2})";
552
+ const ID_CHAR = `(?:[a-zA-Z0-9._-]|${PCT_ENCODED})`;
553
+ const METHOD = "([a-z0-9]+)";
554
+ const METHOD_ID = `((?:${ID_CHAR}*:)*(${ID_CHAR}+))`;
555
+ const PARAM_CHAR = "[a-zA-Z0-9_.:%-]";
556
+ const PARAM = `;${PARAM_CHAR}+=${PARAM_CHAR}*`;
557
+ const PARAMS = `((${PARAM})*)`;
558
+ const PATH = `(/[^#?]*)?`;
559
+ const QUERY = `([?][^#]*)?`;
560
+ const FRAGMENT = `(#.*)?`;
561
+ const DID_MATCHER = new RegExp(`^did:${METHOD}:${METHOD_ID}${PARAMS}${PATH}${QUERY}${FRAGMENT}$`);
562
+ if (didUrl === "" || !didUrl) return null;
563
+ const sections = didUrl.match(DID_MATCHER);
564
+ if (sections) {
565
+ const parts = {
566
+ did: `did:${sections[1]}:${sections[2]}`,
567
+ method: sections[1],
568
+ id: sections[2],
569
+ didUrl
570
+ };
571
+ if (sections[4]) {
572
+ const params = sections[4].slice(1).split(";");
573
+ parts.params = {};
574
+ for (const p of params) {
575
+ const kv = p.split("=");
576
+ parts.params[kv[0]] = kv[1];
577
+ }
578
+ }
579
+ if (sections[6]) parts.path = sections[6];
580
+ if (sections[7]) parts.query = sections[7].slice(1);
581
+ if (sections[8]) parts.fragment = sections[8].slice(1);
582
+ return parts;
583
+ }
584
+ return null;
585
+ }, "parse");
586
+
587
+ // src/utils/mdoc.ts
588
+ var mdoc = __toESM(require("@sphereon/kmp-mdoc-core"), 1);
589
+ function isWrappedMdocCredential(vc) {
590
+ return vc.format === "mso_mdoc";
591
+ }
592
+ __name(isWrappedMdocCredential, "isWrappedMdocCredential");
593
+ function isWrappedMdocPresentation(vp) {
594
+ return vp.format === "mso_mdoc";
595
+ }
596
+ __name(isWrappedMdocPresentation, "isWrappedMdocPresentation");
597
+ function getMdocDecodedPayload(mdoc2) {
598
+ const mdocJson = mdoc2.toJson();
599
+ if (!mdocJson.issuerSigned.nameSpaces) {
600
+ throw Error(`Cannot access Issuer Signed items from the Mdoc`);
601
+ }
602
+ const issuerSignedJson = mdoc2.issuerSigned.toJsonDTO();
603
+ const namespaces = issuerSignedJson.nameSpaces;
604
+ const decodedPayload = {};
605
+ for (const [namespace, items] of Object.entries(namespaces)) {
606
+ decodedPayload[namespace] = items.reduce((acc, item) => ({
607
+ ...acc,
608
+ [item.key]: item.value.value
609
+ }), {});
610
+ }
611
+ return decodedPayload;
612
+ }
613
+ __name(getMdocDecodedPayload, "getMdocDecodedPayload");
614
+ function decodeMdocIssuerSigned(oid4vpIssuerSigned) {
615
+ const issuerSigned = mdoc.com.sphereon.mdoc.data.device.IssuerSignedCbor.Static.cborDecode(mdoc.com.sphereon.kmp.decodeFrom(oid4vpIssuerSigned, mdoc.com.sphereon.kmp.Encoding.BASE64URL));
616
+ const holderMdoc = issuerSigned.toDocument();
617
+ return holderMdoc;
618
+ }
619
+ __name(decodeMdocIssuerSigned, "decodeMdocIssuerSigned");
620
+ function encodeMdocIssuerSigned(issuerSigned, encoding = "base64url") {
621
+ return mdoc.com.sphereon.kmp.encodeTo(issuerSigned.cborEncode(), mdoc.com.sphereon.kmp.Encoding.BASE64URL);
622
+ }
623
+ __name(encodeMdocIssuerSigned, "encodeMdocIssuerSigned");
624
+ function decodeMdocDeviceResponse(vpToken) {
625
+ const deviceResponse = mdoc.com.sphereon.mdoc.data.device.DeviceResponseCbor.Static.cborDecode(mdoc.com.sphereon.kmp.decodeFrom(vpToken, mdoc.com.sphereon.kmp.Encoding.BASE64URL));
626
+ return deviceResponse;
627
+ }
628
+ __name(decodeMdocDeviceResponse, "decodeMdocDeviceResponse");
629
+ var mdocDecodedCredentialToUniformCredential = /* @__PURE__ */ __name((decoded, opts) => {
630
+ const document = decoded.toJson();
631
+ const json = document.toJsonDTO();
632
+ const type = "Personal Identification Data";
633
+ const MSO = document.MSO;
634
+ if (!MSO || !json.issuerSigned?.nameSpaces) {
635
+ throw Error(`Cannot access Mobile Security Object or Issuer Signed items from the Mdoc`);
636
+ }
637
+ const nameSpaces = json.issuerSigned.nameSpaces;
638
+ if (!("eu.europa.ec.eudi.pid.1" in nameSpaces)) {
639
+ throw Error(`Only PID supported at present`);
640
+ }
641
+ const items = nameSpaces["eu.europa.ec.eudi.pid.1"];
642
+ if (!items || items.length === 0) {
643
+ throw Error(`No issuer signed items were found`);
644
+ }
645
+ const credentialSubject = items.reduce((acc, item) => {
646
+ if (Array.isArray(item.value)) {
647
+ acc[item.key] = item.value.map((val) => val.value).join(", ");
648
+ } else {
649
+ acc[item.key] = item.value.value;
650
+ }
651
+ return acc;
652
+ }, {});
653
+ const validFrom = MSO.validityInfo.validFrom;
654
+ const validUntil = MSO.validityInfo.validUntil;
655
+ const docType = MSO.docType;
656
+ const expirationDate = validUntil;
657
+ let issuanceDateStr = validFrom;
658
+ const issuanceDate = issuanceDateStr;
659
+ if (!issuanceDate) {
660
+ throw Error(`JWT issuance date is required but was not present`);
661
+ }
662
+ const credential = {
663
+ type: [
664
+ docType
665
+ ],
666
+ "@context": [],
667
+ credentialSubject: {
668
+ type,
669
+ ...credentialSubject
670
+ },
671
+ issuanceDate,
672
+ expirationDate,
673
+ proof: {
674
+ type: IProofType.MdocProof2024,
675
+ created: issuanceDate,
676
+ proofPurpose: IProofPurpose.authentication,
677
+ verificationMethod: json.issuerSigned.issuerAuth.payload,
678
+ mso_mdoc: mdoc.com.sphereon.kmp.encodeTo(decoded.cborEncode(), mdoc.com.sphereon.kmp.Encoding.BASE64URL)
679
+ }
680
+ };
681
+ return credential;
682
+ }, "mdocDecodedCredentialToUniformCredential");
683
+
684
+ // src/utils/sd-jwt.ts
685
+ var import_decode = require("@sd-jwt/decode");
686
+ function decodeSdJwtVc(compactSdJwtVc, hasher) {
687
+ const { jwt, disclosures, kbJwt } = (0, import_decode.decodeSdJwtSync)(compactSdJwtVc, hasher);
688
+ const signedPayload = jwt.payload;
689
+ const decodedPayload = (0, import_decode.getClaimsSync)(signedPayload, disclosures, hasher);
690
+ const compactKeyBindingJwt = kbJwt ? compactSdJwtVc.split("~").pop() : void 0;
691
+ return {
692
+ compactSdJwtVc,
693
+ decodedPayload,
694
+ disclosures: disclosures.map((d) => {
695
+ const decoded = d.key ? [
696
+ d.salt,
697
+ d.key,
698
+ d.value
699
+ ] : [
700
+ d.salt,
701
+ d.value
702
+ ];
703
+ if (!d._digest) throw new Error("Implementation error: digest not present in disclosure");
704
+ return {
705
+ decoded,
706
+ digest: d._digest,
707
+ encoded: d.encode()
708
+ };
709
+ }),
710
+ signedPayload,
711
+ ...compactKeyBindingJwt && kbJwt && {
712
+ kbJwt: {
713
+ header: kbJwt.header,
714
+ compact: compactKeyBindingJwt,
715
+ payload: kbJwt.payload
716
+ }
717
+ }
718
+ };
719
+ }
720
+ __name(decodeSdJwtVc, "decodeSdJwtVc");
721
+ async function decodeSdJwtVcAsync(compactSdJwtVc, hasher) {
722
+ const { jwt, disclosures, kbJwt } = await (0, import_decode.decodeSdJwt)(compactSdJwtVc, hasher);
723
+ const signedPayload = jwt.payload;
724
+ const decodedPayload = await (0, import_decode.getClaims)(signedPayload, disclosures, hasher);
725
+ const compactKeyBindingJwt = kbJwt ? compactSdJwtVc.split("~").pop() : void 0;
726
+ return {
727
+ compactSdJwtVc,
728
+ decodedPayload,
729
+ disclosures: disclosures.map((d) => {
730
+ const decoded = d.key ? [
731
+ d.salt,
732
+ d.key,
733
+ d.value
734
+ ] : [
735
+ d.salt,
736
+ d.value
737
+ ];
738
+ if (!d._digest) throw new Error("Implementation error: digest not present in disclosure");
739
+ return {
740
+ decoded,
741
+ digest: d._digest,
742
+ encoded: d.encode()
743
+ };
744
+ }),
745
+ signedPayload,
746
+ ...compactKeyBindingJwt && kbJwt && {
747
+ kbJwt: {
748
+ header: kbJwt.header,
749
+ payload: kbJwt.payload,
750
+ compact: compactKeyBindingJwt
751
+ }
752
+ }
753
+ };
754
+ }
755
+ __name(decodeSdJwtVcAsync, "decodeSdJwtVcAsync");
756
+ var sdJwtDecodedCredentialToUniformCredential = /* @__PURE__ */ __name((decoded, opts) => {
757
+ const { decodedPayload } = decoded;
758
+ const { exp, nbf, iss, iat, vct, cnf, status, sub, jti } = decodedPayload;
759
+ const maxSkewInMS = opts?.maxTimeSkewInMS ?? 1500;
760
+ const expirationDate = jwtDateToISOString({
761
+ jwtClaim: exp,
762
+ claimName: "exp"
763
+ });
764
+ let issuanceDateStr = jwtDateToISOString({
765
+ jwtClaim: iat,
766
+ claimName: "iat"
767
+ });
768
+ let nbfDateAsStr;
769
+ if (nbf) {
770
+ nbfDateAsStr = jwtDateToISOString({
771
+ jwtClaim: nbf,
772
+ claimName: "nbf"
773
+ });
774
+ if (issuanceDateStr && nbfDateAsStr && issuanceDateStr !== nbfDateAsStr) {
775
+ const diff = Math.abs(new Date(nbfDateAsStr).getTime() - new Date(iss).getTime());
776
+ if (!maxSkewInMS || diff > maxSkewInMS) {
777
+ throw Error(`Inconsistent issuance dates between JWT claim (${nbfDateAsStr}) and VC value (${iss})`);
778
+ }
779
+ }
780
+ issuanceDateStr = nbfDateAsStr;
781
+ }
782
+ const issuanceDate = issuanceDateStr;
783
+ if (!issuanceDate) {
784
+ throw Error(`JWT issuance date is required but was not present`);
785
+ }
786
+ const excludedFields = /* @__PURE__ */ new Set([
787
+ "vct",
788
+ "cnf",
789
+ "iss",
790
+ "iat",
791
+ "exp",
792
+ "nbf",
793
+ "jti",
794
+ "sub"
795
+ ]);
796
+ const credentialSubject = Object.entries(decodedPayload).reduce((acc, [key, value]) => {
797
+ if (!excludedFields.has(key) && value !== void 0 && value !== "" && !(typeof value === "object" && value !== null && Object.keys(value).length === 0)) {
798
+ acc[key] = value;
799
+ }
800
+ return acc;
801
+ }, {});
802
+ const credential = {
803
+ type: [
804
+ vct
805
+ ],
806
+ "@context": [],
807
+ credentialSubject: {
808
+ ...credentialSubject,
809
+ id: credentialSubject.id ?? sub ?? jti
810
+ },
811
+ issuanceDate,
812
+ expirationDate,
813
+ issuer: iss,
814
+ ...cnf && {
815
+ cnf
816
+ },
817
+ ...status && {
818
+ status
819
+ },
820
+ proof: {
821
+ type: IProofType.SdJwtProof2024,
822
+ created: nbfDateAsStr ?? issuanceDate,
823
+ proofPurpose: IProofPurpose.authentication,
824
+ verificationMethod: iss,
825
+ jwt: decoded.compactSdJwtVc
826
+ }
827
+ };
828
+ return credential;
829
+ }, "sdJwtDecodedCredentialToUniformCredential");
830
+ var jwtDateToISOString = /* @__PURE__ */ __name(({ jwtClaim, claimName, isRequired = false }) => {
831
+ if (jwtClaim) {
832
+ const claim = parseInt(jwtClaim.toString());
833
+ return new Date(claim * (claim < 9999999999 ? 1e3 : 1)).toISOString().replace(/\.000Z/, "Z");
834
+ } else if (isRequired) {
835
+ throw Error(`JWT claim ${claimName} is required but was not present`);
836
+ }
837
+ return void 0;
838
+ }, "jwtDateToISOString");
839
+
840
+ // src/mapper/credential-constraints.ts
841
+ var StatusListCredentialIdMode = /* @__PURE__ */ function(StatusListCredentialIdMode2) {
842
+ StatusListCredentialIdMode2["ISSUANCE"] = "ISSUANCE";
843
+ StatusListCredentialIdMode2["NEVER"] = "NEVER";
844
+ return StatusListCredentialIdMode2;
845
+ }({});
846
+ var StatusListDriverType = /* @__PURE__ */ function(StatusListDriverType2) {
847
+ StatusListDriverType2["AGENT_TYPEORM"] = "agent_typeorm";
848
+ return StatusListDriverType2;
849
+ }({});
850
+
851
+ // src/mapper/credential-mapper.ts
852
+ var import_jwt_decode = require("jwt-decode");
853
+ var sha2562 = /* @__PURE__ */ __name((data) => {
854
+ return defaultHasher(data, "sha256");
855
+ }, "sha256");
856
+ var CredentialMapper = class _CredentialMapper {
857
+ static {
858
+ __name(this, "CredentialMapper");
859
+ }
860
+ /**
861
+ * 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
862
+ * with the other decode methods.
863
+ */
864
+ static decodeSdJwtVcAsync(compactSdJwtVc, hasher) {
865
+ return decodeSdJwtVcAsync(compactSdJwtVc, hasher ?? sha2562);
866
+ }
867
+ /**
868
+ * Decodes a Verifiable Presentation to a uniform format.
869
+ *
870
+ * When decoding SD-JWT credentials, a hasher implementation must be provided. The hasher implementation must be sync. When using
871
+ * an async hasher implementation, use the decodeSdJwtVcAsync method instead and you can provide the decoded payload to methods
872
+ * instead of the compact SD-JWT.
873
+ *
874
+ * @param presentation
875
+ * @param hasher Hasher implementation to use for SD-JWT decoding.
876
+ */
877
+ static decodeVerifiablePresentation(presentation, hasher) {
878
+ if (_CredentialMapper.isJwtEncoded(presentation)) {
879
+ const payload = (0, import_jwt_decode.jwtDecode)(presentation);
880
+ const header = (0, import_jwt_decode.jwtDecode)(presentation, {
881
+ header: true
882
+ });
883
+ payload.vp.proof = {
884
+ type: IProofType.JwtProof2020,
885
+ created: payload.nbf,
886
+ proofPurpose: IProofPurpose.authentication,
887
+ verificationMethod: header["kid"] ?? payload.iss,
888
+ jwt: presentation
889
+ };
890
+ return payload;
891
+ } else if (_CredentialMapper.isJwtDecodedPresentation(presentation)) {
892
+ return presentation;
893
+ } else if (_CredentialMapper.isSdJwtEncoded(presentation)) {
894
+ return decodeSdJwtVc(presentation, hasher ?? sha2562);
895
+ } else if (_CredentialMapper.isSdJwtDecodedCredential(presentation)) {
896
+ return presentation;
897
+ } else if (_CredentialMapper.isMsoMdocOid4VPEncoded(presentation)) {
898
+ return presentation;
899
+ } else if (_CredentialMapper.isMsoMdocDecodedPresentation(presentation)) {
900
+ return presentation;
901
+ } else if (_CredentialMapper.isJsonLdAsString(presentation)) {
902
+ return JSON.parse(presentation);
903
+ } else {
904
+ return presentation;
905
+ }
906
+ }
907
+ /**
908
+ * Decodes a Verifiable Credential to a uniform format.
909
+ *
910
+ * When decoding SD-JWT credentials, a hasher implementation must be provided. The hasher implementation must be sync. When using
911
+ * an async hasher implementation, use the decodeSdJwtVcAsync method instead and you can provide the decoded payload to methods
912
+ * instead of the compact SD-JWT.
913
+ *
914
+ * @param hasher Hasher implementation to use for SD-JWT decoding
915
+ */
916
+ static decodeVerifiableCredential(credential, hasher) {
917
+ if (_CredentialMapper.isJwtEncoded(credential)) {
918
+ const payload = (0, import_jwt_decode.jwtDecode)(credential);
919
+ const header = (0, import_jwt_decode.jwtDecode)(credential, {
920
+ header: true
921
+ });
922
+ payload.vc.proof = {
923
+ type: IProofType.JwtProof2020,
924
+ created: payload.nbf,
925
+ proofPurpose: IProofPurpose.authentication,
926
+ verificationMethod: header["kid"] ?? payload.iss,
927
+ jwt: credential
928
+ };
929
+ return payload;
930
+ } else if (_CredentialMapper.isJwtDecodedCredential(credential)) {
931
+ return credential;
932
+ } else if (_CredentialMapper.isJsonLdAsString(credential)) {
933
+ return JSON.parse(credential);
934
+ } else if (_CredentialMapper.isSdJwtEncoded(credential)) {
935
+ return decodeSdJwtVc(credential, hasher ?? sha2562);
936
+ } else if (_CredentialMapper.isSdJwtDecodedCredential(credential)) {
937
+ return credential;
938
+ } else {
939
+ return credential;
940
+ }
941
+ }
942
+ /**
943
+ * Converts a presentation to a wrapped presentation.
944
+ *
945
+ * When decoding SD-JWT credentials, a hasher implementation must be provided. The hasher implementation must be sync. When using
946
+ * an async hasher implementation, use the decodeSdJwtVcAsync method instead and you can provide the decoded payload to methods
947
+ * instead of the compact SD-JWT.
948
+ *
949
+ * @param hasher Hasher implementation to use for SD-JWT decoding
950
+ */
951
+ static toWrappedVerifiablePresentation(originalPresentation, opts) {
952
+ if (_CredentialMapper.isMsoMdocDecodedPresentation(originalPresentation) || _CredentialMapper.isMsoMdocOid4VPEncoded(originalPresentation)) {
953
+ let deviceResponse;
954
+ let originalType;
955
+ if (_CredentialMapper.isMsoMdocOid4VPEncoded(originalPresentation)) {
956
+ deviceResponse = decodeMdocDeviceResponse(originalPresentation);
957
+ originalType = "mso_mdoc-encoded";
958
+ } else {
959
+ deviceResponse = originalPresentation;
960
+ originalType = "mso_mdoc-decoded";
961
+ }
962
+ const mdocCredentials = deviceResponse.documents?.map((doc) => _CredentialMapper.toWrappedVerifiableCredential(doc, opts));
963
+ if (!mdocCredentials || mdocCredentials.length === 0) {
964
+ throw new Error("could not extract any mdoc credentials from mdoc device response");
965
+ }
966
+ return {
967
+ type: originalType,
968
+ format: "mso_mdoc",
969
+ original: originalPresentation,
970
+ presentation: deviceResponse,
971
+ decoded: deviceResponse,
972
+ vcs: mdocCredentials
973
+ };
974
+ }
975
+ if (_CredentialMapper.isSdJwtDecodedCredential(originalPresentation) || _CredentialMapper.isSdJwtEncoded(originalPresentation)) {
976
+ let decodedPresentation;
977
+ if (_CredentialMapper.isSdJwtEncoded(originalPresentation)) {
978
+ decodedPresentation = decodeSdJwtVc(originalPresentation, opts?.hasher ?? sha2562);
979
+ } else {
980
+ decodedPresentation = originalPresentation;
981
+ }
982
+ return {
983
+ type: _CredentialMapper.isSdJwtDecodedCredential(originalPresentation) ? "sd-jwt-vc-decoded" : "sd-jwt-vc-encoded",
984
+ format: "vc+sd-jwt",
985
+ original: originalPresentation,
986
+ presentation: decodedPresentation,
987
+ decoded: decodedPresentation.decodedPayload,
988
+ // NOTE: we also include the SD-JWT VC as the VC, as the SD-JWT acts as both the VC and the VP
989
+ vcs: [
990
+ _CredentialMapper.toWrappedVerifiableCredential(originalPresentation, opts)
991
+ ]
992
+ };
993
+ }
994
+ const proof = _CredentialMapper.getFirstProof(originalPresentation);
995
+ const original = typeof originalPresentation !== "string" && _CredentialMapper.hasJWTProofType(originalPresentation) ? proof?.jwt : originalPresentation;
996
+ if (!original) {
997
+ throw Error("Could not determine original presentation, probably it was a converted JWT presentation, that is now missing the JWT value in the proof");
998
+ }
999
+ const decoded = _CredentialMapper.decodeVerifiablePresentation(original);
1000
+ const isJwtEncoded = _CredentialMapper.isJwtEncoded(original);
1001
+ const isJwtDecoded = _CredentialMapper.isJwtDecodedPresentation(original);
1002
+ const type = isJwtEncoded ? "jwt-encoded" : isJwtDecoded ? "jwt-decoded" : "json-ld";
1003
+ const format = isJwtDecoded || isJwtEncoded ? "jwt_vp" : "ldp_vp";
1004
+ let vp;
1005
+ if (isJwtEncoded || isJwtDecoded) {
1006
+ vp = _CredentialMapper.jwtDecodedPresentationToUniformPresentation(decoded, false, opts);
1007
+ } else {
1008
+ vp = decoded;
1009
+ }
1010
+ if (!vp) {
1011
+ throw Error(`VP key not found`);
1012
+ }
1013
+ const noVCs = !("verifiableCredential" in vp) || !vp.verifiableCredential || vp.verifiableCredential.length === 0;
1014
+ if (noVCs) {
1015
+ console.warn(`Presentation without verifiable credentials. That is rare! `);
1016
+ }
1017
+ const vcs = noVCs ? [] : _CredentialMapper.toWrappedVerifiableCredentials(vp.verifiableCredential ?? [], opts);
1018
+ const presentation = {
1019
+ ...vp,
1020
+ verifiableCredential: vcs
1021
+ };
1022
+ return {
1023
+ type,
1024
+ format,
1025
+ original,
1026
+ decoded,
1027
+ presentation,
1028
+ vcs
1029
+ };
1030
+ }
1031
+ /**
1032
+ * Converts a list of credentials to a list of wrapped credentials.
1033
+ *
1034
+ * When decoding SD-JWT credentials, a hasher implementation must be provided. The hasher implementation must be sync. When using
1035
+ * an async hasher implementation, use the decodeSdJwtVcAsync method instead and you can provide the decoded payload to methods
1036
+ * instead of the compact SD-JWT.
1037
+ *
1038
+ * @param hasher Hasher implementation to use for SD-JWT decoding
1039
+ */
1040
+ static toWrappedVerifiableCredentials(verifiableCredentials, opts) {
1041
+ return verifiableCredentials.map((vc) => _CredentialMapper.toWrappedVerifiableCredential(vc, opts));
1042
+ }
1043
+ /**
1044
+ * Converts a credential to a wrapped credential.
1045
+ *
1046
+ * When decoding SD-JWT credentials, a hasher implementation must be provided. The hasher implementation must be sync. When using
1047
+ * an async hasher implementation, use the decodeSdJwtVcAsync method instead and you can provide the decoded payload to methods
1048
+ * instead of the compact SD-JWT.
1049
+ *
1050
+ * @param hasher Hasher implementation to use for SD-JWT decoding
1051
+ */
1052
+ static toWrappedVerifiableCredential(verifiableCredential, opts) {
1053
+ if (_CredentialMapper.isMsoMdocDecodedCredential(verifiableCredential) || _CredentialMapper.isMsoMdocOid4VPEncoded(verifiableCredential)) {
1054
+ let mdoc2;
1055
+ if (_CredentialMapper.isMsoMdocOid4VPEncoded(verifiableCredential)) {
1056
+ mdoc2 = decodeMdocIssuerSigned(verifiableCredential);
1057
+ } else {
1058
+ mdoc2 = verifiableCredential;
1059
+ }
1060
+ return {
1061
+ type: _CredentialMapper.isMsoMdocDecodedCredential(verifiableCredential) ? "mso_mdoc-decoded" : "mso_mdoc-encoded",
1062
+ format: "mso_mdoc",
1063
+ original: verifiableCredential,
1064
+ credential: mdoc2,
1065
+ decoded: getMdocDecodedPayload(mdoc2)
1066
+ };
1067
+ }
1068
+ if (_CredentialMapper.isSdJwtDecodedCredential(verifiableCredential) || _CredentialMapper.isSdJwtEncoded(verifiableCredential)) {
1069
+ let decodedCredential;
1070
+ if (_CredentialMapper.isSdJwtEncoded(verifiableCredential)) {
1071
+ const hasher = opts?.hasher ?? sha2562;
1072
+ decodedCredential = decodeSdJwtVc(verifiableCredential, hasher);
1073
+ } else {
1074
+ decodedCredential = verifiableCredential;
1075
+ }
1076
+ return {
1077
+ type: _CredentialMapper.isSdJwtDecodedCredential(verifiableCredential) ? "sd-jwt-vc-decoded" : "sd-jwt-vc-encoded",
1078
+ format: "vc+sd-jwt",
1079
+ original: verifiableCredential,
1080
+ credential: decodedCredential,
1081
+ decoded: decodedCredential.decodedPayload
1082
+ };
1083
+ }
1084
+ const proof = _CredentialMapper.getFirstProof(verifiableCredential);
1085
+ const original = _CredentialMapper.hasJWTProofType(verifiableCredential) && proof ? proof.jwt ?? verifiableCredential : verifiableCredential;
1086
+ if (!original) {
1087
+ throw Error("Could not determine original credential, probably it was a converted JWT credential, that is now missing the JWT value in the proof");
1088
+ }
1089
+ const decoded = _CredentialMapper.decodeVerifiableCredential(original);
1090
+ const isJwtEncoded = _CredentialMapper.isJwtEncoded(original);
1091
+ const isJwtDecoded = _CredentialMapper.isJwtDecodedCredential(original);
1092
+ const type = isJwtEncoded ? "jwt-encoded" : isJwtDecoded ? "jwt-decoded" : "json-ld";
1093
+ const credential = isJwtEncoded || isJwtDecoded ? _CredentialMapper.jwtDecodedCredentialToUniformCredential(decoded, opts) : decoded;
1094
+ const format = isJwtEncoded || isJwtDecoded ? "jwt_vc" : "ldp_vc";
1095
+ return {
1096
+ original,
1097
+ decoded,
1098
+ format,
1099
+ type,
1100
+ credential
1101
+ };
1102
+ }
1103
+ static isJwtEncoded(original) {
1104
+ return ObjectUtils.isString(original) && original.startsWith("ey") && !original.includes("~");
1105
+ }
1106
+ static isSdJwtEncoded(original) {
1107
+ return ObjectUtils.isString(original) && original.startsWith("ey") && original.includes("~");
1108
+ }
1109
+ static isMsoMdocOid4VPEncoded(original) {
1110
+ return ObjectUtils.isString(original) && !original.startsWith("ey") && ObjectUtils.isBase64(original);
1111
+ }
1112
+ static isW3cCredential(credential) {
1113
+ return typeof credential === "object" && "@context" in credential && (credential.type?.includes("VerifiableCredential") || false);
1114
+ }
1115
+ static isCredential(original) {
1116
+ try {
1117
+ if (_CredentialMapper.isJwtEncoded(original)) {
1118
+ const vc = _CredentialMapper.toUniformCredential(original);
1119
+ return _CredentialMapper.isW3cCredential(vc);
1120
+ } else if (_CredentialMapper.isSdJwtEncoded(original)) {
1121
+ return true;
1122
+ } else if (_CredentialMapper.isMsoMdocDecodedCredential(original)) {
1123
+ return true;
1124
+ } else if (_CredentialMapper.isMsoMdocOid4VPEncoded(original)) {
1125
+ return true;
1126
+ }
1127
+ return _CredentialMapper.isW3cCredential(original) || _CredentialMapper.isSdJwtDecodedCredentialPayload(original) || _CredentialMapper.isJwtDecodedCredential(original) || _CredentialMapper.isSdJwtDecodedCredential(original);
1128
+ } catch (e) {
1129
+ return false;
1130
+ }
1131
+ }
1132
+ static isPresentation(original) {
1133
+ try {
1134
+ if (_CredentialMapper.isJwtEncoded(original)) {
1135
+ const vp = _CredentialMapper.toUniformPresentation(original);
1136
+ return _CredentialMapper.isW3cPresentation(vp);
1137
+ } else if (_CredentialMapper.isSdJwtEncoded(original)) {
1138
+ return false;
1139
+ } else if (_CredentialMapper.isMsoMdocDecodedPresentation(original)) {
1140
+ return true;
1141
+ } else if (_CredentialMapper.isMsoMdocOid4VPEncoded(original)) {
1142
+ return true;
1143
+ }
1144
+ return _CredentialMapper.isW3cPresentation(original) || _CredentialMapper.isSdJwtDecodedCredentialPayload(original) || _CredentialMapper.isJwtDecodedPresentation(original) || _CredentialMapper.isSdJwtDecodedCredential(original);
1145
+ } catch (e) {
1146
+ return false;
1147
+ }
1148
+ }
1149
+ static hasProof(original) {
1150
+ try {
1151
+ if (_CredentialMapper.isMsoMdocOid4VPEncoded(original)) {
1152
+ return false;
1153
+ } else if (_CredentialMapper.isMsoMdocDecodedCredential(original) || _CredentialMapper.isMsoMdocDecodedPresentation(original)) {
1154
+ return true;
1155
+ } else if (_CredentialMapper.isJwtEncoded(original) || _CredentialMapper.isJwtDecodedCredential(original)) {
1156
+ return true;
1157
+ } else if (_CredentialMapper.isSdJwtEncoded(original) || _CredentialMapper.isSdJwtDecodedCredential(original)) {
1158
+ return true;
1159
+ }
1160
+ if (typeof original !== "object") {
1161
+ return false;
1162
+ }
1163
+ if ("vc" in original && original.vc.proof) {
1164
+ return true;
1165
+ }
1166
+ if ("vp" in original && original.vp.proof) {
1167
+ return true;
1168
+ }
1169
+ return !!original.proof;
1170
+ } catch (e) {
1171
+ return false;
1172
+ }
1173
+ }
1174
+ static isW3cPresentation(presentation) {
1175
+ return typeof presentation === "object" && "@context" in presentation && (presentation.type?.includes("VerifiablePresentation") || false);
1176
+ }
1177
+ static isSdJwtDecodedCredentialPayload(credential) {
1178
+ return typeof credential === "object" && "vct" in credential;
1179
+ }
1180
+ static areOriginalVerifiableCredentialsEqual(firstOriginal, secondOriginal) {
1181
+ if (typeof firstOriginal === "string" || typeof secondOriginal === "string") {
1182
+ return firstOriginal === secondOriginal;
1183
+ } else if (_CredentialMapper.isMsoMdocDecodedCredential(firstOriginal) || _CredentialMapper.isMsoMdocDecodedCredential(secondOriginal)) {
1184
+ if (!_CredentialMapper.isMsoMdocDecodedCredential(firstOriginal) || !_CredentialMapper.isMsoMdocDecodedCredential(secondOriginal)) {
1185
+ return false;
1186
+ }
1187
+ return firstOriginal.issuerSigned.equals(secondOriginal.issuerSigned);
1188
+ } else if (_CredentialMapper.isSdJwtDecodedCredential(firstOriginal) || _CredentialMapper.isSdJwtDecodedCredential(secondOriginal)) {
1189
+ return firstOriginal.compactSdJwtVc === secondOriginal.compactSdJwtVc;
1190
+ } else {
1191
+ return JSON.stringify(secondOriginal.proof) === JSON.stringify(firstOriginal.proof);
1192
+ }
1193
+ }
1194
+ static isJsonLdAsString(original) {
1195
+ return ObjectUtils.isString(original) && original.includes("@context");
1196
+ }
1197
+ static isSdJwtDecodedCredential(original) {
1198
+ return typeof original === "object" && (original.compactSdJwtVc !== void 0 || original.kbJwt !== void 0);
1199
+ }
1200
+ static isMsoMdocDecodedCredential(original) {
1201
+ return typeof original === "object" && "issuerSigned" in original && original.issuerSigned !== void 0;
1202
+ }
1203
+ static isMsoMdocDecodedPresentation(original) {
1204
+ return typeof original === "object" && "version" in original && original.version !== void 0;
1205
+ }
1206
+ static isJwtDecodedCredential(original) {
1207
+ return typeof original === "object" && original.vc !== void 0 && original.iss !== void 0;
1208
+ }
1209
+ static isJwtDecodedPresentation(original) {
1210
+ return typeof original === "object" && original.vp !== void 0 && original.iss !== void 0;
1211
+ }
1212
+ static isWrappedSdJwtVerifiableCredential = isWrappedSdJwtVerifiableCredential;
1213
+ static isWrappedSdJwtVerifiablePresentation = isWrappedSdJwtVerifiablePresentation;
1214
+ static isWrappedW3CVerifiableCredential = isWrappedW3CVerifiableCredential;
1215
+ static isWrappedW3CVerifiablePresentation = isWrappedW3CVerifiablePresentation;
1216
+ static isWrappedMdocCredential = isWrappedMdocCredential;
1217
+ static isWrappedMdocPresentation = isWrappedMdocPresentation;
1218
+ static jwtEncodedPresentationToUniformPresentation(jwt, makeCredentialsUniform = true, opts) {
1219
+ return _CredentialMapper.jwtDecodedPresentationToUniformPresentation((0, import_jwt_decode.jwtDecode)(jwt), makeCredentialsUniform, opts);
1220
+ }
1221
+ static jwtDecodedPresentationToUniformPresentation(decoded, makeCredentialsUniform = true, opts) {
1222
+ const { iss, aud, jti, vp, ...rest } = decoded;
1223
+ const presentation = {
1224
+ ...rest,
1225
+ ...vp
1226
+ };
1227
+ if (makeCredentialsUniform) {
1228
+ if (!vp.verifiableCredential) {
1229
+ throw Error("Verifiable Presentation should have a verifiable credential at this point");
1230
+ }
1231
+ presentation.verifiableCredential = vp.verifiableCredential.map((vc) => _CredentialMapper.toUniformCredential(vc, opts));
1232
+ }
1233
+ if (iss) {
1234
+ const holder = presentation.holder;
1235
+ if (holder) {
1236
+ if (holder !== iss) {
1237
+ throw new Error(`Inconsistent holders between JWT claim (${iss}) and VC value (${holder})`);
1238
+ }
1239
+ }
1240
+ presentation.holder = iss;
1241
+ }
1242
+ if (aud) {
1243
+ const verifier = presentation.verifier;
1244
+ if (verifier) {
1245
+ if (verifier !== aud) {
1246
+ throw new Error(`Inconsistent holders between JWT claim (${aud}) and VC value (${verifier})`);
1247
+ }
1248
+ }
1249
+ presentation.verifier = aud;
1250
+ }
1251
+ if (jti) {
1252
+ const id = presentation.id;
1253
+ if (id && id !== jti) {
1254
+ throw new Error(`Inconsistent VP ids between JWT claim (${jti}) and VP value (${id})`);
1255
+ }
1256
+ presentation.id = jti;
1257
+ }
1258
+ return presentation;
1259
+ }
1260
+ static toUniformCredential(verifiableCredential, opts) {
1261
+ if (_CredentialMapper.isMsoMdocDecodedCredential(verifiableCredential)) {
1262
+ return mdocDecodedCredentialToUniformCredential(verifiableCredential);
1263
+ }
1264
+ if (_CredentialMapper.isSdJwtDecodedCredential(verifiableCredential)) {
1265
+ return sdJwtDecodedCredentialToUniformCredential(verifiableCredential, opts);
1266
+ }
1267
+ const original = typeof verifiableCredential !== "string" && _CredentialMapper.hasJWTProofType(verifiableCredential) ? _CredentialMapper.getFirstProof(verifiableCredential)?.jwt : verifiableCredential;
1268
+ if (!original) {
1269
+ throw Error("Could not determine original credential from passed in credential. Probably because a JWT proof type was present, but now is not available anymore");
1270
+ }
1271
+ const decoded = _CredentialMapper.decodeVerifiableCredential(original, opts?.hasher ?? sha2562);
1272
+ const isJwtEncoded = _CredentialMapper.isJwtEncoded(original);
1273
+ const isJwtDecoded = _CredentialMapper.isJwtDecodedCredential(original);
1274
+ const isSdJwtEncoded = _CredentialMapper.isSdJwtEncoded(original);
1275
+ const isMdocEncoded = _CredentialMapper.isMsoMdocOid4VPEncoded(original);
1276
+ if (isSdJwtEncoded) {
1277
+ return sdJwtDecodedCredentialToUniformCredential(decoded, opts);
1278
+ } else if (isMdocEncoded) {
1279
+ return mdocDecodedCredentialToUniformCredential(decodeMdocIssuerSigned(original));
1280
+ } else if (isJwtDecoded || isJwtEncoded) {
1281
+ return _CredentialMapper.jwtDecodedCredentialToUniformCredential(decoded, opts);
1282
+ } else {
1283
+ return decoded;
1284
+ }
1285
+ }
1286
+ static toUniformPresentation(presentation, opts) {
1287
+ if (_CredentialMapper.isSdJwtDecodedCredential(presentation)) {
1288
+ throw new Error("Converting SD-JWT VC to uniform VP is not supported.");
1289
+ } else if (_CredentialMapper.isMsoMdocDecodedPresentation(presentation)) {
1290
+ throw new Error("Converting MSO_MDOC to uniform VP is not supported yet.");
1291
+ }
1292
+ const proof = _CredentialMapper.getFirstProof(presentation);
1293
+ const original = typeof presentation !== "string" && _CredentialMapper.hasJWTProofType(presentation) ? proof?.jwt : presentation;
1294
+ if (!original) {
1295
+ throw Error("Could not determine original presentation, probably it was a converted JWT presentation, that is now missing the JWT value in the proof");
1296
+ }
1297
+ const decoded = _CredentialMapper.decodeVerifiablePresentation(original, opts?.hasher ?? sha2562);
1298
+ const isJwtEncoded = _CredentialMapper.isJwtEncoded(original);
1299
+ const isJwtDecoded = _CredentialMapper.isJwtDecodedPresentation(original);
1300
+ const uniformPresentation = isJwtEncoded || isJwtDecoded ? _CredentialMapper.jwtDecodedPresentationToUniformPresentation(decoded, false) : decoded;
1301
+ if (opts?.addContextIfMissing && !uniformPresentation["@context"]) {
1302
+ uniformPresentation["@context"] = [
1303
+ "https://www.w3.org/2018/credentials/v1"
1304
+ ];
1305
+ }
1306
+ uniformPresentation.verifiableCredential = uniformPresentation.verifiableCredential?.map((vc) => _CredentialMapper.toUniformCredential(vc, opts));
1307
+ return uniformPresentation;
1308
+ }
1309
+ static jwtEncodedCredentialToUniformCredential(jwt, opts) {
1310
+ return _CredentialMapper.jwtDecodedCredentialToUniformCredential((0, import_jwt_decode.jwtDecode)(jwt), opts);
1311
+ }
1312
+ static jwtDecodedCredentialToUniformCredential(decoded, opts) {
1313
+ const { exp, nbf, iss, vc, sub, jti, ...rest } = decoded;
1314
+ const credential = {
1315
+ ...rest,
1316
+ ...vc
1317
+ };
1318
+ const maxSkewInMS = opts?.maxTimeSkewInMS ?? 1500;
1319
+ if (exp) {
1320
+ const expDate = credential.expirationDate;
1321
+ const jwtExp = parseInt(exp.toString());
1322
+ const expDateAsStr = jwtExp < 9999999999 ? new Date(jwtExp * 1e3).toISOString().replace(/\.000Z/, "Z") : new Date(jwtExp).toISOString();
1323
+ if (expDate && expDate !== expDateAsStr) {
1324
+ const diff = Math.abs(new Date(expDateAsStr).getTime() - new Date(expDate).getTime());
1325
+ if (!maxSkewInMS || diff > maxSkewInMS) {
1326
+ throw new Error(`Inconsistent expiration dates between JWT claim (${expDateAsStr}) and VC value (${expDate})`);
1327
+ }
1328
+ }
1329
+ credential.expirationDate = expDateAsStr;
1330
+ }
1331
+ if (nbf) {
1332
+ const issuanceDate = credential.issuanceDate;
1333
+ const jwtNbf = parseInt(nbf.toString());
1334
+ const nbfDateAsStr = jwtNbf < 9999999999 ? new Date(jwtNbf * 1e3).toISOString().replace(/\.000Z/, "Z") : new Date(jwtNbf).toISOString();
1335
+ if (issuanceDate && issuanceDate !== nbfDateAsStr) {
1336
+ const diff = Math.abs(new Date(nbfDateAsStr).getTime() - new Date(issuanceDate).getTime());
1337
+ if (!maxSkewInMS || diff > maxSkewInMS) {
1338
+ throw new Error(`Inconsistent issuance dates between JWT claim (${nbfDateAsStr}) and VC value (${issuanceDate})`);
1339
+ }
1340
+ }
1341
+ credential.issuanceDate = nbfDateAsStr;
1342
+ }
1343
+ if (iss) {
1344
+ const issuer = credential.issuer;
1345
+ if (issuer) {
1346
+ if (typeof issuer === "string") {
1347
+ if (issuer !== iss) {
1348
+ throw new Error(`Inconsistent issuers between JWT claim (${iss}) and VC value (${issuer})`);
1349
+ }
1350
+ } else {
1351
+ if (!issuer.id && Object.keys(issuer).length > 0) {
1352
+ issuer.id = iss;
1353
+ }
1354
+ if (issuer.id !== iss) {
1355
+ throw new Error(`Inconsistent issuers between JWT claim (${iss}) and VC value (${issuer.id})`);
1356
+ }
1357
+ }
1358
+ } else {
1359
+ credential.issuer = iss;
1360
+ }
1361
+ }
1362
+ if (sub) {
1363
+ const subjects = Array.isArray(credential.credentialSubject) ? credential.credentialSubject : [
1364
+ credential.credentialSubject
1365
+ ];
1366
+ for (let i = 0; i < subjects.length; i++) {
1367
+ const csId = subjects[i].id;
1368
+ if (csId && csId !== sub) {
1369
+ throw new Error(`Inconsistent credential subject ids between JWT claim (${sub}) and VC value (${csId})`);
1370
+ }
1371
+ Array.isArray(credential.credentialSubject) ? credential.credentialSubject[i].id = sub : credential.credentialSubject.id = sub;
1372
+ }
1373
+ }
1374
+ if (jti) {
1375
+ const id = credential.id;
1376
+ if (id && id !== jti) {
1377
+ throw new Error(`Inconsistent credential ids between JWT claim (${jti}) and VC value (${id})`);
1378
+ }
1379
+ credential.id = jti;
1380
+ }
1381
+ return credential;
1382
+ }
1383
+ static toExternalVerifiableCredential(verifiableCredential) {
1384
+ let proof;
1385
+ if (verifiableCredential.proof) {
1386
+ if (!verifiableCredential.proof.type) {
1387
+ throw new Error("Verifiable credential proof is missing a type");
1388
+ }
1389
+ if (!verifiableCredential.proof.created) {
1390
+ throw new Error("Verifiable credential proof is missing a created date");
1391
+ }
1392
+ if (!verifiableCredential.proof.proofPurpose) {
1393
+ throw new Error("Verifiable credential proof is missing a proof purpose");
1394
+ }
1395
+ if (!verifiableCredential.proof.verificationMethod) {
1396
+ throw new Error("Verifiable credential proof is missing a verification method");
1397
+ }
1398
+ proof = {
1399
+ ...verifiableCredential.proof,
1400
+ type: verifiableCredential.proof.type,
1401
+ created: verifiableCredential.proof.created,
1402
+ proofPurpose: verifiableCredential.proof.proofPurpose,
1403
+ verificationMethod: verifiableCredential.proof.verificationMethod
1404
+ };
1405
+ }
1406
+ return {
1407
+ ...verifiableCredential,
1408
+ type: verifiableCredential.type ? typeof verifiableCredential.type === "string" ? [
1409
+ verifiableCredential.type
1410
+ ] : verifiableCredential.type : [
1411
+ "VerifiableCredential"
1412
+ ],
1413
+ proof
1414
+ };
1415
+ }
1416
+ static storedCredentialToOriginalFormat(credential) {
1417
+ const type = _CredentialMapper.detectDocumentType(credential);
1418
+ if (typeof credential === "string") {
1419
+ if (type === 0) {
1420
+ return _CredentialMapper.toCompactJWT(credential);
1421
+ } else if (type === 1) {
1422
+ return JSON.parse(credential);
1423
+ } else if (type === 2) {
1424
+ return credential;
1425
+ }
1426
+ } else if (type === 0 && ObjectUtils.isObject(credential) && "vc" in credential) {
1427
+ return _CredentialMapper.toCompactJWT(credential);
1428
+ } else if (ObjectUtils.isObject(credential) && "proof" in credential && credential.proof.type === "JwtProof2020" && credential.proof.jwt) {
1429
+ return credential.proof.jwt;
1430
+ } else if (ObjectUtils.isObject(credential) && "proof" in credential && credential.proof.type === IProofType.SdJwtProof2024 && credential.proof.jwt) {
1431
+ return credential.proof.jwt;
1432
+ } else if (type === 2 && this.isSdJwtDecodedCredential(credential)) {
1433
+ return credential.compactSdJwtVc;
1434
+ }
1435
+ return credential;
1436
+ }
1437
+ static storedPresentationToOriginalFormat(presentation) {
1438
+ const type = _CredentialMapper.detectDocumentType(presentation);
1439
+ if (typeof presentation === "string") {
1440
+ if (type === 0) {
1441
+ return _CredentialMapper.toCompactJWT(presentation);
1442
+ } else if (type === 1) {
1443
+ return JSON.parse(presentation);
1444
+ }
1445
+ } else if (type === 0 && ObjectUtils.isObject(presentation) && "vp" in presentation) {
1446
+ return _CredentialMapper.toCompactJWT(presentation);
1447
+ } else if (ObjectUtils.isObject(presentation) && "proof" in presentation && presentation.proof.type === "JwtProof2020" && presentation.proof.jwt) {
1448
+ return presentation.proof.jwt;
1449
+ }
1450
+ return presentation;
1451
+ }
1452
+ static toCompactJWT(jwtDocument) {
1453
+ if (!jwtDocument || _CredentialMapper.detectDocumentType(jwtDocument) !== 0) {
1454
+ throw Error("Cannot convert non JWT credential to JWT");
1455
+ }
1456
+ if (typeof jwtDocument === "string") {
1457
+ return jwtDocument;
1458
+ }
1459
+ let proof;
1460
+ if (ObjectUtils.isObject(jwtDocument) && "vp" in jwtDocument) {
1461
+ proof = "jwt" in jwtDocument.vp.proof ? jwtDocument.vp.proof.jwt : jwtDocument.vp.proof;
1462
+ } else if (ObjectUtils.isObject(jwtDocument) && "vc" in jwtDocument) {
1463
+ proof = "jwt" in jwtDocument.vc.proof ? jwtDocument.vc.proof.jwt : jwtDocument.vc.proof;
1464
+ } else {
1465
+ proof = Array.isArray(jwtDocument.proof) ? jwtDocument.proof[0].jwt : jwtDocument.proof.jwt;
1466
+ }
1467
+ if (!proof) {
1468
+ throw Error(`Could not get JWT from supplied document`);
1469
+ }
1470
+ return proof;
1471
+ }
1472
+ static detectDocumentType(document) {
1473
+ if (this.isMsoMdocOid4VPEncoded(document) || this.isMsoMdocDecodedCredential(document)) {
1474
+ return 4;
1475
+ } else if (this.isMsoMdocDecodedPresentation(document) || this.isMsoMdocDecodedPresentation(document)) {
1476
+ return 4;
1477
+ } else if (this.isJsonLdAsString(document)) {
1478
+ return 1;
1479
+ } else if (this.isJwtEncoded(document)) {
1480
+ return 0;
1481
+ } else if (this.isSdJwtEncoded(document) || this.isSdJwtDecodedCredential(document)) {
1482
+ return 2;
1483
+ }
1484
+ const proofs = typeof document !== "string" && ("vc" in document ? document.vc.proof : "vp" in document ? document.vp.proof : document.proof);
1485
+ const proof = Array.isArray(proofs) ? proofs[0] : proofs;
1486
+ if (proof?.jwt) {
1487
+ return 0;
1488
+ } else if (proof?.type === "EthereumEip712Signature2021") {
1489
+ return 3;
1490
+ }
1491
+ return 1;
1492
+ }
1493
+ static hasJWTProofType(document) {
1494
+ if (typeof document === "string") {
1495
+ return false;
1496
+ }
1497
+ return !!_CredentialMapper.getFirstProof(document)?.jwt;
1498
+ }
1499
+ static getFirstProof(document) {
1500
+ if (!document || typeof document === "string") {
1501
+ return void 0;
1502
+ }
1503
+ const proofs = "vc" in document ? document.vc.proof : "vp" in document ? document.vp.proof : document.proof;
1504
+ return Array.isArray(proofs) ? proofs[0] : proofs;
1505
+ }
1506
+ static issuerCorrelationIdFromIssuerType(issuer) {
1507
+ if (issuer === void 0) {
1508
+ throw new Error("Issuer type us undefined");
1509
+ } else if (typeof issuer === "string") {
1510
+ return issuer;
1511
+ } else if (typeof issuer === "object") {
1512
+ if ("id" in issuer) {
1513
+ return issuer.id;
1514
+ } else {
1515
+ throw new Error("Encountered an invalid issuer object: missing id property");
1516
+ }
1517
+ } else {
1518
+ throw new Error("Invalid issuer type");
1519
+ }
1520
+ }
1521
+ };
1522
+ function isWrappedSdJwtVerifiableCredential(vc) {
1523
+ return vc.format === "vc+sd-jwt";
1524
+ }
1525
+ __name(isWrappedSdJwtVerifiableCredential, "isWrappedSdJwtVerifiableCredential");
1526
+ function isWrappedSdJwtVerifiablePresentation(vp) {
1527
+ return vp.format === "vc+sd-jwt";
1528
+ }
1529
+ __name(isWrappedSdJwtVerifiablePresentation, "isWrappedSdJwtVerifiablePresentation");
1530
+ var OriginalType = /* @__PURE__ */ function(OriginalType2) {
1531
+ OriginalType2["JSONLD"] = "json-ld";
1532
+ OriginalType2["JWT_ENCODED"] = "jwt-encoded";
1533
+ OriginalType2["JWT_DECODED"] = "jwt-decoded";
1534
+ OriginalType2["SD_JWT_VC_ENCODED"] = "sd-jwt-vc-encoded";
1535
+ OriginalType2["SD_JWT_VC_DECODED"] = "sd-jwt-vc-decoded";
1536
+ OriginalType2["MSO_MDOC_ENCODED"] = "mso_mdoc-encoded";
1537
+ OriginalType2["MSO_MDOC_DECODED"] = "mso_mdoc-decoded";
1538
+ return OriginalType2;
1539
+ }({});
1540
+ var JWT_PROOF_TYPE_2020 = "JwtProof2020";
1541
+ var DocumentFormat = /* @__PURE__ */ function(DocumentFormat2) {
1542
+ DocumentFormat2[DocumentFormat2["JWT"] = 0] = "JWT";
1543
+ DocumentFormat2[DocumentFormat2["JSONLD"] = 1] = "JSONLD";
1544
+ DocumentFormat2[DocumentFormat2["SD_JWT_VC"] = 2] = "SD_JWT_VC";
1545
+ DocumentFormat2[DocumentFormat2["EIP712"] = 3] = "EIP712";
1546
+ DocumentFormat2[DocumentFormat2["MSO_MDOC"] = 4] = "MSO_MDOC";
1547
+ return DocumentFormat2;
1548
+ }({});
1549
+
1550
+ // src/mapper/jsonld-language-values.ts
1551
+ var isLanguageValueObject = /* @__PURE__ */ __name((claim) => {
1552
+ if (!claim || !ObjectUtils.isObject(claim) || Array.isArray(claim)) {
1553
+ return false;
1554
+ }
1555
+ const keys = Object.keys(claim);
1556
+ if (keys.length !== 2) {
1557
+ return false;
1558
+ } else if (!("language" in claim && !!claim.language)) {
1559
+ return false;
1560
+ } else if (!("value" in claim && !!claim.value)) {
1561
+ return false;
1562
+ }
1563
+ return true;
1564
+ }, "isLanguageValueObject");
1565
+ var isLanguageValueObjects = /* @__PURE__ */ __name((claim) => {
1566
+ if (!claim || !Array.isArray(claim)) {
1567
+ return false;
1568
+ }
1569
+ return claim.every((val) => isLanguageValueObject(val));
1570
+ }, "isLanguageValueObjects");
1571
+ var toLanguageValueObject = /* @__PURE__ */ __name((claim) => {
1572
+ return isLanguageValueObject(claim) ? claim : void 0;
1573
+ }, "toLanguageValueObject");
1574
+ var toLanguageValueObjects = /* @__PURE__ */ __name((claim) => {
1575
+ if (isLanguageValueObject(claim)) {
1576
+ return ObjectUtils.asArray(toLanguageValueObject(claim));
1577
+ } else if (isLanguageValueObjects(claim)) {
1578
+ return claim;
1579
+ }
1580
+ return void 0;
1581
+ }, "toLanguageValueObjects");
1582
+ var mapLanguageValue = /* @__PURE__ */ __name((claim, opts) => {
1583
+ const langValues = toLanguageValueObjects(claim);
1584
+ if (Array.isArray(langValues)) {
1585
+ if (langValues.length === 0) {
1586
+ return claim;
1587
+ }
1588
+ const filteredLangValues = langValues.filter((val) => opts?.language ? val.language.toLowerCase().includes(opts.language.toLowerCase()) : true);
1589
+ let langValue;
1590
+ if (filteredLangValues.length > 0) {
1591
+ langValue = filteredLangValues[0];
1592
+ } else {
1593
+ if (opts?.fallbackToFirstObject === false) {
1594
+ return claim;
1595
+ }
1596
+ langValue = langValues[0];
1597
+ }
1598
+ return langValue.value;
1599
+ }
1600
+ return claim;
1601
+ }, "mapLanguageValue");
1602
+ var mapLanguageValues = /* @__PURE__ */ __name((claimsOrCredential, opts) => {
1603
+ const result = opts?.noDeepClone ? claimsOrCredential : JSON.parse(JSON.stringify(claimsOrCredential));
1604
+ Object.keys(claimsOrCredential).forEach((key) => {
1605
+ result[key] = mapLanguageValue(result[key], opts);
1606
+ if (ObjectUtils.isObject(result[key]) || Array.isArray(result[key])) {
1607
+ result[key] = mapLanguageValues(result[key], {
1608
+ ...opts,
1609
+ noDeepClone: true
1610
+ });
1611
+ }
1612
+ });
1613
+ return result;
1614
+ }, "mapLanguageValues");
1615
+
1616
+ // src/index.ts
1617
+ var logger = Loggers.DEFAULT.get("sphereon:ssi");
1618
+ logger.debug(`Sphereon logger initialized`);
1619
+ //# sourceMappingURL=index.cjs.map