@owf/mdoc 0.6.0 → 0.6.1-alpha-20260521074626

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.
package/dist/index.mjs CHANGED
@@ -1,333 +1,6 @@
1
- import { Encoder, addExtension, addExtension as addExtension$1 } from "cbor-x";
1
+ import { CborStructure, CoseKey, CoseKey as CoseKey$1, CosePayloadMustBeDefinedError, Curve, DataItem, DateOnly, KeyOps, KeyType, Mac0, Mac0 as Mac0$1, MacAlgorithm, ProtectedHeaders, ProtectedHeaders as ProtectedHeaders$1, RegisteredCwtClaimKey, RegisteredCwtHeaderClaimKey, RegisteredCwtHeaderClaimKey as RegisteredCwtHeaderClaimKey$1, Sign1, Sign1 as Sign1$1, SignatureAlgorithm, UnprotectedHeaders, UnprotectedHeaders as UnprotectedHeaders$1, cborDecode, cborDecode as cborDecode$1, cborEncode, cborEncode as cborEncode$1 } from "@owf/cose";
2
2
  import z$1, { z } from "zod";
3
- import { createErrorMap, fromError } from "zod-validation-error";
4
- //#region src/utils/zod-error.ts
5
- z$1.config({ customError: createErrorMap() });
6
- function formatZodError(error) {
7
- if (!error) return "";
8
- return fromError(error, {
9
- prefix: "",
10
- prefixSeparator: "✖ ",
11
- issueSeparator: "\n✖ ",
12
- unionSeparator: "\n OR ✖ "
13
- }).toString();
14
- }
15
- //#endregion
16
- //#region src/error/ValidationError.ts
17
- var ValidationError = class extends Error {
18
- constructor(message, zodError) {
19
- super(message);
20
- this.message = `${message}\n${zodError ? formatZodError(zodError) : ""}`;
21
- Object.defineProperty(this, "zodError", {
22
- value: zodError,
23
- writable: false,
24
- enumerable: false
25
- });
26
- }
27
- };
28
- //#endregion
29
- //#region src/utils/zod.ts
30
- const zUint8Array = z$1.instanceof(Uint8Array);
31
- function parseStructureWithErrorHandling(structureName, schema, data, customErrorMessage) {
32
- const parseResult = z$1.safeParse(schema, data);
33
- if (!parseResult.success) throw new ValidationError(customErrorMessage ?? `Error decoding ${structureName}`, parseResult.error);
34
- return parseResult.data;
35
- }
36
- function decodeStructureWithErrorHandling(structureName, schema, data, customErrorMessage) {
37
- const decodeResult = z$1.safeDecode(schema, data);
38
- if (!decodeResult.success) throw new ValidationError(customErrorMessage ?? `Error decoding ${structureName}`, decodeResult.error);
39
- return decodeResult.data;
40
- }
41
- function encodeStructureWithErrorHandling(structureName, schema, data, customErrorMessage) {
42
- const encodeResult = z$1.safeEncode(schema, data);
43
- if (!encodeResult.success) throw new ValidationError(customErrorMessage ?? `Error encoding ${structureName}`, encodeResult.error);
44
- return encodeResult.data;
45
- }
46
- //#endregion
47
- //#region src/cbor/parser.ts
48
- const encoderDefaults = {
49
- tagUint8Array: false,
50
- useRecords: false,
51
- mapsAsObjects: false,
52
- unwrapTopLevelDataItem: true,
53
- variableMapSize: true
54
- };
55
- const cborDecode = (input, options = encoderDefaults) => {
56
- const params = {
57
- ...encoderDefaults,
58
- ...options
59
- };
60
- const decoded = new Encoder(params).decode(input);
61
- return params.unwrapTopLevelDataItem && typeof decoded === "object" && decoded instanceof DataItem ? decoded.data : decoded;
62
- };
63
- const cborEncode = (obj, options = encoderDefaults) => {
64
- const enc = new Encoder({
65
- ...encoderDefaults,
66
- ...options
67
- });
68
- return Uint8Array.from(enc.encode(obj));
69
- };
70
- //#endregion
71
- //#region src/cbor/data-item.ts
72
- /**
73
- * DataItem is an extension defined https://www.rfc-editor.org/rfc/rfc8949.html#name-encoded-cbor-data-item
74
- * > Sometimes it is beneficial to carry an embedded CBOR data item that is
75
- * > not meant to be decoded immediately at the time the enclosing data item is being decoded.
76
- *
77
- * The idea of this class is to provide lazy encode and decode of cbor data.
78
- *
79
- * Due to a bug in the cbor-x library, we are eagerly encoding the data in the constructor.
80
- * https://github.com/kriszyp/cbor-x/issues/83
81
- *
82
- */
83
- var DataItem = class DataItem {
84
- #data;
85
- #buffer;
86
- constructor(options) {
87
- if (!("data" in options) && !("buffer" in options)) throw new Error("DataItem must be initialized with either the data or a buffer");
88
- if ("data" in options) this.#data = options.data;
89
- this.#buffer = "buffer" in options ? options.buffer : cborEncode(options.data);
90
- }
91
- get data() {
92
- if (!this.#data) this.#data = cborDecode(this.#buffer);
93
- return this.#data;
94
- }
95
- get buffer() {
96
- return this.#buffer;
97
- }
98
- static fromData(data) {
99
- return new DataItem({ data });
100
- }
101
- static fromBuffer(buffer) {
102
- return new DataItem({ buffer });
103
- }
104
- };
105
- addExtension({
106
- Class: DataItem,
107
- tag: 24,
108
- encode: (instance, encode) => {
109
- return encode(instance.buffer);
110
- },
111
- decode: (buffer) => {
112
- return DataItem.fromBuffer(buffer);
113
- }
114
- });
115
- //#endregion
116
- //#region src/cbor/cbor-structure.ts
117
- var CborStructure = class {
118
- constructor(structure) {
119
- this.structure = structure;
120
- }
121
- get decodedStructure() {
122
- return this.structure;
123
- }
124
- /**
125
- * Static getter for the Zod codec schema that defines the CBOR structure.
126
- * Subclasses CAN override this to provide their specific schema for automatic encoding/decoding.
127
- * The schema should be a Zod schema or codec that handles validation and transformation.
128
- * If not provided, subclasses must override encode(), decode(), and fromEncodedStructure().
129
- */
130
- static get encodingSchema() {}
131
- /**
132
- * Returns the encoded structure that will be serialized to CBOR.
133
- * By default, returns the protected structure property.
134
- * Override if custom encoding logic is needed.
135
- */
136
- get encodedStructure() {
137
- const encodingSchema = this.constructor.encodingSchema;
138
- if (!encodingSchema) throw new Error("encodedStructure must be implemented when encodingSchema is not provided");
139
- return encodeStructureWithErrorHandling(this.constructor.name, encodingSchema, this.structure);
140
- }
141
- /**
142
- * Encodes this structure to CBOR bytes.
143
- */
144
- encode(options) {
145
- return cborEncode(options?.asDataItem ? DataItem.fromData(this.encodedStructure) : this.encodedStructure);
146
- }
147
- /**
148
- * Decodes CBOR bytes into a structure instance.
149
- * Uses the encodingSchema's decode() method to validate and transform the decoded data.
150
- */
151
- static decode(bytes) {
152
- const rawStructure = cborDecode(bytes);
153
- return new this(this.fromEncodedStructure(rawStructure).decodedStructure);
154
- }
155
- /**
156
- * Creates a structure instance from the encoded CBOR structure (after calling cborDecode).
157
- *
158
- * Uses the encodingSchema's decode() method to validate and transform the structure if available.
159
- * Otherwise, subclasses must override this method.
160
- */
161
- static fromEncodedStructure(encodedStructure) {
162
- if (!this.encodingSchema) throw new Error("fromEncodedStructure must be implemented when encodingSchema is not provided");
163
- return new this(decodeStructureWithErrorHandling(this.name, this.encodingSchema, encodedStructure));
164
- }
165
- static fromDataItem(dataItem) {
166
- return new this(parseStructureWithErrorHandling(this.name, z.instanceof(DataItem).transform((di) => di.data).transform((d) => this.fromEncodedStructure(d).decodedStructure), dataItem, `Error decoding ${this.name} from DateItem`));
167
- }
168
- /**
169
- * Creates a structure instance from the decoded structure.
170
- *
171
- * Uses the encodingSchema's parse method to validate the structure if available.
172
- * Otherwise, subclasses must override this method.
173
- */
174
- static fromDecodedStructure(decodedStructure) {
175
- const encodingSchema = this.encodingSchema;
176
- if (!encodingSchema) throw new Error("fromDecodedStructure must be implemented when encodingSchema is not provided");
177
- const decodedSchema = encodingSchema instanceof z.ZodPipe ? encodingSchema.out : encodingSchema;
178
- return new this(parseStructureWithErrorHandling(this.name, decodedSchema, decodedStructure));
179
- }
180
- };
181
- //#endregion
182
- //#region src/cbor/models/date.ts
183
- addExtension({
184
- Class: Date,
185
- tag: 0,
186
- encode: (date, encode) => encode(`${date.toISOString().split(".")[0]}Z`),
187
- decode: (isoStringDateTime) => new Date(isoStringDateTime)
188
- });
189
- //#endregion
190
- //#region src/cbor/models/date-only.ts
191
- const customInspectSymbol = Symbol.for("nodejs.util.inspect.custom");
192
- var DateOnly = class DateOnly {
193
- constructor(date) {
194
- this.date = date ? new Date(date) : /* @__PURE__ */ new Date();
195
- }
196
- get [Symbol.toStringTag]() {
197
- return DateOnly.name;
198
- }
199
- toString() {
200
- return this.toISOString();
201
- }
202
- toJSON() {
203
- return this.toISOString();
204
- }
205
- toISOString() {
206
- return this.date.toISOString().split("T")[0];
207
- }
208
- [customInspectSymbol]() {
209
- return this.toISOString();
210
- }
211
- };
212
- addExtension({
213
- Class: DateOnly,
214
- tag: 1004,
215
- encode: (date, encode) => encode(date.toISOString()),
216
- decode: (isoStringDate) => new DateOnly(isoStringDate)
217
- });
218
- //#endregion
219
- //#region src/cose/error.ts
220
- var CoseError = class extends Error {
221
- constructor(message = new.target.name) {
222
- super(message);
223
- }
224
- };
225
- var CoseUnsupportedMacError = class extends CoseError {};
226
- var CoseInvalidSignatureError = class extends CoseError {};
227
- var CoseInvalidAlgorithmError = class extends CoseError {};
228
- var CosePayloadMustBeNullError = class extends CoseError {};
229
- var CosePayloadMustBeDefinedError = class extends CoseError {};
230
- var CosePayloadInvalidStructureError = class extends CoseError {};
231
- var CoseInvalidTypeForKeyError = class extends CoseError {};
232
- var CoseInvalidValueForKtyError = class extends CoseError {};
233
- var CoseInvalidKtyForRawError = class extends CoseError {};
234
- var CoseXNotDefinedError = class extends CoseError {};
235
- var CoseYNotDefinedError = class extends CoseError {};
236
- var CoseDNotDefinedError = class extends CoseError {};
237
- var CoseKNotDefinedError = class extends CoseError {};
238
- var CoseEphemeralMacKeyIsRequiredError = class extends CoseError {};
239
- var CoseCertificateNotFoundError = class extends CoseError {};
240
- var CoseKeyTypeNotSupportedForPrivateKeyExtractionError = class extends CoseError {};
241
- //#endregion
242
- //#region src/cose/headers/defaults.ts
243
- let Header = /* @__PURE__ */ function(Header) {
244
- Header[Header["Algorithm"] = 1] = "Algorithm";
245
- Header[Header["Critical"] = 2] = "Critical";
246
- Header[Header["ContentType"] = 3] = "ContentType";
247
- Header[Header["KeyId"] = 4] = "KeyId";
248
- Header[Header["Iv"] = 5] = "Iv";
249
- Header[Header["PartialIv"] = 6] = "PartialIv";
250
- Header[Header["CounterSignature"] = 7] = "CounterSignature";
251
- Header[Header["CounterSignature0"] = 9] = "CounterSignature0";
252
- Header[Header["CounterSignatureV2"] = 11] = "CounterSignatureV2";
253
- Header[Header["CounterSignature0V2"] = 12] = "CounterSignature0V2";
254
- Header[Header["X5Bag"] = 32] = "X5Bag";
255
- Header[Header["X5Chain"] = 33] = "X5Chain";
256
- Header[Header["X5T"] = 34] = "X5T";
257
- Header[Header["X5U"] = 35] = "X5U";
258
- return Header;
259
- }({});
260
- let SignatureAlgorithm = /* @__PURE__ */ function(SignatureAlgorithm) {
261
- SignatureAlgorithm[SignatureAlgorithm["EdDSA"] = -8] = "EdDSA";
262
- SignatureAlgorithm[SignatureAlgorithm["ES256"] = -7] = "ES256";
263
- SignatureAlgorithm[SignatureAlgorithm["ES384"] = -35] = "ES384";
264
- SignatureAlgorithm[SignatureAlgorithm["ES512"] = -36] = "ES512";
265
- SignatureAlgorithm[SignatureAlgorithm["PS256"] = -37] = "PS256";
266
- SignatureAlgorithm[SignatureAlgorithm["PS384"] = -38] = "PS384";
267
- SignatureAlgorithm[SignatureAlgorithm["PS512"] = -39] = "PS512";
268
- SignatureAlgorithm[SignatureAlgorithm["RS256"] = -257] = "RS256";
269
- SignatureAlgorithm[SignatureAlgorithm["RS384"] = -258] = "RS384";
270
- SignatureAlgorithm[SignatureAlgorithm["RS512"] = -259] = "RS512";
271
- return SignatureAlgorithm;
272
- }({});
273
- let MacAlgorithm = /* @__PURE__ */ function(MacAlgorithm) {
274
- MacAlgorithm[MacAlgorithm["HS256"] = 5] = "HS256";
275
- MacAlgorithm[MacAlgorithm["HS384"] = 6] = "HS384";
276
- MacAlgorithm[MacAlgorithm["HS512"] = 7] = "HS512";
277
- return MacAlgorithm;
278
- }({});
279
- let EncryptionAlgorithm = /* @__PURE__ */ function(EncryptionAlgorithm) {
280
- EncryptionAlgorithm[EncryptionAlgorithm["A128GCM"] = 1] = "A128GCM";
281
- EncryptionAlgorithm[EncryptionAlgorithm["A192GCM"] = 2] = "A192GCM";
282
- EncryptionAlgorithm[EncryptionAlgorithm["A256GCM"] = 3] = "A256GCM";
283
- EncryptionAlgorithm[EncryptionAlgorithm["Direct"] = -6] = "Direct";
284
- return EncryptionAlgorithm;
285
- }({});
286
- //#endregion
287
- //#region src/cose/headers/protected-headers.ts
288
- const protectedHeadersEncodedStructure = zUint8Array;
289
- const protectedHeadersDecodedStructure = z$1.map(z$1.number(), z$1.unknown());
290
- var ProtectedHeaders = class extends CborStructure {
291
- static get encodingSchema() {
292
- return z$1.codec(protectedHeadersEncodedStructure, protectedHeadersDecodedStructure, {
293
- encode: (decoded) => cborEncode(decoded),
294
- decode: (encoded) => cborDecode(encoded)
295
- });
296
- }
297
- get headers() {
298
- return this.structure;
299
- }
300
- static create(options) {
301
- return this.fromDecodedStructure(options.protectedHeaders ?? /* @__PURE__ */ new Map());
302
- }
303
- };
304
- //#endregion
305
- //#region src/cose/headers/unprotected-headers.ts
306
- const unprotectedHeadersStructure = z$1.map(z$1.number(), z$1.unknown());
307
- var UnprotectedHeaders = class extends CborStructure {
308
- static get encodingSchema() {
309
- return unprotectedHeadersStructure;
310
- }
311
- get headers() {
312
- return this.structure;
313
- }
314
- static create(options) {
315
- return this.fromDecodedStructure(options.unprotectedHeaders ?? /* @__PURE__ */ new Map());
316
- }
317
- };
318
- //#endregion
319
- //#region src/cose/key/curve.ts
320
- let Curve = /* @__PURE__ */ function(Curve) {
321
- Curve[Curve["P-256"] = 1] = "P-256";
322
- Curve[Curve["P-384"] = 2] = "P-384";
323
- Curve[Curve["P-521"] = 3] = "P-521";
324
- Curve[Curve["X25519"] = 4] = "X25519";
325
- Curve[Curve["X448"] = 5] = "X448";
326
- Curve[Curve["Ed25519"] = 6] = "Ed25519";
327
- Curve[Curve["Ed448"] = 7] = "Ed448";
328
- return Curve;
329
- }({});
330
- //#endregion
3
+ import { createErrorMap } from "zod-validation-error";
331
4
  //#region src/utils/transformers.ts
332
5
  const base64ToBytes = z$1.codec(z$1.base64(), z$1.instanceof(Uint8Array), {
333
6
  decode: (base64String) => z$1.util.base64ToUint8Array(base64String),
@@ -521,323 +194,145 @@ function typedMap(entries, { allowAdditionalKeys = true, encode, decode } = {})
521
194
  });
522
195
  }
523
196
  //#endregion
524
- //#region src/cose/key/key-operation.ts
525
- let KeyOps = /* @__PURE__ */ function(KeyOps) {
526
- KeyOps[KeyOps["Sign"] = 1] = "Sign";
527
- KeyOps[KeyOps["Verify"] = 2] = "Verify";
528
- KeyOps[KeyOps["Encrypt"] = 3] = "Encrypt";
529
- KeyOps[KeyOps["Decrypt"] = 4] = "Decrypt";
530
- KeyOps[KeyOps["WrapKey"] = 5] = "WrapKey";
531
- KeyOps[KeyOps["UnwrapKey"] = 6] = "UnwrapKey";
532
- KeyOps[KeyOps["DeriveKey"] = 7] = "DeriveKey";
533
- KeyOps[KeyOps["DeriveBits"] = 8] = "DeriveBits";
534
- KeyOps[KeyOps["MACCreate"] = 9] = "MACCreate";
535
- KeyOps[KeyOps["MACVerify"] = 10] = "MACVerify";
536
- return KeyOps;
537
- }({});
197
+ //#region src/utils/zod-error.ts
198
+ z$1.config({ customError: createErrorMap() });
538
199
  //#endregion
539
- //#region src/cose/key/key-type.ts
540
- let KeyType = /* @__PURE__ */ function(KeyType) {
541
- KeyType[KeyType["Okp"] = 1] = "Okp";
542
- KeyType[KeyType["Ec"] = 2] = "Ec";
543
- KeyType[KeyType["Oct"] = 4] = "Oct";
544
- KeyType[KeyType["Reserved"] = 0] = "Reserved";
545
- return KeyType;
546
- }({});
200
+ //#region src/utils/zod.ts
201
+ const zUint8Array = z$1.instanceof(Uint8Array);
547
202
  //#endregion
548
- //#region src/cose/key/jwk.ts
549
- const swapMap = (map) => Object.fromEntries(Object.entries(map).map(([key, value]) => [value, key]));
550
- const swapNestedMap = (nestedMap) => Object.fromEntries(Object.entries(nestedMap).map(([category, mappings]) => [category, Object.fromEntries(Object.entries(mappings).map(([key, value]) => [value, key]))]));
551
- const jwkCoseKeyMap = {
552
- kty: {
553
- OKP: KeyType.Okp,
554
- EC: KeyType.Ec,
555
- OCT: KeyType.Oct
556
- },
557
- crv: {
558
- "P-256": Curve["P-256"],
559
- "p-384": Curve["P-384"],
560
- "p-521": Curve["P-521"],
561
- X25519: Curve.X25519,
562
- Ed25519: Curve.Ed25519,
563
- Ed448: Curve.Ed448
564
- },
565
- alg: {
566
- EdDSA: SignatureAlgorithm.EdDSA,
567
- ES256: SignatureAlgorithm.ES256,
568
- ES384: SignatureAlgorithm.ES384,
569
- ES512: SignatureAlgorithm.ES512,
570
- PS256: SignatureAlgorithm.PS256,
571
- PS384: SignatureAlgorithm.PS384,
572
- PS512: SignatureAlgorithm.PS512,
573
- RS256: SignatureAlgorithm.RS256,
574
- RS384: SignatureAlgorithm.RS384,
575
- RS512: SignatureAlgorithm.RS512,
576
- HS256: MacAlgorithm.HS256,
577
- HS384: MacAlgorithm.HS384,
578
- HS512: MacAlgorithm.HS512,
579
- A128GCM: EncryptionAlgorithm.A128GCM,
580
- A192GCM: EncryptionAlgorithm.A192GCM,
581
- A256GCM: EncryptionAlgorithm.A256GCM,
582
- Direct: EncryptionAlgorithm.Direct
583
- },
584
- keyOps: {
585
- sign: KeyOps.Sign,
586
- verify: KeyOps.Verify,
587
- encrypt: KeyOps.Encrypt,
588
- decrypt: KeyOps.Decrypt,
589
- wrapKey: KeyOps.WrapKey,
590
- unwrapKey: KeyOps.UnwrapKey,
591
- deriveKey: KeyOps.DeriveKey,
592
- deriveBits: KeyOps.DeriveBits,
593
- mACCreate: KeyOps.MACCreate,
594
- mACVerify: KeyOps.MACVerify
595
- }
596
- };
597
- const coseKeyJwkMap = swapNestedMap(jwkCoseKeyMap);
598
- const jwkCoseOptionsMap = {
599
- kty: "keyType",
600
- kid: "keyId",
601
- alg: "algorithm",
602
- keyOps: "keyOps",
603
- baseIv: "baseIv",
604
- crv: "curve",
605
- x: "x",
606
- y: "y",
607
- d: "d"
608
- };
609
- const coseOptionsJwkMap = swapMap(jwkCoseOptionsMap);
610
- const jwkToCoseKey = {
611
- kty: (kty) => {
612
- return jwkCoseKeyMap.kty[kty] ?? kty;
613
- },
614
- crv: (crv) => jwkCoseKeyMap.crv[crv] ?? crv,
615
- alg: (alg) => jwkCoseKeyMap.alg[alg] ?? alg,
616
- kid: (kid) => kid,
617
- keyOps: (keyOps) => Array.isArray(keyOps) ? keyOps?.map((ko) => jwkCoseKeyMap.keyOps[ko] ?? ko) : void 0,
618
- x: (s) => s && typeof s === "string" ? base64url.decode(s) : void 0,
619
- y: (s) => s && typeof s === "string" ? base64url.decode(s) : void 0,
620
- d: (s) => s && typeof s === "string" ? base64url.decode(s) : void 0
621
- };
622
- const coseKeyToJwk = {
623
- keyType: (keyType) => coseKeyJwkMap.kty[keyType],
624
- keyId: (keyId) => keyId,
625
- algorithm: (algorithm) => algorithm ? coseKeyJwkMap.alg[algorithm] : void 0,
626
- keyOps: (keyOps) => keyOps && Array.isArray(keyOps) ? keyOps.map((ko) => coseKeyJwkMap.keyOps[ko]) : void 0,
627
- baseIv: (baseIv) => baseIv,
628
- curve: (curve) => curve ? coseKeyJwkMap.crv[curve] : void 0,
629
- x: (x) => x ? base64url.encode(x) : void 0,
630
- y: (y) => y ? base64url.encode(y) : void 0,
631
- d: (d) => d ? base64url.encode(d) : void 0
632
- };
633
- //#endregion
634
- //#region src/cose/key/key.ts
635
- let CoseKeyParameter = /* @__PURE__ */ function(CoseKeyParameter) {
636
- CoseKeyParameter[CoseKeyParameter["KeyType"] = 1] = "KeyType";
637
- CoseKeyParameter[CoseKeyParameter["KeyId"] = 2] = "KeyId";
638
- CoseKeyParameter[CoseKeyParameter["Algorithm"] = 3] = "Algorithm";
639
- CoseKeyParameter[CoseKeyParameter["KeyOps"] = 4] = "KeyOps";
640
- CoseKeyParameter[CoseKeyParameter["BaseIv"] = 5] = "BaseIv";
641
- CoseKeyParameter[CoseKeyParameter["CurveOrK"] = -1] = "CurveOrK";
642
- CoseKeyParameter[CoseKeyParameter["X"] = -2] = "X";
643
- CoseKeyParameter[CoseKeyParameter["Y"] = -3] = "Y";
644
- CoseKeyParameter[CoseKeyParameter["D"] = -4] = "D";
645
- return CoseKeyParameter;
646
- }({});
647
- const coseKeySchema = typedMap([
648
- [CoseKeyParameter.KeyType, z.union([z.enum(KeyType), z.string()])],
649
- [CoseKeyParameter.KeyId, zUint8Array.or(z.string()).exactOptional()],
650
- [CoseKeyParameter.Algorithm, z.union([z.string({ error: "Cose algorithm must be a string" }), z.number({ error: "Cose algorithm must be a number" })]).exactOptional()],
651
- [CoseKeyParameter.KeyOps, z.array(z.union([z.enum(KeyOps), z.string()])).exactOptional()],
652
- [CoseKeyParameter.BaseIv, zUint8Array.exactOptional()],
653
- [CoseKeyParameter.CurveOrK, z.union([z.enum(Curve), zUint8Array]).exactOptional()],
654
- [CoseKeyParameter.X, zUint8Array.exactOptional()],
655
- [CoseKeyParameter.Y, zUint8Array.exactOptional()],
656
- [CoseKeyParameter.D, zUint8Array.exactOptional()]
203
+ //#region src/mdoc/models/ble-options.ts
204
+ const bleOptionsSchema = typedMap([
205
+ [0, z.boolean()],
206
+ [1, z.boolean()],
207
+ [10, zUint8Array.exactOptional()],
208
+ [11, zUint8Array.exactOptional()],
209
+ [20, zUint8Array.exactOptional()]
657
210
  ]);
658
- var CoseKey = class extends CborStructure {
211
+ var BleOptions = class extends CborStructure {
659
212
  static get encodingSchema() {
660
- return coseKeySchema;
661
- }
662
- get keyType() {
663
- return this.structure.get(CoseKeyParameter.KeyType);
664
- }
665
- get keyId() {
666
- const keyId = this.structure.get(CoseKeyParameter.KeyId);
667
- return keyId instanceof Uint8Array ? bytesToString(keyId) : keyId;
668
- }
669
- get algorithm() {
670
- return this.structure.get(CoseKeyParameter.Algorithm);
671
- }
672
- get keyOps() {
673
- return this.structure.get(CoseKeyParameter.KeyOps);
674
- }
675
- get baseIv() {
676
- return this.structure.get(CoseKeyParameter.BaseIv);
213
+ return bleOptionsSchema;
677
214
  }
678
- get curve() {
679
- if (this.keyType === KeyType.Ec || this.keyType === KeyType.Okp) return this.structure.get(CoseKeyParameter.CurveOrK);
215
+ get peripheralServerMode() {
216
+ return this.structure.get(0);
680
217
  }
681
- get x() {
682
- return this.structure.get(CoseKeyParameter.X);
218
+ get centralClientMode() {
219
+ return this.structure.get(1);
683
220
  }
684
- get y() {
685
- return this.structure.get(CoseKeyParameter.Y);
221
+ get peripheralServerModeUuid() {
222
+ return this.structure.get(10);
686
223
  }
687
- get d() {
688
- return this.structure.get(CoseKeyParameter.D);
224
+ get centralClientModeUuid() {
225
+ return this.structure.get(11);
689
226
  }
690
- get k() {
691
- if (this.keyType === KeyType.Oct) return this.structure.get(CoseKeyParameter.CurveOrK);
227
+ get peripheralServerModeDeviceAddress() {
228
+ return this.structure.get(20);
692
229
  }
693
230
  static create(options) {
694
- const map = new TypedMap([[CoseKeyParameter.KeyType, options.keyType]]);
695
- if (options.keyId !== void 0) map.set(CoseKeyParameter.KeyId, stringToBytes(options.keyId));
696
- if (options.algorithm !== void 0) map.set(CoseKeyParameter.Algorithm, options.algorithm);
697
- if (options.keyOps !== void 0) map.set(CoseKeyParameter.KeyOps, options.keyOps);
698
- if (options.baseIv !== void 0) map.set(CoseKeyParameter.BaseIv, options.baseIv);
699
- if (options.curve !== void 0) map.set(CoseKeyParameter.CurveOrK, options.curve);
700
- if (options.x !== void 0) map.set(CoseKeyParameter.X, options.x);
701
- if (options.y !== void 0) map.set(CoseKeyParameter.Y, options.y);
702
- if (options.d !== void 0) map.set(CoseKeyParameter.D, options.d);
703
- if (options.k !== void 0) map.set(CoseKeyParameter.CurveOrK, options.k);
704
- return this.fromDecodedStructure(map);
705
- }
706
- static fromJwk(jwk) {
707
- if (!("kty" in jwk)) throw new CoseInvalidValueForKtyError("JWK does not contain required kty value");
708
- const options = Object.entries(jwk).reduce((prev, [key, value]) => {
709
- const mappedKey = jwkCoseOptionsMap[key] ?? key;
710
- const mapFunction = jwkToCoseKey[key];
711
- const convertedValue = mapFunction ? mapFunction(value) : value;
712
- if (convertedValue !== void 0) return {
713
- ...prev,
714
- [mappedKey]: convertedValue
715
- };
716
- return prev;
717
- }, {});
718
- return this.create(options);
719
- }
720
- get publicKey() {
721
- if (this.keyType !== KeyType.Ec) throw new CoseInvalidKtyForRawError();
722
- if (!this.x) throw new CoseXNotDefinedError();
723
- if (!this.y) throw new CoseYNotDefinedError();
724
- return concatBytes([
725
- Uint8Array.from([4]),
726
- this.x,
727
- this.y
728
- ]);
231
+ const map = new Map([[0, options.peripheralServerMode], [1, options.centralClientMode]]);
232
+ if (options.peripheralServerModeUuid !== void 0) map.set(10, options.peripheralServerModeUuid);
233
+ if (options.centralClientModeUuid !== void 0) map.set(11, options.centralClientModeUuid);
234
+ if (options.peripheralServerModeDeviceAddress !== void 0) map.set(20, options.peripheralServerModeDeviceAddress);
235
+ return this.fromEncodedStructure(map);
729
236
  }
730
- get privateKey() {
731
- if (this.keyType === KeyType.Ec) {
732
- if (!this.d) throw new CoseDNotDefinedError();
733
- return this.d;
734
- }
735
- if (this.keyType === KeyType.Oct) {
736
- if (!this.k) throw new CoseKNotDefinedError();
737
- return this.k;
738
- }
739
- throw new CoseKeyTypeNotSupportedForPrivateKeyExtractionError();
740
- }
741
- get jwk() {
742
- const options = {
743
- keyType: this.keyType,
744
- keyId: this.keyId,
745
- algorithm: this.algorithm,
746
- keyOps: this.keyOps,
747
- baseIv: this.baseIv,
748
- curve: this.curve,
749
- x: this.x,
750
- y: this.y,
751
- d: this.d,
752
- k: this.k
753
- };
754
- return Object.entries(options).reduce((prev, [key, value]) => ({
755
- ...prev,
756
- [coseOptionsJwkMap[key] ?? key]: typeof coseKeyToJwk[key] === "function" ? coseKeyToJwk[key](value) : void 0
757
- }), {});
237
+ };
238
+ //#endregion
239
+ //#region src/mdoc/errors.ts
240
+ var MdlError = class extends Error {
241
+ constructor(message = new.target.name) {
242
+ super(message);
758
243
  }
759
244
  };
245
+ var MdlParseError = class extends MdlError {};
246
+ var PresentationDefinitionOrDocRequestsAreRequiredError = class extends MdlError {};
247
+ var SessionTranscriptOrSessionTranscriptBytesAreRequiredError = class extends MdlError {};
248
+ var DuplicateNamespaceInIssuerNamespacesError = class extends MdlError {};
249
+ var DuplicateDocumentInDeviceResponseError = class extends MdlError {};
250
+ var EitherSignatureOrMacMustBeProvidedError = class extends MdlError {};
251
+ var AtLeastOneCertificateRequiredError = class extends MdlError {};
252
+ var SignatureAlgorithmDoesNotMatchSigningKeyAlgorithmError = class extends MdlError {};
253
+ //#endregion
254
+ //#region src/mdoc/check-callback.ts
255
+ const defaultVerificationCallback = (verification) => {
256
+ if (verification.status !== "FAILED") return;
257
+ throw new MdlError(verification.reason ?? verification.check);
258
+ };
259
+ const onCategoryCheck = (onCheck, category) => {
260
+ return (item) => {
261
+ onCheck({
262
+ ...item,
263
+ category
264
+ });
265
+ };
266
+ };
760
267
  //#endregion
761
- //#region src/mdoc/models/ble-options.ts
762
- var BleOptionsKeys = /* @__PURE__ */ function(BleOptionsKeys) {
763
- BleOptionsKeys[BleOptionsKeys["PeripheralServerMode"] = 0] = "PeripheralServerMode";
764
- BleOptionsKeys[BleOptionsKeys["CentralClientMode"] = 1] = "CentralClientMode";
765
- BleOptionsKeys[BleOptionsKeys["PeripheralServerModeUuid"] = 10] = "PeripheralServerModeUuid";
766
- BleOptionsKeys[BleOptionsKeys["CentralClientModeUuid"] = 11] = "CentralClientModeUuid";
767
- BleOptionsKeys[BleOptionsKeys["PeripheralServerModeDeviceAddress"] = 20] = "PeripheralServerModeDeviceAddress";
768
- return BleOptionsKeys;
769
- }(BleOptionsKeys || {});
770
- const bleOptionsSchema = typedMap([
771
- [BleOptionsKeys.PeripheralServerMode, z.boolean()],
772
- [BleOptionsKeys.CentralClientMode, z.boolean()],
773
- [BleOptionsKeys.PeripheralServerModeUuid, zUint8Array.exactOptional()],
774
- [BleOptionsKeys.CentralClientModeUuid, zUint8Array.exactOptional()],
775
- [BleOptionsKeys.PeripheralServerModeDeviceAddress, zUint8Array.exactOptional()]
776
- ]);
777
- var BleOptions = class extends CborStructure {
268
+ //#region src/mdoc/models/device-signed-items.ts
269
+ const deviceSignedItemsSchema = z.map(z.string(), z.unknown());
270
+ var DeviceSignedItems = class extends CborStructure {
778
271
  static get encodingSchema() {
779
- return bleOptionsSchema;
780
- }
781
- get peripheralServerMode() {
782
- return this.structure.get(BleOptionsKeys.PeripheralServerMode);
272
+ return deviceSignedItemsSchema;
783
273
  }
784
- get centralClientMode() {
785
- return this.structure.get(BleOptionsKeys.CentralClientMode);
274
+ get deviceSignedItems() {
275
+ return this.structure;
786
276
  }
787
- get peripheralServerModeUuid() {
788
- return this.structure.get(BleOptionsKeys.PeripheralServerModeUuid);
277
+ static create(options) {
278
+ return this.fromEncodedStructure(options.deviceSignedItems);
789
279
  }
790
- get centralClientModeUuid() {
791
- return this.structure.get(BleOptionsKeys.CentralClientModeUuid);
280
+ };
281
+ //#endregion
282
+ //#region src/mdoc/models/device-namespaces.ts
283
+ const deviceNamespacesEncodedSchema = z.map(z.string(), deviceSignedItemsSchema);
284
+ const deviceNamespacesDecodedSchema = z.map(z.string(), z.instanceof(DeviceSignedItems));
285
+ var DeviceNamespaces = class extends CborStructure {
286
+ static get encodingSchema() {
287
+ return z.codec(deviceNamespacesEncodedSchema, deviceNamespacesDecodedSchema, {
288
+ decode: (input) => {
289
+ const deviceNamespaces = /* @__PURE__ */ new Map();
290
+ input.forEach((value, key) => {
291
+ deviceNamespaces.set(key, DeviceSignedItems.fromEncodedStructure(value));
292
+ });
293
+ return deviceNamespaces;
294
+ },
295
+ encode: (output) => {
296
+ const map = /* @__PURE__ */ new Map();
297
+ output.forEach((value, key) => {
298
+ map.set(key, value.encodedStructure);
299
+ });
300
+ return map;
301
+ }
302
+ });
792
303
  }
793
- get peripheralServerModeDeviceAddress() {
794
- return this.structure.get(BleOptionsKeys.PeripheralServerModeDeviceAddress);
304
+ get deviceNamespaces() {
305
+ return this.structure;
795
306
  }
796
307
  static create(options) {
797
- const map = new Map([[BleOptionsKeys.PeripheralServerMode, options.peripheralServerMode], [BleOptionsKeys.CentralClientMode, options.centralClientMode]]);
798
- if (options.peripheralServerModeUuid !== void 0) map.set(BleOptionsKeys.PeripheralServerModeUuid, options.peripheralServerModeUuid);
799
- if (options.centralClientModeUuid !== void 0) map.set(BleOptionsKeys.CentralClientModeUuid, options.centralClientModeUuid);
800
- if (options.peripheralServerModeDeviceAddress !== void 0) map.set(BleOptionsKeys.PeripheralServerModeDeviceAddress, options.peripheralServerModeDeviceAddress);
801
- return this.fromEncodedStructure(map);
308
+ return this.fromDecodedStructure(options.deviceNamespaces);
802
309
  }
803
310
  };
804
311
  //#endregion
805
312
  //#region src/mdoc/models/nfc-options.ts
806
- var NfcOptionsKeys = /* @__PURE__ */ function(NfcOptionsKeys) {
807
- NfcOptionsKeys[NfcOptionsKeys["MaxCommandDataLength"] = 0] = "MaxCommandDataLength";
808
- NfcOptionsKeys[NfcOptionsKeys["MaxResponseDataLength"] = 1] = "MaxResponseDataLength";
809
- return NfcOptionsKeys;
810
- }(NfcOptionsKeys || {});
811
- const nfcOptionsSchema = typedMap([[NfcOptionsKeys.MaxCommandDataLength, z.number()], [NfcOptionsKeys.MaxResponseDataLength, z.number()]]);
313
+ const nfcOptionsSchema = typedMap([[0, z.number()], [1, z.number()]]);
812
314
  var NfcOptions = class extends CborStructure {
813
315
  static get encodingSchema() {
814
316
  return nfcOptionsSchema;
815
317
  }
816
318
  get maxCommandDataLength() {
817
- return this.structure.get(NfcOptionsKeys.MaxCommandDataLength);
319
+ return this.structure.get(0);
818
320
  }
819
321
  get maxResponseDataLength() {
820
- return this.structure.get(NfcOptionsKeys.MaxResponseDataLength);
322
+ return this.structure.get(1);
821
323
  }
822
324
  static create(options) {
823
- const map = new Map([[NfcOptionsKeys.MaxCommandDataLength, options.maxCommandDataLength], [NfcOptionsKeys.MaxResponseDataLength, options.maxResponseDataLength]]);
325
+ const map = new Map([[0, options.maxCommandDataLength], [1, options.maxResponseDataLength]]);
824
326
  return this.fromEncodedStructure(map);
825
327
  }
826
328
  };
827
329
  //#endregion
828
330
  //#region src/mdoc/models/wifi-options.ts
829
- var WifiOptionsKeys = /* @__PURE__ */ function(WifiOptionsKeys) {
830
- WifiOptionsKeys[WifiOptionsKeys["Passphrase"] = 0] = "Passphrase";
831
- WifiOptionsKeys[WifiOptionsKeys["OperatingClass"] = 1] = "OperatingClass";
832
- WifiOptionsKeys[WifiOptionsKeys["ChannelNumber"] = 2] = "ChannelNumber";
833
- WifiOptionsKeys[WifiOptionsKeys["SupportedBands"] = 3] = "SupportedBands";
834
- return WifiOptionsKeys;
835
- }(WifiOptionsKeys || {});
836
331
  const wifiOptionsSchema = typedMap([
837
- [WifiOptionsKeys.Passphrase, z.string().exactOptional()],
838
- [WifiOptionsKeys.OperatingClass, z.number().exactOptional()],
839
- [WifiOptionsKeys.ChannelNumber, z.number().exactOptional()],
840
- [WifiOptionsKeys.SupportedBands, zUint8Array.exactOptional()]
332
+ [0, z.string().exactOptional()],
333
+ [1, z.number().exactOptional()],
334
+ [2, z.number().exactOptional()],
335
+ [3, zUint8Array.exactOptional()]
841
336
  ]);
842
337
  var WifiOptions = class extends CborStructure {
843
338
  static get encodingSchema() {
@@ -847,23 +342,23 @@ var WifiOptions = class extends CborStructure {
847
342
  return this.structure.toMap();
848
343
  }
849
344
  get passphrase() {
850
- return this.structure.get(WifiOptionsKeys.Passphrase);
345
+ return this.structure.get(0);
851
346
  }
852
347
  get channelInfoOperatingClass() {
853
- return this.structure.get(WifiOptionsKeys.OperatingClass);
348
+ return this.structure.get(1);
854
349
  }
855
350
  get channelInfoChannelNumber() {
856
- return this.structure.get(WifiOptionsKeys.ChannelNumber);
351
+ return this.structure.get(2);
857
352
  }
858
353
  get bandInfoSupportedBands() {
859
- return this.structure.get(WifiOptionsKeys.SupportedBands);
354
+ return this.structure.get(3);
860
355
  }
861
356
  static create(options) {
862
357
  const entries = [];
863
- if (options.passphrase !== void 0) entries.push([WifiOptionsKeys.Passphrase, options.passphrase]);
864
- if (options.channelInfoOperatingClass !== void 0) entries.push([WifiOptionsKeys.OperatingClass, options.channelInfoOperatingClass]);
865
- if (options.channelInfoChannelNumber !== void 0) entries.push([WifiOptionsKeys.ChannelNumber, options.channelInfoChannelNumber]);
866
- if (options.bandInfoSupportedBands !== void 0) entries.push([WifiOptionsKeys.SupportedBands, options.bandInfoSupportedBands]);
358
+ if (options.passphrase !== void 0) entries.push([0, options.passphrase]);
359
+ if (options.channelInfoOperatingClass !== void 0) entries.push([1, options.channelInfoOperatingClass]);
360
+ if (options.channelInfoChannelNumber !== void 0) entries.push([2, options.channelInfoChannelNumber]);
361
+ if (options.bandInfoSupportedBands !== void 0) entries.push([3, options.bandInfoSupportedBands]);
867
362
  const map = new Map(entries);
868
363
  return this.fromEncodedStructure(map);
869
364
  }
@@ -896,9 +391,9 @@ var DeviceRetrievalMethod = class extends CborStructure {
896
391
  return z.codec(deviceRetrievalMethodEncodedSchema, deviceRetrievalMethodDecodedSchema, {
897
392
  decode: ([type, version, retrievalOptions]) => {
898
393
  let options;
899
- if (type === DeviceRetrievalMethodType.Nfc) options = NfcOptions.fromEncodedStructure(retrievalOptions);
900
- else if (type === DeviceRetrievalMethodType.Ble) options = BleOptions.fromEncodedStructure(retrievalOptions);
901
- else if (type === DeviceRetrievalMethodType.WifiAware) options = WifiOptions.fromEncodedStructure(retrievalOptions);
394
+ if (type === 1) options = NfcOptions.fromEncodedStructure(retrievalOptions);
395
+ else if (type === 2) options = BleOptions.fromEncodedStructure(retrievalOptions);
396
+ else if (type === 3) options = WifiOptions.fromEncodedStructure(retrievalOptions);
902
397
  else options = retrievalOptions;
903
398
  return {
904
399
  type,
@@ -940,7 +435,7 @@ var ProtocolInfo = class extends CborStructure {
940
435
  };
941
436
  //#endregion
942
437
  //#region src/mdoc/models/e-device-key.ts
943
- var EDeviceKey = class extends CoseKey {};
438
+ var EDeviceKey = class extends CoseKey$1 {};
944
439
  //#endregion
945
440
  //#region src/mdoc/models/security.ts
946
441
  const securityEncodedSchema = z.tuple([z.number(), z.instanceof(DataItem)]);
@@ -1092,77 +587,69 @@ var ServerRetrievalMethod = class extends CborStructure {
1092
587
  };
1093
588
  //#endregion
1094
589
  //#region src/mdoc/models/device-engagement.ts
1095
- var DeviceEngagementKeys = /* @__PURE__ */ function(DeviceEngagementKeys) {
1096
- DeviceEngagementKeys[DeviceEngagementKeys["Version"] = 0] = "Version";
1097
- DeviceEngagementKeys[DeviceEngagementKeys["Security"] = 1] = "Security";
1098
- DeviceEngagementKeys[DeviceEngagementKeys["DeviceRetrievalMethods"] = 2] = "DeviceRetrievalMethods";
1099
- DeviceEngagementKeys[DeviceEngagementKeys["ServerRetrievalMethods"] = 3] = "ServerRetrievalMethods";
1100
- DeviceEngagementKeys[DeviceEngagementKeys["ProtocolInfo"] = 4] = "ProtocolInfo";
1101
- return DeviceEngagementKeys;
1102
- }(DeviceEngagementKeys || {});
1103
590
  const deviceEngagementSchema = typedMap([
1104
- [DeviceEngagementKeys.Version, z.string()],
1105
- [DeviceEngagementKeys.Security, z.instanceof(Security)],
1106
- [DeviceEngagementKeys.DeviceRetrievalMethods, z.array(z.instanceof(DeviceRetrievalMethod)).exactOptional()],
1107
- [DeviceEngagementKeys.ServerRetrievalMethods, z.array(z.instanceof(ServerRetrievalMethod)).exactOptional()],
1108
- [DeviceEngagementKeys.ProtocolInfo, z.instanceof(ProtocolInfo).exactOptional()]
591
+ [0, z.string()],
592
+ [1, z.instanceof(Security)],
593
+ [2, z.array(z.instanceof(DeviceRetrievalMethod)).exactOptional()],
594
+ [3, z.array(z.instanceof(ServerRetrievalMethod)).exactOptional()],
595
+ [4, z.instanceof(ProtocolInfo).exactOptional()]
1109
596
  ]);
1110
597
  var DeviceEngagement = class extends CborStructure {
1111
598
  static get encodingSchema() {
1112
599
  return z.codec(deviceEngagementSchema.in, deviceEngagementSchema.out, {
1113
600
  decode: (input) => {
1114
601
  const map = TypedMap.fromMap(input);
1115
- map.set(DeviceEngagementKeys.Security, Security.fromEncodedStructure(input.get(DeviceEngagementKeys.Security)));
1116
- if (input.has(DeviceEngagementKeys.DeviceRetrievalMethods)) {
1117
- const deviceMethods = input.get(DeviceEngagementKeys.DeviceRetrievalMethods);
1118
- map.set(DeviceEngagementKeys.DeviceRetrievalMethods, deviceMethods.map((encoded) => DeviceRetrievalMethod.fromEncodedStructure(encoded)));
602
+ map.set(1, Security.fromEncodedStructure(input.get(1)));
603
+ if (input.has(2)) {
604
+ const deviceMethods = input.get(2);
605
+ map.set(2, deviceMethods.map((encoded) => DeviceRetrievalMethod.fromEncodedStructure(encoded)));
1119
606
  }
1120
- if (input.has(DeviceEngagementKeys.ServerRetrievalMethods)) {
1121
- const serverMethods = input.get(DeviceEngagementKeys.ServerRetrievalMethods);
1122
- map.set(DeviceEngagementKeys.ServerRetrievalMethods, serverMethods.map((encoded) => ServerRetrievalMethod.fromEncodedStructure(encoded)));
607
+ if (input.has(3)) {
608
+ const serverMethods = input.get(3);
609
+ map.set(3, serverMethods.map((encoded) => ServerRetrievalMethod.fromEncodedStructure(encoded)));
1123
610
  }
1124
- if (input.has(DeviceEngagementKeys.ProtocolInfo)) map.set(DeviceEngagementKeys.ProtocolInfo, ProtocolInfo.fromEncodedStructure(input.get(DeviceEngagementKeys.ProtocolInfo)));
611
+ if (input.has(4)) map.set(4, ProtocolInfo.fromEncodedStructure(input.get(4)));
1125
612
  return map;
1126
613
  },
1127
614
  encode: (output) => {
1128
615
  const map = output.toMap();
1129
- map.set(DeviceEngagementKeys.Security, output.get(DeviceEngagementKeys.Security).encodedStructure);
1130
- const deviceRetrievalMethods = output.get(DeviceEngagementKeys.DeviceRetrievalMethods);
1131
- if (deviceRetrievalMethods) map.set(DeviceEngagementKeys.DeviceRetrievalMethods, deviceRetrievalMethods.map((drm) => drm.encodedStructure));
1132
- const serverRetrievalMethods = output.get(DeviceEngagementKeys.ServerRetrievalMethods);
1133
- if (serverRetrievalMethods) map.set(DeviceEngagementKeys.ServerRetrievalMethods, serverRetrievalMethods.map((srm) => srm.encodedStructure));
1134
- const protocolInfo = output.get(DeviceEngagementKeys.ProtocolInfo);
1135
- if (protocolInfo) map.set(DeviceEngagementKeys.ProtocolInfo, protocolInfo.encodedStructure);
616
+ map.set(1, output.get(1).encodedStructure);
617
+ const deviceRetrievalMethods = output.get(2);
618
+ if (deviceRetrievalMethods) map.set(2, deviceRetrievalMethods.map((drm) => drm.encodedStructure));
619
+ const serverRetrievalMethods = output.get(3);
620
+ if (serverRetrievalMethods) map.set(3, serverRetrievalMethods.map((srm) => srm.encodedStructure));
621
+ const protocolInfo = output.get(4);
622
+ if (protocolInfo) map.set(4, protocolInfo.encodedStructure);
1136
623
  return map;
1137
624
  }
1138
625
  });
1139
626
  }
1140
627
  get version() {
1141
- return this.structure.get(DeviceEngagementKeys.Version);
628
+ return this.structure.get(0);
1142
629
  }
1143
630
  get security() {
1144
- return this.structure.get(DeviceEngagementKeys.Security);
631
+ return this.structure.get(1);
1145
632
  }
1146
633
  get deviceRetrievalMethods() {
1147
- return this.structure.get(DeviceEngagementKeys.DeviceRetrievalMethods);
634
+ return this.structure.get(2);
1148
635
  }
1149
636
  get serverRetrievalMethods() {
1150
- return this.structure.get(DeviceEngagementKeys.ServerRetrievalMethods);
637
+ return this.structure.get(3);
1151
638
  }
1152
639
  get protocolInfo() {
1153
- return this.structure.get(DeviceEngagementKeys.ProtocolInfo);
640
+ return this.structure.get(4);
1154
641
  }
1155
642
  static create(options) {
1156
- const map = new Map([[DeviceEngagementKeys.Version, options.version], [DeviceEngagementKeys.Security, options.security]]);
1157
- if (options.deviceRetrievalMethods !== void 0) map.set(DeviceEngagementKeys.DeviceRetrievalMethods, options.deviceRetrievalMethods);
1158
- if (options.serverRetrievalMethods !== void 0) map.set(DeviceEngagementKeys.ServerRetrievalMethods, options.serverRetrievalMethods);
1159
- if (options.protocolInfo !== void 0) map.set(DeviceEngagementKeys.ProtocolInfo, options.protocolInfo);
643
+ const map = new Map([[0, options.version], [1, options.security]]);
644
+ if (options.deviceRetrievalMethods !== void 0) map.set(2, options.deviceRetrievalMethods);
645
+ if (options.serverRetrievalMethods !== void 0) map.set(3, options.serverRetrievalMethods);
646
+ if (options.protocolInfo !== void 0) map.set(4, options.protocolInfo);
1160
647
  return this.fromEncodedStructure(map);
1161
648
  }
1162
649
  };
1163
650
  //#endregion
1164
651
  //#region src/mdoc/models/e-reader-key.ts
1165
- var EReaderKey = class extends CoseKey {};
652
+ var EReaderKey = class extends CoseKey$1 {};
1166
653
  //#endregion
1167
654
  //#region src/mdoc/models/handover.ts
1168
655
  var Handover = class extends CborStructure {
@@ -1364,11 +851,11 @@ var Oid4vpDraft18Handover = class extends Handover {
1364
851
  static async create(options, ctx) {
1365
852
  const clientIdHash = await ctx.crypto.digest({
1366
853
  digestAlgorithm: "SHA-256",
1367
- bytes: cborEncode([options.clientId, options.mdocGeneratedNonce])
854
+ bytes: cborEncode$1([options.clientId, options.mdocGeneratedNonce])
1368
855
  });
1369
856
  const responseUriHash = await ctx.crypto.digest({
1370
857
  digestAlgorithm: "SHA-256",
1371
- bytes: cborEncode([options.responseUri, options.mdocGeneratedNonce])
858
+ bytes: cborEncode$1([options.responseUri, options.mdocGeneratedNonce])
1372
859
  });
1373
860
  return this.fromDecodedStructure({
1374
861
  clientIdHash,
@@ -1671,338 +1158,6 @@ var SessionTranscript = class extends CborStructure {
1671
1158
  }
1672
1159
  };
1673
1160
  //#endregion
1674
- //#region src/cose/mac0.ts
1675
- const mac0EncodedSchema = z.tuple([
1676
- zUint8Array,
1677
- z.map(z.unknown(), z.unknown()),
1678
- zUint8Array.nullable(),
1679
- zUint8Array
1680
- ]);
1681
- const mac0DecodedSchema = z.object({
1682
- protectedHeaders: z.instanceof(ProtectedHeaders),
1683
- unprotectedHeaders: z.instanceof(UnprotectedHeaders),
1684
- payload: zUint8Array.nullable(),
1685
- tag: zUint8Array
1686
- });
1687
- var Mac0 = class Mac0 extends CborStructure {
1688
- static {
1689
- this.tag = 17;
1690
- }
1691
- static get encodingSchema() {
1692
- return z.codec(mac0EncodedSchema, mac0DecodedSchema, {
1693
- decode: ([protectedHeadersBytes, unprotectedHeadersMap, payload, tag]) => ({
1694
- protectedHeaders: ProtectedHeaders.fromEncodedStructure(protectedHeadersBytes),
1695
- unprotectedHeaders: UnprotectedHeaders.fromEncodedStructure(unprotectedHeadersMap),
1696
- payload,
1697
- tag
1698
- }),
1699
- encode: ({ protectedHeaders, unprotectedHeaders, payload, tag }) => [
1700
- protectedHeaders.encodedStructure,
1701
- unprotectedHeaders.encodedStructure,
1702
- payload,
1703
- tag
1704
- ]
1705
- });
1706
- }
1707
- get protectedHeaders() {
1708
- return this.structure.protectedHeaders;
1709
- }
1710
- get unprotectedHeaders() {
1711
- return this.structure.unprotectedHeaders;
1712
- }
1713
- get payload() {
1714
- return this.structure.payload;
1715
- }
1716
- get tag() {
1717
- return this.structure.tag;
1718
- }
1719
- get toBeAuthenticated() {
1720
- const payload = this.payload ?? this.detachedPayload;
1721
- if (!payload) throw new CosePayloadMustBeDefinedError();
1722
- return Mac0.toBeAuthenticated({
1723
- payload,
1724
- protectedHeaders: this.protectedHeaders,
1725
- externalAad: this.externalAad
1726
- });
1727
- }
1728
- /**
1729
- * Decodes CBOR bytes into a Sign1 instance.
1730
- * Uses the encodingSchema's decode() method to validate and transform the decoded data.
1731
- */
1732
- static decode(bytes) {
1733
- const rawStructure = cborDecode(bytes);
1734
- return new this(rawStructure instanceof Mac0 ? rawStructure.decodedStructure : this.fromEncodedStructure(rawStructure).decodedStructure);
1735
- }
1736
- static toBeAuthenticated(options) {
1737
- const toBeAuthenticated = ["MAC0", options.protectedHeaders.encodedStructure];
1738
- if (options.externalAad) toBeAuthenticated.push(options.externalAad);
1739
- toBeAuthenticated.push(options.payload);
1740
- return cborEncode(toBeAuthenticated);
1741
- }
1742
- get signatureAlgorithmName() {
1743
- const algorithm = this.protectedHeaders.headers?.get(Header.Algorithm) ?? this.unprotectedHeaders.headers?.get(Header.Algorithm);
1744
- if (!algorithm) throw new CoseInvalidAlgorithmError();
1745
- const algorithmName = coseKeyToJwk.algorithm(algorithm);
1746
- if (!algorithmName) throw new CoseInvalidAlgorithmError();
1747
- return algorithmName;
1748
- }
1749
- static async create(options, ctx) {
1750
- const protectedHeaders = options.protectedHeaders instanceof ProtectedHeaders ? options.protectedHeaders : ProtectedHeaders.create({ protectedHeaders: options.protectedHeaders });
1751
- const unprotectedHeaders = options.unprotectedHeaders instanceof UnprotectedHeaders ? options.unprotectedHeaders : UnprotectedHeaders.create({ unprotectedHeaders: options.unprotectedHeaders });
1752
- const ephemeralMacKey = await ctx.crypto.calculateEphemeralMacKey({
1753
- privateKey: options.privateKey.encode(),
1754
- publicKey: options.ephemeralKey.encode(),
1755
- sessionTranscriptBytes: options.sessionTranscript instanceof SessionTranscript ? options.sessionTranscript.encode({ asDataItem: true }) : options.sessionTranscript,
1756
- info: "EMacKey"
1757
- });
1758
- const payload = options.payload ?? options.detachedPayload;
1759
- if (!payload) throw new CosePayloadMustBeDefinedError();
1760
- const tag = await ctx.cose.mac0.sign({
1761
- toBeAuthenticated: Mac0.toBeAuthenticated({
1762
- payload,
1763
- protectedHeaders,
1764
- externalAad: options.externalAad
1765
- }),
1766
- key: ephemeralMacKey
1767
- });
1768
- const mac0 = this.fromDecodedStructure({
1769
- protectedHeaders,
1770
- unprotectedHeaders,
1771
- payload: options.payload ?? null,
1772
- tag
1773
- });
1774
- mac0.externalAad = options.externalAad;
1775
- mac0.detachedPayload = options.detachedPayload;
1776
- return mac0;
1777
- }
1778
- };
1779
- addExtension$1({
1780
- Class: Mac0,
1781
- tag: Mac0.tag,
1782
- encode(instance, encodeFn) {
1783
- return encodeFn(instance.encodedStructure);
1784
- },
1785
- decode: (encoded) => Mac0.fromEncodedStructure(encoded)
1786
- });
1787
- //#endregion
1788
- //#region src/cose/sign1.ts
1789
- const sign1EncodedSchema = z$1.tuple([
1790
- protectedHeadersEncodedStructure,
1791
- unprotectedHeadersStructure,
1792
- zUint8Array.nullable(),
1793
- zUint8Array
1794
- ]);
1795
- const sign1DecodedSchema = z$1.object({
1796
- protected: z$1.instanceof(ProtectedHeaders),
1797
- unprotected: z$1.instanceof(UnprotectedHeaders),
1798
- payload: sign1EncodedSchema.def.items[2],
1799
- signature: sign1EncodedSchema.def.items[3]
1800
- });
1801
- var Sign1 = class Sign1 extends CborStructure {
1802
- static {
1803
- this.tag = 18;
1804
- }
1805
- static get encodingSchema() {
1806
- return z$1.codec(sign1EncodedSchema, sign1DecodedSchema, {
1807
- encode: (decoded) => [
1808
- decoded.protected.encodedStructure,
1809
- decoded.unprotected.encodedStructure,
1810
- decoded.payload,
1811
- decoded.signature
1812
- ],
1813
- decode: ([protectedHeaders, unprotected, payload, signature]) => ({
1814
- protected: ProtectedHeaders.fromEncodedStructure(protectedHeaders),
1815
- unprotected: UnprotectedHeaders.fromEncodedStructure(unprotected),
1816
- payload,
1817
- signature
1818
- })
1819
- });
1820
- }
1821
- get protectedHeaders() {
1822
- return this.structure.protected;
1823
- }
1824
- get unprotectedHeaders() {
1825
- return this.structure.unprotected;
1826
- }
1827
- get payload() {
1828
- return this.structure.payload;
1829
- }
1830
- get signature() {
1831
- return this.structure.signature;
1832
- }
1833
- get certificateChain() {
1834
- return this.x5chain ?? [];
1835
- }
1836
- get certificate() {
1837
- const [certificate] = this.certificateChain;
1838
- if (!certificate) throw new CoseCertificateNotFoundError();
1839
- return certificate;
1840
- }
1841
- getIssuingCountry(ctx) {
1842
- return ctx.x509.getIssuerNameField({
1843
- certificate: this.certificate,
1844
- field: "C"
1845
- })[0];
1846
- }
1847
- getIssuingStateOrProvince(ctx) {
1848
- return ctx.x509.getIssuerNameField({
1849
- certificate: this.certificate,
1850
- field: "ST"
1851
- })[0];
1852
- }
1853
- get toBeSigned() {
1854
- const payload = this.payload ?? this.detachedPayload;
1855
- if (!payload) throw new CosePayloadMustBeDefinedError();
1856
- return Sign1.toBeSigned({
1857
- payload,
1858
- protectedHeaders: this.protectedHeaders,
1859
- externalAad: this.externalAad
1860
- });
1861
- }
1862
- /**
1863
- * Decodes CBOR bytes into a Sign1 instance.
1864
- * Uses the encodingSchema's decode() method to validate and transform the decoded data.
1865
- */
1866
- static decode(bytes) {
1867
- const rawStructure = cborDecode(bytes);
1868
- return new this(rawStructure instanceof Sign1 ? rawStructure.decodedStructure : this.fromEncodedStructure(rawStructure).decodedStructure);
1869
- }
1870
- static toBeSigned(options) {
1871
- return cborEncode([
1872
- "Signature1",
1873
- options.protectedHeaders.encodedStructure,
1874
- options.externalAad ?? new Uint8Array(),
1875
- options.payload
1876
- ]);
1877
- }
1878
- get signatureAlgorithmName() {
1879
- const algorithm = this.protectedHeaders.headers?.get(Header.Algorithm) ?? this.unprotectedHeaders.headers?.get(Header.Algorithm);
1880
- if (!algorithm) throw new CoseInvalidAlgorithmError();
1881
- const algorithmName = coseKeyToJwk.algorithm(algorithm);
1882
- if (!algorithmName) throw new CoseInvalidAlgorithmError();
1883
- return algorithmName;
1884
- }
1885
- get x5chain() {
1886
- const x5chain = this.protectedHeaders.headers?.get(Header.X5Chain) ?? this.unprotectedHeaders.headers?.get(Header.X5Chain);
1887
- if (!x5chain?.[0]) return;
1888
- return Array.isArray(x5chain) ? x5chain : [x5chain];
1889
- }
1890
- async verifySignature(options, ctx) {
1891
- const publicKey = options.key ?? await ctx.x509.getPublicKey({
1892
- certificate: this.certificate,
1893
- alg: this.signatureAlgorithmName
1894
- });
1895
- return await ctx.cose.sign1.verify({
1896
- sign1: this,
1897
- key: publicKey
1898
- });
1899
- }
1900
- static async create(options, ctx) {
1901
- const payload = options.payload ?? options.detachedPayload;
1902
- if (!payload) throw new CosePayloadMustBeDefinedError();
1903
- const protectedHeaders = options.protectedHeaders instanceof ProtectedHeaders ? options.protectedHeaders : options.protectedHeaders ? ProtectedHeaders.fromDecodedStructure(options.protectedHeaders) : ProtectedHeaders.create({});
1904
- const signature = await ctx.cose.sign1.sign({
1905
- toBeSigned: Sign1.toBeSigned({
1906
- payload,
1907
- protectedHeaders,
1908
- externalAad: options.externalAad
1909
- }),
1910
- key: options.signingKey,
1911
- algorithm: options.algorithm ?? options.signingKey.algorithm
1912
- });
1913
- const sign1 = this.fromDecodedStructure({
1914
- payload: options.payload ?? null,
1915
- protected: protectedHeaders,
1916
- unprotected: options.unprotectedHeaders instanceof UnprotectedHeaders ? options.unprotectedHeaders : options.unprotectedHeaders ? UnprotectedHeaders.fromEncodedStructure(options.unprotectedHeaders) : UnprotectedHeaders.create({}),
1917
- signature
1918
- });
1919
- sign1.detachedPayload = options.detachedPayload;
1920
- sign1.externalAad = options.externalAad;
1921
- return sign1;
1922
- }
1923
- };
1924
- addExtension$1({
1925
- Class: Sign1,
1926
- tag: Sign1.tag,
1927
- encode(instance, encodeFn) {
1928
- return encodeFn(instance);
1929
- },
1930
- decode: (encoded) => Sign1.fromEncodedStructure(encoded)
1931
- });
1932
- //#endregion
1933
- //#region src/mdoc/errors.ts
1934
- var MdlError = class extends Error {
1935
- constructor(message = new.target.name) {
1936
- super(message);
1937
- }
1938
- };
1939
- var MdlParseError = class extends MdlError {};
1940
- var PresentationDefinitionOrDocRequestsAreRequiredError = class extends MdlError {};
1941
- var SessionTranscriptOrSessionTranscriptBytesAreRequiredError = class extends MdlError {};
1942
- var DuplicateNamespaceInIssuerNamespacesError = class extends MdlError {};
1943
- var DuplicateDocumentInDeviceResponseError = class extends MdlError {};
1944
- var EitherSignatureOrMacMustBeProvidedError = class extends MdlError {};
1945
- var AtLeastOneCertificateRequiredError = class extends MdlError {};
1946
- var SignatureAlgorithmDoesNotMatchSigningKeyAlgorithmError = class extends MdlError {};
1947
- //#endregion
1948
- //#region src/mdoc/check-callback.ts
1949
- const defaultVerificationCallback = (verification) => {
1950
- if (verification.status !== "FAILED") return;
1951
- throw new MdlError(verification.reason ?? verification.check);
1952
- };
1953
- const onCategoryCheck = (onCheck, category) => {
1954
- return (item) => {
1955
- onCheck({
1956
- ...item,
1957
- category
1958
- });
1959
- };
1960
- };
1961
- //#endregion
1962
- //#region src/mdoc/models/device-signed-items.ts
1963
- const deviceSignedItemsSchema = z.map(z.string(), z.unknown());
1964
- var DeviceSignedItems = class extends CborStructure {
1965
- static get encodingSchema() {
1966
- return deviceSignedItemsSchema;
1967
- }
1968
- get deviceSignedItems() {
1969
- return this.structure;
1970
- }
1971
- static create(options) {
1972
- return this.fromEncodedStructure(options.deviceSignedItems);
1973
- }
1974
- };
1975
- //#endregion
1976
- //#region src/mdoc/models/device-namespaces.ts
1977
- const deviceNamespacesEncodedSchema = z.map(z.string(), deviceSignedItemsSchema);
1978
- const deviceNamespacesDecodedSchema = z.map(z.string(), z.instanceof(DeviceSignedItems));
1979
- var DeviceNamespaces = class extends CborStructure {
1980
- static get encodingSchema() {
1981
- return z.codec(deviceNamespacesEncodedSchema, deviceNamespacesDecodedSchema, {
1982
- decode: (input) => {
1983
- const deviceNamespaces = /* @__PURE__ */ new Map();
1984
- input.forEach((value, key) => {
1985
- deviceNamespaces.set(key, DeviceSignedItems.fromEncodedStructure(value));
1986
- });
1987
- return deviceNamespaces;
1988
- },
1989
- encode: (output) => {
1990
- const map = /* @__PURE__ */ new Map();
1991
- output.forEach((value, key) => {
1992
- map.set(key, value.encodedStructure);
1993
- });
1994
- return map;
1995
- }
1996
- });
1997
- }
1998
- get deviceNamespaces() {
1999
- return this.structure;
2000
- }
2001
- static create(options) {
2002
- return this.fromDecodedStructure(options.deviceNamespaces);
2003
- }
2004
- };
2005
- //#endregion
2006
1161
  //#region src/mdoc/models/device-authentication.ts
2007
1162
  const deviceAuthenticationEncodedSchema = z.tuple([
2008
1163
  z.literal("DeviceAuthentication"),
@@ -2051,30 +1206,32 @@ var DeviceAuthentication = class extends CborStructure {
2051
1206
  };
2052
1207
  //#endregion
2053
1208
  //#region src/mdoc/models/device-mac.ts
2054
- var DeviceMac = class extends Mac0 {
1209
+ var DeviceMac = class extends Mac0$1 {
2055
1210
  async verify(options, ctx) {
2056
- const key = await ctx.crypto.calculateEphemeralMacKey({
2057
- privateKey: options.privateKey.privateKey,
2058
- publicKey: options.publicKey.publicKey,
2059
- sessionTranscriptBytes: options.sessionTranscript instanceof SessionTranscript ? options.sessionTranscript.encode({ asDataItem: true }) : options.sessionTranscript,
2060
- info: options.info ?? "EMacKey"
2061
- });
1211
+ const key = await this.createDeviceMacKey(options, ctx);
2062
1212
  return ctx.cose.mac0.verify({
2063
1213
  mac0: this,
2064
1214
  key
2065
1215
  });
2066
1216
  }
2067
- static async create(options, ctx) {
2068
- return super.create(options, ctx);
1217
+ static create(options) {
1218
+ return super.create(options);
1219
+ }
1220
+ async createDeviceMacKey(options, ctx) {
1221
+ return await ctx.crypto.hdkf({
1222
+ privateKey: options.privateKey.privateKey,
1223
+ publicKey: options.publicKey.publicKey,
1224
+ salt: await ctx.crypto.digest({
1225
+ digestAlgorithm: "SHA-256",
1226
+ bytes: options.sessionTranscript instanceof SessionTranscript ? options.sessionTranscript.encode({ asDataItem: true }) : options.sessionTranscript
1227
+ }),
1228
+ info: stringToBytes(options.info ?? "EMacKey")
1229
+ });
2069
1230
  }
2070
1231
  };
2071
1232
  //#endregion
2072
1233
  //#region src/mdoc/models/device-signature.ts
2073
- var DeviceSignature = class extends Sign1 {
2074
- static create(options, ctx) {
2075
- return super.create(options, ctx);
2076
- }
2077
- };
1234
+ var DeviceSignature = class extends Sign1$1 {};
2078
1235
  //#endregion
2079
1236
  //#region src/mdoc/models/device-auth.ts
2080
1237
  const deviceAuthSchema = typedMap([["deviceSignature", z.instanceof(DeviceSignature).exactOptional()], ["deviceMac", z.instanceof(DeviceMac).exactOptional()]]).refine((map) => [map.get("deviceMac"), map.get("deviceSignature")].filter((i) => i !== void 0).length === 1, { error: () => "deviceAuth must contain either a deviceMac or deviceSignature, but not both or neither" });
@@ -2186,7 +1343,7 @@ var DeviceAuth = class extends CborStructure {
2186
1343
  };
2187
1344
  //#endregion
2188
1345
  //#region src/mdoc/models/device-key.ts
2189
- var DeviceKey = class extends CoseKey {};
1346
+ var DeviceKey = class extends CoseKey$1 {};
2190
1347
  //#endregion
2191
1348
  //#region src/mdoc/models/key-authorizations.ts
2192
1349
  const keyAuthorizationsSchema = typedMap([["nameSpaces", z.array(z.string()).exactOptional()], ["dataElements", z.map(z.string(), z.array(z.string())).exactOptional()]]);
@@ -2325,19 +1482,22 @@ var ReaderAuthentication = class extends CborStructure {
2325
1482
  };
2326
1483
  //#endregion
2327
1484
  //#region src/mdoc/models/reader-auth.ts
2328
- var ReaderAuth = class extends Sign1 {
1485
+ var ReaderAuth = class extends Sign1$1 {
2329
1486
  async verify(options, ctx) {
2330
1487
  const readerAuthentication = options.readerAuthentication instanceof ReaderAuthentication ? options.readerAuthentication : new ReaderAuthentication(options.readerAuthentication);
2331
1488
  const onCheck = onCategoryCheck(options.verificationCallback ?? defaultVerificationCallback, "READER_AUTH");
2332
1489
  this.detachedPayload = readerAuthentication.encode({ asDataItem: true });
2333
1490
  onCheck({
2334
- status: await this.verifySignature({}, ctx) ? "PASSED" : "FAILED",
1491
+ status: await this.verifySignature({}, {
1492
+ verify: ctx.cose.sign1.verify,
1493
+ x509: ctx.x509
1494
+ }) ? "PASSED" : "FAILED",
2335
1495
  check: "Signature is invalid on the reader auth",
2336
1496
  reason: "Signature is invalid on the reader auth"
2337
1497
  });
2338
1498
  }
2339
- static create(options, ctx) {
2340
- return super.create(options, ctx);
1499
+ static create(options) {
1500
+ return super.create(options);
2341
1501
  }
2342
1502
  };
2343
1503
  //#endregion
@@ -2720,16 +1880,16 @@ var MobileSecurityObject = class extends CborStructure {
2720
1880
  };
2721
1881
  //#endregion
2722
1882
  //#region src/mdoc/models/issuer-auth.ts
2723
- var IssuerAuth = class extends Sign1 {
2724
- static create(options, ctx) {
1883
+ var IssuerAuth = class extends Sign1$1 {
1884
+ static create(options) {
2725
1885
  return super.create({
2726
1886
  ...options,
2727
1887
  payload: options.payload instanceof MobileSecurityObject ? options.payload.encode({ asDataItem: true }) : options.payload
2728
- }, ctx);
1888
+ });
2729
1889
  }
2730
1890
  get mobileSecurityObject() {
2731
1891
  if (!this.payload) throw new CosePayloadMustBeDefinedError();
2732
- return zUint8Array.transform((payload) => cborDecode(payload, { unwrapTopLevelDataItem: false })).pipe(z$1.instanceof(DataItem).transform((di) => MobileSecurityObject.fromEncodedStructure(di.data))).parse(this.payload);
1892
+ return zUint8Array.transform((payload) => cborDecode$1(payload, { unwrapTopLevelDataItem: false })).pipe(z$1.instanceof(DataItem).transform((di) => MobileSecurityObject.fromEncodedStructure(di.data))).parse(this.payload);
2733
1893
  }
2734
1894
  async verify(options, ctx) {
2735
1895
  const verificationCallback = options.verificationCallback ?? defaultVerificationCallback;
@@ -2761,7 +1921,10 @@ var IssuerAuth = class extends Sign1 {
2761
1921
  });
2762
1922
  }
2763
1923
  onCheck({
2764
- status: await this.verifySignature({}, ctx) ? "PASSED" : "FAILED",
1924
+ status: await this.verifySignature({}, {
1925
+ x509: ctx.x509,
1926
+ verify: ctx.cose.sign1.verify
1927
+ }) ? "PASSED" : "FAILED",
2765
1928
  check: "Issuer auth signature is invalid"
2766
1929
  });
2767
1930
  const { validityInfo } = this.mobileSecurityObject;
@@ -3061,26 +2224,29 @@ var DeviceResponse = class DeviceResponse extends CborStructure {
3061
2224
  docType,
3062
2225
  deviceNamespaces
3063
2226
  }).encode({ asDataItem: true });
3064
- const unprotectedHeaders = signingKey.keyId ? UnprotectedHeaders.create({ unprotectedHeaders: new Map([[Header.KeyId, signingKey.keyId]]) }) : UnprotectedHeaders.create({});
3065
- const protectedHeaders = ProtectedHeaders.create({ protectedHeaders: new Map([[Header.Algorithm, signingKey.algorithm]]) });
2227
+ const unprotectedHeaders = signingKey.keyId ? UnprotectedHeaders$1.create({ unprotectedHeaders: new Map([[RegisteredCwtHeaderClaimKey$1.KeyId, signingKey.keyId]]) }) : UnprotectedHeaders$1.create({});
2228
+ const protectedHeaders = ProtectedHeaders$1.create({ protectedHeaders: new Map([[RegisteredCwtHeaderClaimKey$1.Algorithm, signingKey.algorithm]]) });
3066
2229
  const deviceAuthOptions = {};
3067
2230
  if (useSignature) deviceAuthOptions.deviceSignature = await DeviceSignature.create({
3068
2231
  unprotectedHeaders,
3069
2232
  protectedHeaders,
3070
- detachedPayload: deviceAuthenticationBytes,
3071
- signingKey
3072
- }, ctx);
2233
+ detachedPayload: deviceAuthenticationBytes
2234
+ }).sign({ signingKey }, { sign: ctx.cose.sign1.sign });
3073
2235
  else {
3074
2236
  const ephemeralKey = options.mac?.ephemeralKey;
3075
2237
  if (!ephemeralKey) throw new Error("Ephemeral key is missing");
3076
- deviceAuthOptions.deviceMac = await DeviceMac.create({
2238
+ const deviceMac = DeviceMac.create({
3077
2239
  protectedHeaders,
3078
2240
  unprotectedHeaders,
3079
- detachedPayload: deviceAuthenticationBytes,
2241
+ detachedPayload: deviceAuthenticationBytes
2242
+ });
2243
+ const macKey = await deviceMac.createDeviceMacKey({
2244
+ publicKey: ephemeralKey,
3080
2245
  privateKey: signingKey,
3081
- ephemeralKey,
3082
2246
  sessionTranscript: options.sessionTranscript
3083
2247
  }, ctx);
2248
+ await deviceMac.authenticate({ key: macKey }, { mac: ctx.cose.mac0.sign });
2249
+ deviceAuthOptions.deviceMac = deviceMac;
3084
2250
  }
3085
2251
  return Document.create({
3086
2252
  docType,
@@ -3157,45 +2323,53 @@ var DeviceSignedBuilder = class {
3157
2323
  return this;
3158
2324
  }
3159
2325
  async sign(options) {
3160
- const protectedHeaders = ProtectedHeaders.create({ protectedHeaders: new Map([[Header.Algorithm, options.algorithm]]) });
3161
- const unprotectedHeaders = UnprotectedHeaders.create({ unprotectedHeaders: new Map([[Header.X5Chain, base64.decode(options.derCertificate)]]) });
3162
- if (options.signingKey.keyId) unprotectedHeaders.headers?.set(Header.KeyId, options.signingKey.keyId);
2326
+ const protectedHeaders = ProtectedHeaders$1.create({ protectedHeaders: new Map([[RegisteredCwtHeaderClaimKey$1.Algorithm, options.algorithm]]) });
2327
+ const unprotectedHeaders = UnprotectedHeaders$1.create({ unprotectedHeaders: new Map([[RegisteredCwtHeaderClaimKey$1.X5Chain, base64.decode(options.derCertificate)]]) });
2328
+ if (options.signingKey.keyId) unprotectedHeaders.headers?.set(RegisteredCwtHeaderClaimKey$1.KeyId, options.signingKey.keyId);
3163
2329
  const deviceAuthentication = DeviceAuthentication.create({
3164
2330
  sessionTranscript: options.sessionTranscript,
3165
2331
  deviceNamespaces: this.namespaces,
3166
2332
  docType: this.docType
3167
2333
  });
3168
- const deviceSignature = await DeviceSignature.create({
2334
+ const deviceSignature = DeviceSignature.create({
3169
2335
  unprotectedHeaders,
3170
2336
  protectedHeaders,
3171
- detachedPayload: deviceAuthentication.encode({ asDataItem: true }),
3172
- signingKey: options.signingKey
3173
- }, this.ctx);
2337
+ detachedPayload: deviceAuthentication.encode({ asDataItem: true })
2338
+ });
2339
+ await deviceSignature.sign({ signingKey: options.signingKey }, { sign: this.ctx.cose.sign1.sign });
3174
2340
  return DeviceSigned.create({
3175
2341
  deviceNamespaces: this.namespaces,
3176
2342
  deviceAuth: DeviceAuth.create({ deviceSignature })
3177
2343
  });
3178
2344
  }
3179
2345
  async tag(options) {
3180
- const protectedHeaders = ProtectedHeaders.create({ protectedHeaders: new Map([[Header.Algorithm, options.algorithm]]) });
3181
- const unprotectedHeaders = UnprotectedHeaders.create({ unprotectedHeaders: new Map([[Header.X5Chain, base64.decode(options.derCertificate)]]) });
3182
- if (options.privateKey.keyId) unprotectedHeaders.headers?.set(Header.KeyId, options.privateKey.keyId);
2346
+ const protectedHeaders = ProtectedHeaders$1.create({ protectedHeaders: new Map([[RegisteredCwtHeaderClaimKey$1.Algorithm, options.algorithm]]) });
2347
+ const unprotectedHeaders = UnprotectedHeaders$1.create({ unprotectedHeaders: new Map([[RegisteredCwtHeaderClaimKey$1.X5Chain, base64.decode(options.derCertificate)]]) });
2348
+ if (options.privateKey.keyId) unprotectedHeaders.headers?.set(RegisteredCwtHeaderClaimKey$1.KeyId, options.privateKey.keyId);
3183
2349
  const deviceAuthentication = DeviceAuthentication.create({
3184
2350
  sessionTranscript: options.sessionTranscript,
3185
2351
  deviceNamespaces: this.namespaces,
3186
2352
  docType: this.docType
3187
2353
  });
3188
- const deviceMac = await DeviceMac.create({
2354
+ const deviceMac = DeviceMac.create({
3189
2355
  unprotectedHeaders,
3190
2356
  protectedHeaders,
3191
- detachedPayload: deviceAuthentication.encode({ asDataItem: true }),
3192
- privateKey: options.privateKey,
3193
- ephemeralKey: options.publicKey,
3194
- sessionTranscript: options.sessionTranscript
3195
- }, this.ctx);
2357
+ detachedPayload: deviceAuthentication.encode({ asDataItem: true })
2358
+ });
2359
+ const salt = await this.ctx.crypto.digest({
2360
+ digestAlgorithm: "SHA-256",
2361
+ bytes: options.sessionTranscript.encode()
2362
+ });
2363
+ const derivedKey = await this.ctx.crypto.hdkf({
2364
+ privateKey: options.privateKey.privateKey,
2365
+ publicKey: options.publicKey.publicKey,
2366
+ info: stringToBytes("EMacKey"),
2367
+ salt
2368
+ });
2369
+ const deviceMacWithTag = await deviceMac.authenticate({ key: derivedKey }, { mac: this.ctx.cose.mac0.sign });
3196
2370
  return DeviceSigned.create({
3197
2371
  deviceNamespaces: this.namespaces,
3198
- deviceAuth: DeviceAuth.create({ deviceMac })
2372
+ deviceAuth: DeviceAuth.create({ deviceMac: deviceMacWithTag })
3199
2373
  });
3200
2374
  }
3201
2375
  };
@@ -3252,16 +2426,17 @@ var IssuerSignedBuilder = class {
3252
2426
  deviceKeyInfo,
3253
2427
  valueDigests: await this.convertIssuerNamespacesIntoValueDigests(options.digestAlgorithm)
3254
2428
  });
3255
- const protectedHeaders = ProtectedHeaders.create({ protectedHeaders: new Map([[Header.Algorithm, options.algorithm]]) });
3256
- const unprotectedHeaders = UnprotectedHeaders.create({ unprotectedHeaders: new Map([[Header.X5Chain, options.certificates.length === 1 ? options.certificates[0] : options.certificates]]) });
3257
- if (options.signingKey.keyId) unprotectedHeaders.headers?.set(Header.KeyId, options.signingKey.keyId);
2429
+ const protectedHeaders = ProtectedHeaders$1.create({ protectedHeaders: new Map([[RegisteredCwtHeaderClaimKey$1.Algorithm, options.algorithm]]) });
2430
+ const unprotectedHeaders = UnprotectedHeaders$1.create({ unprotectedHeaders: new Map([[RegisteredCwtHeaderClaimKey$1.X5Chain, options.certificates.length === 1 ? options.certificates[0] : options.certificates]]) });
2431
+ if (options.signingKey.keyId) unprotectedHeaders.headers?.set(RegisteredCwtHeaderClaimKey$1.KeyId, options.signingKey.keyId);
3258
2432
  const issuerAuth = await IssuerAuth.create({
3259
2433
  payload: mso,
3260
2434
  unprotectedHeaders,
3261
- protectedHeaders,
2435
+ protectedHeaders
2436
+ }).sign({
3262
2437
  signingKey: options.signingKey,
3263
2438
  algorithm: options.algorithm
3264
- }, this.ctx);
2439
+ }, { sign: this.ctx.cose.sign1.sign });
3265
2440
  return IssuerSigned.create({
3266
2441
  issuerNamespaces: this.namespaces,
3267
2442
  issuerAuth
@@ -3305,7 +2480,7 @@ var Issuer = class {
3305
2480
  return this;
3306
2481
  }
3307
2482
  async sign(options) {
3308
- const signingKey = options.signingKey instanceof CoseKey ? options.signingKey : CoseKey.fromJwk(options.signingKey);
2483
+ const signingKey = options.signingKey instanceof CoseKey$1 ? options.signingKey : CoseKey$1.fromJwk(options.signingKey);
3309
2484
  return await this.isb.sign({
3310
2485
  ...options,
3311
2486
  signingKey
@@ -3320,6 +2495,6 @@ var Verifier = class {
3320
2495
  }
3321
2496
  };
3322
2497
  //#endregion
3323
- export { AtLeastOneCertificateRequiredError, BleOptions, CoseCertificateNotFoundError, CoseDNotDefinedError, CoseEphemeralMacKeyIsRequiredError, CoseInvalidAlgorithmError, CoseInvalidKtyForRawError, CoseInvalidSignatureError, CoseInvalidTypeForKeyError, CoseInvalidValueForKtyError, CoseKNotDefinedError, CoseKey, CoseKeyParameter, CoseKeyTypeNotSupportedForPrivateKeyExtractionError, CosePayloadInvalidStructureError, CosePayloadMustBeDefinedError, CosePayloadMustBeNullError, CoseUnsupportedMacError, CoseXNotDefinedError, CoseYNotDefinedError, Curve, DataItem, DateOnly, DeviceAuth, DeviceAuthentication, DeviceEngagement, DeviceKey, DeviceKeyInfo, DeviceMac, DeviceNamespaces, DeviceRequest, DeviceResponse, DeviceRetrievalMethod, DeviceRetrievalMethodType, DeviceSignature, DeviceSigned, DeviceSignedBuilder, DeviceSignedItems, DocRequest, Document, DocumentError, DuplicateDocumentInDeviceResponseError, DuplicateNamespaceInIssuerNamespacesError, EDeviceKey, EReaderKey, EitherSignatureOrMacMustBeProvidedError, EncryptionAlgorithm, ErrorItems, Errors, Header, Holder, Issuer, IssuerAuth, IssuerNamespaces, IssuerSigned, IssuerSignedBuilder, IssuerSignedItem, ItemsRequest, KeyAuthorizations, KeyInfo, KeyOps, KeyType, Mac0, MacAlgorithm, MdlError, MdlParseError, MobileSecurityObject, NfcHandover, NfcOptions, Oidc, PresentationDefinitionOrDocRequestsAreRequiredError, ProtectedHeaders, ProtocolInfo, QrHandover, ReaderAuth, Security, ServerRetrievalMethod, SessionTranscript, SessionTranscriptOrSessionTranscriptBytesAreRequiredError, Sign1, SignatureAlgorithm, SignatureAlgorithmDoesNotMatchSigningKeyAlgorithmError, TypedMap, UnprotectedHeaders, ValidityInfo, ValueDigests, Verifier, WebApi, WifiOptions, base64, base64url, bytesToString, cborDecode, cborEncode, compareBytes, concatBytes, coseKeyToJwk, coseOptionsJwkMap, defaultVerificationCallback, deviceSignedItemsSchema, errorItemsSchema, hex, issuerNamespacesDecodedSchema, issuerNamespacesEncodedSchema, issuerSignedItemSchema, jwkCoseOptionsMap, jwkToCoseKey, limitDisclosureToDeviceRequestNameSpaces, onCategoryCheck, protectedHeadersDecodedStructure, protectedHeadersEncodedStructure, sessionTranscriptEncodedSchema, stringToBytes, typedMap, unprotectedHeadersStructure };
2498
+ export { AtLeastOneCertificateRequiredError, BleOptions, CoseKey, Curve, DateOnly, DeviceAuth, DeviceAuthentication, DeviceEngagement, DeviceKey, DeviceKeyInfo, DeviceMac, DeviceNamespaces, DeviceRequest, DeviceResponse, DeviceRetrievalMethod, DeviceRetrievalMethodType, DeviceSignature, DeviceSigned, DeviceSignedBuilder, DeviceSignedItems, DocRequest, Document, DocumentError, DuplicateDocumentInDeviceResponseError, DuplicateNamespaceInIssuerNamespacesError, EDeviceKey, EReaderKey, EitherSignatureOrMacMustBeProvidedError, ErrorItems, Errors, Holder, Issuer, IssuerAuth, IssuerNamespaces, IssuerSigned, IssuerSignedBuilder, IssuerSignedItem, ItemsRequest, KeyAuthorizations, KeyInfo, KeyOps, KeyType, Mac0, MdlError, MdlParseError, MobileSecurityObject, NfcHandover, NfcOptions, Oidc, PresentationDefinitionOrDocRequestsAreRequiredError, ProtectedHeaders, ProtocolInfo, QrHandover, ReaderAuth, RegisteredCwtClaimKey, RegisteredCwtHeaderClaimKey, Security, ServerRetrievalMethod, SessionTranscript, SessionTranscriptOrSessionTranscriptBytesAreRequiredError, Sign1, SignatureAlgorithm, SignatureAlgorithmDoesNotMatchSigningKeyAlgorithmError, TypedMap, UnprotectedHeaders, ValidityInfo, ValueDigests, Verifier, WebApi, WifiOptions, base64, base64url, bytesToString, cborDecode, cborEncode, compareBytes, concatBytes, defaultVerificationCallback, deviceSignedItemsSchema, errorItemsSchema, hex, issuerNamespacesDecodedSchema, issuerNamespacesEncodedSchema, issuerSignedItemSchema, limitDisclosureToDeviceRequestNameSpaces, onCategoryCheck, sessionTranscriptEncodedSchema, stringToBytes, typedMap };
3324
2499
 
3325
2500
  //# sourceMappingURL=index.mjs.map