@openeudi/openid4vp 0.2.1 → 0.4.0

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.js CHANGED
@@ -1,9 +1,33 @@
1
- import { splitSdJwt, decodeSdJwt, getClaims } from '@sd-jwt/decode';
2
- import { decodeProtectedHeader, importX509, jwtVerify, importJWK } from 'jose';
3
- import { decode } from 'cbor-x';
4
1
  import { v4 } from 'uuid';
2
+ import { Encoder, Tag } from 'cbor-x';
3
+ import { importX509, decodeProtectedHeader, jwtVerify, importJWK } from 'jose';
4
+ import { splitSdJwt, decodeSdJwt, getClaims } from '@sd-jwt/decode';
5
+ import { matchQuery, buildSubmission } from '@openeudi/dcql';
6
+ export { DcqlMatchError, DcqlValidationError } from '@openeudi/dcql';
5
7
 
6
- // src/parsers/sd-jwt.parser.ts
8
+ // src/authorization.ts
9
+ function createAuthorizationRequest(input, query) {
10
+ if (!input.clientId) throw new TypeError("clientId is required");
11
+ if (!input.nonce) throw new TypeError("nonce is required");
12
+ if (!input.responseUri) throw new TypeError("responseUri is required");
13
+ const state = input.state ?? v4();
14
+ const responseMode = input.responseMode ?? "direct_post";
15
+ const params = new URLSearchParams({
16
+ response_type: "vp_token",
17
+ response_mode: responseMode,
18
+ response_uri: input.responseUri,
19
+ client_id: input.clientId,
20
+ nonce: input.nonce,
21
+ state,
22
+ dcql_query: JSON.stringify(query)
23
+ });
24
+ return {
25
+ uri: `openid4vp://authorize?${params.toString()}`,
26
+ dcqlQuery: query,
27
+ nonce: input.nonce,
28
+ state
29
+ };
30
+ }
7
31
 
8
32
  // src/errors.ts
9
33
  var InvalidSignatureError = class extends Error {
@@ -41,12 +65,619 @@ var NonceValidationError = class extends Error {
41
65
  Object.setPrototypeOf(this, new.target.prototype);
42
66
  }
43
67
  };
68
+ var HaipValidationError = class extends Error {
69
+ code;
70
+ credentialId;
71
+ constructor(code, message, credentialId) {
72
+ super(message);
73
+ this.name = "HaipValidationError";
74
+ this.code = code;
75
+ this.credentialId = credentialId;
76
+ Object.setPrototypeOf(this, new.target.prototype);
77
+ }
78
+ };
44
79
 
45
- // src/parsers/sd-jwt.parser.ts
80
+ // src/haip.ts
81
+ var HAIP_DOCTYPE_NAMESPACES = {
82
+ "org.iso.18013.5.1.mDL": "org.iso.18013.5.1",
83
+ "eu.europa.ec.eudi.pid.1": "eu.europa.ec.eudi.pid.1"
84
+ };
85
+ function buildHaipQuery(input) {
86
+ if (input.claims.length === 0) {
87
+ throw new HaipValidationError(
88
+ "NO_CLAIMS",
89
+ `credential '${input.credentialId}' must declare at least one claim`,
90
+ input.credentialId
91
+ );
92
+ }
93
+ let meta;
94
+ let claims;
95
+ if (input.format === "dc+sd-jwt") {
96
+ if (!input.vctValues || input.vctValues.length === 0) {
97
+ throw new HaipValidationError(
98
+ "MISSING_SDJWT_META",
99
+ `credential '${input.credentialId}' with format 'dc+sd-jwt' must provide non-empty vctValues`,
100
+ input.credentialId
101
+ );
102
+ }
103
+ meta = { vct_values: input.vctValues };
104
+ claims = input.claims.map((c) => ({ path: [c] }));
105
+ } else {
106
+ if (!input.doctypeValue) {
107
+ throw new HaipValidationError(
108
+ "MISSING_MDOC_META",
109
+ `credential '${input.credentialId}' with format 'mso_mdoc' must provide doctypeValue`,
110
+ input.credentialId
111
+ );
112
+ }
113
+ meta = { doctype_value: input.doctypeValue };
114
+ const namespace = HAIP_DOCTYPE_NAMESPACES[input.doctypeValue] ?? input.doctypeValue;
115
+ claims = input.claims.map((c) => ({ path: [namespace, c] }));
116
+ }
117
+ const credential = {
118
+ id: input.credentialId,
119
+ format: input.format,
120
+ meta,
121
+ claims
122
+ };
123
+ if (input.trustedAuthorities && input.trustedAuthorities.length > 0) {
124
+ credential.trusted_authorities = input.trustedAuthorities;
125
+ }
126
+ return { credentials: [credential] };
127
+ }
128
+ var HAIP_FORMATS = /* @__PURE__ */ new Set(["dc+sd-jwt", "mso_mdoc"]);
129
+ function validateHaipQuery(query) {
130
+ if (!query.credentials || query.credentials.length === 0) {
131
+ throw new HaipValidationError(
132
+ "EMPTY_QUERY",
133
+ "query.credentials must have at least one entry"
134
+ );
135
+ }
136
+ if (query.credential_sets !== void 0) {
137
+ throw new HaipValidationError(
138
+ "CREDENTIAL_SETS_DISALLOWED",
139
+ "credential_sets are not permitted in HAIP-minimal"
140
+ );
141
+ }
142
+ for (const credential of query.credentials) {
143
+ if (!HAIP_FORMATS.has(credential.format)) {
144
+ throw new HaipValidationError(
145
+ "UNSUPPORTED_FORMAT",
146
+ `credential '${credential.id}' uses unsupported format '${credential.format}' (allowed: dc+sd-jwt, mso_mdoc)`,
147
+ credential.id
148
+ );
149
+ }
150
+ if (credential.format === "dc+sd-jwt") {
151
+ const vctValues = credential.meta?.vct_values;
152
+ if (!vctValues || vctValues.length === 0) {
153
+ throw new HaipValidationError(
154
+ "MISSING_SDJWT_META",
155
+ `credential '${credential.id}' with format 'dc+sd-jwt' must set meta.vct_values`,
156
+ credential.id
157
+ );
158
+ }
159
+ }
160
+ if (credential.format === "mso_mdoc") {
161
+ if (typeof credential.meta?.doctype_value !== "string") {
162
+ throw new HaipValidationError(
163
+ "MISSING_MDOC_META",
164
+ `credential '${credential.id}' with format 'mso_mdoc' must set meta.doctype_value`,
165
+ credential.id
166
+ );
167
+ }
168
+ }
169
+ if (!credential.claims || credential.claims.length === 0) {
170
+ throw new HaipValidationError(
171
+ "NO_CLAIMS",
172
+ `credential '${credential.id}' must declare at least one claim`,
173
+ credential.id
174
+ );
175
+ }
176
+ if (credential.claim_sets !== void 0) {
177
+ throw new HaipValidationError(
178
+ "CLAIM_SETS_DISALLOWED",
179
+ `credential '${credential.id}' uses claim_sets, not permitted in HAIP-minimal`,
180
+ credential.id
181
+ );
182
+ }
183
+ }
184
+ }
185
+ function isHaipQuery(query) {
186
+ try {
187
+ validateHaipQuery(query);
188
+ return true;
189
+ } catch {
190
+ return false;
191
+ }
192
+ }
193
+ var decoder = new Encoder({ mapsAsObjects: false, useRecords: false });
194
+ var HEADER_ALG = 1;
195
+ var HEADER_X5CHAIN = 33;
196
+ var COSE_ALG_TO_NAME = {
197
+ [-7]: "ES256",
198
+ [-35]: "ES384",
199
+ [-36]: "ES512"
200
+ };
201
+ function decodeCoseSign1(bytes) {
202
+ let outer = decoder.decode(bytes);
203
+ if (outer instanceof Tag && outer.tag === 18) {
204
+ const tagValue = outer.value;
205
+ outer = tagValue instanceof Uint8Array ? decoder.decode(tagValue) : tagValue;
206
+ }
207
+ if (!Array.isArray(outer) || outer.length !== 4) {
208
+ throw new MalformedCredentialError("COSE_Sign1 must be a CBOR array of length 4");
209
+ }
210
+ const [protectedHeaderBytes, unprotectedHeader, payloadRaw, signature] = outer;
211
+ if (!(protectedHeaderBytes instanceof Uint8Array)) {
212
+ throw new MalformedCredentialError("COSE_Sign1 protected header must be a bstr");
213
+ }
214
+ if (!(unprotectedHeader instanceof Map)) {
215
+ throw new MalformedCredentialError("COSE_Sign1 unprotected header must be a Map");
216
+ }
217
+ if (!(signature instanceof Uint8Array)) {
218
+ throw new MalformedCredentialError("COSE_Sign1 signature must be a bstr");
219
+ }
220
+ let protectedHeader;
221
+ try {
222
+ const decoded = decoder.decode(protectedHeaderBytes);
223
+ if (!(decoded instanceof Map)) {
224
+ throw new Error("protected header not a Map");
225
+ }
226
+ protectedHeader = decoded;
227
+ } catch {
228
+ throw new MalformedCredentialError("COSE_Sign1 protected header is not decodable CBOR");
229
+ }
230
+ const algLabel = protectedHeader.get(HEADER_ALG);
231
+ const alg = typeof algLabel === "number" ? COSE_ALG_TO_NAME[algLabel] : void 0;
232
+ if (!alg) {
233
+ throw new MalformedCredentialError(`COSE_Sign1 uses unknown alg label: ${String(algLabel)}`);
234
+ }
235
+ let payload;
236
+ if (payloadRaw instanceof Uint8Array) {
237
+ payload = payloadRaw;
238
+ } else if (payloadRaw instanceof Tag && payloadRaw.tag === 24 && payloadRaw.value instanceof Uint8Array) {
239
+ payload = payloadRaw.value;
240
+ } else {
241
+ throw new MalformedCredentialError("COSE_Sign1 payload must be a byte string");
242
+ }
243
+ const x5raw = unprotectedHeader.get(HEADER_X5CHAIN);
244
+ let x5chain;
245
+ if (x5raw === void 0) {
246
+ throw new MalformedCredentialError("COSE_Sign1 missing x5chain in unprotected header (label 33)");
247
+ }
248
+ if (x5raw instanceof Uint8Array) {
249
+ x5chain = [x5raw];
250
+ } else if (Array.isArray(x5raw) && x5raw.every((v) => v instanceof Uint8Array)) {
251
+ x5chain = x5raw;
252
+ } else {
253
+ throw new MalformedCredentialError("COSE_Sign1 x5chain must be a bstr or array of bstr");
254
+ }
255
+ return {
256
+ protectedHeaderBytes,
257
+ protectedHeader,
258
+ unprotectedHeader,
259
+ payload,
260
+ signature,
261
+ x5chain,
262
+ alg
263
+ };
264
+ }
265
+ var ALG_TO_HASH = {
266
+ ES256: "SHA-256",
267
+ ES384: "SHA-384",
268
+ ES512: "SHA-512"
269
+ };
270
+ async function verifyCoseSign1(coseSign1, publicKey, allowedAlgorithms) {
271
+ if (!allowedAlgorithms.includes(coseSign1.alg)) {
272
+ throw new MalformedCredentialError(`COSE_Sign1 algorithm ${coseSign1.alg} not in allowlist`);
273
+ }
274
+ const hashAlg = ALG_TO_HASH[coseSign1.alg];
275
+ if (!hashAlg) {
276
+ throw new MalformedCredentialError(`no hash mapping for alg ${coseSign1.alg}`);
277
+ }
278
+ const sigStructure = ["Signature1", coseSign1.protectedHeaderBytes, new Uint8Array(0), coseSign1.payload];
279
+ const sigInput = decoder.encode(sigStructure);
280
+ const ok = await crypto.subtle.verify(
281
+ { name: "ECDSA", hash: hashAlg },
282
+ publicKey,
283
+ new Uint8Array(coseSign1.signature),
284
+ sigInput
285
+ );
286
+ if (!ok) {
287
+ throw new MalformedCredentialError("COSE_Sign1 signature verification failed");
288
+ }
289
+ }
290
+ var decoder2 = new Encoder({ mapsAsObjects: false, useRecords: false });
291
+ var ALLOWED_HASH_ALGS = /* @__PURE__ */ new Set(["SHA-256", "SHA-384", "SHA-512"]);
292
+ async function computeItemDigest(itemBytes, digestAlgorithm) {
293
+ if (!ALLOWED_HASH_ALGS.has(digestAlgorithm)) {
294
+ throw new MalformedCredentialError(`Unknown digest algorithm: ${digestAlgorithm}`);
295
+ }
296
+ const buf = await crypto.subtle.digest(digestAlgorithm, new Uint8Array(itemBytes));
297
+ return new Uint8Array(buf);
298
+ }
299
+ function bytesEqual(a, b) {
300
+ if (a.length !== b.length) return false;
301
+ for (let i = 0; i < a.length; i++) {
302
+ if (a[i] !== b[i]) return false;
303
+ }
304
+ return true;
305
+ }
306
+ function unwrapItemMap(itemBytes) {
307
+ let decoded;
308
+ try {
309
+ decoded = decoder2.decode(itemBytes);
310
+ } catch {
311
+ throw new MalformedCredentialError("IssuerSignedItem is not decodable CBOR");
312
+ }
313
+ let inner;
314
+ if (decoded instanceof Tag && decoded.tag === 24 && decoded.value instanceof Uint8Array) {
315
+ inner = decoder2.decode(decoded.value);
316
+ } else if (decoded !== null && typeof decoded === "object" && !(decoded instanceof Tag) && !(decoded instanceof Map) && !(decoded instanceof Uint8Array) && "value" in decoded && decoded.value instanceof Uint8Array) {
317
+ inner = decoder2.decode(decoded.value);
318
+ } else if (decoded instanceof Map) {
319
+ inner = decoded;
320
+ } else {
321
+ throw new MalformedCredentialError("IssuerSignedItem must be a tag-24 wrapped CBOR Map");
322
+ }
323
+ if (!(inner instanceof Map)) {
324
+ throw new MalformedCredentialError("IssuerSignedItem must decode to a Map");
325
+ }
326
+ return inner;
327
+ }
328
+ async function verifyAllDigests(nameSpaces, mso) {
329
+ for (const [ns, items] of nameSpaces) {
330
+ const expected = mso.valueDigests.get(ns);
331
+ if (!expected) {
332
+ throw new MalformedCredentialError(`namespace ${ns} has no valueDigests entry in MSO`);
333
+ }
334
+ for (const itemBytes of items) {
335
+ const hash = await computeItemDigest(itemBytes, mso.digestAlgorithm);
336
+ const item = unwrapItemMap(itemBytes);
337
+ const digestID = item.get("digestID");
338
+ if (typeof digestID !== "number") {
339
+ throw new MalformedCredentialError("IssuerSignedItem missing digestID");
340
+ }
341
+ const expectedDigest = expected.get(digestID);
342
+ if (!expectedDigest) {
343
+ throw new MalformedCredentialError(`digestID ${digestID} missing from MSO valueDigests[${ns}]`);
344
+ }
345
+ if (!bytesEqual(hash, expectedDigest)) {
346
+ throw new MalformedCredentialError(`digest mismatch for ns=${ns} digestID=${digestID}`);
347
+ }
348
+ }
349
+ }
350
+ }
351
+ var decoder3 = new Encoder({ mapsAsObjects: false, useRecords: false });
352
+ function decodeDateLike(value) {
353
+ if (value instanceof Date) return value;
354
+ if (value instanceof Tag) {
355
+ if (value.tag === 0 && typeof value.value === "string") {
356
+ return new Date(value.value);
357
+ }
358
+ if (value.tag === 1 && typeof value.value === "number") {
359
+ return new Date(value.value * 1e3);
360
+ }
361
+ if (value.tag === 1004 && typeof value.value === "string") {
362
+ return new Date(value.value);
363
+ }
364
+ }
365
+ if (typeof value === "string") {
366
+ return new Date(value);
367
+ }
368
+ throw new MalformedCredentialError(`unsupported date encoding in MSO: ${typeof value}`);
369
+ }
370
+ function decodeMso(payload) {
371
+ let raw;
372
+ try {
373
+ raw = decoder3.decode(payload);
374
+ if (raw instanceof Tag && raw.tag === 24 && raw.value instanceof Uint8Array) {
375
+ raw = decoder3.decode(raw.value);
376
+ } else if (raw !== null && typeof raw === "object" && !(raw instanceof Tag) && !(raw instanceof Map) && !(raw instanceof Uint8Array) && "value" in raw && raw.value instanceof Uint8Array) {
377
+ raw = decoder3.decode(raw.value);
378
+ }
379
+ } catch (err) {
380
+ if (err instanceof MalformedCredentialError) throw err;
381
+ throw new MalformedCredentialError("MSO payload is not decodable CBOR");
382
+ }
383
+ if (!(raw instanceof Map)) {
384
+ throw new MalformedCredentialError("MSO must be a CBOR Map");
385
+ }
386
+ const m = raw;
387
+ const version = m.get("version");
388
+ if (typeof version !== "string") {
389
+ throw new MalformedCredentialError("MSO.version must be a string");
390
+ }
391
+ const digestAlgorithm = m.get("digestAlgorithm");
392
+ if (typeof digestAlgorithm !== "string") {
393
+ throw new MalformedCredentialError("MSO.digestAlgorithm must be a string");
394
+ }
395
+ const docType = m.get("docType");
396
+ if (typeof docType !== "string") {
397
+ throw new MalformedCredentialError("MSO.docType must be a string");
398
+ }
399
+ const vdRaw = m.get("valueDigests");
400
+ if (!(vdRaw instanceof Map)) {
401
+ throw new MalformedCredentialError("MSO.valueDigests must be a Map");
402
+ }
403
+ const valueDigests = /* @__PURE__ */ new Map();
404
+ for (const [ns, inner] of vdRaw.entries()) {
405
+ if (typeof ns !== "string" || !(inner instanceof Map)) {
406
+ throw new MalformedCredentialError("MSO.valueDigests entry malformed");
407
+ }
408
+ const perNs = /* @__PURE__ */ new Map();
409
+ for (const [id, digest] of inner.entries()) {
410
+ if (typeof id !== "number" || !(digest instanceof Uint8Array)) {
411
+ throw new MalformedCredentialError("MSO digest entry must map number\u2192bstr");
412
+ }
413
+ perNs.set(id, digest);
414
+ }
415
+ valueDigests.set(ns, perNs);
416
+ }
417
+ const viRaw = m.get("validityInfo");
418
+ if (!(viRaw instanceof Map)) {
419
+ throw new MalformedCredentialError("MSO.validityInfo must be a Map");
420
+ }
421
+ const vi = viRaw;
422
+ const validityInfo = {
423
+ signed: decodeDateLike(vi.get("signed")),
424
+ validFrom: decodeDateLike(vi.get("validFrom")),
425
+ validUntil: decodeDateLike(vi.get("validUntil"))
426
+ };
427
+ if (vi.has("expectedUpdate")) {
428
+ validityInfo.expectedUpdate = decodeDateLike(vi.get("expectedUpdate"));
429
+ }
430
+ return { version, digestAlgorithm, valueDigests, docType, validityInfo };
431
+ }
432
+ function validateMsoValidity(mso, now) {
433
+ const { signed, validFrom, validUntil } = mso.validityInfo;
434
+ if (signed.getTime() > now.getTime()) {
435
+ throw new MalformedCredentialError(`MSO signed=${signed.toISOString()} is in the future`);
436
+ }
437
+ if (validFrom.getTime() > now.getTime()) {
438
+ throw new MalformedCredentialError(`MSO validFrom=${validFrom.toISOString()} is in the future`);
439
+ }
440
+ if (validFrom.getTime() > validUntil.getTime()) {
441
+ throw new MalformedCredentialError("MSO validFrom is after validUntil");
442
+ }
443
+ if (signed.getTime() < validFrom.getTime() || signed.getTime() > validUntil.getTime()) {
444
+ throw new MalformedCredentialError("MSO signed is outside the validity window");
445
+ }
446
+ if (validUntil.getTime() < now.getTime()) {
447
+ throw new ExpiredCredentialError(`MSO validUntil=${validUntil.toISOString()} is in the past`);
448
+ }
449
+ }
450
+ function validateMsoDocType(mso, expectedDocType) {
451
+ if (mso.docType !== expectedDocType) {
452
+ throw new MalformedCredentialError(`MSO docType=${mso.docType} does not match expected ${expectedDocType}`);
453
+ }
454
+ }
455
+
456
+ // src/parsers/mdoc.parser.ts
457
+ var decoder4 = new Encoder({ mapsAsObjects: false, useRecords: false });
458
+ var encoder = new Encoder({ mapsAsObjects: false, useRecords: false });
46
459
  var DEFAULT_ALLOWED_ALGORITHMS = ["ES256", "ES384", "ES512"];
460
+ function bytesEqual2(a, b) {
461
+ if (a.length !== b.length) return false;
462
+ for (let i = 0; i < a.length; i++) {
463
+ if (a[i] !== b[i]) return false;
464
+ }
465
+ return true;
466
+ }
467
+ function derToPem(der) {
468
+ let binary = "";
469
+ for (const b of der) binary += String.fromCharCode(b);
470
+ const b64 = globalThis.btoa(binary);
471
+ const lines = b64.match(/.{1,64}/g) || [];
472
+ return `-----BEGIN CERTIFICATE-----
473
+ ${lines.join("\n")}
474
+ -----END CERTIFICATE-----`;
475
+ }
476
+ function extractCountryHintFromCert(_certDer) {
477
+ return "";
478
+ }
479
+ function extractRawItemBytes(item) {
480
+ if (item instanceof Tag && item.tag === 24 && item.value instanceof Uint8Array) {
481
+ return item.value;
482
+ }
483
+ if (item instanceof Uint8Array) {
484
+ return item;
485
+ }
486
+ if (item !== null && typeof item === "object" && !(item instanceof Tag) && !(item instanceof Map) && "value" in item && item.value instanceof Uint8Array) {
487
+ return item.value;
488
+ }
489
+ throw new MalformedCredentialError("IssuerSignedItem must be a tag-24 byte string");
490
+ }
491
+ function mapRawToClaims(nameSpaces) {
492
+ const flat = {};
493
+ const namespaced = {};
494
+ for (const [ns, items] of nameSpaces.entries()) {
495
+ const nsBucket = namespaced[ns] ?? {};
496
+ for (const itemBytes of items) {
497
+ let decoded;
498
+ try {
499
+ decoded = decoder4.decode(itemBytes);
500
+ } catch {
501
+ continue;
502
+ }
503
+ let inner;
504
+ if (decoded instanceof Tag && decoded.tag === 24 && decoded.value instanceof Uint8Array) {
505
+ inner = decoder4.decode(decoded.value);
506
+ } else if (decoded !== null && typeof decoded === "object" && !(decoded instanceof Tag) && !(decoded instanceof Map) && !(decoded instanceof Uint8Array) && "value" in decoded && decoded.value instanceof Uint8Array) {
507
+ inner = decoder4.decode(decoded.value);
508
+ } else if (decoded instanceof Map) {
509
+ inner = decoded;
510
+ } else {
511
+ continue;
512
+ }
513
+ if (inner instanceof Map) {
514
+ const id = inner.get("elementIdentifier");
515
+ const val = inner.get("elementValue");
516
+ if (typeof id === "string") {
517
+ flat[id] = val;
518
+ nsBucket[id] = val;
519
+ }
520
+ }
521
+ }
522
+ namespaced[ns] = nsBucket;
523
+ }
524
+ return { flat, namespaced };
525
+ }
526
+ var MdocParser = class {
527
+ format = "mdoc";
528
+ /**
529
+ * Returns true when the token is binary data (Uint8Array or Buffer),
530
+ * indicating a CBOR-encoded mDOC DeviceResponse.
531
+ * Buffer extends Uint8Array, so `instanceof Uint8Array` catches both.
532
+ */
533
+ canParse(vpToken) {
534
+ return vpToken instanceof Uint8Array;
535
+ }
536
+ /**
537
+ * Parses and validates an mDOC DeviceResponse token.
538
+ *
539
+ * @throws {MalformedCredentialError} when the CBOR structure cannot be decoded
540
+ * or does not match the expected DeviceResponse format
541
+ */
542
+ async parse(vpToken, options) {
543
+ if (!(vpToken instanceof Uint8Array)) {
544
+ throw new MalformedCredentialError("mDOC vpToken must be a Uint8Array");
545
+ }
546
+ const allowedAlgorithms = options.allowedAlgorithms ?? DEFAULT_ALLOWED_ALGORITHMS;
547
+ let deviceResponse;
548
+ try {
549
+ const decoded = decoder4.decode(vpToken);
550
+ if (!(decoded instanceof Map)) throw new Error();
551
+ deviceResponse = decoded;
552
+ } catch {
553
+ throw new MalformedCredentialError("vpToken is not a CBOR DeviceResponse Map");
554
+ }
555
+ const docs = deviceResponse.get("documents");
556
+ if (!Array.isArray(docs) || docs.length === 0) {
557
+ throw new MalformedCredentialError("DeviceResponse has no documents");
558
+ }
559
+ const document = docs[0];
560
+ if (!(document instanceof Map)) {
561
+ throw new MalformedCredentialError("document must be a Map");
562
+ }
563
+ const issuerSigned = document.get("issuerSigned");
564
+ if (!(issuerSigned instanceof Map)) {
565
+ throw new MalformedCredentialError("document.issuerSigned must be a Map");
566
+ }
567
+ const issuerAuth = issuerSigned.get("issuerAuth");
568
+ if (!Array.isArray(issuerAuth)) {
569
+ throw new MalformedCredentialError("issuerAuth must be a COSE_Sign1 array");
570
+ }
571
+ const issuerAuthBytes = encoder.encode(issuerAuth);
572
+ const cose = decodeCoseSign1(issuerAuthBytes);
573
+ if (!allowedAlgorithms.includes(cose.alg)) {
574
+ return {
575
+ valid: false,
576
+ format: this.format,
577
+ claims: {},
578
+ issuer: { certificate: new Uint8Array(), country: "" },
579
+ error: `Unsupported algorithm: ${cose.alg}`
580
+ };
581
+ }
582
+ const issuerCertBytes = cose.x5chain[0];
583
+ if (!issuerCertBytes) {
584
+ throw new MalformedCredentialError("Missing issuer certificate in x5chain");
585
+ }
586
+ if (options.trustedCertificates.length === 0) {
587
+ if (options.skipTrustCheck !== true) {
588
+ throw new MalformedCredentialError(
589
+ "trustedCertificates must not be empty unless skipTrustCheck is true"
590
+ );
591
+ }
592
+ } else {
593
+ const trusted = options.trustedCertificates.some((t) => bytesEqual2(t, issuerCertBytes));
594
+ if (!trusted) {
595
+ return {
596
+ valid: false,
597
+ format: this.format,
598
+ claims: {},
599
+ issuer: { certificate: issuerCertBytes, country: "" },
600
+ error: "Issuer certificate is not trusted"
601
+ };
602
+ }
603
+ }
604
+ const publicKey = await importX509(derToPem(issuerCertBytes), cose.alg);
605
+ try {
606
+ await verifyCoseSign1(cose, publicKey, allowedAlgorithms);
607
+ } catch (err) {
608
+ if (err instanceof MalformedCredentialError) {
609
+ return {
610
+ valid: false,
611
+ format: this.format,
612
+ claims: {},
613
+ issuer: { certificate: issuerCertBytes, country: "" },
614
+ error: err.message
615
+ };
616
+ }
617
+ throw err;
618
+ }
619
+ const mso = decodeMso(cose.payload);
620
+ try {
621
+ validateMsoValidity(mso, /* @__PURE__ */ new Date());
622
+ } catch (err) {
623
+ if (err instanceof ExpiredCredentialError) {
624
+ return {
625
+ valid: false,
626
+ format: this.format,
627
+ claims: {},
628
+ issuer: { certificate: issuerCertBytes, country: "" },
629
+ error: "Credential expired"
630
+ };
631
+ }
632
+ throw err;
633
+ }
634
+ if (options.expectedDocType !== void 0) {
635
+ try {
636
+ validateMsoDocType(mso, options.expectedDocType);
637
+ } catch (err) {
638
+ if (err instanceof MalformedCredentialError) {
639
+ return {
640
+ valid: false,
641
+ format: this.format,
642
+ claims: {},
643
+ issuer: { certificate: issuerCertBytes, country: "" },
644
+ error: err.message
645
+ };
646
+ }
647
+ throw err;
648
+ }
649
+ }
650
+ const nsRaw = issuerSigned.get("nameSpaces");
651
+ if (!(nsRaw instanceof Map)) {
652
+ throw new MalformedCredentialError("issuerSigned.nameSpaces must be a Map");
653
+ }
654
+ const nameSpaces = /* @__PURE__ */ new Map();
655
+ for (const [ns, items] of nsRaw.entries()) {
656
+ if (typeof ns !== "string" || !Array.isArray(items)) {
657
+ throw new MalformedCredentialError("nameSpaces entry malformed");
658
+ }
659
+ nameSpaces.set(ns, items.map(extractRawItemBytes));
660
+ }
661
+ await verifyAllDigests(nameSpaces, mso);
662
+ const { flat: claims, namespaced: namespacedClaims } = mapRawToClaims(nameSpaces);
663
+ const issuer = {
664
+ certificate: issuerCertBytes,
665
+ country: extractCountryHintFromCert()
666
+ };
667
+ return {
668
+ valid: true,
669
+ format: this.format,
670
+ claims,
671
+ issuer,
672
+ docType: mso.docType,
673
+ namespacedClaims
674
+ };
675
+ }
676
+ };
677
+ var DEFAULT_ALLOWED_ALGORITHMS2 = ["ES256", "ES384", "ES512"];
47
678
  var sha256Hasher = async (data, _alg) => {
48
- const encoder = new TextEncoder();
49
- const input = typeof data === "string" ? encoder.encode(data) : data;
679
+ const encoder2 = new TextEncoder();
680
+ const input = typeof data === "string" ? encoder2.encode(data) : data;
50
681
  const hashBuffer = await crypto.subtle.digest("SHA-256", input);
51
682
  return new Uint8Array(hashBuffer);
52
683
  };
@@ -68,14 +699,14 @@ function base64ToBytes(base64) {
68
699
  }
69
700
  return bytes;
70
701
  }
71
- function bytesEqual(a, b) {
702
+ function bytesEqual3(a, b) {
72
703
  if (a.length !== b.length) return false;
73
704
  for (let i = 0; i < a.length; i++) {
74
705
  if (a[i] !== b[i]) return false;
75
706
  }
76
707
  return true;
77
708
  }
78
- function derToPem(base64Der) {
709
+ function derToPem2(base64Der) {
79
710
  const lines = base64Der.match(/.{1,64}/g) || [];
80
711
  return `-----BEGIN CERTIFICATE-----
81
712
  ${lines.join("\n")}
@@ -132,7 +763,7 @@ var SdJwtParser = class {
132
763
  if (typeof vpToken !== "string") {
133
764
  throw new MalformedCredentialError("VP token must be a string");
134
765
  }
135
- const allowedAlgorithms = options.allowedAlgorithms ?? DEFAULT_ALLOWED_ALGORITHMS;
766
+ const allowedAlgorithms = options.allowedAlgorithms ?? DEFAULT_ALLOWED_ALGORITHMS2;
136
767
  const invalidResult = (error) => ({
137
768
  valid: false,
138
769
  format: this.format,
@@ -163,7 +794,7 @@ var SdJwtParser = class {
163
794
  let issuerKey;
164
795
  let issuerCertBytes;
165
796
  try {
166
- issuerKey = await importX509(derToPem(x5cArray[0]), alg);
797
+ issuerKey = await importX509(derToPem2(x5cArray[0]), alg);
167
798
  issuerCertBytes = base64ToBytes(x5cArray[0]);
168
799
  } catch (err) {
169
800
  if (err instanceof MalformedCredentialError) throw err;
@@ -188,7 +819,7 @@ var SdJwtParser = class {
188
819
  );
189
820
  }
190
821
  } else {
191
- const isTrusted = options.trustedCertificates.some((trusted) => bytesEqual(trusted, issuerCertBytes));
822
+ const isTrusted = options.trustedCertificates.some((trusted) => bytesEqual3(trusted, issuerCertBytes));
192
823
  if (!isTrusted) {
193
824
  return invalidResult("Issuer certificate is not trusted");
194
825
  }
@@ -255,226 +886,16 @@ var SdJwtParser = class {
255
886
  } catch {
256
887
  throw new MalformedCredentialError("Failed to decode SD-JWT disclosures");
257
888
  }
889
+ const vct = typeof payload["vct"] === "string" ? payload["vct"] : void 0;
258
890
  return {
259
891
  valid: true,
260
892
  format: this.format,
261
893
  claims: mapToCredentialClaims(resolvedClaims),
262
- issuer: issuerInfo
263
- };
264
- }
265
- };
266
- function isBinaryData(value) {
267
- return value instanceof Uint8Array;
268
- }
269
- function bytesEqual2(a, b) {
270
- if (a.length !== b.length) return false;
271
- for (let i = 0; i < a.length; i++) {
272
- if (a[i] !== b[i]) return false;
273
- }
274
- return true;
275
- }
276
- function extractCertificateFromIssuerAuth(issuerAuth) {
277
- const unprotected = issuerAuth[1];
278
- if (unprotected && typeof unprotected === "object") {
279
- const certFromUnprotected = extractX5Chain(unprotected);
280
- if (certFromUnprotected) return certFromUnprotected;
281
- }
282
- const protectedHeader = issuerAuth[0];
283
- if (isBinaryData(protectedHeader)) {
284
- try {
285
- const decoded = decode(protectedHeader);
286
- if (decoded && typeof decoded === "object") {
287
- const certFromProtected = extractX5Chain(decoded);
288
- if (certFromProtected) return certFromProtected;
289
- }
290
- } catch {
291
- }
292
- return new Uint8Array(protectedHeader);
293
- }
294
- return new Uint8Array();
295
- }
296
- function extractX5Chain(header) {
297
- if (header instanceof Map) {
298
- const cert = header.get(33);
299
- if (isBinaryData(cert)) {
300
- return new Uint8Array(cert);
301
- }
302
- } else if (typeof header === "object" && header !== null) {
303
- const rec = header;
304
- const cert = rec[33] ?? rec["x5chain"] ?? rec["33"];
305
- if (isBinaryData(cert)) {
306
- return new Uint8Array(cert);
307
- }
308
- }
309
- return null;
310
- }
311
- function mapToCredentialClaims2(items) {
312
- const claims = {};
313
- for (const item of items) {
314
- const key = item.elementIdentifier;
315
- const value = item.elementValue;
316
- switch (key) {
317
- case "age_over_18":
318
- if (typeof value === "boolean") claims.age_over_18 = value;
319
- break;
320
- case "age_over_21":
321
- if (typeof value === "boolean") claims.age_over_21 = value;
322
- break;
323
- case "resident_country":
324
- if (typeof value === "string") claims.resident_country = value;
325
- break;
326
- case "nationality":
327
- if (typeof value === "string") claims.nationality = value;
328
- break;
329
- case "family_name_birth":
330
- if (typeof value === "string") claims.family_name_birth = value;
331
- break;
332
- default:
333
- claims[key] = value;
334
- break;
335
- }
336
- }
337
- return claims;
338
- }
339
- function extractValidityPeriod(issuerAuth) {
340
- const payload = issuerAuth[2];
341
- if (!payload) return {};
342
- try {
343
- const decoded = isBinaryData(payload) ? decode(payload) : payload;
344
- if (decoded && typeof decoded === "object") {
345
- const obj = decoded;
346
- const validityInfo = obj["validityInfo"];
347
- if (validityInfo) {
348
- return {
349
- validFrom: validityInfo["validFrom"] instanceof Date ? validityInfo["validFrom"] : typeof validityInfo["validFrom"] === "string" ? new Date(validityInfo["validFrom"]) : void 0,
350
- validUntil: validityInfo["validUntil"] instanceof Date ? validityInfo["validUntil"] : typeof validityInfo["validUntil"] === "string" ? new Date(validityInfo["validUntil"]) : void 0
351
- };
352
- }
353
- }
354
- } catch {
355
- }
356
- return {};
357
- }
358
- var MdocParser = class {
359
- format = "mdoc";
360
- /**
361
- * Returns true when the token is binary data (Uint8Array or Buffer),
362
- * indicating a CBOR-encoded mDOC DeviceResponse.
363
- */
364
- canParse(vpToken) {
365
- return isBinaryData(vpToken);
366
- }
367
- /**
368
- * Parses and validates an mDOC DeviceResponse token.
369
- *
370
- * @throws {MalformedCredentialError} when the CBOR structure cannot be decoded
371
- * or does not match the expected DeviceResponse format
372
- */
373
- async parse(vpToken, options) {
374
- if (!isBinaryData(vpToken)) {
375
- throw new MalformedCredentialError("VP token must be a Uint8Array or Buffer");
376
- }
377
- const invalidResult = (error) => ({
378
- valid: false,
379
- format: this.format,
380
- claims: {},
381
- issuer: { certificate: new Uint8Array(), country: "" },
382
- error
383
- });
384
- let deviceResponse;
385
- try {
386
- deviceResponse = decode(vpToken);
387
- } catch {
388
- throw new MalformedCredentialError("Failed to decode CBOR DeviceResponse");
389
- }
390
- if (!deviceResponse || typeof deviceResponse !== "object" || !Array.isArray(deviceResponse.documents) || deviceResponse.documents.length === 0) {
391
- throw new MalformedCredentialError("Invalid DeviceResponse structure: missing or empty documents array");
392
- }
393
- const document = deviceResponse.documents[0];
394
- if (!document.issuerSigned || !document.issuerSigned.nameSpaces || !document.issuerSigned.issuerAuth) {
395
- throw new MalformedCredentialError("Invalid mDOC document: missing issuerSigned data");
396
- }
397
- const issuerAuth = document.issuerSigned.issuerAuth;
398
- if (!Array.isArray(issuerAuth) || issuerAuth.length < 4) {
399
- throw new MalformedCredentialError("Invalid issuerAuth: expected COSE_Sign1 array with 4 elements");
400
- }
401
- const issuerCertBytes = extractCertificateFromIssuerAuth(issuerAuth);
402
- const issuerInfo = {
403
- certificate: issuerCertBytes,
404
- country: ""
405
- };
406
- if (options.trustedCertificates.length === 0) {
407
- if (options.skipTrustCheck !== true) {
408
- throw new MalformedCredentialError(
409
- "trustedCertificates must not be empty unless skipTrustCheck is true"
410
- );
411
- }
412
- } else {
413
- const isTrusted = options.trustedCertificates.some((trusted) => bytesEqual2(trusted, issuerCertBytes));
414
- if (!isTrusted) {
415
- return invalidResult("Issuer certificate is not trusted");
416
- }
417
- }
418
- const { validUntil } = extractValidityPeriod(issuerAuth);
419
- if (validUntil) {
420
- const now = /* @__PURE__ */ new Date();
421
- if (validUntil < now) {
422
- return invalidResult("Credential has expired");
423
- }
424
- }
425
- const pidNamespace = "eu.europa.ec.eudi.pid.1";
426
- const nameSpaces = document.issuerSigned.nameSpaces;
427
- const items = nameSpaces[pidNamespace] ?? nameSpaces[document.docType] ?? Object.values(nameSpaces)[0] ?? [];
428
- const claims = mapToCredentialClaims2(items);
429
- if (claims.resident_country && typeof claims.resident_country === "string") {
430
- issuerInfo.country = claims.resident_country;
431
- }
432
- return {
433
- valid: true,
434
- format: this.format,
435
- claims,
436
- issuer: issuerInfo
894
+ issuer: issuerInfo,
895
+ ...vct !== void 0 ? { vct } : {}
437
896
  };
438
897
  }
439
898
  };
440
- function createAuthorizationRequest(input) {
441
- const state = input.state ?? v4();
442
- const presentationDefinition = {
443
- id: v4(),
444
- input_descriptors: input.requestedAttributes.map((attr, index) => ({
445
- id: `descriptor_${index}`,
446
- format: Object.fromEntries(
447
- input.acceptedFormats.map((fmt) => {
448
- if (fmt === "sd-jwt-vc") return ["vc+sd-jwt", { "sd-jwt_alg_values": ["ES256"] }];
449
- return ["mso_mdoc", { alg: ["ES256"] }];
450
- })
451
- ),
452
- constraints: {
453
- fields: [
454
- {
455
- path: [`$.${attr}`, `$['${attr}']`],
456
- filter: { type: attr.startsWith("age_over") ? "boolean" : "string" }
457
- }
458
- ]
459
- }
460
- }))
461
- };
462
- const params = new URLSearchParams({
463
- response_type: "vp_token",
464
- response_mode: "direct_post",
465
- response_uri: input.responseUri,
466
- client_id: input.clientId,
467
- nonce: input.nonce,
468
- state,
469
- presentation_definition: JSON.stringify(presentationDefinition)
470
- });
471
- return {
472
- uri: `openid4vp://authorize?${params.toString()}`,
473
- presentationDefinition,
474
- nonce: input.nonce,
475
- state
476
- };
477
- }
478
899
 
479
900
  // src/presentation.ts
480
901
  var parsers = [new SdJwtParser(), new MdocParser()];
@@ -492,10 +913,69 @@ async function parsePresentation(vpToken, options) {
492
913
  error: "Unsupported credential format"
493
914
  };
494
915
  }
916
+ var INTERNAL_TO_DCQL_FORMAT = {
917
+ "sd-jwt-vc": "dc+sd-jwt",
918
+ mdoc: "mso_mdoc"
919
+ };
920
+ function classifyMismatch(query, decoded, hasDetail) {
921
+ if (decoded.format !== query.format) return "format_mismatch";
922
+ if (query.format === "dc+sd-jwt") {
923
+ const allowed = query.meta?.vct_values;
924
+ if (allowed && allowed.length > 0 && !allowed.includes(decoded.vct ?? "")) {
925
+ return "vct_mismatch";
926
+ }
927
+ }
928
+ if (query.format === "mso_mdoc") {
929
+ const expected = query.meta?.doctype_value;
930
+ if (expected && expected !== decoded.doctype) return "doctype_mismatch";
931
+ }
932
+ if (query.trusted_authorities && query.trusted_authorities.length > 0) {
933
+ const decodedAuthIds = decoded.trusted_authority_ids ?? [];
934
+ const anyMatch = query.trusted_authorities.some(
935
+ (ta) => ta.values.some((v) => decodedAuthIds.includes(v))
936
+ );
937
+ if (!anyMatch) return "trusted_authority_mismatch";
938
+ }
939
+ if (hasDetail) return "missing_claims";
940
+ return "no_credential_found";
941
+ }
942
+ function refineUnmatched(query, decoded, match) {
943
+ if (match.unmatched.length === 0) return match;
944
+ const refined = match.unmatched.map((entry) => {
945
+ const credentialQuery = query.credentials.find((c) => c.id === entry.queryId);
946
+ if (!credentialQuery) return entry;
947
+ const specific = classifyMismatch(credentialQuery, decoded, entry.detail !== void 0);
948
+ return { ...entry, reason: specific };
949
+ });
950
+ return { ...match, unmatched: refined };
951
+ }
952
+ async function verifyPresentation(vpToken, query, options) {
953
+ const parsed = await parsePresentation(vpToken, options);
954
+ const dcqlFormat = INTERNAL_TO_DCQL_FORMAT[parsed.format] ?? parsed.format;
955
+ const decodedClaims = parsed.format === "mdoc" && parsed.namespacedClaims !== void 0 ? parsed.namespacedClaims : parsed.claims;
956
+ const decoded = {
957
+ id: query.credentials[0]?.id ?? "presented",
958
+ format: dcqlFormat,
959
+ claims: decodedClaims
960
+ };
961
+ if (parsed.format === "sd-jwt-vc" && typeof parsed.vct === "string") {
962
+ decoded.vct = parsed.vct;
963
+ }
964
+ if (parsed.format === "mdoc" && typeof parsed.docType === "string") {
965
+ decoded.doctype = parsed.docType;
966
+ }
967
+ const rawMatch = matchQuery(query, [decoded]);
968
+ const match = refineUnmatched(query, decoded, rawMatch);
969
+ const submission = match.satisfied ? buildSubmission(query, match) : null;
970
+ return {
971
+ parsed,
972
+ match,
973
+ submission,
974
+ valid: parsed.valid && match.satisfied
975
+ };
976
+ }
977
+ var VERSION = "0.4.0";
495
978
 
496
- // src/index.ts
497
- var VERSION = "0.2.1";
498
-
499
- export { ExpiredCredentialError, InvalidSignatureError, MalformedCredentialError, MdocParser, NonceValidationError, SdJwtParser, UnsupportedFormatError, VERSION, createAuthorizationRequest, parsePresentation };
979
+ export { ExpiredCredentialError, HAIP_DOCTYPE_NAMESPACES, HaipValidationError, InvalidSignatureError, MalformedCredentialError, MdocParser, NonceValidationError, SdJwtParser, UnsupportedFormatError, VERSION, buildHaipQuery, createAuthorizationRequest, isHaipQuery, parsePresentation, validateHaipQuery, verifyPresentation };
500
980
  //# sourceMappingURL=index.js.map
501
981
  //# sourceMappingURL=index.js.map